text:
Q: Serious Memory Leak When Iteratively Parsing XML Files Context
When iterating over a set of Rdata files (each containing a character vector of HTML code) that are loaded, analyzed (via XML functionality) and then removed from memory again, I experience a significant increase in an
R process' memory consumption (killing the process eventually).
It just seems like

*

*freeing objects via free(),

*removing them via rm() and

*running gc()
do not have any effects, so the memory consumption cumulates until there's no more memory left.
EDIT 2012-02-13 23:30:00
Thanks to valuable insight shared by the author and maintainer of package XML, Duncan Temple Lang (again: I really appreciate it very much!), the problem seems to be closely related to the way external pointers are freed and how garbage collection is handled in the XML package. Duncan issued a bug-fixed version of the package (3.92-0) that consolidated certain aspects of parsing XML and HTML and features an improved garbage collection where it's not necessary anymore to explicitly free the object containing the external pointer via free(). You find the source code and a Windows binary at Duncan's Omegahat website.

EDIT 2012-02-13 23:34:00
Unfortunately, the new package version still does not seem to fix the issues I'm encountering in the little little example that I've put together. I followed some suggestion and simplified the example a bit, making it easier to grasp and to find the relevant functions where things seem to go wrong (check functions ./lib/exampleRun.R and .lib/scrape.R).

EDIT 2012-02-14 15:00:00
Duncan suggested trying to force to free the parsed document explicitly via .Call("RS_XML_forceFreeDoc", html). I've included a logical switch in the example (do.forcefree in script ./scripts/memory.R) that, if set to TRUE, will do just that. Unfortunately, this made my R console crash. It'd be great if someone could verify this on their machine! Actually, the doc should be freed automatically when using the latest version of XML (see above). The fact that it isn't seems to be a bug (according to Duncan).

EDIT 2012-02-14 23:12:00
Duncan pushed yet another version of XML (3.92-1) to his Omegahat website Omegahat website. This should fix the issue in general. However, I seem to be out of luck with my example as I still experience the same memory leakage.

EDIT 2012-02-17 20:39:00 > SOLUTION!
YES! Duncan found and fixed the bug! It was a little typo in a Windows-only script which explained why the bug didn't show in Linux, Mac OS etc. Check out the latest version 3.92-2.! Memory consumption is now as constant as can be when iteratively parsing and processing XML files!
Special thanks again to Duncan Temple Lang and thanks to everyone else that responded to this question!

>>> LEGACY PARTS OF THE ORIGINAL QUESTION <<<
Example Instructions (edited 2012-02-14 15:00:00)

*

*Download folder 'memory' from my Github repo.

*Open up the script ./scripts/memory.R and set a) your working directory at line 6, b) the example scope at line 16 as well c) whether to force the freeing of the parsed doc or not at line 22. Note that you can still find the old scripts; they are "tagged" by an "LEGACY" at the end of the filename.

*Run the script.

*Investigate the latest file ./memory_<TIMESTAMP>.txt to see the increase in logged memory states over time. I've included two text files that resulted from my own test runs.

Things I've done with respect to memory control

*

*making sure a loaded object is removed again via rm() at the end of each iteration.

*When parsing XML files, I've set argument addFinalizer=TRUE, removed all R objects that have a reference to the parsed XML doc before freeing the C pointer via free() and  removing the object containing the external pointer.

*adding a gc() here and there.

*trying to follow the advice in Duncan Temple Lang's notes on memory management when using its XML package (I have to admit though that I did not fully comprehend what's stated there)

EDIT 2012-02-13 23:42:00:
As I pointed out above, explicit calls to free() followed by rm() should not be necessary anymore, so I commented these calls out.
System Info

*

*Windows XP 32 Bit, 4 GB RAM

*Windows 7 32 Bit, 2 GB RAM

*Windows 7 64 Bit, 4 GB RAM

*R 2.14.1

*XML 3.9-4

*XML 3.92-0 as found at http://www.omegahat.org/RSXML/
Initial Findings as of 2012-02-09 01:00:00

*

*Running the webscraping scenario on several machines (see section "System Info" above) always busts the memory consumption of my R process after about 180 - 350 iterations (depending on OS and RAM).

*Running the plain rdata scenario yields constant memory consumption if and only if you set an explicit call to the garbage collector via gc() in each iteration; else you experience the same behavior as in the webscraping scenario.

Questions

*

*Any idea what's causing the memory increase?

*Any ideas how to work around this?

Findings as of 2012-02-013 23:44:00
Running the example in ./scripts/memory.R on several machines (see section "System Info" above) still busts the memory consumption of my R process after about 180 - 350 iterations (depending on OS and RAM).
There's still an evident increase in memory consumption and even though it may not appear to be that much when just looking at the numbers, my R processes always died at some point due to this.
Below, I've posted a couple of time series that resulted from running my example on a WinXP 32 Bit box with 2 GB RAM:
TS_1 (XML 3.9-4, 2012-02-09)
29.07
33.32
30.55
35.32
30.76
30.94
31.13
31.33
35.44
32.34
33.21
32.18
35.46
35.73
35.76
35.68
35.84
35.6
33.49
33.58
33.71
33.82
33.91
34.04
34.15
34.23
37.85
34.68
34.88
35.05
35.2
35.4
35.52
35.66
35.81
35.91
38.08
36.2
TS_2 (XML 3.9-4, 2012-02-09)
28.54
30.13
32.95
30.33
30.43
30.54
35.81
30.99
32.78
31.37
31.56
35.22
31.99
32.22
32.55
32.66
32.84
35.32
33.59
33.32
33.47
33.58
33.69
33.76
33.87
35.5
35.52
34.24
37.67
34.75
34.92
35.1
37.97
35.43
35.57
35.7
38.12
35.98
Error Message associated to TS_2
[...]
Scraping html page 30 of ~/data/rdata/132.rdata
Scraping html page 31 of ~/data/rdata/132.rdata
error : Memory allocation failed : growing buffer
error : Memory allocation failed : growing buffer
I/O error : write error
Scraping html page 32 of ~/data/rdata/132.rdata
Fehler in htmlTreeParse(file = obj[x.html], useInternalNodes = TRUE, addFinalizer =     TRUE):
 error in creating parser for (null)
> Synch18832464393836

TS_3 (XML 3.92-0, 2012-02-13)
20.1
24.14
24.47
22.03
25.21
25.54
23.15
23.5
26.71
24.6
27.39
24.93
28.06
25.64
28.74
26.36
29.3
27.07
30.01
27.77
28.13
31.13
28.84
31.79
29.54
32.4
30.25
33.07
30.96
33.76
31.66
34.4
32.37
35.1
33.07
35.77
38.23
34.16
34.51
34.87
35.22
35.58
35.93
40.54
40.9
41.33
41.6
Error Message associated to TS_3
[...]
---------- status: 31.33 % ----------

Scraping html page 1 of 50
Scraping html page 2 of 50
[...]
Scraping html page 36 of 50
Scraping html page 37 of 50
Fehler: 1: Memory allocation failed : growing buffer
2: Memory allocation failed : growing buffer

Edit 2012-02-17: please help me verifying counter value
You'd do me a huge favor if you could run the following code.
It won't take more than 2 minutes of your time.
All you need to do is

*

*Download an Rdata file and save it as seed.Rdata.

*Download the script containing my scraping function and save it as scrape.R.

*Source the following code after setting the working directory accordingly.

Code:
setwd("set/path/to/your/wd")
install.packages("XML", repos="http://www.omegahat.org/R")
library(XML)
source("scrape.R")
load("seed.rdata")
html <- htmlParse(obj[1], asText = TRUE)
counter.1 <- .Call("R_getXMLRefCount", html)
print(counter.1)
z <- scrape(html)
gc()
gc()
counter.2 <- .Call("R_getXMLRefCount", html)
print(counter.2)
rm(html)
gc()
gc()

I'm particularly interested in the values of counter.1 and counter.2 which should be 1 in both calls. In fact, it is on all machines that Duncan has tested this on. However, as it turns out counter.2 has value 259 on all of my machines (see details above) and that's exactly what's causing my problem.

A: From the XML package's webpage, it seems that the author, Duncan Temple Lang, has quite extensively described certain memory management issues.  See this page: "Memory Management in the XML Package".
Honestly, I'm not proficient in the details of what's going on here with your code and the package, but I think you'll either find the answer in that page, specifically in the section called "Problems", or in direct communication with Duncan Temple Lang.

Update 1.  An idea that might work is to use the multicore and foreach packages (i.e. listResults = foreach(ix = 1:N) %dopar% {your processing;return(listElement)}.  I think that for Windows you'll need doSMP, or maybe doRedis; under Linux, I use doMC.  In any case, by parallelizing the loading, you'll get faster throughput.  The reason I think you may get some benefit from memory usage is that it could be that forking R, could lead to different memory cleaning, as each spawned process gets killed when complete.  This isn't guaranteed to work, but it could address both memory and speed issues.
Note, though: doSMP has its own idiosyncracies (i.e. you may still have some memory issues with it).  There have been other Q&As on SO that mentioned some issues, but I'd still give it a shot.

A: I've experienced similar issues with the XML package. The amount of memory being used by R was ballooning, to the point where my computer would crash. This answer solved my problem, I just set addFinalizer = F.
Here's a minimum reproducible example:
library(tidyverse)
library(XML)

url <- "https://en.wikipedia.org/wiki/Main_Page"
httr::GET(url) %>% base::saveRDS("html.rds")

Memory usage before running anything else:

Memory usage after running the following:
for(i in 1:10000){
    base::readRDS(file = "html.rds") %>%
        XML::htmlParse(., asText=TRUE) %>%
        XML::xpathSApply(., path = "//h1", xmlValue, addFinalizer = F)
}

Memory usage after removing addFinalizer = F (the default):
for(i in 1:10000){
    base::readRDS(file = "html.rds") %>%
        XML::htmlParse(., asText=TRUE) %>%
        XML::xpathSApply(., path = "//h1", xmlValue)
}

A: @Rappster My R doesn't crash when I first check and make sure the XML doc exists and then call the C function for realizing the memory.
 for (i in 1:1000) {

  pXML<-xmlParse(file)

if(exists("pXML")){
  .Call("RS_XML_forceFreeDoc", pXML)
                  }
}


text:
Q: How to display var_dump() results in a pretty format? Sometimes I'm using the var_dump() for debugging which outputs unformatted results.
Is there a way which can display structured information with colors, etc...

A: My favorite way of viewing var_dump is to install Xdebug. You should then be able to get formatted and colored output as shown on their website.

A: echo "<pre>";
var_dump($var);
echo "</pre>";

redpajama_set_name: RedPajamaStackExchange


text:
Q: Powershell: formating a double in scientific, using a dot regardless of locale-settings I want do display a double in scientific notation, with 3 decimal places and also three decimals in the exponent-part. Also, I want to display the number using a dot (".") as decimal delimitor (my localization always prints it with a comma). My desired format is like this:
1.234e+001

How do I do this? All my attempts with
echo ( "{0:e}" -f $myDouble )

have failed so far... Any hints welcome :)

