text:
Q: How to we get the inverse function? Let $f(x)=\sqrt{\frac{e^x-1}{x}}, x \neq 0$, $f(0)=1$.
It is given that $g=f^2$.
I want to show that the function $f^{-1}:(0,+\infty) \to \mathbb{R}$ is a function and that the equation $f(x)=f^{-1}(x)$ has at least 2 solutions, $x_2>x_1>1$.
Also, show that $x_1, x_2$ are the only solutions of the above equation and that there is a unique $\xi>1$ such that $g(\xi)+2\xi f(\xi)=e^{\xi}$. (we suppose that $f$ is convex)
According to wolframalpha, the inverse function is the following:

What exactly is $W$ ? And how to we come to the inverse of the function?
EDIT: I have thought the following:
WE have that $f(f^{-1}(x))=x$. Thus we get that $\frac{e^{f^{-1}(x)-1}}{f^{-1}(x)}=x^2$.
Does this help ? Can we find like that the formula of the function $f^{-1}$ ?

A: Lambert's $W$ is defined as the function $W(x)$ that satisfies the relationship
$$W(x)e^{W(x)}=x\tag1$$
Let $y(x)=f^{-1}(x)$ denote the inverse function of the function
$$f(x)=\begin{cases}\sqrt{\frac{e^x-1}{x}}&,x\ne 0\\\\1&,x=0\end{cases}\tag2$$
Then it is easy to see from $(2)$ that $y(x)$ satisfies the equation
$$e^{y(x)}=x^2\left(y(x)+\frac1{x^2}\right)\tag3$$
Substituting $s(x)=-\left(y(x)+\frac1{x^2}\right)$ into $(3)$ yields
$$s(x)e^{s(x)}=-\frac{e^{-1/x^2}}{x^2}\tag4$$
Comparing $(4)$ with $(1)$ reveals
$$s(x)=W\left(-\frac{e^{-1/x^2}}{x^2}\right)$$
whereupon we find that
$$f^{-1}(x)=-W\left(-\frac{e^{-1/x^2}}{x^2}\right)-\frac1{x^2}$$
which agrees with the result from Wolframalpha that the OP reported.

Now, let's take a step backward.  First, the function $f(x)$ as given in $(2)$ is differentiable with $f'(x)>0$ on $[0,\infty)$.  Therefore, $f(x)$ has a unique inverse function for $x\ge 0$.

Next, let's show that $f(x)=x$ has two roots. Note that $f(x)>x$ for $x=0$.
Then, using $e<3$ it is easy to see that $f(2)=\sqrt{\frac{e^2-1}{2}}<2$.  So, $f(x)<x$ at $x=2$.
Finally, since $e^x-1\ge \frac{x^4}{24}$, we find that $f(x)\ge \frac{x^{3/2}}{24}$ and hence $f(x)>x$ for $x>24$.
Putting this together, we see that $f(x)=x$ for two distinct values ox $x$, $x_1$ and $x_2$ such that $0<x_1<2$ and $2< x_2<24$.  A numerical root search finds that $x_1   \approx 1.545$ and $x_2\approx 4.567$.

Note that at any fixed point $x_0$ of $f$, $f(x_0)=x_0\implies x_0=f^{-1}(x_0)$.  Therefore, $x_1$ and $x_2$ are also solutions of the equation $f(x)=f^{-1}(x)$.

A: $\require{begingroup} \begingroup$
$\def\e{\mathrm{e}}\def\W{\operatorname{W}}\def\Wp{\operatorname{W_0}}\def\Wm{\operatorname{W_{-1}}}$
The wolframalpha solution
is incomplete.
It should be
\begin{align}
f^{-1}(x)
&=
\begin{cases}
f_0^{-1}(x)=
-\Wp(-\tfrac1{x^2}\exp(-\tfrac1{x^2}))- \tfrac1{x^2}
,\quad & x\in(0,1)
,\\
f_1^{-1}(x)=
-\Wm(-\tfrac1{x^2}\exp(-\tfrac1{x^2}))- \tfrac1{x^2}
,\quad & x\in[1,\infty)
,
\end{cases}
\end{align}
where $\Wp$ is the principal branch
and $\Wm$ is the other real branch
of the Lambert $\W$ function.
And indeed the equation $f(x)=f^{-1}(x)$
has two real solutions, which can be fouund numerically as
\begin{align}
x_1&\approx 1.5450
,\\
x_2&\approx 4.5670
.
\end{align}
$\endgroup$


text:
Q: Creating and managing separate heaps using pThreads In this scenario, I have a vector of vectors of unsigned integers which I am processing. In the normal case, there will be 256 vectors of 1048576 unsigned integers. I want to use the pThread c++ API such that each pthread will do the following work on its assigned sub-list of unsigned integers(of length 1048576).
for(int i = 0; i < list_size; i++)
{
    int *arg = (int *) malloc(sizeof(*arg));
    *arg = i;
    thread_err = pthread_create(&(threads[i]), NULL, &Heap_Build, arg);
    if (thread_err != 0)
        printf("\nCan't create thread :[%s]", strerror(thread_err));
}

As you tell from the above code, I am simply generating as many threads as there are sub-lists in the main list and I'm sending them each with an index value into the main vector of sub-lists so they know which sub-list they are effectively processing.
void* Heap_Build(void *arg)
{
   int main_list_index = *((int *)arg);

   //pthread_mutex_lock( &mutex1 );
   num_of_nodes = 0;
   pheapType heap = pheapType(malloc((k+usage_offset) * sizeof(heapType)));
   unsigned int sublist_value;

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

     sublist_value = main_list.at(main_list_index).at(i);

     Heap_Insert_Node(heap, sublist_value);
   }

   for(int i = k; i < sub_list_size; i++)
   {
       sublist_value = main_list.at(main_list_index).at(i);

       if(sublist_value < heap[usage_offset])
       {
          Heap_Update_Key_CPU(heap, 0, sublist_value);
       }
    }
    //pthread_mutex_unlock( &mutex1 );
    cpu_results[main_list_index] = heap[usage_offset];
    free(heap);
}

Note

*

*num_of_nodes - Is the number of nodes currently inserted into the heap structure. This is set at 0 before each heap's construction and used by the update_key and insert_node operations to determine the index in the heap array to place the value.

*sublist_value - Is the current value of the sublist being processed.
The above function essentially allocates an array of memory to build a heap from the first 'k' elements in the sub-list that the thread is processing. It then processes the remaining elements, using the heap's update key operation.
So each thread is given an index to a sub-list in a global vector of sub-lists of unsigned integers. It creates a heap from the first kth elements in the sub-list then processes the remaining kth elements in the sub-lists based on that heap which it created.
I can get everything to work fine if I do 2^8 sub-lists of size 2^8 or 256 threads processing 256 sub-lists of 256 integers or even 1 sub-list of 2^20 integers, but in the test case, 2^8 sub-lists of 2^20 integers. The program either has a segmentation fault or simply just aborts.
If I uncomment the mutex locks. Any case works fine, but unfortunately, it would be doing the computation in a serial manner. I'm not sure what the issue may be, mainly because I'm new at dealing with POSIX threads. Obviously, the issue has to deal with number of integers in the sub-list being too great in combination with the number of threads and possibly a race condition but I'm not sure how to identify the critical regions in the overall computation instead of just placing a mutex lock over the entire computation and removing all parallelism.
If needed, I could provide the code for the two heap functions used in the Heap_Build but I'm not trying to bog down this question with too much code.
EDIT: I believe the problem in the above code is that all threads are referencing the same memory space, 'heap', instead of each thread allocating a heap structure of their own. Therefore when the first thread that finishes the computation frees the space of memory allocated for 'heap', the other threads are referencing an invalid memory area thus the segmentation fault.
If I remove the 'free(heap)' line, the error disappears but the values are incorrect. I'm not sure how to correct this, I think it would require giving each pthread it's own heap memory space to work within so that none of the threads would be stepping on each other's data, but I'm not quite sure how to accomplish this.

A: In the code you have shown, each thread running Heap_Build function allocates its own heap structure to work with:
pheapType heap = pheapType(malloc((k+usage_offset) * sizeof(heapType)));

This memory is local to a thread (in the sense that it is not known to other threads, unless shared by some code not shown in the question), thus I think your concern in bold is not valid.
However your code does not check that the memory was really allocated. 256 vectors of 1048576 integers already consume 2^(20+8+2)=2^30, or 1GB, of memory. If the code is 32 bit and the allocation size is significant, it might happen that there is no free memory block of sufficient length. Then, in some thread heap can be NULL, and manipulations with such a "heap" will likely result in a crash.
Another possibility is data races in Heap_Insert_Node and/or Heap_Update_Key_CPU, in case these functions have side effects (e.g. modify some global variables).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Parsing tab separated data I have a text file (~10GB) with the following format:
data1<TAB>data2<TAB>data3<TAB>data4<NEWLINE>

I want to scan through it and do processing only on data2. What is the best (fastest) way to extract data2 in C++.
EDIT: Added NEWLINE

A: Read the file line by line.  For each line, split on the tab.  That will leave you with an array containing the fields, allowing you to work with the second field (data2).

A: This sounds like a job for a higher level tool like shell utilities:
cut -f2           # from stdin
cut -f2 <my_file  # from file

But nonetheless, you can do that with C++ as well:
void parse(std::istream& in)
{
    std::string word;
    while( in ) {
        std::cin >> word;  // throwaway 1
        std::cin >> word;  // data2
        process(word);
        std::cin >> word >> word;  // throwaway 3 and 4
    }
}

// ...
parse(std::cin);
std::ifstream file("my_file");
parse(file);

A: Well, open a file stream (which should be able to handle 10gig files) and then just jump to after the first tab, which is a '\t', read your data and then skip to the next newline and repeat.
#include <fstream>
#include <string>

int main(){
  std::fstream fin("your_file.txt");

  while(fin){
    std::string data2;
    char sink = '\0';

    // skip to first tab
    fin.ignore(1024,'\t');

    fin >> data2;
    // do stuff with data2

    // skip to next line
    fin.ignore(1024,'\n');
  }
}

A: Read the file a line at a time. It's pretty straight forward parsing out the tabs from there. You could use something like strtok() or similar routine.

A: Since the file is of a considerable size, you might consider using a technique that will allow you overlap your I/O with your processing. In response a comment, you mentioned you were working on linux. Provided you are using kernel 2.6 or later you might consider using Linux asynchronous I/O (AIO). Specifically you would use aio_read to queue up some read requests, then use aio_suspend to wait for one (or more) of the request to end. As requests complete you would scan through the buffers using a plain char* to locate the data you are interested in. For each piece of data you find you could at that point create a std::string (although avoiding copying may be beneficial) and process it. Once you have scanned a block you would requeue it to read another block from the file. You continue doing this until you have processed every block in the file.
The code for this method will be more complex than reading the file line by line, but it may be considerably faster.

A: You could use iostream as others have suggested.  Another way to go would be to simply use fscanf.  For example:
#include <stdio.h>

...

FILE* fp = fopen(path_to_file, "r");
char[256] data;

while(fscanf(fp, "%*s<tab>%s<tab>%*s<tab>%*s", data))
{
   do what you want with your data
}


text:
Q: Wordpress metabox populate checkboxes group with custom post type I'm creating a metabox with a checkbox group and i want to populate the checkboxes with a custom post type.
I'm using the code in this article: Reusable Custom Meta Boxes Part 2
Now for checkboxes group i have the values hardcoded:
    array (
    'label' => 'Sponsors',
    'desc'  => 'Sponsors for this exercise.',
    'id'    => $prefix.'sponsors',
    'type'  => 'checkbox_group',
    'options' => array (
        'one' => array (
            'label' => 'Option One',
            'value' => 'one'
        ),
        'two' => array (
            'label' => 'Option Two',
            'value' => 'two'
        ),
        'three' => array (
            'label' => 'Option Three',
            'value' => 'three'
        ),
        'four' => array (
            'label' => 'Option Four',
            'value' => 'four'
        )
    )
)

and this code saves the data:
case 'checkbox_group':
foreach ($field['options'] as $option) {
    echo '<input type="checkbox" value="'.$option['value'].'" name="'.$field['id'].'[]" id="'.$option['value'].'"',$meta && in_array($option['value'], $meta) ? ' checked="checked"' : '',' />
            '.$option['label'].'
';
}

break;
I want to use a custom post type to load the checkboxes:
function get_sponsors()
{
    $args = array(
    'numberposts' = -1,
    'post_type' = 'px_sponsor',
    'orderby' = 'post_title',
    'order' = 'ASC'
    );

    $my_sponsors = get_posts( $args );

    return $my_sponsors;
}

How can i modify it so it shows my custom post type values instead of the hard coded ones?

A: Solved!
i changed the function get_sponsors() to return an array with posts:
function get_sponsors()
{
    $args = array(
    'numberposts' => -1,
    'post_type' => 'movies'
    );

    $my_movies = get_posts($args);

    $options = array();
    foreach($my_movies as $m)
        $options[$m->ID] = array(
            'label' => $m->post_title,
            'value' => $m->ID
        );

    return $options;
}

