text:
Q: Missing error message from Selenium after button click I'm doing a simple form submit using the click method:
$this->url('/');
$move = $this->byName('move');
$move->click();
$content = $this->byTag('body')->text();

But I can't understand the error message I get from Selenium:
PHPUnit_Extensions_Selenium2TestCase_WebDriverException:
Build info: version: '3.6.0', revision: '6fbf3ec767', time: '2017-09-27T16:15:40.131Z'
System info: host: 'olle-GA-H81M-S2H', ip: '127.0.1.1', os.name: 'Linux', os.arch: 'amd64', os.version: '4.4.0-51-generic', java.version: '1.8.0_141'
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities [{moz:profile=/tmp/rust_mozprofile.EeZF7cCPXFo3, rotatable=false, timeouts={implicit=0, pageLoad=300000, script=30000}, pageLoadStrategy=normal, moz:headless=false, platform=LINUX, specificationLevel=0, moz:accessibilityChecks=false, acceptInsecureCerts=false, browserVersion=56.0, platformVersion=4.4.0-51-generic, moz:processID=6598, browserName=firefox, javascriptEnabled=true, platformName=LINUX}]
Session ID: eae99c32-7401-4892-9190-e242b3b81f5a

I can var_dump the $move button and confirm that is no null. Any ideas?
The PHP backtrace:
vendor/phpunit/phpunit-selenium/PHPUnit/Extensions/Selenium2TestCase/Driver.php:165
vendor/phpunit/phpunit-selenium/PHPUnit/Extensions/Selenium2TestCase/Driver.php:175
vendor/phpunit/phpunit-selenium/PHPUnit/Extensions/Selenium2TestCase/CommandsHolder.php:100
tests/questions/DateTimeValidationTest.php:215
vendor/phpunit/phpunit-selenium/PHPUnit/Extensions/Selenium2TestCase.php:371
vendor/phpunit/phpunit-selenium/PHPUnit/Extensions/Selenium2TestCase.php:337

Edit: Above was the gecko driver. I get a similar error for the Facebook driver:
Facebook\WebDriver\Exception\UnrecognizedExceptionException:
Build info: version: '3.6.0', revision: '6fbf3ec767', time: '2017-09-27T16:15:40.131Z'
System info: host: 'olle-GA-H81M-S2H', ip: '127.0.1.1', os.name: 'Linux', os.arch: 'amd64', os.version: '4.4.0-51-generic', java.version: '1.8.0_141'
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities [{moz:profile=/tmp/rust_mozprofile.TpTQ5MWyL1hl, rotatable=false, timeouts={implicit=0, pageLoad=300000, script=30000}, pageLoadStrategy=normal, moz:headless=false, platform=LINUX, specificationLevel=0, moz:accessibilityChecks=false, acceptInsecureCerts=false, browserVersion=56.0, platformVersion=4.4.0-51-generic, moz:processID=9146, browserName=firefox, javascriptEnabled=true, platformName=LINUX}]
Session ID: 56036593-dc86-4132-9d0f-78beb369b35c

vendor/facebook/webdriver/lib/Exception/WebDriverException.php:158
vendor/facebook/webdriver/lib/Remote/HttpCommandExecutor.php:320
vendor/facebook/webdriver/lib/Remote/RemoteWebDriver.php:535
vendor/facebook/webdriver/lib/Remote/RemoteExecuteMethod.php:40
vendor/facebook/webdriver/lib/Remote/RemoteWebElement.php:81
tests/questions/FacebookDriverTest.php:42

The HTML for the button is:
<button type="submit" value="movesubmit" name="move" accesskey="l" class="ls-move-btn ls-move-submit-btn btn btn-lg btn-primary">
    Submeter
</button>

Edit 2: Exception from selenium:
15:35:15.177 INFO - Executing: [find element: By.name: move])
15:35:15.193 INFO - Done: [find element: By.name: move]
1509374115699   addons.productaddons    INFO    downloadXHR File download. status=200
1509374115702   addons.productaddons    INFO    Downloaded file will be saved to /tmp/tmpaddon-e50bf4
1509374116634   DeferredSave.webext.sc.lz4      DEBUG   Starting write
1509374116639   DeferredSave.webext.sc.lz4      DEBUG   Write succeeded
15:35:17.196 INFO - Executing: [click: 0 [[FirefoxDriver: firefox on LINUX (32c1dfec-9af4-448f-86fa-3a41035bf6b5)] -> name: move]])
15:35:17.501 WARN - Exception thrown
org.openqa.selenium.ElementNotInteractableException:

Edit 3: Mystery solved, I had two buttons with the same name, and the first one was hidden. Hence, the exception. Solved by putting a proper ID on the element I want to interact with.


text:
Q: Zend Framework 2 - Database connection Trying to wrap my head around the new concepts of Zend Framework 2.0.
I'm trying to connect to a database, and to get that connection in a controller or model.
Nothing fancy, just the pure connection to run queries against.
So this is my current code:
//module.config.php
return array(
    'db' => array(
        'driver'         => 'Pdo',
        'dsn'            => 'mysql:dbname=DBNAME;host=HOSTNAME,
        'driver_options' => array(
            PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
        ),
        'username' => 'USERNAME',
        'password' => 'PASSWORD',
    ),
    'service_manager' => array(
        'factories' => array(
            'translator' => 'Zend\I18n\Translator\TranslatorServiceFactory',
            'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
        ),
    ),
);

What am I doing wrong?

A: Create db.local.php in your ./config/autoload folder and add the following content
return array(
'db' => array(
    'driver'         => 'Pdo',
    'dsn'            => 'mysql:dbname=zenBlog;host=localhost',
    'username'       =>'root',
    'password'      =>'',
    'driver_options' => array(
        PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
    ),
),
'service_manager' => array(
    'aliases' => array(
'db' => 'Zend\Db\Adapter\Adapter',
),
),);

in your controller $this->getServiceLocator()->get('db');  to access  to database.

A: This is how my local.php in config\autoload\local.php looks like.
<?php
return array(
 'db' => array(
    'driver'         => 'Pdo',
     'dsn' => 'mysql:dbname=<dbname>;host=localhost',
     'username' => 'root',
     'password' => <your password here>,
     'driver_options' => array(
    PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
 ),
 ),
'service_manager' => array(
'aliases' => array(
'adapter' => 'Zend\Db\Adapter\Adapter',
),
),);

Now use this to create a database adapter:
$adapter = $this->getServiceLocator()->get('adapter');

Create a sql statetment and put in variable $sql.
Now do this:
$statement = $adapter->createStatement($sql);
$result = $statement->execute();

Hope this helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there any way to make a direct download link for song ? When i do something like this: It opens the website in the browser when i click on download button it go to the page of website.I upload my song on the url.Is there any way to make it on single button click download.plz help me..

A: It might be helpfull for u
https://stackoverflow.com/a/3028660/1661067
Look at all realisations!


text:
Q: From Sql Database to Azure Storage Emulator I have a Sql database and I have to put it in my Azure Storage Emulator (In Storage > Development > Tables); how can I do it? In Visual Studio I don't find any possibility to import, for example, a .bacpac file.
UPDATE:
I discovered that the database should not be put in there, but then how do I properly simulate Azure storage and my Sql database as well?

A: Just to clarify: Azure Storage (Tables, Blobs, Queues) is completely different from SQL Azure databases.
If you use the latest version of SQL Express it's very very similar to SQL Azure and fine for most development needs.
There isn't a SQL Azure simulator that I know of - but it's really easy to get a FREE 30 day Azure account and I would strongly suggest you do some development and testing against that: SQL Azure has far more connection issues (no connection, handshake problems, lags) than a database that is local to the app, and you need to be prepared for this (investigate Transient Fault Handling strategies).
You can work locally and connect to your SQL Azure instance = a 'real' SQL Azure simulation.

A: When developing locally for Azure SQL Database, please use SQL Server Express - it is the relational database equivalent for Azure Storage Emulator (Azure Blob, Queue, and Table).


text:
Q: IDE and Dynamic memory this may sound like a silly question but does anyone know if the memory used in heap from executing codes in an IDE will be freed after the program ends? If it is not automatically freed, is there a way to clean up the heap? Please kindly advise.

A:
does anyone know if the memory used in heap from executing codes in an IDE will be freed after the program ends?

Yes. Operating systems generally releases all resources allocated to a process when the process terminates. Note that this is not something specified by the C++ language nor is this behaviour C++ specific.
Whether the process started by an IDE or something else does not matter.


text:
Q: Style the text before  in single.php I'd like to style differently the content before the  link, but in single.php.
To be more specific, all my posts on the homepage only have a summary, and the rest of the text is cut thanks to the use of the more tag. So when I click on "read more" I see the complete post, starting with the summary we previously seen on the homepage. I'd like to differentiate this summary from the rest of the text, adding it some bold for example, to show to the user what he as already read.
Unfortunately I think this is not possible. Is it ?

