text:
Q: Magento 2.2.4 : Image not displaying in product page In a custom theme, my image isn't displaying on my product page.
However, if I look in my source code, the image is indeed loaded.
But the image is displayed on the category list item.
Maybe it's because of this view.xml that I've found I don't remember where :
<?xml version="1.0"?>
<!--
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<view xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Config/etc/view.xsd">
    <media>
        <images module="Magento_Catalog">
            <image id="bundled_product_customization_page" type="thumbnail">
                <width>140</width>
                <height>140</height>
            </image>
            <image id="cart_cross_sell_products" type="small_image">
                <width>240</width>
                <height>300</height>
            </image>
            <image id="cart_page_product_thumbnail" type="small_image">
                <width>165</width>
                <height>165</height>
            </image>
            <image id="category_page_grid" type="small_image">
                <width>240</width>
                <height>300</height>
            </image>
            <image id="category_page_grid-1" type="small_image">
                <width>240</width>
                <height>300</height>
            </image>
            <image id="category_page_list" type="small_image">
                <width>240</width>
                <height>300</height>
            </image>
            <image id="customer_account_my_tags_tag_view" type="small_image">
                <width>100</width>
                <height>100</height>
            </image>
            <image id="customer_account_product_review_page" type="image">
                <width>285</width>
                <height>285</height>
            </image>
            <image id="customer_shared_wishlist" type="small_image">
                <width>113</width>
                <height>113</height>
            </image>
            <image id="gift_messages_checkout_small_image" type="small_image">
                <width>75</width>
                <height>75</height>
            </image>
            <image id="gift_messages_checkout_thumbnail" type="thumbnail">
                <width>100</width>
                <height>100</height>
            </image>
            <image id="mini_cart_product_thumbnail" type="thumbnail">
                <width>75</width>
                <height>75</height>
            </image>
            <image id="new_products_content_widget_grid" type="small_image">
                <width>240</width>
                <height>300</height>
            </image>
            <image id="new_products_content_widget_list" type="small_image">
                <width>270</width>
                <height>340</height>
            </image>
            <image id="new_products_images_only_widget" type="small_image">
                <width>78</width>
                <height>78</height>
            </image>
            <image id="product_base_image" type="image">
                <width>265</width>
                <height>265</height>
            </image>
            <image id="product_comparison_list" type="small_image">
                <width>140</width>
                <height>140</height>
            </image>
            <image id="product_page_image_large" type="image"/>
            <image id="product_page_image_large_no_frame" type="image">
                <frame>false</frame>
            </image>
            <image id="product_page_image_medium" type="image">
                <width>700</width>
                <height>560</height>
            </image>
            <image id="product_page_image_medium_no_frame" type="image">
                <width>700</width>
                <height>700</height>
                <frame>false</frame>
            </image>
            <image id="product_page_image_small" type="thumbnail">
                <width>88</width>
                <height>110</height>
            </image>
            <image id="product_page_main_image" type="image">
                <width>700</width>
                <height>560</height>
            </image>
            <image id="product_page_main_image_default" type="image">
                <width>700</width>
                <height>560</height>
            </image>
            <image id="product_page_more_views" type="thumbnail">
                <width>88</width>
                <height>110</height>
            </image>
            <image id="product_stock_alert_email_product_image" type="small_image">
                <width>76</width>
                <height>76</height>
            </image>
            <image id="product_small_image" type="small_image">
                <width>135</width>
                <height>135</height>
            </image>
            <image id="product_thumbnail_image" type="thumbnail">
                <width>75</width>
                <height>75</height>
            </image>
            <image id="recently_compared_products_grid_content_widget" type="small_image">
                <width>240</width>
                <height>300</height>
            </image>
            <image id="recently_compared_products_images_names_widget" type="thumbnail">
                <width>75</width>
                <height>90</height>
            </image>
            <image id="recently_compared_products_images_only_widget" type="thumbnail">
                <width>76</width>
                <height>76</height>
            </image>
            <image id="recently_compared_products_list_content_widget" type="small_image">
                <width>270</width>
                <height>340</height>
            </image>
            <image id="recently_viewed_products_grid_content_widget" type="small_image">
                <width>240</width>
                <height>300</height>
            </image>
            <image id="recently_viewed_products_images_names_widget" type="small_image">
                <width>75</width>
                <height>90</height>
            </image>
            <image id="recently_viewed_products_images_only_widget" type="small_image">
                <width>76</width>
                <height>76</height>
            </image>
            <image id="recently_viewed_products_list_content_widget" type="small_image">
                <width>270</width>
                <height>340</height>
            </image>
            <image id="related_products_list" type="small_image">
                <width>152</width>
                <height>190</height>
            </image>
            <image id="review_page_product_image" type="small_image">
                <width>285</width>
                <height>285</height>
            </image>
            <image id="rss_thumbnail" type="thumbnail">
                <width>75</width>
                <height>75</height>
            </image>
            <image id="sendfriend_small_image" type="small_image">
                <width>75</width>
                <height>75</height>
            </image>
            <image id="shared_wishlist_email" type="small_image">
                <width>135</width>
                <height>135</height>
            </image>
            <image id="side_column_widget_product_thumbnail" type="thumbnail">
                <width>75</width>
                <height>90</height>
            </image>
            <image id="upsell_products_list" type="small_image">
                <width>152</width>
                <height>190</height>
            </image>
            <image id="wishlist_sidebar_block" type="thumbnail">
                <width>75</width>
                <height>90</height>
            </image>
            <image id="wishlist_small_image" type="small_image">
                <width>113</width>
                <height>113</height>
            </image>
            <image id="wishlist_thumbnail" type="small_image">
                <width>240</width>
                <height>300</height>
            </image>
        </images>
    </media>
    <vars module="Magento_Catalog">

        <!-- Gallery and magnifier theme settings. Start -->
        <var name="gallery">
            <var name="nav">thumbs</var> <!-- Gallery navigation style (false/thumbs/dots) -->
            <var name="loop">true</var> <!-- Gallery navigation loop (true/false) -->
            <var name="keyboard">true</var> <!-- Turn on/off keyboard arrows navigation (true/false) -->
            <var name="arrows">true</var> <!-- Turn on/off arrows on the sides preview (true/false) -->
            <var name="caption">false</var> <!-- Display alt text as image title (true/false) -->
            <var name="allowfullscreen">true</var> <!-- Turn on/off fullscreen (true/false) -->
            <var name="navdir">horizontal</var> <!-- Sliding direction of thumbnails (horizontal/vertical) -->
            <var name="navarrows">true</var> <!-- Turn on/off on the thumbs navigation sides arrows(true/false) -->
            <var name="navtype">slides</var> <!-- Sliding type of thumbnails (slides/thumbs) -->
            <var name="transition">
                <var name="effect">slide</var> <!-- Sets transition effect for slides changing (slide/crossfade/dissolve) -->
                <var name="duration">500</var> <!-- Sets transition duration in ms -->
            </var>
            <var name="fullscreen">
                <var name="nav">thumbs</var> <!-- Fullscreen navigation style (false/thumbs/dots) -->
                <var name="loop">true</var> <!-- Fullscreen navigation loop (true/false/null) -->
                <var name="arrows">true</var> <!-- Turn on/off arrows on the sides preview in fullscreen (true/false/null) -->
                <var name="caption">false</var> <!-- Display alt text as image title in fullscreen(true/false) -->
                <var name="navdir">horizontal</var> <!--Sliding direction of thumbnails in fullscreen(horizontal/vertical)  -->
                <var name="navarrows">false</var> <!-- Turn on/off on the thumbs navigation sides arrows(true/false) -->
                <var name="navtype">slides</var> <!-- Sliding type of thumbnails (slides/thumbs) -->
                <var name="transition">
                    <var name="effect">slide</var> <!-- Sets transition effect for slides changing (slide/crossfade/dissolve) -->
                    <var name="duration">500</var> <!-- Sets transition duration in ms -->
                </var>
            </var>
        </var>

        <var name="magnifier">
            <var name="fullscreenzoom">20</var>  <!-- Zoom for fullscreen (integer)-->
            <var name="top"></var> <!-- Top position of magnifier -->
            <var name="left"></var> <!-- Left position of magnifier -->
            <var name="width"></var> <!-- Width of magnifier block -->
            <var name="height"></var> <!-- Height of magnifier block -->
            <var name="eventType">hover</var> <!-- Action that atcivates zoom (hover/click) -->
            <var name="enabled">false</var> <!-- Turn on/off magnifier (true/false) -->
            <var name="mode">outside</var> <!-- Zoom type (outside/inside) -->
        </var>

        <var name="breakpoints">
            <var name="mobile">
                <var name="conditions">
                    <var name="max-width">767px</var>
                </var>
                <var name="options">
                    <var name="options">
                        <var name="nav">dots</var>
                    </var>
                </var>
            </var>
        </var>
        <!-- end. Gallery and magnifier theme settings -->

        <var name="product_small_image_sidebar_size">100</var>  <!-- Override for small product image -->
        <var name="product_base_image_size">275</var>           <!-- Override for base product image -->
        <var name="product_base_image_icon_size">48</var>       <!-- Base product image icon size -->

        <var name="product_list_image_size">166</var>           <!-- New Product image size used in product list -->
        <var name="product_zoom_image_size">370</var>           <!-- New Product image size used for zooming -->

        <var name="product_image_white_borders">0</var>
    </vars>
    <vars module="Magento_Bundle">
        <var name="product_summary_image_size">58</var>         <!-- New Product image size used for summary block-->
    </vars>

    <vars module="Magento_ConfigurableProduct">
        <var name="gallery_switch_strategy">prepend</var>
    </vars>

    <vars module="Js_Bundle">
        <var name="bundle_size">1MB</var>
    </vars>
    <exclude>
        <item type="file">Lib::jquery/jquery.min.js</item>
        <item type="file">Lib::jquery/jquery-ui-1.9.2.js</item>
        <item type="file">Lib::jquery/jquery.ba-hashchange.min.js</item>
        <item type="file">Lib::jquery/jquery.details.js</item>
        <item type="file">Lib::jquery/jquery.details.min.js</item>
        <item type="file">Lib::jquery/jquery.hoverIntent.js</item>
        <item type="file">Lib::jquery/colorpicker/js/colorpicker.js</item>
        <item type="file">Lib::requirejs/require.js</item>
        <item type="file">Lib::requirejs/text.js</item>
        <item type="file">Lib::date-format-normalizer.js</item>
        <item type="file">Lib::legacy-build.min.js</item>
        <item type="file">Lib::mage/captcha.js</item>
        <item type="file">Lib::mage/dropdown_old.js</item>
        <item type="file">Lib::mage/list.js</item>
        <item type="file">Lib::mage/loader_old.js</item>
        <item type="file">Lib::mage/webapi.js</item>
        <item type="file">Lib::mage/zoom.js</item>
        <item type="file">Lib::mage/translate-inline-vde.js</item>
        <item type="file">Lib::mage/requirejs/mixins.js</item>
        <item type="file">Lib::mage/requirejs/static.js</item>
        <item type="file">Magento_Customer::js/zxcvbn.js</item>
        <item type="file">Magento_Catalog::js/zoom.js</item>
        <item type="file">Magento_Ui::js/lib/step-wizard.js</item>
        <item type="file">Magento_Ui::js/form/element/ui-select.js</item>
        <item type="file">Magento_Ui::js/form/element/file-uploader.js</item>
        <item type="file">Magento_Ui::js/form/components/insert.js</item>
        <item type="file">Magento_Ui::js/form/components/insert-listing.js</item>
        <item type="directory">Magento_Ui::js/timeline</item>
        <item type="directory">Magento_Ui::js/grid</item>
        <item type="directory">Magento_Ui::js/dynamic-rows</item>
        <item type="directory">Magento_Ui::templates/timeline</item>
        <item type="directory">Magento_Ui::templates/grid</item>
        <item type="directory">Magento_Ui::templates/dynamic-rows</item>
        <item type="directory">Magento_Swagger::swagger-ui</item>
        <item type="directory">Lib::modernizr</item>
        <item type="directory">Lib::tiny_mce</item>
        <item type="directory">Lib::varien</item>
        <item type="directory">Lib::jquery/editableMultiselect</item>
        <item type="directory">Lib::jquery/jstree</item>
        <item type="directory">Lib::jquery/fileUploader</item>
        <item type="directory">Lib::css</item>
        <item type="directory">Lib::lib</item>
        <item type="directory">Lib::extjs</item>
        <item type="directory">Lib::prototype</item>
        <item type="directory">Lib::scriptaculous</item>
        <item type="directory">Lib::less</item>
        <item type="directory">Lib::mage/adminhtml</item>
        <item type="directory">Lib::mage/backend</item>
    </exclude>