Credits for solution to Mridul Aggarwal for replying in this post


text:
Q: SQL server programming for interview our input data is - 101001101
and i need the output like - 232332232
how to do this in SQL server

A: Use Replace
DECLARE @input VARCHAR(15)='101001101'

SELECT REPLACE(REPLACE(@input,'1','2'),'0','3')

Output:

A: One more way:
DECLARE @str nvarchar(max) = '101001101'

SELECT REPLACE(@str*2,0,3)

A: Use Update Statement
update tbl set col = case when col>0 then col+3 else col+1 end;


text:
Q: Custom task build order in Gradle I have a multi-project Gradle build with a custom defind xjc task to build the jaxb generated objects and I am having issues with steps building in the correct order.
I have 3 projects, common, ref and product. ref depends on common and product depends on ref and common. The naming is important to my problem as it seems gradle does things in alphabetical order and I have stripped out some other dependencies as they do not impact the problem.
Within each project the order should be jaxb, java compile and then scala compile.
In the top level build.gradle I specify the jaxb task to be:
task jaxb() {
    description 'Converts xsds to classes'
    def jaxbTargetFile = file( generatedSources )
    def jaxbSourceFile =  file ( jaxbSourceDir )
    def jaxbEpisodesFile =  file ( jaxbEpisodeDir )
    def bindingRootDir =  file ( rootDir.getPath() + '/')

    inputs.dir jaxbSourceDir
    outputs.dir jaxbTargetFile
    doLast {
        ant.taskdef(name: 'xjc', classname: 'com.sun.tools.xjc.XJCTask', classpath: configurations.jaxb.asPath)

        jaxbTargetFile.mkdirs()
        jaxbEpisodesFile.mkdirs()

        for ( xsd in bindingsMap) {
            if (!episodeMap.containsKey(xsd.key)) {
                ant.fail( "Entry no found in the episodeMap for xsd $xsd.key" )
            }
            def episodeFile = projectDir.getPath() + '/' + jaxbEpisodeDir + '/' + episodeMap.get(xsd.key)
            println( "Processing xsd $xsd.key with binding $xsd.value producing $episodeFile" )
            ant.xjc(destdir: "$jaxbTargetFile", extension: true, removeOldOutput: true) {
                    schema(dir:"$jaxbSourceFile", includes: "$xsd.key")
                    binding(dir:"$bindingRootDir" , includes: "$xsd.value")
                    arg(value: '-npa')
                    arg(value: '-verbose')
                    arg(value: '-episode')
                    arg(value: episodeFile)
            }
        }
    }
}

In the individual build.gradle file for product I specify (with similar in ref)
dependencies {
     compile project(':common')
     compile project(':ref')
}

and in all three projects I specify
compileJava.dependsOn(jaxb)

when I run publish (or jar) in the product project I can see the following output:
common:jaxb
common:compileJava
common:compileScala
common:jar
product:jaxb
ref:jaxb
refcompileJava
ref:compileScala
ref:jar
product:compileJava
product:compileScala

This gives me an error because the xsd in product refers to ref and as ref has not run jaxb yet there are no episode binding files for ref and product regenerates the imported classes with the wrong package name.
How can I ensure that ref jaxb runs before product jaxb?

A: If your product's jaxb tasks depends on jaxb tasks for ref and common, you should define this dependency:
(in product build.gradle)
task jaxb(dependsOn: [':common:jaxb', ':ref:jaxb']) {
...
}

Set same kind dependency in ref (on commmon)


text:
Q: android avd connect to localhost php Lumen Port 8000 I have installed php-Server:
https://windows.php.net/download/
Then I built the Lumen based Webserver with this Link:
https://computerhalbwissen.de/wie-man-mit-dem-lumen-framework-eine-rest-api-erstellt/
I can now go to the following path:
cd C:\php\lumen-api
Then I typed in this line:
php -S localhost:8000 -t public
And I easily got my json-String with this line, when I typed it in
the browser address line:
http://localhost:8000/api/items/
I did a GET request in the browser of my android avd:
10.0.2.2:8000/api/items/
I get following screen:

What do I have to do to avoid this response. Do I have to
set something in the configurations of my avd?
Thank you for your help.

A: I cant access the php-Server with my Android-Device.
I installed xampp and everything works fine.


text:
Q: Table width scrolling site left and right I'm stumped as to what is causing this. I have duplicate sites but in one of them, I have a table that is causing my site to scroll left and right.
Using Web Developer Toolbar, I am able to outline the table which shows the table being pushed out. See Figure 1.

And here's the link...http://goo.gl/0r2if
Furthermore, I have tried everything in Firebug to see if I can force that table to be smaller without any joy.

I've also compared it to the other site which is just a replica of this one cannot seem to find a difference.
I've also searched to see if I can find something about odd 100% widths in tables and nothing I've tried has worked either.
No doubt it is going to be a simple mistake but I think I just need some fresh eyes on this please?
Thank you!

A: The continue shopping link has css value width: 1083px;
Continue shopping

#shoppingcartcontents a.continue-shopping {
    color: #9F1B32;
    display: block;
    font: 15px 'another_typewriterregular',arial,helvetica,sans-serif;
    padding-top: 10px;
    width: 1083px;
}

It's inside the last row of the shopping cart table, so that's what's causing it. Remove the width and it's fixed.


text:
Q: Convert ASPX files to XML or RSS for Wordpress Is any possibility how can i convert simple ASPX files to XML file?
I need to convert cca 300 files and import them to Wordpress, but i´m .NET beginner.

A: It´s for my client, so i need to do that by this way.
I need as an output only 1 XML/RSS file for import articles to Wordpress.
ASPX files look like this:
    <%@ Page Title="Megújulnak az oktatás alapjai a Debreceni Egyetemen" Language="C#" MasterPageFile="/hun/news/news.master" %>

<asp:content contentplaceholderid="cphHead" runat="Server">
    <meta name="keywords" content="Megújulnak az oktatás alapjai a Debreceni Egyetemen" />
    <meta name="description" content="A felhő alapú levelezést és az Office 365 szolgáltatásait minden debreceni egyetemista ingyenesen veheti igénybe a Oktatási Alapcsomagjának köszönhetően." />

</asp:content>
<asp:content contentplaceholderid="cphContent" runat="Server">

Megújulnak az oktatás alapjai a Debreceni Egyetemen

A felhő alapú levelezést és az Office 365 szolgáltatásait minden debreceni egyetemista ingyenesen veheti igénybe a  Digitális Oktatási Alapcsomagjának köszönhetően.

A világszinten is a legmodernebbek közé tartozó szolgáltatást a Debreceni Egyetem meglévő hallgatói már használhatják, az idén felvettek pedig a beiratkozáskor kapnak olyan egyedi e-mail címet, amelynek a vége az oktatási intézményre utal, ily módon is erősítve az egyetemi közösséghez tartozást.

Az egyetem és a szoftvercég együttműködése a jövőben tovább folytatódik: a Microsoft szakemberei képzéseket tartanak majd az egyetemen, így a hallgatók ingyenesen megtanulhatják a most bevezetett technológiák használatát, s azt, hogyan használhatják a felhő alapú alkalmazásokat a tanulás során és a nemzetközi tudományos életben. A Microsoft Magyarország az ország több más egyetemével működik együtt, és tervez hasonló, innovatív együttműködést.

    <%--
A Digitális Oktatási Alapcsomagról:

             Magyarország és a Microsoft Magyarország sikeres együttműködésének eredményeként 2012-től még hatékonyabb tanulási és tanítási környezet válik elérhetővé hazánk oktatási intézményeinek részére. A  felajánlásaként minden köz- és felsõoktatási intézmény ingyenes igényelheti az úgynevezett Digitális Oktatási Alapcsomagot. A megoldáscsomag része – többek között – az intézményi és diáklevelezés, a csoportmunka, az intranet, vagy éppen az előadás-sugárzási és videokonferencia-lehetőség is.

             A Digitális Oktatási Alapcsomag által kínált korszerű tanulási környezetet a diákok és hallgatók az iskolán kívülről, otthonról is elérhetik. Ennek köszönhetően a jövő nemzedéke már a tanulmányai során közvetlen tapasztalatot szerezhet arról, mit jelent a távoli munkavégzés, a coworking és a mobilitás egy olyan korban, ahol az ún. felhő-alapú szolgáltatások alapvetően változtatják meg az emberek viszonyát a munkaidő, vagy a fizikai értelemben vett munkahely fogalmaihoz.

A ról:

             A  a világ legnagyobb számítástechnikai eszközszállító és szolgáltató cége. Széles termékválasztéka az operációs rendszerektől és alkalmazásoktól kezdve a felhőalapú lakossági és vállalati szolgáltatásokon át az összetett hálózati, üzleti szoftverekig terjed. A céget William H. Gates és Paul G. Allen alapította 1975-ben. Mára a világ több mint 90 országában van jelen, dolgozóinak száma pedig meghaladja a 80 000 főt.

             A  Magyarország 1993-ban alakult, mindössze 2 fővel. Dolgozóinak létszáma jelenleg megközelíti a 200 főt, partnerprogramjában pedig 2200 hazai vállalkozással működik együtt. A magyar leányvállalat 2003-ban, 2006-ban, 2008-ban, valamint 2012-ben is elnyerte a "Legjobb Munkahely" címet, 2010-ben pedig az MNKSZ pályázatán a "Legjobb Női Munkahely 2009" címet érdemelte ki. A  Magyarország a 2012-2013-as üzleti évben a világ összes  leányvállalata közül a legjobbnak bizonyult. A magyar leányvállalat ügyvezetői igazgatói posztját 2011. október 24-től Papp István tölti be.

--%>
</asp:content>

and i need something like:
    <?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0"
    xmlns:excerpt="http://wordpress.org/export/1.2/excerpt/"
    xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:wfw="http://wellformedweb.org/CommentAPI/"
    xmlns:dc="http://purl.org/dc/elements/1.1/"
    xmlns:wp="http://wordpress.org/export/1.2/"
>
<item><title>Már Magyarországon is kapható a Lumia 530 okostelefon</title>

<content:encoded>

Már Magyarországon is kapható a Lumia 530 okostelefon

2014. szeptember 9., Budapest - A Microsoft bejelentette, hogy már elérhető Magyarországon a Lumia 530 belépő szintű okostelefon, amely bevezeti a felhasználókat a Windows Phone világába. A készülék páratlan ár-érték arányú okostelefon-élményt kínál a felsőkategóriás telefonokban is megtalálható, legújabb Microsoft és Lumia innovációkkal és szolgáltatásokkal. A kártyafüggetlen Lumia 530 készülék ára bruttó 34.990 forint.

Az egy és két SIM kártyás változatban egyaránt kapható, 3G-s Lumia 530 készülék jutányos áron kínálja az legújabb generációs okostelefon-élményt és szélesebb felhasználói réteg számára teszi elérhetővé a Microsoft ökoszisztéma szolgáltatásait. A Windows Phone 8.1 operációs rendszer kimagasló személyre szabhatóságának köszönhetően a Lumia 530 okostelefon a következő előnyöket biztosítja:

</content:encoded></item>
 </rss>


text:
Q: ORA-00972: identifier is too long on GridView DataBind This is kinda weird, I have this code that loads the DataSource of a GridView and binds it:
gvwPesquisaCotacao.DataSource = Pesquisar(new Corretor()
{
    IdPessoa = ddlCorretorPesquisa.SelectedValue.Split('|').GetValue(0).ToString(),
    RazaoSocial = ddlCorretorPesquisa.SelectedValue.Split('|').GetValue(1).ToString(),
    Departamento = new Departamento() { Descricao = ddlCorretorPesquisa.SelectedValue.Split('|').GetValue(2).ToString() },

    IdCorretor = ddlCorretorPesquisa.SelectedValue.Split('|').GetValue(4).ToString(),
    TpUsuario = Pessoa.TipoUsuario.CORRETOR,
});

gvwPesquisaCotacao.DataBind();

I'm having this Exception thrown when the last line of code is executed.
Here's the implementation of the methods that are being called to fill the DataSource(in the right sequence):
private List<Cotacao> Pesquisar(Corretor pCorretor)
{
    try
    {
        return new CotacaoBO().Listar(new Cotacao()
        {
            Id = Convert.ToInt32(String.IsNullOrEmpty(txtNumeroCotacao.Text) ? "0" : txtNumeroCotacao.Text),
            Proponente = new Proponente() { CNPJ = String.IsNullOrEmpty(txtCNPJ.Text) ? "0" : txtCNPJ.Text, RazaoSocial = txtRazaoSocial.Text, Fantasia = txtRazaoSocial.Text },
            Status = new Status() { Id = ddlSituacao.SelectedIndex.Equals(0) ? "999" : ddlSituacao.SelectedItem.Value.ToString() },
            Filial = pCorretor.Filial,
            Corretor = pCorretor,
            Produto = new Produto() { Id = Convert.ToInt32(ddlProdutoIdVersao.SelectedValue.Split(';').GetValue(0).ToString()) },
            Proposta = new Proposta(Convert.ToDecimal(String.IsNullOrEmpty(txtNumPI.Text) ? "0" : txtNumPI.Text))
        }).OrderByDescending(order => order.Id).ToList();
    }
    catch (Exception ex)
    {
        ...
    }
}