A: Well that is a fascinating trip down locale-settings that I've not had the privilege of doing beforehand, so thank you!  Try this for me:
$a = New-Object System.Globalization.CultureInfo("en-US")
[double] $myDouble = 1000
$myDouble.tostring("e3", $a)

A: You could use the e custom format specifier to specify the exact format you want regardless of the current culture.  In this case, one digit before the decimal point, three digits after the decimal point, and a three-digit exponent:
PS> '{0:0.000e+000}' -f 1000
1.000e+003

The problem with that, however, is that the . in the above format string will be the localized decimal point (, in your case).  There's a few ways you can specify to use a literal . character instead...
PS> '{0:0\.000e+000}' -f 1000
1.000e+000
PS> '{0:0"."000e+000}' -f 1000
1.000e+000
PS> "{0:0'.'000e+000}" -f 1000
1.000e+000

...but now the exponent is wrong and I'm not sure how to work around that.  One way to get it to produce the text you want without any further modification necessary is to force it to use the invariant culture instead of the current culture:
PS> (1000).ToString('0.000e+000', [System.Globalization.CultureInfo]::InvariantCulture)
1.000e+003

Note that this works because in the invariant culture the decimal character happens to be the . you want.  If that wasn't the case, or if you just wanted to save some typing, then you can modify the NumberDecimalSeparator property for the current culture's number formatting.  Here's an example that changes the decimal character to ! for the duration of the current PowerShell session/script:
PS> [System.Globalization.NumberFormatInfo]::CurrentInfo.NumberDecimalSeparator
.
PS> '{0:0.000e+000}' -f 1000
1.000e+003
PS> [System.Globalization.NumberFormatInfo]::CurrentInfo.NumberDecimalSeparator = '!'
PS> '{0:0.000e+000}' -f 1000
1!000e+003

A: How about:
echo ( "{0:e3}" -f $myDouble )


text:
Q: How to remove inline scripts and styles from WordPress (Yoast SEO, emojis)? I want to remove most css and scripts added by Yoast SEO plugin to my wordpress page. How can I trace which function in Yoast SEO plugin adds which code so that I can try to remove it. I am a noob, so I would appreciate if you could show also a complete code to put to my functions.php to remove for instance this:
a)
<script type="text/javascript">
window._wpemojiSettings = ...

b)
<script src="http://dev.a2b.lv/wp-includes/js/wp-emoji-release.min.js?ver=4.8.2" type="text/javascript" defer=""></script>

c)
<style type="text/css">
img.wp-smiley,
img.emoji {
display: inline !important;
...
}
</style>

d)
<link rel="stylesheet" id="admin-bar-css" href="http://dev.a2b.lv/wp-includes/css/admin-bar.min.css?ver=4.8.2" type="text/css" media="all">

I hope from there I will figure out how to remove the rest.

A: All of your a, b, c, d problems are not relate to Yoast SEO plugin. It's come from WordPress core.
abc) Add this code to the end of your functions.php file of your current theme:
function disable_emojis() {
    remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
    remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );
    remove_action( 'wp_print_styles', 'print_emoji_styles' );
    remove_action( 'admin_print_styles', 'print_emoji_styles' );
    remove_filter( 'the_content_feed', 'wp_staticize_emoji' );
    remove_filter( 'comment_text_rss', 'wp_staticize_emoji' );
    remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' );
    add_filter( 'tiny_mce_plugins', 'disable_emojis_tinymce' );
}
add_action( 'init', 'disable_emojis' );

function disable_emojis_tinymce( $plugins ) {
    if ( is_array( $plugins ) ) {
        return array_diff( $plugins, array( 'wpemoji' ) );
    } else {
        return array();
    }
}

d) Logout from your WordPress page will do the job. That means your normal visitor will not have to load admin-bar.css...


text:
Q: When can I use the word Temporal? I'm wondering about the word "temporal." The definitions I've read are as follows:
adjective
adjective: temporal

*

*relating to worldly as opposed to spiritual affairs; secular.
  synonyms:  secular, nonspiritual, worldly, profane, material, mundane, earthly, terrestrial;
  antonyms:  spiritual

*of or relating to time.
  synonyms:  secular, nonspiritual, worldly, profane, material, mundane, earthly, terrestrial;
  antonyms:  spiritual
  GRAMMAR
  relating to or denoting time or tense.

Is it fair to say that I can use this word in place of the word time? For instance, "parsing temporal data" meaning "parsing time related data." The data I'm referring to here is Hour, Minute, Second, Day, Week, etc. It has nothing to do with wordly/secular things.

A: The question seems to be whether "temporal" can be substituted for the word "time", particularly in text about data. I would suggest (firmly) that the answer is no. My arguments are as follows:

*

*Time data is not data related to time as a concept, or to the idea of time as it pertains to human thinking. It is data about points in time, specific measured moments on a clock. Even that data is not about the punctual nature of the measurement itself. It is about the contingent event or marker it serves to measure. In other words, when you store a time in a database, you're not concerned so much about the clock reading itself as you are about what happened at the instant you or your equipment took the reading. "Temporal" applies to the idea, the concept of time in its role within human thinking. I oppose ideas and data in my mind - not that they contradict one another, but conceptually they should be kept separate. An idea is not as valuable if it is not based on data, but data does not constitute an idea.

*The sheer clarity of the phrase "time data" is compelling. The data describes a reading of hours, minutes, seconds and milliseconds (or something else entirely, such a a counter in the case of atomic clocks or computer CPUs). It would sound pedantic to talk of "temporal data" just as it would sound pedantic to say "spatial data" when you actually mean "size measurements". I believe it would also be misleading.

I thought I would mention that "temporal" (related to the temple) and "temporal" (related to the concept of time) do not share a common origin. One comes from the latin templum/i meaning open or consecrated space, the other comes from the latin tempus/oris meaning time. It's tempting to think they are somehow related, but they're really not. Latin, like English, was a mix and match of several varied original languages and words that looked like one another did not necessarily have common ancestry or connected meaning.
Finally, I think the reason that "temporal" has come to be the antonym of "sacred" in English is through the dichotomy of life and death, or more specifically Godliness versus mortality. We are mortals, and Time is our enemy. Gods are eternal, free from Time's grip. The fundamental theology of the Romans, inherited from the Greeks, starts with the Titan Saturnus (Chronos, the spirit of Time) being defeated by his son Jupiter (Zeus) thus granting all Gods their immortality. From mortal versus immortal, the idea of secular versus sacred is thus attached to the concept of Time.
Perhaps one exception to my suggestion of not using "temporal" as a replacement for "time" in technical manuals and papers would be when talking about "spatiotemporal" data, which describes data related to space-time, keeping in mind that space-time is something quite different from the simple amalgam of space and time. So perhaps not so much an exception as a warning about a possible false association.

A: Java, which is arguably the most popular software platform around, uses temporal in the way you want, so if it's good enough for them ...
See https://docs.oracle.com/javase/8/docs/api/java/time/temporal/package-summary.html

Package java.time.temporal Description
Access to date and time using fields and units, and date time adjusters
[...]  a temporal object, such as a date, time, offset or some combination of these.


text:
Q: NetSuite SuiteScript Join Saved Search not returning values I have tried all manner of different ways to get this search to work properly. I even removed the filter to return values that I know the search returns. I then added the filter, and got different project ID's and verified the search (through the UI) did the job correctly.
It's a JOIN type search that should accept one parameter (project id) and return two pieces of data. That's it. Any ideas on why my parameter (filter) is not working the way it should?
var filter = new Array();
filter[0] = new nlobjSearchFilter('entityid', 'job', 'is', int_Project_ID);

var results = nlapiSearchRecord('transaction', 'customsearch_[...]', filter, null);

if ( !isNull(results) && results.length > 0 )

Here is a link to the criteria and results tabs of the search in NetSuite.
Imgur Link

A: try this to set the filters after loading search .
var filter = mySearch.filters;
                    var newfilters = [];
                    var filterss = {};
                    filterss.name = 'department';
                    filterss.operator = 'IS';
                    filterss.values = dep_fil;
                    filterss.join = 'employee';
                    filterss.summary = 'max';
                    newfilters.push(search.createFilter(filterss));
                    mySearch.filters = newfilters;

var searchResults = mySearch.run().getRange({
                    start : 0,
                    end : 500
                });

you can get the values by using
  searchResult.getValue({
                            name : 'email',
                            join : 'employee',
                            summary : 'max'
                        });

There are diffrent type of summary like max,sum,group etc I think the summmary is the reason.
note that this is suitescript 2 method.


text:
Q: Creating Vanity URLs I currently run a site where I want to give people the ability to make their own URLs.  For example, here is my URL:
http://www.hikingsanfrancisco.com/hiker_community/hiker_public_profile.php?community_member_id=2
You see, it is named just by id, which is uninteresting and also bad for SEO (not that it matters here).
Ideally I want my site members to also have their names in the URL.  How is that typically done?  So in my case, it would be something like:
http://www.hikingsanfrancisco.com/alex-genadinik and have the id hidden.
Is that possible?  Any advice would be appreciated!
Thanks,
Alex

A: you need router, see https://stackoverflow.com/questions/115629/simplest-php-routing-framework

A: Code Igniter is a great MVC framework which provides configuration derived routes, which can easily be configured to send all requests through a common controller, where content can be dynamically pulled from a database and rendered.
Here is an example of a basic routing rule, which excludes request for users, students, and lessons, but routes all other request to a common content controller.
So if you request http://mydomain.com/hiking-and-camping-info, the url would be parsed, and hiking-and-camping-info would be looked up in the database and the related content pulled down.
Routing configuration:
$route['^(?!lessons|students|users|content).*'] = 'content';

and the content controller then grabs the url segment and finds the matching content and loads it:
class Content extends Controller {

    function __construct() {
        parent::Controller();
        $this->load->model('Content_model', 'content');
    }

    function index() {
        $content_url = $this->uri->segment(1);
        $data['content'] = $this->content->get_content_by_name($content_url);
        $this->load->view('content', $data);
    }
}

A: Generally this is accomplished via the use of an htaccess file on a server with mod_rewrite (most Linux servers).  An example might be like:
Options -Indexes
RewriteEngine On
RewriteRule ^([0-9a-zA-Z\-]+)$ $1.php
RewriteRule ^/(alex[\-]genadinik)$ /hiker_community/hiker_public_profile.php?       community_member_name=$1

This implies that your hiker_public_profile.php script will need to accept "alex-genadinik" as $_GET variable "community_member_name," and then query the database via the name instead of the ID.
So you'd take the above code, save it in a file called ".htaccess," and then upload it to the root directory of your website.  Learning regular expressions is recommended.


text:
Q: Python -- Unable to find element by Xpath, ID and Name

I just recently start to use Python, and I'm trying to input something into a search bar as shown in the picture.
I have tried Xpath, Name and ID, but none of those works. It looks pretty straight forward, but I keep receiving error messages.
I have tried:
driver.find_element_by_xpath('//*[@id="PRCSRUNCNTL_RUN_CNTL_ID"]')
driver.find_element_by_name("PRCSRUNCNTL_RUN_CNTL_ID")
driver.find_element_by_id("win0divPRCSRUNCNTL_RUN_CNTL_ID")