A: using: http://codex.wordpress.org/Function_Reference/the_content#Overriding_Archive.2FSingle_Page_Behavior
and the $strip_teaser parameter:
http://codex.wordpress.org/Function_Reference/the_content#Usage
in single.php, replace <?php the_content(); ?> with:
<?php if( strpos(get_the_content(), '

  <?php global $more; $more=0; the_content(''); $more=1; ?>

<?php endif; ?>
<?php the_content('', true); ?>

A: I solved this by creating 2 functions to split the_content() in a before and after-function:
class MyClass
{
    /**
     * Echo the content before the  tag
     */
    public static function getContentBeforeMore()
    {
        global $more;
        $more = false;
        the_content(false);
        $more = true;
    }

    /**
     * Echo the content after the  tag
     */
    public static function getContentAfterMore($removeMoreTag = true)
    {
        $content = get_the_content(null, true);
        $content = apply_filters( 'the_content', $content );
        $content = str_replace( ']]>', ']]>', $content );
        // Remove the empty paragraph with the -tag:
        if($removeMoreTag)
        {
            $content = preg_replace('/
<\/span><\/p>/m', '', $content);
        }
        echo $content;
    }
}

In a template it can be used like this:

<?php MyClass::getContentBeforeMore(); ?>

... some other styling, like date or something ...

<?php MyClass::getContentAfterMore(); ?>


text:
Q: Delegate send on click submit button (jQuery) Say we have
$submitButton.click(function(e){
    doSomething(e);
    return false;
});

Where $submitButton is the jQuery object of the submit button of a form. Say doSomething is an async method with an AJAX call.
If I return true then the form is submitted before doSomething ends, so I want to return false and then once doSomething ends the AJAX, in the success callback, I want to actually submit the form.
Is this possible using just e? how?

A: $submitButton.click(function(e){
    //make doSomething return a promise that you can chain off of
    doSomething(e).then(function(){
        //submit the parent form
        $submitButton.closest('form').trigger('submit');
    });

    //cancel the click and wait for the ajax to finish
    return false;
});


text:
Q: Understanding how Django Apps system works After some months of using Django, I feel the need to create the first my Django application. In this way I can really take the advantages of the Django's power.
Someone can give me hints and directions for learning well about it?
How Django's apps system works? And how can I create my first reusable app?
I think Django's is one of the best framework ever created and I want to learn it very well for using it in various contexts.
And now I would to take my Django's experience and skills to the next level.

A: In addition to the official Django documentation and tutorial, which are excellent, I would recommend two books you should check out:
Ayman Hourieh's Django Web Development 1.0:
http://www.amazon.com/gp/aw/d/1847196780/ref=redir_mdp_mobile/191-3941588-1909500
An awesome book that will take you step by step through creating your first Django app, and that touches on several of Django's features and functionality.
The Definitive Guide to Django:
http://www.amazon.com/gp/aw/d/1847196780/ref=redir_mdp_mobile/191-3941588-1909500
The title says it all, written by Django's creator and lead developer.

A: Don't miss a great talk about reusable apps by James Bennet: http://www.youtube.com/watch?v=A-S0tqpPga4 .

A: Try here for starters:
https://docs.djangoproject.com/en/1.3/intro/tutorial01/

This document describes Django 1.3.
  Writing your first Django app, part 1...

And I suggest you go to Amazon.com, look through Django books and read a lot of the reviews until you find something that sounds appropriate for you.
HTH


text:
Q: How to property call component inside same component using ReactJS? I'm building a sidebar menu with submenu levels, and I'm using this code to build the menu and the submenus:
Sidebar menu:
import React from 'react';

import SidebarMenuItem from './SidebarMenuItem';

var menuData = require("./data/menu.json");

class SidebarMenu extends React.Component {
    constructor(props)
    {
        super(props);

        this.state = { expanded: true };
    };

  render() {

      return (

          {
            menuData.map((item, index) => <SidebarMenuItem id={ index.toString()} key={index.toString()} {...item} />)
          }

      );
  };
}

export default SidebarMenu;

SidebarMenuItem:
import React from 'react';

class SidebarMenuItem extends React.Component {

    render() {

        console.log(this.props.id);

        return (

                {this.props.title}

                {this.props.submenu ? this.props.submenu.map((subitem, index) => <SidebarMenuItem key={this.props.id + index.toString()} {...subitem} />) : null }

            )
    }

}

SidebarMenuItem.propTypes = {
    id: React.PropTypes.string,
    key: React.PropTypes.string,
    title: React.PropTypes.string,
    ref: React.PropTypes.string,
    icon: React.PropTypes.string,
    submenu: React.PropTypes.array
}

export default SidebarMenuItem;

Although I can see the submenus on screen, I'm getting the following error:
Warning: SidebarMenuItem: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop.

Another clue that something is wrong is the console output:
0
1
undefined <-- I was supposed to get 11 and 12 here, as this option has 2 submenus
2

And finally my menu.JSON data:
[
  {
    "title": "Option1",
    "link": "www.google.com",
    "icon": "fa-edit"
  },
  {
    "title": "Option2",
    "link": "",
    "icon": "fa-hello",
    "submenu":
    [
      {
        "title": "SubOption2.1",
        "link": "wwww.yahoo.com",
        "icon": "fa-asterisk"
      },
      {
        "title": "SubOption2.2",
        "link": "wwww.tisafe.com",
        "icon": "fa-save"
      }
    ]
  },
  {
    "title": "Option3",
    "link": "www.mezasoft.com",
    "icon": "fa-save"
  }
]

Help appreaciated to find out what's wrong with my code.

A: You are getting the warning because key is a restricted attribute and cannot be passed as a prop, change it to keyValue. Also you get undefined when you use this.props.id because in your SidebarMenuItem render function for submenus you are still calling the same component and there you are not passing the id as a prop. you can see that in the snippet below. I hope it helps

class SidebarMenu extends React.Component {
    constructor(props)
    {
        super(props);

        this.state = { expanded: true };
    };

  render() {
      var menuData = [
  {
    "title": "Option1",
    "link": "www.google.com",
    "icon": "fa-edit"
  },
  {
    "title": "Option2",
    "link": "",
    "icon": "fa-hello",
    "submenu":
    [
      {
        "title": "SubOption2.1",
        "link": "wwww.yahoo.com",
        "icon": "fa-asterisk"
      },
      {
        "title": "SubOption2.2",
        "link": "wwww.tisafe.com",
        "icon": "fa-save"
      }
    ]
  },
  {
    "title": "Option3",
    "link": "www.mezasoft.com",
    "icon": "fa-save"
  }
];
      return (

          {
           menuData.map((item, index) => <SidebarMenuItem id={ index.toString()} keyValue={index.toString()} {...item} />)
          }

      );
  };
}

class SidebarMenuItem extends React.Component {

    render() {

        console.log('in render',this.props);

        return (

                {this.props.title}

                {this.props.submenu ? this.props.submenu.map((subitem, index) => <SidebarMenuItem keyValue={this.props.id + index.toString()} {...subitem} />) : null }

            )
    }

}

SidebarMenuItem.propTypes = {
    id: React.PropTypes.string,
    keyValue: React.PropTypes.string,
    title: React.PropTypes.string,
    ref: React.PropTypes.string,
    icon: React.PropTypes.string,
    submenu: React.PropTypes.array
}

ReactDOM.render(<SidebarMenu/>, document.getElementById('app'));


text:
Q: How to redirect pdf files to corresponding page? I have pdf urls for each of my pages.
For example :
https://seorooz.net/panda-algorithm/?print=pdf
https://seorooz.net/panda-algorithm/
I want 301 redirect all request from pdf urls to original page urls.
How can i do this from .htaccess file?
Update:Solved.I have this code in my .htaccess file:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

I  just added this code after RewriteBase / :
RewriteCond %{THE_REQUEST} /([^?]+)\?print=pdf [NC]
RewriteRule ^ /%1? [R=301,L,NE]

And work perfectly.

A: You can use this rule in your DOCUMENT_ROOT/.htaccess file:
RewriteEngine On

RewriteCond %{THE_REQUEST} /([^?]+)\?print=pdf [NC]
RewriteRule ^ /%1? [R=302,L,NE]


text:
Q: Can I ask about a perceived structural problem with another Stack Exchange site? Can I post a question here on Meta Stack Exchange about a large problem regarding the structural organization of a particular Stack Exchange? I want to know this first before preparing the detailed question with diagrams. Overall, I believe that I have found a major problem with one of the Stack Exchanges that needs to be solved.

A: That depends.

*

*If your question is about the overall structure of SE across multiple sites, it is a question about SE and should be posted on Meta.SE

*If your question is specific to the SE site and how it is organized, it should be posted on that site's own Meta Page.

Not knowing what your question is, I cannot tell you whether or not it is appropriate for this site or for the Meta site.
What you can do is post the question on whichever site you believe it is best suited for, and if it would be better suited for the other site's meta page, it will be migrated to that site by a moderator.  So even if you post it on the wrong site, your question will not be lost!
However, whatever you do please do not post it on both Meta sites - this is frowned upon as it requires one question to be closed, and may cause some confusion about which one should be closed.  Cross-site posting is generally frowned upon for this reason, so please only post your question on one site or the other.


text:
Q: A question relating to uniform integrability and tightness Let $(f_n)$ be a sequence of integrable functions on $\mathbb{R}$. I want to show that $(f_n)$ is uniformly integrable
and tight over $\mathbb{R}$ if and only if for each $\varepsilon>0$, there are positive numbers $r$ and $\delta$ such that for
each open subset $\mathcal{O}$ of $\mathbb{R}$ and index $n$, if $m(\mathcal{O}\cap (-r,r))<\delta$, then $\int\limits_{\mathcal{O}}|f_n|dm<\varepsilon$.
If the given condition holds, then it is easy to show that $f$ is uniformly integrable and tight. Let $\varepsilon >0$. Then there exist $\delta >0,r>0$ such that for all open sets $\mathcal{O}$ with $m(\mathcal{O}\cap (-r,r))<\delta\implies \int\limits_{\mathcal{O}}|f_n|dm<\varepsilon$. Let $A$ be a measurable subset of $\mathbb R$ with $m(A)<\frac{\delta}{2}$. Thus there exists an open set $\mathcal{O}$ containing $A$ such that $m(\mathcal{O}\setminus A)<\frac{\delta}{2}$. Thus\begin{align}
m(\mathcal{O}\cap (-r,r)) & = m((\mathcal{O}\setminus A) \cap (-r,r))\\
&\quad +m(A\cap (-r,r))\\
& <\frac{\delta}{2}+\frac{\delta}{2}\\
& =\delta.\end{align}
Thus by hypothesis $\int\limits_{\mathcal{O}}|f_n|dm<\varepsilon$. Hence $\int\limits_A |f_n|dm\leq \int\limits_{\mathcal{O}}|f_n|dm<\varepsilon$. Also $\mathbb R\setminus [-r,r]$ is an open set such that $(\mathbb R\setminus [-r,r])\cap (-r,r)=\emptyset$. Thus $\int\limits_{\mathbb R\setminus [-r,r]}|f_n|dm<\varepsilon$ and so $(f_n)$ is tight. But how to prove the converse? Help please!

A: For the converse, fix a positive $\varepsilon$. From uniform integrability, we know that there exists a positive $\delta$ such that for all measurable set of measure smaller than $\delta$, $\sup_n\int_A\left\lvert f_n\right\rvert dm\lt\varepsilon$. From tightness, we know that there exists a set  $E_0$ such that $\sup_n\int_{\mathbb R\setminus E_0}\left\lvert f_n\right\rvert dm\lt\varepsilon$. Choose $r$ such that $m\left(E_0\setminus [-r,r]\right)\lt \delta$.
Let $O$ be an open set such that $m\left(O\cap [-r,r]\right)\lt \delta$. With $A:=O\cap [-r,r]$, we get that
$$
\tag{*}\sup_n\int_{O\cap [-r,r]}\left\lvert f_n\right\rvert dm\lt\varepsilon.
$$
Since $$\int_{O\cap [-r,r]^c}\left\lvert f_n\right\rvert dm\leqslant \int_{ [-r,r]^c}\left\lvert f_n\right\rvert dm
=\int_{ E_0 \cap [-r,r]^c}\left\lvert f_n\right\rvert dm+\int_{ E_0^c \cap [-r,r]^c}\left\lvert f_n\right\rvert dm,$$ we by applying uniform integrability this time with $A=E_0 \cap [-r,r]^c$ and using tightness for the second term that
$$\tag{**}
\sup_n\int_{O\cap [-r,r]^c}\left\lvert f_n\right\rvert dm\leqslant 2\varepsilon
$$
hence the combination of $(*)$ and $(**)$ yields
$$
\sup_n\int_O\left\lvert f_n\right\rvert dm\lt 3\varepsilon.
$$


text:
Q: Find the value of one column based on maximum value in another column per group I have a query which gives me three columns: an ID, the day of week of event and count of how many events each day of week has, i.e.
ID    Day_Name    Cnt
1     Thursday    1
2     Monday      3
2     Thursday    2
2     Sunday      2
3     Tuesday     7
3     Wednesday   3

I get this by using query
SELECT P.ID, DAYNAME(E.EVENT_DATE) AS Day_Name, COUNT(*) AS Cnt
FROM EVENT AS E

INNER JOIN PERSON AS P
ON P.ID_2 = E.ID_2

WHERE E.EVENT_DATE > '2016-01-01'
AND E.EVENT_STATUS LIKE '%OCCURED%'

GROUP BY P.ID, DAYNAME(E.EVENT_DATE)

I would like to reduce this query to only return the day of week for each user with the maximum count. At the same time, I would like to change the column with counts to instead show the frequency of events for that weekday. For the example above I would like to change the output to be
ID    Day_Name    Frequency
1     Thursday    1
2     Monday      0.429
3     Tuesday     0.7

Thankful if anyone got an idea

A: To get the expected result set you could do your calculation in outer query like
SELECT ID,
SUBSTRING_INDEX(GROUP_CONCAT(Day_Name ORDER BY Cnt DESC),',',1) Day_Name,
MAX(Cnt)/SUM(Cnt) Frequency
FROM(
    SELECT P.ID, DAYNAME(E.EVENT_DATE) AS Day_Name, COUNT(*) AS Cnt
    FROM EVENT AS E
    INNER JOIN PERSON AS P
    ON P.ID_2 = E.ID_2
    WHERE E.EVENT_DATE > '2016-01-01'
    AND E.EVENT_STATUS LIKE '%OCCURED%'
    GROUP BY P.ID, DAYNAME(E.EVENT_DATE)
) t
GROUP BY ID

A: So here's a partial answer...
SELECT a.*
  FROM ([your query here]) a
  JOIN
     ( SELECT id,MAX(cnt) cnt FROM ([your query here]) GROUP BY id ) b
    ON b.id = a.id
   AND b.cnt = a.cnt;

For a more complete answer I suggest you provide the original 18 row data set. See: Why should I provide an MCVE for what seems to me to be a very simple SQL query?


text:
Q: can't seem to select from dropdown flipkart Not able to select a value from the drop down for the maximum side.I am using flipkart and trying to find top few products under a certain range sorted by new. in the end I need to print the results in an excel file. There is also a slider to adjust the price.
Main error line
if(driver.findElement(By.xpath("//h1[contains(text(),'5G')]")).isDisplayed())
&
goToPhones();
does not relate to that function it seems.
//imports
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;

public class FlipkartSearch {

public static WebDriver driver;

        public static void createDriver() {
              //close the poppup for login and continue with selections.
System.setProperty("webdriver.chrome.driver","C:\\Users\\hp\\Desktop\\selenium\\qwertyuiop\\chromedriver.exe");
                  driver=new ChromeDriver();
                 driver.manage().window().maximize();
                 driver.get("https://www.flipkart.com/");
                 driver.manage().timeouts().pageLoadTimeout(5,TimeUnit.SECONDS);

            if(driver.findElement(By.xpath("/html[1]/body[1]/div[2]/div[1]/div[1]/button[1]")).isDisplayed())
            {
                driver.findElement(By.xpath("/html[1]/body[1]/div[2]/div[1]/div[1]/button[1]")).click();
            }

        }

        public static void goToPhones() {//get to the page for mobile phones

            WebElement Electronics=driver.findElement(By.xpath("//span[contains(text(),'Electronics')]"));

            Actions hover=new Actions(driver);
            hover.moveToElement(Electronics).build().perform();

            WebDriverWait wait=new WebDriverWait(driver,10);

            wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[contains(text(),'Mobiles')]")));
        driver.findElement(By.xpath("//a[contains(text(),'Mobiles')]")).click();
        driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);

        if(driver.findElement(By.xpath("//h1[contains(text(),'5G')]")).isDisplayed())
        {
// a pop up page appears a few times, in order to ignore that and run the code again
            driver.navigate().back();
            goToPhones();
            }

        }

        public static void phoneFilters()  {// set price range filters and sort by new and store top 5 results in excel
            WebDriverWait wait=new WebDriverWait(driver,10);
            wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//body//div[@id='container']//div//div//div[3]//select[1]")));
            driver.findElement(By.xpath("//body//div[@id='container']//div//div//div[3]//select[1]")).click();
            Select s=new Select(driver.findElement(By.xpath("//body//div[@id='container']//div//div//div[3]//select[1]")));
            s.selectByVisibleText("₹2000");
        }
    public static void main(String[]args){
       // FlipkartSearch fs=new FlipkartSearch();
       createDriver();
        goToPhones();
        phoneFilters();
        }
     }

Full list of errors
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 85.0.4183.102, chrome: {chromedriverVersion: 85.0.4183.87 (cd6713ebf92fa..., userDataDir: C:\Users\hp\AppData\Local\T...}, goog:chromeOptions: {debuggerAddress: localhost:53215}, javascriptEnabled: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: WINDOWS, platformName: WINDOWS, proxy: Proxy(), setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify, webauthn:virtualAuthenticators: true}
Session ID: 228126d9615990fe197ccf525c9635b8
*** Element info: {Using=xpath, value=//h1[contains(text(),'5G')]}
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:187)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:122)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:323)
    at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:428)
    at org.openqa.selenium.By$ByXPath.findElement(By.java:353)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:315)
    at FlipkartSearch.goToPhones(FlipkartSearch.java:44)
    at FlipkartSearch.main(FlipkartSearch.java:65)

