text:
Q: How to insert an item at the beginning of an array in PHP? I know how to insert it to the end by:
$arr[] = $item;

But how to insert it to the beginning?

A: There are two solutions:

*

*if you have array with keys that matter to you

$new = ['RLG' => array(1,2,3)];
$array = ['s' => array(2,3), 'l' => [], 'o' => [], 'e' => []];

$arrayWithNewAddedItem = array_merge($new, $array);

*if you have an array without any keys.

array_unshift(array, value1);

A: Use array_unshift() to insert the first element in an array.
Use array_shift() to remove the first element of an array.

A: Use array_unshift($array, $item);
$arr = array('item2', 'item3', 'item4');
array_unshift($arr , 'item1');
print_r($arr);

will give you
Array
(
 [0] => item1
 [1] => item2
 [2] => item3
 [3] => item4
)

A: Or you can use temporary array and then delete the real one if you want to change it while in cycle:
$array = array(0 => 'a', 1 => 'b', 2 => 'c');
$temp_array = $array[1];

unset($array[1]);
array_unshift($array , $temp_array);

the output will be:
array(0 => 'b', 1 => 'a', 2 => 'c')

and when are doing it while in cycle, you should clean $temp_array after appending item to array.

A: Since PHP7.4 you can use the spread opperator, very similar to JavaScript
$arr = [$item, ...$arr];

https://wiki.php.net/rfc/spread_operator_for_array
A few more examples:
// Add an item before
$arr = [$item, ...$arr];

// Add an item after
$arr = [...$arr, $item];

// Add a few more
$arr = [$item1, $item2, ...$arr, $item3];

// Multiple arrays and and items
$arr = [$item1, ...$arr1, $item2, ...$arr2, $item3];

*

*Note: this is only possible with int keys, not for associative arrays.

*Note2: The keys are not kept.

BREAKING Example:
$car = ['brand' => 'Audi', 'model' => 'A8'];
$engine = ['cylinder' => 6, 'displacement' => '3000cc'];

$merged = [...$car, ...$engine];

var_dump($merged);

Will result in:

[ Error ] Cannot unpack array with string keys

A: In case of an associative array or numbered array where you do not want to change the array keys:
$firstItem = array('foo' => 'bar');

$arr = $firstItem + $arr;

array_merge does not work as it always reindexes the array.

A: Insert an item in the beginning of an associative array with string/custom key
<?php

$array = ['keyOne'=>'valueOne', 'keyTwo'=>'valueTwo'];

$array = array_reverse($array);

$array['newKey'] = 'newValue';

$array = array_reverse($array);

RESULT
[
  'newKey' => 'newValue',
  'keyOne' => 'valueOne',
  'keyTwo' => 'valueTwo'
]

A: For an associative array you can just use merge.
$arr = array('item2', 'item3', 'item4');
$arr = array_merge(array('item1'), $arr)


text:
Q: DRAM3 memory fetch time I am trying to understand how much time required in fpga time slots to fetch 128 bite value from DRAM3. I have a fpga board with 100 Mhz chip that talks with DRAM3 1600 Mhz. Thanks

A: In general, DRAM access time depends on many factors:

*

*actual DRAM timings and frequency

*bus width

*whether operations access open or precharged rows and whether they are "pipelined"

*page and power policies of the DRAM controller

*internal details of the DRAM controller

If an order of magnitude estimation is okay, worst-case random access latency should be somewhere between 50 and 100 ns assuming no power saving modes are used.
ADDED: this also assumes the DRAM controller in the FPGA does not introduce its own latencies.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to get updated quantity when Add to cart function is called React or Javascript currently quantity is 1, how do i get updated quantity when addTocart function is called,
if i enter 4 in the TextField i need  quantity  to be updated to 4 and get that object in addTocart function, currently i am getting quantity is 1
const allProducts=[
    { id:1, productName:'Apple',price:100,quantity:1}
    { id:2, productName:'Cherry',price:70,quantity:1}
    { id:3, productName:'Orange',price:60,quantity:1}
    { id:4, productName:'Grapes',price:69,quantity:1}
]
const [state, dispatch] = useReducer(reducer, allProducts)

newItem is { id:4,   productName:'Grapes',  price:69,  quantity:updatedQuantity}
const addToCart = (newItem) => {
     //want updated quantity when this function called
}

{ state.map(item=>(
   <div>
     <TextField defaultValue={item.quantity} />

     <Button  onClick={()=>addTocart(item)} > Add to cart</Button>
  </div>
)
}

A: const reducer = (state, action) => {
   switch (action.type) {
      case "UPDATE" :
         return [...state.filter(i => i.id !== action.product.id), action.product]
   }
}

dispatch({type:"UPDATE", product:item})

I think this can help you.
Basically you remove the old product item from the array and add the updated one.


text:
Q: Delphi: Canvas.FillRect in List View On change of a text of List View's SubItem I need to brush and fill a whole row:
procedure TForm1.ListViewDrawItem(Sender: TCustomListView;
  Item: TListItem; Rect: TRect; State: TOwnerDrawState);
begin
  if Item.SubItems[2]='Done'
   then
  begin
    Sender.Canvas.Font.Color := clBlack;
    Sender.Canvas.Brush.Color := clGreen;
    Sender.Canvas.Brush.Style := bsSolid;
    Sender.Canvas.FillRect(Rect);
  end;
end;

But Sender.Canvas.FillRect(Rect) will fill only a Rect of the SubItem. How to fill a whole row?
The question is asked on a base of Delphi: how to draw small icons in List View on CustomDrawItem
Thanks!

A: First, if you have three columns, they are Caption, SubItems[0], and SubItems[1], remember? There is no SubItems[2]!
Anyhow, this is very easy. You only need a very, very small modification of the old code.
procedure TForm1.ListView1DrawItem(Sender: TCustomListView; Item: TListItem;
  Rect: TRect; State: TOwnerDrawState);
var
  i: Integer;
  x1, x2: integer;
  r: TRect;
  S: string;
const
  DT_ALIGN: array[TAlignment] of integer = (DT_LEFT, DT_RIGHT, DT_CENTER);
begin
  if SameText(Item.SubItems[1], 'done') then
  begin
    Sender.Canvas.Font.Color := clBlack;
    Sender.Canvas.Brush.Color := clLime;
  end
  else
    if Odd(Item.Index) then
    begin
      Sender.Canvas.Font.Color := clBlack;
      Sender.Canvas.Brush.Color := $F6F6F6;
    end
    else
    begin
      Sender.Canvas.Font.Color := clBlack;
      Sender.Canvas.Brush.Color := clWhite;
    end;
  Sender.Canvas.Brush.Style := bsSolid;
  Sender.Canvas.FillRect(Rect);
  x1 := 0;
  x2 := 0;
  r := Rect;
  Sender.Canvas.Brush.Style := bsClear;
  Sender.Canvas.Draw(3, r.Top + (r.Bottom - r.Top - bm.Height) div 2, bm);
  for i := 0 to ListView1.Columns.Count - 1 do
  begin
    inc(x2, ListView1.Columns[i].Width);
    r.Left := x1;
    r.Right := x2;
    if i = 0 then
    begin
      S := Item.Caption;
      r.Left := bm.Width + 6;
    end
    else
      S := Item.SubItems[i - 1];
    DrawText(Sender.Canvas.Handle,
      S,
      length(S),
      r,
      DT_SINGLELINE or DT_ALIGN[ListView1.Columns[i].Alignment] or
        DT_VCENTER or DT_END_ELLIPSIS);
    x1 := x2;
  end;
end;

Notice in particular that I use clLime instead of clGreen, because clBlack text on a clGreen background looks horrible! You might consider clWhite text on a clGreen background, though:

Update in response to comments:
To change the third column of the list view, it doesn't do to just do
procedure TForm1.FormClick(Sender: TObject);
begin
  ListView1.Items[3].SubItems[1] := 'Done';
end;

Indeed, Windows doesn't know that the data of one column affects the appearance of the entire row! The simplest fix is to tell Windows to repaint the entire control when you have changed the value Better: just tell Windows to redraw the current row:
procedure TForm1.FormClick(Sender: TObject);
begin
  ListView1.Items[3].SubItems[1] := 'Done';
  ListView1.Items[3].Update;
end;


text:
Q: Azure SQL slow inserts & high latency I am testing my SQL Server db setup, that is Gen 5 with 4 cores and cannot go over 45 inserts per second for a super simple "insert into test select 'a', 'b', 'c'" query. The same app on the local machine inserts around 5k rows per second. I looked at the pooling and with true goes to 5 and false goes to 45. This is still way below what I expect. Anyone has any idea? What could be wrong? I looked at the metrics in Azure and I see that they CPU is used only 3-4% percent, and memory less than <5%
Any idea?
Connection speed is Okay from what I see. I can do on Cosmos DB around 200 inserts per second with the lowest SKU.


text:
Q: Why Is This Custom Module Helper Returning the Same Value In A Loop In A Template? I have a custom module, called JLS_Composers, which is used to input a "composer." Each product can have one or more Composers associated with it (which is accomplished in the Product edit page). I now have a page which loops through all the products and displays a bit of information from each... which includes the composer(s). The problem is, the helper function in the JLS_Composer module is only returning the data for the first composer, and then repeats that for all subsequent products. I am getting the product collection via:
$products = Mage::getResourceModel('catalog/product_collection');
$products->addAttributeToSelect('*');
$products->addAttributeToFilter('visibility', array('neq' => 1));
$products->addAttributeToFilter('status', 1);
$products->addAttributeToSort('composer', 'ASC');
$products->addAttributeToSort('name', 'ASC');
$products->addAttributeToSort('entity_id', 'ASC');
$products->load();

Then, within a foreach loop of ($products as $product), the helper is:
$composers = Mage::helper('jls_composers/product')->getSelectedComposers($product);

Do Magento helpers persist data somewhere? How is it that I am calling the helper each time, with a new, distinct product, but get the same results? I have never experienced this behavior and am curious to solve the problem. I have tried various methods of getting the information through the $product object but all to no avail. I can supply additional code as necessary.
Has anyone experienced and solved this? Or have I approached the issue in the wrong direction?
The Helper method is:
public function getSelectedComposers(Mage_Catalog_Model_Product $product){
    if (!$product->hasSelectedComposers()) {
        $composers = array();
        foreach ($this->getSelectedComposersCollection($product) as $composer) {
            $composers[] = $composer;
        }
        $product->setSelectedComposers($composers);
    }
    return $product->getData('selected_composers');
}

EDIT: The getSelectedComposersCollection method is as follows:
public function getSelectedComposersCollection(Mage_Catalog_Model_Product $product){
    $collection = Mage::getResourceSingleton('jls_composers/composer_collection')
        ->addProductFilter($product);
    return $collection;
}

A: Nice first question Welcome to MagentoSE.
First are you sure there are multiple products being returned in your initial production collection?
zend_debug::dump($products->getData());
Next, you'll most likely want to setup some local protected $_product to your helper class and define a getter/setter:
/**
 * Set current Product
 *
 * @param Mage_Catalog_Model_Product $product
 * @return Mage_Catalog_Helper_Image
 */
protected function setProduct($product)
{
    $this->_product = $product;
    return $this;
}

/**
 * Get current Product
 *
 * @return Mage_Catalog_Model_Product
 */
protected function getProduct()
{
    return $this->_product;
}

As I believe Helpers in Magento are not as specific as Models.
For example:

*

*https://github.com/OpenMage/magento-mirror/blob/magento-1.9/app/code/core/Mage/Catalog/Helper/Image.php
Also be sure and review and ensure you're extending the abstract class Mage_Core_Helper_Abstract and make note there are caching calls as well, so you may also want to try and disable caching completely during testing.
On another note the helper method you've defined may make more sense as a Model and not a Helper. http://inchoo.net/magento/misuse-of-helper-classes-in-magento/
Hope this helps.


text:
Q: Theorem: Cubic Polynomials with Rational Coefficients and Roots of h' and h'' I need help explaining this theorem and example provided below.
$f (x) = (x^2 + bx + c)(x − d)$
$= x^3 + (2u − 3d)x^2 + (u^2 − 4ud + 3d^2 − v^2
)x− d(u − d − v)(u − d + v)$. (2)
For brevity, let us call polynomials with integer (respectively, rational) coefficients and roots Z-polynomials (respectively, Q-polynomials). The formula (2) describes all monic (leading coefficient 1) cubic Z-polynomials $ f$ with rational roots of $f'$ and $f''$.
To get the complete description of all cubic Q-polynomials $h$ with rational roots of $h'$ and $h''$ we need the following result of algebraic folk-lore: for a polynomial $f$ and number $α$ $\neq$ 0, define a new polynomial $f_{α}$ by $f_{a}(x)$ = $f(αx)$, then $r$ is a root of $f$ , if and only if $\frac{r}{a}$ is a root of $f_{α}$. Then the following proposition is
the key to a full description:
Proposition & Proof to the Theorem: enter image description here
(1) $f (x) = x^3 − ux^2 − v^2x + uv^2 = (x − u) · (x^2 − v^2)$
Theorem. Let h be a cubic polynomial with rational coefficients. Then h, h' and h'' have rational roots, if and only if $h = μf_{λ}$ where μ, λ are rational numbers and $f$ is a polynomial of the form (1) with u, v.
For the practical application of this result, start with a polynomial $f$ of form (1) with u, v being integers. Then choose any rational λ,μ =/= 0 and form $μf_{λ}$. This is the polynomial to be graphed.
Example: For $u = 1, v = 4$, formula (4) gives $f (x) = x^3 − x^2 − 16x + 16$ with
roots 1, 4, −4. For λ = 2, form $f_{2}$ and get $h(x) = \frac{1}{4} f_{2} = 2x^3 − x^2 − 8x + 4$ with roots $\frac{1}{2} , 2, −2$.
What happens if u = 13, v = 3 for formula (1)?


text:
Q: Access a module's class variables inside a class in Ruby I have a module with a class variable in it
module Abc
  @@variable = "huhu"

  def self.get_variable
    @@variable
  end

  class Hello
    def hola
      puts Abc.get_variable
    end
  end
end

a = Abc::Hello.new
a.hola

Is it possible to get @@variable inside Hello without using get_variable method? I mean something like Abc.variable would be nice. Just curious.

A: You cannot access @@variable directly (i.e., Abc.variable) within the scope of the Hello class in the module Abc. Why? Because, when the Ruby interpreter sees something like Abc.variable, it would think variable as class/module method of Abc.
It is important to think the Ruby way when programming in Ruby.

A: try this
Abc.class_variable_get(:variable)


text:
Q: Escaping punctuation, and 'The' prefix in song titles when collating a MPMediaQuery The code works and populates the table with sections, but it has a flaw: It doesn't escape punctuation and 'The' prefixes in song titles, just like how the native music app does.
Would really appreciate some guidance on how I should go about doing this.
- (void)viewDidLoad
{
    [super viewDidLoad];
    MPMediaQuery *songQuery = [MPMediaQuery songsQuery];
    self.songsArray = [songQuery items];
    self.sectionedSongsArray = [self partitionObjects:self.songsArray collationStringSelector:@selector(title)];
}

- (NSArray *)partitionObjects:(NSArray *)array collationStringSelector:(SEL)selector
{
    UILocalizedIndexedCollation *collation = [UILocalizedIndexedCollation currentCollation];
    NSInteger sectionCount = [[collation sectionTitles] count];
    NSMutableArray *unsortedSections = [NSMutableArray arrayWithCapacity:sectionCount];
    for(int i = 0; i < sectionCount; i++)
    {
        [unsortedSections addObject:[NSMutableArray array]];
    }
    for (id object in array)
    {
        NSInteger index = [collation sectionForObject:object collationStringSelector:selector];
        [[unsortedSections objectAtIndex:index] addObject:object];
    }
    NSMutableArray *sections = [NSMutableArray arrayWithCapacity:sectionCount];
    for (NSMutableArray *section in unsortedSections)
    {
        [sections addObject:[collation sortedArrayFromArray:section collationStringSelector:selector]];
    }
    return sections;
}

A: I completely overlooked this. The answer here is to simply use MPMediaQuerySection. The Apple docs are there for a reason!

A: Cocotutch -
Here's the implementation that I used to index a query containing all the songs in my music library:
MPMediaQuery *allSongsQuery = [MPMediaQuery songsQuery];

// Fill in the all songs array with all the songs in the user's media library
allSongsArray = [allSongsQuery items];

allSongsArraySections = [allSongsQuery itemSections];

allSongsArraySections is an NSArray of MPMediaQuerySection, each of which has a title and a range. The NSArray object for section zero (with title @"A" in my case) has range.location of 0 and range.length of 158.
I return the range.length value for each section when numberOfRowsInSection is called for my UITableView. I use the range.location value in cellForRowAtIndexPath as the starting row of the section, and then add indexPath.row to it in order to arrive at the cell I need to return from my allSongsArray.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
....
    // Return the number of rows in the section.
    MPMediaQuerySection *allSongsArraySection = globalMusicPlayerPtr.allSongsArraySections[section];
    return allSongsArraySection.range.length;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
...
    MPMediaQuerySection *allSongsArraySection = globalMusicPlayerPtr.allSongsArraySections[indexPath.section];
    rowItem = [globalMusicPlayerPtr.allSongsArray objectAtIndex:allSongsArraySection.range.location + indexPath.row];
....
}