public List<Cotacao> Listar(Cotacao pCotacao)
{
    try
    {
        List<Cotacao> lstCotacao = new List<Cotacao>();

        new CotacaoDAO().Listar(pCotacao).ForEach(delegate(Cotacao resCotacao) {

            resCotacao.Mercadoria.TaxaMercadoria = new MercadoriaBO().GetTaxaMercadoria(resCotacao).TaxaMercadoria;
            resCotacao.ParametroSistema = new ParametroSistemaBO().Listar(resCotacao.Produto, resCotacao.Corretor).First();
            resCotacao.Produto.Moeda.IOF = new MoedaBO().ListarIOF(new Moeda() { Id = resCotacao.ParametroSistema.cMoeApo }, resCotacao.ParametroSistema).IOF;
            resCotacao.CoberturasAdicionais = new CoberturaBO().ListarCoberturasAdicionaisByCotacao(pCotacao, false);
            resCotacao.TrechoComplementar = new TrechoComplementarBO().ListarPorCotacao(pCotacao.Id);
            lstCotacao.Add(resCotacao);
        });
        return lstCotacao;
    }
    catch (Exception ex)
    {
        ...
    }
}

The last method is HUGE but it basically executes a sql command, fills a reader with the return of it and mounts the returning list to the previous application layer.
public List<Cotacao> Listar(Cotacao pCotacao)
{
    try
    {
        var sql = new StringBuilder();
        sql.Append(" SELECT DISTINCT NUMERO_COTACAO ");
        sql.Append("       ,COD_PRODUTO ");
        sql.Append("       ,VERSAO_PRODUTO ");
        sql.Append("       ,DESCRICAO_PRODUTO ");
        sql.Append("       ,DSC_PROD_DOC ");
        sql.Append("       ,CNPJ_CLIENTE ");
        sql.Append("       ,NOME_CLIENTE ");
        sql.Append("       ,SIT_COTACAO ");
        sql.Append("       ,SIT_DESCRICAO ");
        sql.Append("       ,CORRETOR ");
        sql.Append("      ,SUSEP_CORRETOR ");
        sql.Append("      ,DESC_CORRETOR ");
        sql.Append("      ,ID_FILIAL_CORRETOR ");
        sql.Append("      ,DESC_FILIAL_CORRETOR ");
        sql.Append("      ,COD_PRODUTOR ");
        sql.Append("      ,DSC_PRODUTOR ");
        sql.Append("       ,FILIAL ");
        sql.Append("       ,VALIDADE_COTACAO ");
        sql.Append("      ," + dbUtility.ValidaNulo() + "(U_CTR_SEG,0) as U_CTR_SEG  ");
        sql.Append("      ," + dbUtility.ValidaNulo() + "(U_PRP,0)  AS U_PRP ");
        sql.Append("      ," + dbUtility.ValidaNulo() + "(U_APO_PNC,0)  AS U_APO_PNC ");
        sql.Append("      ," + dbUtility.ValidaNulo() + "(C_EMS_SEG,0)  AS C_EMS_SEG ");
        sql.Append("      ,DATA_COTACAO");
        sql.Append("      ,DATA_EMBARQUE");
        sql.Append("      ,DATA_ALTERACAO");
        sql.Append("      ,ORIGEM ");
        sql.Append("      ,DESCRICAO_ORIGEM ");
        sql.Append("      ,COMPLEMENTO_ORIGEM ");
        sql.Append("      ,DESCRICAO_COMPLEMENTO_ORIGEM ");
        sql.Append("      ,DESTINO ");
        sql.Append("      ,DESCRICAO_DESTINO ");
        sql.Append("      ,COMPLEMENTO_DESTINO ");
        sql.Append("      ,DESCRICAO_COMPLEMENTO_DESTINO ");
        sql.Append("      ,MEIO_TRANSPORTE ");
        sql.Append("      ,TIPO_VEICULO ");
        sql.Append("      ,VEICULO_TRANSPORTE ");
        sql.Append("      ,ID_NAVIO ");
        sql.Append("      ,GRUPO_MERCADORIA ");
        sql.Append("      ,TIPO_MERCADORIA ");
        sql.Append("      ,ID_MERCADORIA ");
        sql.Append("      ,DESCRICAO_MERCADORIA ");
        sql.Append("      ,COMPLEMENTO_MERCADORIA ");
        sql.Append("      ,IS_CONTAINER ");
        sql.Append("      ,ID_EMBALAGEM ");
        sql.Append("      ,ID_COBERTURA_BASICA ");
        sql.Append("      ,DESCRICAO_COBERTURA ");
        sql.Append("      ,VLR_FOB ");
        sql.Append("      ,VLR_FOB_CONVERT ");
        sql.Append("      ,MOEDA_FOB ");
        sql.Append("      ,CAMBIO_FOB ");
        sql.Append("      ,VLR_PREMIO_FOB ");
        sql.Append("      ,VLR_FRETE ");
        sql.Append("      ,VLR_FRETE_CONVERT ");
        sql.Append("      ,MOEDA_FRETE ");
        sql.Append("      ,CAMBIO_FRETE ");
        sql.Append("      ,VLR_PREMIO_FRETE ");
        sql.Append("      ,VLR_DESPESAS ");
        sql.Append("      ,VLR_DESPESAS_CONVERT ");
        sql.Append("      ,MOEDA_DESPESAS ");
        sql.Append("      ,CAMBIO_DESPESAS ");
        sql.Append("      ,PERCENTUAL_DESPESAS ");
        sql.Append("      ,VLR_PREMIO_DESPESAS ");
        sql.Append("      ,VLR_LUCRO ");
        sql.Append("      ,VLR_LUCRO_CONVERT ");
        sql.Append("      ,MOEDA_LUCRO ");
        sql.Append("      ,CAMBIO_LUCRO ");
        sql.Append("      ,PERCENTUAL_LUCRO ");
        sql.Append("      ,VLR_PREMIO_LUCRO ");
        sql.Append("      ,VLR_IMPOSTOS ");
        sql.Append("      ,VLR_IMPOSTOS_ORI ");
        sql.Append("      ,CAMBIO_IMPOSTOS ");
        sql.Append("      ,MOEDA_IMPOSTOS ");
        sql.Append("      ,VLR_PREMIO_IMPOSTOS ");
        sql.Append("      ,PERCENTUAL_LUC_DESP_IMP ");
        sql.Append("      ,VLR_CONTAINER ");
        sql.Append("      ,VLR_PREMIO_CONTAINER ");
        sql.Append("      ,V_IS_TOTAL ");
        sql.Append("      ,VLR_PREMIO_TOTAL ");
        sql.Append("      ,VLR_PREMIO_LIQUIDO ");
        sql.Append("      ,VLR_PREMIO_CALCULADO ");
        sql.Append("      ,VLR_IMP_II_ORI ");
        sql.Append("      ,VLR_IMP_II ");
        sql.Append("      ,PERCENTUAL_IMP_II ");
        sql.Append("      ,MOEDA_II ");
        sql.Append("      ,CAMBIO_II ");
        sql.Append("      ,VLR_IMP_IPI_ORI ");
        sql.Append("      ,VLR_IMP_IPI ");
        sql.Append("      ,PERCENTUAL_IMP_IPI ");
        sql.Append("      ,MOEDA_IPI ");
        sql.Append("      ,CAMBIO_IPI ");
        sql.Append("      ,VLR_IMP_ICMS_ORI ");
        sql.Append("      ,VLR_IMP_ICMS ");
        sql.Append("      ,PERCENTUAL_IMP_ICMS ");
        sql.Append("      ,MOEDA_ICMS ");
        sql.Append("      ,CAMBIO_ICMS ");
        sql.Append("      ,VLR_IMP_PIS_ORI ");
        sql.Append("      ,VLR_IMP_PIS ");
        sql.Append("      ,PERCENTUAL_IMP_PIS ");
        sql.Append("      ,MOEDA_PIS ");
        sql.Append("      ,CAMBIO_PIS ");
        sql.Append("      ,VLR_IMP_COFINS_ORI ");
        sql.Append("      ,VLR_IMP_COFINS ");
        sql.Append("      ,PERCENTUAL_IMP_COFINS ");
        sql.Append("      ,MOEDA_COFINS ");
        sql.Append("      ,CAMBIO_COFINS ");
        sql.Append("     ,MOEDA_CERTIFICADO ");
        sql.Append("     ,CAMBIO_CERTIFICADO ");
        sql.Append("     ,VLR_TOTAL_CERTIFICADO ");
        sql.Append("     ,PREMIO_CERTIFICADO ");
        sql.Append("      ,DATA_VENCIMENTO_PROPOSTA ");
        sql.Append("      ,SERIE_DOCUMENTO ");
        sql.Append("      ,NUMERO_DOCUMENTO ");
        sql.Append("      ,PERCENTUAL_COMISSAO ");
        sql.Append("      ,NUMERO_APOLICE ");
        sql.Append("      ,DATA_INI_VIGENCIA_APOLICE ");
        sql.Append("      ,DATA_FIM_VIGENCIA_APOLICE ");
        sql.Append("      ,DATA_EMISSAO_APOLICE ");
        sql.Append("      ,OBSERVACAO ");
        sql.Append("      ,PERC_FRANQUIA ");
        sql.Append("      ,CAMBIO_MOEDA_PRODUTO ");
        sql.Append("      ,IS_GERENCIAMENTO_RISCO ");
        sql.Append("      ,INCOTERM ");
        sql.Append("      ,PROC_SUSEP ");
        sql.Append("      ,COD_BANCO ");
        sql.Append("      ,NUM_PROPOSTA ");
        sql.Append("      ,DIG_PROPOSTA ");
        sql.Append("      ,IDENTIFICACAO_PAGAMENTO ");
        sql.Append("      ,VALOR_IOF ");
        sql.Append("      ,VALOR_IOF_CALCULADO ");
        sql.Append("      ,IS_CARTA_CREDITO ");
        sql.Append("      ,COD_RAMO_ATIVIDADE ");
        sql.Append("      ,COD_INCOTERM ");
        sql.Append("      ,DESC_INCOTERM ");
        sql.Append("      ,IS_PONTA_IMPORTACAO ");
        sql.Append("      ,IS_DESTINO_EXPORTACAO ");
        sql.Append("      ,IS_CIF_FECHADO ");
        sql.Append("      ,IS_RETORNO_BENEF ");
        sql.Append("      ,VALOR_BENEF ");
        sql.Append("      ,PREMIO_BENEF ");
        sql.Append("      ,IS_RETORNO_EVENTO ");
        sql.Append("      ,DSC_PROD_DOC ");
        sql.Append("      ,DT_EMISSAO ");
        sql.Append("      ,HR_EMISSAO ");
        sql.Append("      ,FORMA_PAGAMENTO ");
        sql.Append("      ,BANCO ");
        sql.Append("      ,AGENCIA ");
        sql.Append("      ,CONTA_CORRENTE ");

        sql.Append("   FROM  " + ConfigurationManager.AppSettings["PrefixNameDbAvulsa"] + ".VW_PESQUISA_COTACAO ");
        sql.Append("  WHERE (1=1) ");

        if (pCotacao != null)
        {
            if (!pCotacao.Id.Equals(0))
            {
                sql.Append(" AND NUMERO_COTACAO = " + dbUtility.Variavel("COTACAO"));
                dbUtility.AddParametro("COTACAO", pCotacao.Id, ParameterDirection.Input);
            }

            if (pCotacao.Produto != null)
            {
                if (!pCotacao.Produto.Id.Equals(0))
                {
                    sql.Append(" AND COD_PRODUTO = " + dbUtility.Variavel("PRODUTO"));
                    dbUtility.AddParametro("PRODUTO", pCotacao.Produto.Id, ParameterDirection.Input);
                }
            }

            if (pCotacao.Proposta != null && !pCotacao.Proposta.Id.Equals(0))
            {
                sql.Append(" AND NUM_PROPOSTA = " + dbUtility.Variavel("NUM_PROPOSTA"));
                dbUtility.AddParametro("NUM_PROPOSTA", pCotacao.Proposta.Id, ParameterDirection.Input);
            }

            if (pCotacao.Proponente != null)
            {
                if (!String.IsNullOrEmpty(pCotacao.Proponente.RazaoSocial))
                {
                    sql.Append(" AND UPPER(NOME_CLIENTE) LIKE " + dbUtility.Variavel("NOME"));
                    dbUtility.AddParametro("NOME", "%" + pCotacao.Proponente.RazaoSocial.Trim().ToUpper() + "%", ParameterDirection.Input);
                }

                if (!String.IsNullOrEmpty(pCotacao.Proponente.CNPJ) && !Int64.Parse(pCotacao.Proponente.CNPJ).Equals(0))
                {
                    sql.Append(" AND CNPJ_CLIENTE = " + dbUtility.Variavel("CNPJ"));
                    dbUtility.AddParametro("CNPJ", pCotacao.Proponente.CNPJ.Replace(".", "").Replace("-", "").Replace("/", ""), ParameterDirection.Input);
                }
            }

            if (pCotacao.Status != null)
            {
                if (!String.IsNullOrEmpty(pCotacao.Status.Id) & !pCotacao.Status.Id.Trim().Equals("999"))
                {
                    sql.Append(" AND SIT_COTACAO = " + dbUtility.Variavel("SITUACAO"));
                    dbUtility.AddParametro("SITUACAO", pCotacao.Status.Id, ParameterDirection.Input);
                }
            }

            if (pCotacao.Corretor != null)
            {
                if (!pCotacao.Corretor.IdPessoa.Equals(0))
                {
                    sql.Append(" AND CORRETOR = " + dbUtility.Variavel("COD_CORRETOR"));
                    dbUtility.AddParametro("COD_CORRETOR", pCotacao.Corretor.IdPessoa, ParameterDirection.Input);
                }
            }

            if (pCotacao.Filial != null)
            {
                if (!pCotacao.Filial.Id.Equals(0))
                {
                    sql.Append(" AND FILIAL = " + dbUtility.Variavel("FILIAL"));
                    dbUtility.AddParametro("FILIAL", pCotacao.Filial.Id, ParameterDirection.Input);
                }
            }
        }

        sql.Append(" ORDER BY NUMERO_COTACAO DESC ");

        reader = dbUtility.Consultar(sql.ToString());

        List<Cotacao> lstCotacao = new List<Cotacao>();

        while (reader.Read())
        {
            Cotacao _cot = new Cotacao();
            _cot.ParametroSistema = pCotacao.ParametroSistema;
            _cot.Apolice = new Apolice();
            _cot.Apolice.Id = reader["NUMERO_APOLICE"].ToString();
            _cot.Apolice.DataIniVigencia = Convert.ToDateTime(reader["DATA_INI_VIGENCIA_APOLICE"]);
            _cot.Apolice.DataFimVigencia = Convert.ToDateTime(reader["DATA_FIM_VIGENCIA_APOLICE"]);
            _cot.Apolice.DataEmissao = Convert.ToDateTime(DBNull.Value.Equals(reader["DATA_EMISSAO_APOLICE"]) ? null : reader["DATA_EMISSAO_APOLICE"]);
            _cot.Id = Convert.ToInt32(reader["NUMERO_COTACAO"]);
            _cot.DtEntrada = Convert.ToDateTime(reader["DATA_COTACAO"]);
            _cot.DtAlteracao = Convert.ToDateTime(reader["DATA_ALTERACAO"]);
            _cot.DtEmbarque = Convert.ToDateTime(reader["DATA_EMBARQUE"]);
            _cot.Produto = new Produto();
            _cot.Produto.Id = Convert.ToInt32(reader["COD_PRODUTO"].ToString());
            _cot.Produto.Descricao = reader["DESCRICAO_PRODUTO"].ToString();
            _cot.Produto.DescricaoDoc = reader["DSC_PROD_DOC"].ToString();
            _cot.Produto.VersaoProduto = reader["VERSAO_PRODUTO"].ToString();
            _cot.Produto.ProcessoSusep = reader["PROC_SUSEP"].ToString();
            _cot.Produto.TipoProduto = (Produto.TpProduto)Enum.Parse(typeof(Produto.TpProduto), _cot.Produto.Id.ToString().Substring(0, 7));
            _cot.Produto.Moeda = new Moeda();
            _cot.Produto.Moeda.Cambio = Convert.ToDecimal(reader["CAMBIO_MOEDA_PRODUTO"]);
            _cot.Produto.IsGerenciamentoRisco = Convert.ToBoolean(reader["IS_GERENCIAMENTO_RISCO"]);
            _cot.Proponente = new Proponente();
            _cot.Proponente.CNPJ = reader["CNPJ_CLIENTE"].ToString();
            _cot.Proponente.RazaoSocial = reader["NOME_CLIENTE"].ToString();
            _cot.Proponente.Fantasia = reader["NOME_CLIENTE"].ToString();
            _cot.Proponente.Corretor = new Corretor();
            _cot.Proponente.Corretor.IdPessoa = reader["CORRETOR"].ToString();
            _cot.Proponente.Corretor.IdCorretor = reader["SUSEP_CORRETOR"].ToString();
            _cot.Proponente.Corretor.RazaoSocial = reader["DESC_CORRETOR"].ToString();
            _cot.Proponente.Corretor.Filial = new Filial();
            _cot.Proponente.Corretor.Filial.Id = Convert.ToInt32(reader["ID_FILIAL_CORRETOR"]);
            _cot.Proponente.Corretor.Filial.Descricao = reader["DESC_FILIAL_CORRETOR"].ToString();
            _cot.Proponente.AtividadePrincipal = new AtividadePrincipal();
            _cot.Proponente.AtividadePrincipal.Id = reader["COD_RAMO_ATIVIDADE"].ToString();
            _cot.Status = new Status();
            _cot.Status.Id = reader["SIT_COTACAO"].ToString();
            _cot.Status.Descricao = reader["SIT_DESCRICAO"].ToString();
            _cot.Corretor = new Corretor();
            _cot.Corretor.IdPessoa = reader["CORRETOR"].ToString();
            _cot.Corretor.IdCorretor = reader["SUSEP_CORRETOR"].ToString();
            _cot.Corretor.RazaoSocial = reader["DESC_CORRETOR"].ToString();
            _cot.Corretor.Filial = new Filial();
            _cot.Corretor.Filial.Id = Convert.ToInt32(reader["ID_FILIAL_CORRETOR"]);
            _cot.Corretor.Filial.Descricao = reader["DESC_FILIAL_CORRETOR"].ToString();
            _cot.Corretor.Produtor = new PessoaFisica();
            _cot.Corretor.Produtor.IdPessoa = reader["COD_PRODUTOR"].ToString();
            _cot.Corretor.Produtor.Nome = reader["DSC_PRODUTOR"].ToString().Trim();
            _cot.Filial = new Filial();
            _cot.Filial.Id = Convert.ToInt32(reader["FILIAL"]);
            _cot.DataValidadeCotacao = Convert.ToDateTime(reader["VALIDADE_COTACAO"]);
            _cot.IdEmissaoSeguradora = Convert.ToInt32(reader["C_EMS_SEG"]);
            _cot.IdContrato = reader["U_CTR_SEG"].ToString();
            _cot.IdProposta = reader["U_PRP"].ToString();
            _cot.Origem = new Local();
            _cot.Origem.Id = Convert.ToInt32(reader["ORIGEM"]);
            _cot.Origem.Descricao = reader["DESCRICAO_ORIGEM"].ToString();
            _cot.Origem.Complemento = new Local();
            _cot.Origem.Complemento.Id = Convert.ToInt32(reader["COMPLEMENTO_ORIGEM"]);
            _cot.Origem.Complemento.Descricao = reader["DESCRICAO_COMPLEMENTO_ORIGEM"].ToString();
            _cot.Destino = new Local();
            _cot.Destino.Id = Convert.ToInt32(reader["DESTINO"]);
            _cot.Destino.Descricao = reader["DESCRICAO_DESTINO"].ToString();
            _cot.Destino.Complemento = new Local();
            _cot.Destino.Complemento.Id = Convert.ToInt32(reader["COMPLEMENTO_DESTINO"]);
            _cot.Destino.Complemento.Descricao = reader["DESCRICAO_COMPLEMENTO_DESTINO"].ToString();
            _cot.Transporte = new Transporte();
            _cot.Transporte.EnMeioTransporte = (Transporte.MTransporte)Enum.Parse(typeof(Transporte.MTransporte), reader["MEIO_TRANSPORTE"].ToString());
            _cot.Transporte.Id = reader["MEIO_TRANSPORTE"].ToString();
            _cot.Transporte.IdNavio = Convert.ToInt32(reader["ID_NAVIO"]);
            _cot.Transporte.TipoVeiculo = reader["TIPO_VEICULO"].ToString();
            _cot.Transporte.IdentificacaoVeiculo = reader["VEICULO_TRANSPORTE"].ToString();
            _cot.Mercadoria = new Mercadoria();
            _cot.Mercadoria.IdGrupoMercadoria = Convert.ToInt32(reader["GRUPO_MERCADORIA"]);
            _cot.Mercadoria.TipoMercadoria = (Mercadoria.TpMercadoria)Enum.Parse(typeof(Mercadoria.TpMercadoria), reader["TIPO_MERCADORIA"].ToString());
            _cot.Mercadoria.Id = reader["ID_MERCADORIA"].ToString();
            _cot.Mercadoria.Descricao = reader["DESCRICAO_MERCADORIA"].ToString();
            _cot.Mercadoria.ComplementoMercadoria = reader["COMPLEMENTO_MERCADORIA"].ToString();
            _cot.Mercadoria.IsContainer = reader["IS_CONTAINER"].ToString();
            _cot.Mercadoria.PercentualFranquia = Convert.ToDecimal(reader["PERC_FRANQUIA"].ToString());
            _cot.Mercadoria.IsRetornoEvento = String.IsNullOrEmpty(reader["IS_RETORNO_EVENTO"].ToString()) ? String.Empty : reader["IS_RETORNO_EVENTO"].ToString();
            _cot.Embalagem = new Embalagem() { Id = Convert.ToInt32(reader["ID_EMBALAGEM"]) };
            _cot.IdentificacaoPagamento = reader["IDENTIFICACAO_PAGAMENTO"].ToString();
            _cot.Cobertura = new Cobertura();
            _cot.Cobertura.Id = Convert.ToInt32(reader["ID_COBERTURA_BASICA"]);
            _cot.Cobertura.Descricao = reader["DESCRICAO_COBERTURA"].ToString();

            _cot.ValorIOF =  Convert.ToDecimal(reader["VALOR_IOF"]);
            _cot.ValorIofCalculado = Convert.ToDecimal(reader["VALOR_IOF_CALCULADO"]);

            _cot.VlrCustoMercadoria = Convert.ToDecimal(reader["VLR_FOB"]);
            _cot.VlrCustoMercadoriaConvert = Convert.ToDecimal(reader["VLR_FOB_CONVERT"]);
            _cot.MoedaCustoMercadoria = new Moeda() { Id = Convert.ToInt32(reader["MOEDA_FOB"]), Cambio = Convert.ToDecimal(reader["CAMBIO_FOB"]) };
            _cot.VlrPremioFOB = Convert.ToDecimal(reader["VLR_PREMIO_FOB"]);

            _cot.VlrValorFrete = Convert.ToDecimal(reader["VLR_FRETE"]);
            _cot.VlrValorFreteConvert = Convert.ToDecimal(reader["VLR_FRETE_CONVERT"]);
            _cot.MoedaFrete = new Moeda() { Id = Convert.ToInt32(reader["MOEDA_FRETE"]), Cambio = Convert.ToDecimal(reader["CAMBIO_FRETE"]) };
            _cot.VlrDespesas = Convert.ToDecimal(reader["VLR_DESPESAS"]);
            _cot.VlrPremioFrete = Convert.ToDecimal(reader["VLR_PREMIO_FRETE"]);

            _cot.VlrDespesasConvert = Convert.ToDecimal(reader["VLR_DESPESAS_CONVERT"]);
            _cot.MoedaDespesas = new Moeda() { Id = Convert.ToInt32(reader["MOEDA_DESPESAS"]), Cambio = Convert.ToDecimal(reader["CAMBIO_DESPESAS"]) };
            _cot.PercDespesas = Convert.ToDecimal(reader["PERCENTUAL_DESPESAS"]);
            _cot.VlrPremioDespesas = Convert.ToDecimal(reader["VLR_PREMIO_DESPESAS"]);

            _cot.VlrLucrosEsperados = Convert.ToDecimal(reader["VLR_LUCRO"]);
            _cot.VlrLucrosEsperadosConvert = Convert.ToDecimal(reader["VLR_LUCRO_CONVERT"]);
            _cot.MoedaLucrosEsperados = new Moeda() { Id = Convert.ToInt32(reader["MOEDA_LUCRO"]), Cambio = Convert.ToDecimal(reader["CAMBIO_LUCRO"]) };
            _cot.PercLucrosEsperados = Convert.ToDecimal(DBNull.Value.Equals(reader["PERCENTUAL_LUCRO"]) ? 0 : reader["PERCENTUAL_LUCRO"]);
            _cot.VlrPremioLucrosEsperados = Convert.ToDecimal(reader["VLR_PREMIO_LUCRO"]);

            _cot.VlrImportanciaSeguradaTotal = Convert.ToDecimal(reader["V_IS_TOTAL"]);
            _cot.VlrPremioTotal = Convert.ToDecimal(reader["VLR_PREMIO_TOTAL"]);
            _cot.VlrPremioLiquido = Convert.ToDecimal(reader["VLR_PREMIO_LIQUIDO"]);
            _cot.VlrPremioCalculado = Convert.ToDecimal(reader["VLR_PREMIO_CALCULADO"]);
            _cot.VlrIImportacao = Convert.ToDecimal(DBNull.Value.Equals(reader["VLR_IMP_II_ORI"]) ? 0 : reader["VLR_IMP_II_ORI"]);
            _cot.VlrIImportacaoConvert = Convert.ToDecimal(DBNull.Value.Equals(reader["VLR_IMP_II"]) ? 0 : reader["VLR_IMP_II"]);
            _cot.PercImpostoIImportacao = Convert.ToDecimal(DBNull.Value.Equals(reader["PERCENTUAL_IMP_II"]) ? 0 : reader["PERCENTUAL_IMP_II"]);
            _cot.MoedaImpostoII = new Moeda();
            _cot.MoedaImpostoII.Id = Convert.ToInt32(DBNull.Value.Equals(reader["MOEDA_II"]) ? 0 : reader["MOEDA_II"]);
            _cot.MoedaImpostoII.Cambio = Convert.ToDecimal(DBNull.Value.Equals(reader["CAMBIO_II"]) ? 0 : reader["CAMBIO_II"]);

            _cot.VlrIPI = Convert.ToDecimal(DBNull.Value.Equals(reader["VLR_IMP_IPI_ORI"]) ? 0 : reader["VLR_IMP_IPI_ORI"]);
            _cot.VlrIPIConvert = Convert.ToDecimal(DBNull.Value.Equals(reader["VLR_IMP_IPI"]) ? 0 : reader["VLR_IMP_IPI"]);
            _cot.PercImpostoIPI = Convert.ToDecimal(DBNull.Value.Equals(reader["PERCENTUAL_IMP_IPI"]) ? 0 : reader["PERCENTUAL_IMP_IPI"]);
            _cot.MoedaImpostoIPI = new Moeda();
            _cot.MoedaImpostoIPI.Id = Convert.ToInt32(DBNull.Value.Equals(reader["MOEDA_IPI"]) ? 0 : reader["MOEDA_IPI"]);
            _cot.MoedaImpostoIPI.Cambio = Convert.ToDecimal(DBNull.Value.Equals(reader["CAMBIO_IPI"]) ? 0 : reader["CAMBIO_IPI"]);

            _cot.VlrICMS = Convert.ToDecimal(DBNull.Value.Equals(reader["VLR_IMP_ICMS_ORI"]) ? 0 : reader["VLR_IMP_ICMS_ORI"]);
            _cot.VlrICMSConvert = Convert.ToDecimal(DBNull.Value.Equals(reader["VLR_IMP_ICMS"]) ? 0 : reader["VLR_IMP_ICMS"]);
            _cot.PercImpostoICMS = Convert.ToDecimal(DBNull.Value.Equals(reader["PERCENTUAL_IMP_ICMS"]) ? 0 : reader["PERCENTUAL_IMP_ICMS"]);
            _cot.MoedaImpostoICMS = new Moeda();
            _cot.MoedaImpostoICMS.Id = Convert.ToInt32(DBNull.Value.Equals(reader["MOEDA_ICMS"]) ? 0 : reader["MOEDA_ICMS"]);
            _cot.MoedaImpostoICMS.Cambio = Convert.ToDecimal(DBNull.Value.Equals(reader["CAMBIO_ICMS"]) ? 0 : reader["CAMBIO_ICMS"]);

            _cot.VlrPIS = Convert.ToDecimal(DBNull.Value.Equals(reader["VLR_IMP_PIS_ORI"]) ? 0 : reader["VLR_IMP_PIS_ORI"]);
            _cot.VlrPISConvert = Convert.ToDecimal(DBNull.Value.Equals(reader["VLR_IMP_PIS"]) ? 0 : reader["VLR_IMP_PIS"]);
            _cot.PercImpostoPIS = Convert.ToDecimal(DBNull.Value.Equals(reader["PERCENTUAL_IMP_PIS"]) ? 0 : reader["PERCENTUAL_IMP_PIS"]);
            _cot.MoedaImpostoPIS = new Moeda();
            _cot.MoedaImpostoPIS.Id = Convert.ToInt32(DBNull.Value.Equals(reader["MOEDA_PIS"]) ? 0 : reader["MOEDA_PIS"]);
            _cot.MoedaImpostoPIS.Cambio = Convert.ToDecimal(DBNull.Value.Equals(reader["CAMBIO_PIS"]) ? 0 : reader["CAMBIO_PIS"]);

            _cot.VlrCOFINS = Convert.ToDecimal(DBNull.Value.Equals(reader["VLR_IMP_COFINS_ORI"]) ? 0 : reader["VLR_IMP_COFINS_ORI"]);
            _cot.VlrCOFINSConvert = Convert.ToDecimal(DBNull.Value.Equals(reader["VLR_IMP_COFINS"]) ? 0 : reader["VLR_IMP_COFINS"]);
            _cot.PercImpostoCOFINS = Convert.ToDecimal(DBNull.Value.Equals(reader["PERCENTUAL_IMP_COFINS"]) ? 0 : reader["PERCENTUAL_IMP_COFINS"]);
            _cot.MoedaImpostoCOFINS = new Moeda();
            _cot.MoedaImpostoCOFINS.Id = Convert.ToInt32(DBNull.Value.Equals(reader["MOEDA_COFINS"]) ? 0 : reader["MOEDA_COFINS"]);
            _cot.MoedaImpostoCOFINS.Cambio = Convert.ToDecimal(DBNull.Value.Equals(reader["CAMBIO_COFINS"]) ? 0 : reader["CAMBIO_COFINS"]);

            _cot.VlrImpostos = Convert.ToDecimal(DBNull.Value.Equals(reader["VLR_IMPOSTOS_ORI"]) ? 0 : reader["VLR_IMPOSTOS_ORI"]);
            _cot.VlrImpostosConvert = Convert.ToDecimal(DBNull.Value.Equals(reader["VLR_IMPOSTOS"]) ? 0 : reader["VLR_IMPOSTOS"]);
            _cot.MoedaImpostos = new Moeda();
            _cot.MoedaImpostos.Id = Convert.ToInt32(DBNull.Value.Equals(reader["MOEDA_IMPOSTOS"]) ? 0 : reader["MOEDA_IMPOSTOS"]);
            _cot.MoedaImpostos.Cambio = Convert.ToDecimal(DBNull.Value.Equals(reader["CAMBIO_IMPOSTOS"]) ? 0 : reader["CAMBIO_IMPOSTOS"]);

            _cot.PercentualDespesasLucrosImpostos = Convert.ToDecimal(DBNull.Value.Equals(reader["PERCENTUAL_LUC_DESP_IMP"]) ? 0 : reader["PERCENTUAL_LUC_DESP_IMP"]);
            _cot.VlrContainer = Convert.ToDecimal(DBNull.Value.Equals(reader["VLR_CONTAINER"]) ? 0 : reader["VLR_CONTAINER"]);
            _cot.Proposta = new Proposta();
            _cot.Proposta.Id = Convert.ToDecimal(reader["NUM_PROPOSTA"]);
            _cot.Proposta.Digito = reader["DIG_PROPOSTA"].ToString();
            _cot.Proposta.DtVencimentoProposta = Convert.ToDateTime(reader["DATA_VENCIMENTO_PROPOSTA"]);
            _cot.Proposta.Banco = new Banco();
            _cot.Proposta.Banco.Id = reader["COD_BANCO"].ToString();
            _cot.SerieDocumento = reader["SERIE_DOCUMENTO"].ToString();
            _cot.NumeroDocumento = reader["NUMERO_DOCUMENTO"].ToString();
            //_cot.PercComissao = Convert.ToDecimal(reader["PERCENTUAL_COMISSAO"]);
            _cot.Observacao = reader["OBSERVACAO"].ToString();

            _cot.Certificado = new Certificado();
            _cot.Certificado.TipoIconterms = reader["INCOTERM"].ToString();
            _cot.Certificado.Moeda = new Moeda();
            _cot.Certificado.Moeda.Id = Convert.ToInt32(reader["MOEDA_CERTIFICADO"]);
            _cot.Certificado.Moeda.Cambio = Convert.ToDecimal(reader["CAMBIO_CERTIFICADO"]);
            _cot.Certificado.VlrPremioTotal = Convert.ToDecimal(reader["PREMIO_CERTIFICADO"]);
            _cot.Certificado.VlrImportanciaSeguradaTotal = Convert.ToDecimal(reader["VLR_TOTAL_CERTIFICADO"]);
            _cot.IsCartaCredito = reader["IS_CARTA_CREDITO"].ToString();
            _cot.Incoterms = new Entities.Geral.Incoterms();
            _cot.Incoterms.Id = reader["COD_INCOTERM"].ToString();
            _cot.Incoterms.Descricao = reader["DESC_INCOTERM"].ToString();

            _cot.Incoterms.IsPontaImportacao = String.IsNullOrEmpty(reader["IS_PONTA_IMPORTACAO"].ToString().Trim()) ? "" : reader["IS_PONTA_IMPORTACAO"].ToString();
            _cot.Incoterms.IsDestinoExportacao = String.IsNullOrEmpty(reader["IS_DESTINO_EXPORTACAO"].ToString().Trim()) ? "" : reader["IS_DESTINO_EXPORTACAO"].ToString();
            _cot.IsCifFechado = reader["IS_CIF_FECHADO"].ToString();

            _cot.VlrBeneficiamento = Convert.ToDecimal(reader["VALOR_BENEF"]);
            _cot.VlrPremioBeneficiamento = Convert.ToDecimal(reader["PREMIO_BENEF"]);
            _cot.IsRetornoBeneficiamento = String.IsNullOrEmpty(reader["IS_RETORNO_BENEF"].ToString()) ? "0" : reader["IS_RETORNO_BENEF"].ToString();

            _cot.HrEmissao = reader["HR_EMISSAO"].ToString();
            _cot.DtEmissao = reader["DT_EMISSAO"].ToString();

            _cot.FormaPagamento = reader["FORMA_PAGAMENTO"].ToString();
            _cot.CodBanco = reader["BANCO"].ToString();
            _cot.CodAgencia = reader["AGENCIA"].ToString();
            _cot.ContaCorrente = reader["CONTA_CORRENTE"].ToString();

            lstCotacao.Add(_cot);
        }

        dbUtility.FecharConexao();

        return lstCotacao;
    }
    catch (Exception ex)
    {
        ...
    }
    finally
    {
        dbUtility.FecharConexao();
    }
}