</view>

Note : already cleared and flushed the cache

A: try run resize image command:
php bin/magento catalog:image:resize

That will resize your image and make it can load on frontend

A: Possible reason 1: You have wrong permissions on your /media/ folder
Solution: Ensure you have writable permissions on this folder. Change permissions to 777 recursively. You can do it using SSH via this command (execute it in Magento directory):
> chmod -R 777 media/

Possible reason 2: Media folder is owned by another user. It can happen if you transfer your Magento store from one server to another
Solution: Change ownership of the /media/ folder:
> chown -R {username}:{username} media/

Important: Make sure that folder owner is the same user as your web server user. If you are not sure, contact your server support administrator.

Possible reason 3: Magento cannot resize images due low PHP memory limit. Magento resize images using GD library however if there is no sufficient amount of memory for such operation Magento will return a placeholder image
Solution: Increase your memory limit. You should open your .htaccess file and find this string:
php_value memory_limit 256M

Make sure that this value is at least 256M, or better 512M.

Possible reason 4: The GD library is not installed/configured
Solution: Make sure that your hosting installed GD library on your server, you can check it using php info.

Possible reason 5: Wrong attribute scope for small_image, thumbnail, base_image. Sometimes Magento processes images incorrectly, if they have scope=Store View (especially in case of multi-store installation)
Solution: You should open your Magento backend > Catalog > Attributes > Manage attributes. After this you should find image, small_image & thumbnail attributes. Make sure that all these attributes have scope = Global.

Possible reason 6: Problem with safe mode
Solution: It is not recommended to disable safe mode, but if you tried all other solutions you might try to disable safe mode on your server
Thank you.

A: In my case image come and goes like blinked and go
in my store there is issue of bootstrap 4.x
in 3.x it worked good
in bootystrap 4.x i removed some css like
.media {
  display: -ms-flexbox;
  display: flex;
  -ms-flex-align: start;
  align-items: flex-start;
}
.media-body {
  -ms-flex: 1;
  flex: 1;
}
and now it working like a magic
i know its not good idea but try it once

A: In my case the generated html didn't contain most of the json options, which caused the faulty behavior. Edit gallery.phtml and replace all $block->getVar("something") with $block->getVar("something", "Magento_Catalog").


text:
Q: Reorder sets of 3D points to retrieve line segments coordinates I have the following two sets of 3D points representing lines coordinates and points.
:
pts  = {{0., -0.004, 0.}, {0., 0.016, 0.}, {0.001, 0.017, 0.}, {0.006, 0.017, 0.},
        {0.011, 0.017, 0.}, {0.011, 0.021, 0.}, {0.011, 0.022, 0.001}, {0.011, 0.022, 0.015}}
pts1 = {{-0.01, 0.015, 0.}, {-0.01, 0.015, 0.01}, {0., 0., 0.}, {0., 0.015, 0.}};

In order to export those sets of data into another software, I would need to find the different lines segments creating the "big line".
So far I've only found the following code giving me the correct points order, which is not robust enough since it doesn't work with the pts1 set.
ordered[p_] := p[[Last[FindShortestTour[p, Method -> "AllTours"]]]]
ordered@pts
Graphics3D[{Red, Line@%, Point@pts}]

For the pts1 I get the following image:

I've tried changing the Method without any luck.
Unfortunately, I haven't use Mathematica in a very long time, and apparently the few skills I had have vanished.