Before using this I had tried to match the native music player's implementation by writing my own, and it didn't behave quite identically. Not only that, but the native indexing is MUCH faster!


text:
Q: Do or did javascript: URLs ever work in CSS, and if so, can it be prevented? So I saw a code snippet today and was horrified:

Hello

*

*Is it possible to execute javascript from within CSS this way? (It didn't work when I tested it on a clean Firefox profile, but maybe I made some stupid mistake here, but the concept works.)

*If so, what means are there to prevent this, either with an HTTP header or by declarations made by the HTML itself (e.g. when sourcing CSS files from another server)?

*If not, was this never possible or has this changed?

A: The current CSS spec says only "valid image formats" can be used in a background-image:

In some cases, an image is invalid, such as a '<url>' pointing to a resource that is not a valid image format. An invalid image is rendered as a solid-color 'transparent' image with no intrinsic dimensions. [...] If the UA cannot download, parse, or otherwise successfully display the contents at the URL as an image, it must be treated as an invalid image.

The spec is silent on whether or not a javascript: url that returns valid image data would work -- it'd be an interesting exercise to try to construct one! -- but I'd be pretty darn surprised if it did.

User agents may vary in how they handle invalid URIs or URIs that designate unavailable or inapplicable resources.

(As @Kaiido points out below, scripts within SVG will not run in this situation either, so I'd expect the whole javascript: protocol to be treated as an "inapplicable resource".)

A: IE supports CSS expressions:
width:expression(document.body.clientWidth > 955 ? "955px": "100%" );

but they are not standard and are not portable across browsers. Avoid them if possible. They are deprecated since IE8.

A: Yes, in the past this attack vector worked (older browsers like IE6). I believe most modern browsers should protect against this kind of attack. That said, there can always be more complicated attacks that may get around current protections. If you are including any user-generated content anywhere, it is best to sanitize it before injecting it into your site.

A: It's possible to execute JavaScript where a URI is expected by prefixing it with javascript:. This is, in fact, how bookmarklets work. I don't think however that this would work with css url(), but it does with href or window.location.
say foo

I think whoever wrote that bit of code was confused about it.


text:
Q: How to get the returned stdout of a program called with QProcess? I am writing a program in Qt and currently using popen to run a linux command and read the output into a string:
    QString Test::popenCmd(const QString command) {
    FILE *filePointer;
    int status;
    int maxLength = 1024;
    char resultStringBuffer[maxLength];
    QString resultString = "";

    filePointer = popen(command.toStdString().c_str(), "r");
    if (filePointer == NULL) {
        return 0;
    }

    while (fgets(resultStringBuffer, maxLength, filePointer) != NULL) {
        resultString += resultStringBuffer;
    }
    status = pclose(filePointer);
    if (status == 0) {
        return resultString;
    } else {
        return 0;
    }
}

So I'd like to throw the above code away as I'd prefer to use higher level  facilities provided by Qt if possible. Does anyone have an example of how to do this with QProcess or atleast a rough idea of how it could be done?
For what it's worth, this will be run on Linux.
Thank you

A: Do like this:
void Process::runCommand(const QString &p_Command) {
    QProcess *console = new QProcess();
    console->connect(console, SIGNAL(readyRead()), this, SLOT(out()));
    console->connect(console, SIGNAL(finished(int)), this, SLOT(processFinished(int)));
    console->start(p_Command);
}

void Process::out() {
    QProcess *console = qobject_cast<QProcess*>(QObject::sender());
    QByteArray processOutput = console->readAll();
}

void Process::processFinished(int p_Code) {
    QProcess *console = qobject_cast<QProcess*>(QObject::sender());
    QByteArray processOutput = console->readAll() + QString("Finished with code %1").arg(p_Code).toLatin1();
}

Signal QProcess::finished() can be used to get the exit code of the process.


text:
Q: violating the given average time complexity in Big-O notation I am trying to Implement a solutions to find k-th largest element in a given integer list with duplicates with O(N*log(N)) average time complexity in Big-O notation, where N is the number of elements in the list.
As per my understanding Merge-sort has an average time complexity of O(N*log(N)) however in my below code I am actually using an extra for loop along with mergesort algorithm to delete duplicates which is definitely violating my rule of find k-th largest element with O(N*log(N)). How do I go about it by achieving my task  O(N*log(N)) average time complexity in Big-O notation?
public class FindLargest {
    public static void nthLargeNumber(int[] arr, String nthElement) {
        mergeSort_srt(arr, 0, arr.length - 1);
        // remove duplicate elements logic
        int b = 0;
        for (int i = 1; i < arr.length; i++) {
            if (arr[b] != arr[i]) {
                b++;
                arr[b] = arr[i];
            }
        }

        int bbb = Integer.parseInt(nthElement) - 1;
        // printing second highest number among given list
        System.out.println("Second highest number is::" + arr[b - bbb]);
    }

    public static void mergeSort_srt(int array[], int lo, int n) {
        int low = lo;
        int high = n;
        if (low >= high) {
            return;
        }

        int middle = (low + high) / 2;
        mergeSort_srt(array, low, middle);
        mergeSort_srt(array, middle + 1, high);
        int end_low = middle;
        int start_high = middle + 1;
        while ((lo <= end_low) && (start_high <= high)) {
            if (array[low] < array[start_high]) {
                low++;
            } else {
                int Temp = array[start_high];
                for (int k = start_high - 1; k >= low; k--) {
                    array[k + 1] = array[k];
                }
                array[low] = Temp;
                low++;
                end_low++;
                start_high++;
            }
        }
    }

    public static void main(String... str) {
        String nthElement = "2";
        int[] intArray = { 1, 9, 5, 7, 2, 5 };

        FindLargest.nthLargeNumber(intArray, nthElement);
    }
}

A: Your only problem here is that you don't understand how to do the time analysis.  If you have one routine which takes O(n) and one which takes O(n*log(n)), running both takes a total of O(n*log(n)).  Thus your code runs in O(n*log(n)) like you want.
To do things formally, we would note that the definition of O() is as follows:
 f(x) ∈ O(g(x)) if and only if there exists values c > 0 and y such that f(x) < cg(x) whenever x > y.
Your merge sort is in O(n*log(n)) which tells us that its running time is bounded above by c1*n*log(n) when n > y1 for some c1,y1.  Your duplication elimination is in O(n) which tells us that its running time is bounded above by c2*n when n > y2 for some c2 and y2.  Using this, we can know that the total running time of the two is bounded above by c1*n*log(n)+c2*n when n > max(y1,y2).  We know that c1*n*log(n)+c2*n < c1*n*log(n)+c2*n*log(n) because log(n) > 1, and this, of course simplifies to (c1+c2)*n*log(n).  Thus, we can know that the running time of the two together is bounded above by (c1+c2)*n*log(n) when n > max(y1,y2) and thus, using c1+c2 as our c and max(y1,y2) as our y, we know that the running time of the two together is in O(n*log(n)).
Informally, you can just know that faster growing functions always dominate, so if one piece of code is O(n) and the second is O(n^2), the combination is O(n^2).  If one is O(log(n)) and the second is O(n), the combination is O(n).  If one is O(n^20) and the second is O(n^19.99), the combination is O(n^20).  If one is O(n^2000) and the second is O(2^n), the combination is O(2^n).

A: Problem here is your merge routine where you have used another loop which i donot understand why, Hence i would say your algorithm of merge O(n^2) which changes your merge sort time to O(n^2).
Here is a pseudo code for typical O(N) merge routine :-
void merge(int low,int high,int arr[]) {

  int buff[high-low+1];
  int i = low;
  int mid = (low+high)/2;
  int j = mid +1;
  int k = 0;
  while(i<=mid && j<=high) {

      if(arr[i]<arr[j]) {
           buff[k++] = arr[i];
           i++;
      }
      else {
           buff[k++] = arr[j];
           j++;
      }
  }

  while(i<=mid) {
        buff[k++] = arr[i];
           i++;
  }

    while(j<=high) {
        buff[k++] = arr[j];
           j++;
  }

  for(int x=0;x<k;x++) {

       arr[low+x] = buff[x];
   }

}


text:
Q: Maximum length of the textual representation of an IPv6 address? I want to store the data returned by $_SERVER["REMOTE_ADDR"] in PHP into a DB field, pretty simple task, really. The problem is that I can't find any proper information about the maximum length of the textual representation of an IPv6 address, which is what a webserver provides through $_SERVER["REMOTE_ADDR"].
I'm not interested in converting the textual representation into the 128 bits the address is usually encoded in, I just want to know how many characters maximum are needed to store any IPv6 address returned by $_SERVER["REMOTE_ADDR"].

A: 45 characters.
You might expect an address to be
0000:0000:0000:0000:0000:0000:0000:0000

8 * 4 + 7 = 39

8 groups of 4 digits with 7 : between them.
But if you have an IPv4-mapped IPv6 address, the last two groups can be written in base 10 separated by ., eg. [::ffff:192.168.100.228]. Written out fully:
0000:0000:0000:0000:0000:ffff:192.168.100.228

(6 * 4 + 5) + 1 + (4 * 3 + 3) = 29 + 1 + 15 = 45

Note, this is an input/display convention - it's still a 128 bit address and for storage it would probably be best to standardise on the raw colon separated format, i.e. [0000:0000:0000:0000:0000:ffff:c0a8:64e4] for the address above.

A: I think @Deepak answer in this link is more close to correct answer. Max length for client ip address. So correct size is 45 not 39. Sometimes we try to scrounge in fields size but it seems to better if we prepare enough storage size.

A: Watch out for certain headers such as HTTP_X_FORWARDED_FOR that appear to contain a single IP address.  They may actually contain multiple addresses (a chain of proxies I assume).
They will appear to be comma delimited - and can be a lot longer than 45 characters total - so check before storing in DB.

A: As indicated a standard ipv6 address is at most 45 chars, but an ipv6 address can also include an ending % followed by a "scope" or "zone" string, which has no fixed length but is generally a small positive integer or a network interface name, so in reality it can be bigger than 45 characters.  Network interface names are typically "eth0", "eth1", "wlan0", a small number of chars.  The max interface name length in linux is 15 chars, so choosing 61 bytes will cover all interface names on linux.

A: Answered my own question:

IPv6 addresses are normally written as eight groups of four hexadecimal digits, where each group is separated by a colon (:).

So that's 39 characters max.

A: On Linux, see constant INET6_ADDRSTRLEN (include <arpa/inet.h>, see man inet_ntop). On my system (header "in.h"):
#define INET6_ADDRSTRLEN 46

The last character is for terminating NULL, as I belive, so the max length is 45, as other answers.


text:
Q: How to clear the recyclerview / adapter in searchview for next search android I am using retrofit to search the images and displaying. I am using SearchView to search and recyclerview and adapter to display the item.
It's working for the very first time. Second time when I search, it's displaying the same item. It's not clearing the view to display.
Here is my code:
    public class MainActivity extends AppCompatActivity {
        private static final String TAG = MainActivity.class.getName();
        ImagesViewModel newsViewModel;
        List<Hits> newsArticles;
        List<Hits> articleArrayList;
        ImagesAdapter newsAdapter;
        RecyclerView rvHeadline;
        SearchView searchView;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            rvHeadline = (RecyclerView) findViewById(R.id.rvNews);
            searchView=(SearchView) findViewById(R.id.searchView);
            searchView.setQueryHint("Search Images");
            searchView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    searchView.setIconified(false);
                }
            });
            searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

                @Override
                public boolean onQueryTextSubmit(String query) {
                    callPixabayImages(query);
                    Toast.makeText(getBaseContext(), query, Toast.LENGTH_LONG).show();
                    return false;
                }

                @Override
                public boolean onQueryTextChange(String newText) {
                    callPixabayImages(newText);
                    Toast.makeText(getBaseContext(), newText, Toast.LENGTH_LONG).show();
                    return false;
                }
            });
            articleArrayList = new ArrayList<>();
 }

 private void callPixabayImages(String query){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ImageApiInterface.PIXABAY_URL)
                .addConverterFactory(GsonConverterFactory.create()) //Here we are using the GsonConverterFactory to directly convert json data to object
                .build();

        ImageApiInterface api = retrofit.create(ImageApiInterface.class);

        Call<MyImages> call = api.getMovieDetails(query);
        call.enqueue(new Callback<MyImages>() {
            @Override
            public void onResponse(Call<MyImages> call, Response<MyImages> response) {
                Log.e("response","response"+response.code());
                if(response.isSuccessful()){
                    Log.e("response","response"+response.code());
                    if((response.body() != null ? response.body().getHits() : null) !=null){
                        List<Hits> imagesList = response.body().getHits();
                        articleArrayList.addAll(imagesList);
                      newsAdapter.notifyDataSetChanged();
                    }
                }

            }

            @Override
            public void onFailure(Call<MyImages> call, Throwable t) {
                System.out.println("Error: "+ t.getMessage());
                Log.e("response","response"+t);
            }
        });

    }
 private void setupRecyclerView() {
        if (newsAdapter == null) {
            newsAdapter = new ImagesAdapter(MainActivity.this, articleArrayList);

            rvHeadline.setLayoutManager(new LinearLayoutManager(this));
            rvHeadline.setAdapter(newsAdapter);
            rvHeadline.setItemAnimator(new DefaultItemAnimator());
            rvHeadline.setNestedScrollingEnabled(true);
        } else {
            newsAdapter.notifyDataSetChanged();
        }
    }