text:
Q: Flight controler isLowerThanBatteryWarningThreshold updates several seconds after the drone is returning home I'm writing a mobile SDK based app and I want to notify the users that there is an "isLowerThanBatteryWarningThreshold" warning and give them the chance to "cancelGoHome" through the app.
The problem is that until the warning state in the flight controller state callback is updated, the remote controller is already beeping for several seconds and the drone (Matrice 100) already starts landing.
is there a way to get/listen/catch the warning faster?
The android SDK version I am using is 4.4.1

A: pls try to update to the latest version of MSDK, 4.7.1 has been released right now, or try to use the key: IS_LOWER_THAN_BATTERY_WARNING_THRESHOLD under FlightControllerKey class, it could directly notify the event, the following is a guide page in github about how to use the key:
https://github.com/dji-sdk/Mobile-SDK-Android/issues/248#issuecomment-371733561


text:
Q: Nginx reverse proxy gives 404 with static content requests Our setup is two servers:

*

*One serves WP installation

*The other one is used for extra custom functionality.

Server 1 that hosts WP is using Nginx as web server and reverse proxy to Server 2.
In Server 1 we have a simple location block for reverse proxy:
location /foo/ {
   proxy_pass        http://1.1.1.2/foo/;
   proxy_set_header  X-Real-IP  $remote_addr;
   proxy_set_header  Host       $host;
   proxy_redirect off;
   proxy_intercept_errors on;
}