Error Messages for Xpath:


text:
Q: Wordpress: List custom taxonomy with children I'm trying to create a list of links for a custom taxonomy along with the children of the terms. i.e:

Telephony

BlackBerry

Fixed IP

Email

Fax

Text

NHS Email

So far I've got:
    <?php
    $termID = 451;
    $taxonomyName = "service_line_category";
    $termchildren = get_term_children( $termID, $taxonomyName );

    echo '
';
    foreach ($termchildren as $child) {
        $term = get_term_by( 'id', $child, $taxonomyName );
        echo '
name, $taxonomyName ) . '">' . $term->name . '
';
    }
    echo '
';
    ?>

However this only grabs the children of '$termID = 451;' but I'm not sure how to modify this to get the parents and the children for all of the terms within 'service_line_category' in a list.
Any ideas?

A: Here is the piece of code you need :
<?php
$taxonomyName = "service_line_category";
$terms = get_terms($taxonomyName,array('parent' => 0));
foreach($terms as $term) {
    echo 'slug,$taxonomyName).'">'.$term->name.'';
    $term_children = get_term_children($term->term_id,$taxonomyName);
    echo '
';
    foreach($term_children as $term_child_id) {
        $term_child = get_term_by('id',$term_child_id,$taxonomyName);
        echo '
term_id, $taxonomyName ) . '">' . $term_child->name . '
';
    }
    echo '
';
}
?>

A: Use a variable, you can do something like this:
$taxonomyName = "service_line_category";
$termID = get_cat_ID($taxonomyName);

A: @Alexcp so something like this:
    <?php
    $taxonomyName = "service_line_category";
    $termID = get_cat_ID($taxonomyName);
    $termchildren = get_term_children( $termID, $taxonomyName );

    echo '
';
    foreach ($termchildren as $child) {
        $term = get_term_by( 'id', $child, $taxonomyName );
        echo '
name, $taxonomyName ) . '">' . $term->name . '
';
    }
    echo '
';
    ?>

Obviously this doesn't work but is this along the right lines?


text:
Q: select change color pattern wont show function colorSelectCheck(){
        var select_val = $('#color_Pattern_selector').val();
    if(select_val)
    {
       colorPattern(select_val);
       //show the pattern i wanted
       //colorPattern(RedBox);
       alert(select_val);
    }

    return;
}

$(document).ready(function () {
    $("#color_Pattern_selector").change(colorSelectCheck).change();
    });

my intention is changing the color pattern depends on select value , but the color wont add if i pass those array to select.
here is my DEMO
remove the // on colorPattern(RedBox) to show what i mean.

A: That's a refference problem, but if you use eval you can do it. Take carefully with eval(), don't use it without ask your parents first ;)
https://jsfiddle.net/qryhth6u/2/
colorPattern(eval(select_val));

A: Your variable color_Pattern_box is a string containing the name of the varible you want to use, not the actual variable itself.
Add your color arrays to an object with their names as property names
var BoxColors = {
   "RedBox": ["#FFEBEE", "#E57373", "#F44336", "#B71C1C"],
   "PinkBox": ["#F48FB1", "#E91E63", "#AD1457"]
};

Then use the value of the select box as an object property name to select the correct color array
var colorArray = BoxColors[select_val];
colorPattern(colorArray);

Demo

var BoxColors = {
  RedBox: ["#FFEBEE", "#E57373", "#F44336", "#B71C1C"],
  PinkBox: ["#F48FB1", "#E91E63", "#AD1457"]
};

function colorPattern(color_Pattern_box){
  var color_Board = $('#colorBoard');
  var color_temp = ('');

  for(var c = 0; c < color_Pattern_box.length; c++){
    color_temp += "

";

  }
  color_Board.html(color_temp);
}

function colorSelectCheck(){
  var select_val = $('#color_Pattern_selector').val();

  if(select_val) {
    colorPattern(BoxColors[select_val]);
  }

  return;
}

$(document).ready(function () {
  $("#color_Pattern_selector").change(colorSelectCheck).change();
});
.mycolor{
    width:50px;
    height:50px;
}

<select id="color_Pattern_selector">
    <option value="RedBox">Red</option>
    <option value="PinkBox">Pink</option>
</select>


text:
Q: AsyncPLayer pauses with "INFO/AwesomePlayer(37): cache is running low" log I am using an AsyncPlayer to stream music from an URI and when testing the app on an android 4 emulator, I am getting an couple of pause and resume sequences generated by:
03-14 17:17:51.926: INFO/AwesomePlayer(37): cache is running low (1.96 secs) , pausing.
03-14 17:17:51.936: WARN/MediaPlayer(548): info/warning (703, 0)
03-14 17:17:51.936: INFO/MediaPlayer(548): Info (703,0)
03-14 17:17:51.946: WARN/MediaPlayer(548): info/warning (701, 0)
03-14 17:17:51.946: INFO/MediaPlayer(548): Info (701,0)
03-14 17:17:52.976: INFO/AwesomePlayer(37): cache has filled up (7.42 secs), resuming.

Did anyone encounter this issue, how can I avoid low cache pauses?
Thanks

A: It's a network issue, the issue come from your bandwidth.
The value of the enum : MEDIA_INFO_NETWORK_BANDWIDTH = 703
src: http://androidxref.com/source/xref/frameworks/base/include/media/mediaplayer.h at line 107


text:
Q: Should I have redundant unit test For example, the server would response
{
   name: "mike",
   age: "12",
   sex: "male"
}

In my code, I only use name, so my code would be string name = json["name"];
For my unit test, should my unit test case be the actual json result above or just
{
   name: "mike",
}

Since I only parse name field?

A: in unit test case, the actual result will be
{
   name: "mike",
}

A: When writing unit-tests you should be thinking for each test, what the purpose of each test is.
In your example, the goal of one test might be to test if your code extracts the name properly from the server result.  But, as the handling of keys and values is part of the language, you don't have to test that this is working for a mixture of keys and values: The expression json["name"] does the actual magic for you.  Therefore, you can keep the 'pseudo' server response quite simple - it does not have to be like an actual server response.  That is, just using { name: "mike", } would be OK.
There will likely be more test cases, for example to test that your code handles error situations properly, for example if the server responds with an answer that does not have a name - or have two or more names - or looks totally garbled.  Again, you would have to define some 'pseudo' server results.
At some point, however, you will have to test your code against the actual server - then you are, however, leaving the realm of unit-testing and enter into integration-testing.


text:
Q: Meromorphic functions on the Riemann sphere , generalization of a result I had an exercise that goes like this that i was able to solve but was wondering if it was true for more Riemann surfaces , hopefully something not isomorphic to $\mathbb{C}_{\infty}$.

Let $f$ and $g$ be two meromorphic functions on $\mathbb{C}_{\infty}$ such that their set of poles and zeroes are disjoint , then $\prod_{p\in \mathbb{C}_{\infty}}f(p)^{ord_p(g)}= \pm \prod_{p \in \mathbb{C}_{\infty}} g(p)^{ord_P(f)}$.

I have come up with a way to do this, that uses the fact that if $f$ is a meromorphic function on the Riemann sphere then if $\{\lambda_i\}_{i=1}^{n}$ denotes its set of poles and zeroes and $e_i =ord_{\lambda_i}(f)$, then $f=a\prod_{i=1}^{n}(z-\lambda_i)^{e_i}$, for some constant $a$ and then we just do the substituitions in each side and get the result we want. My quesiton is if there is an alternative way to do this, something a little more abstract, if there are other Riemann surfaces where this result is true and why ?
I have tried to see if this was even true for $\mathbb{P}^1$ because they are isomorphic but i still havent been able to do it, in fact i think its easy to construct a counterexample, wich is odd because the surfaces are isomorphic, does anyone know if this is true or not and give some insight on why ?Thanks in advance.


text:
Q: Finding the names of the duplicate values in an Excel Worksheet I have 2 columns of data that I am checking against, both of them contain names. Example:
Name1           Name 2
John Smith      John Smit
Bill Burr       Billy Burr
Mike Jones      Mike Jones

I need to find which names match and which names are partially matched. in order to do this i used the add-in Fuzzy Lookup to see where their were partial matches and created a column with the numbers, i then made a function to show which was a match and which was a partial match:
=IF(C2=1,"MATCH",IF(C2=0,"NO MATCH","PARTIAL"))

Following that i then calculated the number of matches, no matches and partial lists using this function
=COUNTIF(G:G,"MATCH") -- And so on

PROBLEM!
This approach is good for finding the number but i want to show which names are duplicates, this is were i am struggling
Going by the data i have retrieved I can see that there are Matches and Partial Matches but now i want to actually show those names
What can i use to achieve this


text:
Q: does such a noun "appropriates" ever exist? Your work is all the activities that you do in the course of doing your job and these activities may be seen as appropriates as much as responsibilities.
I am wondering what the bold part means?
What is more, I never managed to find such a word as a noun, let alone its plural form.

A: Collins and OALD both list only "appropriateness" as noun derrived from "appropriate" (verb/adjective).
So I'm led to assume that "appropriate" is not a propper noun.


text:
Q: iOS detachNewThreadSelector leaking I have a UIScrollView that I am loading some images in.  Sometimes I am apply an effect to an image and it takes a bit to do the pre-loading so I decided to do this on a different thread using detachNewThreadSelector.  I am using the KTPhotoBrowser that is on gitHub for this.
So basically, I have a function as so.
- (void)setCurrentIndex:(NSNumber *)newIndex
{

   NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

   currentIndex_ = [newIndex integerValue];

   [self loadPhoto:currentIndex_];
   [self loadPhoto:currentIndex_ + 1];
   [self loadPhoto:currentIndex_ - 1];
   [self unloadPhoto:currentIndex_ + 2];
   [self unloadPhoto:currentIndex_ - 2];

  [self setTitleWithCurrentPhotoIndex];
  [self toggleNavButtons];
  [pool release];

}

I call this using
[NSThread detachNewThreadSelector:@selector(setCurrentIndex:) toTarget:self withObject:[NSNumber numberWithInt:5]];

When I run this, it appears to be throwing a leak.  I am beginning to wonder if I should be putting the AutoRelease pool around the code in the loadPhoto method.  If you are curious about this code, I have included it below.
- (void)loadPhoto:(NSInteger)index
{
   if (index < 0 || index >= photoCount_) {
      return;
   }

   id currentPhotoView = [photoViews_ objectAtIndex:index];
   if (NO == [currentPhotoView isKindOfClass:[KTPhotoView class]]) {
      // Load the photo view.
      CGRect frame = [self frameForPageAtIndex:index];
      KTPhotoView *photoView = [[KTPhotoView alloc] initWithFrame:frame];
      [photoView setScroller:self];
      [photoView setIndex:index];
      [photoView setBackgroundColor:[UIColor clearColor]];

      // Set the photo image.
      if (dataSource_) {
         if ([dataSource_ respondsToSelector:@selector(imageAtIndex:photoView:)] ==    NO) {
            UIImage *image = [dataSource_ imageAtIndex:index];
            [photoView setImage:image];
         } else {
        [dataSource_ imageAtIndex:index photoView:photoView];
         }
      }

      [scrollView_ addSubview:photoView];
      [photoViews_ replaceObjectAtIndex:index withObject:photoView];
      [photoView release];
   } else {
      // Turn off zooming.
      [currentPhotoView turnOffZoom];
   }
}