A: Update: A more robust approach (than NearestNeighborGraph in the original answer below) is to use DistanceMatrix to identify the farthest apart pair of points and use one of the two points as the first element and sort all the points by their distance to this point:
ClearAll[pathF]
pathF = Module[{max = Max@DistanceMatrix[#] , first},
    first = First @ SelectFirst[Subsets[#, {2}], EuclideanDistance @@ # == max &];
    SortBy[#, EuclideanDistance [#, first] &]] &;

Row[Graphics3D[{Red, PointSize[Large], Point @ #, Blue,
   Line @ pathF @ #}, BoxRatios -> 1, ImageSize -> 300] & /@ {pts,  pts1}, Spacer[10]]

Original answer:
An alternative is to use NearestNeighborGraph and FindPath:
pathF = Module[{nng = NearestNeighborGraph@#, l = Length@#},
    FindPath[nng, ## & @@ GraphPeriphery[nng], l]] &;

paths = pathF /@ {pts, pts1};
Graphics3D[{Red, Thick, Line@#, Blue, Sphere[#, .5]},
    ImageSize -> 300, Boxed -> True] & /@ paths // Row

paths2 = pathF /@ {RandomSample @ pts, RandomSample @ pts1}
Graphics3D[{Red, Thick, Line@#, Blue, Sphere[#, .5]},
    ImageSize -> 300, Boxed -> True] & /@ paths // Row

same picture

redpajama_set_name: RedPajamaStackExchange


text:
Q: Handle network interruption in WebRTC I am using Amazon Kinesis Video Streams WebRTC for video chat connection between a mobile app and web site. I need to handle network interruption on web side. Let me explain the steps I have done already.
I can detect that network is disconnected on event listener ...
peerConnection.addEventListener('iceconnectionstatechange', event => {
  if (event.target.connectionState === 'connected' && event.target.iceConnectionState ===
  'disconnected') {
   // do something to handle network interruption
  }
}

In this case I will send a request to the server (test api) in a loop time interval to detect whether network is Ok or not.
In the case network connection is OK, I will run ... (reference)
const newOffer = await peerConnection.createOffer({ iceRestart: true })
            await peerConnection.setLocalDescription(newOffer)

After that I can see the connection established (connectionState/iceConnectionState status is connected) but I can not receive any datastream (the video from mobile user is freeze). However after 1 minute the send stream will be displayed on mobile side.
Thank you!

A: I found that I had to send sdp offer. So the code will be like ...
const newOffer = await peerConnection.createOffer({ iceRestart: true })
await peerConnection.setLocalDescription(newOffer)

// Send sdp offer
master.signalingClient.sendSdpOffer(peerConnection.localDescription, viewerClientID)

Now it works as expected!


text:
Q: How are numbers greater than 2^32 handled by a 32 bit machine? I am trying to understand how calculations involving numbers greater than 232 happen on a 32 bit machine.
C code
$ cat size.c
#include<stdio.h>
#include<math.h>

int main() {

    printf ("max unsigned long long = %llu\n",
    (unsigned long long)(pow(2, 64) - 1));
}
$

gcc output
$ gcc size.c -o size
$ ./size
max unsigned long long = 18446744073709551615
$

Corresponding assembly code
$ gcc -S size.c -O3
$ cat size.s
    .file   "size.c"
    .section    .rodata.str1.4,"aMS",@progbits,1
    .align 4
.LC0:
    .string "max unsigned long long = %llu\n"
    .text
    .p2align 4,,15
.globl main
    .type   main, @function
main:
    pushl   %ebp
    movl    %esp, %ebp
    andl    $-16, %esp
    subl    $16, %esp
    movl    $-1, 8(%esp)   #1
    movl    $-1, 12(%esp)  #2
    movl    $.LC0, 4(%esp) #3
    movl    $1, (%esp)     #4
    call    __printf_chk
    leave
    ret
    .size   main, .-main
    .ident  "GCC: (Ubuntu 4.4.3-4ubuntu5) 4.4.3"
    .section    .note.GNU-stack,"",@progbits
$

What exactly happens on the lines 1 - 4?
Is this some kind of string concatenation at the assembly level?

A: similar to the way as we handle numbers greater than 9, with only digits 0 - 9.
(using positional digits). presuming the question is a conceptual one.

A: In your case, the compiler knows that 2^64-1 is just 0xffffffffffffffff, so it has pushed -1 (low dword) and -1 (high dword) onto the stack as your argument to printf. It's just an optimization.
In general, 64-bit numbers (and even greater values) can be stored with multiple words, e.g. an unsigned long long uses two dwords. To add two 64-bit numbers, two additions are performed - one on the low 32 bits, and one on the high 32 bits, plus the carry:
; Add 64-bit number from esi onto edi:
mov     eax, [esi] ; get low 32 bits of source
add     [edi], eax ; add to low 32 bits of destination
; That add may have overflowed, and if it did, carry flag = 1.
mov     eax, [esi+4] ; get high 32 bits of source
adc     [edi+4], eax ; add to high 32 bits of destination, then add carry.

You can repeat this sequence of add and adcs as much as you like to add arbitrarily big numbers. The same thing can be done with subtraction - just use sub and sbb (subtract with borrow).
Multiplication and division are much more complicated, and the compiler usually produces some small helper functions to deal with these whenever you multiply 64-bit numbers together. Packages like GMP which support very, very large integers use SSE/SSE2 to speed things up. Take a look at this Wikipedia article for more information on multiplication algorithms.

A: As others have pointed out all 64-bit aritmetic in your example has been optimised away. This answer focuses on the question int the title.
Basically we treat each 32-bit number as a digit and work in base 4294967296. In this manner we can work on arbiterally big numbers.
Addition and subtraction are easiest. We work through the digits one at a time starting from the least significant and moving to the most significant. Generally the first digit is done with a normal add/subtract instruction and later digits are done using a specific "add with carry" or "subtract with borrow" instruction. The carry flag in the status register is used to take the carry/borrow bit from one digit to the next. Thanks to twos complement signed and unsigned addition and subtraction are the same.
Multiplication is a little trickier, multiplying two 32-bit digits can produce a 64-bit result. Most 32-bit processors will have instructions that multiply two 32-bit numbers and produces a 64-bit result in two registers. Addition will then be needed to combine the results into a final answer. Thanks to twos complement signed and unsigned multiplication are the same provided the desired result size is the same as the argument size. If the result is larger than the arguments then special care is needed.
For comparision we start from the most significant digit. If it's equal we move down to the next digit until the results are equal.
Division is too complex for me to describe in this post, but there are plenty of examples out there of algorithms. e.g. http://www.hackersdelight.org/hdcodetxt/divDouble.c.txt

Some real-world examples from gcc https://godbolt.org/g/NclqXC , the assembler is in intel syntax.
First an addition. adding two 64-bit numbers and producing a 64-bit result. The asm is the same for both signed and unsigned versions.
int64_t add64(int64_t a, int64_t b) { return a +  b; }
add64:
    mov     eax, DWORD PTR [esp+12]
    mov     edx, DWORD PTR [esp+16]
    add     eax, DWORD PTR [esp+4]
    adc     edx, DWORD PTR [esp+8]
    ret

This is pretty simple, load one argument into eax and edx, then add the other using an add followed by an add with carry. The result is left in eax and edx for return to the caller.
Now a multiplication of two 64-bit numbers to produce a 64-bit result. Again the code doesn't change from signed to unsigned. I've added some comments to make it easier to follow.
Before we look at the code lets consider the math. a and b are 64-bit numbers I will use lo() to represent the lower 32-bits of a 64-bit number and hi() to represent the upper 32 bits of a 64-bit number.
(a * b) = (lo(a) * lo(b)) + (hi(a) * lo(b) * 2^32) + (hi(b) * lo(a) * 2^32) + (hi(b) * hi(a) * 2^64)
(a * b) mod 2^64 = (lo(a) * lo(b)) + (lo(hi(a) * lo(b)) * 2^32) + (lo(hi(b) * lo(a)) * 2^32)
lo((a * b) mod 2^64) = lo(lo(a) * lo(b))
hi((a * b) mod 2^64) = hi(lo(a) * lo(b)) + lo(hi(a) * lo(b)) + lo(hi(b) * lo(a))
uint64_t mul64(uint64_t a, uint64_t b) { return a*b; }
mul64:
    push    ebx                      ;save ebx
    mov     eax, DWORD PTR [esp+8]   ;load lo(a) into eax
    mov     ebx, DWORD PTR [esp+16]  ;load lo(b) into ebx
    mov     ecx, DWORD PTR [esp+12]  ;load hi(a) into ecx
    mov     edx, DWORD PTR [esp+20]  ;load hi(b) into edx
    imul    ecx, ebx                 ;ecx = lo(hi(a) * lo(b))
    imul    edx, eax                 ;edx = lo(hi(b) * lo(a))
    add     ecx, edx                 ;ecx = lo(hi(a) * lo(b)) + lo(hi(b) * lo(a))
    mul     ebx                      ;eax = lo(low(a) * lo(b))
                                     ;edx = hi(low(a) * lo(b))
    pop     ebx                      ;restore ebx.
    add     edx, ecx                 ;edx = hi(low(a) * lo(b)) + lo(hi(a) * lo(b)) + lo(hi(b) * lo(a))
    ret

Finally when we try a division we see.
int64_t div64(int64_t a, int64_t b) { return a/b; }
div64:
    sub     esp, 12
    push    DWORD PTR [esp+28]
    push    DWORD PTR [esp+28]
    push    DWORD PTR [esp+28]
    push    DWORD PTR [esp+28]
    call    __divdi3
    add     esp, 28
    ret

The compiler has decided that division is too complex to implement inline and instead calls a library routine.

A: __printf_chk is a wrapper around printf which checks for stack overflow, and takes an additional first parameter, a flag (e.g. see here.)
pow(2, 64) - 1 has been optimised to 0xffffffffffffffff as the arguments are constants.
As per the usual calling conventions, the first argument to __printf_chk() (int flag) is a 32-bit value on the stack (at %esp at the time of the call instruction).  The next argument, const char * format, is a 32-bit pointer (the next 32-bit word on the stack, i.e. at %esp+4).  And the 64-bit quantity that is being printed occupies the next two 32-bit words (at %esp+8 and %esp+12):
pushl   %ebp                 ; prologue
movl    %esp, %ebp           ; prologue
andl    $-16, %esp           ; align stack pointer
subl    $16, %esp            ; reserve bytes for stack frame
movl    $-1, 8(%esp)   #1    ; store low half of 64-bit argument (a constant) to stack
movl    $-1, 12(%esp)  #2    ; store high half of 64-bit argument (a constant) to stack
movl    $.LC0, 4(%esp) #3    ; store address of format string to stack
movl    $1, (%esp)     #4    ; store "flag" argument to __printf_chk to stack
call    __printf_chk         ; call routine
leave                        ; epilogue
ret                          ; epilogue

The compiler has effectively rewritten this:
printf("max unsigned long long = %llu\n", (unsigned long long)(pow(2, 64) - 1));

...into this:
__printf_chk(1, "max unsigned long long = %llu\n", 0xffffffffffffffffULL);

...and, at runtime, the stack layout for the call looks like this (showing the stack as 32-bit words, with addresses increasing from the bottom of the diagram upwards):
        :                 :
        :     Stack       :
        :                 :
        +-----------------+
%esp+12 |      0xffffffff | \
        +-----------------+  } <-------------------------------------.
%esp+8  |      0xffffffff | /                                        |
        +-----------------+                                          |
%esp+4  |address of string| <---------------.                        |
        +-----------------+                 |                        |
%esp    |               1 | <--.            |                        |
        +-----------------+    |            |                        |
                  __printf_chk(1, "max unsigned long long = %llu\n", |
                                                    0xffffffffffffffffULL);

A: The compiler actually made a static optimization of your code.
lines #1 #2 #3 are parameters for printf()

A: As @Pafy mentions, the compiler has evaluated this as a constant.
2 to the 64th minus 1 is 0xffffffffffffffff.
As 2 32-bit integers this is: 0xffffffff and 0xffffffff, which if you take that as a pair of 32-bit signed types, ends up as: -1, and -1.
Thus for your compiler the code generated happens to be equivalent to:
printf("max unsigned long long = %llu\n", -1, -1);

In the assembly it's written like this:
movl    $-1, 8(%esp)   #Second -1 parameter
movl    $-1, 12(%esp)  #First -1 parameter
movl    $.LC0, 4(%esp) #Format string
movl    $1, (%esp)     #A one.  Kind of odd, perhaps __printf_chk
                       #in your C library expects this.
call    __printf_chk

By the way, a better way to calculate powers of 2 is to shift 1 left.  Eg.  (1ULL << 64) - 1.

A: No one in this thread noticed that the OP asked to explain the first 4 lines, not lines 11-14.
The first 4 lines are:
    .file   "size.c"
    .section    .rodata.str1.4,"aMS",@progbits,1
    .align 4
.LC0:

Here's what happens in first 4 lines:
.file   "size.c"

This is an assembler directive that says that we are about to start a new logical file called "size.c".
.section    .rodata.str1.4,"aMS",@progbits,1

This is also a directive for read only strings in the program.
.align 4

This directive sets the location counter to always be a multiple of 4.
.LC0:

This is a label LC0 that can be jumped to, for example.
I hope I provided the right answer to the question as I answered exactly what OP asked.


text:
Q: Difference between external table and internal table when using Apache HAWQ? I am using HAWQ to handle a column-based file. While reading the Pivotal document, they suggest that user should use gpfdist to read and write the readable external table in order to quickly process the data in a parallel way.
I made a table as recommended in the documentation and confirmed my data by SQL as below statement.
CREATE EXTERNAL TABLE ext_data
(col1 text, col2 text,col3 text, col4 text, col5 int, col6 int, col7 int,col8 int)
LOCATION ('gpfdist://hawq2:8085/*.csv')
FORMAT 'CSV'(DELIMITER ',');

SELECT gp_segment_id,count(*) from ext_data GROUP BY gp_segment_id;

The data was evenly distributed on all the slave nodes.
Previous my goal was creating the table, reading the data from the file and identifying the loaded data was distributed well. It was achieved by above procedure using gpfdist.
But the question is the difference between the external table and internal table. What is the reason of being using external or internal table even though two methods were same functionality.
I found some blogs that some users follow below procedures when using HAWQ or Greenplume database.
1. making external table using gpfdist
2. making internal table again
3. reading the data from external data into internal data.

I didn't fully get the idea of this behavior. Above all, I don't know why external and internal table exist and should be used for handling data using Apache Hawq or greenplume database.

A: An External Table that uses gpfdist

*

*Data is in a posix filesystem, not HDFS

*No statistics

*Files could be on ETL nodes which aren't part of the cluster

*You could have multiple files across many servers too

*Ideal solution to load data in parallel to an Internal table
insert into table_name select * from external_table_name;

Internal Table

*

*Data is stored in HDFS

*Statistics are gathered and stored in the catalog

*Files are HDFS files only

*You can take advantage of HDFS features like parquet format and snappy compression

*Provide the best performance for queries

External Tables just make it easier to load data into the database and make it do so faster.
Think about this scenario.  You get a file from your Accounting system that you need to load.  You could do this:

*

*scp the file to an edge node

*hdfs put the file into hdfs

*Create an external table in HAWQ using PXF to read the file

*Insert the data into HAWQ table

That will work and PXF will read the file in HDFS in parallel.  However, step 2 is a single process and a bottleneck.  Instead, do this:

*

*scp the file to an edge node

*Start a gpfdist process

*Create an external table in HAWQ using gpfdist to read the file

*Insert the data into HAWQ table

Now the "put" into HDFS is done in parallel because HAWQ will start virtual segments on each node to put the data.  This are typically 6 virtual segments per data node so in a 10 node cluster, you'll have 60 processes putting data into HDFS rather than a single one.


text:
Q: Set of filenames not sorted I'm using os.walk with a generator to populate a set of filenames for later manipulation using the following:
file_path = '/home/user/Developer/10/'
list_of_files = {}
cnt = 0
for (dirpath, dirnames, filenames) in os.walk(file_path):
    for filename in filenames:
        if filename.endswith('.xml'):
            list_of_files[cnt] = os.sep.join( [dirpath, filename] )
            cnt += 1

With list_of_files sorted as:
{0: '/home/user/Developer/10/2/test/channe 1_UTC_DEtoSE_183126.585.xml',
 1: '/home/user/Developer/10/2/test/channe 1_UTC_DEtoSE_183216.572.xml',
 2: '/home/user/Developer/10/2/test/channe 1_UTC_DEtoSE_183123.015.xml',
 3: '/home/user/Developer/10/2/test/channe 1_UTC_DEtoSE_183058.016.xml',
 4: '/home/user/Developer/10/2/test/channe 1_UTC_DEtoSE_183130.151.xml',
 5: '/home/user/Developer/10/2/test/channe 1_UTC_DEtoSE_183140.873.xml',
 6: '/home/user/Developer/10/2/test/channe 1_UTC_DEtoSE_183223.729.xml',
 7: '/home/user/Developer/10/2/test/channe 1_UTC_DEtoSE_183054.451.xml',
 8: '/home/user/Developer/10/2/test/channe 1_UTC_DEtoSE_183148.014.xml',
 9: '/home/user/Developer/10/2/test/channe 1_UTC_DEtoSE_183202.296.xml'}

I know that python does not sort filenames when populating lists, but I was under the impression that sets were self-sorting? If not how can I sort this set alphanumerically by filename? If I use sorted() if returns a list object with set element numbers which is pretty useless.

A: I'm not sure if snippet below would be of some help; basically, you sort by the dictionary's values (not key).
for v in sorted(list_of_files.values()):
    print(v)

A: As comments pointed out, list_of_files is a dictionary, not a set. Changing list_of_files to be initialized as an empty list and using append() such as:
file_path = '/home/user/Developer/10/'
list_of_files = []
for (dirpath, dirnames, filenames) in os.walk(file_path):
    for filename in filenames:
        if filename.endswith('.xml'):
            list_of_files.append( os.sep.join( [dirpath, filename] ) )

does the trick.
Thanks for the helpful, timely comments!

A: you can use the pathlib module to extract all the XML files with just one dict comprehension.
from pathlib import Path

file_path = Path('./home/user/Developer/10/')
list_of_files = {
    index: str(xml_file.absolute())
    for index, xml_file in enumerate(file_path.glob('**/*.xml'))
}

list_of_files  = dict(sorted(list_of_files.items(),key=lambda x:x[0])) # sort dict based on values


text:
Q: VBA Excel - Alterar cell entre True e False Estou a fazer um código mas como ainda sou muito verde no VBA não sei meter isto a funcionar. É muito simples, eu quero carregar numa celula e ela vai alterar um boolean entre True e False.
Eu quando carrego ele mete VERDADEIRO, mas depois se carregar lá outra vez, ou sair da celula e voltar a seleccionar ele não muda para false!
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.Cells.Count > 1 Then Exit Sub

        Dim mudancasAtivas As Boolean
        If Not Intersect(Target, Range("E1:E1")) Is Nothing Then
            With Target(1, 3)
                If mudancasAtivas = True Then
                     mudancasAtivas = False
                    .value = mudancasAtivas
                ElseIf mudancasAtivas = False Then
                     mudancasAtivas = True
                    .value = mudancasAtivas
                End If
            End With
        End If

        If Not Intersect(Target, Range("E2:E10000")) Is Nothing Then

            If mudancasAtivas = True Then
                Codexxx
            End If
        End If
  End If
 End Sub

Há alguma maneira mais fácil ou viável de fazer isto e funcionar?

A: O problema está ocorrendo, pois o código executa em dois momentos distintos. Como a variável mudancasAtivas é local, na 2a execução o valor que foi atribuído a ela, na 1a execução, já não vale mais.
Assim, o que você poderia fazer pra resolver isso é declarar essa variável como global no módulo da planilha.
Veja abaixo o código:
Dim mudancasAtivas As Boolean

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Target.Cells.Count > 1 Then
        Exit Sub
    End If

    If Not Intersect(Target, Range("E1:E1")) Is Nothing Then
        With Target(1, 3)
            If mudancasAtivas = True Then
                 mudancasAtivas = False
                .Value = mudancasAtivas
            ElseIf mudancasAtivas = False Then
                 mudancasAtivas = True
                .Value = mudancasAtivas
            End If
        End With
    End If

    If Not Intersect(Target, Range("E2:E10000")) Is Nothing Then

        If mudancasAtivas = True Then
            Debug.Print "OI"
        End If
    End If
End Sub

Abaixo vai uma versão reduzida e que não precisa da variável mudancasAtivas, veja:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
      If Target.Cells.Count > 1 Then
          Exit Sub
      End If

      If Not Intersect(Target, Range("E1:E1")) Is Nothing Then
          Target(1, 3).Value = Not Target(1, 3).Value
      End If

      If Not Intersect(Target, Range("E2:E10000")) Is Nothing Then
          If Cells(1, 7).Value = -1 Then
              Debug.Print "OI"
          End If
      End If
End Sub

Da maneira que está, os valores ficarão trocando entre 0 e -1. 0 é a constante que representa o FALSO no Excel e -1 a constante que representa o VERDADEIRO.
Caso você queira que seja trocado entre VERDADEIRO e FALSO, basta escrever na célula um desses dois valores.


text:
Q: Solving a linear PDE by the method of characteristics without using a parameter I'm trying to solve the partial differential equation $$2u_x + u_t = x,\qquad u(x, 0) = f(x)$$ by the method of characteristics while not retaining an extra parameter. I'm able to find the characteristic lines fairly easily, but for whatever reason, I cannot find a final solution for $u(x, t)$ that satisfies both the initial condition and the PDE itself.
Here's my work so far:
Using $dx/2 = dt/1$, I've found that the characteristic curves are $x - 2t = c$, for arbitrary $c$.
Using $du / x = dx / 2$, I've found  that $u = 1/4 x^2 + k$, for arbitrary $k$.
My next logic here was to say that $k = g(c) = g(x - 2t)$, for arbitrary function $g$.
This is where it begins to break, though. Normally, I'd substitute the initial condition $u(x, 0) = f(x)$ into the equation and find how $g$ relates to $f$, and then finally give an answer for $u$. However, the initial condition here is completely violated no matter what $g$ equals, since there is no way to get $1/4x^4$ to equal $x$ by changing $g$, so clearly there's a big gap in my logic. How would I be able to solve this problem using this general method but without this flaw? My professor said it is possible to solve this without introducing a parameter.

A: You correctly found two equations of characteristic curves :
$$x - 2t = c$$
$$u = \frac14 x^2 + k$$
Then you correctly wrote $k = g(c)$ but you made a mistake at next step. You wrote
$k= g(x - ct)$ which is not correct since $c=x-2t$. The correct writting is :
$$k=g(x-2t)$$
$$u=\frac14 x^2+g(x-2t)$$
Then the condition $u(x,0)=f(x)=\frac14 x^2+g(x)$ gives $$g(x)=f(x)-\frac14 x^2$$
Now the function $g$ is determined, any variable $X$ :
$$g(X)=f(X)-\frac14 X^2$$
We put this function into the general solution $u=\frac14 x^2+g(x-2t)$ where $X=x-2t$ :
$$u=\frac14 x^2+f(x-2t)-\frac14 (x-2t)^2$$


text:
Q: How Google Analytics inserts the tracking pixel? I am working with JS and I was looking to the GA's JS codes and I noticed something.
When I upload a page, in the console I see an image request like that;
https://www.google-analytics.com/collect?v=1&_v=j82&a=174999582&t=pageview&_s=1&dl=..

This is an image as the console said. I get this, Google inserts an image with some information about user behavior and collects the data from the request for the image. But when I look the page I can not find this "pixel", how can they send the request without including it in the page?

A: When you open the network tab in the developer tools you can see the Initiator of the request analytics.js:25. When you click on it, it will show you the code that adds a img tag with js var b=M.createElement("img");b.width=1;b.height=1;b.src=a.
The Browser loads the image even if it is not added to the DOM. That is why you can't find it there.


text:
Q: Diablo angel and demon name etymologies Is there any reasoning behind the names of the angels and demons in the Diablo series? I'm talking about characters like Azmodan, Tyrael, Malthael, etc.
Are they completely made up by the Diablo team or did they have some obscure source for the names. Do they actually mean anything?

A: Many of the details of Heaven and Hell in Diablo are heavily influenced by Judeo-Christian theology.
A lot of the names are either almost the same as, or at least share a similar naming structure to Judeo-Christian Angels and Demons.
Examples include,

*

*Azmodan (Asmodai/Asmodeus),

*Tyrael (very close to Turiel, one of The Watchers, who were tasked with watching over humanity, and became the parents of the Nephilim)

*Diablo (from the latin "diabolicus", and thus the Spanish word for Devil)

*Lilith (literally the same name, Adam's "first wife", who left him to mate with Samael the Angel of Death and give birth to a race of demons)

If you look through the below lists, you will notice a lot of similarities of structure:
http://en.wikipedia.org/wiki/List_of_angels_in_theology
http://en.wikipedia.org/wiki/List_of_theological_demons


text:
Q: Number of 3-colorings of an n-length cycle Let $C(n)$ be a cycle of length $n$, with $n\ge5$ and let $A(n)$ be the number of ways to color said cycle with the three colours ${1,2,3}$. Give a combinatorial proof that $A(n) = A(n-1) + 2A(n-2)$.
I'm at a bit of a loss on where to start with this. Could anyone guide me in the right direction? Thanks in advance for your time!

A: HINT: Number the vertices of the cycle $1$ through $n$ in cyclic order. If vertices $1$ and $n-1$ have different colors, you can remove vertex $n$ to get a properly colored $(n-1)$-cycle. Conversely, given a properly colored $(n-1)$-cycle, you can insert a vertex $n$ between vertices $1$ and $n-1$, and there is only one possible way to color it. That accounts for $A(n-1)$ properly colored $n$-cycles, those in which vertices $1$ and $n-1$ have different colors.
To finish the job, you need to show that there are $2A(n-2)$ properly colored $n$-cycles in which vertices $1$ and $n-1$ are the same color. Consider removing vertices $n$ and $n-1$.


text:
Q: WPF DataTrigger Animation only fires once I have an MVVM pattern application where I want the users to be able to enter dates, but also apply some validation on those dates. I do this by checking whatever they enter and overwriting it with the nearest valid date, if their entry is not valid. In order to let the user know that their date has been overwritten, I would have tried to animate the foreground of the date picker textbox, but I find that the animation is only visible on the first time their date is "corrected" in this way.
In the MainViewModel, I have a Ping property that notifies the UI each time it is set to "true" and a validation method that sets Ping = true each time it has to overwrite a date:
public bool Ping
{
    get => _ping;
    set
    {
        if (value && !_ping)
        {
            _ping = value;
            OnPropertyChanged();
            _ping = false;
        }
    }
}

private DateTime _from;

//Bound to the Date input field in the UI
public DateTime From
{
    get { return _from; }
    set
    {
        if (_from != value)
        {
            _from = giveValidDate("From", value);
            OnPropertyChanged();
        }
    }
}

private DateTime giveValidDate(string posn, DateTime givenDate)
{
    DateTime validDate = new DateTime();
    // [...A Load of validation that results in a valid Date output...] //

    Ping = givenDate != validDate;

    return validDate;
}

There is a TextBox style that I am using that has the animation on it:
<Style x:Key="PingableTextBox" TargetType="TextBox">
    <Setter Property="TextBlock.FontSize" Value="18"/>
    <Setter Property="TextElement.FontSize" Value="18"/>
    <Setter Property="TextElement.Foreground" Value="{StaticResource Text_LightBrush}"/>
    <Setter Property="TextElement.FontWeight" Value="Normal"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="TextBox">
                <Border BorderThickness="{TemplateBinding Border.BorderThickness}"
                        CornerRadius="2"
                        BorderBrush="{StaticResource Highlight_LightBrush}"
                        Background="{StaticResource Empty_DarkBrush}"
                        x:Name="border"
                        SnapsToDevicePixels="True">
                    <ScrollViewer HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden"
                                  Name="PART_ContentHost" Focusable="False" />
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="UIElement.IsMouseOver" Value="True">
                        <Setter Property="Border.BorderBrush" TargetName="border" Value="{StaticResource Good_MidBrush}"/>
                        <Setter Property="Cursor" Value="IBeam"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Style.Triggers>
        <DataTrigger Binding="{Binding Ping}" Value="true">
            <DataTrigger.EnterActions>
                <StopStoryboard BeginStoryboardName="Pinger"/>
                <BeginStoryboard Name="Pinger">
                    <Storyboard>
                        <ColorAnimation Storyboard.TargetProperty="Foreground.Color"
                                        From="{StaticResource Bad_Bright}" To="{StaticResource Text_Light}" FillBehavior="Stop"
                                        Duration="0:0:0:1.0"/>
                    </Storyboard>
                </BeginStoryboard>
            </DataTrigger.EnterActions>
            <DataTrigger.ExitActions>
                <RemoveStoryboard BeginStoryboardName="Pinger"/>
            </DataTrigger.ExitActions>
        </DataTrigger>
    </Style.Triggers>
</Style>

However, when I run the application, the trigger is only seen to act once (the brief red flash when an invalid date is selected):

I have seen many other questions on Stack Overflow about the same issue, but the solution has always been to add the line <StopStoryboard BeginStoryboardName="Pinger"/> in the Enter Actions, to add the line <RemoveStoryboard BeginStoryboardName="Pinger"/> to the Exit Actions or to add FillBehavior="Stop" to the storyboard. I have tried every combination of each of these in all places I could think of and the problem still persists.
Is there some other explanation for the problem that I could have missed that would fix it for me, or something that I have failed to implement correctly.. In short, why is it only firing once?
PS - some of the questions I have used to implement the code you see above:
WPF Storyboard only fires once
WPF Fade In / Out only runs once
WPF MultiDataTrigger on Tag property only firing once
WPF - problem with DataTrigger which work only once

A: You must raise the PropertyChanged after you reset the Ping property in order to trigger the Trigger.ExitAction.
Setting the backing field _ping does not propagate any change notification to the view.
This means your problem is not the problem that your quoted answer tries to solve.
You should also not define the Trigger.ExitAction in your scenario. Since you have configured the animation to stop automatically once the timeline has completed (FillBehavior="Stop"), you don't need to do anything to stop it. Note that RemoveStoryboard does not do you any favor in your case. It would only complicate the logic to reset the property since RemoveStoryboard would kill the animation immediately on the instant property toggle. This means, avoiding the Trigger.ExitAction or to be more precise the RemoveStoryboard allows you to toggle the property instantly:
// Trigger the animation
Ping = givenDate != validDate;

// Reset the property immediately to reset the animation trigger.
// Because the `Trigger.ExitAction` is deleted,
// the currently running animation will complete the timeline.
Ping = false;

If you want to implement the logic more gracefully you can toggle the Ping property and define the Trigger.EnterAction for the true state and the Trigger.ExitAction for the false state (thus converting each state into a validation error signal):
public bool Ping
{
    get => _ping;
    set
    {
        if (value && !_ping)
        {
            _ping = value;
            OnPropertyChanged();
        }
    }
}

private DateTime giveValidDate(string posn, DateTime givenDate)
{
    DateTime validDate = new DateTime();
    // [...A Load of validation that results in a valid Date output...] //

    // Trigger the animation by toggling the property.
    if (givenDate != validDate)
    {
      Ping ^= true;
    }

    return validDate;
}

    <DataTrigger Binding="{Binding Ping}" Value="true">
        <DataTrigger.EnterActions>
            <BeginStoryboard>
                <Storyboard>
                    <ColorAnimation Storyboard.TargetProperty="Foreground.Color"
                                    From="{StaticResource Bad_Bright}" To="{StaticResource Text_Light}" FillBehavior="Stop"
                                    Duration="0:0:0:1.0"/>
                </Storyboard>
            </BeginStoryboard>
        </DataTrigger.EnterActions>
        <DataTrigger.ExitActions>
            <BeginStoryboard>
                <Storyboard>
                    <ColorAnimation Storyboard.TargetProperty="Foreground.Color"
                                    From="{StaticResource Bad_Bright}" To="{StaticResource Text_Light}" FillBehavior="Stop"
                                    Duration="0:0:0:1.0"/>
                </Storyboard>
            </BeginStoryboard>
        </DataTrigger.ExitActions>
    </DataTrigger>


text:
Q: Phonegap installation error (npm) I have been searching for a solution for two days now to setup Phonegap on my Windows 8.1
system without any success.
Whenever I try to install Phonegap through npm I get an error that I think has to do
with Cordova(-lib).
To install Phonegap I had to install Node.js (v0.10.28) on my system. After this I opened up Windows Powershell and issued the following command like instructed on the Phonegap website:
npm install -g phonegap

Output: (This is the only part of the error)
error notarget No compatible version found: cordova-lib@'lorinbeer/cordova-lib.git#configparser_module'
error notarget Valid install targets:
error notarget ["0.21.2","0.21.3"]
error notarget
error notarget This is most likely not a problem with npm itself.
error notarget In most cases you or one of your dependencies are requesting
error notarget a package version that doesn't exist.

I also tried installing just Cordova through the npm and then install Phonegap, but that
didn't solve anything either.
Running the Powershell with administrator rights also didn't help and tried solutions of other people who also had problems setting up Phonegap, but nothing works.
I really hope that someone could help me out here.
Thanks in advance.

A: I had the same issue yesterday. If you check npm-debug.log, you'll notice that there is a permission issue ("Permission denied") when npm tries to access the cordova-lib git repository url. Actually, cordova-lib is a dependency for phonegap. So, it can't install it and I think that's why you get that error.
So, I tried this: install cordova-lib first then Phonegap. Yet, it still won't work; npm does not seem to check if cordova-lib is installed before trying to do it.
At this point, what I could do is to change the repository from which it retrieves cordova-lib. Here is the NPM install syntax:
npm install <tarball file>
npm install <tarball url>
npm install <folder>
npm install <pkg>
npm install <pkg>@<tag>
npm install <pkg>@<version>
npm install <pkg>@<version range>

This means I can install from a tar.gz file. Great! So, I just went to this page https://www.npmjs.org/package/phonegap to check the phonegap repository and performed these steps:

*

*Download the zip of phonegap-cli repo (https://github.com/phonegap/phonegap-cli/archive/master.zip)

*Unzip it

*Open the package.json file and find the cordova-lib entry in dependencies (line 32)

*Change the value to 0.21.3 which is the last version.

*Recreate an archive of the folder to the tar.gz format

*Open your CLI and run this command:
npm install -g path/to/archive/phonegap-cli-master.tar.gz

It should work now.
Hope that help!

A: I had a similar problem today too on Mac, even after Lorenzo said it should be all fine.  Just running this:
sudo npm install -g phonegap

... produced loads of errors like this:
error: file ./objects/pack/pack-48c0ff4147fb7e8922546c4a857b98a1cb48e01f.pack is far too short to be a packfile

I combined Lorenzo and arpan shah's solutions:
sudo npm install -g phonegap@3.4
sudo npm cache clean
sudo npm update -g phone gap

... and it seemed to magically work.

A: Problem
We published with a dependency on a branch of cordova-lib. This fork appears unavailable when lots of requests are coming through (I think). One way or another, it's unreliable.
Changing the dependency to 0.21.3 will cause commands to fail, but will allow the install.
Solutions

*

*update the 'cordova-lib' dependency to the npm published version '0.21.3'
**note, this will allow the install, but other phonegap commands will fail

*wait for about 20 minutes, then npm update -g phonegap
testing an update to resolve this issue
further updates momentarily
update
We've pushed version 3.5.0-0.20.3 which should resolve this issue
$ npm update -g phonegap

if that doesn't work, try
$ npm cache clean

and reinstall phonegap

A: Download the older version. I think there was a problem in the new one
npm install -g phonegap@3.4

I tried this and worked for me.

A: I tryed above comamnds npm cache clear and reinstall phoegap. It downloaded all libs but not command line scripts (phonegap command had still 3.4 as version). I found that better was to give command: npm install -g cordova (v 3.5)!


text:
Q: How to delete a limited number of rows in Apache Derby I want to delete a certain number of obsolete rows from a table in Derby. Something like this:
DELETE FROM table WHERE obsolete = 1 LIMIT 100000;

But Derby doesn't support the non-standard LIMIT syntax. Unfortunately the usual replacement does not work either:
DELETE FROM table WHERE obsolete = 1 FETCH FIRST 100000 ROWS ONLY;

While the following eventually works, performance is awful:
DELETE FROM table WHERE id IN
(SELECT id FROM table WHERE obsolete = 1 FETCH FIRST 100000 ROWS ONLY);

And iterating over a ResultSet calling .deleteRow() repeatedly terminates after visiting a few more than 64K rows, with no indication that anything went wrong, the cursor just stops returning rows as if there weren't any left.
Is there a better way to delete a large number, but not all, of the rows in a table?

A: This is just a suggestion. Try adding an index on (obsolete, id) and then run this variation (and perhaps experimenting with smaller than 100000 number:
DELETE
FROM table
WHERE id IN
      ( SELECT id
        FROM table
        WHERE obsolete = 1
        ORDER BY id
        FETCH FIRST 100000 ROWS ONLY
      )

The idea is to use the index to get the ids and not scan the whole table every time the statement is executed.


text:
Q: Select every 10 row as a new column in sql server I have a SQL Table with data as shown,
Item     Qty
------------
A1       59
A2       76
A3       86
A1       12
A2       17
A3       15
A1       23
A2       39
A3       07

Here we can see Item is repeated.So, i would like to group the records by Item.
I want to get the output table look like below
 Item    Qty1     Qty2     qty3
----------------------------------
    A1      59       12       23
    A2      76       17       39
    A3      86       15       07

A: Use pivot with ranking function ROW_NUMBER:
WITH CTE
AS
(

    SELECT
      Item, QTy, ROW_NUMBER() OVER(PARTITION BY ITem ORDER BY Item) AS RN
    FROM tablename

)
SELECT Item, [1] AS Qty1, [2] AS Qty2, [3] AS Qty3
FROM CTE
PIVOT
(
    SUM(Qty)
    FOR rn IN([1], [2], [3])
) AS p;

*

*demo
Results:
| Item | Qty1 | Qty2 | Qty3 |
|------|------|------|------|
|   A1 |   59 |   12 |   23 |
|   A2 |   39 |   17 |   76 |
|   A3 |   86 |   15 |    7 |

If these quantities are not fixed and they are not 3 always, you need to do it dynamically like this:
DECLARE @cols AS NVARCHAR(MAX);
DECLARE @query AS NVARCHAR(MAX);
DECLARE @colNames AS NVARCHAR(MaX);

select @cols = STUFF((SELECT distinct ',' +
                QUOTENAME(CAST(RN AS NVARCHAR(10)))
                      FROM
                      (
                        SELECT
      Item, QTy, ROW_NUMBER() OVER(PARTITION BY ITem ORDER BY Item) AS RN
    FROM tablename ) as t
                      FOR XML PATH(''), TYPE
                     ).value('.', 'NVARCHAR(MAX)')
                        , 1, 1, '');

select @colNames = STUFF((SELECT distinct ',' +
                '[' + CAST(RN AS NVARCHAR(10)) + '] AS Qty' +
                         CAST(RN AS NVARCHAR(10))
                      FROM
                      (
                        SELECT
      Item, QTy, ROW_NUMBER() OVER(PARTITION BY ITem ORDER BY Item) AS RN
    FROM tablename ) as t
                      FOR XML PATH(''), TYPE
                     ).value('.', 'NVARCHAR(MAX)')
                        , 1, 1, '');

SELECT @query = 'WITH CTE
AS
(

    SELECT
      Item, QTy, ROW_NUMBER() OVER(PARTITION BY ITem ORDER BY Item) AS RN
    FROM tablename

)
SELECT Item,' + @colNames + '
FROM CTE
PIVOT
(
    SUM(Qty)
    FOR rn IN(' + @cols + ')
) AS p;';

execute(@query);

demo

A: You can use pivot as below:
Select * from (
    Select *, Qtys = Concat('Qty', Row_Number() over(partition by Item order by Item))
        from #itemdata
        ) a
    pivot (max(qty) for qtys in ([Qty1],[Qty2],[Qty3])) p

For dynamic list you can query as below:
Declare @cols1 varchar(max)
Declare @query nvarchar(max)

Select @cols1 = stuff((select top (select max(cnt) from (select count(*) cnt from #itemdata group by item ) a) ','+
    QuoteName(Concat('Qty', Row_Number() over(order by (select Null)))) from
    master..spt_values c1, master..spt_values c2  for xml path('')),1,1,'')

Select @query = ' Select * from (
    Select *, Qtys = Concat(''Qty'', Row_Number() over(partition by Item order by Item))
            from #itemdata
        ) a
    pivot (max(qty) for qtys in (' + @cols1 + ')) p '

Exec sp_executesql @query


text:
Q: Concatenate strings and variables giving typeerror, unsupported operand for 'Tag' I have followed Data Science Dojo's tutorial on Web Scraping here: https://www.youtube.com/watch?v=XQgXKtPSzUI
I think my BeautifulSoup python is all good and operational.
But my final concatenate string and variable function is giving an error.
This is strange because the format is exactly the same as in the tutorial.
Any ideas how I can concatenate my strings and variables to run the code without errors, therefore creating the final csv?
from bs4 import BeautifulSoup as soup
from urllib.request import urlopen as uReq

my_url = ('https://www.frogbikes.com/lightweight-kids-bikes/')
uClient = uReq(my_url)
bike_cats = uClient.read()
uClient.close()
frog_soup = soup(bike_cats, "html.parser")

bike_styles = frog_soup.findAll("div", {"class": "item bike"})

filename = "products.csv"
f = open(filename, "w")
headers = "category, size(cm), age, start_price\n"

f.write(headers)

for bike_style in bike_styles:
    category = bike_style.a.h2
    info = bike_style.find("div", {"class": "info group"})
    size_list = info.div.findAll("span")
    size = size_list[1]
    info2 = info.findAll("div")
    age = info2[1].span
    start_price = info2[2].span

    # print("category: " + category)
    # print("size: " + size)
    # print("age: " + age)
    # print("start_price: " + start_price)

    f.write(category + "," + size + "," + age + "," + start_price + "\n")

f.close()

Error message:

f.write(category + "," + size + "," + age + "," + start_price + "\n")
  TypeError: unsupported operand type(s) for +: 'Tag' and 'str'

A: add .text to all the variables you are trying to save:
category = bike_style.a.h2.text
info = bike_style.find("div", {"class": "info group"})
size_list = info.div.findAll("span")
size = size_list[1].text
info2 = info.findAll("div")
age = info2[1].span.text
start_price = info2[2].span.text

The reason you are getting the error is because your variables are html tags i.e. £234. To get the actual string from the html element, call .text, which returns the str i.e. £234


text:
Q: Rails: Simple_form on one line? I am making a form with simple_form, and I'm trying to get all inputs on the same line (I want all elements to be inline horizontally on the rendered page).
I have googled the problem for some hours, but I couldn't find a solution that works.
The simple_form code:
<%= simple_form_for(@post, :html => {:class => 'form-inline' }) do |f| %>
   <%= f.input :link, label: false, placeholder: "here..." %>
   <%= f.input :type, as: :radio_buttons, collection: [[''.html_safe, '0'], [''.html_safe, '1'], [' + '.html_safe, '2']], item_wrapper_class: 'inline', label: false %>
   <%= button_tag(type: 'submit', class: "btn btn-inverse") do %>

   <% end %>
<% end %>

Any solution to this?

A: simple_form creates a form containing a div for each input.
Each div contains a label and an input field
so your css should look like:
.form-inline div { display: inline-block }


text:
Q: Fortan fully portable I/O unformatted files I have found several questions and answers about this, but among "stream", "recl", HDF,etc. I am a bit lost ( I am quite a newbie ).
I apologize if there is somewhere a plain answer to my question.
This is my problem: I want to insert into an existing Fortran code a "WRITE" statement that produces an unformatted file that I can subsequently read with another post-processing Fortran code that I have written. With portability I mean that I can do this regardless the compiler and compilation flags used and, ideally, between different platforms (computers). Is this possible? How? If not, what are the compromises that I must accept?
If the anwer is supported by a detailed, but not too complicated, explanation, it would be highly appreciated.
p.s.
I want to use unformatted files because they are lighter and the I/O operations should be faster than with formatted files. Correct?
Update #1
From a comment it seems that it is not strictly possible to obtain an unformatted file which is portable to different machines. Therefore, let us assume I want to use a single machine. I am using ifort and gfortran. If with Fotran90 is not possbile, I think I can use Fortran2003. For me it is a bit complicated to control the compilation flags used to compile the original code, but if it is necessary I can work to control that aspect too.


text:
Q: how to add the Hero Cards in bot conversation using Form Flow concept. I am working bot framework technology, in one of my project I want to display the Hero Card in Forms.
For that scenario I used Form Flow concept for developing my own form, but I got struggled to add Hero Card in the middle of my Form Conversation with my bot.
I followed the below document for Hero Card Coding using C#.
http://docs.botframework.com/en-us/csharp/builder/sdkreference/attachments.html
And also followed the below document for developing my own Form Using Form Flow concept.
http://docs.botframework.com/en-us/csharp/builder/sdkreference/forms.html
Please tell me how to add the Hero Cards in bot conversation using Form Flow concept.
-Pradeep


text:
Q: Drawing curved lines in canvas Is it possible to draw curved lines in canvas by their equations? If so, how? Let's say that I have math equation y=0,5*x^2 , how to print equation's graph?
I tried using bezierCurveTo and quadraticCurveTo methods unsuccessfully.

A: You need to populate the array of points, then use moveTo and lineTo to draw it. Something like this
var x1 = 0; // Minimum x
var x2 = 10; // Maximum x
var xstep = 0.1; // How smooth the curve should be
// ctx is the context object
// You may want to apply some transformations to the coordinate system
for (var x = x1; x < x2; x += xstep) {
    var y = 0.5 * x * x;
    if (x == x1) {
         ctx.moveTo(x, y); // First point
    } else {
         ctx.lineTo(x, y); // Subsequent points
    }
}

ctx.stroke();

bezierCurveTo, quadraticCurveTo, and the like have fixed equation form. I am not sure if they can be used to draw parabolas, but arbitrary curves are out of question.


text:
Q: Should I say "started to" or "started by"? I recently asked a question on the SE website vi and vim and my question was edited to correct my grammar mistakes.
I wrote:

I started to yank the declaration of var.

And it was corrected to:

I started by yanking the declaration of var.

To remove the technical content of this sentence, I guess we can replace it by:

I started by copying the text of the file.

My question is: why should I use started by instead of started to?
According to this answer:

Begin and start can be followed by infinitives or -ing forms.

So, I guess the way I wrote the sentence is correct. But there is no information about the "started by -ing" construction so I'm wondering if there is a subtility with this form.

A: There's a (potentially big) semantic difference between...

1: She started to cry
   and
   2: She started by crying

Pragmatically we can assume that in #1 above, there must have been something that caused her to cry, but nothing about the words as presented gives any implication that her crying was part of any "defined sequence" of events. And it certainly says nothing about whether she might do anything else after starting to cry (apart from continuing to cry, obviously! :)
But the syntax of #2 very strongly implies that there was a [planned] sequence of actions [with some expected outcome] - the first of which was to cry. Usually (but not always), when someone starts by doing something, the implication is that they're consciously aware of the intended sequence that will follow. Perhaps if she didn't get what she wanted by crying, she might switch to cajoling or insisting.

I've no idea what to yank the declaration of var means, so I can't say whether that's a credible construction or not with that particular "verb".
For example, it's quite possible to say I started by marrying the boss's daughter (as the first step in my plan to take over the company), but you can't really say I started to marry the boss's daughter in any context I can think of.

A: When you say that you 'started to do something', you mean only that you commenced doing the named activity, and you are discussing nothing else. I started to shower (I went naked into the shower and turned on the water).
When you say that you 'started by doing something', you mean that the named activity was the first of a series of activities which altogether comprised a larger plan or process, which you have previously mentioned. I needed to get ready for my wedding. I started by showering (then I put on my underwear, suit, socks and shoes, and combed my hair).


text:
Q: How to search for list of files with specific extension present in a branch using gitlab api Not able to find the list of all files with "csv" extension in a branch named av.
Tried this
https://gitlab.com/api/v4/projects/101010/repository/files/av.csv?ref=av

as the command requires complete name not with *.csv.
Is it possible with gitlab api ?

A: With the help of Gitlab api able to listdown the files under a specific branch.
curl -s -H "Authorization: Bearer <private token> -H "Content-Type:application/json" -d '{ "query": "{ project(fullpath: \"'<full_path_of_project>'\") {repository {tree (ref: \"'<Branch_name>'\", recursive: true){ blobs{ nodes {name}}}}}}"}' -k https://git_url.com/api/graphql | grep -io '"\([a-z.]*\)csv"' | sed -e 's\"\\g'


text:
Q: What will firebase.getInstance() get if there are multiple databases I was using a firebase database in my Android app. Now I need to use another database but I want to know for the old versions of my app what will "firebaseDatabase.getInstance" return? Which database from my databases will be returned?
FirebaseDatabase.getInstance();

A: .getInstance() function actually gets a string of url as an input parameter. You can see it here.
Alternatively you can follow the tutorial here to actually create more than one instance in one app with manually setting FirebaseOptions, FirebaseApp and FirebaseDatabase objects.
// Manually configure Firebase Options
FirebaseOptions options = new FirebaseOptions.Builder()
        .setApplicationId("1:27992087142:android:ce3b6448250083d1") // Required for Analytics.
        .setApiKey("AIzaSyADUe90ULnQDuGShD9W23RDP0xmeDc6Mvw") // Required for Auth.
        .setDatabaseUrl("https://myproject.firebaseio.com") // Required for RTDB.
        .build();

// Initialize with secondary app.
FirebaseApp.initializeApp(this /* Context */, options, "secondary");

// Retrieve secondary app.
FirebaseApp secondary = FirebaseApp.getInstance("secondary");
// Get the database for the other app.
FirebaseDatabase secondaryDatabase = FirebaseDatabase.getInstance(secondary);

Please also read the notes in the end, as using different databases might confuse your Google Analytics, causing analytics data drops.


text:
Q: BASH KDialog multiple file input - split string on certain space I'm using kdialog's file selection dialog to help me select multiple files and store the location of said files into an array. Unfortunately the string that is captured by kdialog has a whitespace as a delimiter. So kdialog essentially retrieves a string that looks like this:
/home/file 1.jpg /home/file 2.jpg /home/file 3.jpg
I'm essentially trying to split this string so it would look like this;
/home/file 1.jpg
/home/file 2.jpg
/home/file 3.jpg
(without the newline in between the lines. I had to add those newlines in because SO was trying to put them all in one line). I tried using this code to split it
IFS=' /' read -r -a array <<< "$variable"

But it wasn't working. Prior to using kdialog, I was using zenity's file selection dialog, which has an output like this:
/home/file 1.jpg|/home/file 2.jpg|/home/file 3.jpg
That output was easier to split with this code;
IFS='|' read -r -a array <<< "$variable"

But kdialog's thumbnails can be resized while zenity couldn't, hency why I'm trying to use kdialog.
Any help would be greatly appreciated. Thanks.

A: variable=$(kdialog --getopenfilename --multiple .);
variable=$(echo $variable | sed 's/\ \//\\n\//g')
kdialog --msgbox "$variable";

I feel so retarded for even asking this question.


text:
Q: What is the correct way to pass arguments to the JavascriptExecutor? I'm trying to use the JavascriptExecutor for my code, which involved passing in a WebElement and get some info from it. I was getting some errors, so I simplified it down to find the problem.
String test = ((JavascriptExecutor)driver).executeScript("return arguments[0];", "macon").toString();
That code won't run. It'll throw a NullPointerException. I can avoid it by not trying to access the passed variable. It doesn't seem to matter what I pass; could be an int, string, WebElement, etc etc.
So what's wrong? I can't see any discrepancies between online examples and my code, but there's obviously something. I'm using the Firefox WebDriver, and my Selenium version is 2.44.0

A: You just need to cast the results to String:
JavaScriptExecutor js = (JavaScriptExecutor) driver;
String test = (String) js.executeScript("return arguments[0];", "macon");

Also, there were compatibility issues between selenium 2.44 and Firefox 35/36 which affected javascript code execution:

*

*Firefox 35: Passing arguments to executeScript isn't working

A: Try this code:
JavaScriptExecutor js = (JavaScriptExecutor) driver;

String example=(String)js.executeScript('return $('table tbodt tr td:eq(0)')') .text();


text:
Q: Install RPostgreSQL on RHEL 6.5 libpq-fe.h Error I have RHEL 6.5 Server with an installation of R (3.1.1) & RStudioServer (0.98.1062)
I have postgresql-9.3 installed and handling a large database. In order to connect R to PostgreSQL, I have in the past used the RPostgreSQL (still do on my CentOS 7 Workstation). However, attempting to compile under RHEL 6.5 I get an error
In file included from RS-PQescape.c:7:
RS-PostgreSQL.h:23:26: error: libpq-fe.h: No such file or directory

The file is located on my system here:
/usr/pgsql-9.3/include/libpq-fe.h

Libpq is part of the Postgres installation, but RPostgreSQL cannot find it:
[root@server /]# yum list libpq*
Loaded plugins: product-id, refresh-packagekit, security, subscription-manager
Installed Packages
libpqxx.x86_64     1:4.0.1-1.rhel6                                               @pgdg93
libpqxx-debuginfo.x86_64     1:4.0.1-1.rhel6                                     @pgdg93
libpqxx-devel.x86_64   1:4.0.1-1.rhel6                                           @pgdg93

Is there any way to tell RPostgreSQL where to look (symbolic links?) or some other workaround? This should be simple, but I've wasted several hours on this already...

A: I ended up looking into the RPostgreSQL configure file in the tarball, searched for the file name the script couldn't find and decided it was easiest to create an environmental variable:

export PG_INCDIR=/usr/pgsql-9.3/include/

Worked like a charm after that.
If you have sudo rights, you could also try:

yum install postgresql-devel

A: Followup info because I just had the same problem.
Installing yum install postgresql-devel resolves the error too.


text:
Q: Plot google maps data as a picture without generating an html file I'm using the python library gmplot for getting a map from GoogleMaps and georeferencing some point coordinates. I would like to plot my Googlemap result in a detached window like I do with images generated with matplotlib, but with gmplot I can see only the draw() function which generates an html of the googlemaps code. Now I'm using the following functions:
gmap = gmplot.GoogleMapPlotter(lat[0],lon[0],18)
gmap.scatter(lat,lon, 'r', 0.1, marker=False)
gmap.draw('map.html')

Should I use another python library or can I generate an image with gmplot?

A: If you want to store a map as an image you can refer this question to do that. With some minor change i was able to get the result in a .bmp format.
here is my small edited code for reference
from PIL import Image
import urllib, StringIO
from math import log, exp, tan, atan, pi, ceil

EARTH_RADIUS = 6378137
EQUATOR_CIRCUMFERENCE = 2 * pi * EARTH_RADIUS
INITIAL_RESOLUTION = EQUATOR_CIRCUMFERENCE / 256.0
ORIGIN_SHIFT = EQUATOR_CIRCUMFERENCE / 2.0

def latlontopixels(lat, lon, zoom):
    mx = (lon * ORIGIN_SHIFT) / 180.0
    my = log(tan((90 + lat) * pi/360.0))/(pi/180.0)
    my = (my * ORIGIN_SHIFT) /180.0
    res = INITIAL_RESOLUTION / (2**zoom)
    px = (mx + ORIGIN_SHIFT) / res
    py = (my + ORIGIN_SHIFT) / res
    return px, py

def pixelstolatlon(px, py, zoom):
    res = INITIAL_RESOLUTION / (2**zoom)
    mx = px * res - ORIGIN_SHIFT
    my = py * res - ORIGIN_SHIFT
    lat = (my / ORIGIN_SHIFT) * 180.0
    lat = 180 / pi * (2*atan(exp(lat*pi/180.0)) - pi/2.0)
    lon = (mx / ORIGIN_SHIFT) * 180.0
    return lat, lon

############################################

upperleft =  '-29.44,-52.0'
lowerright = '-29.45,-51.98'

zoom = 18   # be careful not to get too many images!

ullat, ullon = map(float, upperleft.split(','))
lrlat, lrlon = map(float, lowerright.split(','))
scale = 1
maxsize = 640
ulx, uly = latlontopixels(ullat, ullon, zoom)
lrx, lry = latlontopixels(lrlat, lrlon, zoom)
dx, dy = lrx - ulx, uly - lry
cols, rows = int(ceil(dx/maxsize)), int(ceil(dy/maxsize))
bottom = 120
largura = int(ceil(dx/cols))
altura = int(ceil(dy/rows))
alturaplus = altura + bottom

final = Image.new("RGB", (int(dx), int(dy)))
for x in range(cols):
    for y in range(rows):
        dxn = largura * (0.5 + x)
        dyn = altura * (0.5 + y)
        latn, lonn = pixelstolatlon(ulx + dxn, uly - dyn - bottom/2, zoom)
        position = ','.join((str(latn), str(lonn)))
        print x, y, position
        urlparams = urllib.urlencode({'center': position,
                                      'zoom': str(zoom),
                                      'size': '%dx%d' % (largura, alturaplus),
                                      'maptype': 'satellite',
                                      'sensor': 'false',
                                      'scale': scale})
        url = 'http://maps.google.com/maps/api/staticmap?' + urlparams
        f=urllib.urlopen(url)
        im=Image.open(StringIO.StringIO(f.read()))
        final.paste(im, (int(x*largura), int(y*altura)))
final.show()

and yes to run the above code you will require pillow module.
hope it may help !

A: This would also work: First download chromedriver to your hard drive (e.g. to C:\chromedriver.exe) and pip install selenium.
Then use this code:
from selenium import webdriver
import time

driver = webdriver.Chrome(r"C:\chromedriver.exe")
driver.get(r"C:\route.html")
time.sleep(3)
driver.save_screenshot('map.png')
driver.quit()


text:
Q: How to style parent element based on his child Let's say our html structure looks like this:

Now on some button action I add active className to child's div.
My question is:
How to style only parent element if child's div has active className
// CSS pseudo code //
if(child.has.className('active')
.parent{
background: red;
}

A: You can use the :has() pseudo class selector, although that's only supported in newer browsers. Otherwise you'll probably need to use JS.

.parent {
  background: #ccc;
}

.parent:has(.active) {
  background: steelblue;
  color: #eee;
}

/* Ignore below, for stylistic purposes only */
.parent {
  margin: 1rem;
  padding: 1rem;
  border-radius: .5rem;
  font-family: Arial, sans-serif;
}

Child

Child (active)

For a JS-based solution there are two ways:

*

*Recommended: in the code that adds the active class, you also toggle a class on the parent, say has-active-child and style it accordingly

*Not recommended: listen to class changes on the child node using MutationObserver API and style the parent node

A: At the moment not all browsers support the pseudo class selector :has() as Terry explained. A JavaScript solution goes as following.
Example from GeeksForGeeks

$('ul li:has(ul.child)').addClass('has_child');
.parent > li > ul > li {
    background:orange;
}
.parent > li.has_child {
    background:red;
}
.parent li {
    background:blue;
    color:black;
}

<!DOCTYPE html>

I am first

I am second

I am third

I am forth

I have kids.

child1

child2

child2.1

child2.2

child2.3

child3

child4

child5

I am sixth

I am seventh

I am eight


text:
Q: Service.startForeground() issue in Android 9 I am using a background service which call a REST API and after getting data it send a local notification to the user but I am facing this issue of Service.startForeground() in android 9. Kindly review the code and help me with it.
NotificationEventReceiver Class
public class NotificationEventReceiver extends BroadcastReceiver
{
    static AlarmManager alarmManager;
    static PendingIntent pendingIntent;
    static int count=0;
    static Context mcon;

    public static void setupAlarm(Context context) {
        mcon=context;
        enableBootReciever();

        AppSession.put(Constants.SERVICE_CALL,1);
        Intent service = new Intent(context, NotificationEventReceiver.class);
        service.setAction("Start");
        pendingIntent = PendingIntent.getBroadcast(context, 0, service, PendingIntent.FLAG_UPDATE_CURRENT);
        alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Calendar calendar = Calendar.getInstance();

        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.setTime(new Date());

        System.out.println("Log: In the Notification Event Receiver");

        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                calendar.getTimeInMillis(),
                10800*1000,
                pendingIntent);
    }

    public static void disableAlarm(Context context) {

        if (alarmManager!=null)
            alarmManager.cancel(pendingIntent);
    }

    static void enableBootReciever(){
        ComponentName receiver = new ComponentName(mcon, NotificationServiceStarterReceiver.class);
        mcon.getPackageManager().setComponentEnabledSetting(receiver,
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if(action.equals("Start")) {
            //Log.d("asdkl",Integer.toString(count));
            Intent i = new Intent(context, Service.class);
            //context.startService(i);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(i);
            } else {
                context.startService(i);
            }
        }}}

NotificationServiceStarterReceiver Class
    public final class NotificationServiceStarterReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        NotificationEventReceiver.setupAlarm(context);
        System.out.print("Log: In the Notification Service Starter Receiver");

    }}

Service Class
    public class Service extends IntentService {
    String CHANNEL_ID = "999";
    private static String CHANNEL_NAME="My Channel";
    private static String CHANNEL_DESCRIPTION="My Channel Description";

    public Service() {

        super(Service.class.getSimpleName());
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {

        StartListening(getApplicationContext());
    }

    @Override
    public void onCreate() {
        super.onCreate();
        System.out.print("Log: In the Service");

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            createNotification();

        }else{
            this.startForeground(1,new Notification());
        }
        //getApplicationContext().startForeground(1,new Notification());
    }

    private void createNotification()
    {
        createNotificationChannel();
        Bitmap largeIcon = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.mipmap.ic_launcher);

        Intent intent = new Intent(this, MainActivity.class);
        intent.putExtra("fromNotification", true);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

        if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            ShortcutBadger.applyCount(getApplicationContext(), AppSession.getInt(Constants.NOTIFICATION_COUNT));
        }
        final NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID);
        builder.setContentTitle("Scheduled Notification")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("Quiz Alert")
                .setContentText("A New Quiz has been scheduled on " + AppSession.get(Constants.QUIZ_DATE_TIME) + ". Kindly don't forget to Join.")
                .setChannelId(CHANNEL_ID)
                .setLargeIcon(largeIcon)
                .setNumber(AppSession.getInt(Constants.NOTIFICATION_COUNT))
                .setBadgeIconType(NotificationCompat.BADGE_ICON_SMALL)
                .setVibrate(new long[]{1000, 1000, 1000, 1000, 1000})
                .setAutoCancel(true)
                .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
                .setColor(getResources().getColor(R.color.colorAccent))
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setContentIntent(pendingIntent)
                .setStyle(new NotificationCompat.BigTextStyle().bigText("A New Quiz has been scheduled on " + AppSession.get(Constants.QUIZ_DATE_TIME) + ". Kindly don't forget to Join."))
                .setGroup("TEST");

        final NotificationManagerCompat manager = NotificationManagerCompat.from(this);
        manager.notify(2, builder.build());

    }

    private void createNotificationChannel() {
        // Create the NotificationChannel, but only on API 26+ because
        // the NotificationChannel class is new and not in the support library

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
            channel.setDescription(CHANNEL_DESCRIPTION);
            NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            notificationManager.createNotificationChannel(channel);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.stopSelf();
    }

    public void StartListening(final Context mcontext) {

        Log.d("In StartListening",("Listening " + Integer.toString(count)));
        System.out.println("In StartListening " + Integer.toString(count));

        //    Toast.makeText(mcontext, "In StartListening", Toast.LENGTH_SHORT).show();
        new RestCaller(new iResponseHandler() {
            @Override
            public void onSuccess(Call call, Response response, int reqCode) {
                if (reqCode == Constants.REQUEST_CODE_QUIZ_DATE) {
                    AppSession.put(Constants.KEY_API_CALL,0);
                    QuizDatePOJO quizDatePojo = (QuizDatePOJO) response.body();

                    if(quizDatePojo.getResponse().getDate()==null){

                    }else{
                        SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
                        SimpleDateFormat outputFormat = new SimpleDateFormat("dd-MM-yyyy");
                        Date date = null;
                        try {
                            date = inputFormat.parse(quizDatePojo.getResponse().getDate());
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        String formattedDate = outputFormat.format(date);
                        String time =quizDatePojo.getResponse().getTime();
                        AppSession.put(Constants.QUIZ_DATE_TIME,formattedDate+" "+time);
                        createNotification();

                    }
                }
            }

            @Override
            public void onFailure(Call call, Response response, int reqCode) {
                AppSession.put(Constants.KEY_API_CALL,"FAILED");
                StartListening(mcontext);
                Loading.cancel();

            }

            @Override
            public void onApiCrash(Call call, Throwable t, int reqCode) {
                AppSession.put(Constants.KEY_API_CALL,"FAILED");
                StartListening(mcontext);
                Loading.cancel();

            }
        }, MainApplication.getRestClient()
                .getApiServices().getQuizDate(), Constants.REQUEST_CODE_QUIZ_DATE);

    }}

Please guide with what changes are required here. This issue comes in Android 9 and the app crashes as soon as the notification pops
Log
Fatal Exception: android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground(): ServiceRecord{a341388 u0 com.developer.emten/.services.Service}
       at android.app.ActivityThread$H.handleMessage + 2112(ActivityThread.java:2112)
       at android.os.Handler.dispatchMessage + 112(Handler.java:112)
       at android.os.Looper.loop + 216(Looper.java:216)
       at android.app.ActivityThread.main + 7593(ActivityThread.java:7593)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run + 524(RuntimeInit.java:524)
       at com.android.internal.os.ZygoteInit.main + 987(ZygoteInit.java:987)

A: Solution is to just add the following in AndroidManifest.xml:
<manifest ...>
     ...
     <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
     ...
     <application ...>
     ...
</manifest>

https://developer.android.com/about/versions/pie/android-9.0-changes-28#fg-svc


text:
Q: How to setup two dynamic conditions in SUMIFS like problem in R? I already tried my best but am still pretty much a newbie to R.
Based on like 500mb of input data that currently looks like this:
TOTALLISTINGS
  listing_id calc.latitude calc.longitude reviews_last30days
1       2818       5829821       335511.0                  1
2      20168       5829746       335265.2                  3
3      25428       5830640       331534.6                  0
4      27886       5832156       332003.1                  3
5      28658       5830888       329727.2                  3
6      28871       5829980       332071.3                  7

I need to calculate the conditional sum of reviews_last30days - the conditions being a specific and changing area range for each respective record, i.e. R should sum only those reviews for which the calc.latitude and calc.longitude do not deviate more than +/-500 from the longitude and latitude values in each row.
EXAMPLE:

*

*ROW 1 has a calc.latitude 5829821 and a calc.longitude 335511.0, so R should take the sum of all reviews_last30days for which the following ranges apply: calc.latitude 5829321 to 5830321 (value of Row 1 latitude +/-500)
calc.longitude 335011.0 to 336011.0 (value of Row 1 longitude +/-500)

So my intended output would look somewhat like this in column 5:
TOTALLISTINGS
 listing_id calc.latitude calc.longitude reviews_last30days  reviewsper1000
1       2818       5829821       335511.0                  1             4
2      20168       5829746       335265.2                  3             4
3      25428       5830640       331534.6                  0            10
4      27886       5832156       332003.1                  3             3
5      28658       5830888       331727.2                  3            10
6      28871       5829980       332071.3                  7            10

Hope I calculated correctly in my head, but you get the idea..
Until now I particularly struggle with the fact that my sum conditions are dynamic and "newly assigned" since the latitude and longitude conditions have to be adjusted for each record.
My current code looks like this but it obviously doesn't work that way:
review1000 <- function(TOTALLISTINGS = NULL){
      # tibble to return
      to_return <- TOTALLISTINGS %>%
        group_by(listing_id) %>%
        summarise(
          reviews1000 = sum(reviews_last30days[(calc.latitude>=(calc.latitude-500) | calc.latitude<=(calc.latitude+500))]))
      return(to_return)
    }

REVIEWPERAREA <- review1000(TOTALLISTINGS)

I know I also would have to add something for longitude in the code above
Does anyone have an idea how to fix this?
Any help or hints highly appreciated & thanks in advance! :)

A: See whether the below code will help.
TOTALLISTINGS$reviews1000 <- sapply(1:nrow(TOTALLISTINGS), function(r) {
  currentLATI <- TOTALLISTINGS$calc.latitude[r]
  currentLONG <- TOTALLISTINGS$calc.longitude[r]
  sum(TOTALLISTINGS$reviews_last30days[between(TOTALLISTINGS$calc.latitude,currentLATI - 500, currentLATI + 500) & between(TOTALLISTINGS$calc.longitude,currentLONG - 500, currentLONG + 500)])
})


text:
Q: What is the difference between image(SQL Server) and longblob(MySQL)? SQL Server Image Table
CREATE TABLE "SqlServerTable" (
    "id" INT NOT NULL,
    "image" IMAGE NOT NULL,
    PRIMARY KEY ("id")
);

MySQL Image Table
CREATE TABLE `MySqlTable` (
    `id` INT NOT NULL,
    `image` LONGBLOB NOT NULL,
    PRIMARY KEY (`id`)
);

What is the difference between image and longblob?
How can convert data from image type in SQL Server to blob type in MySQL?
When I copy data from SQL Server to MySQL, does not show any image with this
file_put_contents('2xx.jpg',$MySqlTable['image']);?
I have do special processing on image type SQL Server?

A:
BLOB in MySQL
  BLOB values are treated as binary strings (byte strings). They have no character set, and sorting and comparison are based on the numeric values of the bytes in column values.
  The four BLOB types are TINYBLOB, BLOB, MEDIUMBLOB, and LONGBLOB. These differ only in the maximum length of the values they can hold.
  MySQL Connector/ODBC defines BLOB values as LONGVARBINARY.

image
  Variable-length binary data from 0 through 2^31-1 (2,147,483,647) bytes.
image data type will be removed in a future version of Microsoft SQL Server. Use varbinary(max) instead.
Microsoft research: To BLOB or Not To BLOB

IMHO, both are a set of binary data and difference is about how each DBMS stores that set of binary data.
I think a better solution to avoid processing over images, streams and so on is to store URL File  Links if there is not any advantage of using in table file data.