A: Replace below code with working code.
    if(driver.findElement(By.xpath("//h1[contains(text(),'5G')]")).isDisplayed()){
            // a pop up page appears a few times, in order to ignore that and run the code again
            driver.navigate().back();
            goToPhones();
   }

Working code.
if (driver.findElements(By.xpath("//h1[contains(text(),'5G')]")).size()>0) {
        // a pop up page appears a few times, in order to ignore that and run the code again
        driver.navigate().back();
        goToPhones();
    }


text:
Q: ActiveMQConsumer.receive(1000) returns null We are putting message into ACtiveMQ, we are running sample program with this method ActiveMessageConsumer.receive(1000) always returns null message.
Even though Queue has messages, still not able to receive those messages.
    url = "http://" ;
connectionFactory = new ActiveMQConnectionFactory("admin", "xxxxx", url);

connection = connectionFactory.createConnection();
((ActiveMQConnection)connection).getPrefetchPolicy().setQueuePrefetch(0);
connection.start();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

destination = session.createQueue("something.sampleQ");
MessageConsumer consumer = session.createConsumer(destination);
ActiveMQObjectMessage message = (ActiveMQObjectMessage) consumer.receive(1000);

A: Your ActiveMQ URL should be one of these:
http://activemq.apache.org/connection-configuration-uri.html
For example: tcp://localhost:61616

A: https://issues.apache.org/jira/browse/AMQ-6823
there is bug with AMQ 5.12.3 which is resolved with 5.15.1 for http connector


text:
Q: References of the dangers of misapplying Gaussianity? This may seem an uncommon request. I am preparing a presentation and for its introduction I am seeking illustrative, public, large-scale cases in which a wrong assumption of Gaussianity created a major problem. Due to the prevalence of the normal distribution and the frequency with which applied scientists tend to misapply it (for example when using it for random variables with physical limits, Pareto fronts, or multiple modes), I am quite sure that there must be some cases out there.
I am looking for references such as this one which was about the dangers of misapplying and misunderstanding correlation. Anecdotal stories in papers, blogs, or newspapers would also be great!


text:
Q: Is there a maximum or minimum top absolute position for SVG images in IE I'm using absolute positioning to move a VERY large SVG img around inside another div element. I've set up a jsFiddle as a demo:
http://jsfiddle.net/wEBnE/6
This works fine in all browsers except (you guessed it) IE. Click the button in the jsFiddle a few times. It increases the top position 3 times until it goes beyond -84245px - then the image stops moving. The css property still increases, but the visible element remains in the same position.
As far as I can tell, this only happens with an img tag. I have other div elements that work fine like this.
Am I correct in thinking it must be some sort of built-in IE maximum setting and is there a way to override this behaviour?
Thanks


text:
Q: How to get the url of all video files stored in photo library with photokit I have found a lot of solutions, but all of them are implemented with ALAssetLibrary, But the assetlibrary will be depreciated in iOS 9, I do not know how to get video files in photo library, and get their url and thumbnail.

A: You could play around with the sample code Apple provides for photo kit
Code would be something like
PHPhotoLibrary.requestAuthorization { (status) -> Void in
            let allVidOptions = PHFetchOptions()
            allVidOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.Video.rawValue)
            allVidOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
            let allVids = PHAsset.fetchAssetsWithOptions(allVidOptions)
            for index in 0..<allVids.count {
                //fetch Asset here
                print(allVids[index])
            }

        }

A: You can also use the function fetchAssets with media type
Video
let videosArray = PHAsset.fetchAssets(with: .video, options: nil)

Images
let imagesArray = PHAsset.fetchAssets(with: .image, options: nil)


text:
Q: Loading table in html takes quite long time I have a big table, which takes a lot of time to load on the web. I'm looking for a solution to speed up the loading time, and I'm not looking into splitting it into various pages. Any suggestion?? Here is the link: http://khi.ac.ir/EnglishW/info/Students/All_Students.aspx

A: Try using JQuery DataTables Server Side Processing to accomplish this task.
http://www.datatables.net/release-datatables/examples/data_sources/server_side.html
This would be the only way to reduce loading time because instead of loading every table row at once, It will load a set of rows at a time.

A: you add a line like this :

آهي عاطفه

for every entry. I suggest that first do not add style="color:Black;font-family:Tahoma;text-decoration:none;" for every table column and use this in a separate css file and also show just the names of the users and a little javascript to add extra information(like download links) to the next td element like:

 آهي عاطفه

A: For those searching for an answer in 2019, here are some paths I tried for a similar problem:
Create a 2D array as a variable with all your data; for me it decreased the table size from 10mb to 3mb, and can possibly decrease it further if I find repetitive long texts and substitute them with a short placeholder. This has an advantage of speeding up the download, but it decreases interpretation time.
Interpretation of a 2D array can be done with a simple string gluer or dom .appendChild builder. I find that string concatenators work the fastest.
function createTable(tableData) {
  var firstdiv = document.getElementById("wrapper");
  var i = 0;
  var text = "

Project	Planner	Item	Comment

";
  var item;
  for (i = 0; i < tableData.length; i++) {
    item = tableData[i];
    text += "
" + item[0] + "	" + item[1] + "	" + item[2] + "	" + item[3] + "
";
      }
  text += "

"

  firstdiv.innerHTML = text;
}