Any ideas would be greatly appreciated.

A: Your code seems ok but you are using UIKit from another thread. UIKit classes should be used only from an application's main thread.
UIKit Framework Reference Introduction

A: Use the following
[self performSelectorInBackground:@selector(setCurrentIndex:) withObject:[NSNumber numberWithInt:5]];

instead of
[NSThread detachNewThreadSelector:@selector(setCurrentIndex:) toTarget:self withObject:[NSNumber numberWithInt:5]];

and it eliminates the memory leak.


text:
Q: ImageVIew slightly outside of the parent view I would like to have an imageview that should be half outside of the view. I have tried with the negative margin. But couldn't get the desired output. The image is getting cut off by the parent layout. Not sure what is the proper way to achieve the desired output. Any guidance would be appreciated.
My Code
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    tools:context=".Activities.ProfileActivity">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="@dimen/margin_padding_size_medium"
        android:padding="@dimen/margin_padding_size_medium"
        android:background="@android:color/holo_blue_bright"
        >

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="80dp"
            android:background="@android:color/darker_gray"
            >
            <ImageView
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="-50dp"
                android:src="@drawable/drawer_background"
                android:scaleType="fitXY"

                />

        </RelativeLayout>
    </FrameLayout>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

This is target output

This is my output

A: You should use the layout_anchor for the CoordinatorLayout children
your xml file need be something like this
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <android.support.design.widget.AppBarLayout
        android:id="@+id/materialup.appbar"
        android:layout_width="match_parent"
        android:layout_height="250dp"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        >

    </android.support.design.widget.AppBarLayout>

    <ImageView
        android:id="@+id/materialup.profile_image"
        android:layout_width="96dp"
        android:layout_height="96dp"
        android:elevation="8dp"
        android:src="@color/black"
        app:layout_anchor="@id/materialup.appbar"
        app:layout_anchorGravity="bottom|center"
        app:layout_scrollFlags="scroll"
        />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

the result

check this link on github for more reading
https://github.com/saulmm/CoordinatorExamples


text: Q: Calling jwt-auth secured service from Oracle Service Bus 12c Is it possible to invoke it from OSB (!) in more or less "declarative" way, I mean not by requesting a new token for each service invocation? Any approved/recommended techniques for cacheing JWT besides dumb-and-obvious solution like storing it in database and re-requesting on Not Authorized? Or even better utilizing security policies (OWSM functionality) or so. I've "invented" several ways to do it (parsing JWT for validity term, creating cached service with lifetime smaller than that of token) but want to be sure whether they were all not just new bicycles before starting to implement one of them :) Any ideas on non-declarative solutions will also be highly appreciated


text:
Q: How to reply to user of post using mailboxer I have been working on user massaging for my rails app using the mailboxer gem.
For some reason I can't render the messages form and my values aren't being passed, like user.id
What's a way of doing this? I know I'm close but I'm fondling hardcore with this one
In my views/posts/show.html.erb:
title & author

<%= @post.title %>

<%= @post.author %>

course

<%= @post.course %>

school

<%= @post.school %>

 price

<%= @post.price %>

  Posted by

  <%= @post.email %>

Description

<%= word_wrap(@post.description, :line_width => 8) %>

    DATE POSTED: <%= @post.created_at %>

  <%= link_to "reply", new_message_path %>

When I click on new message path this is the page it goes to:
view/messages/new.html.erb
Send a message to

<%= @user.username %>
<%= form_tag({controller: "messages", action: "create"}, method: :post) do %>
 <%= label_tag :subject %>
 <%= text_field_tag :subject %>
<%= label :body, "Message text" %>
<%= text_area_tag :body %>
<%= hidden_field_tag(:user, "#{@user.id}") %>
<%= submit_tag 'Send message' %>
<% end %>

I would like to pass the value of the username of the post, or pass post.email to the messages form.
The other way I tried to do it, and the way I prefer of doing it is to
    <%= render 'messages/form', conversation: conversation %>
but when I do that I get
undefined method error for 'conversation'

views/messages/_form.html.erb:
Reply:
 <%= form_for :message, url: [:reply, conversation] do |f| %>
 <%= f.text_area :body %>
 <%= f.submit "Send Message", class: 'btn btn-primary' %>
 <%= submit_tag 'Clear Reply Box', type: :reset, class: 'btn btn-danger' %>
 <% end %>

Basically I want to add a reply button to a post and let the user send a message to the user who posted. I'm using devise and all users are logged in.

A: You should define the new message nested under post in your routes.rb...
  resources :posts do
    resources :messages, only: [:new, :create]
  end

That will give you a path
new_post_message GET /posts/:posts_id/messages/new   messages#create
You would specify the post as part of the link
<%= link_to 'reply', new_post_message_path(@post) %>

That passes the param[:post_id] to the create method in the messages controller so you can retrieve the post, set it to an instance variable, and use it in the view/messages/new format.


text:
Q: PHP Word File line counter I need to make a PHP function that will count the number of lines in a Word File (.doc, docx)
This code does not seem to work correctly for me :
 $name = 'test.doc';
 $line_count = count(file($name));
 echo $line_count

My guess is  that this script does not work well with .doc or .docx but works good in .txt files. Are there any alternatives available out there? Tnx!

A: Only .docx can be opened with simple PHP as it is a zip file:
$zip = new ZipArchive;
if ($zip->open('test.docx') === TRUE) {
    $xml = $zip->getFromName('docProps/app.xml');
    $zip->close();
} else {
    $xml = false;
}

if($xml){
    $xml = simplexml_load_string($xml);
    echo $xml->Lines;
}


text:
Q: Proving optimality of greedy algorithm Problem I came across is as follows:
We have n tasks with l_i and w_i being completion time and weight of task i. Come up with an algorithm that minimizes sum for all i of f_i * w_i where f_i is time when task i was finished. If for example some task i is scheduled first then f_i = t_i and if second then f_i = t_i + t_(first task).
I spent some time on this, I first thought that simply making the list of tasks by selecting tasks from highest weight to lowest weight will be good enough, but realized it's wrong, for example if we have 2 tasks:
1 task : w_i = 10, l_i = 100
2 task : w_i = 9, l_i = 1
if we selected the one with w_i 10 first then we would get 10*100 + 9*101 = 1909 but if we selected it second we would get 9*1 + 10*101 = 1019.
Now I think the optimal algo is the one that schedules tasks from highest ratio of w_i/l_i to the lowest, but I am not sure how to prove it. Could anyone help with it?

A: You should be able to show that if the tasks are not arranged as you suggest you can improve the schedule by swapping two adjacent tasks that are in the wrong order. If you subtract total weighted completion times for these two cases you should end up looking at an expression for the difference in the weighted completion times of something like
L1W1 + (L1 + L2)W2 - [L2W2 + (L2 + L1)W1] and finding that you gain by reversing the order if L1/W1 and L2/W2 compare in the wrong direction.

A: You are right the tasks should be scheduled according to decreasing order of w_i/L_i.
Check the explanation of the proof of correctness given by Professor Tim Roughgarden
Part 1
part 2


text:
Q: Image View not getting displayed I'm stuck with this problem for 3 days. I have the following layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <com.confero.android.videoview.VideoView
        android:id="@+id/video"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" />

    <RelativeLayout
        android:id="@+id/hitting_stumps_layout"
        android:layout_width="180dp"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/video" >

        <ImageView
            android:id="@+id/hitting_stumps_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_marginLeft="2dp"
            android:contentDescription="@string/app_name"
            android:src="@drawable/lbw_hitting_the_stumps" />

        <ImageView
            android:id="@+id/hitting_stumps_decision"
            android:layout_width="12dp"
            android:layout_height="12dp"
            android:layout_alignRight="@+id/hitting_stumps_image"
            android:layout_centerInParent="true"
            android:layout_marginRight="5dp"
            android:contentDescription="@string/app_name"
            android:src="@drawable/lbw_tick" />
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/impact_line_layout"
        android:layout_width="180dp"
        android:layout_height="wrap_content"
        android:layout_below="@+id/hitting_stumps_layout" >

        <ImageView
            android:id="@+id/impact_line_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="2dp"
            android:contentDescription="@string/app_name"
            android:src="@drawable/lbw_impact_in_line" />

        <ImageView
            android:id="@+id/impact_line_decision"
            android:layout_width="12dp"
            android:layout_height="12dp"
            android:layout_alignRight="@+id/impact_line_image"
            android:layout_centerInParent="true"
            android:layout_marginRight="5dp"
            android:contentDescription="@string/app_name"
            android:src="@drawable/lbw_tick" />
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/pitched_line_layout"
        android:layout_width="180dp"
        android:layout_height="wrap_content"
        android:layout_below="@+id/impact_line_layout" >

        <ImageView
            android:id="@+id/pitched_line_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="2dp"
            android:contentDescription="@string/app_name"
            android:src="@drawable/lbw_pitching_in_line" />

        <ImageView
            android:id="@+id/pitched_line_decision"
            android:layout_width="12dp"
            android:layout_height="12dp"
            android:layout_alignRight="@+id/pitched_line_image"
            android:layout_centerInParent="true"
            android:layout_marginRight="5dp"
            android:contentDescription="@string/app_name"
            android:src="@drawable/lbw_tick" />
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/shot_offered_layout"
        android:layout_width="180dp"
        android:layout_height="wrap_content"
        android:layout_below="@+id/pitched_line_layout" >

        <ImageView
            android:id="@+id/shot_offered_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="2dp"
            android:contentDescription="@string/app_name"
            android:src="@drawable/lbw_shot_offered" />

        <ImageView
            android:id="@+id/shot_offered_decision"
            android:layout_width="12dp"
            android:layout_height="12dp"
            android:layout_alignRight="@+id/shot_offered_image"
            android:layout_centerInParent="true"
            android:layout_marginRight="5dp"
            android:contentDescription="@string/app_name"
            android:src="@drawable/lbw_tick" />
    </RelativeLayout>

</RelativeLayout>

and I'm trying to make the image view visible at certain time as the video playback goes on. I have used a CountDownTimer.
/**
 *
 */

package com.confero.android.videoview;

import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

public class LbwTutorialActivity extends Activity {