Here where I need to reset to search the new item inorder to avoid to display the previous item. List is not clearing to display the new items.
Here is Adapter class:
public class ImagesAdapter extends RecyclerView.Adapter<ImagesAdapter.NewsViewHolder> {
    private Context context;
    private List<Hits> articles;

    public ImagesAdapter(Context context, List<Hits> articles) {
        this.context = context;
        this.articles = articles;
    }

    @NonNull
    @Override
    public ImagesAdapter.NewsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.images_item, parent, false);
        return new NewsViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ImagesAdapter.NewsViewHolder holder, final int position) {
        String image = articles.get(position).getLargeImageURL();
        Log.e("imagestest",image);
        if (image != null) {
            Glide.with(context) //passing context
                    .load(image) //passing your url to load image.
                    .dontAnimate()
                    .placeholder(context.getDrawable(R.drawable.image_not_available)) //this would be your default image (like default profile or logo etc). it would be loaded at initial time and it will replace with your loaded image once glide successfully load image using url.
                    //.centerCrop()//this method help to fit image into center of your ImageView
                    .into(holder.ivNews); //pass imageView reference to appear the image.*/
        }
    }

    @Override
    public int getItemCount() {
        return articles.size();
    }

    class NewsViewHolder extends RecyclerView.ViewHolder {

        ImageView ivNews;
        private NewsViewHolder(@NonNull View itemView) {
            super(itemView);
            ivNews = itemView.findViewById(R.id.ivNews);

        }
    }
}

I am clueless where exactly I need to clear the view to fetch the newly searched item.
Trial 1: I tried to clear the list object articleArrayList but it throws crash that adapter size is null.

A: Clean the

articleArrayList