text:
Q: Spring Security 403 http status I am implementing Spring Security on a Spring Boot 2.0.1 project.
I have some web services that used to work fine before Spring Security implementation. But now, they don't.
This is the error message displayed in REST client.
{
    "timestamp": "2018-07-27T11:14:40.080+0000",
    "status": 403,
    "error": "Forbidden",
    "message": "Access Denied",
    "path": "/lsm/notification/getCurrentUserNotifications"
}

and the same error on google chrome :

Below is the controller listing the services:
package com.sap.lsm.web;

import java.util.List;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.sap.lsm.dao.NotifiedUserRepository;
import com.sap.lsm.dao.UserNotificationRepository;
import com.sap.lsm.entities.NotifiedUser;
import com.sap.lsm.entities.UserNotification;
import com.sap.lsm.service.UserNotificationService;

@RestController
public class UserNotificationController {

@Autowired
private UserNotificationService userNotificationService;

@Autowired
private UserNotificationRepository userNotificationRepository;

@RequestMapping(value="/notification/getCurrentUserNotifications", method=RequestMethod.GET)
public List<UserNotification> getCurrentUserNotifs() {
    return userNotificationService.getCurrentUserAllNotifications();
}

@RequestMapping(value="/notification/getCurrentUserNotSeenNotifications", method=RequestMethod.GET)
public List<UserNotification> getCurrentUserNotSeenNotifs() {
    return userNotificationService.getCurrentUserNotSeenNotifications();
}

@RequestMapping(value="/notification/deleteNotification/{id}", method=RequestMethod.DELETE)
public void deleteNotification(@PathVariable("id") Long id){
    userNotificationService.deleteNotification(id);
}

@RequestMapping(value="/notification/getNotification/{id}", method=RequestMethod.GET)
public UserNotification getNotification(@PathVariable("id") Long id) {
    UserNotification notification = this.userNotificationService.getNotification(id);

    if(!notification.equals(null)) {
        notification.setStatus("seen");
        userNotificationRepository.save(notification);
    }

    return notification;
}

@RequestMapping(value="/notification/markCurrentUserNotificationsAsSeen", method=RequestMethod.GET)
public void markCurrentUserNotificationsAsSeen() {
    userNotificationService.markAllNotificationsAsSeen();
}
}

And this is the Spring Security Config :
package com.sap.lsm.config;

import javax.servlet.Filter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.access.channel.ChannelProcessingFilter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@EnableGlobalMethodSecurity(prePostEnabled=true)
@EnableWebSecurity
@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private UserDetailsService userDetailsService;

@Autowired
private RequestFilter requestFilter;

@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;

public SpringSecurityConfig(UserDetailsService userDetailsService, BCryptPasswordEncoder bCryptPasswordEncoder) {
    this.userDetailsService = userDetailsService;
    this.bCryptPasswordEncoder = bCryptPasswordEncoder;
}

public void setUserDetailsService(UserDetailsService userDetailsService) {
    this.userDetailsService = userDetailsService;
}

public void setbCryptPasswordEncoder(BCryptPasswordEncoder bCryptPasswordEncoder) {
    this.bCryptPasswordEncoder = bCryptPasswordEncoder;
}

@Override
protected void configure(HttpSecurity http) throws Exception {

    http.csrf().disable();
    http.cors()
        .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
            .logout().deleteCookies("JSESSIONID").invalidateHttpSession(true)
        .and()
            .authorizeRequests()
            .antMatchers("/lsm/listCustomers").hasAnyAuthority("ADMIN","CONSULTANT")
            .antMatchers("/lsm/addCustomer").hasAnyAuthority("CONSULTANT")
            .antMatchers("/lsm/getAllCustomers").hasAnyAuthority("ADMIN","CONSULTANT")
            .antMatchers("/lsm/getOldCustomers").hasAnyAuthority("ADMIN","CONSULTANT")
            .antMatchers("/lsm/getCustomers").hasAnyAuthority("ADMIN","CONSULTANT")
            .antMatchers("/lsm/getCustomer/*").hasAnyAuthority("ADMIN","CONSULTANT")
            .antMatchers("/lsm/deleteCustomer/*").hasAnyAuthority("ADMIN","CONSULTANT")
            .antMatchers("/lsm/cancelCustomer/*").hasAnyAuthority("ADMIN","CONSULTANT")
            .antMatchers("/lsm/restoreCustomer/*").hasAnyAuthority("ADMIN","CONSULTANT")
            .antMatchers("/lsm/updateCustomer/*").hasAnyAuthority("ADMIN","CONSULTANT")
            .antMatchers("/lsm/getLSMUsers").hasAnyAuthority("ADMIN","CONSULTANT")
            .antMatchers("/lsm/addLSMUser").hasAnyAuthority("ADMIN")
            .antMatchers("/lsm/getLSMUser/*").hasAnyAuthority("ADMIN")
            .antMatchers("/lsm/deleteLSMUser/*").hasAnyAuthority("ADMIN")
            .antMatchers("/lsm/cancelLSMUser/*").hasAnyAuthority("ADMIN")
            .antMatchers("/lsm/restoreLSMUser/*").hasAnyAuthority("ADMIN")
            .antMatchers("/lsm/updateLSMUser/*").hasAnyAuthority("ADMIN")
            .antMatchers("/lsm/notification/getCurrentUserNotifications/*").hasAnyAuthority("ADMIN","CONSULTANT")
            .antMatchers("/lsm/notification/getCurrentUserNotSeenNotifications/*").hasAnyAuthority("ADMIN","CONSULTANT")
            .antMatchers("/lsm/notification/deleteNotification/*").hasAnyAuthority("ADMIN","CONSULTANT")
            .antMatchers("/lsm/notification/getNotification/*").hasAnyAuthority("ADMIN","CONSULTANT")
            .antMatchers("/lsm/notification/markCurrentUserNotificationsAsSeen/*").hasAnyAuthority("ADMIN","CONSULTANT")
            .antMatchers("/assets/**","/login","/*").permitAll()
        .and()
            .authorizeRequests().anyRequest().authenticated()
        .and()
            .addFilter(new JWTAuthenticationFilter(authenticationManager()))
            .addFilterBefore((Filter) new JWTAuthorizationFilter(),UsernamePasswordAuthenticationFilter.class)
            .addFilterBefore(requestFilter, ChannelProcessingFilter.class);
}

@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
}

}

If you need JWT authentication and authorization filters, i'll post them later on .
Please help me,
Thanks
** update **
The role of the connected user is ADMIN.
The path /lsm is declared as property in the pom.xml as follows:
<m2eclipse.wtp.contextRoot>/lsm</m2eclipse.wtp.contextRoot>

This root path is used to run the application under Jenkins (integration server)


text:
Q: Do updating state of an object inside the useEffect() creates a new object? import { useEffect, useState } from "react";

function CountSecrets() {
  const [secret, setSecret] = useState({ value: "", countSecrets: 0 });

  useEffect(() => {
    if (secret.value === 'secret') {
      setSecret(s => ({...s, countSecrets: s.countSecrets + 1}));    }
  }, [secret]);
  const onChange = ({ target }) => {
    setSecret(s => ({ ...s, value: target.value }));
  };

  return (

      <input type="text" value={secret.value} onChange={onChange} />

Number of secrets: {secret.countSecrets}

  );
}

when the secret is typed the react goes into an infinite loop
I am reading this code through a blog post and its written that the setting the state of an object inside the useEffect creates a new object so the dependency inside the [ ] of useEffect
changes and cause infinite loop.
Here is my question when we type and onchange  is triggered and is also updating the state, so is updating the state inside the onchange do not creates a new object?And what are the cases of creation of new objects ?
Here is the link of the blog (its the second point) Link

A: Thumb rule in React is that state object is immutable, can not change it directly. So whenever you want to update state you always create new objects.
Looking at your code, new objects created in both the cases in onChange as well as in useEffects. But useEffects creates infinite loop as dependency gets changed whereas onChange does not create infinite loop as state update does not onChange again
if you want to avoid an infinite loop, I suggest 2 ways.

*

*Change the dependency array from [secret] --> [secret.value]

*Or have these 2 values value, countSecretsas 2 different state

In summary, when you have object as state then you should always create new object and set it. Where as for value based state,  react will take care of it.


text:
Q: Nomenclature in geodesy and its deviation When learning about deviation from geodesics I had these thoughts a long time ago about naming of associated concepts. The comments pertain to 2D surfaces embedded in 3D-space.

*

*Liouville called lines  deviant from geodesy as possessing a geodesic curvature property. It is the non- geodesic line that  should have a name to describe its deviation or difference.  A  line is identified  as a geodesic when this property vanishes. A geodesic has zero curvature or no curvature.  A non-geodesic has a property of geodesic curvature  deviation...and should that be not so called?

*Circles around a point equidistant from a central point P of geodesic polar coordinates description are called geodesic circles. In fact only the lines perpendicular these circles through P are geodesics. The "concentric" non-zero torsion circles ane not geodesics.
It is perhaps better to refer to them as involutes. In case of both plane and surfaces of revolution being orthogonal they respectively obey differential equations
$$ r \sin \psi  = C_1 ,\;   r \cos \psi= C_2 ,\;$$
where  $C_1,C_2$ are radii of circles to which variable tangents are drawn and from which variable start point taut strings are unwound, respectively in the plane.
Iirc, it was Leibnitz who suggested the involutes name.

*Buckminster Fuller called  his design/architecture  spherical domes as geodesic domes.

None of the reinforcements run along straight lines or great circles from end to end of the domes. An icosahedron is subdivided into $p$ parts and so we have $2p,4p, 20p$ subdivisions etc. One sees a series of breaks when going from one dome end to the other along many zigzag broken triangle edges. Only the tiny part segments are along geodesics/great circles.
A  polygon in a plane built out of   finitely many number of sides is not a geodesic in the plane, just as a circle is  geodesically not straight when assembled from infinitely many differential straight segments with curvature.
A  better word would perhaps be a tessellated dome.
Names started by original researcher gets stuck with time?
Seek your comments for a light vein discussion, so posed as a soft question.


text:
Q: Is it possible to embed different compilers to my application? I am trying to work on a desktop application using JavaFX/Java that requires me to compile and run c++ and Python code when it's requested, offline. I was wondering if this even possible?
How can this be done? Are there any libraries that can compile other languages' code and run them, which can be added in JavaFX/Java environment? Or do I need the user to install c++ compiler and Python in their machinees and then somehow integrate those tools in my application?
I would appreciate any help or insight.

A: Packaging a C++ or python compiler into a Java application is impractical. Your system would have to store, unpack and install each compiler into the local directory, resulting in a massive file size, it would also take a very long time.
The best method is to require that the user have those compilers installed or provide them with the install utilities so they can install them separately.
Once the compilers are installed you can get Java to run a shell script which builds and compiles the files.
I hope that solved your question, if you need any further clarification please feel free to reach out to me.
Sincerely,
Owen


text:
Q: parse a unix timestamp to date in emacs (elisp) Given 1525505457, return a date object(Sat May 05 2018 15:30:57 GMT+0800 (CST)) representing it.
http://ergoemacs.org/emacs/elisp_parse_time.html this article only tell how to format a date to unix time, but not otherwise.