In Server 2 we also have a location block because the platform requires a bit URL rewriting. It's a bit mixed bag because the platform loads some content via index.php?args but there's also static content:
location /foo/ {
   index index.php;
   try_files $uri $uri/ /foo/index.php?$args;
}

The problem we are facing is that while domain.com/foo/?bar, domain.com/foo/bar works great, domain.com/foo/img/photo.png gives 404.
I assume this is due try_files but I can't seem to get it working.

A: This wasn't about reverse proxy after all. There was another regex location block in Server 1 that trapped all image requests and they didn't make it to reverse proxy at all. Problem solved.
posted again as an answer to mark the question as solved


text:
Q: R markdown kable strikethrough row(s)? Hi I have table that I would like to print in using kable.
ds <- read.table(header = TRUE, text ="
                 g1 color
                 A red
                 A yellow
                 B red
                 C red
                 C yellow
                 ")

so let say in when this prints to pdf is it possible to have the entire row strikethough if it contains "yellow"?
thanks in advance.
A.

A: Use package: 'formattable' to do this in html. Not sure about pdf.
library(formattable)
ds <- read.table(header = TRUE, text ="
             g1 color
             A red
             A yellow
             B red
             C red
             C yellow
             ")

formattable(ds, list(
area(row = which(ds$color == "yellow")) ~ formatter("span",
  style = "text-decoration:line-through")))

If you want to use kable then you can mutate the row with formatter function and use kableExtras package to output to html
library(kableExtra)
library(formattable)
library(dplyr)

    ds <- read.table(header = TRUE, text ="
                     g1 color
                     A red
                     A yellow
                     B red
                     C red
                     C yellow
                     ")

    ds <- ds %>% mutate(g1 = formatter("span",
        style = x ~ style("text-decoration" = ifelse(ds$color == "yellow", "line-through", NA)))(g1),
        color = formatter("span",
        style = x ~ style("text-decoration" = ifelse(ds$color == "yellow", "line-through", NA)))(color))

    kable(ds, "html", escape = F)

At this point you can knit to html and use a html to pdf converter and call a system command from R.
system("wkhtmltopdf --javascript-delay 1 --dpi 300 in.html out.pdf")

A: Hat tip to Hao Zhu
library(kableExtra)
library(formattable)
library(dplyr)

ds <- read.table(header = TRUE, text ="
                 g1 color
                 A red
                 A yellow
                 B red
                 C red
                 C yellow
                 ")

ds %>% as.data.frame() %>% mutate_if(is.factor,as.character) %>%
mutate(
g1 = ifelse(
  color == "yellow",
  paste0("\\sout{", g1, "}"), g1
  ), color = ifelse(
  color == "yellow",
  paste0("\\sout{", color, "}"), color
  )
) %>%
kable("latex", escape = F, booktabs = T)

Note: need to include ulem TeX package while compiling (e.g., YAML header of Rmd document)


text:
Q: How to scale your 1 server Rails application I have a rails application running on a single VPS that uses passenger, apache and MySQL. I am moving this to Amazon AWS with the following simple setup:
ELB > Web Server > MySQL
Lets say I am expecting a huge spike in daily users and want to start to scale this out on Amazon AWS using multiple instances. Where does a newbie start on this journey? Do I simply create an AMI from my production configured web server and get the ASG to launch these when required?
I understand that AWS increases the number of instances using auto scale groups as the load demands it, but do I need to architect anything differently in my Rails application for it to run at scale across multiple interfaces?

A: The problem with scaling horizontally is that it really depends on the application. There's no "just-add-water" ways to do it.
But there are some generic recipes you can follow in the beginning:

*

*Extract MySQL server into a separate instance, which is capable of holding a higher load. Then create as many worker (i.e. app) instances that connect to the MySQL database as you need. You can keep doing so before your MySQL server gets saturated with requests, and can no longer keep up with the load.

*When you're done with step 1, you can add MySQL replicas and setup a master-slave replication. This will leave you with a MySQL cluster, where one server can accept writes and all the others are read-only. After your set it up, change your application to send SELECT's to read-only replicas and INSERT/DELETE/UPDATE's to the writeable master server. This approach is based on the fact that most of the applications do reads way more often than writes. It can be not the case for you, but if it is, it'll keep your afloat pretty long. Right before you saturate MySQL master server write performance.

*Once you've squeezed everything from step 2, you can go ahead and shard the data. This is now becoming more and more dependent on your application. But I will provide a blind example in order to convey the idea. Say, you have a user-centric application (e.g. a private photo-album, with no sharing capabilities), and each user has a name. In this case you can make two completely independent clusters, where the first one will serve users with names starting A-M, and the second one will serve ones with N-Z. It essentially makes the load twice as less, but complicates the whole architecture.
Though generic, these recipes can help you build a pretty solid application capable of serving millions of users daily before you're forced to bring up more exotic ways of scaling.
Hope this helps!


text:
Q: setInterval function not always working as intended So, I tried to do an animated banner (containing two images- #baner1 and #baner2. When one fades out the second fades in). It works properly most of the times, but sometimes these images change rapidly (like one second after each other, despite the timer is 12000 miliseconds). Any idea what causes it?
My code:
setInterval(()=>{
  $('#baner1').fadeOut(2000);
  $('#baner2').fadeIn(2000);
},12000)

setInterval(()=>{
  $('#baner1').fadeIn(2000);
  $('#baner2').fadeOut(2000);
},24000)

Also, it's (as far as I know) my only code affecting these images.
Thanks in advance for help.

A: Your callbacks are overlapped.
They go like a, a+b, a, a+b...
The a+b is sometimes executed as b+a (because two setIntervals aren't synchronized perfectly) and I think this is what's causing you trouble.
What you meant to do is a, b, a, b...
You can try changing you logic to use a single setInterval, and use a variable to know if it's the a "turn" or the b "turn". Something like this:
let nextTurn = 'a';
setInterval(()=>{
    if (nextTurn === 'a') {
        $('#baner1').fadeOut(2000);
        $('#baner2').fadeIn(2000);
        nextTurn = 'b';
    } else {
        $('#baner1').fadeIn(2000);
        $('#baner2').fadeOut(2000);
        nextTurn = 'a';
    }
},12000)


text:
Q: Cassandra - order of consistency I know that in Cassandra, there's no strong consistency unless you explicitly request it (and even then, there're no transactions).
However, I'm interested in the "order" of consistency. Take the following example:
In a database node, there are 3 nodes (A, B and C). Two insert queries are sent trough the same CQL-connection (or thrift for that matter, I don't think that's relevant to this question anyway). Both operate on different tables (this might be relevant).
INSERT INTO table_a (id) VALUES (0)
INSERT INTO table_b (id) VALUES (1)

Directly after the questions have been successfuly executed on the node that they're sent to, it goes down. The node may or may not have succeeded in propogating these two queries to B and C.
Now, I'd think that there is an order of consistency. Either both are successfully propogated and executed on B and C, or only the first query is, or both are. I'd think that, under no circumstances only the second query is propogated and executed, and not the first (because of the order of tcp packets, and the fact that obviously, all nodes share the same consistency strategy).
Am I right?

A: You're right, at least on the node you connect to.  What happens on the server is, for a consistency level ONE write:

*

*Receive insert to table_a

*Write into commitlog

*Acknowledge write to client

*Receive insert to table_b

*Write into commitlog

*Acknowledge write to client

The key is that there is a global commitlog.  So you can't flush it for one table and not another.  Also, because the writes are sequential, you know the write was made to the commitlog before returning.
The commitlog gets flushed periodically (by default), so could flush after 2 but before 5, in which case only the insert to table_a is kept in the event of a crash immediately after 4 or 5.
On other nodes, the ordering isn't guaranteed, because the write is done asynchronously and writes are multithreaded.  But it's not possible to totally lose the first write and not the second if the original node doesn't fail permanently.
If you want stronger guarantees, you can use Cassandra's batching.
Cassandra can guarantee that neither or both of the writes succeed if you write them as a batch.  For even old Cassandra versions, if updates within a batch have the same row key (partition key in CQL speak), even if they are in different column families (tables), they will get committed to the commitlog atomically.
New in 1.2 is a batchlog across multiple rows that offers the same guarantees - either all the batch gets applied or none.


text:
Q: Error join table with lambda expression c# I have 2 tables and I want join them with a lambda expression.
The code looks like this:
  var maintenance = maintenanceService.GetAll();
  var mDetail = maintenanceDetailService.GetAll();

  var data = maintenance.Join
  (
      mDetail,
      m => m.Id,
      md => md.MaintenanceId,
      (i, m, md) => new VehicleFuelReportViewModel
                    {
                       MaintenanceDate = m.MaintenanceDate
                    }
 );

I get this error:

Error 12  The type arguments for method
      'System.Linq.Enumerable.Join
      (System.Collections.Generic.IEnumerable,
       System.Collections.Generic.IEnumerable,
       System.Func,
       System.Func, System.Func)'
       cannot be inferred from the usage. Try specifying the type arguments explicitly.

maintenance and mDetail are IEnumerable<>. Can anyone help me? Thank you

A: class NewVehicleFuelReportViewModel
{
   public int Index { get; set; }
   public MaintenanceDate { get; set; }
}

var data = maintenance.Join(mDetail,
   m => m.Id,
   md => md.MaintenanceId,
   ( m, md) => new VehicleFuelReportViewModel {
      MaintenanceDate = m.MaintenanceDate
   });
   int i = 0;
   var dataWithIndex = data.select(d=>{
   var tempdata = new NewVehicleFuelReportViewModel();
   tempdata.Indx = i++;
   tempdata.MaintenanceDate = d.MaintenanceDate;
   return tempdata;
}).ToList();

A: There is not an overload of Join that takes an index parameter in the third lambda.  If you need a number column in the result then do a subsequent Select:
var data = maintenance.Join(mDetail,
   m => m.Id,
   md => md.MaintenanceId,
   (m, md) => m.MaintenanceDate)
                      .Select((i, m) new VehicleFuelReportViewModel {
      MaintenanceDate = m.MaintenanceDate,
      Index = i}) ;

Although I'm confused why you're doing a Join if you're not using any data from the joined table.  Did you mean to do a count of related records?


text:
Q: Time setting for hour i want to get hours from 18:00 pm to 6:00 am of the next day for each day on the week. How can I get this time for plotBands in GWT/highchart? I want to highlight this nighttime on the charts.
This is asample in JS, where the date was set from 2 to 4 June and the plotband was drawn. How can I do the same but for getting hours in GWT highcharts?
chart.setPlotBands(xaxis.createPlotBand()
                    .setFrom(time.getTime())// how to get here 18:00 pm hour?
                    .setTo(time.getTime())// and here 6:00 am hour?
                    .setColor("#060606"));

I tryed it with utc, get nothing, but don't think that is right way:
 .setFrom(time.getTime().UTC(2014, 7, 7, 18, 0, 0))
 .setFrom(time.getTime().UTC(2014, 7, 8, 6, 0, 0))

I want "mark time x to time y with color z" and get something like on this picture with color for certain time from 18 to 6

A: I don't think there's a way to highlight a pattern directly with highchart. I made a quick sketch, but did not test the result in GWT/highchart. This method highlights the daily period described by the int fields hourStart (18 in your example) and lengthInHours (12 as per your description):
/*
 * start and end are the lower and upper bounds of your chart data
 *
 */
public void highlightBands(Date start, Date end) {

  Date startDay = toLocalDay(start);
  Date endDay = toLocalDay(end);
  Date current = add(startDay, Calendar.DAY_OF_MONTH, -1);

  while (current.before(endDay)) {
    Date bandStart = add(current, Calendar.HOUR_OF_DAY, hourStart);
    Date bandEnd = add(bandStart, Calendar.HOUR_OF_DAY, lengthInHours);
    PlotBand band = x.createPlotBand().setFrom(bandStart).setTo(bandEnd);
    x.addPlotBands(band);
    current = add(current, Calendar.DAY_OF_MONTH, 1);
  }
}

The posted code is a simplified version of this gist, just to show my approach and without using anything outside java.util


text:
Q: How to declare the nsurl variable with inital value as nil and also for nsarray? This is a simple and basics but I had a doubt that if it is declared globally with out initial value what happens ?
NSURL *finalURL; // here i need to initial value as nil if it is like this NSURL *finalURL=@""; giving warning.

nssarry *array=nil; // is this correct.

Please give the reply,
Thank You,
Madan Mohan.

A: It should be static NSURL *finalURL = nil; and you have to define that inside a method. Then you can check if finalURL == nil and init it.
- (void)method
{
    static NSURL *url = nil;
    if(url == nil) {
        url = [[NSURL urlWithString:@"http://host"] retain];
    }
}

You can't do NSURL *finalURL = @"" because @"" is a String and not an NSURL!
NSArray *array = nil; is only correct if you capitalize NSArray correct!


text: Q: Which would be faster out of compact vs reduce to remove nil elements from an array? Say you have an array in ruby and you want to remove all the nil elements, typically you would use compact, but could having a reducer that looks like .reduce([]) { |x, i| x<<i unless i.nil?; x } do the same thing faster?


text: Q: Don't display status bar for navigation tabs in react-bootstrap In react-bootstrap the tabs are rendered as a tags with href='#'. This means that on hover and after clicking a tab, there will be <site-url># in the browser's status bar. This doesn't really mean anything to the user so I'd like to not show that. I've tried using preventDefault() and removeAttribute('href') in the onSelect handler but it doesn't seem to work. Is there any decent way to do this while still using react-bootstrap?


text:
Q: Techniques for counting items in a category I'm building an e-shop using RDBMS, and wanted to know what is the most efficient way to represent the number of items in a particular category? So for instance, my category menu would look something like this:

*

*Books (212)

*MP3 players (13)

*Footwear (562)

What techniques do you use to get those numbers? I'm using PostgreSQL 9.1, but I assume the mechanics should be similar throughout all DBMSs.

A: You need GROUP BY
SELECT category, count(*)
FROM items
GROUP BY category

This will count the number of items in the table for each category.

A: Well, the actual query for what you want is:
SELECT category || ' (' || cast(count(*) as varchar(255)) || ')' as entry
FROM items
GROUP BY category


text:
Q: How to trim values and send to deepEquals method () public static void main(String args[]){
         String [] a={"A","B"};
         String[] b ={"  B"," A"};
         Arrays.sort(a);
         Arrays.sort(b);
         System.out.println(Arrays.deepEquals(a,b));
}

I want to compare two string arrays and should return true values but its giving a false value since String[] b values has space. How do I trim my values and send to deepEquals method .

A: You can go through each element of the array and use the trim function.
String[] trimmedA = new String[a.length];
    for (int i = 0; i < a.length; i++)
        trimmedA[i] = a[i].trim();

You can also check that the lengths of a and b are equal. If they aren't you can return false right away without sorting and trimming.
On the other hand, if you do not need to use the original strings again, you can do the trimming in place:
for (int i = 0; i < a.length; i++)
    a[i] = a[i].trim();

A: You can apply the trim function on each of the strings first.

public String trim()
    Returns a copy of the string, with leading and
    trailing whitespace omitted.

Something as the following should work:
void trimAll(String[] vec){
    for (int i = 0; i < vec.length; i++)
        vec[i] = vec[i].trim();
}

public static void main(String args[]){
         String [] a={"A","B"};
         String[] b ={"  B"," A"};
         trimAll(a);
         trimAll(b);
         Arrays.sort(a);
         Arrays.sort(b);
         System.out.println(Arrays.deepEquals(a,b));
}

Reference here

A: Java 8's streams make this pretty neat:
public static void main(String args[]){
    String [] a={"A","B"};
    String[] b ={"  B"," A"};
    a = trimAndSort(a);
    b = trimAndSort(b);
    System.out.println(Arrays.deepEquals(a,b));
}

private static String[] trimAndSort(String[] arr) {
    return Arrays.stream(arr).map(String::trim).sorted().toArray(String[]::new);
}

Note that since you're dealing with a one-dimensional array, you don't really need to use Arrays#deepEquals, and Arrays#equals would suffice.

A: trim() doesn't match all whitespace either (it matches all characters that have a value <= space, most of which aren't technically whitespace). Therefore, this would be feasible.
for(int i=0;i<b.length,i++)
{
  b[i] = b.replaceAll("\\p{Z}","");
}


text:
Q: Calculate distance between two points in spherical coordinate I try to calculate distances between two points in spherical coord.
There are two latitude and longitude array which size is around 1100000
lat = [-10, 10, 1, 82, ..., -72]
lon = [120, -58, 13, 22, ..., 122]

Also, there is a standard point
loc_lat = -60
loc_lon = -50

so I try to calculate using below code, but It takes too much time.
Is there any efficient way ?
from geopy import distance
D_from_loc = [distance.distance((lat[i], lon[i]), (loc_lat, loc_lon)).km for i in range(len(lon))]

A: sklearn implementations is quite fast;
import numpy as np
from sklearn.metrics import pairwise_distances

size = 1100000
X = np.random.random( (size,2))
Y = np.array([[-60,-50]])

radians_X = np.radians(X)
radians_Y = np.radians(Y)

result = pairwise_distances(radians_X,radians_Y, metric='haversine')
result * 6371000/1000  # multiply by Earth radius to get kilometers

This will take <1 second. Make sure to test if you have lat/long order right, which for sklearn is (lat,long) pairs. Also, the result might slightly differ from other implementations, as the earth needs to be approximated as a big sphere. The choose of the exact radius has (small) impact.


text:
Q: Days in year between certain dates In OpenOffice (or Excel), I need to calculate the exact number of days that a certain date range falls within a certain year. Eg. the date range 2009/1/1 to 2010/11/01 has 365 days in 2009 and 305 days in 2010. So far it seems a function days_in_year(year;startdate;enddate) does not exist and doing something similar in a formula using WHEN would be quite a long formular.
Does anybody know something small for this purpose (without macros)?

A:
=MAX(MIN(DATE(year,12,31),enddate)-MAX(DATE(year,1,1),startdate)+1,0)

(for Excel)

A: To calculate the number of days between two dates, you can use use the subtraction (-) operator.
A
Date
6/8/2007
6/20/2007

Formula     Description
--------    ------------
=A3-A2      Days between the two dates (12)


text:
Q: Sending Cookies over WCF using the ChannelFactory I use an IOC container which provides me with IService.
In the case where IService is a WCF service it is provided by a channel factory
When IService lives on the same machine it is able to access the same cookies and so no problem however once a WCF Service is called it needs to be sent those cookies.
I've spent a lot of time trying to find a way to send cookies using a channel factory and the only way I could find that works is the following
var cookie = _authenticationClient.GetHttpCookie();
HttpRequestMessageProperty httpRequestProperty = new HttpRequestMessageProperty();
httpRequestProperty.Headers.Add(HttpRequestHeader.Cookie, cookie.Name + "=" + cookie.Value);
using(var scope = new OperationContextScope((IClientChannel)_service))
{
   OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;
   var result = _service.Add(details);
   if (result.Result == RPGResult.Success)
   {
       return RedirectToAction("Index", "Home", result.Id);
   }
}

The problem with me using that method is that I have to know that I'm calling a WCF Service which is not always the case. I've tried writing a wrapper for the ChannelFactory that opens a new operationcontextscope when it creates a new service and various other solutions but nothing has worked.
Anyone have any experience with sending cookies over WCF Services?
I found a solution involving using SilverLight, unfortunately I'm not using silverlight, the solution is here: http://greenicicleblog.com/2009/10/27/using-the-silverlight-httpclient-in-wcf-and-still-passing-cookies/
Unfortunately standard .net doesn't contain the IHttpCookieContainerManager interface
Ideally I would be able to use something similar,i.e. I would be able to tell the channelfactory to pass a cookie whenever it opened.
If anyone has a better way to pass a token that is used for authentication that would be appreciated too.

A: I have a solution where I create a proxy class of IService and then every time a method on IService is called it invokes the proxy created by the channel factory but the call itself is wrapped in an operationcontextscope just like the one I have in my question.
I used the proxy factory from this link  http://www.codeproject.com/KB/cs/dynamicproxy.aspx


text:
Q: Convert int to value when changing datatype in column Is it possible with liquibase to do some kind of mapping when doing a modifyDataType?
Considering the following example:
<changeSet id="1" author="me">
    <createTable tableName="person">
        <column name="id" type="int">
            <constraints primaryKey="true" nullable="false" />
        </column>
        <column name="firstName" type="varchar(100)"></column>
        <column name="lastName" type="varchar(100)"></column>
        <column name="marital_status" type="int">
            <constraints nullable="false" />
        </column>
    </createTable>
</changeSet>
<changeSet id="2" author="me">
    <modifyDataType tableName="person" columnName="type"
        newDataType="varchar(36)" />
</changeSet>

I would like in my column 'type' that the following mapping occurs:
0->single
1->married
etc..

Is this possible with liquibase? I'm using it via the command line.

A: I think this is not possible directly via some kind of mapping or refactoring.
One way to do this is using sql and put this into another changeset which is run right after the one that changes the data type:
<changeSet id="3" author="me">
    <sql>
        update person set martial_status = 'single' where martial_status = 0;
        update person set martial_status = 'married' where martial_status = 1;
    </sql>
</changeSet>

I just wrote this down as an idea. It is untested.
You could add a precondition to execute this changeset only if changeset with id 2 ran successful.


text:
Q: Is there a way to change existing JavaScript using a Firefox extension? I'm writing a Firefox extension to make a dynamic web app more accessible (applying ARIA roles, alt text for images, etc.) and I was wondering: is it possible to change the contents of existing JavaScript from the extension?  I was previously using the GreaseMonkey add-on to do something like this:
SomeObjectTheyCreated.Method = function(text){
    // My code here.
};

But the "GreaseMonkey compiler" is out of date and causes more trouble then it's worth, so I've got a ton of homework to do just learning to use this old-fashioned SDK (a command prompt, really? lol).  :)
All joking aside though, when I try to do something like the code above, the command prompt gives me the error "SomeObjectTheyCreated is undefined".  This makes sense, of course, because I didn't define it in the extension.  So what I'm wondering is, is there another way to sort of "re-define" scripts on the page?  Thanks. :)


text:
Q: Installing Arch Linux on Thinkpad W530 I am installing Arch Linux on a Thinkpad W530, using the LiveCD.
When I boot from the LiveCD, at the Syslinux bootloader screen, my hardware buttons (volume/mute) and Fn-keys work. I am able to control the brightness.
But once I boot into the Arch live medium, they stop working. I checked lsmod and have thinkpad_acpi running.
Is this just a problem because I am running LiveCD and haven't installed Arch yet?
Is there another module that I have to run? Do I need to install Xorg first?
I have installed Debian and Ubuntu, and almost everything works out of the box. Including when running their LiveCD. What allows Ubuntu to recognize the Fn-keys?

A: I believe the Fn keys are mapped to X86... named keys. Therefore, I'm assuming you have to install the x-server first.  As for the brightness issue, ArchWiki has some relevant information, among which is the possible systemd-backlight problem/workaround:

Inverted Brightness (Intel i915 only)
Symptoms:
after installing xf86-video-intel systemd-backlight.service turns off the backlight during boot
possible solution: mask systemd-backlight.service
switching from X to another VT turns the backlight off
the brightness keys are inverted (i.e. turning up the brightness makes the screen darker)
This problem may be solved by adding i915.invert_brightness=1 to the
list of kernel parameters.


text:
Q: What will a HRegionServer do if the zookeeper node that connected to the HRegionServer goes down? In HBase, when a HRegionServer starts up, it will create an ephemeral znode in the ZooKeeper cluster. When the HRegionServer crashes, the ephemeral znode will be deleted, and the HMaster can be notified about the crash of the HRegionServer.
As I known, ZooKeeper will clean up ephemeral znodes for the closed sessions. For example, a client C connects with a ZooKeeper node ZK1 and creates an ephmeral znode "/eph". When client C crashes or ZK1 crashes, the ephmeral znode "/eph" will be deleted after a while.
So, I'm curious about what will a HRegionServer do if the zookeeper node that connected to the HRegionServer goes down. Will the HRegionServer recreate the ephemeral znode? Will the HMaster be notified about the deletion of the HRegionServer's ephemeral znode? Will the HMaster start the server shutdown handling process?


text:
Q: Apply states on minions after they come online Imagine you want to apply some states on a group of minions, such as all ubuntu clients. It's possible by the time we apply that states some of the minions are offline.
How long do states remain in the message bus to be pushed on minions? What strategies do you suggest to tackle this problem and change minions states when they come back online? Is there a better way to make minion pull states than running salt-call state.highstate?

A: Salt comes with the so called reactor system, which should fit your needs.
The following is untested and taken from the linked docs.
/etc/salt/master.d/reactor.conf:
reactor:
    - 'salt/minion/*/start':          # Match the start event
        - /srv/reactor/start.sls      # Things to do when a minion starts

/srv/reactor/start.sls:
highstate_run:
    local.state.apply:
        - tgt: {{ data['id'] }}  # data included event data, id is the minion id.

This should ensure that each minion applies state.highstate after it has opened a connection to the salt master.


text:
Q: Intersection of free submodules over Noetherian ring In general, it is not true that intersections of free submodules of a free module are free, see here. What if our ring is particularly nice?
Over $k[x_1, x_2]$, the intersection of free submodules $F_1, F_2 \subseteq F$ of a free module can be written as the pull-back $F_1 \times_F F_2$, which is free by the syzygy theorem.
What about more general polynomial rings? Are intersections of free submodules of a free modules free for $k[x_1,\dotsc,x_n]$-modules, or other Noetherian rings?

A: The answer is no. Here is an example.
Let the ring be $k[x,y,z]$. Let $F$ be the free module of rank $4$ on $e_1,e_2,e_3,e_4$. Let $F_1$ be the free submodule generated by $e_1,e_2,e_3$ and $F_2$ be the free submodule generated by $e_1+xe_4,e_2+ye_4,e_3+ze_4$. I will let you check that $F_1\cap F_2$ is not free.


text:
Q: Vertically center menu within variable height header I have a header that may or may not contain an image/logo and whose size is variable.
I'd like to vertically align my navigation menu within the header regardless of the size of the logo.
I've tried the ghost element trick to vertically center the nav but can't get it to work. I think this is perhaps due to the logo being floated.
Markup:

Link

Link

Link

Link

CSS:
header {
    background-color: #f0f0f0;
    padding: 1em;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
}

.brand {
    float: right;
}

ul {
    list-style-type: none;
    padding: 0;
    margin: 0;
}

li {
    display: inline-block;
    margin-right: 0.25em;
}

http://jsfiddle.net/benfosterdev/R247T/

A: Set the nav to position:relative, set the ul to position:absolute and give it a top of 50%, and a margin-top of half of it's height. This will work as long as your menu has a fixed height. If you need a floating sub menu you will still be good as you can set the menu ul to have overflow:visible, but it MUST have a fixed height. If you can do that, you are golden.
nav {
    position:relative;
}

ul {
    list-style-type: none;
    padding: 0;
    margin: 0;
    position:absolute;
    left:10px;
    top:50%;
    height:26px;
    margin-top:-13px;
}

http://jsfiddle.net/R247T/2/
Note, this should work on older browsers as well.

A: You didn't mention browser support, but using transform may work, if I understand correctly:
nav {
    position: absolute;
    top: 50%;
   -webkit-transform: translateY(-50%);
   -o-transform: translateY(-50%);
   -moz-transform: translateY(-50%);
   -ms-transform: translateY(-50%);
    transform: translateY(-50%);
}

Updated fiddle

A: Just thought I'd throw this alternate solution into the mix.  You can also vertically align (and horizontally for that matter), by absolute positioning the element and using margin: auto.
The only caveat for this approach is that you will need to specify a height and width for the links nav.
nav {
    margin: auto 0;
    position: absolute;
    top: 0;
    bottom: 0;
    width: 100px;
    height: 40px;
}

Fiddle


text:
Q: library management using C++ I am working on a Library Management system using C++, but while trying to search a book by its title, the output prints 'No records found' even when the book was entered.
How should i resolve this issue?
#include <iostream>
#include <stdlib.h>
#include <conio.h>
#include <string.h>

using namespace std;

struct library
{
char title[30];
char author[30];
int price;
int numberofcopies;
};

int b;
library librarybooks[50];

int main()
{
  int choice;
  while(true)
  {
     cout<<"\n***********LIBRARY MANAGEMENT SYSTEM***********\n\n";
     cout<<"1- Enter the book details\n";
     cout<<"2- Display the book list\n";
     cout<<"3- Search a book by it's name\n";
     cout<<"4- Search a book by author\n";
     cout<<"5- Sort the books\n";
     cout<<"6- Exit\n";
     cout<<"\nPlease enter your choice: ";
     cin>>choice;

Search function:
case 3:
        char bookname[30];
        int i;
        cout<<"Enter the book title: ";
        cin>>bookname;
        for(int i=0;i<b;i++)
        {
            if(strcmp(bookname,librarybooks[i].title)==0)
            {
                cout<<"\nBook Name: \n"<<librarybooks[i].title;
                cout<<"\nCopies Available: \n"<<librarybooks[i].numberofcopies;
            }
            else
            {
                cout<<"No records found";
            }

        }break;


text:
Q: minimal surface between two long distance aligned circles Here is my problem:
If I take two circles , let's say (cos(t), sin(t),0) and (cos(t), sin(t),x) (t between 0 and 2pi), when x is small the minimale surface between them looks like a slightly incurved cylinder. Here I call "minimale surface" a smooth (non necessarily connected) surface S of minimale area such that the boundary of S is exactly the two circles.
My question is about what happens when x goes to infinity: Is there a point where "the" minimal surface becomes the union of two disks, or does it always stay diffeomorphic to a cylinder ?
Thanks!

A: Actually, the maximum plane separation is about $2/3$ of the diameter when the two circles have the same diameter. The exact figure near $2/3$ is the reciprocal of the slope of the tangent line to the standard catenoid that passes through the origin. From my calculator, the slope is $s \approx 1.508879561,$ so the reciprocal is $\frac{1}{s} \approx 0.6627434$

There is another way to discuss this, published by Nitsche, but there is a quick proof. It is not possible to have the planes separated so far apart (say, more than that diameter) that two copies of the surface, one rotated  $90^\circ,$ can be separated laterally and then brought into tangential contact in an interior point. This is prohibited by the maximum principle
There is a surprising part: if we misalign the circles a little bit, there will still be a sort of tube minimal surface joining them, it will just be a bit slanted rather than being a surface of revolution anymore. The surprise, due to Riemann, is that the intesection of this tube with any parallel plane is also a circle. There is no single agreed upon name for the resulting surface, i like to call it the Riemann Staircase, because the phrase Riemann Surface already has too many important associations.


text:
Q: chrome console how to avoid stop which error happend position If there are some errors which includes some error , then chrome debugger auto stop before error happend and wait for user's input to check the statement. But I want to make this settings invalid.Do you know how to avoid this settings?
Thanks in advance.

A: JavaScript standard says that an application should stop executing once an unhandled exception has been reached. This means that you code raises an Error that is not caught in a try(){...}catch(){} block. Wrap your code in a try-catch block to get it to work
E.G:
function raiseError(){
  //...Error-raising code here
  throw new Error("Test Exception");
};

try{
  raiseError();
}
catch(e){
  console.log("Error caught", e);
}


text:
Q: Convert post title to CamelCase I'm trying to convert a post title to CamelCase to create a twitter hashtag, I'm using strip but its returning a object instead I dont know if this is the right way?
# views.py
def post_create(request):
    if not request.user.is_authenticated():
        raise Http404

    form_class = PostCreateForm
    if request.method == 'POST':

        form = form_class(request.POST, request.FILES)
        if form.is_valid():

            instance = form.save(commit=False)
            instance.creator = request.user
            instance.slug = slugify(instance.title)
            instance.hashtag = instance.title.strip()
            instance.save()

            slug = slugify(instance.title)
            return redirect(instance.get_absolute_url())

    else:
        form = form_class()

    context = {
        'form': form,
    }

    return render(request, "posts/post_create.html", context)

Which returns <built-in method strip of unicode object at 0x031ECB48> in the template var, the result I'm looking for is like this MyPostTitle into the template
    # Template view
    <h3>#{{instance.hashtag|title}}</h3>

models.py
class Post(models.Model):
    creator = models.ForeignKey(ProfileUser)
    title = models.CharField(max_length=80)
    hashtag = models.CharField(max_length=80)
    slug = models.SlugField(unique=True)

    def __unicode__(self):
        return self.title

    def get_absolute_url(self):
        return reverse("posts:detail", kwargs={"slug": self.slug})

A: strip only removes the whitespace from the beginning or end of the string (https://docs.python.org/2/library/string.html#string.strip). You might use
instance.hashtag = instance.title.replace(' ', '')

As a side note, it might be cleaner to add this functionality as a method to your model class:
class Post(models.Model):
    ...
    def hashtag(self):
        if self.title is not None:
            return self.title.replace(' ', '')

A: >>> a = "foo baz bar"
>>> "".join([s.capitalize() for s in a.rsplit()])
>>> FooBazBar

To save:
import re
r = re.compile("[/!/?,:.;-]")

t = r.sub(" ",instance.title) # clear punctuation
instance.hashtag = "".join([s.capitalize() for s in t.rsplit()])

A: Python's unicode class also has a title() method, meaning you may do:
$ python3
>>> 'foo bar baz'.title()
'Foo Bar Baz'
>>> 'foo bar baz'.title().replace(' ', '')
'FooBarBaz'

Note that the order of .title().replace() is important!


text:
Q: Webfont as Fallback for local font I've a question about webfonts and how they get loaded.
The thing is, I have to use the Calibri font. It's a regular windows font.
So the font stack could be something like:
font-family: Calibri, Candara, Arial, sans-serif;

However there is a webfont of Calibri but it's pretty pricey. So my idea was to build the font stack like this:
font-family: Calibri, 'Calibri', Candara, Segoe, "Segoe UI", Optima, Arial, sans-serif;

So the first font should be the local one and the second the webfont. So if the local one is not found, it loads the webfont.
The font is priced for xxx views. The question is, would this work and if so would this save me some font loads?

A: Unfortunately this isn't how CSS works. In order to implement the webfont you'd first need to include it in your website (via HTML <link>, CSS @import or through JavaScript).
This means that prior to your font-family declaration, the font will have already been loaded (and presumably counted as a view by the company who hosts the font).
One solution could be to detect whether the browser is able to load the Calibri font by default (using JavaScript), and if not then download the webfont and use that instead, but in doing this you'd create a strage user experience whereby the page would default to using a font that could be loaded and then after a short while change to the webfont (after JavaScript has loaded it and your CSS has kicked in).
If you are willing to go down that path, there are several topics about how to detect which font has been loaded through JavaScript, such as Detecting which font was used in a web page

A: The way to use a web-font as a fallback for a local font is to make an alias using your @font-face rule:
@font-face {
  font-family: Calibri;
  src: local(Calibri),
       url(Calibri.woff) format("woff");
}

font-family: Calibri, Candara, Arial, sans-serif;

This method is preferable to giving the web-font a different name and including both in your font stack, which can sometimes result in the web-font being downloaded when it's not needed. By moving both to the @font-face rule, the web-font will not be downloaded if a local installation of Calibri is found on the user's system.
(I know your original question entailed other complications, with the web-font being hosted at a different domain and charged per view. I figure these are secondary though to the title and fundamental question of using a 'Webfont as Fallback for local font'.)

A: For saving font loading, you can also use a service worker to cache fonts or return the specified font file. It can intercept the loading of fonts and return a customized response. You can use the workbox to make it easier to cache font files.
The following is an example of caching Google fonts
  import {ExpirationPlugin} from 'workbox-expiration';
  import {registerRoute} from 'workbox-routing';
  import {StaleWhileRevalidate} from 'workbox-strategies';

  // Cache Google Fonts with a stale-while-revalidate strategy, with
  // a maximum number of entries.
  registerRoute(
    ({url}) => url.origin === 'https://fonts.googleapis.com' ||
               url.origin === 'https://fonts.gstatic.com',
    new StaleWhileRevalidate({
      cacheName: 'google-fonts',
      plugins: [
        new ExpirationPlugin({maxEntries: 20}),
      ],
    }),
  );


text:
Q: Jboss GC settings We are using jboss EAP-6.4.0/jboss
i am trying to enforce GC every 30 mins. the start up file is as below
 NO_GC_LOG_ROTATE=`echo $JAVA_OPTS | $GREP "\-verbose:gc"`
if [ "x$NO_GC_LOG_ROTATE" = "x" ]; then
    # backup prior gc logs
    mv "$JBOSS_LOG_DIR/gc.log.0" "$JBOSS_LOG_DIR/backupgc.log.0" >/dev/null 2>&1
    mv "$JBOSS_LOG_DIR/gc.log.1" "$JBOSS_LOG_DIR/backupgc.log.1" >/dev/null 2>&1
    mv "$JBOSS_LOG_DIR/gc.log.2" "$JBOSS_LOG_DIR/backupgc.log.2" >/dev/null 2>&1
    mv "$JBOSS_LOG_DIR/gc.log.3" "$JBOSS_LOG_DIR/backupgc.log.3" >/dev/null 2>&1
    mv "$JBOSS_LOG_DIR/gc.log.4" "$JBOSS_LOG_DIR/backupgc.log.4" >/dev/null 2>&1
    mv "$JBOSS_LOG_DIR"/gc.log.*.current "$JBOSS_LOG_DIR/backupgc.log.current" >/dev/null 2>&1
    "$JAVA" $JVM_OPTVERSION -verbose:gc -Xloggc:"$JBOSS_LOG_DIR/gc.log" -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=5 -XX:+UseParallelOldGC **-Dsun.rmi.dgc.client.gcInterval=1800000 -Dsun.rmi.dgc.server.gcInterval=1800000** -XX:GCLogFileSize=3M -XX:-TraceClassUnloading -version >/dev/null 2>&1 && mkdir -p $JBOSS_LOG_DIR && PREPEND_JAVA_OPTS="$PREPEND_JAVA_OPTS -verbose:gc -Xloggc:\"$JBOSS_LOG_DIR/gc.log\" -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=5 -XX:GCLogFileSize=3M -XX:-TraceClassUnloading"
fi

Not sure why this isn't working???

A: GC logs in EAP cannot rotate on a time based rotation. Rather, they can rotate on a size based rotation.
The gc.log can be rolled through JVM settings UseGCLogFileRotation / NumberOfGCLogFiles / GCLogFileSize on the OpenJDK  Oracle JDK. For example:
-verbose:gc -Xloggc:gc.log -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=5 -XX:GCLogFileSize=1048576


text:
Q: Need to migrate a CakePhp application from php 5 to 7 in AWS Centos I need to move a cakePhp Application from php 5 to 7 in a AWS instance.
I have created a new AWS Centos instance and installed php 7 on it. Then I moved all the files from original server to the new server.
I have tried to upgrade CakePhp to latest version. (Through shell, from the logs Everything was updated successfully except Version.txt file and licensce.txt File.
I am not able to access my application through New change.
Error while accessing the application: http://34.210.73.74/util/index.php
Host Not Found
DNS error (the host name of the page you are looking for does not exist) or Server did not accept the connection.