    private String TAG = "LbwTutorialActivity";
    private VideoView video;
    private CountDownTimer videoTimer;

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            if (msg.arg1 == 1) {
                handleShotOffered(msg.arg2);
            } else if (msg.arg1 == 2) {
                handlePitchedInline(msg.arg2);
            } else if (msg.arg1 == 3) {
                handleImpactLine(msg.arg2);
            } else if (msg.arg1 == 4) {
                handleHittingStumps(msg.arg2);
            }
        }
    };

    @Override
    public void onCreate(Bundle icicle) {

        super.onCreate(icicle);
        setContentView(R.layout.main);

        Uri uri = Uri.parse("android.resource://com.confero.android.videoview/"
                + R.raw.lbw2_lh);

        handleShotOffered(0);
        handleImpactLine(0);
        handlePitchedInline(0);
        handleHittingStumps(0);

        if (uri != null) {

            video = (VideoView) findViewById(R.id.video);
            video.setVideoURI(uri);
            video.setKeepScreenOn(true);
            video.setOnCompletionListener(new OnCompletionListener() {

                @Override
                public void onCompletion(MediaPlayer mp) {
                    // TODO Auto-generated method stub
                    video.stopPlayback();
                    videoTimer.cancel();
                }
            });

            video.setOnPreparedListener(new OnPreparedListener() {

                @Override
                public void onPrepared(MediaPlayer mp) {
                    // TODO Auto-generated method stub
                    video.requestFocus();

                    videoTimer = new CountDownTimer(30000, 125) {

                        @Override
                        public void onTick(long millisUntilFinished) {
                            // TODO Auto-generated method stub
                            int stopTime = video.getCurrentPosition();
                            Message message;

                            if (stopTime >= 1500 && stopTime < 1620) {

                                message = new Message();
                                message.arg1 = 1;
                                message.arg2 = 1;
                                handler.sendMessage(message);
                            } else if (stopTime >= 4100 && stopTime < 4220) {
                                message = new Message();
                                Log.d(TAG, "Pause 1");
                                try {
                                    message.arg1 = 1;
                                    message.arg2 = 0;
                                    handler.sendMessage(message);
                                    video.pause();
                                    message.arg1 = 2;
                                    message.arg2 = 1;
                                    handler.sendMessage(message);
                                    this.wait(1500);
                                    video.start();
                                } catch (InterruptedException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                            } else if (stopTime >= 4220 && stopTime < 4340) {
                                message = new Message();
                                Log.d(TAG, "Pause2");
                                try {
                                    message.arg1 = 2;
                                    message.arg2 = 0;
                                    handler.sendMessage(message);
                                    video.pause();
                                    message.arg1 = 3;
                                    message.arg2 = 1;
                                    handler.sendMessage(message);
                                    this.wait(1500);
                                    video.start();
                                } catch (InterruptedException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                            } else if (stopTime >= 9400 && stopTime < 9520) {
                                message = new Message();
                                Log.d(TAG, "Pause 3");
                                try {
                                    message.arg1 = 3;
                                    message.arg2 = 0;
                                    handler.sendMessage(message);
                                    video.pause();
                                    message.arg1 = 4;
                                    message.arg2 = 1;
                                    handler.sendMessage(message);
                                    this.wait(1500);
                                    video.start();
                                } catch (InterruptedException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                            }
                        }

                        @Override
                        public void onFinish() {
                            // TODO Auto-generated method stub
                        }
                    };

                    videoTimer.start();
                    video.start();
                }
            });
        }
    }

    private void handleShotOffered(int status) {

        if (status == 1) {
            ((ImageView) findViewById(R.id.shot_offered_image))
                    .setVisibility(View.VISIBLE);
            ((ImageView) findViewById(R.id.shot_offered_decision))
                    .setVisibility(View.VISIBLE);
        } else {
            ((ImageView) findViewById(R.id.shot_offered_decision))
                    .setVisibility(View.INVISIBLE);
            ((ImageView) findViewById(R.id.shot_offered_image))
                    .setVisibility(View.INVISIBLE);
        }
    }

    private void handlePitchedInline(int status) {

        if (status == 1) {
            ((ImageView) findViewById(R.id.pitched_line_image))
                    .setVisibility(View.VISIBLE);
            ((ImageView) findViewById(R.id.pitched_line_decision))
                    .setVisibility(View.VISIBLE);
        } else {
            ((ImageView) findViewById(R.id.pitched_line_decision))
                    .setVisibility(View.INVISIBLE);
            ((ImageView) findViewById(R.id.pitched_line_image))
                    .setVisibility(View.INVISIBLE);
        }
    }

    private void handleImpactLine(int status) {

        if (status == 1) {
            ((ImageView) findViewById(R.id.impact_line_image))
                    .setVisibility(View.VISIBLE);
            ((ImageView) findViewById(R.id.impact_line_decision))
                    .setVisibility(View.VISIBLE);
        } else {
            ((ImageView) findViewById(R.id.impact_line_decision))
                    .setVisibility(View.INVISIBLE);
            ((ImageView) findViewById(R.id.impact_line_image))
                    .setVisibility(View.INVISIBLE);
        }
    }

    private void handleHittingStumps(int status) {

        if (status == 1) {
            ((ImageView) findViewById(R.id.hitting_stumps_image))
                    .setVisibility(View.VISIBLE);
            ((ImageView) findViewById(R.id.hitting_stumps_decision))
                    .setVisibility(View.VISIBLE);
        } else {
            ((ImageView) findViewById(R.id.hitting_stumps_decision))
                    .setVisibility(View.INVISIBLE);
            ((ImageView) findViewById(R.id.hitting_stumps_image))
                    .setVisibility(View.INVISIBLE);
        }
    }
}

My problem is that the image views are not getting visible. Is there a problem with layout or the Java code?
Please help. Thanks in advance.


text:
Q: Calculate string values dynamically Say I'm storing settings in a Python file, like so:
#!/usr/bin/env python
#
# settings.py

import os

LOG_DIR = '/tmp'
LOG_FILE_MAIN = os.path.join(LOG_DIR, 'main.log')

Now, I include that file like so and change one of the values:
#!/usr/bin/env python
#
# main.py

import settings

settings.LOG_DIR = '/home/myuser'

When I print out a variable that relies on a (now changed) "reference" variable, I'll see that the value hasn't changed.
print(settings.LOG_FILE_MAIN)

Will return:
/tmp/main.log

Instead of:
/home/myuser/main.log

I understand why this is (Python has already calculated the strings value), but I need to work around it. Is there a way to achieve the desired result, other than creating a class and overriding the __setattr__ function?

A: Python has already executed the expression setting LOG_FILE_MAIN, and won't set it again just because you changed one of the inputs. The result of the expression is stored, not the expression itself.
You'll have to manually set the other variable again, or calculate it with a function at a later point, provided it is always to be calculated from LOG_DIR. E.g. LOG_FILE_MAIN should not be part of your settings, but always be calculated from settings as needed. I prefer low-tech approaches like that over the alternatives, which do require you to override the __setattr__ function, or otherwise handle all key attributes as setters.
Another approach is to use formatting operations; define LOG_FILE_MAIN as a string that'll have the whole settings module applied as keyword arguments in a str.format() call:
LOG_FILE_MAIN = '{LOG_DIR}/main.log'

and then every time you need to use LOG_FILE_MAIN do:
settings.LOG_FILE_MAIN.format(**vars(settings))

optionally applying a dir separator translation step to that too to make it platform-specific.


text:
Q: \strip@pt\textwidth gives "undefined control sequence" I'm sure that this is something silly, but I've been beating my head against the statement \strip@pt\textwidth giving "undefined control sequence".  I'm trying to modify some drawings in TikZ widths dynamically, and there's a lot of math involved due to the fact I need to support 3 page widths. It also gives me the opportunity to learn tikz and the fp package, but I need to strip the "pt" from the \textwidth statement.
I'm using this document definition: \documentclass[journal,letterpaper]{IEEEtran}
If \strip@pt is not defined, how do I define it?
edit
My minimal example:
\documentclass[journal,letterpaper]{IEEEtran}
\usepackage{fp}

\begin{document}
\newcommand\bitfieldwidth{32}
\newcommand\bitfielddivision{8}
\FPeval{\bitcolumnwidth}{(\strip@pt\textwidth) / \bitfieldwidth}
% the issue is here        ^^^^^^^^^
\begin{tabular}{|c|c|}
\hline
variable & value \\
\hline
textwidth &\the\textwidth \\
\hline
columnwidth &\the\columnwidth \\
\hline
bitcolumnwidth &$\bitcolumnwidth$ \\
\hline
\end{tabular}

\end{document}

A: The macro \strip@pt has @ in its name, so it can only be used in a context where @ is a letter, see What do \makeatletter and \makeatother do?
\documentclass[journal,letterpaper]{IEEEtran}
\usepackage{fp}

\begin{document}

\newcommand\bitfieldwidth{32}
\newcommand\bitfielddivision{8}
\makeatletter
\FPeval{\bitcolumnwidth}{(\strip@pt\textwidth) / \bitfieldwidth}
\makeatother

\begin{tabular}{|c|c|}
\hline
variable & value \\
\hline
textwidth &\the\textwidth \\
\hline
columnwidth &\the\columnwidth \\
\hline
bitcolumnwidth &$\bitcolumnwidth$ \\
\hline
\end{tabular}

\end{document}

You can define a "user level" macro:
\documentclass[journal,letterpaper]{IEEEtran}
\usepackage{fp}

\makeatletter
\let\strippt\strip@pt
\makeatother

\begin{document}

\newcommand\bitfieldwidth{32}
\newcommand\bitfielddivision{8}
\FPeval{\bitcolumnwidth}{(\strippt\textwidth) / \bitfieldwidth}

\begin{tabular}{|c|c|}
\hline
variable & value \\
\hline
textwidth &\the\textwidth \\
\hline
columnwidth &\the\columnwidth \\
\hline
bitcolumnwidth &$\bitcolumnwidth$ \\
\hline
\end{tabular}

\end{document}

However, you don't need fp to do this, provided you just divide by an integer:
\edef\bitcolumnwidth{\the\dimexpr\textwidth/\bitfieldwidth\relax}

will define \bitcolumnwidth as something that can be used in the context of a dimension:
\documentclass[journal,letterpaper]{IEEEtran}

\begin{document}

\newcommand\bitfieldwidth{32}
\newcommand\bitfielddivision{8}
\edef\bitcolumnwidth{\the\dimexpr\textwidth/\bitfieldwidth\relax}

\begin{tabular}{|c|c|}
\hline
variable & value \\
\hline
textwidth &\the\textwidth \\
\hline
columnwidth &\the\columnwidth \\
\hline
bitcolumnwidth &\bitcolumnwidth \\
\hline
\end{tabular}

\end{document}


text:
Q: Any manifold admits a morse function with one minimum and one maximum I have heard the claim: "Any closed manifold admits a Morse function which has one local minimum and one local maximum" often used in talks without a reference.
This does not seem to be very easy to prove "hands on". Trying to perturb the minima/maxima away locally will create new local minima/maxima, so I don't believe this will work.
One idea I had is to embed the manifold in $\mathbb{R}^n$, using Whitney, taking the height function, and turning on some flow in one fixed direction (I see this as stretching a balloon). I could not get the details right at all though...
Thus my question is: Is there an elementary proof of this fact? What are the standard references?

A: Here's a direct proof.  Let $M$ be a smooth $n$-manifold and $f$ a Morse function on $M$.  Let $p_i$ be the local minima, $q_j$ be the index-$1$ critical points, $f(p_i)<f(q_j)$ for all $i,j$, and $\gamma_{ij}$ the gradient flow line from $p_i$ to $q_j$.  Connect each $p_i$ to $p_0$ by a direct path of $\gamma_{ij}$s.  Note in particular the graph we have defined is contractible.  Homotope $f$ so the $q_j$ which are not on any paths have a greater value than the $q_j$ which are on the path, say (by scaling and translating) $f^{-1}(1)$ separates the greater $q_j$ and the $q_j$ on the path.  Now consider $B = f^{-1}(\infty,1]$.  By construction, this is diffeomorphic to an $n$-ball.  In $B$, replace $f$ by the radial distance function (possibly homotoped to match smoothly with $f$ on $\partial B$).  This new $f$, call it $\widetilde{f}$, has exactly one index $0$ critical point.
Repeat the procedure for $-\widetilde{f}$ to get exactly one index $n$ critical point.
Intuitively, think of a level surface flow.  It starts with a bunch of dots, the index $0$ critical points, expanding.  Then they send out tendrils which join together at the index $1$ critical points.  Controlling the Morse function is tantamount to controlling the level surface flow.  We slow down the level surfaces near some of the index $1$ points so that the level surfaces all join into a giant sphere.  This is our motivation; inside the sphere, we modify the function so that the sphere has expanded from a single dot, instead of many dots.

Here's another proof using handlebody decompositions.
By duality between Morse theory and handlebody theory, "Every manifold admits a Morse function with exactly one local maximum and exactly one local minimum" is equivalent to saying that every closed manifold admits a handlebody decomposition with exactly one $0$-handle and exactly one $n$-handle.  To see this, take a smooth handlebody decomposition of $M$ ("smooth" so that the attaching maps are all smooth maps).  Since this is done by gluing successive handles, we may focus our attention on the $0$-handles $M^0$ and the manifold obtained by gluing $1$-handles, $M^1$.
Since $M$ is connected and the only handle with disconnected attaching spheres are $1$-handles, $M^1$ is connected (that is, the gluing of $1$-handles kills all elements of $\pi_0$).  Therefore, we may pick a single $0$-handle and connect it to each other $0$-handle by a path of $1$-handles (possibly through other $0$-handles).  This union of $0$- and $1$-handles is homeomorphic to a ball, so we may replace it with a single $0$-handle and regard the remaining $1$-handles as attaching to the single $0$-handle.
Turn the handlebody decomposition upside down and repeat to obtain a single $n$-handle.

References to look into: Milnor's Morse Theory, Milnor's "Killing paper", Ranicki's book on surgery.


text:
Q: Django REST Framework: How do I change the color of top strip in Browsable UI There is a few pixels wide strip at the very top of the Browsable UI. The default color for it is #A30000. It's defined in a stylesheet bootstrap-tweaks.css for the element navbar-inner. I'd like to change the color of that strip, but I'm not sure how to do it.
What should I put in my api.html to modify the color? Thanks.

A: Here's what I added to my api.html:
{% block style %}

{{ block.super }}
<style>
.navbar .navbar-inner {
    -moz-border-bottom-colors: none;
    -moz-border-left-colors: none;
    -moz-border-right-colors: none;
    -moz-border-top-colors: none;
    background: none repeat scroll 0 0 #2C2C2C;
    border-color: ****MY_COLOR_HERE**** -moz-use-text-color -moz-use-text-color;
    border-image: none;
    border-radius: 0 0 0 0;
    border-right: medium none;
    border-style: solid none none;
    border-width: 5px medium medium;
    color: #FFFFFF;
    }
</style>

{% endblock %}


text:
Q: how to set on InterceptTouchEvent I know that can use onInterceptTouchEvent on Override over a custom listview by extending. How Can set this event,or handle it.
Notice, I know setOnTouchListener can stop scrolling from this
but this can not help me.
can everyone help me?
thank you!

A: Unfortunately as Android API level 19 (4.4 KitKat) there is not any handler method and interface to perform a hypothetical setOnInterceptTouchEventListener() or similar. So a boilerplate class extending ListView must be created in order to override onInterceptTouchEvent().


text:
Q: JavaScript Google Chart Invalid Row #1 I am trying to create a google chart that has a list of all fixtures from a certain week and how many posts each one has.
This is the code I am running:
<script type="text/javascript">
  google.charts.load('current', {'packages':['bar']});
  google.charts.setOnLoadCallback(drawChart);

  function drawChart() {
      var stringArray = [];
      <c:forEach items="${posts}" var="post" varStatus="count">

        stringArray.push("<c:out value='${post.fixture.home.teamName}v${post.fixture.away.teamName}'/>", 1);
    </c:forEach>
    var newArray = [["Games", "Amount of Posts"]];
    var postArray = [1,2,3,4,5,6,7,8];
    var x = 1;
    while(x <= stringArray.length){
        var games = stringArray[x];
        var numbers = postArray[x];
        console.log("Game " + games);
        newArray.push([games, numbers]);
        x++;
    }
    console.log(newArray[1]);
    var data = google.visualization.arrayToDataTable(newArray);

    var options = {
      chart: {
        title: 'Referee Performance',
        subtitle: 'Season 20-21',
      },
      bars: 'horizontal'
    };

    var chart = new google.charts.Bar(document.getElementById('barchart_material'));

    chart.draw(data, google.charts.Bar.convertOptions(options));
  }
  </script>

Lets take a closer look at this section
        var newArray = [["Games", "Amount of Posts"]];
    var postArray = [1,2,3,4,5,6,7,8];
    var x = 1;
    while(x <= stringArray.length){
        var games = stringArray[x];
        var numbers = postArray[x];
        console.log("Game " + games);
        newArray.push([games, numbers]);
        x++;
    }

So the newArray is what will be used to draw the table because it has the headers, I then have an array with all the fixtures in (stringArray) and another array of how many posts each one has (postArray). I am trying to add the first index of string array and postArray to the next index in newArray. This isn't working and is doing something weird. I've added console.log and this is the output I am getting.
Game 1
2:50 Game Crystal PalacevSouthampton
2:50 Game 1
2:50 Game Crystal PalacevSouthampton
2:50 Game 1
2:50 Game undefined
2:54 (2) [1, 2]

So there is 2 problems with this. For some reason x isn't incrementing and it isn't saving the team Names its saving a 1 for some reason. I'm not sure if I'm doing something stupid or not?
So how can I fix the error above?
Thank you for your time


text:
Q: Deleting file in node.js not working I am using Node.js with Express.
I am trying to delete a file after sending it to client with express js.
function deleteFile (file) {
    fs.unlink(file, function (err) {
        if (err) {
            logger.error(err);
        }
    });
}

app.get("/deleteFileAfterDownload", function (req, res){
    var fileName = "a.pdf"
    var stream = fs.createReadStream(fileName);
    var streamClosed = false;
    req.on('end',function(){
        if (!streamClosed){
            stream.emit('close');
            // I tried stream.destroy() but that is also not working
        }
    });
    stream.on('close', function () {
        streamClosed = true;
        deleteFile(fileName);
    });
    req.on('data', function(){});
    stream.pipe(res);
});

But the file is not getting deleted. it seems the process is still using file because just after I end the process, the file is getting deleted.
Can anybody tell me why?
If I am doing it wrong, please tell me a good way.

A: Please add a log in deleteFile, makesure it is called.
Try simplify it:
var fileName = "a.pdf"
var stream = fs.createReadStream(fileName);
stream.pipe(res);
res.once("finish", function () {
    deleteFile(fileName);
});

The previous example only delete file if download finished,
if you want delete file unconditionly, try the following:
var fileName = "a.pdf";
var stream = fs.createReadStream(fileName);
stream.pipe(res).once("close", function () {
    stream.close();
    deleteFile(fileName);
});

stream.close() is important here, because stream not close if pipe aborted.


text:
Q: Pandas ExcelWriter set_column fails to format numbers after DataFrame.to_excel used I have tried the example code found on the xlsxwriter webpage at http://xlsxwriter.readthedocs.org/en/latest/example_pandas_column_formats.html
import pandas as pd

# Create a Pandas dataframe from some data.
df = pd.DataFrame({'Numbers':    [1010, 2020, 3030, 2020, 1515, 3030, 4545],
                   'Percentage': [.1,   .2,   .33,  .25,  .5,   .75,  .45 ],
})

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter("pandas_column_formats.xlsx", engine='xlsxwriter')

# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1')

# Get the xlsxwriter workbook and worksheet objects.
workbook  = writer.book
worksheet = writer.sheets['Sheet1']

# Add some cell formats.
format1 = workbook.add_format({'num_format': '#,##0.00'})
format2 = workbook.add_format({'num_format': '0%'})

# Note: It isn't possible to format any cells that already have a format such
# as the index or headers or any cells that contain dates or datetimes.

# Set the column width and format.
worksheet.set_column('B:B', 18, format1)

# Set the format but not the column width.
worksheet.set_column('C:C', None, format2)

# Close the Pandas Excel writer and output the Excel file.
writer.save()

However it does not format the columns as expected - they simply appear unformatted (no numeric rounding, percentages.)
I am using Pandas 0.15.2. Any ideas. Has this changed recently in Pandas perhaps?
Any ideas would be welcome.

A: This seems like it is fixed in Pandas 16. See https://github.com/jmcnamara/XlsxWriter/issues/204


text:
Q: What does "the way of" mean in "To the deer it is a reminder of the way of all flesh ... "? What does "the way of" mean in:

A deep chesty bawl echoes from rimrock to rimrock, rolls down the mountain, and fades into the far blackness of the night. … Every living thing (and perhaps many a dead one as well) pays heed to that call. To the deer it is a reminder of the way of all flesh, to the pine a forecast of midnight scuffles and of blood upon the snow, to the coyote a promise of gleanings to come, to the cowman a threat of red ink at the bank, to the hunter a challenge of fang against bullet. … Only the mountain has lived long enough to listen objectively to the howl of a wolf.

Context: Thinking Like a Mountain By Aldo Leopold

A: the way of all flesh is an idiom for death.

go the way of all flesh
  1. To die.
  2. To come to an end.
American Heritage® Dictionary of the English Language

The quoted sentence means:
To the deer it is a reminder of its own mortality.

A: Way means both a course of travel or movement, and a means of passing from one place or point to another, especially of entry or exit. It is widely used for both literal and figurative purposes. (OED)
The way of all flesh refers to experience common to all people as they pass through life.

2002   NFT Programme Booklet Sept. 11/1   Stroheim's cruelly ironic tale of a rakish Ruritanian aristocrat..who falls for an innocent young girl.., only for their love to go the way of all flesh.

To go the way of all flesh is a euphemism for dying

1836   Dickens Sketches by Boz 1st Ser. II. 27   He pardoned us off-hand, and allowed us something to live upon, till he went the way of all flesh.

The way(s) of the world uses 'way' in a similar fashion (meaning the customary course of events; the manner in which people typically think or behave; the way things are. Chiefly used to express resigned acceptance of a regrettable but predictable state of affairs).

A: "The way of all flesh" is an idiom meaning mortality. The origin is unclear, but Dictionary.com thinks it a misquotation from the Bible.


text:
Q: Android Recycle View Scrolling hi I am building chat app using firebase realtime , facing issue with scrolling to last message -Bottom- when new message received , its working fine scrolling and every thing but not showing full height for the last item
here is my code
binding.items.smoothScrollToPosition(adapter.itemCount);

if any code to scroll with offset and how to calculate offset for dynamic height for message

A: I found soultion to use
layoutManager.stackFromEnd = true

final code is
 val layoutManager = binding.items.layoutManager as LinearLayoutManager
                layoutManager.stackFromEnd = true
                binding.items.smoothScrollToPosition(adapter.itemCount)


text:
Q: How do I Dynamically add a Table row into the a table at certain position? Below is a snippet of the table that I would like to add a row to. I would like to add a row in the middle at a certain position of this table. (Not at the end and not at the beginning). I would like to pinpoint a certain position in the table a insert a row at that position. Should I go with traversing the table looking for the row by id?
for example:
For Each row As TableRow in tblDates.Rows

//Code for  statement to grab the position of the Table Row by ID
  If Row.Id = (Name of ID)

// code to add row

or is it more like a matter of somehow traversing the ASP Elements. I usually deal with C# so this is a learning moment for me honestly. any thoughts would help me understand.

                    <asp:Label ID="lblDate" runat="server" Text="Date" Font-Bold="true"></asp:Label>

                    <asp:Label ID="lblDateFormat" runat="server" Text="(MM/DD/YYYY)" Font-Bold="true"></asp:Label>

                    <asp:Label ID="lblNumOfDays" runat="server" Text="Number of Days to Complete Action"
                        Font-Bold="true"></asp:Label>

                    <asp:Label ID="lblSubmittedToESO" runat="server" Text="Date Site Plan Submitted to ESO for Approval: "></asp:Label>

                    <asp:TextBox ID="txtSubmittedToESO" runat="server"></asp:TextBox>

                    <asp:Label ID="lblPWO" runat="server" Text="PWO: "></asp:Label>

                    <asp:TextBox ID="txtPWO" runat="server"></asp:TextBox>

A: I would NOT do this at the markup level. We have a database system, or at the very least a whole boatload of data table, data row and even more objects.
So, do NOT do this at the UI level, but at the data level.
Say, A simple grid like this:
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
        DataKeyNames="ID" CssClass="table" >
        <Columns>
                <asp:BoundField DataField="FirstName" HeaderText="FirstName" />
                <asp:BoundField DataField="LastName" HeaderText="LastName"  />
                <asp:BoundField DataField="HotelName" HeaderText="HotelName" />
                <asp:BoundField DataField="City" HeaderText="City" />
                <asp:BoundField DataField="Description" HeaderText="Description"  />

                <asp:TemplateField HeaderText="Active" ItemStyle-HorizontalAlign="Center" ><ItemTemplate>
                    <asp:CheckBox ID="chkActive" runat="server" Checked='<%# Eval("Active") %>'  />
                </ItemTemplate></asp:TemplateField>
        </Columns>
    </asp:GridView>

    Add new row at what position: <asp:TextBox ID="txtRow" runat="server"></asp:TextBox>

    <asp:Button ID="cmdRowAdd" runat="server" Text="+Add row"
        OnClick="cmdRowAdd_Click"
        />

Code to fill like this:
Dim rstData As New DataTable

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    If Not IsPostBack Then
        LoadData()
        GridView1.DataSource = rstData
        GridView1.DataBind()
        ViewState("rstData") = rstData
    Else
        rstData = ViewState("rstData")
    End If

End Sub

Sub LoadData()

    Using conn As New SqlConnection(My.Settings.TEST4)
        Dim strSQL = "SELECT * FROM tblHotelsA ORDER BY HotelName"
        Using cmdSQL As New SqlCommand(strSQL, conn)
            conn.Open()
            rstData.Load(cmdSQL.ExecuteReader)
        End Using
    End Using

End Sub

And now we have this:

So, now we have that text box and button - add a row, and at what position.
That code is this:
Protected Sub cmdRowAdd_Click(sender As Object, e As EventArgs)

    ' add new row to grid at location choosen by user:

    Dim NewRow As DataRow = rstData.NewRow
    NewRow("HotelName") = "Hotel Name"
    NewRow("City") = "City"
    NewRow("Active") = False

    rstData.Rows.InsertAt(NewRow, txtRow.Text)

    GridView1.DataSource = rstData
    GridView1.DataBind()

End Sub

So, if I type in 0 (first row), and hit button, then I get this:

So, normally, we would go
rstData.Rows.Add(MyNewRow)

but, you can as per above, use this:
rstData.Rows.InsertAt(NewRow, 2)

So, its near always better to manipulate your data at the data level, and if you need or want to display such results, then re-bind the grid or whatever.


text:
Q: jqGrid 'setGridHeight' not firing in IE I am adding a custom grow/shrink buttons to my jqGrid title bar to allow the user to change the height of the grid.  The following code works perfectly in Firefox and Chrome, but not in Internet Explorer (version 8).  In IE, the alerts before and after the call to setGridHeight are working, but the grid is not re-sized.  (And unfortunately, IE is the business's default browser.)  Has anyone come across a similar problem or know a solution?
var expand = "alert('start');
 $('#grid').jqGrid('setGridHeight',
 $(window).innerHeight()/1.5);
 alert('end');";
$("#gview_grid .ui-jqgrid-titlebar").append
 ('
   ');

Any help would be greatly appreciated.  Thanks!

A: Will it help if you create expand as a function?
    var expand = function(){/*...
   */}

and call it from your markup as expand()?

A: In creating a simplified example to post to jsfiddle, I discovered that the original posted code does indeed work in IE.  The issue was that I had bound the size of grid to the window resize function (and apparently IE did not like that).
$(window).bind('resize', function() {
    $('#grid').jqGrid('setGridHeight', $(window).innerHeight()/3);
}).trigger('resize');

I am still working on a solution so that these can work together in IE, but for now at least we know what the problem was.


text:
Q: Como resolver o erro "Cannot modify header information - headers already sent by" no PHP? Porque quando fazemos o uso das funções header() e setcookie() acontece o erro:

Warning: Cannot modify header information - headers already sent by (output started at /teste.php:10) in /teste.php on line 21

Porque esse erro acontece? Como resolver?

A: Na verdade, ele não é um erro. É um aviso(warning).
Isso é feito quando o seu navegador faz uma requisição ao servidor web. Com a resposta do servidor web. Ele te entrega um cabeçalho de resposta(header). Esse cabeçalho contém informações sobre a codificação da página, tamanho da página, tempo de duração do cache, hora da ultima atualização e tudo que seja relevante, sobre uma página da internet, para um navegador.
Quando você lê "headers already sent" significa que o servidor já enviou o header e APÓS esse envio você está tentando alterar alguma informação que deva ser enviada no header.
Mas se você não está manipulando nada que venha no header. Você não fez nada e está recebendo este erro.
No PHP o header começa a ser enviado logo que você insira o primeiro caracter HTML. Seja fora do PHP ou dentro do código PHP com um echo ou print().
<?php
  $numero_1 = 5;
  echo $numero_1;
?>

Tudo que está fora do código PHP é HTML, um espaço na linha 1 antes da abertura de código do PHP seria o motivo de uma resposta para o cliente. Qualquer função, sessão, cookie iria causar erro.
Para arrumar este aviso. Você teria que colocar todo o código que trabalhe com session, cookie, redirecionamentos, etc... antes de qualquer caractere pro HTML. Nada de tentar definir/criar um cookie depois de enviar um mensagem de "Olá mundo" para o navegador.
Se você precisa definir/criar um cookie antes de enviar uma mensagem "Olá mundo" ou qualquer coisa, repense o que você está fazendo.

A: Depende, se você está editando com DreamWeaver ele adiciona aos seus arquivos no momento de salvar uma opção chamada CODIFICAÇÃO BOM (algo do tipo), isto impede que seus scripts em PHP rodem corretamente principalmente em servidores linux, em windows funciona normalmente.
Caso contrário, veja se verificações em php como:
<?php
if(isset($_POST['teste'])){
  header("Location: index.php");
  // é essencial utilizar o exit() após um redireccionamento com header() para evitar possíveis erros
  exit();
}
?>

E demais verificações encontram-se no cabeçalho da página, ou seja, as linhas que fazem uma verificação/redirecionamento devem sempre estar acima do código, sempre com as tags no começo da página HTML.
Formulários, textos, etc, jamais podem estar acima do php quando são feitos redirecionamentos. Sempre acima. Poste seu código para nós que fica mais fácil de ajudar.


text:
Q: Insert angular2 components in Svg I recently started web dev. and angular2 in particular.
I must say that this framework is fantastic!
But I have one challenge that I cant figure out how to solve in the best way:
I want to build my web app with angular2 (datamodels, common services etc.).
But for the "main area screens" templates, I want to design in svg, drawing the static lines and circles etc with wysiwyg.
Then I want to embed all my different angular components to these "main area screens" svg pages. This is because our layout is not typical grid style, and the different components need to be placed on "pixel precision" over the staic svg background.
I have searched the web for different approaches, but nothing seems to solve my challenge.
Is it possible to embed angular2 components inside svg, and then add the svg to an angular template?

A: if you use an attribute selector for a SVG group, it will work, but I cannot seem to get the component as a custom element syntax that you are looking for to work.SVG does not have shadow DOM
For example, this works just fine:
@Component({
  selector: 'g[inner-svg]'
})

@View({
  template: `
    <text x="10" y="20">{{ text }}</text>
  `
})

export class InnerSvg {
  @Input() text: string;
}

<svg>
<g inner-svg text="This works"></g>
</svg>

A: Yes it is possible to add the svg as angular 2 components :
you can try this.
defining your circle component
@Component({
    selector: 'g[circle]',
    templateUrl: './circle.component.html',
    styleUrls: ['./circle.component.scss']
})

circle.component.hmtl :
<svg:circle
            [attr.cx]="circle?.x"
            [attr.cy]="circle?.y"
            [attr.r]="radius"

            [attr.fill]="circle?.fill"
             />

and your root html will be like
<svg>
<g circle *ngFor="let circle of circles"
                    [attr.fill-opacity]="opacity"
                    [attr.transform]="scale"
                    [circle]="circle"
                     />
</svg>

similarly you can use all the other svg shapes by creating similar components with selector as defied above.
You can use this library which provides all the svg elements
https://www.npmjs.com/package/angular-svg


text:
Q: Can 'all' be applied to a list of Maybe? Is it possible to use all on a [Maybe Int] list?
I know all (< 9) [2,4,6,8,10] returns False, but that is using a list with just integers.
I am trying to accomplish something similar except with a list that looks like this:
[Just 3, Just 6, Nothing, Nothing, Just 7]
I want all (<=9) [Just 3, Just 6, Nothing, Nothing, Just 7] to return True

A: > all (<= Just 9) [Just 3, Just 6, Nothing, Nothing, Just 7]
True

This works because Nothing is less than any Just x.
Alternatively, one can use catMaybes :: [Maybe a] -> [a] from the Data.Maybe module to discard the Nothings, and remove the Just wrappers, turning the list into a list of numbers, which can then be handled as usual:
> all (<= 9) $ catMaybes [Just 3, Just 6, Nothing, Nothing, Just 7]
True

Another alternative: define your own predicate on Maybe Int.
let p :: Maybe Int -> Bool
    p Nothing = True
    p (Just x) = x <= 9
 in all p [Just 3, Just 6, Nothing, Nothing, Just 7]

Even better: define p using maybe, as Zeta suggests.
Yet another alternative, using a list comprehension and and:
and [ x <= 9 | Just x <- [Just 3, Just 6, Nothing, Nothing, Just 7] ]

A: Sure. maybe True (< 9). maybe default func uses the given function func if you have Just, or the default if you have Nothing:
ghci> all (maybe True (< 9))  [Just 3, Just 6, Nothing, Nothing, Just 7]
True

You can use that to write your allMaybe function:
allMaybe :: (a -> Bool) -> [Maybe a] -> Bool
allMaybe p = all (maybe True p)

Or we could "lift" your predicate to Maybe:
liftP :: (a -> Bool) -> Maybe a -> Bool
liftP _ Nothing  = True
liftP p (Just x) = p x
-- or simply
-- liftP p = maybe True p

allMaybe' p = all (liftP p)

But that only hides the underlying maybe away.

A: A slightly more esoteric solution than those by chi and Zeta would be using Compose so that all sees the two layers as a single structure containing numbers:
GHCi> import Data.Functor.Compose
GHCi> all (<=9) $ Compose [Just 3, Just 6, Nothing, Nothing, Just 7]
True


text:
Q: In Windows 7 Libraries, how do you hide the folder location subview to be like default Documents library? All of the default libraries in Windows 7 do not show any subdivisions of where the files in the library are actually stored on disk.  But when you create a new custom library, the folders (even if there is only one folder) are "arranged" by folder location like so:

I would like to only see actual folders such as in the Documents library, and hide these subdivisions.  I tried changing the "Arrange by" setting at the top right, to various settings, but when I do that, the inner folders such as those in C:\Users\nafieta\Downloads\Installers in the picture are not shown, but their contents are shown, giving me a big mess of files.

A: Right-click > Group By > None.


text:
Q: image pointer to pointer initialization in C++ I meet a problem when dealing with image initialization.
I have a class like this:
Class MyImage
{
   private:
       unsigned int** image;
       const unsigned int w;
       const unsigned int h;
   public:
       MyImage(unsigned int** _image,unsigned int _w,
                unsigned int _h); // copy constructor
}

it seems if I use copy constructor as above, I need to delete image first like below:
 MyImage(unsigned int** _image,unsigned int _w,unsigned int _h)
   {
       if (image)
       {
           for (int i = 0;i < w;++i)
               delete[] image[i];
           delete[] image;
       }

       // .. copy _image to imge
   }

however if w and h are const members, it seems w and h must be initialized in the inialization list, like below:
   MyImage(unsigned int** _image,unsigned int _w,unsigned int _h): w(_w),h(_h)
   {
        // ..code
   }

then I can't delete image because w changes before it. My Question is what should I do if I don't want to eliminate const decoration in w and h? Any method? Thanks.

A: This is not a copy-constructor
MyImage(unsigned int** _image,unsigned int _w,unsigned int _h)

This is a copy-constructor
MyImage(const MyImage &image)

Don't use : w(_w) and first delete previous image, then use w = image._w.
However, you don't need delete anything because it's a constructor.

A: In your case, there is nothing wrong with w and h being a const. You can write your constructor in the following way:
 MyImage(unsigned int** _image,unsigned int _w,unsigned int _h)
     : w(_w), h(_h)
 {
     // No data is allocated in the memory pointed to by image yet
     // We have to allocate it here. Remember, that copy-ctor is
     // a constructor, so it operates on newly created instance,
     // not on an existing one.

     image = new unsigned int * [h];
     for (int i = 0; i < h; i++)
     {
         image[i] = new unsigned int [w];
         memcpy(image[i], _image[h], w * sizeof(unsigned int));
     }
 }

From my image-processing experience, consider storing an image as a single table, row-by-row. You can access (x, y)-th element by calling data[y * w + x]; In such case, you can simplify your copy ctor:
MyImage::MyImage(unsigned int * source, int newW, int newH)
    : w(newW), h(newH)
{
    image = new unsigned int[w * h];
    memcpy((void *)image, (void *)source, w * h * sizeof(unsigned int));
}

The copy constructor, as C++ community understands this term, would look like this:
MyImage::MyImage(const MyImage &source)
    : w(source.w), h(source.h)
{
    image = new unsigned int[w * h];
    memcpy((void *)image, (void *)source.image, w * h * sizeof(unsigned int));
}

Notice, that the image field does not exist when you call the constructor, so you do not need to free anything.
 // Your code
 MyImage(unsigned int** _image,unsigned int _w,unsigned int _h)
 {
     // Class is allocated into some part of memory, which might
     // have been used, so in effect this may be actually true,
     // because image may contain some rubbish data
     if (image)
     {
         // But this will result mostly likely in Access Violation
         // error, because you would try to use (free!) some random
         // data in memory.
         for (int i = 0;i < w;++i)
             delete[] image[i];
         delete[] image;
     }

     // .. copy _image to imge
}

If you need an assign-like method, which copies contents of some image (either stored in a unsigned int * or in another Image class) to an existing instance of Image, w and h cannot be const.

A: Use an encapsulated std::vector to manager the image data.  The default copy constructor, move constructor, assignment operator, move assignment operator and default destructor will all be automatically generated for you and do the right things.  Further by allocating the image data in a continuous block of memory and using a stride over row (or column) major order, it will be far more efficient than allocating a new memory block for every line...
struct MyImage
{
    const size_t w, h;
    vector<int> image;

    MyImage(const vector<int>& image, size_t w, size_t h)
        : image(image)
        , w(w)
        , h(h)
    {
        assert(image.size() == w*h);
    }

    MyImage(vector<int>&& image, size_t w, size_t h)
        : image(move(image))
        , w(w)
        , h(h)
    {
        assert(image.size() == w*h);
    }

    int& pixel(size_t x, size_t y) { return image[w*y+x]; }
    int pixel(size_t x, size_t y) const { return image[w*y+x]; }
};


text:
Q: How to replace a specific word from a dynamic list of String How to replace "current timestamp" from the list of string contains "{ts '2017-01-12 16:09:20'}", The ts value changed for each String.
Eg: //Need to replace the list of old time stamp values to current time stamp
private void replaceOldTimeStampToCurrentTimeStamp(){
    List<String>sampleString = new ArrayList<String>();
    sampleString.add("VALUES ('CODE','01234','DDC','DDC','',1,'01100',null,null,'Y','SD','PRODUCT','','','',2200,2603,{ts '2017-04-25 14:09:20'},'dba',{ts '2017-04-25 14:09:20'},'dba')");
    sampleString.add("VALUES ('TYPE','NW','New','New','',1,'01100',null,null,'Y','PRODUCT',null,'','',2200,2604,{ts '2017-01-12 16:09:20'},'dba',{ts '2017-01-12 16:09:20'},'dba')");
}

desired output:
VALUES('TYPE','NW','New','New','',1,'01100',null,null,'Y','PRODUCT',null,'','',2200,2604,current timestamp,'dba',current timestamp,'dba')
VALUES('CODE','01234','DDC','DDC','',1,'01100',null,null,'Y','SD','PRODUCT','','','',2200,2603,current timestamp,'dba',current timestamp,'dba')

A: You can try someting like this:
private void replaceOldTimeStampToCurrentTimeStamp(){
    String ts = "current timestamp" //the value you want, a string value
    List<String>sampleString = new ArrayList<String>();
    sampleString.add("VALUES ('CODE','01234','DDC','DDC','',1,'01100',null,null,'Y','SD','PRODUCT','','','',2200,2603,"+ts+",'dba',"+ts+",'dba')");
    sampleString.add("VALUES ('TYPE','NW','New','New','',1,'01100',null,null,'Y','PRODUCT',null,'','',2200,2604,"+ts+",'dba',"+ts+",'dba')");
}


text:
Q: Is the Birkhoff Theorem valid for the FLRW metric? The FLRW metric, in the case of positive scalar curvature, is: $ds^2 =- c^2 dt^2+a(t)^2\left(dw^2+\sin^{2}w(d\theta^2+\sin^2\theta d\phi^2)\right)$.
The Birkhoff's theorem states that "any spherically symmetric solution of the vacuum field equations must be static and asymptotically flat".
The FLRW metric stated above is obviously spherically symmetric, and also a solution of the vacuum field equation, but it is surely not static nor asymptotically flat (indeed it is not the Schwarzschild solution).
So what is the flaw in my reasoning?

A:
So what is the flaw in my reasoning?

The flaw is that the FLRW spacetime is not a vacuum solution. Indeed, as you correctly point out the one you wrote down has positive scalar curvature. A vacuum solution has a zero Ricci tensor and therefore a zero scalar curvature.
Physically, the FLRW spacetime represents an isotropic and homogenous distribution of matter. It is not vacuum (except for the trivial solution) anywhere.


text:
Q: How tin-can-api works offline? I am creating the ebook with some activities like quiz, puzzles using HTML5, CSS, JavaScript and Jquery. How to add Tin-Can into it. It should tract the action of reader and work offline.
As mention in Tin-Can API document API Doc, it works online and offline. How it works offline?
As I understand Actor, Verb and Object statement has to store locally in log and send to LRS when its connected to LRS. Am I correct?
If Yes, How to maintain the log of Actor, Verb and Object statement locally?
If i am wrong, How its works offline and how to maintain the Actor, Verb and Object statements of reader?

A: The mechanism for Tin Can to enable offline tracking is the timestamp property. This enables you to record not just when data was stored, but when the learning experience actually happened so that statements can be stored and transferred to the LRS later when a connection is available.
As Tin Can is a specification to support interoperable communication between learning technologies, the exact mechanism for storing the data doesn't matter. So long as you send the data in the right way when you get a connection, the LRS will be able to receive that data, however it was stored prior to sending.
Now, whilst that technically answers your question, I imagine that "you can store it however you like" may not be a helpful answer if you're looking for one way, any way, to store the data rather than being in a situation of having lots of options and wanting to choose the Tin Can conformant option from that list.
I recommend that your next steps are for you to ask (or search for) a more generic question about data storage on your particular platform e.g. "How do I store data on android?" or "How can I use JavaScript local storage?" as this particular technical challenge is in no way specific to Tin Can.
I hope that helps!


text:
Q: El operador '<' está reservado para uso futuro Al querer importar el archivo esquema.sql por consola en el Visual Studio Code:
C:\xampp\htdocs\okventa> mysql -u root -p okventa_by_parzibyte < esquema.sql (esta es la ruta q le indico)
me salta el siguiente error:
En línea: 1 Carácter: 39

*

*mysql -u root -p okventa_by_parzibyte < esquema.sql

El operador '<' está reservado para uso futuro.

*

*CategoryInfo: ParserError: (:) [],ParentContainsErrorRecordException

*FullyQualifiedErrorId : RedirectionNotSupported

Hay otra manera de importar el archivo .sql para no usar el operador < ?
Muchas gracias