A: Use the combination of decode-time & seconds-to-time, like this:
(decode-time (seconds-to-time 1525505457))
=> (57 30 9 5 5 2018 6 t 7200)

The same module, time-date.el has other functions for conversion into time object, like string, etc.:
(decode-time (date-to-time "2018-05-05T12:33:05Z"))
=> (5 33 14 5 5 2018 6 t 7200)


text:
Q: trigger result by column value in pandas Let us consider a dataframe with numbers distributed between -1 and 1. In this sequence there are two boundaries that change the state of system: -0.5 and 0.5. If the system cross 0.5, it will maintain its position until the system passes the -0.5 (and the oposite). A visual example is given in the following dataframe:
d = pd.DataFrame([[0.1,0.3,-0.1,-0.8,-0.7,0.2,0.9,0.4,-0.1,-0.8], [None, None, None, -1,-1,-1, 1, 1, 1, -1]]).T

How can we compute column 1 without using a for loop?

A: First, set up your conditions:
c1 = (df[0].lt(-0.5) & df[0].shift().gt(-0.5)) | (df[0].gt(-0.5) & df[0].shift().lt(-0.5))
c2 = (df[0].lt(0.5) & df[0].shift().gt(0.5)) | (df[0].gt(0.5) & df[0].shift().lt(0.5))

Then use np.select and ffill:
df.assign(out=np.select([c1, c2], [-1, 1], np.nan)).ffill()

     0  out
0  0.1  NaN
1  0.3  NaN
2 -0.1  NaN
3 -0.8 -1.0
4 -0.7 -1.0
5  0.2 -1.0
6  0.9  1.0
7  0.4  1.0
8 -0.1  1.0
9 -0.8 -1.0

The one thing this approach does not handle is what to do if both thresholds are crossed in a single step.  For example, if you go from -0.6 to 0.8, this will just default to the first condition.  You may want to adjust the conditions based on your need, but this will get you started.


text:
Q: HTML Agility pack - System.NullReferenceException: Object reference not set to an instance of an object I am using HTML Agility pack in Xamarin and I keep getting the following error. System.NullReferenceException: Object reference not set to an instance of an object.
The error is coming from the foreach loop and I saw that the nodes variable was null, but I don't know why. It is probably because my node selection is not right, but I don't how to fix it as I already tried different selections.
string source = getSource(url);
if (source == "") return;

HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(source);

HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//div[@id='events']");

var nodeText = "";

foreach (HtmlNode node in nodes)
{
    nodeText += node.InnerText;
}
lbl_geheel.Text = nodeText;

So I guess ("//div[@id='events']") is not right.
This is the HTML code that I am scraping:
<div id="events" class="">

From the following page: https://www.espn.in/football/scoreboard


text:
Q: putting a string of numbers in an array I'm trying to receive an integer of 40 characters as a string from the console and iterate over each element in that string and then save it as an element in an array of int's. this is not working and just returns 49 50 51 as array members.
public HugeInteger(string myString)
{
    for (int i = 0; i < 39; i++)
    {
        int t = Convert.ToInt16(myString[i]);
        this.myInteger[i] = t;
    }
}

A: Since you are trying to convert chars '0' .. '9' to integers, you just need to subtract the character code for '0' from each character, like so:
public HugeInteger(string myString)
{
    for (int i = 0; i < 39; i++)
    {
        char c = myString[i];

        // Remove the next `if` (and its body) if error checking is not required.

        if (c < '0' || c > '9')
            throw new InvalidOperationException("Non-digit in input");

        this.myInteger[i] = c - '0';
    }
}

This works because:

*

*The character codes for '0' to '9' are 48 .. 57

*If you subtract '0' from a character code, you are effectively subtracting 48 from it.

*Therefore subtracting '0' from a digit character will yield the int equivalent.

Note that there is no error checking in your loop, so if the string contains any non-digit characters, the result will be wrong!

A: If you want the string to be converted to an array i would suggest that you convert the string to char array and then convert back to int[] like below:
class Program
    {
        static void Main(string[] args)
        {
            string myString = "1231654165152112315461561561651561562165";
            var charArray = myString.ToCharArray();
            foreach (var item in charArray)
            {
                Console.WriteLine(item);

            }
            int[] myStringIntegers = Array.ConvertAll(charArray, c => (int)Char.GetNumericValue(c));
            Console.WriteLine(myStringIntegers.Length);

            int i = 0;
            foreach (var item in myStringIntegers)
            {
                Console.WriteLine("Value at pos("+i+") : " + item);
                i++;
            }
            Console.Read();
        }
    }

if you have multi digit numbers then i would say that you have the myString value separated by a comma ',' or space or whatever you like.
CAUTION : If the value is non-numeric then it will result in code failure. So you need to make a regex check or some sort of validation to address non-numeric inputs

A: If your input is like this :
"1 2 3 4"

You should split it with ' ' or else you should separate your numbers with  a separator.
        List<int> myInteger=new List<int>();
        public void HugeInteger(string myString)
        {
            foreach (string value in myString.Split(' '))
            {
                myInteger.Add(int.Parse(value));
            }

        }

Without seperator you should iterate by this way:
    foreach (char c in myString)
    {
        myInteger.Add(int.Parse(c.ToString()));
    }

A: Below is 2 simple ways of extracting an array of integers from a string.

*

*Converting char to int.

*Converting a split string to int.

This may not be the best or most elegant solution but you can get some idea on how you would want to approach your problem.
class Program
{
    static void Main(string[] args)
    {
        Console.Write("Input str: ");
        string str = Console.ReadLine();
        int[] numbers = StringToIntArray(str);
        foreach(int num in numbers)
        {
            Console.WriteLine(num);
        }
        Console.Write("Input str: ");
        str = Console.ReadLine();
        Console.Write("Input split char: ");
        ConsoleKeyInfo splitChar = Console.ReadKey();
        numbers = StringToIntArray(str, splitChar.KeyChar);
        Console.WriteLine();
        foreach (int num in numbers)
        {
            Console.WriteLine(num);
        }
        Console.ReadKey();
    }

    public static int[] StringToIntArray(string str, char? splitChar = null)
    {
        List<int> numbers = new List<int>();

        if (splitChar.HasValue)
        {
            string[] split = str.Split(splitChar.Value);

            foreach(string splitStr in split)
            {
                int parsedInt = 0;

                if (int.TryParse(splitStr, out parsedInt))
                {
                    numbers.Add(parsedInt);
                }
            }
        }
        else
        {
            foreach (char c in str)
            {
                int parsedInt = 0;

                if (int.TryParse(c.ToString(), out parsedInt))
                {
                    numbers.Add(parsedInt);
                }
            }
        }

        return numbers.ToArray();
    }
}

Output:

A: static void Main(string[] args)
        {
            Console.WriteLine("Input number");
            string myStr = Console.ReadLine();
            int[] intNums = new int[40];
            string flag = "";

            for (int i = 0; i < myStr.Length; i++)
            {

                int a = 1;
                flag = myStr.Substring(i, a);
                a = i;
                intNums[i] = Convert.ToInt32(flag);
                a = i;

            }

            foreach (var item in intNums)
            {

                if (item > 0)
                {
                    Console.Write(item+",");
                }

            }
            Console.ReadKey();
        }

IF you take an input you should sub-string the string, convert each part to an int, and then store in the array. Not sure a 40 character long integer would work just with the number bits even int64 can handle


text:
Q: Show that for any integer $n$ we have $1+2\left( abc \right)^{n}\ge a^{2n}+b^{2n}+c^{2n}$ Let be $a,b,c$ real numbers from $\left[ -1,1 \right]$ satisfying :
$$1+2abc\ge a^{2}+b^{2}+c^{2}$$
Show that  :
$$\forall n\in \mathbb{N} \ \ \ \ 1+2\left( abc \right)^{n}\ge a^{2n}+b^{2n}+c^{2n}$$
I tried using induction but I can't find  way to lower the term $a^{2n+2}+b^{2n+2}+c^{2n+2}$ properly.
Any suggestions or hints
This problem was on IMC 2010.

A: Let $ab\geq0.$
Thus, since the condition gives $$(ab-c)^2\leq(1-a^2)(1-b^2)$$ and we need to prove that
$$(a^nb^n-c^n)^2\leq(1-a^{2n})(1-b^{2n}),$$ by C-S we obtain:
$$(a^nb^n-c^n)^2=(ab-c)^2\left(\sum_{k-0}^{n-1}(ab)^{n-1-k}c^k\right)^2\leq$$
$$\leq(ab-c)^2\left(\sum_{k-0}^{n-1}(ab)^{k}\right)^2\leq(ab-c)^2\sum_{k=0}^{n-1}a^{2k}\sum_{k=0}^{n-1}b^{2k}\leq$$
$$\leq(1-a^2)(1-b^2)\sum_{k=0}^{n-1}a^{2k}\sum_{k=0}^{n-1}b^{2k}=(1-a^{2n})(1-b^{2n}).$$


text:
Q: Why does differential signaling send complementary signals instead of just pairing the input and ground voltage? I'm very new to EE, so please excuse me if this question is bad or has an obvious answer. After reading an overview of differential signalling, it left me wondering:
Why does differential signalling use "complementary" signals for D+ and D- instead of simply making D+ the input voltage and D- the "ground" voltage (or whatever the reference voltage is)? In other words, instead of:
D+ = +½ V_SIGNAL
D- = -½ V_SIGNAL
(as this site states is the case for differential signalling), why not simply make the signal pair as follows:
D+ = V_SIGNAL
D- = V_GROUND
External interference would still affect both wires the same, and the receiver could still do V_SIGNAL = (D+) - (D-) to remove common-mode interference and recover the original signal.

Update: This graphic I made should help clarify what I'm asking - Why is the DS sent as "complement" signals (like on the left) instead of sending the orignal signal "as is" and ground reference (like on the right)? Would external interference not be "induced" into the ground wire in the same way?

A: "Ground" as a concept needs some clarification. If you have just one signal line and one ground, then yes, it's hard to tell the difference. But if there's anything else going on, it matters.
All AC signalling involves current flow, even if it's being measured as a voltage on the receiver. At a minimum, you have to charge/discharge the parasitic capacitance of the receiver, and the signal wire will have a capacitance to ground as well. Note that the common mode behavior only holds if the two wires have the same length and are a constant distance from each other.
So if you have a signal wire and a ground wire, then the current in the signal wire must be matched by a corresponding current in the other direction in the ground wire. If you have lots of signals, the ground wire will contain a mashed-together copy of all the signals. Therefore it's advantageous for each signal to have its own ground. If you look at VGA, you'll notice that each signal gets its own ground because of this. If you look at 80 pin IDE, each pair of signals has a ground wire between it in the ribbon cable. Those are to prevent the signal wires inducing currents in each other ("crosstalk").
Once you've accepted that each signal must have its own matched ground, it's more natural to embrace the two as a matched pair, disconnect one from ground and connect the two of them together via a termination resistor network, and drive / read them as a differential signal.