before loading the searched items again.... by executing this line articleArrayList.clear();
public void onResponse(Call<MyImages> call, Response<MyImages> response) {
                    Log.e("response","response"+response.code());
                    if(response.isSuccessful()){
                        Log.e("response","response"+response.code());
                        if((response.body() != null ? response.body().getHits() : null) !=null){
                            List<Hits> imagesList = response.body().getHits();

                            articleArrayList.clear();

                          articleArrayList.addAll(imagesList);
                            newsAdapter.notifyDataSetChanged();
                        }
                    }

A: You're adding generated imagesList to the articleArrayList, you should be replacing the values.
articleArrayList = imagesList;


text:
Q: facebook's object debugger says 'we're sorry, but something went wrong' I set ogp tags on my website.
Even though it should be OK, facebook's object debugger says 'something went wrong'.
Here's my website.
https://makeyourownemblem.herokuapp.com/showemblem/2
BTW I use following gems.
meta-tags, sitemap_generator
Could you give me some advice?


text:
Q: XMLA Parsing to gain multiple attributes I have the following XML which I need to parse values from.
<ads>
    <ad id="987654321">
        <price>
            <currency-iso-code>
                <value localized-label="£">GBP</value>
            </currency-iso-code>
            <amount>345</amount>
        </price>
        <price_frequency>
            <value>WEEKLY</value>
        </price_frequency>
        <title>This is the Title</title>
        <description>
            Description
        </description>
        <ad_status>
            <value>ACTIVE</value>
        </ad_status>
        <email>EXIST</email>
        <user-id>123456</user-id>
        <phone>123456</phone>
        <modification-date-time>2013-09-02T11:40:41.000+01:00</modification-date-time>
        <start-date-time>2013-09-02T11:40:39.000+01:00</start-date-time>
        <features_active>
            <category id="3">
                <id-name>category-name</id-name>
                <localized-name>Category name</localized-name>
            </category>
            <locations>
                <location id="10000392">
                    <id-name>uk</id-name>
                    <localized-name>United Kingdom</localized-name>
                </location>
            </locations>
            <neighborhood>Neighbourhood Name</neighborhood>
            <attributes>
                <attribute localized-label="Seller type" type="ENUM" name="seller_type">
                    <value localized-label="Agency">trade</value>
                </attribute>
                <attribute localized-label="Property type" type="ENUM" name="property_type">
                    <value localized-label="Flat">flat</value>
                </attribute>
                <attribute localized-label="Number of beds" type="LONG" name="property_number_beds">
                    <value>1</value>
                </attribute>
                <attribute localized-label="Date available" type="DATETIME" name="available_date">
                    <value localized-label="15/05/2013">2013-05-15T00:00:00.000+01:00</value>
                </attribute>
            </attributes>
            <link rel="self" href="https://api2.domain.com/api/ads/987654321">
            <link rel="self-user" href="https://api2.domain.com/api/users/123456/ads/987654321">
            <public_link href="http://domain.com/public_facing_link">
                <pictures>
                    <picture>
                        <link rel="extrabig" href="http://domain.com/images/80.JPG">
                        <link rel="preview" href="http://domain.com/images/81.JPG">
                        <link rel="big" href="http://domain.com/images/79.JPG">
                        <link rel="thumb" href="http://domain.com/images/78.JPG">
                        <link rel="moreadsthumb" href="http://domain.com/images/77.JPG">
                    </picture>
                    <picture>
                        <link rel="extrabig" href="http://domain.com/images/80.JPG">
                        <link rel="preview" href="http://domain.com/images/81.JPG">
                        <link rel="big" href="http://domain.com/images/79.JPG">
                        <link rel="thumb" href="http://domain.com/images/78.JPG">
                        <link rel="moreadsthumb" href="http://domain.com/images/77.JPG">
                    </picture>
                </pictures>
            </public_link>
        </features_active>
    </ad>
</ads>

I need to pull the following data from this xml
Title, Description - easy enoguht to pull. Done them
I also need public_link href and the pictures href link for those with rel="thumb"
Through checking numerous posts on here and php documentation I have come up with something like this.
$ads = simplexml_load_string($xml);

foreach ($ads as $ad) {

    $item['price']      = $ad->price->amount;
    $item['title']      = $ad->title;

    $link = simplexml_load_string($ad->features_active->public_link);

    foreach($link->attributes() as $attr => $value) {
        if($attr == 'href'){
            $item['link'] = $value;

        }
    }

    $pics = simplexml_load_string($ad->features_active->public_link->pictures);

    foreach($pics->picture[0]->attributes() as $attr => $value) {
        if($attr == 'thumb'){
            $item['picture'] = $value;

        }
    }

    echo "

" . $item['price'];
    echo "
" . $item['title'];
    echo "
" . $item['link'];
    echo "
" . $item['picture'];

}

For some reason it's not wanting to pull the attributes. Can anyone point me in the right direction for this?

A: Try PHP DOMDocument for XML Parser. Refer the below URL for getting the tag and attribute value.
http://www.php.net/manual/en/domdocument.getelementsbytagname.php
$objDOM = new DOMDocument('1.0');
$objDOM->preserveWhiteSpace = false;
$objDOM->loadXML($xml);


text:
Q: How to pass variable to a function call in angular forEach I am using a  leaflet Directive to show maps on openStreet map.To list all markers my code looks like this :
$scope.goTo = function() {
    restAPI.getSomething().success(function(data) {
        var anArray = data.lists;
        console.log(anArray);
        var anotherList = {};
        angular.forEach(anArray, function(value, key) {
            if (value.geolocation) {
                $scope.project = value;
                anotherList[anArray[key].ao] = {
                    lat: value.lat,
                    lng: value.lng,
                    focus: false,
                    draggable: false,
                    icon: icon,
                    message: '<button type="button" ng-click="openProject(project)">' + value.ao + '</button> {{project.ao}}',
                    clickable: true
                }
            }
        });
        $scope.map.anotherList = anotherList;
    });
}

Here in that message template i am adding a  button with a function call, As i understood to pass a variable in template, Scope is the solution, but here, on all markers value.ao name is different but project.ao is same ...(why ????)
when i click on each marker its opening last project in array(anArray).
How can i bind scope value in each iteration ?,So i can open correct project on each marker

A: my working solution looks like:
$scope.goTo = function() {
    restAPI.getSomething().success(function(data) {
        var anArray = data.lists;
        console.log(anArray);
        var anotherList = {};
        $scope.project = {};
        angular.forEach(anArray, function(value, key) {
            if (value.geolocation) {
                $scope.project[key] = value;
                anotherList[anArray[key].ao] = {
                    lat: value.lat,
                    lng: value.lng,
                    focus: false,
                    draggable: false,
                    icon: icon,
                    message: '<button type="button" ng-click="openProject('+key+')">' + value.ao + '</button> {{project.ao}}',
                    clickable: true
                }
            }
        });
        $scope.map.anotherList = anotherList;
    });
}

$scope.openProject = function(key){
   var project = $scope.project[key];
   // this is how i got correct project
}

Thanks to Edwin for pointing out to pass key value.


text:
Q: Meteor collection observe user activity log Hi I'm trying to observe changes on a collection, and save a changes log, I set up the observe right after creating the collection, the problem is, I can't figure out how to know which user did the changes, I tried putting the observer on the publish method, but it generates multiple observers and creates many entries on the log when only one thing was done, I saved the handle to the observer after that to prevent multiple observers, but then doesn't matter what user I log in, the log is saved in the name of the first user that got to subscribe to the publish, and I don't want to create an observer for each user and remove the observer handle dynamically, I'm pretty sure that will be really intense on the server, there must be a better way. Maybe setting up the observer in the client? but I don't want the client to have access to the log collection.
Products = new Mongo.Collection("products");
Log = new Mongo.Collection("log");

var initializing = true;
Products.find().observe({
    added: function(newDocument) {
        if (initializing) return;
        //how to get user here?
        Log.insert({
            idUser: ???,
            date: new Date(),
            document: newDocument
        });
    }
});
initializing = false;

That's my first try, here's how I try it on the publish:
var productsObserveHandle;

Meteor.publish('products', function() {
    var initializing = true;
    if (!productsObserveHandle) {
        productsObserveHandle = Products.find().observe( {
            added: function (document) {
                if (initializing) return;
                var userProfile = Meteor.users.findOne({_id:this.userId}).profile;
                Log.insert( {
                    idUser: this.userId,
                    userProfile: userProfile,
                    date: new Date(),
                    eventType: "added",
                    document: document
                });
            }.bind(this)
        });
    }
    initializing = false;
    ...
});

This one almost got it, but it always saves the log as the same user, no matter how many different users I try, since the observer handle is already created.
UPDATE: Ok, I think I'm getting somewhere, I set up the observe on the client after the collection subscription, and then all the observe methods added, changed, removed call a meteor method, that saves the log and gets the user by Meteor.userId() and it works, but now the deal is, that when you logout, and login, minimongo database gets updated, but the subscription is the same (I do all subscriptions on Meteor.startup, on client side), so I can't stop the observer and restart it after the update, is there a way to know when minimongo is being updated because of an account change? I could try to remove the observer after user logout and wait a timeout after login to setup the observer again, but I find this risky, since it may take more time to update minimongo than the timeout I setup and the last inserts may leak into the changes log.

A: This doesn't directly answer your question, but provides an alternate solution instead.  I have implemented this pattern often in my meteor apps and I always use the Collection Hooks package.
More specifically you could use .after.insert(userId, doc) and .after.update(userId, doc, fieldNames, modifier, options) methods.  Both of which correctly handle the user id.
If you don't want to use a package for this, then you ought to be able to see how they solved your issue since it would be required to make the package work.


text:
Q: How to search by city in Google Maps? I'm developing a Google Maps web app and I'm using Google Maps autocomplete feature to pick places and save the address in the database. Right now I'm getting the full formatted address by using this https://maps.googleapis.com/maps/api/geocode/json?latlng=42.072845,19.516300
As you can see, the city name there is "Shkodër" but can also be searched as "Shkoder".
So in the database I may be saving either "Rruga Besnik Sykja, Shkodër, Albania" or "Rruga Besnik Sykja, Shkoder, Albania".
1)

2)
I am also using the Google Maps Autocomplete form to search for locations and I want to be able to select city from the autocomplete field and then display all locations I have saved in the database containing that city name.
My problem lies here: What if in the database I have received and saved the city name as "Shkodër" but in the search form users pick "Shkoder"? They wouldn't match and the user may not get the correct result from my database.
Is there any solid way to search all markers from a city even when the city name may change, using some general city ID or something?
I haven't been able to find anything useful so far...

A: You can use Place ID: https://developers.google.com/places/place-id

A place ID is a textual identifier that uniquely identifies a place.
  It looks like this:
ChIJrTLr-GyuEmsRBfy61i59si0
Place IDs are available for most locations, including businesses,
  landmarks, parks, and intersections. These IDs are stable, meaning
  that once you've identified the place ID for a place, you can reuse
  that value when you next look up that place.
You can use the same place ID across the Places API and a number of
  Google Maps APIs. For example, you can use the same place ID to
  reference a place in the Google Places API, the Google Maps JavaScript
  API, the Google Maps Geocoding API, the Google Maps Embed API and the
  Google Maps Roads API

A: You can use componentRestrictions of google map api v3 for autocomplete
Here is the reference link
https://developers.google.com/maps/documentation/javascript/places-autocomplete


text:
Q: General term of $x_{n+1} = 1 - a\left(1-\frac{b}{1-(1-b)^{n+1}(1-\frac{1}{c})}\right)(1-x_n)$ I would like to know whether it is possible to give the general term of a sequence $(x_n)_{n\geq 1}$ defined inductively by
$$x_{n+1} = 1 - a\left(1-\frac{b}{1-(1-b)^{n+1}(1-\frac{1}{c})}\right)(1-x_n),$$
with $a,b,c\in(0,1)$.

