text:
Q: PyQt5: can't figure out how to call glReadPixels I'm trying to use glReadPixels in a QOpenGLWidget class (Qt 5.8.0, PyQt 5.8.0, python 3.6.1), but can't figure out how to access the function.
Here's a segment of my code:
self.vp = QOpenGLVersionProfile()
self.vp.setVersion(2,1)
self.glFunc = QOpenGLContext.currentContext().versionFunctions(self.vp)
self.glFunc.glReadPixels(...)

Regardless of what I pass to the function, I get an error:
AttributeError: 'QOpenGLFunctions_2_1' object has no attribute 'glReadPixels'

Running print(dir(self.glFunc) returns a huge list of functions but does not include glReadPixels or any variation that I can find (there's GL_READ_PIXELS but it's an int).
Am I looking in the wrong place for this function?


text:
Q: How does "ee.reducer.mean()" work when applying a mask over an image if the spatial resoultions of the image and the mask aren't the same? I am trying to calculate NDVI using MODIS images over corn fields. But I'd like to mask the areas which are not corn. The spatial resolution of MODIS images is 250m, but the resolution of the cropland layer(corn mask) is 30 m.
My question is that when I apply a mean reducer in the region, how does Google Earth Engine average the pixels over the mismatched resolutions?
Does it consider the fraction of non-masked pixels to calculate the average NDVI value? or Does it resample the pixels based on the given scale?
I don't understand it.
Here is the code that I've written:
https://code.earthengine.google.com/e036f993c9c4a8f5f84eb877e10dbfd0
Here is the image:

A: At the most primitive level of Earth Engine, a band's value and mask are processed as functions from coordinates to numeric values.
When you use reduceRegion(), the reduction operation asks the image's bands for their value and mask at points on a grid — the spacing between the points being determined by the scale parameter of the reduction. At each point, the image will determine which of its actual stored pixels (assuming it's an image asset or straightforwardly derived from one) is closest to the requested point, and return that point.
This is in a sense the same process as produced the image you are looking at. You can see in your screenshot that the mask and the data have two different "original" pixel grids, and you're looking at it on a third pixel grid, that of your screen. Similarly, the reducer has its own grid determined by scale and CRS.
So, you can consider this process to be nearest-neighbor resampling, performed on the data value and mask separately. But if you use a fine enough scale on the reduction, the values will act like they're weighted/fractional, because, for example, a data pixel that is half-masked will be sampled half as many times as one that is fully unmasked, so it will contribute only half as much to the mean.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I get JavaScript setTimeout to stop after 10 tries? I have the following part of a jQuery .ajax call. It checks every second I believe. How can I get to stop after 10 tries?
 success: function (data) {
                    if (!data) {
                        setTimeout(function (inputInner) { CallIsDataReady(inputInner); }, 1000);
                    }

EDIT: I implemented one solution but the logging for the service call seems to stop after 2 times.
function CallIsDataReady(input) {
            var timer;
            var count = 0;

            $.ajax({
                url: "http://www.example.com/services/TestsService.svc/IsDataReady",
                type: "GET",
                contentType: "application/json; charset=utf-8",
                data: input,
                // dataType: "json",
                success: function (data) {
                    if (!data) {
                        setTimeout(function(inputInner) {
                            CallIsDataReady(inputInner);
                            count++;
                            if (count == 10) {
                                clearInterval(timer);
                                count = 0;
                            }
                        }, 1000);
                    }
                    else {
                        console.log("data returned - calling callUpDateGrid");
                        //Continue as data is ready
                        callUpdateGrid(input);
                    }
                },
                error: function (jqXHR, textStatus, errThrown) {
                    console.log("AJAX call failed in CallIsDataReady");
                    console.log(errThrown);
                }
            });

A: Just assign your setTimeout to a variable, and use a counter, when it reaches 10, call clearTimeout()

A: user setInterval with a counter:
if (!data) {
    var count = 0;
    var interval;
    interval = setInterval(function (inputInner) {
        if (count === 10) {
            clearInterval(interval);
            return;
        }
        CallIsDataReady(inputInner);
        count++;
    }, 1000);
}

A:   // global variable - should be outside your ajax function
 var timer;
 var count = 0;

 ....
 success : function( data) {
               if( ! data ) {
                  // don't know where you are getting inputInner. assuming its a global variable
                  timer = setInterval ( function ( inputInner ) {
                                            CallIsDataReady(inputInner);
                                            count++;
                                            if ( count == 10 ) {
                                              clearInterval(timer);
                                              count = 0;
                                            }
                                        }, 1000);
                }
           }

A: Use an interval
var count = 0,
    handler = setInterval(dostuff, 1000);

function dostuff(inputInner){

   //CallIsDataReady(inputInner);

   if(++count === 10)
       clearInterval(handler);
}

http://jsfiddle.net/mGgLz/
However, you should never rely on the assumption that the ajax call always takes < 1000ms. Check the readyState on the XHR and make sure it's 4 before polling again.


text:
Q: PHP random numbers frequency of occurrence In PHP I want to generate random numbers from 1 to 10 in a loop.
So for example:
$factor="1"; // this will be changed in another area

for ($i=0;$i<10;$i++) {
if ($factor=="1") {$output = rand(1,10);}
else if ($factor=="2") {$output = rand(1,10);}
else {$output = rand(1,10);}

 }

Now to explain this - In result I want to receive 10 random numbers, but when $factor = "2", in that case I want to receive numbers from 6 to 10 more frequently as lower numbers.
It means, from 10 numbers I need to have 80% higher random numbers (it means larger than 5) and in 20% lower numbers (5 or lower).
E.g. 1,2,6,7,8,9,7,9,8,6  (1,2 are the only lower numbers = 20%, the rest are higher = 80)
If the $factor will change, then I want to change the percentage, in that case for example 40% lower numbers, 60% higher numbers.
The idea I have is to put each output in the loop to an array, then check each result and somehow calculate, if there is no 80% of larger numbers, then get random numbers again for those, but this seems to be an overkill.
Is there a simplier solution?

A: Let's go with the percentages you mention and first generate a random number between 1 and 100. Then the lower number, 1 to 20, have to represent outputs 1 to 5 and the higher numbers, 21 to 100, have to represent output 6 to 10. In PHP that would look like this:
function HighMoreOften()
{
    $percentage = rand(1, 100);
    if ($percentage <= 20) {
        return rand(1, 5);
    } else {
        return rand(6, 10);
    }
}

That should do the trick. You can also convert the percentage you got into the output, this would probably be slightly faster:
function HighMoreOften()
{
    $percentage = rand(1, 100);
    if ($percentage <= 20) {
        return ceil($percentage / 5);
    } else {
        return 6 + ceil(($percentage - 20) / 20);
    }
}

but personally I think the first version is easier to understand and change.

A: To change frequency you gonna need an array of numbers. And a sum to this direction. frequency is the relation of something between an array of things.
$t = 0;

// $factor = 1; // let's say that this means 20%
$factor = 2; // let's say that this means 40%

 if ($factor === 1) {

     for ($i = 1; $i <= 80; $i++) {
         $t += rand(1,10);
     }
     for ($i = 1; $i <= 20; $i++) {
         $t += rand(6,10);
     }

 } else if ($factor === 2) {

     for ($i = 1; $i <= 60; $i++) {
         $t += rand(1,10);
     }
     for ($i = 1; $i <= 40; $i++) {
         $t += rand(6,10);
     }

 } else {
     for ($i = 1; $i <= 100; $i++) {
         $t += rand(1,10);
     }
 }
 echo round(($t/100), 0);

Something like that! :)

A: I came with a very simple (maybe creepy) solution, but this works as I wanted:
echo print_r(generate("2"));

function generate($factor) {

$nums=array();

for ($i=0;$i<10;$i++) {

    if ($i<$factor) {$rnd = rand(1,5);}
    else {$rnd = rand(6,10);}

    array_push($nums,$rnd);

     }
     return $nums;
    }

I can also shuffle the final array results, as the lower numbers will be on the beginning always, but in my case it doesn't matter.


text:
Q: CSS3 multiple backgrounds across selectors What I want to achieve is to set background in two separate CSS classes (using CSS3's multiple backgrounds would be great). I would like to that with as little markup as possible and to be universal.
Example:
CSS
.button {
    display: block;
}

.green {
    background-color: #87b400;
    background: -moz-linear-gradient(top,  #a4d400,  #739e00);
}

.icon {
    background-repeat: no-repeat;
}

.icon.add {
    background-image: url('../img/icons/add.png');
}

HTML
add item
<input type="submit" name="example" value="add item" class="button green icon add" />
<button type="submit" class="button green icon add">add item</button>

I realize that i can do something like that
add item

but I think that there is a better way and I wouldn't be able to use it inside input element.
I also don't want to do something like this
.button.green.icon.add {
    background: -moz-linear-gradient(top,  #a4d400,  #739e00),
                url('../img/icons/add.png');
}

because having, let's say, 5 colors and 11 icons it is going to be a horror.

A: It is my understanding that CSS3 multiple image backgrounds are only possible in the same declaration.
http://www.w3.org/TR/css3-background/#layering

A: DaiYoukai is right, CSS3 multiple image backgrounds - can not be used across selectors.
Workaround: you can use CSS3 Content feature - it virtually create additional element.
CSS
.icon{
    background-image: url('../img/icons/icon.png');
    width:16px;
    height:16px;
}
.icon.add:after {/* new virtual layer */
    background-image: url('../img/icons/icon_add.png');
    content: "";
    display: block;
    position: absolute;
    width:16px;
    height:16px;
}

Note: Modern browsers correctly supports both CSS3 features, except IE:

*

*CSS3 multiple backgrounds - from IE9.

*CSS3 Content - from IE8.

A: If jQuery is an option:
$(".green, .icon.add").each(function () {
  var backgrounds = [];
  if ($(this).hasClass("green"))
    backgrounds.push("linear-gradient(#a4d400,  #739e00)");
  if ($(this).hasClass("icon") && $(this).hasClass("add"))
    backgrounds.push("url('../img/icons/add.png')");
  $(this).css("background", backgrounds.join(", "));
});

The solution with :after can have some unwanted side effects in some situations, and you can only have one of it. With this you can have an unlimited amount of backgrounds.


text:
Q: Search Db Code Add-in for Visual Studio After 5 versions of Visual Studio I think I should be able to right mouse click on a Stored Procedure node of a database connection in the Server Explorer window and be able to search (at least) SQL Server code for the occurrence of a string.
I don't want to have to rely on running an Stored Procedure to search SYSCOMMENTS. I want a real a GUI tool that is integrated with Visual Studio.
Does anyone know of one, preferably free?

A: sql search by redgate is free http://www.red-gate.com/products/sql_search/index.htm
Integrates with SSMS

A: I think Redgate's tool mentioned above is your answer. Also, SSMS Tools Pack has a free data search tool that will search Table, View or Database Data .
http://www.ssmstoolspack.com/


text:
Q: VichUploaderBundle : image_name can't be null error I'm using Symfony3.1 and I have just installed VichUploaderBundle.
I have followed the documentation but I get this error means that Field 'image_name' can not be empty (null)
SQLSTATE[23000]: Integrity constraint violation: 1048 Le champ 'image_name' ne peut être vide (null)
Config
vich_uploader:
db_driver: orm
mappings:
    product_image:
        uri_prefix:         /images/actualites
        upload_destination: kernel.root_dir/../web/images/actualites

        inject_on_load:     false
        delete_on_update:   true
        delete_on_remove:   true

the entity
/**
 *
 * @Vich\UploadableField(mapping="actualite_image", fileNameProperty="imageName")
 *
 * @var File
 */
private $imageFile;

/**
 * @ORM\Column(type="string", length=255)
 *
 * @var string
 */
private $imageName;

/**
 * @ORM\Column(type="datetime")
 *
 * @var \DateTime
 */
private $updatedAt;

/**
 * @param File|\Symfony\Component\HttpFoundation\File\UploadedFile $image
 *
 * @return Actualite
 */

public function setImageFile(File $image = null)
{
    $this->imageFile = $image;

    if ($image) {
        // It is required that at least one field changes if you are using doctrine
        // otherwise the event listeners won't be called and the file is lost
        $this->updatedAt = new \DateTime('now');
    }

    return $this;
}

/**
 * @return File
 */
public function getImageFile()
{
    return $this->imageFile;
}

/**
 * @param string $imageName
 *
 * @return Actualite
 */
public function setImageName($imageName)
{
    $this->imageName = $imageName;

    return $this;
}

/**
 * @return string
 */
public function getImageName()
{
    return $this->imageName;
}

FormType:
->add('imageFile', FileType::class)

twig
<form class="form-horizontal" method="post" enctype="multipart/form-data">
 //...
 {{ form_widget(form.imageFile) }}

Action
public function creerAction(Request $request)
{
    $entity = new Actualite();
    $form = $this->createForm(BaseType::class, $entity);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($entity);
        $em->flush();

        return $this->redirectToRoute('backend_actualite_liste');
    }

    return $this->render('Backend/Actualite/creer.html.twig',array(
            'form' => $form->createView(),
        )
    );
}

A: Solved
The error is that the upload mapping name in the config and the mapping name in the entity are different but they must be the same.
In the config file is product_image and in the entity is actualite_image.
Now I give them the same name and it works good now.

A: So, actually according to what hous stated, this is the change required to the app/config/config.yml file:
vich_uploader:
    db_driver: orm
    mappings:
        actualite_image:
            uri_prefix:         /images/actualites
            upload_destination: kernel.root_dir/../web/images/actualites

Note to hous: You don't need those last 3 options in the config.yml file, since they are the default

A: Just as a note, there is different Symfony3 setup here, which might be helpful.
I think for your setup, it's different for Symfony3.
Try this:
->add('imageFile', VichImageType::class, array(
    'required'      => false,
))

Also, you need this change too:
# app/config/config.yml
twig:
    form_themes:
        # other form themes
        - 'VichUploaderBundle:Form:fields.html.twig'


text:
Q: How to submit a select menu without a submit button in a loop? I have a code that submits a form when an option in a select box is clicked, but my problem is when I put it inside a loop, it doesn't work. Can you help me with it?
Here's the code:
<?php
  $y1=5;
  for($x1=1; $x1<=$y1; $x1++){
?>
    <form name="myform[]" action="test.php" id ="myform" method="post">
      <select id="sel_id" name="sel_name[]"  onchange="submitform();">
      <?php
        $y=5;
        for($x=1; $x<=$y; $x++){
      ?>
          <option value="<?php echo $x;?>"><?php echo $x;?></option>
      <?php
        }
      ?>
      </select>
    </form>

    <script type="text/javascript">
      function submitform()
      {
        document.myform.submit();
      }
    </script>

<?php
  }
?>

Now, I want every value of it be printed:
<?php
  echo $_POST['sel_name'];
?>

A: Just use this inside your function submitform() :
document.getElementById("myform").submit();

EDIT : I didnt notice your for loop
You are using form in for loop, so you need separate id for each form.
So try this :
<?php
$y1=5;
for($x1=1; $x1<=$y1; $x1++){
?>
<form name="myform[]" action="test.php" id ="myform<?php echo $x1;?>" method="post">
<select id="sel_id<?php echo $x1;?>" name="sel_name[]"  onchange="submitform(<?php echo $x1;?>);">
<?php
$y=5;
for($x=1; $x<=$y; $x++){
?>
<option value="<?php echo $x;?>"><?php echo $x;?></option>
<?php
}
?>
</select>
</form>
<?php } ?>

And outside of your for loop write your JS function :
function submitform(id)
{
document.getElementById("myform"+id).submit();
}

A: You are using multiple form with same id="myform". this should be unique for every form.
Example:
<?php
$y1=5;
For($x1=1; $x1<=$y1; $x1++){
?>
<form name="myform[]" action="test.php" id ="myform_<?=$x1?>" method="post">
<select id="sel_id" name="sel_name[]"  onchange="submitform(<?=$x1?>);">
<?php
$y=5;
For($x=1; $x<=$y; $x++){
?>
<option value="<?php echo $x;?>"><?php echo $x;?></option>
<?php
}
?>
</select>
</form>
<?php
}
?>

Your Java Script:
<script type="text/javascript">
function submitform(id)
{
    document.getElementById("myform_"+id).submit();
}
</script>

Your test.php:
<?php
if(isset($_POST['sel_name']))
    print_r($_POST['sel_name']);
?>

I am using different form ids as myform_<?=$x1?> and also using this id into submitform() function.
As per @Mr.Engineer, no need to use java script function submitform() inside the for() when you are using the unique IDs for form submission.

A: Please try below code for submit form using selectbox.
<select id="sel_id" name="sel_name[]" onchange="this.form.submit()">
    ...
</select>

A: Try to this may be it's help for you
$(field).closest("form").submit();

For example, to handle the onchange event, you would have this:
$(select your fields here).change(function() {
    $(this).closest("form").submit();
});


text:
Q: Killing Apache spark job from web UI is not killing its python subprocess pyspark code written to call another python job using subprocess.Popen(command)
Tried to kill Sparkcontext manually from spark master web UI http://localhost:8080 and it killed successfully
by the time python subprocess triggered and running in worker node as a python process.
Using Redhatlinux
How to kill python subprocess if I kill pyspark sparkcontext?

A: In general it's quite hard to kill a subprocess reliably because the subprocess can be executing uninterruptible code when you want to kill it. That being said, it sounds like a "best effort" approach might be appropriate for your case. You'll want to create and wait on your subprocess in a way allows you to clean up if the process is interrupted. The easiest way to do this is to put your subprocess in a try/finally block.
try:
    print("starting subprocess")
    x = subprocess.Popen(["sleep", "100000"])
    x.wait()
finally:
    print("stopping subprocess")
    x.terminate()

I believe spark sends an interrupt signal

A: Below code works for me
from subprocess import Popen, PIPE, CalledProcessError
from contextlib import contextmanager
from pyspark import SparkContext
from pyspark import SparkConf
import sys, os, subprocess, signal, time

@contextmanager
def spark_manager():
    conf = SparkConf().setAppName("TEST-SPARK")
    conf.set("spark.scheduler.mode", "FAIR")
    sc = SparkContext(conf=conf)

    try:
        yield sc
    finally:
        sc.stop()

with spark_manager() as context:
    process = subprocess.Popen(['python3', 'test.py'], shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

    # Poll process for new output until finished
    while True:
        if context._jsc.sc().isStopped():
            print(process.pid)
            time.sleep(1.0)
            os.kill(process.pid, signal.SIGKILL)
            break
        nextline = process.stdout.readline()
        if nextline == '' and process.poll() is not None:
            break
        sys.stdout.write(nextline)
        sys.stdout.flush()

    output = process.communicate()[0]
    exitCode = process.returncode

    if (exitCode == 0):
        print(output)
    else:
        raise ProcessException(command, exitCode, output)


text:
Q: Instagram Subscription Callback using AWS API Gateway - Invalid SSL certificate We're trying to set up an instagram app and have worked our way through the process. We've now got stuck when trying to create a subscription.
We have our app hosted on AWS API Gateway, which can only be deployed with HTTPS endpoints (it does not support unencrypted connections).
When we do the POST to get instagram to subscribe to a user using the following:
curl -F 'client_id=CLIENT-ID' \
     -F 'client_secret=CLIENT-SECRET' \
     -F 'object=user' \
     -F 'aspect=media' \
     -F 'verify_token=myVerifyToken' \
     -F 'callback_url=https://YOUR-CALLBACK/URL' \
     https://api.instagram.com/v1/subscriptions/

then we get the following error:
{
    "meta": {
        "error_type": "APISubscriptionError",
        "code": 400,
        "error_message": "Invalid response"
    }
}

This happens whether we use our own HTTPS certificate that we have registered with API Gateway, or whether we use the stock AWS URL (https://xxxx.execute-api.us-east-1.amazonaws.com) as the callback (which also has a valid HTTPS certificate). I have verified that the certificates are 'good' using SSLLabs (they both get an A result). Our code NEVER gets called (so it's not the return of the hub.challenge parameter that's the problem. Instagram seems to reject the HTTPS certificate when initiating the connection.
Interestingly, if we use the same certificate that we use with AWS API Gateway on a normal machine (EC2 instance) and change the DNS records to point to this server, then it all works as expected and the subscription works.
Has anyone got Instagram Subscriptions working when using AWS API Gateway?

A: We contacted Instagram about this. The version of Python (or their libraries) that Instagram uses does not support SNI which API Gateway uses (http://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-custom-domains.html) so Instagram apps will not work if hosted on API Gateway unfortunately until Instagram upgrades their version of Python.
As Garrett points out below, whilst Instagram cannot post directly to API Gateway, you can put a cloudfront distribution in front of your API Gateway endpoints and let Instagram point to that. This will work.

A: I came across this post and felt deceived by the current answer given that API gateway can still be used despite instagram's api not accepting the SNI.
"Instagram apps will not work if hosted on API Gateway unfortunately until Instagram upgrades their version of Python." is not true.
All you need to do is put a CloudFront instance in front of the api gateway and it will work fine without needing an expensive SSL cert or anything.
I included screenshots of my config so that it may help someone in the future.
Here is the first configuration screenshot
Behavior Settings
Origin Settings

A: To verify if this is a API Gateway issue have you tried to issue the same challenge request that Instagram is making to your API endpoint directly ?
If you haven't already, you should also try to enable CloudWatch logging on your API stage to debug the call.


text:
Q: Headless selenium chromium/chrome downloads dont's run/save I'm using a script to download some PDF files to a folder on my computer. The script works perfectly, however, when this same script is run with the argument ("--headless") of chrome active, the files are no longer saved as usual.
I can't understand what this "headless" property is doing to prevent files from being saved.
Below is the code being used:
(No error is displayed when running the script.)
######### looping if ctrl+p
print("Setando configurações...")
settings = {
    "recentDestinations": [{
            "id": "Save as PDF",
            "origin": "local",
            "account": "",
        }],
        "isLandscapeEnabled": True,
        "selectedDestinationId": "Save as PDF",
        "version": 2,
    }
prefs = {
    "printing.print_preview_sticky_settings.appState": json.dumps(settings),
    "profile.default_content_settings.popups" : 0,
    "savefile.default_directory": r'/home/file_name/directory_downloads/pdfs',# Para salvar com o 'headless' inativo
    "download.default_directory": r'/home/file_name/directory_downloads/pdfs', # Para salvar com o 'headless' ativo
    "download.prompt_for_download": False,
    "download.directory_upgrade": True,
    "safebrowsing.enabled": True
    }

chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option('prefs', prefs)
chrome_options.add_argument('--kiosk-printing')
chrome_options.add_argument('--headless') # Se ativo, salva os arquivos em um diretório desconhecido ou sobrepões arquivos salvos

print('Abrindo navegador...')
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get(dashObject.url)
driver.maximize_window()

print('Pausa para carregar o conteúdo da página')
sleep(7)
texto_xpath2 = driver.find_element_by_xpath('//*[@id="embedWrapperID"]/div[2]/logo-bar/div/div/div/logo-bar-navigation/span/a/span/span[3]').text
int_num_page2 = int(texto_navegacao_xpath2)

print('Preparando os arquivos PDFs...')
int_num_page = 1
while int_num_page <= int_num_page2:
    numero_pagina1 = str(int_num_page)

    driver.execute_script('window.print();')
    print(f'PDF da pagina {int_num_page} de {int_num_page2} OK')

    print('Proxima pagina...')
    xpath_next = '//*[@id="embedWrapperID"]/div[2]/logo-bar/div/div/div/logo-bar-navigation/span/button[2]'
    driver.find_element_by_xpath(xpath_next).click()
    sleep(3)

    print("Mudando nome do arquivo...")
    pasta_download = pasta_pdfs + '/'
    arquivo_pdf = max([pasta_download + f for f in os.listdir(pasta_download)],key=os.path.getctime)
    shutil.move(arquivo_pdf,os.path.join(pasta_download,r"file_name"+ numero_pagina1 + dashUUID + ".pdf"))

    int_num_page += 1

print('Fechando navegador...')
driver.quit()

A: I ran into the same issue recently with a download that worked in the regular mode and then stopped working in a headless mode.
The issue on my part was that, on regular mode, clicking on the download button opened a second tab on the browser (chrome), which usually (on regular mode) automatically closed after few seconds once the file was downloaded. The consequence of that behavior was that the active window briefly swiched from the first tab (the targetted webdriver) to the second opened tab (the downloading tab), then back to the first tab.
So on headless mode, the issue was that that second tab opened, BUT for some reason, didn't automatically closed when the download was over. So the active window (webdriver) remained the second tab. Because of that, it was unable to carry on the rest of the code (which is supposed to apply to the first tab).
Accordingly, for the headless mode to work, I had to expressly close the second tab and switch to the first tab in order for my code to carry on. Below an extract of that code :
while len(driver.window_handles) > 1: # if there are more than 1 tab
    time.sleep(5) # wait for download to finish or add a function that ensure the file is downloaded
    driver.switch_to.window(driver.window_handles[1])
    driver.close()
    driver.switch_to.window(driver.window_handles[0])


text:
Q: Partition a FetchedRC (custom order of cells) I currently have a Note and Tag Relationship which I am trying to sort a tableView by. I am wanting to use a FetchedRC like my other tableViews but am unsure how I would continue using it and have the correct sorting. I am trying to sort by if the Note contains the Tag as a relationship. How can I use a FetchedRC and get this result? This is my current working code that bypasses the FetchedRC and makes its own customOrder Tag array, I just need it somehow to be sorting on the FetchedRC because I would like the built in updating:
private func fetch() {
    let request = Tag.fetchRequest() as NSFetchRequest<Tag>
    let primarySortDescriptor = NSSortDescriptor(keyPath: \Tag.notes, ascending: true)
    request.sortDescriptors = [primarySortDescriptor]
    do {
        var fetch = try context.fetch(request)
        fetch.partition(by: { !($0.notes?.contains(self.note!))! })
        self.customOrder = fetch
    }
}


text:
Q: Why is the last character getting removed after applying tranwrd function I want to replace certain values in my json file (in this example null values with empty quotation marks.) My solution is working correctly but, for some mysterious reason, the last character of the json file is deleted. Regardless of the last character, the code always deletes it - I have also tried with a different json file that ends in curly braces.
What is causing this and more importantly how can I prevent this?
data testdata_;
input var1 var2 var3;
format _all_ commax10.1;
datalines;
 3.1582 0.3 1.8
 21 . .
 1.2 4.5 6.4
;
proc json out = 'G:\test.json' pretty fmtnumeric nosastags keys;
export testdata_;
run;

data _null_;
  infile 'G:\test.json';
  file 'G:\test.json';
  input;
  _infile_ = tranwrd(_infile_,'null','""');
  put _infile_ ;
run;

To see how the contents change, first run the code until "data null" statement and check the file content, then run the last statement.

A: Data _null_ has it correct; don't write to the same file. SAS offers this option, but in the modern day it's almost always the wrong answer, due to how SAS supports this and the fact that storage is sufficiently cheap and fast.
In this case, it looks like it's a relatively easy fix, but you probably should do as suggested and write to a new file anyway - there will be other issues.
data testdata_;
input var1 var2 var3;
format _all_ commax10.1;
datalines;
 3.1582 0.3 1.8
 21 . .
 1.2 4.5 6.4
;
proc json out = 'H:\temp\test.json' pretty fmtnumeric nosastags keys;
export testdata_;
run;

data _null_;
  infile 'H:\temp\test.json' end=eof;
  file 'H:\temp\test.json';
  input @;
  putlog _infile_;
  _infile_ = tranwrd(_infile_,'null','""  ');

  len = length(_infile_);
  put _infile_ ;
  if eof then put _infile_;
run;

There's two changes. One, I use '""  ' instead of '""' in the tranwrd; that's because otherwise you end up with slightly odd results with new lines being added.  If your JSON parser doesn't like ""  ,, then you may want to instead have two tranwrd, one for null, and one for null, or something similar (or use a regular expression).  But what's important is the number of characters needs to match in the input and the output.  If you can't handle that (like the extra spaces are problematic) then you're left with "write a new file".
Two, I look for the end of the file, then intentionally write out a second line there.  That avoids the issue you're having with the bracket, as it avoids having the EOF being written out before the bracket.  I'm not 100% sure I know why you need that - but you do.
Another option, which might make more sense, is to only write the lines that have the bracket.
data _null_;
  infile 'H:\temp\test.json' sharebuffers;
  file 'H:\temp\test.json';
  input @;
  putlog _infile_;
  if find(_infile_,'null') then do;
    _infile_ = tranwrd(_infile_,'null','"" ');
    put _infile_;
  end;
run;

I added sharebuffers because that should make it run a bit faster.  Note that I also remove one space - something weird about how SAS does this seems to otherwise remove a space from the following line otherwise.  No idea why, probably something weird with EOL characters.
But again - don't do any of this unless there's no other option.  Write a new file.

A: One strange thing is that the PROC JSON always writes a text file that uses LF as the end of line characters.
So you might be able to get your overwriting of the file to work if add these caveats:

*

*Use TERMSTR=LF on the INFILE statement.

*Use SHAREDBUFFERS on the INFILE statement.

*Replace the string with the same number of bytes with the TRANWRD() function and not put a space as the last character on the line.

I would also search for ': null' instead of just 'null' to reduce risk of replacing those characters in some other string in the file.
data _null_;
  infile json SHAREBUFFERS termstr=lf ;
  file json ;
  input ;
  _infile_ = tranwrd(_infile_,': null',':   ""');
  put _infile_;
run;


text:
Q: one explicit Intent for a list of activities A implicit intent will present a list of Apps to the user when several apps meets the action. The user then chooses an this app is launched.
However, if you have a list of packagenames (or/and classname) is the same possible for explicit intent? Something like (does not work this way, but this is what I want):
Intent i = new Intent().setClassName(ListofPackagenames, ListofClassnames)
startActivity(i);

With ListofPackagenames a (Array)List of packagenames and ListofClassnames an (Array)List of classnames.
With startActivity, a dialog should be presented much like when you want to start an implicit intent.
If this is not possible, ofcourse I can make a costum dialog.
Is there then a way, only from the packagename or classname, to get appicon?

A: You can use PackageManager to get the launch activity and create a chooser intent with EXTRA_INITIAL_INTENTS.
Something like:
List<String> listofPackageNames=....
List<Intent> intentList=new ArrayList<Intent>();
PackageManager pm = getPackageManager();
for(String packageName:listofPackageNames){
    intentList.add(pm.getLaunchIntentForPackage(packageName));
}
Intent[] intents=new Intent[intentList.size()];
intents=intentList.toArray(intents);
Intent chooser=Intent.createChooser(intents[0],"Choose ...");
chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS,Arrays.copyOfRange(intents,1,intents.length));
startActivity(chooser);


text:
Q: MySQL does not roll back after delete transaction fails I'm using such construction:
mysql_query('BEGIN') or die('BEGIN transaction failed!');
$query = "DELETE FROM transaction";

try {
    $result = mysql_query($query);

    if (!$result) {
        throw new Exception('Db error', 1);
    }

    $query = "  INS ERT INTO transaction
                SELECT ....."; // just buggy request
    $result = mysql_query($query);

    if (!$result) {
        throw new Exception('Db error', 1);
    }

    mysql_query('COMMIT') or die('COMMIT transaction failed!');
} catch (Exception $e) {
    mysql_query('ROLLBACK') or die('ROLLBACK transaction failed!');

}

but for some reason, the "delete" transaction does not roll back and the table stays empty.
Did I miss anything?

A:
MySQL Server (version 3.23-max and all versions 4.0 and above)
  supports transactions with the InnoDB and BDB

Please change the table engine to innoDB in order to support Transactions
here is how you can go to change engine
ALTER TABLE table_name ENGINE = InnoDB;


text:
Q: ChrUbuntu (Acer): How to load kernel 3.8.0-16 instead 3.4.0? I have Acer C7 Chromebook with Intel CPU, and I had installed there ChrUbuntu. I had updated (Chr)Ubuntu to 13.04 daily version using dist-upgrade. But I found that I still use google v.3.4.0 linux kernel, not Canonical v.3.8.0.
So how I can change kernel?
I found how to do it on normal computers with GRUB, but it is Chromebook, so there is NO Grub.

A: I don't think you can switch. The Chrubuntu maintainer hasn't really been packaging things. I think it's because the chromebook's bootloader looks for the kernel in a different partition, so I suspect the kernel is directly written (with dd?) to a raw partition that the bootloader (BIOS) knows to look for. I don't think this is insurmountable, but there's no current easy way to do it.

A: I'm not sure how this works out on older models but chrx.org and newer versions of ChrUbuntu are able to use stock distribution or custom kernels on newer Chromebooks¹.
Quote from the ChrUbuntu project blog:

Since I started ChrUbuntu back in December of 2010, it's always been necessary to utilize the Chrome OS Linux kernel with Ubuntu in order to solve some compatibility issues with the Chromebook architecture. That's changed with the Chromebook Pixel and the newer Haswell-based Chromebooks like the Acer C720 and HP Chromebook 14. Each of these models supports booting from a more traditional PC BIOS mode which makes it simple to use stock Ubuntu kernels on them.

*

*Except very old models with Intel Pineview (1, 2). Sandy/Ivy Bridge models like the Acer C7/PARROT are supported.


text:
Q: After fixing open menu on mouseover in bootstrap3.0, when we click on menuitem the menu is not closing it remain opened I have set up a navbar with some dropdown menus in it (using class="dropdown-toggle" data-toggle="dropdown"), and it works fine.
The thing is it works onClick, while I would prefer if it worked onHover.
Is there any built-in way to do this?
I tried this
.dropdown:hover .dropdown-menu
{
   display: block;
}

this works fine menu will open on mouse over, but problem is when we click on any menu item it will not close menu will be kept opened, menu should be closed after we click on any menu item.

A: Answer from this question, maybe a possible duplicate
CSS:
.sidebar-nav {
    padding: 9px 0;
}

.dropdown-menu .sub-menu {
    left: 100%;
    position: absolute;
    top: 0;
    visibility: hidden;
    margin-top: -1px;
}

.dropdown-menu li:hover .sub-menu {
    visibility: visible;
}

.dropdown:hover .dropdown-menu {
    display: block;
}

.nav-tabs .dropdown-menu, .nav-pills .dropdown-menu, .navbar .dropdown-menu {
    margin-top: 0;
}

.navbar .sub-menu:before {
    border-bottom: 7px solid transparent;
    border-left: none;
    border-right: 7px solid rgba(0, 0, 0, 0.2);
    border-top: 7px solid transparent;
    left: -7px;
    top: 10px;
}
.navbar .sub-menu:after {
    border-top: 6px solid transparent;
    border-left: none;
    border-right: 6px solid #fff;
    border-bottom: 6px solid transparent;
    left: 10px;
    top: 11px;
    left: -6px;
}

Demo
OR
Simply use this plugin Bootstrap: Dropdown on Hover Plugin


text:
Q: Tool for comparing two databases and creating ALTER scripts to sync them I have two IBM DB2 databases A and B with different database schemas. Database A schema is older, and database B schema is newer. I would neet to create SQL alter scripts that can update A schema to match that of B schema. This can ofcourse be done manually, but is there a tool that could analyse the two databases and do this for me?
I am using the free IBM Data Studio client for querying the database. Can the above operation be done using this tool?

A: Redgate sql compare is one of tge bests.


text:
Q: Ember js table component I made a very simple table component. It takes a model, and builds a table from it.
http://emberjs.jsbin.com/raqomebeqi/1
Since its very primitive and has hard-coded property names, I decided to make an in-component representation of the model, to sort, filter the content of the table. It also allows to show just certain columns from the bounded model. (columns property)
http://emberjs.jsbin.com/raqomebeqi/2
The problem: It doesn't react to the changes of the model anymore. In the first example If I hit the 'change' button, it takes the first record, and set a new name. One can see the change in the table. In the second case Ember inspector shows the change of the name, but the table shows the old value.
I know I could do
data: Ember.computed('model.@each.name', function(){
  //...
})

to monitor the changes on the name, but it is not very dynamic. How could I make my data react to each and every change on the model?

A: If you want your data to react on every change, you could do:
data: Ember.computed('model', function(){
    //...
})

UPDATE:
This is not working


text:
Q: How to avoid Mayavi pipeline pollution? Below is some minimal code that fully demonstrates what I call "pipeline pollution". Each time you press the 'Draw' button, the MayaviScene editor (accessed via the top-left button on the figure) will update the figure, but also create a new scene's "shell" that lingers in the pipeline (as seen in the attached image).
I'm worried that in my more complex project, this pileup will have adverse effects.
Can someone please guide me on how to best set up this Mayavi scene to simply be updated without excess accumulation? I've read through tons of online materials, but still don't understand the developer's logic.

import sys, os
import numpy as np

from pyface.qt import QtGui, QtCore
os.environ['ETS_TOOLKIT'] = 'qt4'

from traits.api import HasTraits,Instance,on_trait_change
from traitsui.api import View,Item
from mayavi import mlab
from mayavi.core.ui.api import MayaviScene, MlabSceneModel, SceneEditor

class Mayavi_Scene(HasTraits):
    scene = Instance(MlabSceneModel, ())

    def update_scene(self):
        Mayavi_Scene.fig1 = mlab.figure(1, bgcolor=(.5,.5,.5))
        self.scene.mlab.clf(figure=Mayavi_Scene.fig1)

        splot = mlab.points3d(P1.x, P1.y, P1.z,
                              scale_factor=0.05, figure=Mayavi_Scene.fig1)

    view = View(Item('scene', editor = SceneEditor(scene_class=MayaviScene),
                    height=300, width=300, show_label=False),
                resizable=True,
                )

class P1(QtGui.QWidget):
    # data starts out empty, wait for user input (below, via 'draw()'):
    x = []
    y = []
    z = []

    def __init__(self, parent=None):
        super(P1, self).__init__(parent)
        layout = QtGui.QGridLayout(self)
        layout.setContentsMargins(20,20,20,20)
        layout.setSpacing(10)

        self.viz1 = Mayavi_Scene()
        self.ui1 = self.viz1.edit_traits(parent=self, kind='subpanel').control
        layout.addWidget(self.ui1, 0, 0, 1, 1)

        def draw(): #a sample user input, could have been a custom data file, etc.
            P1.x = np.random.random((100,))
            P1.y = np.random.random((100,))
            P1.z = np.random.random((100,))
            Mayavi_Scene().update_scene()
            #repeated presses pollute MayaviScene pipeline

        # button to draw data:
        self.btn1 = QtGui.QPushButton('Draw',self)
        self.connect(self.btn1, QtCore.SIGNAL('clicked()'), draw)
        layout.addWidget(self.btn1, 1, 0, 1, 1)
        self.btn1.show()

class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.window = P1(self)
        self.setCentralWidget(self.window)
        self.show()

if __name__ == '__main__':
    app = QtGui.QApplication.instance()
    w = MainWindow()
    sys.exit(app.exec_())

A: The cause is likely the line containing Mayavi_Scene().update_scene() in the draw internal function. Every time draw is called, it creates a new Mayavi_Scene. The following P1 class instead defines draw as a method that accesses self.viz1 directly. I've also replaced the reference to draw with a reference to self.draw
class P1(QtGui.QWidget):
    # data starts out empty, wait for user input (below, via 'draw()'):
    x = []
    y = []
    z = []

    def __init__(self, parent=None):
        super(P1, self).__init__(parent)
        layout = QtGui.QGridLayout(self)
        layout.setContentsMargins(20,20,20,20)
        layout.setSpacing(10)

        self.viz1 = Mayavi_Scene()
        self.ui1 = self.viz1.edit_traits(parent=self, kind='subpanel').control
        layout.addWidget(self.ui1, 0, 0, 1, 1)

        # button to draw data:
        self.btn1 = QtGui.QPushButton('Draw',self)
        # Connect the widget's draw method and the button
        self.connect(self.btn1, QtCore.SIGNAL('clicked()'), self.draw)
        layout.addWidget(self.btn1, 1, 0, 1, 1)
        self.btn1.show()

    def draw(self): #a sample user input, could have been a custom data file, etc.
        P1.x = np.random.random((100,))
        P1.y = np.random.random((100,))
        P1.z = np.random.random((100,))
        # Update the current scene without creating a new one.
        self.viz1.update_scene()


text:
Q: Cannot connect to Jupyter Notebook localhost I have been struggling with this problem the last few days. I am running Manjaro Linux on my laptop and I have recently installed Jupyter Notebook and Jupyterlab using pip.
However, when I try to run it, I get the following output:
[I 2021-05-20 16:21:19.980 LabApp] JupyterLab extension loaded from /usr/lib/python3.9/site-packages/jupyterlab
[I 2021-05-20 16:21:19.980 LabApp] JupyterLab application directory is /usr/share/jupyter/lab
[I 16:21:20.005 NotebookApp] Serving notebooks from local directory: /home/veducha
[I 16:21:20.005 NotebookApp] Jupyter Notebook 6.4.0 is running at:
[I 16:21:20.005 NotebookApp] http://localhost:8888/?token=ffd911982ac39542bc13b182354204b7caec5b86dc5ffad4
[I 16:21:20.005 NotebookApp]  or http://127.0.0.1:8888/?token=ffd911982ac39542bc13b182354204b7caec5b86dc5ffad4
[I 16:21:20.005 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
[C 16:21:20.056 NotebookApp]

To access the notebook, open this file in a browser:
    file:///home/veducha/.local/share/jupyter/runtime/nbserver-72176-open.html
Or copy and paste one of these URLs:
    http://localhost:8888/?token=ffd911982ac39542bc13b182354204b7caec5b86dc5ffad4
 or http://127.0.0.1:8888/?token=ffd911982ac39542bc13b182354204b7caec5b86dc5ffad4

followed by a tab opening on my browser saying that it is unable to connect to the localhost.
I have tried different using browsers, and some of the answers given in other posts (downgrading tornado, for example) do not seem to work since now you're required to have the latest version of tornado.
Can anyone please help me?
Thanks,
E.


text:
Q: Drawing overlay view on top of a web view I am trying to make an app that can annotate PDFs.
What I have done, is add the PDF through a UIWebview, so my main UIViewControllerhas a UIWebView Delegate.
What I am trying to do is put my drawing layer, which is a UIView over the top of my PDF view.
I have tried setting the background colour to "clearColour" and the opaque property to no, I still get a weird affect.
I think the issue might be because of drawing a bitmap onto the UIView, but I would still like some insight, or an example if one exists.
Thanks.
This is an image of the problem, the little white band at the top is the PDF, the white box is the UIView which I am drawing on.
The code I used for the "drawing code" is here, see "SmoothedBIView"
http://mobile.tutsplus.com/tutorials/iphone/ios-sdk_freehand-drawing/

A: Sorry, just noticed you had two questions. Again maybe this project can help you.


text:
Q: SQL Server :Dynamic SQL with Pivot on the basis of maximum count I have this SQL Server query:
SELECT [VendorID], [QuotedAmount]
FROM [tbl_Vendor_Quotation]
WHERE [ProductID] = 1
ORDER BY vendorID

This query returns data like this:
VendorID     QuotedAmount
-------------------------
   1            1000000
   1             900000
   1             750000
   1             720000
   1             650000
   2            1250000
   2            1200000
   3            1500000
   4            1000000
   4             970000
   4             950000
   5            1450000
   6            1450000
   8            1200000

I want to pivot this such a way that it will come up as per the below table
 VendorId        R0       R1        R2       R3        R4
 ----------------------------------------------------------
    1         1000000    900000   750000   720000    650000
    2         1250000   1200000
    3         1500000
    4         1000000    970000   950000
    5         1450000
    6         1450000
    8         1200000

R0, R1---Rn Shows Maximum times VendorID Repeated with QuotedAmount.In this case R0,R1 ---R4(5 times) as VendorID 1 is maximum time repeated 5 times.
I followed a lot of example to make it but didn't get successes. Please help me.

A: You have to Rank them first with row_number window function:
 select VendorId, [1] as R0,[2] as R1,[3] as R2,[4] as R3,[5] as R4
   from (
        select VendorId, QuotedAmount,
               ROW_NUMBER () over (partition By VendorId order by QuotedAmount desc) as rn
         from tbl_Vendor_Quotation
        WHERE [ProductID] = 1) t1
  PIVOT
  (
    max(QuotedAmount)
    for rn in ([1],[2],[3],[4],[5])) As PivotTable

A: Dynamic SQL + pivoting:
DECLARE @cols nvarchar(max),
        @sql nvarchar(max)

SELECT @cols = (
    SELECT DISTINCT ',[R'+  CAST(ROW_NUMBER() OVER (PARTITION BY VendorID ORDER BY (SELECT NULL)) - 1 as nvarchar(10)) +']'
    FROM tbl_Vendor_Quotation
    FOR XML PATH('')
    )

SELECT @sql = N'
SELECT *
FROM (
    SELECT  VendorID,
            QuotedAmount,
            ''R''+  CAST(ROW_NUMBER() OVER (PARTITION BY VendorID ORDER BY (SELECT NULL)) - 1 as nvarchar(10)) as Cols
    FROM tbl_Vendor_Quotation
    WHERE [ProductID] = 1
    ) as p
PIVOT (
    MAX(QuotedAmount) FOR Cols IN ('+STUFF(@cols,1,1,'')+')
) as pvt'

EXEC sp_executesql @sql

Output:
VendorID    R0      R1      R2      R3      R4
1           1000000 900000  750000  720000  650000
2           1250000 1200000 NULL    NULL    NULL
3           1500000 NULL    NULL    NULL    NULL
4           1000000 970000  950000  NULL    NULL
5           1450000 NULL    NULL    NULL    NULL
6           1450000 NULL    NULL    NULL    NULL
8           1200000 NULL    NULL    NULL    NULL

The Rn number will grow dynamically in case when row number for vendor will grow.

A: Thanks @vercelli
I got my answer with this query with your help.
Declare @ProdID int
set @ProdID=1
DECLARE @columnName VARCHAR(1000)
DECLARE @columnVal VARCHAR(1000)
DECLARE @Query VARCHAR(1000)

 --Create dynamic column name
 SELECT @columnName =COALESCE(@columnName + ', ','')+'['+cast(rn as varchar(10))+'] AS [R'+cast(rn as varchar(10))+']',
  @columnVal =COALESCE(@columnVal + ',','')+'['+cast(rn as varchar(10))+']' FROM
 ( select distinct
               ROW_NUMBER () over (partition By VendorId order by QuotedAmount desc) as rn
         from tbl_Vendor_Quotation where [ProductRequestID]=@ProdID  ) a

     print  @columnName    print  @columnVal

  set @Query='select VendorId,'+@columnName+'
   from (
        select VendorId, QuotedAmount,
               ROW_NUMBER () over (partition By VendorId order by QuotedAmount desc) as rn
         from tbl_Vendor_Quotation where [ProductRequestID]='+cast(@ProdID as varchar(10))+') t1
  PIVOT
  (
    max(QuotedAmount)
    for rn in ('+@columnVal+')) As PivotTable'
    exec (@Query)


text:
Q: Way to activate hover when in the vicinity of the element I have a bunch of elements on a page that when hovered show a menu. Because hovering requires to be on the element and if you are right at the border it gets very tricky to activate them iIwas wondering if there is a way to activate the hover menu when the mouse is close to the element, let's say at a tolerance rate of 10 pixels from any border (N,S,E,W).
Tracking the mouse on the page is really not an option, too much processing needed on the client side and the page is already loaded with lots of javascript code.

A: I think wrapping the menu item content with a div / span element and then applying the hover styles to that would work best. And then as Sime said, increase the padding on the menu item.
For example the html would be:

content here

Then the CSS would be something like:
li {
     padding:10px;
}

li:hover span {
      /* Hover style of menu item here */
}


text:
Q: What is way to fetch large json data from url? I am fetching data from url by inputstream and appending it in string buffer like:
rssUrl = new URL(url);
InputStream resultStream = rssUrl.openStream();
byte[] B = new byte[8069];
for (int N; (N = resultStream.read(B)) != -1;)
{
    String str = new String(B, 0, N);
    put.append(str);
}
resultStream.close();

Here in json data image is in string formate which i decode in bitmap. My problem is when above code is running , it is taken long time to fetch.
And I took screen shot where grow heap showing, it there is any other way by which I can fetch data fast.

A: Use async task ,load your data in doInBackground() method, update the ui or the elements in postExecute() method,
try this try this tutorial


text:
Q: how do we plot bar chart in lightningchartjs Is there a way to draw a simple bar chart on x axis and y axis like  . I need a bar chart on x : 0 and height till y: 10 , then x:1 and height till y:5 like that ?
I need to share the x axis with different axis.


text:
Q: Show sub sub menu when mouse is hover i have this code: http://jsfiddle.net/7Zr44/
And i want to show the sub sub menu the mouse hover.
the display:block is not doing nothing

Menu 1

Sub 1.1

Sub 1.2

Sub 1.3

Menu 2

Sub 2.1

Sub Sub 2.1.1

Sub 2.2

Menu 3

Edit: I can't give level 1, 2 etc to the because this menu is being generated by PHP + SQL script.

A: You need to unhide the li tag and show only next level of Ul. like this :  Demo
.tonho li:hover > ul {
    display: block;
}


text:
Q: When and how are system calls interrupted? This is a followup question to Is a successful send() "atomic"?, as I think it actually concerns system calls in general, not just sends on sockets.
Which system calls can be interrupted, and when they are, where is the interruption handled? I've learned about SA_RESTART, but don't exactly understand what is going on.

*

*If I make a system call without SA_RESTART, can the call be interrupted by any kind of interrupts (e.g. user input) that don't concern my application, but require the OS to abort my call and do something else? Or is it only interrupted by signals that directly concern my process (CTRL+C, socket closed, ...)?

*When setting SA_RESTART, what are the semantics of a send() or any other "slow" syscall? Will it always block until all of my data is transmitted or the socket goes down, or can it return with a number smaller than the count in send()'s parameter?

*Where is restarting implemented? Does the OS know that I want the call to be restarted upon any interrupts, or is some signal sent to my process and then handled by library code? Or do I have to do it myself, e.g. wrap the call in a while loop and retry as often as necessary?

A: System calls can be interrupted by any signal, this includes such signals as SIGINT (generated by CTRL-C), SIGHUP, etc.
When SA_RESTART is set, a send() will return (with the sent count) if any data was transmitted before the signal was received, it will return an error EINTR if a send timeout was set (as those can't be restarted), otherwise the send() will be restarted.
System call restarting is implemented in the kernel's signal handling code. The system call internally returns -ERESTARTSYS upon detecting a pending signal (or having a wait interrupted by a signal), which causes the signal handling code to restore the instruction pointer and relevant registers to the state before the call, making the syscall repeat.


text:
Q: Counting characters in Azure Translate and having hybrid pricing tier Regarding the Azure Translator service,

*

*The Frequently Asked Questions page says:

For scripts based on graphic symbols, such as written Chinese and Japanese Kanji, the Translator service counts the number of Unicode code points. One character per symbol. Exception: Unicode surrogate pairs count as two characters.

Am I correct to say that "驚くばかり" would count as 5 characters, even though it's 15 bytes, but the emoji "" would count as 7 characters, because of the surrogate pairs?

*It appears that I can either choose to have "2M free chars" or "pay as I go", but not both: "first 2M chars free, then pay as I go".
However, is it OK/allowed to create two Translate resources, where one would be on the "Free tier", and the other "Pay as you go", and have the application point to the second one when I exceed the 2M free quota?

A: Not sure about emoji because each emoji can be counted as different character counts. But yes, each foreign character will be counted single.
And when it comes to pricing, there isn't any option for hybrid pricing. Therefore, you either choose a free F0 or Pay as you go S1 pricing tier based on your requirement.


text:
Q: Angular routing/navigation not working properly: Appending instead of replacing component This question has been asked before,
but none of the answers seems to help me.
I can't route to different pages on angular, instead, it just appends at the end of my homepage the HTML of the desired component. Here is my code:
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { ToggleFullscreenDirectiveDirective } from './toggle-fullscreen-directive.directive';
import { HttpClientModule } from '@angular/common/http';
import { AnnouncementsComponent } from './announcements/announcements.component';
import { AdminComponent } from './admin/admin.component';
import { RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';

    import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { ToggleFullscreenDirectiveDirective } from './toggle-fullscreen-directive.directive';
import { HttpClientModule } from '@angular/common/http';
import { AnnouncementsComponent } from './announcements/announcements.component';
import { AdminComponent } from './admin/admin.component';
import { RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';

@NgModule({
  declarations: [
    AppComponent,
    ToggleFullscreenDirectiveDirective,
    AnnouncementsComponent,
    AdminComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    RouterModule.forRoot([
      { path: '', component: AppComponent },
      { path: 'admin', component: AdminComponent }

    ])
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }

app.component.html
...My custom html
<router-outlet></router-outlet>

index.html
 <!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Angular Bootstrap Demo</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
  <app-root>Loading...</app-root>
  <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

</body>
</html>

Based on other answers the problem might be with imports,
I tried to remove some that I used on the code, like the toggle fullscreen, another possibility is that there might be a console error which I checked and there is no problem. can anyone help me?
I am lost!
Thanks

A: App.component is rendered and it's the container for all other components. So don't include it in routing,
So what you have to do is copy your code from App.component and add that code to a new component (called home.component)
Then configure routing as follows.
RouterModule.forRoot([
  { path: '', component: HomeComponent},
  { path: 'admin', component: AdminComponent }

])

app.component.html
<router-outlet></router-outlet>

home.component.html
...My custom html

A: Based on your routes, try to change your routerModule to:
RouterModule.forRoot([
      { path: '', redirectTo: '/admin', pathMatch: 'full' },
      { path: 'admin', component: AdminComponent }
    ])

By the way, when you create a forRoot router, Angular looks for a <router-outlet> selector in your bootstrap component from your application (app.component.html usually). There's no need to specify your app.component with forRoot configuration!


text:
Q: plone zodb ERROR CMFUid ASSERT we have a very large Data.fs (~15Gb) - I think this comes trough usage of "Working Copy Support" with custom folderish content types!
If I try to use "portal_historiestorage", the instance quits and shows > XX errors of:
ERROR CMFUid ASSERT: 17 objects have 1642 as uid!!!

How can I clear this objects and shrink my DB?
I already cleared/rebuild "portal_catalog", reference_catalog and uid_catalog
thanks in advance
plone 3.3.6

A: I also had this kind of problem.
In my case it was the cmf_uid index missing in the portal_catalog: so every search was returning all the catalog brains.
So I guess that the problem in the question was related to the fact that multiple objects have been indexed with the same cmf_uid (which is an attribute on the object).
[b.getObject() for b in portal_catalog(cmf_uid='1642')]

should point out the relevant objects.
You should take the objects and verify they have a proper cmf_uid, taking care of possible acquisition problems.


text:
Q: How do I unpack binary files with Perl? I have two binary files equal in size, but not in values. I used unpack as follows, but the results are weird.
When I use "big" binary files, both of the outputs shows part of the results:
One binary file starts good - ends bad,
Second binary file goes wrong at the start.
Where do you think may be the weak point?
open(BIN_FILE1, "<bin_files/BINF1.bin") or die("Cannot open file for writing");
open(BIN_FILE2, "<bin_files/BINF2.bin") or die("Cannot open file for writing");
binmode(BIN_FILE1);
binmode(BIN_FILE2);
# N An unsigned long (32-bit) in "network" (big-endian) order.
my @values_tmp1 =  unpack("N*", <BIN_FILE1>);
my @values_tmp2 =  unpack("N*", <BIN_FILE2>);
close (BIN_FILE1);
close (BIN_FILE2);
my $tmp_bin1 = @values_tmp1;
my $tmp_bin2 = @values_tmp2;
print "\nBIN FILE1 LENGTH: ",$tmp_bin1,"\n";
print "\nBIN FILE2 LENGTH: ",$tmp_bin2,"\n";

The output is:

BIN FILE1 LENGTH: 1203
BIN FILE2 LENGTH: 124

The input files are:
-rw-rw-r-- 1 yodar yodar   9600 2009-12-23 19:59 BINF1.bin
-rw-rw-r-- 1 yodar yodar   9600 2009-12-27 16:38 BINF2.bin

If there is another simple and safe way to gather binary files data to an array I'll be glad to know.

A: You said you had "big" files.  It looks like they aren't all that big, and will fit easily in memory.
However, if your files are too big to fit in memory all at once you can use read or sysread to read data in chunks.
Example - Read in 4000 bytes at a time:
my $file_path = 'bin_files/BINF1.bin';

open my $fh, '<:encoding(raw)', $file_path
    or die "Cannot open file '$file_path' for reading";

my $buffer;
while ( my $got = read( $fh, $buffer, 4000 ) ) {

  warn "Read $got bytes from file\n."

  my @integers = unpack "N*", $buffer;

  do_stuff( \@integers );

  $buffer = '';
}

Use a 3 argument open with lexical handles, it avoids certain security and maintainability issues.  3 arg open also allows you to specify file encoding in the mode flag.  That way you don't need to call binmode.

A: I suspect that you are not reading the entire file (the <> operator tries to read a record, using the record seperator $/ which is newline by default). Try changing the read to something like this:
{
    # Enable slurp mode
    local $/;
    my @values_tmp1 =  unpack("N*", <BIN_FILE1>);
    my @values_tmp2 =  unpack("N*", <BIN_FILE2>);
}


text:
Q: Passing variable between php web page and a background script I am trying to run a php script in the background on windows.
Im looking for a way to pass a variable between them. Basically thats what im trying to accomplish:
php page:
  session_start();
  $_SESSION['abc'] = 1 ;
  $cmd = "c:\wamp\bin\php\php5.5.12\php -f c:\wamp\www\FinalProject\newEmptyPHP.php" ;
  pclose(popen("start /B ".$cmd, 'r'));
  while ( $_SESSION['abc'] == 1)
  {
      sleep(1) ;
  }
  echo 'Done';

background script:
session_start();
$_SESSION['abc'] = 0 ;

Im open to any suggestions.

A: You should execute this passing the var as an argument on the console call:
    session_start();
    $_SESSION['abc'] = 1 ;
    $cmd = "c:\wamp\bin\php\php5.5.12\php -f c:\wamp\www\FinalProject\newEmptyPHP.php " . $_SESSION['abc'] ;
    /** ... */

After that you will be able to get the argument from newEmptyPHP.php using $argv var (http://php.net/manual/en/reserved.variables.argv.php)
I think that you will never get your session updated in that way because:
1) PHP is not listening to external changes in $_SESSION during the execution. If it were possible, the would be a very difficult to maintain and debug. 2) The script in console will not be using the sessions as a session is only accessible by the client that opened it (see http://www.w3schools.com/php/php_sessions.asp)
But... Why do you need to call a PHP script from PHP using popen? It will be very slow. I recommend to build the feature you need to use from  newEmptyPHP.php inside your application.


text:
Q: How does the tolerance influence QgsGraphBuilder and tieing of points? I am developing a script which uses OpenStreetMap data to calculate the distance (over the road network) between each building and the nearest hospital.
To do this, I mainly follow the official tutorial http://www.qgis.org/en/docs/pyqgis_developer_cookbook/network_analysis.html
My problem comes when calling QgsGraphBuilder. Because my buildings obviously don't lie exactly on the road network, I want to specify a tolerance value when creating the builder.
However, with
builder = QgsGraphBuilder(crs, True, 200.0, "WGS84")

it doesn't "snap" my buildings to the network... Is there anything wrong with the way I call the function QgsGraphBuilder? I haven't seen any example which actually implements this tolerance parameter...
EDIT
I actually also tie all my buildings'centroids to the network:
builder = QgsGraphBuilder(crs, True, 200.0, "WGS84")

all_points = [] # A list that will contain the coordinates of all objects to be tied to the network
all_points.append(hospital) # I add the coordinates of the hospital

for building in coord_buildings.values():
    all_points.append(building) # I add the coordinates of all the buildings'centroids

    tiedPoints = director.makeGraph( builder, all_points ) # I tie the buildings'centroids to the graph

    graph = builder.graph() # I build the graph

    startId = graph.findVertex(hospital) # I take the id of the hospital in the graph

    print startId # Displays -1

If I understand correctly, this means that my hospital doesn't match to anything in the network because it hasn't been tied properly... maybe because of the tolerance value?
By the way, my data is in a PostGIS database, unprojected (EPSG 4326), in case it makes any difference
EDIT 2
I just saw that some buildings are actually tied to the network when I use only one parameter
builder = QgsGraphBuilder(crs)

or
builder = QgsGraphBuilder(crs, True, 0.0)

But rougly 1000 are still not tied. So probably really to do with the tolerance factor?
When I specify the other parameters
builder = QgsGraphBuilder(crs, True, 200.0, "WGS84")

the dijkstra process fails (the tree only contains -1 values)

A: This doesn't actually answer the question but it still solved my problem:
What I did was "simply" to snap my points (hospitals) to the road network within PostGIS beforehand. Now that all my points lie exactly on the network, I no longer need to worry about the tolerance.
This is not very elegant though, so if anyone has a "real" solution, I would still be interested to read it! :-)


text:
Q: R run old version from command OSX I've got an application that relies on R for some scientific calculations. It is installed in OS X and R is in its default location (/Library/Frameworks/R.framework).
The application needs to start Rserve (R CMD Rserve).
This runs /usr/local/bin/R (which is a script that does various things) and everything works fine.
However, when the user installs a new version of R, (R CMD Rserve) references to the new R version which has not the required packaged installed and may not work due to compatibility issues.
How can I start Rserve in the correct version of R?
I know that I can change all the symlink that link to the current R version in /Library/Frameworks/R.framework, however, I don't want to change the R version globally. Just my application should use the old version..


text:
Q: Example of infinite game without any Nash equiblibria I have to find an example of a game that does not admit (mixed strategy) Nash equilibria.
Consider a game in normal form. Let $N=\{1,2\}$ be set of players and $S_i=\mathbb{R}$ a set of possible strategies for each player (uncountably many), $i=1,2$.
The rules of this game are as follows: each player chooses one real number (his strategy). Player who chose a bigger number than the other player wins $1$, player who chose smaller number gets $0$. If both players choose the same number, they both get $0$.
Formally, payoff functions of each player one looks like this:
$$v_1(s_1,s_2)=\left\{\begin{matrix} 1 \ \mathrm{if}\ s_1>s_2 \\ 0 \ \mathrm{if}\ s_1\leq s_2 \end{matrix}\right. $$
$$v_2(s_1,s_2)=\left\{\begin{matrix} 1 \ \mathrm{if}\ s_2>s_1 \\ 0 \ \mathrm{if}\ s_2\leq s_1 \end{matrix}\right. $$
Do you think it's a good example?

A: There is none, unless the problem is wrongly planned. By definition, every game has at least one equilibrium in mixed strategies.


text:
Q: What does invoking call method inside another constructor function do? I have two constructor functions here: Car and Van
    var Car = function (location) {
        this.loc = location
    };

    Car.prototype.move = function () {
        this.loc++
    }

    var Van = function (location) {
      Car.call(this, location)
    }

Could you tell me what this line Car.call(this, location) is doing? My assumption is that we want to inherit the loc property from the Car class to the Van class.
My confusion is on what now this inside
    Car.call(this, location)

is referring to? and also what this inside Car
    var Car = function (location) {
        this.loc = location
    };

is referring to? Can someone provide any insight?

A: Car.call(this, location)

this will associate the .loc property to the Van object. this here refers to the Van.
If you instantiate Van, it will associate the same
var v = new Van(1); // v.loc=1


text:
Q: Computation expressions for a Haskell programmer I'm looking to learn F#, but one thing that's confusing to me is the computation expression (do-notation??) syntax and desugaring.
In haskell, you have a very simple Monad typeclass and rules for desugaring do-notation into bind and return. There's no magic involved in adding keywords; the only thing must match up are the types.
In F# there's a bunch of builders, and keywords, and complexity.
Is there a good explanation of how to map one concept to the other?
I basically want to know how I map
do
  x <- monadicComputation
  foo x
  someOtherMonadicComputation
  let y = somePureComputation x
  return $ bar y

to F#.
The only keywords in the haskell are do, (<-) and let.

A: If you come from the Haskell background than you might be interested in an academic article that I wrote about F# computation expressions recently.
It links the computation expression syntax (which is quite flexible) to standard type classes that are used in Haskell. As already mentioned, F# does not easily let you write code generic over monad (it can be done, but it is not idiomatic), but on the other hand it lets you choose the most appropriate syntax and you can even get nice syntax for MonadPlus or for monad transformers.
In addition to the async monad that was mentioned by Lee, here is an example of MonadPlus (using the sequence expression - a list monad - as an example):
let duplicate list = seq {
  for n in list do
    yield n
    yield n ∗ 10 }

Or a computation expression for parsers:
let rec zeroOrMore p = parse {
  return! oneOrMore p
  return [] }

A: The haskell do notation has only one special syntax i.e <- which is mapped to bind function, everything else inside do is just normal function application for which the result is the monad type, for example: return, putStr etc.
Similarly in F# you have let! to represent bind operation and return keyword syntactic sugar (not normal function call like in haskell but this keyword maps to the Return function that you define). Now there are many other keywords that your computation expressions can support (you can omit them easily if not required), they all are documented here. These additional operations sort of give you the syntactic sugar to use F# keywords instead of normal functions that return the monadic value. You can see that all the keyword that you can overload in F# computation expressions have monadic return value.
So basically, you don't need to be worried about all these keywords, just think of them as normal monad returning functions (with a specific type signature that you can find in documentation) that you can call using F# keywords inside the computation expression syntax.

A: You can't write generic monadic code in F#, instead you have to specify the monad you're working in by naming the builder associated with the expression. Your example code would look like:
let example = async {
    let! a = someAsyncComputation
    foo a
    do! someOtherAsyncComputation
    let y = somePureComputation a
    return (bar y)
}

for the async computation expression type. The 'bang' pattern (do!, let! etc.) is used when binding monadic values, while the regular keywords are used for non-monadic values.
let! corresponds to bind (>>=) while let corresponds to let in do notation. return corresponds to return, while return! is used to yield an existing monadic value. do! is similar to (>>) which executes a monadic value for its effects, while do is for non-monadic effects, which has no parallel in Haskell.


text:
Q: Log odds as prior I have this problem: In betting situations one is often interested in odds, referring in the thumbtack tossing $\theta / (1 - \theta)$. Alternatively one may consider the log-odds:
$\lambda=log(\theta/(1-\theta))$
Show that a uniform distribution for $\lambda$ implies the following distribution for $\theta$:
$p(\theta)=\theta^{-1}(1-\theta)^{-1}$
What problems are associated with this distribution if it is used as a prior in the thumbtack tossing problem?
Now I have the thumbtack thingy, I know what it will happen if we use that p as prior, but the uniform for $\lambda$ implies the p($\theta$) I don't get it, I have tried to get to the p($\theta$) from both sides but I always get to $log(\theta)-log(1-\theta)$ and can't get out, any help??

A: $$\frac{d\lambda}{d\theta}=\frac{1}{\theta} + \frac{1}{1-\theta} = \frac{1}{\theta(1-\theta)}$$
$$f(\lambda)\,d\lambda\propto d\lambda \quad \text{(improper uniform; aka Lebesgue measure)}$$
$$g(\theta)\,d\theta =f(\lambda)\,d\lambda=f(\lambda(\theta))\frac{d\lambda}{d\theta}\,d\theta\propto \frac{1}{\theta(1-\theta)}d\theta$$
$$g(\theta)\propto\frac{1}{\theta(1-\theta)} \quad \text{(improper Haldane's prior; see also Jaynes)}$$


text:
Q: How do I change file extension based on the number in a file name in Python I have some files stored in one main directory with .map extensions that are the output of a model. The filenames include the timestep of the model.
For example: P_1_.map, P_2_.map and P_10_.map are the output of the 1st, 2nd and 10th timestep of the model respectively.
The extension of the files has to be changed to a three-digit number that corresponds to the timestep. I need to change the .map extension to .001, .002 and .010.
Finally I would like to change all the filenames to the same name, lets say "Ptest". In the the end the old files should be changed like this:
P_1_.map to  Ptest.001
P_2_.map to  Ptest.002
P_10_.map to Ptest.010
Does someone know how to do this in Python? Any help would be much appreciated :)

A: import os

for name in os.listdir(): # look through the entire directory
    # break up the name so we can work with it
    parts = name.split('_')
    # skip non-matching files
    if len(parts) != 3: continue
    if parts[0] != 'P' or parts[2] != '.map': continue
    # figure out the new name
    newname = "Ptest.%03d" % int(parts[1])
    # do the rename
    os.rename(name, newname)


text:
Q: IndexError: too many indices for array: array is 1-dimensional, but 3 were indexed
I am trying to train binary data. It is working fine with some binary datasets but for my binary file its showing error.

Here is the binary file reading function:

def read_f32_bin(filename, start_idx, channel_first):
    with open(filename, 'rb') as bin_f:
        iq_seq = np.fromfile(bin_f, dtype='f')
        n_samples = iq_seq.shape[0] // 2
        IQ_data = np.zeros((2, n_samples))
        IQ_data[0, :] = iq_seq[range(0, iq_seq.shape[0]-1, 2)]
        IQ_data[1, :] = iq_seq[range(1, iq_seq.shape[0], 2)]

    del iq_seq
    rtn_data = IQ_data[:, start_idx:]
    print(rtn_data.shape)
    if not channel_first:
        rtn_data = rtn_data.T

    return rtn_data

And here is the splitData function:
def splitData(splitRatio, allData, allLabel, splitType='random'):
    if not isinstance(allData, np.ndarray):
        allData = np.array(allData)
        allLabel = np.array(allLabel)

    if splitType == 'random':
        allDataSize = len(allLabel)

        train_ind, val_ind = getSplitIndex(allDataSize, splitRatio)

        trainData, trainLabels = allData[train_ind, :, :], allLabel[train_ind]
        valData, valLabels = allData[val_ind, :, :], allLabel[val_ind]
    elif splitType == 'order':
        allDataSize = len(allLabel)
        train_size = int(allDataSize * splitRatio['train'])
        val_size = int(allDataSize * splitRatio['val'])
        trainData, trainLabels = allData[:train_size, :, :], allLabel[:train_size]
        valData, valLabels = allData[train_size:, :, :], allLabel[train_size:]
    else:
        raise
    return trainData, trainLabels, valData, valLabels

And I am getting the following errors:

in loadData
x_train_pd, y_train_pd, x_test_pd, y_test_pd = utility.splitData(split_ratio, X_data_pd, y_data_pd)
in main
train_x, train_y, test_x, test_y, NUM_CLASS = load_slice_IQ.loadData(dataOpts, split=True)

in splitData
trainData, trainLabels = allData[train_ind, :, :], allLabel[train_ind]
IndexError: too many indices for array: array is 1-dimensional, but 3 were indexed

Can anyone help me to solve the problem?


text:
Q: jqgrid with custom row colors I´m using dynamic data

...

...

...

...

...

...

The rows are mark with id from 1 to 12.
How can i color the row with id=11 and id=12 with maybe red?
This is a scoring board, and the two rows in the bottom marks that they will be sent down to lower premier league.

A: If you will always have a list of 12 teams in this table and want to highlight bottom two only then its easy to do via CSS. Just create a rule like
tr#11{ background-color:#fff100}
same for tr#12
However if you want it to be dynamic and want to have last two rows with relegate ID. Then you need to do following on server side or client side.

*

*Get the length of array that contains teams

*In your Iterator check when it has reached second last item by comparing current position with 2 less than the length

*Give this tr a new class or if you cant replace the class attribute then add a new attribute like relegated="1" or something similar.

*In CSS just use the selector or class to keep the new background-color.

You can also use DOM to navigate to last tr item in table and keep one previous item in a variable as well then use both items and add a style attribute to them with background colour.
There are several ways to achieve this. Depends on how you are getting your grid out and which way you feel comfortable as well as performance overheads.


text:
Q: Iterating over same-name objects of different classes I have multiple Perl objects, all of different classes, say triangle, square and circle. All classes/objects/instances have an equally named method, say render.
How do I loop over them, invoking the same methods in all of them?

A: I don't see a problem:
for my $obj ($triangle, $square, $circle) {
    $obj->render;
}

Or, more shortly
$_->render for $triangle, $square, $circle;


text:
Q: Pass data from Rad Parent Window to Child Window I have a rad window, that user can add few items to the grid [For an Example : Stationary]. Once User need to remove item, I want to popup a rad window which request User Name Password and Redirect to Another page to remove item. Only Some users are allowed to remove items. So my question is how to pass that Grid data from Parent Window to Child window.?  [I am saving grid data on ViewState]

A: Finally I have found a solution for this
http://webapps-in-action.com/post/How-to-use-a-Telerik-RadWindow-(Modal)-with-independent-IFrame-to-load-collect-validate-user-data
Source Code Download


text:
Q: Show that $T: L^2([0, \infty )) \to C_0([0,\infty))$ is compact operator. Let $C_0 \left( [0,\infty) \right)$ be the set of continuous functions on $[0,\infty)$ vanishing at $\infty$, which is Banach space with $\lVert f \rVert_\infty = \underset{t \in [0,\infty)}{\sup} |f(t)|$. Define $T \in B\left(L^2([0,\infty)), C_0 ([0,\infty)) \right)$ by
$$Tf(t) = \frac{1}{1+t} \int_0^t f(s) ds.$$
Show that $T$ is a compact operator.
Hint: To show that $TB_{L^2 [0,\infty)}$ is totally bounded, take sufficiently large $R >0$ such that $\underset{t \ge R}{\sup} |Tf(t)|$ is uniformly small for $f \in B_{L^2[0,\infty)}$, and then apply the Ascoli-Arzela theorem to the restriction of $TB_{L^2[0,\infty)}$ to $[0,R]$. I do not know how to apply this hint.
Edited: I have seen some similar questions in the web, but all of them was on closed intervals. In this case the interval is not bounded, so at first -as I know- I have to prove that $T$ is bounded, which is not realy clear when the interval is not bounded. And After that I need to prove the compactness of the operator, by definition or by theorems, Could you please show me steps (hints) that i can follow.
My proof till now:
First let's show the boundedness of $T$.
$|Tf(t)| \le \frac{1}{1+t} \int_0^t f(s)ds \le \|f\|_2 \frac{t}{1+t}$. So, $\|T\| \le 1$
Is is OK?

A: (Never mind the crossed-out text; based on the hint, you have not learned what it assumes) The easiest approach is to use the "completely continuous" characterization of compactness: if $X$ is reflexive, then $T\in L(X\to Y)$ is compact iff $f_n\rightharpoonup0\Rightarrow Tf_n\to0$.  $L^2$ is reflexive, so you want to show that, if $$\int_0^{\infty}{f_n(x)g(x)}\to0\text{ for all }g\in L^2$$ then $Tf_n\overset{C_0}{\to}0$.  Now expand the definition of $T$ and choose $g$ cleverly.
If you haven't seen that characterization, then you'll need a tool to characterize compact subsets of $C_0$.  In the problems you've seen, the interval was closed (and thus compact) so you could apply Arzelà-Ascoli.  Of course, $C_0$ is not defined on a compact interval. It turns out that for noncompact spaces, one can obtain an analogous result, as long as one has uniform decay at each end.  So here's a simple sufficient condition:Fn. 1

Suppose that

*

*$f_n\to0$ uniformly on any compact set $K\subseteq[0,\infty)$ and

*there is a constant $A$ independent of $n$ such that $|f_n(x)|\leq\frac{A}{\sqrt{x}}$.

Then $\{f_n\}_n$ has a subsequence converging in $C_0$ to $0$.

Using a strengtheningFn. 2 of the boundedness argument you gave in comments, this shows that $T$ sends the unit ball to a sequentially-compact set.
Fn. 1 This is not a standard result, so if this is a homework question, make sure to prove this as a lemma in your solution.  This is where you apply the hint.
Fn. 2 More than just fixing the flaw Andrew McMillan pointed out.

A: You will first need the following which follows from Cauchy Schwartz:
$$\left|\int_x^yf(s)ds\right|=\left|\int_{[x,y]}f(s)1ds\right| \leq ||f||_2||x-y||^{\frac{1}{2}}. $$
Now you have: $$\left|Tf(t)\right|\leq \frac{\sqrt{t}}{1+t}||f||_2 $$
As $\left|\frac{\sqrt{t}}{1+t}\right|\to 0$ as $t\to \infty $ and fixing $||f||_2\leq 1$ , given $\epsilon>0$, we can find $R$ so that for all $t>R$, $\left|Tf(t)\right| <  \epsilon$
Now for $f\in L_2([0,\infty)), ||f||_2\leq 1 $ we have that $Tf$ is bounded. Further, direct application of our first inequality shows that the following is equicontinuous:
$$\{ Tf:[0,R]\to \mathbb{R}: ||f||_2\leq 1\} $$.
So Arzelà–Ascoli theorem applies and the above is actually precompact and hence totally bounded. However, we need, $\{ Tf:[0,\infty)\to \mathbb{R}: ||f||_2\leq 1\} $ to be totally bounded. Fortunately, we can extend any finite $\epsilon$ cover of the former to  a $2\epsilon$ cover of the the latter by noticing for $t>R$ and $||f||_2,||g||_2\leq 1$
$$ \sup_{t>R}\{|Tf(t)-Tg(t)|\}<2\epsilon$$ hence $\{ Tf:[0,\infty)\to \mathbb{R}: ||f||_2\leq 1\} $ is totally bounded and hence $T$ is compact.


text:
Q: Only ask for filename if one has not been input I am using C# and a winform and am saving data to a .xlsx on a button click event.  I have a unique situation that I am not sure how to code for....
If the form is still displayed and the user clicks the button, I want it to prompt for a file name and save location.  BUT if the form has not been closed and the user clicks the button a second time, I want .xlsx to be saved in the same location and with the same filename and over write with no prompt.
This is the syntax I use to prompt for save name and location, but how do I check to determine if a filename/save location has already been input and if it has do not prompt again?
private void btnOne_Click(object sender, EventArgs e)
{
    SaveFileDialog save = new SaveFileDialog();
    save.InitialDirectory = @"C:\";
    save.RestoreDirectory = true;
    save.Title = "Select save location file name";
    save.DefaultExt = "xlsx";

    if (save.ShowDialog() == DialogResult.OK)
    {
        try
        {
            var file = new FileInfo(save.FileName);
            using (var package = new ExcelPackage(file))
            {
                package.Save();
            }
        }
        catch { Messagebox.Show("An error has occured"; }
    }
}

A: So, whether the data has a set filename is a part of the state of the class.  Inside the class where you have btnOne_Click, just define a string with the filename, defaulted to null:
string filepath = null;

Then, in your btnOne_Click, you want to check for the filepath.  If it's not there, open the saveAs dialog.  After that, if filepath is set, just save.  It will be restructured like this:
private void btnOne_Click(object sender, EventArgs e)
{
    if (filepath == null)
    {
        SaveFileDialog save = new SaveFileDialog();
        save.InitialDirectory = @"C:\";
        save.RestoreDirectory = true;
        save.Title = "Select save location file name";
        save.DefaultExt = "xlsx";

        if (save.ShowDialog() == DialogResult.OK) {
            filepath = save.FileName;
        }
    }

    if (filepath != null)
    {
        try
        {
            var file = new FileInfo(filepath);
            using (var package = new ExcelPackage(file))
            {
                package.Save();
            }
        }
        catch { MessageBox.Show("An error has occured"; }
    }
}

This logical structure gives you standard behavior for when a user presses a save button.  If they cancel the saveAs dialog, then the save is aborted and the filename state is not changed.

A: Declare this globally:
public string Filename;

Then change your subroutine like this:
private void btnOne_Click(object sender, EventArgs e)
{
    if (string.IsNullOrWhiteSpace(Filename))
    {
    SaveFileDialog save = new SaveFileDialog();
    save.InitialDirectory = @"C:\";
    save.RestoreDirectory = true;
    save.Title = "Select save location file name";
    save.DefaultExt = "xlsx";

    if (save.ShowDialog() == DialogResult.OK)
    {
        try
        {
            Filename = save.FileName;
            var file = new FileInfo(save.FileName);
            using (var package = new ExcelPackage(file))
            {
                package.Save();
            }
        }
        catch { MessageBox.Show("An error has occured"); }
    }
    }
    else
    {
        var file = new FileInfo(Filename);
        using (var package = new ExcelPackage(file))
        {
            package.Save();
        }
    }
}


text:
Q: How to make a flexbox item in the corner and responsive? I'm new to css and I want to let five boxes lined up horizontally in the top left corner and the last one stay in the bottom right corner even if you resize the browser.I try to use flex to do this but failed to make the F element in the right corner.Can you tell me how to do this?

#container {
    display: flex;
    flex-flow: row nowrap;
}

#A, #B, #C, #D, #E, #F {
    background: #eeeff2;
    width: 100px;
    height: 150px;
    border-left: 10px dotted #D0D0FF;
    margin-right:10px;
}

p {
    font-family: Tahoma, sans-serif;
    font-size:40px;
    padding-left: 10px;
}

#A:hover, #B:hover, #C:hover, #D:hover, #E:hover, #F:hover {
    background: yellow;
    cursor: pointer;
    color: goldenrod;
}
<!DOCTYPE html>

        <link href="styleB.css" rel="stylesheet">

A

B

C

D

E

F

A: You have to need set margin for last-child #F{ margin-left:auto; }

#container {
  display: flex;
  flex-flow: row nowrap;
}

#A,
#B,
#C,
#D,
#E,
#F {
  background: #eeeff2;
  width: 100px;
  height: 150px;
  border-left: 10px dotted #D0D0FF;
  margin-right: 10px;
}

#F {
  margin-left: auto;
}

p {
  font-family: Tahoma, sans-serif;
  font-size: 40px;
  padding-left: 10px;
}

#A:hover,
#B:hover,
#C:hover,
#D:hover,
#E:hover,
#F:hover {
  background: yellow;
  cursor: pointer;
  color: goldenrod;
}

A

B

C

D

E

F


text:
Q: Laravel Eloquent for Social Network
I'm building a social network. I have Users and Posts. for like concept I created a table (Likes):
 _______________________
|id | post_id | user_id |
|   |         |         |
I want to show people who like a post below each post.
so I need to save a row for each Like
.
My problem is Eloquent and how to save a Like row
    $post = Post::find($request->postId);
    $like = new Likes();
    $user = $request->user();
    $post->likes()->save($like, $user);
    return 'done';

this code set user_id (Likes tabel) 0
is there a better way for Like Concept?

A: in your controller use this method  :
    public function postLikePost(Request $request)
    {
        $post_id = $request['postId'];
        $is_like = $request['isLike'] === 'true' ? true:false;
        $update = false;
        $post = Post::find($post_id);
        if(!$post){
            return null;
        }
        $user = Auth::user();
        $like = $user->likes()->where('post_id',$post_id)->first();
        if($like){
            $liked = $like->likes;
            $update = true;
            if($liked == $is_like)
            {
                $like->delete();
                return null;
            }
        } else
        {
            $like = new Like();
            //die($like);
        }
    $like->likes = $is_like;
    $like->user_id = $user->id;
    $like->post_id = $post->id;
    if($update){
        $like->update();
    }
    else{
        $like->save();
    }
    return null;
    }


text:
Q: Upper-bound on the ratio of gaussian pdf to cdf Suppose I have the following  function $f: \mathbb{R} \to \mathbb{R}$:
$$f(r) = (\gamma^2 -\epsilon^2) - 2 r^2 - r \frac{(\gamma -3\epsilon)\phi\left(\frac{\epsilon-\gamma}{r}\right)  - (\gamma+\epsilon)\phi\left(-\frac{\gamma+\epsilon}{r}\right) }{\Phi\left(\frac{\epsilon-\gamma}{r}\right)-\Phi\left(-\frac{\gamma+\epsilon}{r}\right)}$$
where $\phi$ and $\Phi$ are respectively the standard gaussian pdf and cdf, and  $\gamma>\epsilon>\frac{2}{3}\gamma>0$ are real-valued constants.
I am looking for a statement along the lines of:
if $r>g(\epsilon,\gamma)$ then $f(r)<0$.
Here is a plot of how the function looks like for some fixed value of $\gamma$ and $\epsilon$.
Unfortunately, I was only able to show that
$f(r) \overset{r \to \infty}{\longrightarrow} \epsilon (\gamma - \frac{5}{3}\epsilon)$ which is a weaker statement. Any idea on how to tackle this problem is welcome (e.g. a tight upper-bound on the ratio of gaussian pdf to cdf).
(EDIT)
It might be helpful to know where does $f(r)$ comes from. I was originally interested in showing that the following quantity is negative:
$$(\gamma^2 -\epsilon^2) - (\gamma+\epsilon) \mathbb{E}[X] - 2\mathbb{E}[X^2 ] $$
where $X \sim \mathcal{N}(0,r^2)$ is a gaussian r.v. truncated on $(\alpha,\beta)$ with $\alpha = -(\gamma+\epsilon)$, $\beta = -(\gamma-\epsilon)$. Plugging in the known moments of the truncated gaussian we get $f(r)$.
(UPDATE)
I was able to find a point $r_0=10(\gamma+\epsilon)$ such that $f(r_0) < 0$. Hence it would be enough to show that $f$ monotonically decreases for $r>r_0$ (numerically this seems to be the case).


text:
Q: Java String of hex to byte [] It's need to convert string like:
String test = "0xF0 0x9F 0x87 0xB7 0xF0 0x9F 0x87 0xBA";
String [] GetByte = test.split(" ");

to byte array like:
byte [] test_arr = new byte [GetByte.length];
        test [0] = (byte) 0xF0;
        test [1] = (byte) 0x9F;
        test [2] = (byte) 0x87;
        test [3] = (byte) 0xB7;
        test [4] = (byte) 0xF0;
        test [5] = (byte) 0x9F;
        test [6] = (byte) 0x87;
        test [7] = (byte) 0xBA;

Any one can help? Thanks!

A: String[] words = test.split(" ");
byte[] bytes = new byte[words.length];
for (int i = 0; i < words.length; ++i) {
    //bytes[i] = Byte.decode(words[i]);
    bytes[i] = Integer.decode(words[i]).byteValue();
}

The method decode would also translate other bases.
Unfortunately byte is signed, so 0xF0 overflows, Byte.decode cannot be used.

A: Integer[] numbers =
    //splitting the string into an array and converting it to a stream
    Arrays.stream(test.split(" "))
        //removing '0x' from each hex string and parsing an integer value from it
        .map(s -> Integer.parseInt(s.replace("0x", ""), 16))
        //collecting everything to an integer array
        .toArray(Integer[]::new);

I've added some comments about how this code works.
The reason why I used integers instead of bytes is that there are some hex values in the given string that overflow byte.

A: If you're 100% sure that each number begins with 0x, then you can substring that out, then parse it using Integer.parseInt(substringed, 16).


text:
Q: Hitting 65k Dex method limit but dex-method-count tools says there is much fewer We've struggled with the 65k method limit for a long time and have done most of the optimizations already. Now I'm trying to add the Jacoco plugin and I'm getting the dex limit error again:
Error:Execution failed for task ':MyProject:dexExternalBetaDebug'.
> com.android.ide.common.internal.LoggedErrorException: Failed to run command:
    /Users/orrieshannon/Code/sdk/sdk/build-tools/21.1.1/dx --dex --no-optimize --output /Me/MyProject/build/intermediates/dex/externalBeta/debug --input-list=/Me/MyProject/build/intermediates/tmp/dex/externalBeta/debug/inputList.txt
  Error Code:
    2
  Output:
    objc[80218]: Class JavaLaunchHelper is implemented in both /Library/Java/JavaVirtualMachines/jdk1.7.0_67.jdk/Contents/Home/bin/java and /Library/Java/JavaVirtualMachines/jdk1.7.0_67.jdk/Contents/Home/jre/lib/libinstrument.dylib. One of the two will be used. Which one is undefined.
    UNEXPECTED TOP-LEVEL EXCEPTION:
    com.android.dex.DexIndexOverflowException: Cannot merge new index 66105 into a non-jumbo instruction!
        at com.android.dx.merge.InstructionTransformer.jumboCheck(InstructionTransformer.java:109)
        at com.android.dx.merge.InstructionTransformer.access$800(InstructionTransformer.java:26)
        at com.android.dx.merge.InstructionTransformer$StringVisitor.visit(InstructionTransformer.java:72)
        at com.android.dx.io.CodeReader.callVisit(CodeReader.java:114)
        at com.android.dx.io.CodeReader.visitAll(CodeReader.java:89)
        at com.android.dx.merge.InstructionTransformer.transform(InstructionTransformer.java:49)
        at com.android.dx.merge.DexMerger.transformCode(DexMerger.java:842)
        at com.android.dx.merge.DexMerger.transformMethods(DexMerger.java:813)
        at com.android.dx.merge.DexMerger.transformClassData(DexMerger.java:786)
        at com.android.dx.merge.DexMerger.transformClassDef(DexMerger.java:682)
        at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:542)
        at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:171)
        at com.android.dx.merge.DexMerger.merge(DexMerger.java:189)
        at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:454)
        at com.android.dx.command.dexer.Main.runMonoDex(Main.java:302)
        at com.android.dx.command.dexer.Main.run(Main.java:245)
        at com.android.dx.command.dexer.Main.main(Main.java:214)
        at com.android.dx.command.Main.main(Main.java:106)

However when I run the dex-method-count tool (found here https://github.com/mihaip/dex-method-counts) it says we are only at 56k methods.
Read in 56024 method IDs.
<root>: 56024
    : 4
    android: 10877
        accessibilityservice: 6
        ...

The Jacoco library is only 1309 methods (counted using the same dex-method-count tool) so we should be well under 65k limit.
Any ideas? Anyone else noticed the dex-method-count tool underreporting the number of methods?

A: Thanks to @JesusFreke for pointing it out, it turns out the limit was in the number of strings being too large, not the number of methods. To increase the number of strings to 2^32 (instead of default 2^16) enable jumboMode in your build.gradle file.
dexOptions {
        jumboMode = true
    }

For more info on the string limit see this post What does 'String count' mean in Dex file Android?