A: The difference is that the differential lines are matched in common mode impedance (wrt ground), so that noise induced or capacitively coupled to the lines tends to be common mode noise and thus rejected.

A: A differentially driven cable creates no effective far field interference - what is created by one wire is cancelled by the other. Everyone so far is talking about susceptibility but the big deal to me is that two antiphase signals being carried along two wires (such as twisted pair) may generate local E and H fields but these fields effectively cancel out at some short distance away.
If you transmitted a single ended signal like this the far field interference would be significantly greater.

A:
why not simply make the signal pair as follows:
D+ = V_SIGNAL
D- = V_GROUND

I assume you mean that the V_GROUND signal would be connected to the circuit ground at one end or the other of the link. Maybe at both ends.
If you do this, you are no longer doing differential signalling, you are doing plain old single-ended or unbalanced signalling.
So the question you're really asking is, When do we use differential signals and when do we use single-ended signals?
Single-ended signals are used in lots of situations. Most traces on a PCB are typically unbalanced signals. For short connections with slowly-changing signals over a ribbon cable between boards, we often use single-ended signals. Even for long connections between boxes, unbalanced signals can still be used.
But to achieve good noise immunity and low radiated emissions, for reasonably fast signals over "long" distances, unbalanced signals typically require a shielded cable, such as coax.
But coax is more expensive than the now-ubiquitous unshielded twisted pair (UTP) cable.
So we'd rather, if we can get away with it, use UTP.
Now, if we drive a signal on one line of a UTP connection, we can, like you say, eliminate common-mode interference by receiving the signal at the other end with a differential receiver (V_SIGNAL = V+ - V-). But look at the signal we're sending out on the cable. The signal we're generating has a substantial common mode component.
V_CM = 0.5 * (D+ + D-)
Because of this common mode signal, our system is likely to radiate strongly, which will make it difficult to sell in most jurisdictions.
So really, we are using differential signalling to allow us to use low-cost UTP wiring with reasonable (hopefully conforming to standards) radiated emissions. In some cases we might still prefer unbalanced signals on shielded cables when the system requirements (very low emissions or very stringent immunity requirements) justify the cost.
Even over short distances within a box, we might use differential signalling on untwisted cable (such as common ribbon cable) to reduce emissions at a lower cost than using shielded cables.
Edit

What is the typical return path for current driven on the differential pair?

The currents on the two conductors of a differential pair (for a differential signal) are equal and opposite. You could say that each one of the conductors is the return path for the other one, or you could say that the net current is zero, so no return path is necessary.
Of course if you launch a common-mode signal on the differential pair, its current will need to return somehow. If there's no designed return path for the common-mode signal, it could travel over a large loop and cause significant EMC issues.

What, exactly, about the differential pair signalling causes the EMR cancellation?

*

*Because the two wires are closely coupled to each other, there is a small loop area between them and so the possibility to generate magnetic fields is small. But you could achieve the same thing with a well-designed single-ended transmission line.

*In twisted pair, you have alternating loops where the magnetic field will be in opposite directions. In the far field, the contributions from the alternating loops will tend to cancel each other out, resulting in very little radiation. There will also be a similar effect for susceptabilty.

A: What you're missing is the noise immunity.
Say you have 2 lines, one at +5V and one at -5V.  The difference between them is 10V.
Now say 1V of noise gets induced into each line equally.  The +5V line becomes +6V, and the -5V line becomes -4V (5 + 1 = 6, -5 + 1 = -4).
The difference between the two lines is still 10V.  The noise has been cancelled out and the original signal is still intact.
That is the main point of differential signalling.


text:
Q: How to use multiple, but a limited number of threads in Python to process a list I have a dataframe, several thousand rows in length, that contains two pairs of GPS coordinates in one of the columns, with which I am trying to calculate the drive time between those coordinates. I have a function that takes in those coordinates and returns the drive time and it takes maybe 3-8 seconds to calculate each entry. So, the total process can take quite a while. What I'd like to be able to do is: using maybe 3-5 threads, iterate through the list and calculate the drive time and move on to the next entry while the other threads are completing and not creating more than 5 threads in the process. Independently, I have everything working - I can run multiple threads, I can track the thread count and wait until the max number of allowed threads drops below limit until the next starts and can iterate the dataframe and calculate the drive time. However, I'm having trouble piecing it all together. Here's an edited, slimmed down version of what I have.
import pandas
import threading
import arcgis

class MassFunction:
    #This is intended to keep track of the active threads
    MassFunction.threadCount = 0

    def startThread(functionName,params=None):
        #This kicks off a new thread and should count up to keep track of the threads
        MassFunction.threadCount +=1

        if params is None:
            t = threading.Thread(target=functionName)
        else:
            t = threading.Thread(target=functionName,args=[params])
        t.daemon = True
        t.start()

class GeoAnalysis:
    #This class handles the connection to the ArcGIS services
    def __init__(self):
        super(GeoAnalysis, self).__init__()
        self.my_gis = arcgis.gis.GIS("https://www.arcgis.com", username, pw)

    def drivetimeCalc(self, coordsString):
        #The coords come in as a string, formatted as 'lat_1,long_1,lat_2,long_2'
        #This is the bottleneck of the process, as this calculation/response
        #below takes a few seconds to get a response
        points = coordsString.split(", ")
        route_service_url = self.my_gis.properties.helperServices.route.url
        self.route_layer = arcgis.network.RouteLayer(route_service_url, gis=self.my_gis)
        point_a_to_point_b = "{0}, {1}; {2}, {3}".format(points[1], points[0], points[3], points[2])
        result = self.route_layer.solve(stops=point_a_to_point_b,return_directions=False, return_routes=True,output_lines='esriNAOutputLineNone',return_barriers=False, return_polygon_barriers=False,return_polyline_barriers=False)
        travel_time = result['routes']['features'][0]['attributes']['Total_TravelTime']
        #This is intended to 'remove' one of the active threads
        MassFunction.threadCount -=1
        return travel_time

class MainFunction:
    #This is to give access to the GeoAnalysis class from this class
    GA = GeoAnalysis()

    def closureDriveTimeCalc(self,coordsList):
        #This is intended to loop in the event that a fifth loop gets started and will prevent additional threads from starting
        while MassFunction.threadCount > 4:
            pass
        MassFunction.startThread(MainFunction.GA.drivetimeCalc,coordsList)

    def driveTimeAnalysis(self,location):
        #This reads a csv file containing a few thousand entries.
        #Each entry/row contains gps coordinates, which need to be
        #iterated over to calculate the drivetimes
        locationMemberFile = pandas.read_csv(someFileName)
        #The built-in apply() method in pandas seems to be the
        #fastest way to iterate through the rows

        locationMemberFile['DRIVETIME'] = locationMemberFile['COORDS_COL'].apply(self.closureDriveTimeCalc)

When I run this right now, using VS Code, I can see the thread counts go up into the thousands in the call stack, so I feel like it is not waiting for the thread to finish and adding/subtracting from the threadCount value.  Any ideas/suggestions/tips would be much appreciated.
EDIT: Essentially my problem is how do I get the travel_time value back so that it can be placed into the dataframe. I currently have no return statement for closureDriveTimeCalc function, so while the function runs correctly, it doesn't send any information back into the apply() method.

A: Rather than do this in an apply, I'd use multiprocessing Pool.map:
from multiprocessing import Pool

with Pool(processes=4) as pool:
    locationMemberFile['DRIVETIME'] = pool.map(self.closureDriveTimeCalc, locationMemberFile['COORDS_COL']))


text:
Q: MS graph api schema extension filter bug with outlook resources (messages, events, contacts) When trying to filter for a custom created schema extension:
https://graph.microsoft.com/v1.0/me/events?$filter=(<schemaId>/<key> eq '<value>')

the error message we get is:
"message": "Could not find a property named 'e2_<ourTenantID>_<schemaId>' on type 'Microsoft.OutlookServices.Event'"

The problem is that before performing search, the API prepends tenantID to schema ID, thus failing to recognize the property. It seems that graph API performs search using their own internal schema ID.
Interesting thing is, that when searching for a non-existing schema, the tenantID is not added.
The problem persists when testing to filter messages, events and contacts.
Our schema extension creation JSON:
{
    "description": "Extension to help avoid duplicates",
    "targetTypes": [
        "Contact",
        "Message",
        "Event"
    ],
    "properties": [
        {
            "name": "UniqueId",
            "type": "String"
        }
    ],
    "status": "InDevelopment",
    "owner": "<appID>",
    "id": "<name>",
    "@odata.type": "#microsoft.graph.ComplexExtensionValue"
}


text:
Q: SWFUpload gives the error "Invalid function name: ReturnUploadStart" in Firefox only I'm using SWFUpload to upload files on my website. It works fine in all browsers except Firefox, where it always gives the javascript error Invalid function name: ReturnUploadStart as soon as the upload starts.
I'm using SWFUpload 2.2.0 Beta 2 with jquery-asyncUpload-0.1.js. I'm using Firefox 6.0.2
What gives?

A: This error occurs in Firefox if there is no css to style the progress bar. Other browsers seem to work just fine, showing the text "Uploading..." instead, but for some reason Firefox breaks.
Try using this css to get you started:
DIV.ProgressBar { width: 100px; padding: 0; border: 1px solid black; margin-right: 1em; height:.75em; margin-left:1em; display:-moz-inline-stack; display:inline-block; zoom:1; *display:inline; }
DIV.ProgressBar DIV { background-color: Green; font-size: 1pt; height:100%; float:left; }
SPAN.asyncUploader OBJECT { position: relative; top: 5px; left: 10px; }

A: This worked for me:

*

*included the CSS as in teedyay's answer

*upgrade swfupload to latest stable (2.2.0 at time of writing)

*only manipulated the flash video (upload button) in the upload completed event (using a jquery hide())


text:
Q: Difficulty reversing fragment animation with backstack I am currently trying to implement a custom animation when changing fragments.
The custom animation only works one way and does not work when back is pressed.  On back press the correct fragment is shown but with no animation.
My code for the fragment transaction:
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right, R.anim.slide_in_right, R.anim.slide_out_left);
transaction.replace(R.id.frame_container, fragment, FragmentTag);
transaction.addToBackStack(null);
transaction.commit();

My code for the anim XML files:
//Slide in left
<?xml version="1.0" encoding="utf-8"?>
<set>
    <objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
        android:propertyName="x"
        android:valueType="floatType"
        android:valueFrom="-1280"
        android:valueTo="0"
        android:duration="500"/>
</set>

//Slide out right
<?xml version="1.0" encoding="utf-8"?>
<set>
    <objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
        android:propertyName="x"
        android:valueType="floatType"
        android:valueFrom="0"
        android:valueTo="-1280"
        android:duration="500"/>
</set>