A: Rearrange $x_{n+1}$ expression:
$\dfrac{x_{n+1}-1}{x_n-1} = a\left(\dfrac{1-b-c'(1-b)^{n+1}}{1-c'(1-b)^{n+1}}\right)=a(1-b)\left(\dfrac{1-c'(1-b)^{n}}{1-c'(1-b)^{n+1}}\right)\tag1$
where $c'=1-\frac{1}{c}$
Let $u_n={1-c'(1-b)^{n}}\tag2$
We get
$\dfrac{x_{n+1}-1}{x_n-1} =a(1-b)\dfrac{u_n}{u_{n+1}}\tag3$
Viz.
$\dfrac{(x_{n+1}-1)}{x_n-1} \dfrac{u_{n+1}}{u_n} =a(1-b)$
$\dfrac{(x_{n}-1)}{x_{n-1}-1} \dfrac{u_{n}}{u_{n-1}} =a(1-b)$
.
.
.
$\dfrac{(x_{2}-1)}{x_{1}-1} \dfrac{u_{2}}{u_{1}} =a(1-b)$
Multiplying both sides from 1 to n we have:
$\dfrac{(x_{n+1}-1)}{x_{1}-1} \dfrac{u_{n+1}}{u_{1}} =a^n(1-b)^n\tag4$
Express $x_{n+1}$ which results the explicit formula:
$x_{n+1}=1+(x_1-1)a^n(1-b)^n\frac{1-c'(1-b)}{1-c'(1-b)^{n+1}}\tag5$


text:
Q: Coypu/SpecFlow acceptance tests hang when run via Jenkins job I'm running acceptance tests on a project via SpecFlow, NUnit and Coypu (for browser automation, using the WatiN driver).  The running of the tests are invoked via a powershell/psake script.
If I run these tests on my local box, they run fine.  However, we have a build server on which a Jenkins job will automatically run these tests, and when run via this Jenkins job they don't execute -- they just hang.
Looking in task manager I can see there's two instances of iexplore.exe that are created when the Jenkins job runs.  However after a certain point they just hang - no changes in memory usage or CPU.
nunit-agent-x86.exe and nunit-console-x86.exe are also running but mostly hung, just nunit-agent-x86.exe going up very slowly in memory.
If I kill one of the iexplore.exe processes things continue, but the SpecFlow specs all subsequently fail.
At the point of killing iexplore.exe, the following exception is in the log:
Unhandled Exception: System.Runtime.InteropServices.COMException: The remote procedure call failed. (Exception from HRESULT: 0x800706BE)

If I invoke the psake script manually when logged in to the server, the specs run OK.
This issue began to occur when I tried to use basic DI for the BrowserSession as in the gist here: https://gist.github.com/2301407
Before that I was sharing the BrowserSession via a static property of an NUnit [SetupFixture] class.  Things were working mostly OK that way, except a small issue with a test involving a modal dialog not working correctly, but I wasn't sure I was doing it right so wanted to do the technique in the gist
I'm a bit lost as to what's causing the hang.  Any ideas what it is or tips to track it down?
UPDATE: After switching to Firefox as the browser, and Selenium as the driver, the problem has gone away...

A: I got a couple of responses on the Coypu list.  I've yet to test them out as everything is fine with Firefox at the moment, but in case they are of assistance to anyone else...

On Thursday, 2 August 2012 16:38:30 UTC+1, Adiel wrote:
[...]i believe that watin needs nunit to run in STA (single-threaded) which could possibly be related to your problem.
In other words, perhaps you made your tests thread safe with the static singleton browser session, but now via specflow's IOC you are
  getting multiple instances due to the way nunit is running.

On Thursday, 2 August 2012 16:41:11 UTC+1, Matt Ellis wrote:
This sounds like it's Internet Explorer's protected mode getting in the way. IE runs different zones, such as Internet and Intranet
  (and about:blank) in different processes, and IIRC WatiN doesn't
  handle that very well. If you can disable protected mode on your
  server, you should be fine.


text:
Q: Upgrade Ubuntu 19 to 20 without installing bootloader While running Ubuntu 19.10 64 bit. Was offered an upgrade to Ubuntu 20.04. Offer accepted. Shortly after the upgrade started it stopped with the message

EFI System Partition (ESP) not usable
Your EFI System Partition (ESP) is not mounted at /boot/efi. Please
  ensure that it is properly configured and try again.

I don't care if the EFI or ESP is not usable. I don't want a bootloader installed. This is a multi boot system with 5 or 6 other Linux installations and I am using rEFind to boot the computer.
Don't want. Don't need. We do this the way I want it done or we format the partition and install something else.
How can I upgrade without installing a bootloader?

A: If you expicitly want to avoid the standard process the updater is made for, just do a sudo sed -i 's/eoan/focal/g' /etc/apt/sources.list, followed by sudo apt update && sudo apt full-upgrade. Be prepared for questions from apt during the process and decisions you have to make yourself, instead of the Ubuntu installer doing that for you.
You also have to make sure that any ppas you have have to be manually lifted to Focal, or kept at Eoan, or deleted, after the upgrade went through.
If you are Power User enough to use rEFInd with different distros, it shouldn't be too difficult. Everyone else, you are advised to stick to the Ubuntu installer.


text:
Q: AOSP project attach process I have import aosp project to android studio. I can watch code with Android Studio.Now I would like to attach an android process to debug, but when I click the button "attach debug to android process",there is no process showing. Even I set the "show all process" checkbox, there is no process anymore.
Any help will be appreciated
I would like to debug java code as ViewRootImpl, I am using mac

A: Most probably, the emulator (or device) to which processes you try to attach is built without debugging support. Try to use eng build target, e.g., run the following commands when you build your AOSP:
source build/envsetup.sh
lunch aosp_arm-eng
make -j8

After building and running the emulator in this way you should be able to see all the processes running in the emulator.


text:
Q: Need jquery or javascript to restrict per line length in textarea I have following html textarea:
<textarea name="splitRepComments"   cols="20" rows="3" ></textarea>

on which I have applied maxlength restriction using jQuery. that Function is as below:
var max = 100;
$('#splitRepComments').bind("keypress", function(e) {

    if (e.which < 0x20) {
        // e.which < 0x20, then it's not a printable character
        // e.which === 0 - Not a character
        return; // Do nothing
    }
    if (this.value.length == max) {
        e.preventDefault();
    } else if (this.value.length > max) {
        // Maximum exceeded
        this.value = this.value.substring(0, max);
    }
});

$('#splitRepComments').bind("paste", function(e) {

    setTimeout(function() {

        var e = jQuery.Event("keypress");
        e.which = 50; // # Some key code value
        $('#splitRepComments').trigger(e);
    }, 100);

});

My hurdle is I have requirement in which we want user to enter only 10 characters in each row (line). And after that input should be taken next line.
This function also should obey maxlength restriction of textarea.
In addition I have tried below solution from SO but is not taking input to next line.
https://stackoverflow.com/a/19876218/1487469
I have jsfiddle ready for your reference.

A: try this:

    var max = 100;
    var characterPerLine = 10;

    $("textarea[name='splitRepComments']").bind("keypress", function(e) {

        if (e.which < 0x20) {
            // e.which < 0x20, then it's not a printable character
            // e.which === 0 - Not a character
            return; // Do nothing
        }
        //calculate length excluding newline character
        var length =  this.value.length - ((this.value.match(/\n/g)||[]).length);
        if (length == max) {
            e.preventDefault();
        } else if (length > max) {
            // Maximum exceeded
            this.value = this.value.substring(0, max);
        }
        if (length % characterPerLine == 0 && length!=0 && length < max)                           {
            $(this).val($(this).val()+'\n');
        }

    });

A: Here's a solution in plain JavaScript (you can transform it to JQuery as you please), I tried to incorporate comments for each statement :
var manageTextAreaSize = function manageTextAreaSize(fieldId, cols, rows){
    // Get textarea text value
    var value = document.getElementById(fieldId).value;
    // Save current cursor position (for mid text typing)
    var currentPosition = document.getElementById(fieldId).selectionStart;
    // Arraye will be used to save separate text lines
    var lines = [];
    // Remove newline characters (by splitting the text using newline character as separator then joining by blank)
    // then cut off extra characters (for limited number of rows only)
    value = value.split("\n").join("");
    if(rows){
      value = value.substr(0, cols * rows);
    }
    // If text length is superior to max number of characters (more than one line)
    if(value.length > cols){
      // Split text by lines of max character length
      for(var i = 0; i < value.length; i += cols){
        lines.push(value.substr(i, cols));
      }
      // Reassemble text into the text are by joining separate lines
      document.getElementById(fieldId).value = lines.join("\n");
      // Reposition cursor back to previously saved position (before resizing text)
      document.getElementById(fieldId).selectionStart = document.getElementById(fieldId).selectionEnd = currentPosition;
    }
    // If text length is inferior to max number of characters (less than on line)
    else if(value.length < cols){
      // Do nothing !
      return;
    }
    // If text length is equal to max number of characters (one line only)
    else{
      // Go to next line
      document.getElementById(fieldId).value += "\n";
    }
  };

Usage : directly to HTML on input event (in the exemple below : 35 characters per line for maximum of 6 lines)
<textarea id="myTextArea" cols="70" rows="20" style="resize: none" oninput="manageTextAreaSize(this.id, 35, 6);"></textarea>

NB : I didn't test this without resize so be careful when using this solution with resize !


text:
Q: Library resources not accessible from cordova Android application I have added external android project as a library in cordova android project from eclipse still Resources of library project is not accessible.
Library reference is also got added in project.properties (android.library.reference.2 = ...)
Getting the following error in the log:

01-15 12:20:52.261: E/AndroidRuntime(1132): java.lang.NoClassDefFoundError: .R$layout

Let me know the exact process to add external android library in Cordova android project.

A: Got the solution.
If you want to access any resources from plugin source files then instead of using R.id.xxx or R.layout.xxx use FakeR.java file which you will get on the net.
FakeR will get resources from the current project R.java instead of plugin's R.java


text:
Q: Detect concrete type of generic class at compile type Followup on this question: Conditional behaviour based on concrete type for generic class
I know you can detect the type of a generic variable using RTTI. However I would like to go one step further.  Is there a way to detect the type at compile time.
I have the following code:
function TBPlusTree<K, V>.TLeaf.AddKey(const Key: K; const Value: V): boolean;
var
  i: integer;
begin
  i:= 0;
  while i < fCount do begin
    if Key = fKeys[i] then exit(false); // Key already exists
    //Todo: replace with binary search
    if Key < fKeys[i] then begin
      // Make space for the key
      Move(fKeys[i], fKeys[i+1], (fCount - i) * SizeOf(TKey));
      // If the key is a String or DynArray zero out the pointer
      if (SizeOf(K) = SizeOf(NativeInt)) then NativeInt((@fKeys[i])^):= 0;
      // If the value is a String or DynArray zero out the pointer
      Move(fValues[i], fValues[i+1], (fCount - i) * SizeOf(V));
      if (SizeOf(V) = SizeOf(NativeInt)) then NativeInt((@fValues[i])^):= 0;
      break;
    end;
    Inc(i);
  end; { while }
  Inc(fCount);
  //ClearKey(fKeys[i]);
  fKeys[i]:= Key;
  // if ValueType = tkUString then UniqueString(PString(@fValues[i])^);
  fValues[i]:= Value;
  Result:= true;
end;

If the tree hold a string as its K or V type then the pointer needs to be zeroed.
The move defeats the COW mechanism and the 2 strings will have the new value.
The nice thing about the above if then is that the compiler eliminates the test.
BPlusTrees.pas.454: if (SizeOf(K) = SizeOf(NativeInt)) then NativeInt((@fKeys[i])^):= 0;
0056BBC4 8B4610           mov eax,[esi+$10]  //Test is eliminated by compiler.
0056BBC7 8D0498           lea eax,[eax+ebx*4]
0056BBCA 33D2             xor edx,edx
0056BBCC 8910             mov [eax],edx

Because the SizeOf can be resolved at compile time the compiler can see that the test always resolves to true (or false) and will eliminate it.
However
The above code needs to only run for reference counted types i.e.: interfaces, strings and dynarrays.
Right now it also runs for integers, objects etc.
The problem with TypeInfo is that it generates checking code which takes more time than the actual code I'm trying to avoid.
BPlusTrees.pas.454: if (SizeOf(K) = SizeOf(NativeInt)) and
          (PTypeInfo(TypeInfo(K))^.Kind <> tkInteger)
          then NativeInt((@fKeys[i])^):= 0;
0056BBC4 A19C104000       mov eax,[$0040109c]
0056BBC9 803801           cmp byte ptr [eax],$01
0056BBCC 740A             jz $0056bbd8
0056BBCE 8B4610           mov eax,[esi+$10]
0056BBD1 8D0498           lea eax,[eax+ebx*4]
0056BBD4 33D2             xor edx,edx
0056BBD6 8910             mov [eax],edx

Is there a way to narrow down the above test so that the test expression can still be resolved at compile time so that it compiles to the same code as above but excludes more types?
I've had a look at the intrinsic routines, but I see nothing there that can help me: http://docwiki.embarcadero.com/RADStudio/XE4/en/Delphi_Intrinsic_Routines

A: There's no way to distinguish, at compile time, unconstrained generic types. There is no operator that is evaluated at compile time that can tell a managed type from an unmanaged type.
Update
Since XE7, there is a new intrinsic IsManagedType that is designed to meet your needs. This intrinsic is, as yet, undocumented. Perhaps the best reference is here: http://delphisorcery.blogspot.co.uk/2014/10/new-language-feature-in-xe7.html?m=1

A: From XE7 onwards the (undocumented) intrinsic function IsManagedType can be used.
Like so:
if IsManagedType(K) then ...

The is a way to do this pre-XE7, by using an (also undocumented) side effect of the TypeInfo intrinsic function.
If you compare one TypeInfo against another TypeInfo the result will be evaluated at compile time.
Thus:
if TypeInfo(K) = TypeInfo(UnicodeString) then .... //resolves at compile type
if (PTypeInfo(TypeInfo(K))^.Kind <> tkUString) //produces lots of code.

so a test to compare against all expected managed types will do the job.
Obviously if a record is used that itself contains a managed type then TypeInfo will not help, but IsManagedType will.


text:
Q: Change font size of popular tags I have a few static tags in a table.
And I'm trying to track clicks on the static tags, and i have seen on other sites (and it actually really good) that the popular tags changes is size.
Have a look at this image:

This image presents the expected output.
The table looks like this:
+-----------+--------+
|    tag    | clicks |
+-----------+--------+
| Falun     | 45     |
| Stockholm | 229    |
| Borlänge  | 77     |
| ...       | ...    |
| ...       | ...    |
+-----------+--------+

More clicks, the "bigger" font size. But font size should be max 40px, and min 5px.
How can I from MySQL and PHP calculate difference in clicks and present it in font-size?
SELECT tag, (SELECT COUNT(percentage) FROM tags) AS tag_size FROM tags
Then
foreach($tags as $tag){
    <a href="#" style="font-size: <?php echo $tag->tag_size ?>px"><?php echo $tag->tag ?>
}

Very sorry for pseudo code, but i have no idea how to do this!

A: First you need to find the maximum number of clicks:
SELECT MAX(`clicks`) FROM `tags`;

Let's assume this is assigned to a variable called $max_clicks. You then need to scale the point sizes according to this value. The formula you use to do this is entirely up to you, but scaling according to the square root of the click count should produce reasonable results:
if ($max_clicks > 0) { // Avoid divide-by-zero error if nothing has been clicked
  $sqrt_max_clicks = sqrt($max_clicks);
  $query = "SELECT `tag`, 5 + 35 * SQRT(`clicks`) / $sqrt_max_clicks FROM `tags`;"
  // ... (Generate tag markup) ...
}

Obviously, 5 is the minimum point size, and 35 is the difference between the maximum and minimum point sizes. I'm assuming here that you want tags to appear in the tag list even if they have a click count of zero.

A: So you can use group by to pull all the tag records together. Then you can use ifs to set your font size. Something like:
$sql = 'SELECT tag, count(clicks) AS tag_size FROM tags group by tag';
$sth = $dbh->prepare($sql);
$sth->execute();
$result = $sth->fetchAll();
foreach($result as $row) {
    $size = $row['tag_size'];
    if($size >700 ){
        $font_size = 40;
    } elseif($size >650 ){
        $font_size = 39;
    } elseif($size >650 ){
        $font_size = 38;
    }...
    else {
        $font_size = 5;
}


text:
Q: Calculating distance between multiple points using ArcMap? The shapefile I created contains 5 points. Their FID's are (0,1,2,3,4).
I need to calculate the distance between all of them. The output table should contain the following info -
points to compare      distance
        0-1           float value
        0-2           float value
        0-3           float value
        0-4           float value
        1-2           float value
        1-3           float value
        1-4           float value
        2-3           float value
        2-4           float value
        3-4           float value

I have found some ways of calculating the distance from one particular point to other multiple points. But trying to calculate the distance between all of them.
Is there any way to do that?
I am using ArcMap 10.6 and ArcPy 2.7.

A: If you have access to the Network Analyst extension with ArcMap, you can use the OD Cost Matrix solver to return the information you need. Input your points as both origins and destinations, apply accumulation settings of distance, then solve.


text:
Q: How to load Kibana3 dashboards into Kibana4? I have recently installed Kibana4 but I am beginning to understand that dashboards are designed differently from Kibana3 i.e., to embed multiple visualizations which are designed individually into every dashboard. I already have a lot of dashboards designed in Kibana3 so I would like to know if there is a way to load them to kibana4 instead of creating everything from scratch.

A: To the best I know, there is no way to do that. Not just the formats, but the queries sent to ES backend are quite different. Kibana 3 used to use facets a lot for segmentation which is a deprecated feature and Kibana4 got rid of that.


text:
Q: Compile external library inside an R package I am building an R package with algorithms for ordinal and monotonic data classification, and I have a method called svmop that uses a version of a external library called libsvm-weights that is implemented in C but has a python wrapper.
I am using that library thought python using reticulate package, this way:
...
svmopredict<-function(models,test){
mysvm<-import_from_path("svmutil",system.file("python","python",package ="pkgName"))
pred<-mysvm$svm_predict(...)
...

where svmutil is placed in package/inst/python/python. However, that actually requires a built shared library to work. Actually I have the shared library built for linux and placed under package/inst/python , but as far as I know any form of binaries are unacceptable to CRAN.
So is there any way to  indicate the package to compile that library for windows or linux depending on the machine it is being installed? or is there any other better way to to this while being CRAN acceptable?


text:
Q: Perform t-tests by groups I am trying to do t test comparing control and treatment groups in a long table.
Part of table looks like this, the ones with T are the one with treatment while the ones without T are the controls and each group has triplicate:

Cell_line
Gene
Group
Values

A
a
1
1

A
a
1
2

A
a
1
3

A
a
1_T
1

A
a
1_T
2

A
a
1_T
3

A
a
2
1

A
a
2
2

A
a
2
3

A
a
2_T
1

A
a
2_T
2

A
a
2_T
3

A
a
3
1

A
a
3
2

A
a
3
3

A
a
3_T
1

A
a
3_T
2

A
a
3_T
3

I want to compare the treatment with the respective control only, so it will be 1 vs 1_T, 2 vs 2_T, 3 vs 3_T and so on. My end goal is to generate a column of p-value from the t test comparing treatment and respective control.
I've tried the codes below and some other codes as well but all are not working. I am thinking if I should change the table format?
Any suggestions or help would be much appreciated!
dataframe <- dataframe %>% group_by(Cell_line, Gene, Group) %>%
 mutate(t.test(Values ~ Group))

dataframe_1 <- dataframe %>% group_by(Cell_line, Gene, Group) %>%
 select_if(is.numeric) %>%
 map_df(t.test(Values, Group, paired = T))

A: You should separate the Group column into 2 columns, one indicates ID and the other indicates treatment(T) or control(C) groups.
library(dplyr)
library(tidyr)

df2 <- df %>%
  separate(Group, c("ID", "Group"), sep = "_", fill = "right") %>%
  mutate(Group = replace_na(Group, "C"))

# > df2
#    Cell_line Gene ID Group   Values
# 1          A    a  1     C 19.00937
# 2          A    a  1     C 19.24884
# 3          A    a  1     C 17.69836
# 4          A    a  1     T 25.38643
# 5          A    a  1     T 23.04596
# 6          A    a  1     T 24.25100
# ...

Then perform the two sample or paired t-test for each ID:
df2 %>%
  group_by(Cell_line, Gene, ID) %>%
  group_map(~ t.test(Values ~ Group, .x, paired = TRUE))

Output
[[1]]
        Paired t-test

data:  Values by Group
t = -6.2599, df = 2, p-value = 0.02458
alternative hypothesis: true mean difference is not equal to 0
95 percent confidence interval:
 -9.407919 -1.743297
sample estimates:
mean difference
      -5.575608

[[2]]
        Paired t-test

data:  Values by Group
t = -8.9412, df = 2, p-value = 0.01228
alternative hypothesis: true mean difference is not equal to 0
95 percent confidence interval:
 -8.261189 -2.893422
sample estimates:
mean difference
      -5.577306

[[3]]
        Paired t-test

data:  Values by Group
t = -1.929, df = 2, p-value = 0.1935
alternative hypothesis: true mean difference is not equal to 0
95 percent confidence interval:
 -11.844963   4.511769
sample estimates:
mean difference
      -3.666597

Update
If you want to summarise each group with the p-value of each t-test, try summarise():
df2 %>%
  group_by(Cell_line, Gene, ID) %>%
  summarise(p.value = t.test(Values ~ Group, paired = TRUE)$p.value) %>%
  ungroup()

# # A tibble: 3 × 4
#   Cell_line Gene  ID    p.value
#   <chr>     <chr> <chr>   <dbl>
# 1 A         a     1      0.0246
# 2 A         a     2      0.0123
# 3 A         a     3      0.194

Data
df <- structure(list(Cell_line = c("A", "A", "A", "A", "A", "A", "A",
"A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A"), Gene = c("a",
"a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a",
"a", "a", "a", "a"), Group = c("1", "1", "1", "1_T", "1_T", "1_T",
"2", "2", "2", "2_T", "2_T", "2_T", "3", "3", "3", "3_T", "3_T",
"3_T"), Values = c(19.0093682898042, 19.2488407161094, 17.6983554368874,
25.3864281704297, 23.0459637706291, 24.2509958128999, 18.6843799736362,
20.7674389968636, 18.833524600653, 23.2825845151011, 26.1647404821767,
25.5699355732609, 20.820013126065, 20.2674129364223, 21.3344018769664,
22.4175652694876, 22.2066293870532, 28.7974230636024)), row.names = c(NA,
-18L), class = "data.frame")


text:
Q: Checking for total memory usage in a bash script which spawns other processes If I have a script which calls other programs, how do I periodically check the memory usage for the script?  I can't just use a loop on pmap or ps using the script's pid since the script spawns other processes (which will have their own pid and memory usages).
Does anyone know a nifty way to get the total memory usage of a script which will take into account all the child processes that the script will spawn too?
Thanks!

A: If child processes don't have their own child it's quite easy:
$ ps h --ppid "$PID" -o vsz | awk '{ SUM+=$0 }; END { print SUM }'

Otherwise you may to rely on process group ID (PGID), but it's worth to ensure that programs you call from script do not set up their's own process groups.
$ ps h -e -o pgid,vsz | awk -v "PGID=$PID" '$1==PGID { SUM+=$2 }; END { print SUM }'

If all children of your script do not belong to the same PGID, we can only loop through processes recursively:
$ cat ~/bin/vsztree

#!/bin/bash

declare -i VSZ_TOTAL

vsz() {
    while read PID VSZ; do
        VSZ_TOTAL+=$VSZ
        vsz "$PID"
    done < <(ps --ppid "$1" --format pid,vsz --no-headers)
}

vsz "$1"
echo $VSZ_TOTAL

$ vsztree "$PID"

Here $PID is a PID of your script. Output is a total virtual memory size in kilobytes.


text:
Q: BigQuery extremely slow for small table queries with many WHERE IN parameters I'd like to understand why a query such as the one below on an 8mb table in BigQuery takes 10-15 seconds.
If I remove most of the WHERE IN parameters it performs as expected.
When comparing performance locally vs BigQuery with all the WHERE IN parameters it's about 20 times faster on my old netbook than it is on BigQuery.
SELECT  id
FROM  `example.example.emails`
WHERE id IN (104281,100567,100701,100941,101087,101157,101337,101391,101513,101831,101967,101973,102111,102403,102613,102653,102671,102843,103597,103613,103623,103729,104145,104163,104315,104325,104537,105165,105179,105257,105275,105291,105351,105363,105401,105797,105811,105893,106007,106315,106329,106363,106743,106829,107213,107371,107499,107501,107561,107677,107759,107873,107899,108029,108061,108093,108153,108537,108561,108599,108839,108861,108863,108895,108907,109011,109113,109227,109845,109931,110061,110221,110227,110267,110325,110471,110521,110553,110685,110977,110989,111179,111249,111291,111733,112015,112107,112139,112141,112431,112461,112641,112835,112971,113101,113123,113227,113281,113449,113549,113609,113661,113685,113905,113961,114015,114119,114427,114459,114609,114713,114839,114973,115187,115265,115453,115491,115497,115911,115915,116099,116497,116553,116825,116869,117005,117059,117089,117105,117235,117423,117597,117787,117929,118147,118297,118535,118573,118643,118841,118987,119147,119195,119273,119335,119389,119469,119555,119997,120369,120761,120875,120977,121029,121063,121107,121127,121155,121159,121187,121251,121265,121317,121337,121339,121363,121371,121427,121457,121467,121637,121683,121701,121827,121915,121949,122119,122441,122619,122663,122669,122737,122867,122919,122999,123121,123139,123257,123655,123741,123889,124123,124145,124221,124309,124833,124837,124909,124925,124991,125015,125019,125073,125391,125467,125725,125743,125827,125851,125895,126033,126069,126107,126593,126687,127005,127017,127059,127235,127473,128137,128201,128267,128323,128417,128539,128741,128751,129049,129245,129325,129691,129877,130329,130337,130769,131231,131317,131389,131413,131505,131591,131725,131961,131971,132081,132155,132277,132297,132299,132359,132361,132363,132365,132367,132375,132599,132613,132625,132635,132721,132747,132925,132947,133401,133493,133525,134283,134787,134801,134803,134807,134837,134845,135161,135195,135199,135271,135283,135285,135303,135311,135347,135361,135707,135869,135889,135913,136155,136205,136523,136621,136751,136757,136845,136875,136877,137127,137143,137155,137509,137623,137637,137693,137719,137739,138013,138279,138343,138553,138731,138761,138847,138929,139413,139489,139507,139995,140031,140105,140725,140813,140867,140883,140917,140993,141109,141135,141197,141265,141721,141729,141763,141849,141907,141939,141971,141973,142033,14244,142779,142797,14290,142931,143029,143153,143403,143639,143707,143711,143713,143737,143739,143745,143773,143779,143783,143791,143793,143807,143827,143829,143833,143849,143851,143853,143855,143863,143883,143887,143889,143967,144219,144311,14445,144569,144745,145357,145439,145545,145679,145681,145757,146133,146391,146407,146475,146605,146751,146989,147089,147161,147381,147543,147679,147693,14771,14783,147889,147969,14817,148533,14861,148761,148781,149101,149157,149231,149331,149333,14936,149517,149525,149725,149745,149857,15001,150079,150139,150167,150259,150345,150697,15084,151037,151115,151341,151399,15140,151423,151431,151503,151513,151543,151603,151607,151617,152079,15228,152345,152413,152529,152635,152805,152889,152901,152933,152955,152965,152977,153003,153099,153165,153189,153277,153533,153749,15401,154307,15436,154419,154667,154687,15471,154863,154883,15506,155115,155215,155321,155467,155491,155529,155549,155697,155923,155971,156279,156311,156315,156319,156389,156525,156535,156539,156617,156643,156685,156689,156695,156715,15689,157009,157551,157607,157765,157839,157945,157997,158015,15805,158059,15825,15827,158393,158413,15850,158537,158641,158669,15874,158889,159141,159455,159565,159637,15965,159795,159821,159843,160063,160095,160105,160355,160443,160535,160537,160549,16083,16109,161173,161201,161371,161563,162009,162123,162175,162281,162513,162661,162675,162765,162801,16304,163043,16345,164021,16444,164659,164831,164967,165541,165551,165563,165631,165639,165755,165883,165959,165985,165991,166009,166027,166029,166407,166591,166727,166769,166809,166847,166973,167125,167459,167551,167573,167655,16791,16797,168371,16856,168981,169729,169743,169865,16992,170079,170149,17050,170559,170587,170847,17098,171047,171199,17122,171253,171281,171379,171543,17157,171593,171713,171837,172005,172015,172041,17223,17240,17248,172503,172709,172953,173423,173437,173497,173527,173555,173655,173693,173711,173743,173765,173805,173823,173825,173897,174007,174225,174261,174337,174447,174599,17472,174805,174853,174899,175263,175339,17540,175489,17550,175607,175655,175813,175853,176213,176247,176355,176423,176429,176561,176683,176851,176857,17688,177021,17722,17726,177431,177543,177797,178135,178235,178409,178677,178725,178855,178907,178981,179053,17906,179507,179557,179625,179857,180249,180269,181049,181067,181097,181305,181429,181499,181565,181701,181771,182017,182169,182321,182689,18276,183061,183261,183589,183895,183897,183947,184091,184171,184191,184627,184635,184653,184659,184797,184907,185291,185905,185981,186513,186519,186541,186567,186665,18676,186799,187243,187247,18752,187585,187591,187617,187941,187949,188123,188281,18831,188581,188587,188607,188743,188965,189221,189393,189513,18969,189743,189787,189869,190249,190539,190557,190769,190777,190801,190903,190949,191359,191417,191447,191561,191819,191823,191873,191879,191975,192001,192111,19231,192497,192617,192737,192851,192909,19297,19300,193069,193095,193155,19328,193459,193645,193971,193979,194027,194053,194657,194837,195225,19527,195271,195321,195503,196013,196107,196673,196843,196863,196865,196959,197043,197261,197489,197569,197765,198085,198135,198233,198399,198513,19887,20163,20214,20222,20250,20346,20396,20468,20632,20664,20679,20736,20764,20766,20780,20789,20809,20813,20847,20861,20899,20906,20914,20951,21071,21107,21132,21171,21176,21348,21428,21475,21631,21937,22043,22107,22241,22297,22729,22750,22755,22787,22814,22865,23034,23173,23206,23260,23276,23311,23350,23355,23395,23420,23445,23545,23726,23839,23899,23907,24402,24619,24643,24692,24712,24781,24786,25098,25112,25236,25266,25393,25428,25439,25502,25512,25553,25734,25735,25753,25789,25800,25814,25960,26007,26068,26083,26084,26085,26152,26164,26212,26231,26260,26283,26376,26411,26617,26652,26664,26741,26758,26773,26790,26885,26949,26976,27100,27193,27287,27325,27400,27467,27528,27587,27714,27814,27840,27911,28020,28102,28239,28246,28262,28279,28306,28316,28364,28387,28447,28533,28555,28602,28709,28824,28870,29031,29076,29095,29119,29159,29161,29331,29340,29420,29464,29532,29643,29781,29898,30017,30020,30033,30084,30123,30124,30140,30150,30158,30176,30216,30249,30276,30305,30343,30350,30397,30403,30581,30595,30731,30787,30793,30842,31063,31153,31182,31186,31193,31247,31390,31437,31460,31548,31559,31683,31703,31722,31736,31837,31918,31977,32006,32021,32142,32247,32262,32283,32297,32442,32532,32591,32607,32662,32687,32724,32764,32821,32904,32905,32921,32928,32993,33172,33185,33240,33261,33299,33303,33334,33336,33341,33452,33490,33539,33584,33627,33635,33698,33724,33740,33945,33964,33971,33982,34082,34211,34242,34244,34390,34397,34402,34438,34471,34654,34684,34759,34886,34920,34978,34981,35015,35068,35165,35175,35276,35390,35438,35486,35628,35668,35777,35819,35863,36008,36035,36062,36070,36130,36157,36170,36190,36336,36413,36420,36450,36469,36475,36575,36608,36612,36651,36825,36826,36875,37008,37081,37106,37124,37213,37326,37402,37688,37898,38020,38079,38123,38170,38198,38241,38646,38883,38990,39030,39050,39126,39141,39165,39300,39316,39355,39387,39431,39447,39480,39481,39505,39559,39642,39717,39776,39783,39787,39896,40006,40041,40055,40138,40217,40243,40256,40286,40299,40313,40344,40391,40419,40452,40547,40560,40564,40670,40699,40726,40756,40825,40897,40948,41024,41078,41091,41131,41276,41283,41316,41336,41471,41476,41506,41677,41698,41771,41835,41880,42104,42248,42251,42292,42316,42324,42430,42439,42443,42444,42460,42517,42530,42607,42668,42688,42750,42755,42792,42846,42951,42987,43077,43212,43313,43327,43471,43500,43550,43577,43582,43599,43654,43734,43774,43788,43810,43857,43859,43914,44211,44408,44503,44644,44823,44839,44852,44912,44939,44943,44981,44997,45089,45137,45186,45189,45455,45586,45670,45785,45864,45903,46001,46032,46139,46147,46294,46392,46508,46518,46545,46548,46575,46837,46840,46842,46860,46890,46907,46935,47000,47066,47180,47211,47216,47217,47251,47281,47660,47698,47879,48166,48207,48381,48415,48466,48541,48567,48674,48765,48779,48799,48824,48893,49018,49052,49115,49326,49331,49342,49345,49439,49468,49729,49743,49750,49789,49977,50038,50080,50148,50313,50315,50325,50374,50388,50410,50414,50430,50573,50696,50743,50769,50795,50803,50858,50891,50895,50964,50990,51010,51082,51114,51132,51152,51291,51324,51366,51575,51875,51955,51961,52028,52071,52184,52236,52239,52277,52502,52666,52710,52772,52783,52855,52933,52959,52974,53021,53053,53098,53182,53259,53320,53324,53416,53475,53660,53662,53676,53706,53787,53921,53995,54063,54077,54190,54256,54263,54374,54377,54408,54554,54563,54570,54586,54590,54607,54983,55014,55079,55101,55152,55248,55264,55275,55282,55290,55351,55453,55510,55635,55649,55760,55773,55788,55968,56208,56242,56358,56447,56459,56529,56536,56537,56619,56704,56736,56942,56991,57009,57064,57150,57152,57153,57216,57241,57372,57435,57535,57593,57792,57816,57854,57903,57928,57934,57945,58209,58214,58272,58273,58307,58320,58325,58461,58467,58512,58522,58593,58604,58683,58758,58938,58969,59074,59202,59220,59271,59278,59286,59297,59324,59341,59377,59378,59406,59453,59458,59468,59505,59515,59519,59527,59553,59568,59594,59627,59651,59919,59920,59979,60013,60038,60163,60360,60390,60414,60489,60506,60606,60708,60718,60720,60805,60885,60934,60935,60941,60981,61030,61042,61206,61303,61344,61516,61537,61709,61725,61743,62167,62293,62343,62514,62630,62634,62708,62763,62771,63053,63076,63183,63411,63483,63493,63542,63583,63631,63695,63700,63723,63741,63762,63772,63846,63872,63893,63911,63947,63963,63971,63986,64076,64082,64106,64126,64211,64232,64249,64461,64473,64482,64483,64583,64594,64664,64733,64760,64785,64866,64873,64974,65009,65010,65043,65089,65093,65217,65259,65342,65397,65489,65539,65682,66261,66265,66272,66436,66634,66751,67165,67252,67363,67472,67487,67626,67856,67901,67914,68085,68117,68402,68404,68623,68674,68757,68770,68794,68834,68845,68867,68903,69107,69175,69209,69247,69315,69486,69652,69755,69801,69809,70027,70239,70299,70361,70782,70834,70851,70884,70952,71112,71139,71154,71411,71557,71615,71711,71718,71806,71871,71964,71986,72066,72083,72603,72709,72999,73063,73287,73293,73406,73606,73726,73728,73734,73766,73778,73899,74326,74421,74727,74835,74859,75047,75127,75207,75583,76031,76061,76069,76217,76259,76333,76423,76553,76679,76687,76699,76723,76847,76877,76925,76951,77192,77299,77307,77411,77681,77819,77847,77933,77981,78005,78099,78431,78745,78955,79009,79093,79121,79159,79165,79239,79403,79787,79909,80001,80037,80069,80279,80449,80521,80717,80849,80941,80997,81006,81125,81265,81267,81355,81409,81560,81609,81717,81723,81935,81953,82019,82331,82461,82487,82631,82655,82839,82969,83001,83061,83137,83331,83413,83437,83603,83665,83929,83937,83941,83947,83949,83953,83987,84031,84093,84127,84141,84171,84185,84189,84191,84201,84309,84331,84343,84361,84383,84435,84439,84489,84501,84523,84535,84573,84613,84665,84779,84833,84932,84991,85015,85347,85367,85445,85495,85559,85571,85797,85807,85973,86157,86203,86223,86275,86447,86523,86615,86897,86915,87039,87103,87281,87475,87795,87873,89075,89197,89205,89241,89251,89261,89695,89721,89741,89783,90325,90425,90845,90861,90915,90995,91009,91091,91131,91165,91169,91197,91201,91233,91307,91429,91477,91479,91491,91511,91567,91649,91999,92339,92457,92617,92759,92765,92907,93035,93417,93525,93691,93763,93805,93917,94043,94051,94193,94303,94847,95041,95433,95475,95545,95557,95645,95749,95885,96153,96211,96417,96479,96567,96639,96651,96673,96773,96791,96853,96921,96943,97053,97073,97495,97597,97625,97681,97697,97727,98241,98377,98519,98817,98895,98937,98991,98993,99007,99067,99555,99569,99643,99647,99657,99781,137953)

I don't believe my table to be anything unusual.

Just in case anyone asks why I'm running BigQuery on an 8mb table...this 8mb table is part of a data set that contains much larger tables 1TB+ and is far easier for me/my application if it's all in one place.
EDIT
Here is the execution data for a similar query with 3140 INs on a 14mb table. This takes 50 seconds.

A: BigQuery team flagged it as a bug. The workaround is to use WHERE id IN UNNEST([1,2,3,...]) instead of WHERE id IN (1,2,3,...).


text:
Q: Pivot Different Prices for the Same Item I have a need to show different prices for the same product where the client wants to understand discrepancies in same region. The source table looks like below

Item
Brand
Concept
Price

00A
A
Alpha
1

00B
A
Alpha
1

00B
A
Alpha
2

00B
A
Beta
3

00A
B
Alpha
1

00B
B
Alpha
1

00B
B
Beta
2

00B
B
Alpha
3

The output I am trying to achieve is a little complicate but can be simplified if we only focus on Brand A so please consider i am pivoting for Brand A only. Result Needed is

Item
Alpha

Beta

00A
1
Null
Null

00B
1
2
3

A: Are you looking for conditional aggregation?
select item, brand,
       max(case when concept = 'Alpha' and seqnum = 1 then price end) as alpha_price_1,
       max(case when concept = 'Alpha' and seqnum = 2 then price end) as alpha_price_2,
       max(case when concept = 'Beta' and seqnum = 1 then price end) as alpha_price_3
from (select t.*,
             row_number() over (partition by item, brand, concept order by price) as seqnum
      from t
     ) t
group by item, brand;


text:
Q: extracting one bit of data from json result I am trying to extract one bit of data from a JSON array when loaded with CURL. Its loads it fine from what I can tell if I echo the results but when I to get the postal_town I just keep coming across a blank???? My PHP code :
  $url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=52.406822,-1.519693&sensor=true";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    $response = curl_exec($ch);
    curl_close($ch);
    $response_a = json_decode($response, true);
    $town = $response_a['results'][0]['address_components'][0]['types']['postal_town'];

    echo $town;

And a sample of the JSON result is:
{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "Ringway Rudge",
               "short_name" : "A4053",
               "types" : [ "route" ]
            },
            {
               "long_name" : "Coventry",
               "short_name" : "Coventry",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Coventry",
               "short_name" : "Coventry",
               "types" : [ "postal_town" ]
            },
            {
               "long_name" : "West Midlands",
               "short_name" : "West Midlands",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "England",
               "short_name" : "England",
               "types" : [ "administrative_area_level_1", "political" ]
            },

A: This does the trick, did what Devon said to do, thanks
   $result = @file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?latlng=53.406822,-1.519693&sensor=true" );
    if ($result === FALSE) {
        //manage exception from file_get_contents call
    } else {
        $geocodedinfo = json_decode($result);
        if ($geocodedinfo->status == "OK") {
            $town = "";
            foreach ($geocodedinfo->results[0]->address_components as $addrcomps) {
                if ( $addrcomps->types[0] == 'postal_town')
                    $town = $addrcomps->long_name;
            }
        }
    }

    echo $town;


text:
Q: HTML Documentation Is there a tool to generate HTML pages from XML Documentation files generated by VS2010?
I searched google for such a tool, but couldn't find one.
I downloaded and installed SandCastle, but I couldn't understand how to use it.

A: Try using the Sandcastle Help File Builder, it adds a UI over sandcastle :)


text:
Q: How to add sensors in SUMO allowing me to get the instant and speed at which a car has passed through? Recently I started using SUMO in order to simulate certain situations in the context of roundabouts.
I would like a recommendation from you for a problem I am trying to solve:
I have a roundabout generated from OpenStreetMap and I have created random trips through the randomTrips.py script.
My goal is to incorporate sensors into the roundabout access ways (entrances and exits) in order to know the exact moment (instant) and speed in which a car passed that sensor.
This way, at the end of the simulation, I will be able to know how many cars have countour the roundabout successfully and for statistical analysis, the respective time and speed.
How can I do this in SUMO?
Thanks in advance.

A: You could use instant induction loops for that task. Just write an XML file (let's call it additional.xml) using the following format:
<additional>
    <instantInductionLoop id="3/1to2/1" lane="3/1to2/1_0" pos="200" file="detector.xml"/>
    <instantInductionLoop id="4/1to3/1" lane="4/1to3/1_0" pos="200" file="detector.xml"/>
</additional>

(you will probably need to adapt lane ids and positions here to match your network)
and add it to your sumo run with the option -a additional.xml.
The resulting output in the file detector.xml will contain speed and time of crossing vehicles, see the wiki for details.


text:
Q: We need a PageSetupDialog which layout and style is the same in Notepad, how to do it? We already know System.Windows.Forms.PageSetupDialog, but its layout and style is not the same in Notepad, and we need a page setup dialog in Notepad. how to do it?
Thanks.

A: You might be able to modify the PageSetupDialog using Reflection and some unholy techniques but that's not the right solution here.
What you probably want to do is build yours from scratch so that it matches the look and feel that you need.


text:
Q: After downloading an .asp or .php file, can it be converted to a .html file? I wonder if downloading files via wget and having them named .asp or .php  means that I download the webpage? Aren't these executable files?
If so, after downloading an .asp or .php file, can it be converted to an .html file?

A: Even though the files are named .asp they're actually HTML files. Look at their content to confirm this, but the use of the extension .asp is because that's the technology that was used to implement that particular site. That's the name that the browser uses when it downloads the files, and hence the name that's used when the files are written to disk, but they're still HTML.
You can also confirm the file's type using the file command:
$ file some.asp

In your earlier question where you posited how does one download a bunch of pages from the w3school website (Possible to download these webpages as a book?). You showed this command:
$ wget -r -np -nH  -p -k  http://www.w3schools.com/sql/default.asp

Notice the results of the files that that command produced for you when you ran it:
$ file ./sql/sql_func_count.asp
./sql/sql_func_count.asp: HTML document, ASCII text, with very long lines, with CRLF line terminators

So this is a bug with wget then, right?
No! This is not a bug, it's just how wget and curl behave. This is part of why I directed you to use httrack in your other Q&A linked above. If you notice the results that it produces, the names of the files are all .html with httrack. wget and curl are respecting the names of the files within the URL as they are the names of the actual files that you downloaded when you accessed them. URLs do not really have any concept of extensions, that's a OS-ism. URLs are just that, Universal Resource Locators.
URLs are meant for uniquely finding content on the internet, not for storing it locally, for later consumption. When you want to download online content for this type of use, you want to use a tool that can actually mirror that content locally and make it locally navigatable.
Tools such as httrack are essentially violating the consistency of the URLs for the sake of allowing this locally stored content to be navigatable, offline. wget and curl can be coaxed to do this, but it's typically much more cumbersome and error-prone, and so as a general rule, discouraged.
It's best to use the proper tool for the job. For mirroring online content locally, httrack is the appropriate tool!

A: No.  The file extensions you mentioned are script files.  These are files that are executed like programs.  They are executed when you click on them on a webpage to cause the effect that you get when you're browsing the site.


text:
Q: Programmatically add javascript in html page I'm trying to build an HTML page like this

    <meta http-equiv="content-type" content="text/html; charset=utf-8" />

But onclick cannot find function BtnClick().
Any ideas?

A: The eval() function evaluates or executes an argument
create BtnClick() function separate as below

function BtnClick(){
                alert("DoTest()");
            }
            function setup() {
                var mydesign = '<input type="button" value="Test" onclick="BtnClick()" />

';
                document.getElementById("myBody").innerHTML = mydesign;
            }

        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <title>JS</title>

A: It is possible to write js functions directly into the onclick attribute

    <meta http-equiv="content-type" content="text/html; charset=utf-8" />


text:
Q: How can color the first item in a select? I have this sample:
link
CODE HTML:
<select name="card_type" id="card_type" class="select-full">
    <option value="">Select</option>
    <option value="visa">Visa</option>
    <option value="mastercard">Mastercard</option>
    <option value="discovery">Discovery</option>
    <option value="maestro">Maestro</option>
</select>

CODE CSS:
select
{
   color: #ccc;
}
option
{
   color: #000;
}
option:first-child
{
   color: red;
}

I have a wish to spot and select only the first item in the list.
The first element to be red and the other to be gray for example.
Is there any possibility to do this?
I tried the above code but does not work. Can you please tell me what is wrong?
Thanks in advance!

A: I have made changes in snippet. Please check it.
is this the way you want?

$(document).ready(function(){
  if($(this).val() == 0){
      $('select').css("color","red");
    }
    else{

      $('select').css("color","#000")
    }
  $('select').change(function(){

    if($(this).val() == 0){
      $('select').css("color","red");
    }
    else{

      $('select').css("color","#000")
    }
  })
})
select
{
   color: #ccc;
}
option
{
   color: #000;
}
option:first-child
{
   color: red;

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="card_type" id="card_type" class="select-full">
    <option value="0">Select</option>
             <option value="visa">Visa</option>
             <option value="mastercard">Mastercard</option>
             <option value="discovery">Discovery</option>
             <option value="maestro">Maestro</option>
        </select>

A: Try this:
select:first-child{color: red;}

A: Use nth-of-type(1)
option:nth-of-type(1)
{
   color: red;
}

A: Well assuming something.
I think you want your <option value="visa">Visa</option> to color red but note that this is second option so use this css
select.select-full option:nth-child(2){
  color:red;
}

fiddle link :https://jsfiddle.net/yudi/L439rrsd/