//Slide in Right
<?xml version="1.0" encoding="utf-8"?>
<set>
    <objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
        android:propertyName="x"
        android:valueType="floatType"
        android:valueFrom="-1280"
        android:valueTo="0"
        android:duration="500"/>
</set>

//Slide out Left
<?xml version="1.0" encoding="utf-8"?>
<set>
    <objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
        android:propertyName="x"
        android:valueType="floatType"
        android:valueFrom="0"
        android:valueTo="-1280"
        android:duration="500"/>
</set>

The code for onBackPressed()
@Override
public void onBackPressed()
{
    super.onBackPressed();
}

Any ideas where I'm going wrong? Thanks for any help

A: Use this code for onBackPressed:
if (getFragmentManager().getBackStackEntryCount() > 0) {
            getFragmentManager().popBackStack();
        } else {
            super.onBackPressed();
        }


text:
Q: Fixing slow initial load for IIS IIS has an annoying feature for low traffic websites where it recycles unused worker processes, causing the first user to the site after some time to get an extremely long delay (30+ seconds).
I've been looking for a solution to the problem and I've found these potential solutions.
A. Use the Application Initialization plugin
B. Use Auto-Start with .NET 4
C. Disable the idle-timeout (under IIS Reset)
D. Precompile the site
I'm wondering which of these is preferred, and more importantly, why are there so many solutions to the same problem? (My guess is they aren't, and I'm just not understanding something correctly).
Edit
Performing C seems to be enough to keep my site warmed up, but I've discovered that the real root of my site's slowness has to do with Entity Framework, which I can't seem to figure out why it's going cold. See this question, which unfortunately hasn't been answered yet has been answered!
I eventually just had to make a warm up script to hit my site occasionally to make sure it stayed speedy.

A: Options A, B and D seem to be in the same category since they only influence the initial start time, they do warmup of the website like compilation and loading of libraries in memory.
Using C, setting the idle timeout, should be enough so that subsequent requests to the server are served fast (restarting the app pool takes quite some time - in the order of seconds).
As far as I know, the timeout exists to save memory that other websites running in parallel on that machine might need. The price being that one time slow load time.
Besides the fact that the app pool gets shutdown in case of user inactivity, the app pool will also recycle by default every 1740 minutes (29 hours).
From technet:

Internet Information Services (IIS) application pools can be
  periodically recycled to avoid unstable states that can lead to
  application crashes, hangs, or memory leaks.

As long as app pool recycling is left on, it should be enough.
But if you really want top notch performance for most components, you should also use something like the Application Initialization Module you mentioned.

A: Writing a ping service/script to hit your idle website is rather a best way to go because you will have a complete control. Other options that you have mentioned would be available if you have leased a dedicated hosting box.
In a shared hosting space, warmup scripts are the best first level defense (self help is the best help). Here is an article which shares an idea on how to do it from your own web application.

A: I'd use B because that in conjunction with worker process recycling means there'd only be a delay while it's recycling. This avoids the delay normally associated with initialization in response to the first request after idle. You also get to keep the benefits of recycling.

A: See this article for tips on how to help performance issues.  This includes both performance issues related to starting up, under the "cold start" section.  Most of this will matter no matter what type of server you are using, locally or in production.
https://blogs.msdn.microsoft.com/b/mcsuksoldev/2011/01/19/common-performance-issues-on-asp-net-web-sites/

If the application deserializes anything from XML (and that includes web services…) make sure SGEN is run against all binaries involved in deseriaization and place the resulting DLLs in the Global Assembly Cache (GAC). This precompiles all the serialization objects used by the assemblies SGEN was run against and caches them in the resulting DLL. This can give huge time savings on the first deserialization (loading) of config files from disk and initial calls to web services.
http://msdn.microsoft.com/en-us/library/bk3w6240(VS.80).aspx

If any IIS servers do not have outgoing access to the internet, turn off Certificate Revocation List (CRL) checking for Authenticode binaries by adding generatePublisherEvidence="false" into machine.config. Otherwise every worker processes can hang for over 20 seconds during start-up while it times out trying to connect to the internet to obtain a CRL list.
http://blogs.msdn.com/amolravande/archive/2008/07/20/startup-performance-disable-the-generatepublisherevidence-property.aspx

http://msdn.microsoft.com/en-us/library/bb629393.aspx

Consider using NGEN on all assemblies. However without careful use this doesn't give much of a performance gain. This is because the base load addresses of all the binaries that are loaded by each process must be carefully set at build time to not overlap. If the binaries have to be rebased when they are loaded because of address clashes, almost all the performance gains of using NGEN will be lost.
http://msdn.microsoft.com/en-us/magazine/cc163610.aspx

A: A good option to ping the site on a schedule is to use Microsoft Flow, which is free for up to 750 "runs" per month. It is very easy to create a Flow that hits your site every hour to keep it warm. You can even work around their limit of 750 by creating a single flow with delays separating multiple hits of your site.
https://flow.microsoft.com

A: Web Hosting Challenge
You have to remember that none of the machine configuration options are available if you are hosted on a shared server as many of us (smaller companies and individuals) are.
ASP.NET MVC Overhead
My site takes at least 30 seconds when it hasn't been hit in over 20 minutes (and the web app has been stopped).  It is terrible.
Another Way to Test Performance
There's another way to test if it is your ASP.NET MVC start up or something else.  Drop a normal HTML page on your site where you can hit it directly.
If the problem is related to ASP.NET MVC start up then the HTML page will render almost immediately even when the web app hasn't been started.
That's how I first recognized that the problem was in the ASP.NET MVC startup.
I loaded an HTML page at any time and it would load blazing fast.  Then, after hitting that HTML page I'd hit one of my ASP.NET MVC URLs and I'd get the Chrome message "Waiting for raddev.us..."
Another Test With Helpful Script
After that I wrote a LINQPad (check out http://linqpad.net for more) script that would hit my web site every 8 minutes (less than the time for the app to unload -- which should be 20 minutes) and I let it run for hours.
While the script was running I hit my web site and every time my site came up blazingly fast.  This gives me a good idea that most likely the slowness I was experiencing was because of ASP.NET MVC startup times.
Get LinqPad and you can run the following script -- just change the URL to your own and let it run and you can test this easily.
Good luck.
NOTE: In LinqPad you'll need to press F4 and add a reference to System.Net to add the library which will retrieve your page.
ALSO : make sure you change the String URL variable to point at a URL that will load a route from your ASP.NET MVC site so the engine will run.
System.Timers.Timer webKeepAlive = new System.Timers.Timer();
Int64 counter = 0;
void Main()
{
    webKeepAlive.Interval = 5000;
    webKeepAlive.Elapsed += WebKeepAlive_Elapsed;
    webKeepAlive.Start();
}

private void WebKeepAlive_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    webKeepAlive.Stop();
    try
    {
        // ONLY the first time it retrieves the content it will print the string
        String finalHtml = GetWebContent();
        if (counter < 1)
        {
            Console.WriteLine(finalHtml);
        }
        counter++;
    }
    finally
    {
        webKeepAlive.Interval = 480000; // every 8 minutes
        webKeepAlive.Start();
    }
}

public String GetWebContent()
{
    try
    {
    String URL = "http://YOURURL.COM";
    WebRequest request = WebRequest.Create(URL);
    WebResponse response = request.GetResponse();
    Stream data = response.GetResponseStream();
    string html = String.Empty;
    using (StreamReader sr = new StreamReader(data))
    {
        html = sr.ReadToEnd();
    }
    Console.WriteLine (String.Format("{0} : success",DateTime.Now));
    return html;
    }
    catch (Exception ex)
    {
        Console.WriteLine (String.Format("{0} -- GetWebContent() : {1}",DateTime.Now,ex.Message));
        return "fail";
    }
}

A: I was getting a consistent 15 second delay on the first request after 4 minutes of inactivity. My problem was that my app was using Windows Integrated Authentication to SQL Server and the service profile was in a different domain than the server. This caused a cross-domain authentication from IIS to SQL upon app initialization - and this was the real source of my delay. I changed to using a SQL login instead of windows authentication. The delay was immediately gone. I still have all the app initialization settings in place to help improve performance but they may have not been needed at all in my case.


text:
Q: How to obtain a BigInt random number within a range in julia? I need to obtain a random number between 1 and a BigInt in Julia, but I couldn't find out in the documentation how this can be done. The code below is what I thought would work:
julia> rand(BigInt(1):BigInt(2^1000))
ERROR: integer division error
 in randu at random.jl:158
 in rand at random.jl:178
 in rand at random.jl:187

edit: GregS mentioned 2^1000 would wrap around zero. Actually, 2^1000 results in zero, so the code above is wrong. But using BigInt(2)^1000 doesn't work:
julia> rand(BigInt(1):BigInt(2)^1000)
ERROR: InexactError()
 in convert at gmp.jl:108
 in colon at range.jl:38

julia> rand(BigInt(1):BigInt(2)^BigInt(1000))
ERROR: InexactError()
 in convert at gmp.jl:108
 in colon at range.jl:38

What is the fastest way to get this done? (Thee numbers should be uniformly distributed).
Thanks!

A: This is available after all if you use ccall.  I'm sure at some point it will be eazy, but here's a way to do this now, I did not find a way to use it from base, but will amend if it things change.  There are 2 calls that need to be made for this to work.  From gmp's docs, I chose mpz_urandomm
GMP Support

— Function: void mpz_urandomm (mpz_t rop, gmp_randstate_t state, const mpz_t n)
    Generate a uniform random integer in the range 0 to n-1, inclusive.
The variable state must be initialized by calling one of the gmp_randinit functions (Random State Initialization) before invoking this function.

You must first initialize the random number generator, I did this not optimally, will update with something refined.

— Function: void gmp_randinit_default (gmp_randstate_t state)
    Initialize state with a default algorithm. This will be a compromise between speed and randomness, and is recommended for applications with no special requirements. Currently this is gmp_randinit_mt.

ccall method
Initialize RNG
Not having an elegant way to declare gmp_randstate_t, just declare a big buffer.  This is important otherwise a segfault occurs.
julia> buffer = Array(Uint8,32);
julia> ccall((:__gmp_randinit_default,:libgmp),Void,(Ptr{Uint8},),buffer);

Generate Random Numbers
Create BigInt, x to store the result
julia> x = BigInt(0)
0

Set y to MaxRange

julia> y = BigInt(2)^1000
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376

Generate random x
julia> ccall((:__gmpz_urandomm,:libgmp),Void,(Ptr{BigInt},Ptr{Uint8},Ptr{BigInt}),&x,buffer,&y)

verify

julia> x
    9301165293246235069759966068146313776551258669855356477271940698500929939755418247622530571466332330697816620308003246225290293476785304004840090056840661553451916748315356563734257724978000166406621823207925733850455027807451108123161768212073821382033500073069184011344280494573919716117539236653172

etc...
julia> ccall((:__gmpz_urandomm,:libgmp),Void,(Ptr{BigInt},Ptr{Uint8},Ptr{BigInt}),&x,buffer,&y)

julia> x
    5073599723113217446035606058203362324610326948685707674578205618189982426100515602680640230141018758328161278469759835943678360952795440512680380424413847653984694781421269745198616340362470820037933917709243387214511018480191308767310495781355601069937334945556566243556239048498564021992916827796124

A: This is an old post, but Julia now makes it easy to solve this question.
For example, using Julia 1.1.0 (I have customized my Julia REPL for a project I am working on called JulieGo.  The answer should work the same in the regular Julia REPL.)
JulieGo>VERSION
v"1.1.0"

# Set seed to get same results again.
JulieGo>rng_info = Random.seed!(12345);

# Here is an answer in Julia 1.1.0.
JulieGo>r1 = rand(big"1":big"2"^1000)
8986172793045621030349078950793778042482316869955566599310906000510726536023373350273552788410494562
1437227128958537257991121543058284731429268230113459330352619981122924349300809967077942239392386680
0757367867423923215806277494619337596597641816501707643360907546040909561196900772512609868177829183

# Print result in an easy to read format.
JulieGo>using Printf

JulieGo>@printf "%0.3E" float(r1)
8.986E+299

# Reseed the RNG.
JulieGo>rng_info = Random.seed!(12345);

# Try again.
JulieGo>r2 = rand(big"1":big"2"^1000)
8986172793045621030349078950793778042482316869955566599310906000510726536023373350273552788410494562
1437227128958537257991121543058284731429268230113459330352619981122924349300809967077942239392386680
0757367867423923215806277494619337596597641816501707643360907546040909561196900772512609868177829183

# The result is the same.
JulieGo>@printf "%0.3E" float(r2)
8.986E+299

JulieGo>r1 == r2
true

# This also works.
# Reseed the RNG.
JulieGo>rng_info = Random.seed!(12345);

# Only the 2 needs to be specified explicitly as a big int.
JulieGo>r3 = rand(1:big"2"^1000)
898617279304562103034907895079377804248231686995556659931090600051072653602337335027355278841049456
143722712895853725799112154305828473142926823011345933035261998112292434930080996707794223939238668
075736786742392321580627749461933759659764181650170764336090754604090956119690077251260986817782918

JulieGo>r3 == r2
true


text:
Q: Angular2 AOT Compilation with static external js file Directed by the answer to my question about Server-side rendering, I'm looking at implementing AOT compilation in my Angular2 app.
A bit of background to the problem I'm having: we have a build running in Visual Studio Online, which runs webpack etc, and ships a functioning webapp. We then have a release in VSO to different environments which puts some values (environment, base urls, important keys) into an env-config.js file. This env-config.js file is not bundled and packaged within the app, but we access it as a global js variable within our Angular code.
env-config.js
var envConfig = {
    'environment': 'local',
    'baseApiUrl': 'localhost:5555',
}

Within app-config.ts, we access envConfig from the window object, store this as a constant, and export the constant AppConfig, which we then register in app.module using an OpaqueToken.
app-config.ts
export function getEnvConfig(): IAppEnvConfig {
    if (window == null) {
        return {
            'environment': '',
            'baseApiUrl': ''
        };
    }
    else {
        return (window as any).envConfig;
    }
}

export const _envConfig: IAppEnvConfig = getEnvConfig();

export const AppConfig: IAppConfig = {
    applicationName: 'Web Application',
    environment: _envConfig.environment,
    baseApiUrl: _envConfig.baseApiUrl,
    otherSetting: 'someValue'
}

This works really well running in the browser with the JIT compiler. I'm following a combination of this and this and other tutorials to enable AOT compilation.
Running ngc gives me the following error:
"node_modules/.bin/ngc" -p app/tsconfig-aot.json Error encountered
resolving symbol values statically. Calling function 'getEnvConfig',
function calls are not supported. Consider replacing the function or lambda
with a reference to an exported function, resolving symbol AppConfig

I added the check for window == null in getEnvConfig() because I don't think window will be available during non-browser compilation. If getEnvConfig() does anything other than return an empty IAppEnvConfig object I get the ngc error.
I have done a lot of Googling, but have found nothing specific to my issue, other than generic answers pointing towards using a factory function to create a new instance of a class, which I've tried to do here.
Sorry if that doesn't make much sense - please feel free to get clarification/tell me that I'm doing something incredibly stupid.
Thanks in advance,
Alex

A: I'm not sure if this solution will fit you, but I post it any way. I faced the same issue and foud the problem was quite easy to solve. Simply put your functions in a class. Something like this:
export class AppConfig {
  _envConfig = AppConfig.getEnvConfig();
  AppConfig = {
    applicationName: 'Web Application',
    environment: this._envConfig.environment,
    baseApiUrl: this._envConfig.baseApiUrl,
    otherSetting: 'someValue'
  };

  static getEnvConfig() {
    if (window == null) {
      return {
        'environment': '',
        'baseApiUrl': ''
      };
    } else {
      return (window as any).envConfig;
    }
  }

  private constructor(){}
}


text:
Q: How do I set a default child route with react-router? I'm using React-Router 1.0.0-rc3, but I'm having trouble understanding how I can set a default route for a child route.
I have a rootRoute setup as follows:
var rootRoute = {
    component: 'div',
    childRoutes: [{
        path: '/',
        component: require('./components/Console'),
        childRoutes: [
            require('./routes/FileManager'),
            require('./routes/UserManager')
        ]
    }]
};

React.render(<Router routes={rootRoute}/>, document.body);

My Console root component is setup as follows:
module.exports = React.createClass({

    render: function () {
        return (
            <div className="console">
                <ConsoleHeader/>
                {this.props.children}
            </div>
        );
    }

});

My FileManager route definition is as follows:
module.exports = {
    path: 'files',

    getComponent: function (location, callback) {
        callback(null, require('./components/FileManager'));
    }
};

My objective is for the Console component to always be loaded while any of its child routes are active. It will contain a child component based on the child route. I want the child components to be loaded asynchronously. I want the FileManager child route to also be default if no child route has been selected.
So the following two routes would both select the FileManager component:
/
/files

I understand one way of doing this would be to do something like this:
{this.props.children || require('./routes/FileManager/components/FileManager')}

This doesn't feel right, however. I don't want to take that path to the FileManager component out of my route definition file.
Perhaps I could create a default child route entry like:
{
    path: '/', //Or maybe empty string here since it concatenates to the parent?
    getComponent: function (location, callback) {
        callback(null, require('./components/FileManager'));
    }
}

But this essentially the same route definition I already have except with a different path.
So it would seem there must be a cleaner way of specifying the default child route, but I can't figure it out even after browsing the API documentation.
How can I make the FileManager child route the default child route?

A: I'd strongly recommend using JSX for your routes. It will make things much more easy to follow.
Below is an example.
var ConsoleApp = require('./components/Console');
var FileManager = require('./routes/FileManager');
var UserManager = require('./routes/UserManager');
var RootDefault = require(./routes/SomeComponent);

var rootRoute = (
  <Route path="/" component={ConsoleApp}>
    <IndexRoute component={RootDefault}/>
    <Route path="file-manager" component={FileManager}/>
    <Route path="user-manager" component={UserManager}/>
  </Route>
)


text:
Q: Invariant Violation: requireNativeComponent: "RNGADBannerView" was not found in the UIManager I recently installed admob for react-native.but i m getting an error "RNGADBannerView" was not found in the UIManager".I don't know what that supposed to mean?
_can anyone help?_
import {AdMobBanner} from 'react-native-admob';

  export default class Home extends Component{
   render(){
    return <View>
        <Text>helo</Text>
        <AdMobBanner
            adSize="fullBanner"
            adUnitID="my_id"
            onAdFailedToLoad={error => console.error(error)}
        />
    </View>
}

dependencies:
   "react": "16.4.1",
   "react-native": "0.56.0",
   "react-native-admob": "^2.0.0-beta.5",
   "react-native-fbsdk": "^0.7.0",
    "react-navigation": "^2.6.2"

A: It seems that you did not link the library to your project.
Using react-native link in the root directory of your project should solve the problem.

A: I was facing the similar issue Invariant Violation: requireNativeComponent:xxx not found in UIManager
Issue seems to be the dependent is not linked to your project, hence 2 solutions for this issue (depending on your 'dependency')

*

*run react-native link in terminal/cmd at your project path.

*Manual append the dependency in your MainApplication.java as shown below:

@Override
    protected List<ReactPackage> getPackages() {

      @SuppressWarnings("UnnecessaryLocalVariable")
      List<ReactPackage> packages = new PackageList(this).getPackages();
      // Packages that cannot be autolinked yet can be added manually here, for
      packages.add(new RNFirebaseAnalyticsPackage());
      packages.add(new xxxPackage());
    }


text:
Q: Probability of two different groups of students passing an exam A group of $60$ students pass their exam with a probability of $0.3$. Another group of $70$ students pass their exam with a probability of $0.5$. What is the expected number of students who will pass their exams? What is the probability of one student passing her/his exam?
So far the only way to approach the problem I can think of is $0.3 \cdot 60 + 0.5 \cdot 70 = 53$ will pass their exams. Therefore, $\frac{53}{(60+70)} = 0.4$ is the probability of one student passing her/his exam.
However, the groups have different number of people. I am not sure if this makes one of the group a more reliable prediction of the outcome.


text:
Q: React fails on build Having my app running with "npm start" works well.
When I build it with "npm run build" and point the server to the build-folder, it fails.
The error in console says:
Uncaught TypeError: Cannot set property 'executeGet' of undefined

I have a file common.js that includes some functions. The one that errored is declared this way:
const executeGet = async (url, options) => {
    return 'something';
}
module.exports.executeGet = executeGet;

Well, it sucks that with npm run it works while when serving the build folder it fails. But what I understand webpack is involved when building and that's maybe there something goes wrong.
I have tried modifying the declaration (but still getting the same error):
module.exports.executeGet = async (url) => {
    return 'something';
}

Or even this way (but it then says: "Uncaught ReferenceError: exports is not defined")
exports.executeGet = async (url) => {
    return 'something';
}

My package.json looks like this:
{
  "dependencies": {
    "@testing-library/jest-dom": "^5.11.6",
    "@testing-library/react": "^11.2.2",
    "@testing-library/user-event": "^12.5.0",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-images-uploader": "^1.2.0-rc1",
    "react-router-dom": "^5.2.0",
    "react-scripts": "4.0.1",
    "react-toastify": "^6.2.0",
    "web-vitals": "^0.2.4"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

Looking in chrome dev-tools, under "Sources" I can see that there is this line:
e.exports.executeGet = r

which is actually undefined. I don't really know what the problem is. Is this about the syntax used to declare exported functions? Which does not relaly work when webpack creates the build?

A: Since you're using react-scripts, you need to export things using the correct ES Modules export/import syntax, not CommonJS module.exports:
const executeGet = async (url, options) => {
    return 'something';
}
export executeGet;

Similarly, if you happen to be using require(), you shouldn't; instead use import.