text:
Q: Issue controlling Enter Key behavior in a TabPanel I have a web application using Tabcontainer controls.
I have defined a HeaderTemplate in a TabPanel and dropped an ImageButton control on it so that I can have a "close panel" X image on the tab.
I am manually controlling the tab visibility from code.
From this image OnClick event - I execute code that does some clean up and manually closes the tab.
Here is the display code:
<asp:TabPanel ID="TabREVRES" runat="server" HeaderText="" Visible="false" DefaultButton="T2ResSearch">
<HeaderTemplate>
<asp:Label ID="ResHdrLbl1" runat="server" Text="Open Resource Review" Font-Size="Smaller"></asp:Label>
            <asp:ImageButton runat="server" ID="ResHdrClose" ImageUrl="../Images/XinBox.jpg" ToolTip="Close Review Tab" OnClick="ResTabClose_Click"
                Height="15" ImageAlign="TextTop" Width="15" />
</HeaderTemplate>

I have a Textbox and Search button on the page within this TabPanel.  I want the Enter key to default to the Search button.  However the Enter key is defaulting  to the TabPanel ImageButton control Onclick event - thereby executing the codebehind logic to close the tab.
As you can see from the code sample - I tried adding a DefaultButton= to the TabPanel but that is not working.  Any help on this would be appreciated.

A: Not sure it's the cleanest approach - but I solved this with the following code in case it helps anyone:
In tabs where I have no button controls - I am stopping the Enter key from closing the tab with this javascript:
function stopRKey(evt) {
        var evt = (evt) ? evt : ((event) ? event : null);
        var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
        if ((evt.keyCode == 13) && (node.type == "text")) { return false; }
    }
    document.onkeypress = stopRKey;

For Tabs with button controls - I make one of them the default as follows:
this.Form.DefaultButton = this.mydefaultbuttonID.UniqueID;


text: Q: How to preserve imported CA certificates through Java updates on windows? I've a windows server. I'm running my application using Tomcat 8 and I've installed COMODO SSL on using java keytool. Everytime I update Java, certificates and cacerts get deleted from jre\bin path. Is there a way to preserve these files even after Java update?

redpajama_set_name: RedPajamaStackExchange


text:
Q: free() function only frees the first element of a struct? I'm working with two structs:
typedef struct ListNode{
    void* value;
    struct ListNode *next;
    struct ListNode *prev;
} Node;

typedef struct List{
    Node *first;
    Node *last;
    int count;
} List;

Then i declare these variable and allocate memory
List *x = calloc(1,sizeof(List));
Node *x1 = malloc(sizeof(Node));
Node *x2 = malloc(sizeof(Node));
x->first = x1;
x->last =x2;
x->count = 2;
free(x);

So i'm pretty sure that if i free x, the x->count, x->first, x->last will also disappear as well. However, in this case ,i use gdb to check, and surprisingly only the first element of x is removed (e.g: if in the struct List i put count on the top, then it will remove only count and leave the rest intact). Why is this happening, and how do i free() the whole struct?

A: Your assumption is wrong. If you do free(x) you're only freeing the block of memory holding the contents of x, but since this block contains some pointers to other blocks, you will need to free() those first. This is because free() does not care about the content of the memory you're freeing, it doesn't do anything fancy. If you see some value modified after using free(), it's just because free() uses that memory to store some useful internal values to keep track of memory usage, and it's only a coincidence if that happens to "clear" a pointer in your struct.
The correct way to free() your struct is the following:
free(x->first);
free(x->last);
// DO NOT free(x->count), it's an integer, not a previously allocated pointer!
free(x);

Here's a visual representation (pardon my awful handwriting):

A: It's important to understand the memory layout of the struct... i'm no expert so this will be really really simplified:
List x = [pointer-to-x1][pointer-to-x2][int] (plus padding)
So when you run calloc(1, sizeof(List)), you aren't creating the x1 and x2 structs in the same region of memory as the List, because they are just pointers to some other place in memory. you are just creating small reference to them which hasn't even been setup yet. That's why you have to malloc x1 and x2 separately.
so when you free(x), you also aren't freeing x1 or x2 either. free doesn't know how and doesn't know that you ran malloc for x1 and x2. if it tried to free it, it could end up freeing memory too early or freeing memory on the stack. it's only going to look at the region of memory i mapped out above.
Was writing this and saw another answer just come in. Marco has a good answer!

A: You seem to have invalid expectation what happens when you call free.
You cannot verify the result of free in GDB.
Freeing a memory location does not mean that the memory in that place is modified in any way. It may still look the same as before. The OS or C runtime library may set it to all zero, but that's not mandatory. Also the pointer x will not change.
Freeing an address only means that you tell the OS it can take it back and give it to someone else.
After calling free you are no longer allowed to access the memory.
That's all what happens after free.
Therefore last and count will not "disappear".
That said, you also have a memory leak as others have already pointed. Freeing x does not free any other memory accessible via x->first or x->last.


text:
Q: Why does ExecuteURL strip the existing headers where File doesn't? It seems to be generally known that serving custom error pages with a responseMode of ExecuteURL rather than File results in the HTTP status code not being maintained.
The remaining headers are also lost during the process resulting in no cache-control header being preserved and more.
What's really happening under the hood? Why are the headers not maintained?
I can find quite a lot of resources explaining the solution but nothing expanding on the reasoning for the problem in the first place.


text:
Q: Dirac equation plane wave solutions for antiparticles (Peskin QFT book overlooked?) I am puzzled by the derivation given here about the Dirac equation plane wave solutions of Peskin QFT book (shown in (3.59) and (3.62) on the scanned image below):
$$
(i \gamma^\mu \partial_\mu -m) \psi=0 \tag{eq.0}
$$

*

*For $\psi(x) =u(p) e^{-i p\cdot x}$, we get the equation of motion (eq.0) becomes
$$
(\gamma^0 E -\gamma^j p^j -m) u(p)  =0 \tag{eq.1}
$$
with $j=1,2,3.$ Here we  choose $p^0=E>0$.

Say I agree with the solution
$$
u(p)=\begin{pmatrix} \sqrt{ p \cdot \sigma} \zeta^s \\ \sqrt{ p \cdot \bar\sigma} \zeta^s \end{pmatrix} \tag{eq.1-sol}
$$
2. For $\psi(x) =v(p) e^{+i p\cdot x}$, we get the equation of motion (eq.0) becomes
$$
(-\gamma^0 E +\gamma^j p^j -m) v(p)  =0 \tag{eq.2}
$$
with $j=1,2,3$, here we still choose $p^0=E>0$
Naively, I can derive $v(p)$ by a mapping from the known solutions (eq.1-sol)? Naively, I thought that we just either map
$$
(E,p^j) \mapsto (-E,-p^j)
$$
then we plug in (eq.1-sol) to get a rewriting of eq.2
to
$
(+\gamma^0 E -\gamma^j p^j -m) v(-p)  =0 \tag{eq.2}
$
so we have also a change of $\zeta$ to $\eta$
$$
v(-p)=\begin{pmatrix} \sqrt{ p \cdot \sigma} \eta^s \\ \sqrt{ p \cdot \bar\sigma} \eta^s \end{pmatrix} \tag{eq.2-sol-a}
$$
or
$$
v( p)=\begin{pmatrix} \sqrt{ -p \cdot \sigma} \eta^s \\ \sqrt{ -p \cdot \bar\sigma} \eta^s \end{pmatrix} \tag{eq.2-sol-b}
$$
But these are all different from Peskin's
$$
v( p)=\begin{pmatrix} \sqrt{  p \cdot \sigma} \eta^s \\ -\sqrt{  p \cdot \bar\sigma} \eta^s \end{pmatrix} \tag{eq.2-sol}
$$

Why do I get (eq.2-sol-a) or (eq.2-sol-b) instead of (eq.2-sol)? Can you correct my mistakes?

A: The way that Peskin and Schroeder (P&S) solves the Dirac equation is by going to the rest frame first. The first solution is then given by
$$ u(p_0)=\sqrt{m}\left(\begin{array}{c} \xi \\ \xi \end{array} \right) , $$
as given in (3.47) in P&S. The full solution then comes from a Lorentz boost of this solution.
When you do the same for the antiparticle solution, you'll get
$$ v(p_0)=\sqrt{m}\left(\begin{array}{c} \xi \\ -\xi \end{array} \right) . $$
So the minus sign in the lower entry does not have anything to do with the momentum vector or its direction. Note that these are positive energy solutions, so $E>0$ for both the particle and the antiparticle.


text:
Q: How to wait for a panicking goroutine? A common way to wait for a goroutine is to use a *sync.WaitGroup:
func main() {
    wg := &sync.WaitGroup{}
    wg.Add(1)
    go func() {
        defer wg.Done()
        // Long running task
    }()
    wg.Wait()
}

No problems here. However, what about this:
func main() {
    wg := &sync.WaitGroup{}
    wg.Add(1)
    go func() {
        defer wg.Done()
        // Long running task
        panic("Something unexpected happened.")
    }()
    wg.Wait()
}

In this case, when wg.Done() is called, I believe main() could exit without details of panic() ever being written to stdout/stderr. Is this true and if yes, how might I prevent it from happening?

A: The panic will kill the process regardless, because no one is recovering from it. If you want to recover from panics in a goroutine, you must have recover wrapping the call stack in the same goroutine.
wg.Done will be called in this case, by the defer statement. But the process may die before the main goroutine finishes the wg.Wait anyway.

A: @Eli Bendersky was right.
Reference src/builtin/builtin.go

The panic built-in function stops normal execution of the current
  goroutine. When a function F calls panic, normal execution of F stops
  immediately. Any functions whose execution was deferred by F are run in
  the usual way, and then F returns to its caller. To the caller G, the
  invocation of F then behaves like a call to panic, terminating G's
  execution and running any deferred functions. This continues until all
  functions in the executing goroutine have stopped, in reverse order. At
  that point, the program is terminated and the error condition is reported,
  including the value of the argument to panic. This termination sequence
  is called panicking and can be controlled by the built-in function
  recover.

after panic, defer func will be called.
Check this in playground: https://play.golang.org/p/yrXkEbE1Af7
package main

import (
    "sync"
    "fmt"
)

func main() {
    wg := &sync.WaitGroup{}
    wg.Add(1)
    go func() {
        defer func(){
            fmt.Println("expected to be called after panic")
            wg.Done()
        }()
        // Long running task
        panic("Something unexpected happened.")
    }()
    wg.Wait()
}

Output
expected to be called after panic
panic: Something unexpected happened.

goroutine 5 [running]:
main.main.func1(0x416020, 0x0)
    /tmp/sandbox946785562/main.go:17 +0x60
created by main.main
    /tmp/sandbox946785562/main.go:11 +0x80

Then your second question, "how to prevent that?"
As metioned before, you can recover after panic
Playground: https://play.golang.org/p/76pPrCVYN8u
package main

import (
    "sync"
    "fmt"
)

func main() {
    wg := &sync.WaitGroup{}
    wg.Add(1)
    go func() {
        defer func(){
            if x:=recover();x!=nil{
                fmt.Printf("%+v\n",x)
            }
            wg.Done()
        }()
        // Long running task
        panic("Something unexpected happened.")
    }()
    wg.Wait()
    for i:=0;i<10;i++{
        fmt.Println(i)
    }
}

Output
Something unexpected happened.
0
1
2
3
4
5
6
7
8
9

A: It's possible to provoke the unwanted behavior by adding defer time.Sleep(time.Second):
func main() {
    wg := &sync.WaitGroup{}
    wg.Add(1)
    go func() {
        defer time.Sleep(time.Second)
        defer wg.Done()
        // Long running task
        panic("Something unexpected happened.")
    }()
    wg.Wait()
}

D:\Projects\Code\Go\src\zyl\testexit>go build .
D:\Projects\Code\Go\src\zyl\testexit>.\testexit.exe
D:\Projects\Code\Go\src\zyl\testexit>echo %errorlevel%
0

The solution to the problem is to not defer the call to Done() and just place it at the end:
func main() {
    wg := &sync.WaitGroup{}
    wg.Add(1)
    go func() {
        // Long running task which might panic
        wg.Done()
    }()
    wg.Wait()
}

In the above code, no dependency on implementation details of go routine behavior exists and will always fail when a panic occurs. After realizing this, I noticed the problem exists in about every tutorial on the subject ever written, meaning we are looking at a wide-spread manifestation of cargo cult programming.


text:
Q: Code for linux date YYY-M-D In the linux date command, I use this code:
TODAY=$(date +"%Y-%m-%d")

sample output YYYY-MM-DD, such as 2016-09-05.
If I want output date YYYY-M-D, such as 2016-9-5, what should I do with this code?

A: Do it:
TODAY=$(date +"%Y-%-m-%-d")

Explaining, the - will remove the leading zeros...
Example:
September month...

%m returns 09
%-m returns 9

A: I am not user you can do that date, but you fix it afterwards:
TODAY=$(date +"%Y-%m-%d")
TODAY="${TODAY//-0/-}"


text:
Q: What is content.php file that is needed for Jetpack infinite scroll plugin? I'm currently learning how to use Jetpack infinite scroll plugin, while going through the documentation I came across 'render' section:
http://jetpack.me/support/infinite-scroll/
It uses default loop, which I actually need to customise, it also says that if I have content.php file in my template than I'm good to go and can omit render argument. However I don't know what content.php file is for. As for the loop and the markup of each post, those are defined in my index.php, single.php and page.php files. Could you please explain and give example of what content.php page is, where it should be located and how can it be used.
I'm speculating that its a file where I can paste just my loop and post markup bit, so perhaps I can than somehow include content.php file in my index.php, single.php and page.php files maybe? Not sure.
I did look for this in the codex, but surprisingly couldn't find explanation of content.php file.

A: There is no standard for a content.php in WordPress, that's why you cannot find in the Codex. Some themes use it to render the post content.
So instead of …
while ( have_posts() )
{
    the_post();
    ?><li <?php post_class(); ?>>
    <?php
        the_title( '
', '
' );
        the_excerpt();
        wp_link_pages();
    ?>

    <?php
}

… they use …
while ( have_posts() )
{
    the_post();
    get_template_part( 'content', get_post_format() );
    ?>

    <?php
}

But you could use any name and it would still work. Jetpack follows a convention from WordPress' last default themes here; these are using a content.php.


text:
Q: How to change the order of posts by number of views not by date in wordpress I'm making a drawing website using WordPress and allowing my users to draw and post their drawings as pinned posts

Now I want to make the theme I'm using  to change the order of the displayed posts to be displayed by number of views or comments not by the date order
Where can I find the code responsible for the posts displaying order in the theme of WordPress.

A:
If you want to changer the display order then you can use
  pre_get_posts action.

To order post by comment count
function wh_post_display_order_comment($query) {
    if ($query->is_home() && $query->is_main_query()) {
        $query->set('orderby', 'comment_count');
        $query->set('order', 'DESC');
    }
}

add_action('pre_get_posts', 'wh_post_display_order_comment');

To order post by view
By default WordPress does not have any option to short post by view so you have to use a little trick
function whpp_track_post_views($post_id) {
    if (!is_single())
        return;
    if (empty($post_id)) {
        global $post;
        $post_id = $post->ID;
    }
    whpp_set_post_views($post_id);
}

add_action('wp_head', 'whpp_track_post_views');

function whpp_set_post_views($postID) {
    $count_key = 'whpp_track_post_views';
    $count = get_post_meta($postID, $count_key, true);
    if ($count == '') {
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
    } else {
        $count++;
        update_post_meta($postID, $count_key, $count);
    }
}

//To keep the count accurate, lets get rid of prefetching
remove_action('wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);

Now that we have set our logic for view so we 'll be shorting it
function wh_post_display_order_view($query) {
    if ($query->is_home() && $query->is_main_query()) {
        $query->set('meta_key', 'whpp_track_post_views');
        $query->set('orderby', 'meta_value_num');
        $query->set('order', 'DESC');
    }
}

add_action('pre_get_posts', 'wh_post_display_order_view');

To order post by both view and comment count
If you want to orderby both the score then again we have to apply a small trick, as there is no default option in WordPress. First we'll count the comment and we'll add a small weightage and add the total view count and keep it is a different meta field and then we'll sort the post on that key.
function whpp_track_post_views($post_id) {
    if (!is_single())
        return;
    if (empty($post_id)) {
        global $post;
        $post_id = $post->ID;
    }
    whpp_set_post_views($post_id);
}

add_action('wp_head', 'whpp_track_post_views');

function whpp_set_post_views($postID) {
    $count_key = 'whpp_track_post_views';
    $count = get_post_meta($postID, $count_key, true);
    //retriving total comments
    $comments_count = wp_count_comments($postID);
    $total_comment = $comments_count->total_comments;

    $comment_point = 2; //change the number with your desired weightage
    $comment_score = $total_comment * $comment_point;
    if ($count == '') {
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
    } else {
        $count++;
        update_post_meta($postID, $count_key, $count);
    }
    update_post_meta($postID, 'whpp_view_comment_score', ($count + $comment_score));
}

//To keep the count accurate, lets get rid of prefetching
remove_action('wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);

function wh_post_display_order_view($query) {
    if ($query->is_home() && $query->is_main_query()) {
        $query->set('meta_key', 'whpp_view_comment_score');
        $query->set('orderby', 'meta_value_num');
        $query->set('order', 'DESC');
    }
}

add_action('pre_get_posts', 'wh_post_display_order_view');

Please Note : Adding extra weight to comment is not mandatory, but if reader will realy like the post then only they 'll give the comment.
Code goes in function.php file of your active child theme (or theme). Or also in any plugin php files.
Code is tested and works.
Hope this helps!


text:
Q: How can I cache an html document in a users browser? I recently visited a website called neocities.org
I was surprised to see how extremely fast their pages loaded after a refresh because it's grabbing content from my browser cache..
exe. apple.neocities.com suyu.neocities.org
After some exploring I found that their site caches all content in the browser with a status 304. It also shows 'cache' on the html document line within the network tab on inspect element.
How can I accomplish this?
Do I need to have http/2 enabled to do this?
I have tried numerous things and nothing worked.
I did enable gzip though which was also enabled on these sites.
I put the code below in my .htaccess
## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType text/html "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 1 month"
</IfModule>
## EXPIRES CACHING ##

I would like to enable some sort of caching that caches every file on my website in a users browser with a status of 304 instead of grabbing the file from the server each time.


text:
Q: Forecasting by autoregressions of invertible linear transform of variables Suppose I have two variables and two alternative variables, where the latter are an invertible linear transform of the former. Suppose further, that I estimate both the new and the original variables as a pure autoregression on one or more lags (and a constant), the same number of lags for the original and the alternative variables.
If I do forecasts with both sets of variables, and then apply the inverse transform on the forecasts from the alternative variables, will they be necessarily the same, except for rounding error?
If not, is there anything I can derive a priori about the quality of the two forecasts from complete information about the original data and the transform? In other words, is it ever the case that I can improve the quality of my forecasts (by autoregression) by applying a linear transform?
This question is motivated by a data set that contains two similarly variable and similarly trended variables, and a linear combination that, rather surprisingly, puts virtually all of the trend in one variable and virtually all of the variability in the other.


text:
Q: Entering an input, clicking it and retrieving particular information with Selenium I'm new to web scraping with Python. My intent is to retrieve the verb for a word of interest. For e.g. dictionary.com has definitions for different parts of speech for word, I would like to enter a word of interest and then hit the search icon, in the resulting page I would like to extract the information under the header 'verb'.

A: To extract the information under verb header Induce WebDriverWait and presence_of_all_elements_located()
Here is the code.
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver=webdriver.Chrome()
driver.get("https://www.dictionary.com/")
WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.XPATH,"//button[contains(.,'Accept Cookies')]"))).click()
elementsearch=WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.CSS_SELECTOR,"input[title='Search']")))
elementsearch.send_keys("interest")
elementsearch.submit()
results=WebDriverWait(driver,20).until(EC.presence_of_all_elements_located((By.XPATH,"//span[@class='luna-pos'][contains(.,'verb')]/following::div[1]//div[@class='default-content']//div")))
for item in results:
    print(item.text)

results1=WebDriverWait(driver,20).until(EC.presence_of_all_elements_located((By.XPATH,"//span[@class='luna-pos'][contains(.,'verb')]/following::div[1]//div[@class='expandable-content']//div")))
for item in results1:
    print(item.get_attribute("textContent"))

Output on console:
to engage or excite the attention or curiosity of:
Mystery stories interested him greatly.
to concern (a person, nation, etc.) in something; involve:
The fight for peace interests all nations.
to cause to take a personal concern or share; induce to participate: to interest a person in an enterprise.
to cause to be concerned; affect.


text:
Q: why flask app run host not working in newer version? I am creating a rest api with flask restful using the below versions.
Werkzeug==2.0.1,
Flask-RESTful==0.3.9,
Flask==2.0.1

If I run my app with specifying host and port
app.run(host='0.0.0.0',port=5001,debug=True)

I am getting http://192.168.1.9:5001/ instead if http://0.0.0.0:5001.
The port is changing but not host.
I changed the versions to
Werkzeug==1.0.1,
Flask-RESTful==0.3.9,
Flask==1.0.1

then its working in older version.Does anyone know what is happening?

A: Its not a problem with flask or Werkzeug
I run the below command and now I can access remotely
sudo ufw allow 5001


text:
Q: Excel keeps changing data on a seperate worksheet form I am in the process of creating some forms that I use every day at work, in excel. On the first form I am doing a VBA lookup from an external database and depending on the selected item the user chooses from the drop down list, it populates the required information on the cell containing the VBA look up formula. This is all working great but one thing that we are required to do when ordering with the form is, we have to track those purchases on another form. I created the second form as well and it populates all the information from the order form to their corresponding cells on the tracking form. The issue I am having is when information is changed in the referenced cells of the order form the information is changed on the tracking form replacing the 1st orders information with the next orders information. What I have been researching (to no avail) is, how to keep the previous orders information on the tracking sheet even though the order form is cleared to imput another order. When imputting the second orders information instead of erasing the previous orders information on the tracking sheet I want the information being imputed on the order form for the second order to  start on the next available colum in their corresponding cell references.
That is one problem the other one is this. The order tracking forms have a set amount of columns of that information can be put in before it get to the bottom of the form. How do I get it to start another tracking form and continue tracking orders on its first available column and once again when getting to the bottom start another form?
I know this was a lot of information and I hope I explained it well enough for you to understand. I was recently brought around to the use of macros but I am still a NOOB when it comes to these. If using macros is the most effficient way to do what I need and have to use one or two or three to get this task met, can you please provide me with the coding for each needed? Thank you again ahead of time.
     V/R

Logistician and loving it

A: You need to make sure that you copy the value from the dynamic sheet to the tracking sheet. If you copy the formula, it will also be dynamic.
For example, let's say you have the following spreadsheet:
        A        B        C        D
    +--------+--------+--------+--------+
  1 |     42 |  =$a$1 |        |        |
    +--------+--------+--------+--------+

and the following code:
Sub Macro1()
    Range("a1").Value = 42                 ' ensure source data as expected'

    Range("c1").Value = Range("b1").Value  ' copy value '

    Range("b1").Copy                       ' copy formula '
    Range("d1").PasteSpecial

    Range("a1").Value = 0                  ' change source data '
End Sub

When you run that code, c1 get the current value of a1 which is 42.  However, d1 gets the current formula from b1 which is a non-relative reference to a1, so you end up with:
        A        B        C        D
    +--------+--------+--------+--------+
  1 |     0  |  =$a$1 |     42 |  =$a$1 |
    +--------+--------+--------+--------+

or c1 being the only cell holding the historical record (because both b1 and d1 are formulaic references, they will reflect changes made to the original data source).


text:
Q: Dfference Between Two running total query I have written two types of Running total with dates as below:-
30 days running Total Sales =
CALCULATE (
    [Total Sales],
    FILTER (
        ALL ( Dates ),
        Dates[Date] > MAX ( Dates[Date] ) - 30
            && Dates[Date] <= MAX ( Dates[Date] )
    )
)

and
Running Total =
CALCULATE (
    [Total Sales],
    DATESINPERIOD ( Dates[Date], LASTDATE ( Dates[Date] ), 30, DAY )
)

I am trying to Calculate 30days running total of Total sales. But both of the queries give the different result as Below.
Can anybody explain ......

A: The values MAX ( Dates[Date] ) and LASTDATE ( Dates[Date] ) should be the same here.
The difference is that your first measure is subtracting 30 days whereas the second is adding 30 days.
Try using -30 instead of 30 in the second one.


text:
Q: How to keep a user subscribed to every chat it is following
Thats the messenger's facebook UI
If you were implementing that with phoenix (elixir framework)
Would you create one phoenix-channel for one chat?
Which will implies that you client (mobile, web etc...) will have to open one channel for every chat it is suscribed at
Which will implies that if there is 2000 chats he is suscribed at, he will have to open 2000 channels (client load).
Would you create one phoenix-channel for one user?
Which will implies that your client (mobile, web etc...) will have to open just one channel and
Which will implies that for every incoming message you'll have to query for al the users in a room (server load).

A: In messaging apps, there are two primary concerns. Managing the list of resources (users, rooms, etc) that a user is subscribed too. This is typically displayed as a list in the client. So you need to render that list and update for thinks like presence, new message alerts, and perhaps showing if the use has an open chat window. The solution for this part is similar regardless if the users/rooms are point-to-point or multi-user (rooms).
The second concern is displaying messages in individual chat windows that are open/visible. The solution for this may vary depending on whether they are point-to-point or multi-user. However, Facebook does support multi-user chat, so I'll answer this based on my experience building a Slack clone in Phoenix.
I recommend two channels, one for users and one for the open chat windows, lets call it chat. Each user will have 1 instance of a user channel and an instance of the chat channel for each open chat window. The user_id can be used for the topic of the user channel like "user:" <> user.user_id. You will probably have a schema for each of the chat sessions (which uses are part of the chat session). So use that id for the chat channel topic like "chat:" <> chat.id.
You can then broadcast new incoming messages in the chat channel and they will go out to everyone in that chat session (people that have the chat window open). This will work for both point-to-point and multi-user windows.
The example you provided in the question shows two uses with different state (text color). One shows a missed call and the other I presume indicates an unread message. This type of state is typically specific to the user, so you would use the use channel put push this information.
To track indicators on the user list, you can subscribe to messages in the chat channel from the user channel. You will then receive info messages in the user channel and take appropriate actions if needed. If you subscribe to the chat join messages, you can build a list of these and store it in your socket.assigns struct. See Phoenix Channels - Multiple channels per socket for more details.
Another API that I use for messaging apps is the intercept api. This allows you define a handle_out function that gets called for specific broadcast events of a channel. It can be used to filter or manipulate outgoing messages broadcast on that channel


text:
Q: Flutter firebase_message plugin setup errors I wanted to try out cloud messaging in my Flutter application, but I always run into errors, and I have not found a solution yet. I followed the steps stated here: firebase_messaging
If I follow the steps except the optional part with creating an Application.java file for background messages, and I send a test message from Firebase to the launched application, I get this error:
java.lang.RuntimeException: Unable to create service io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService: java.lang.RuntimeException: PluginRegistrantCallback is not set.
   at android.app.ActivityThread.handleCreateService(ActivityThread.java:3577)
   at android.app.ActivityThread.access$1400(ActivityThread.java:200)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1689)
   at android.os.Handler.dispatchMessage(Handler.java:106)
   at android.os.Looper.loop(Looper.java:201)
   at android.app.ActivityThread.main(ActivityThread.java:6806)
   at java.lang.reflect.Method.invoke(Native Method)
   at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
E/AndroidRuntime(29468): Caused by: java.lang.RuntimeException: PluginRegistrantCallback is not set.
   at io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService.startBackgroundIsolate(FlutterFirebaseMessagingService.java:157)
   at io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService.onCreate(FlutterFirebaseMessagingService.java:77)
   at android.app.ActivityThread.handleCreateService(ActivityThread.java:3565)

For me it seems like that the optional part is needed too, but when I do that I get errors when the app opens. After the errors the app still runs, and if I send a test message from Firebase the app receives it succesfully. Later it doesn't even receives the message, but thows the same errors.
java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.Application android.app.Activity.getApplication()' on a null object reference
   at com.github.adee42.keyboardvisibility.KeyboardVisibilityPlugin.registerWith(KeyboardVisibilityPlugin.java:107)
   at io.flutter.plugins.GeneratedPluginRegistrant.registerWith(GeneratedPluginRegistrant.java:22)
   at io.flutter.plugins.Application.registerWith(Application.java:18)
   at io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService.startBackgroundIsolate(FlutterFirebaseMessagingService.java:164)
   at io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin.onMethodCall(FirebaseMessagingPlugin.java:133)
   at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:222)
   at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:96)
   at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:656)
   at android.os.MessageQueue.nativePollOnce(Native Method)
   at android.os.MessageQueue.next(MessageQueue.java:326)
   at android.os.Looper.loop(Looper.java:165)
   at android.app.ActivityThread.main(ActivityThread.java:6806)
   at java.lang.reflect.Method.invoke(Native Method)
   at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)

[ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: PlatformException(error, Attempt to invoke virtual method 'android.app.Application android.app.Activity.getApplication()' on a null object reference, null)
    StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:569:7)
    MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:316:33)
    <asynchronous suspension>
    FirebaseMessaging.configure (package:firebase_messaging/firebase_messaging.dart:118:16)
    main (package:vonatles/main.dart:18:22)
    _AsyncAwaitCompleter.start (dart:async-patch/async_patch.dart:43:6)
    main (package:vonatles/main.dart:12:10)
    _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:229:25)
    _rootRun (dart:async/zone.dart:1124:13)
    _CustomZone.run (dart:async/zone.dart:1021:19)
    _runZoned (dart:async/zone.dart:1516:10)
    runZoned (dart:async/zone.dart:1500:12)
    _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:221:5)
    _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:305:19)
    _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:172:12)

Versions:
firebase_core: ^0.4.0+1
firebase_database: 3.0.7
firebase_messaging: 5.1.5

classpath 'com.android.tools.build:gradle:3.3.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.0"
classpath 'com.google.gms:google-services:4.3.0'

In the Flutter main function I have this:
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();

_firebaseMessaging.configure(
  onMessage: (Map<String, dynamic> message) async {
    print("onMessage: $message");
  },
  onLaunch: (Map<String, dynamic> message) async {
    print("onLaunch: $message");
  },
  onResume: (Map<String, dynamic> message) async {
    print("onResume: $message");
  },
);

The Application.java code:
package io.flutter.plugins;

 import io.flutter.app.FlutterApplication;
 import io.flutter.plugin.common.PluginRegistry;
 import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback;
 import io.flutter.plugins.GeneratedPluginRegistrant;
 import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService;

 public class Application extends FlutterApplication implements PluginRegistrantCallback {
   @Override
   public void onCreate() {
     super.onCreate();
     FlutterFirebaseMessagingService.setPluginRegistrant(this);
   }

   @Override
   public void registerWith(PluginRegistry registry) {
     GeneratedPluginRegistrant.registerWith(registry);
   }
 }

My android main directory:
-main
  -java
    -io.flutter.plugins
      Apllication.java
      GeneratedPluginRegistrant.java
  -kotlin
    -my.package.name
      MainActivity.kt

AndroidManifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="my.package.name">
    <application
        android:name="io.flutter.plugins.Application"
        android:label="mylabel"
        android:icon="@mipmap/ic_launcher">
        <activity
            android:name=".MainActivity"
            ...
            <intent-filter>
                <action android:name="FLUTTER_NOTIFICATION_CLICK" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>
</manifest>

A: Since my MainActivity in android was a Kotlin class, I got the solution to this problem when I tried the Application class as a Kotlin class instead of trying it as a Java class.
I tried many solutions, still, I was not able to run the app.
Application.kt
package YOUR_PACKAGE_NAME

import io.flutter.app.FlutterApplication
import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService

public class Application: FlutterApplication(), PluginRegistrantCallback {
    override fun onCreate() {
        super.onCreate()
        FlutterFirebaseMessagingService.setPluginRegistrant(this)
    }

    override fun registerWith(registry: PluginRegistry) {
        FirebaseCloudMessagingPluginRegistrant.registerWith(registry)
    }
}

Also, FirebaseCloudMessagingPluginRegistrant.kt
package YOUR_PACKAGE_NAME

import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin

class FirebaseCloudMessagingPluginRegistrant {
    companion object {
        fun registerWith(registry: PluginRegistry) {
            if (alreadyRegisteredWith(registry)) {
                return;
            }
            FirebaseMessagingPlugin.registerWith(registry.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"))
        }

        fun alreadyRegisteredWith(registry: PluginRegistry): Boolean {
            val key = FirebaseCloudMessagingPluginRegistrant::class.java.name
            if (registry.hasPlugin(key)) {
                return true
            }
            registry.registrarFor(key)
            return false
        }
    }
}

This can be added in the sample directory where your MainActivity is.
Try this Along with the steps mentioned here: Firebase messaging

A: by the way you can create a notification_handler.dart  like this Unhandled Exception: NoSuchMethodError: The method 'toRawHandle' was called on null.
i have posted my notification_handler.dart their.
try to configure with that and just call is as below from your statefullWidget and the let me know.
   @override
    void initState() {
      super.initState();
      new NotificationHandler().initializeFcmNotification();
    }

A: Background notification setup is not optional anymore. Make sure to follow intructions properly. And i was confused in making change in AndroidManifest.xml, So i wanted to share clear instruction.
PluginRegistrantCallback is not set" means Application.java file is not called properly at AndroidManifest.xml. Make change as follows:
First it looks like this
Change it to yourpackagename.Application like this
If you get "Default activity not found" error, run "flutter clean" command in your project folder and run it again.

A: In your AndroidManifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="my.package.name">
<application
    android:name=".Application" //edit this line
    android:label="mylabel"
    android:icon="@mipmap/ic_launcher">
    <activity
        android:name=".MainActivity"
        ...
        <intent-filter>
            <action android:name="FLUTTER_NOTIFICATION_CLICK" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>
</application>


text:
Q: Does there exist a bounded function that preserves strict expectation inequalities? Suppose that $\{X_i: i \in I\}$ is a collection of random variables on the measurable space $(\Omega, \mathcal F)$ taking values in the extended reals $[-\infty, \infty]$.

Does there exist a measurable function $g: [-\infty, \infty] \to [a,b]$ into a bounded interval that preserves strict expectation inequalities for $\{X_i: i \in I\}$, in the sense that for all probability measures $P$ on $(\Omega, \mathcal F)$ and all $i,j \in I$,
$$\int X_i dP < \int X_j P \ \ \text{implies} \ \int g(X_i)dP < \int g(X_j)dP?\tag{1}$$

I know that there are homeomorphisms between $[-\infty, \infty]$ and bounded intervals $[a,b]$, so my thought was to try one of those that is also strictly increasing, like $g(x) = \arctan(x)$. But I've been unable to see that (1) holds. Note that strictly increasing is necessary: just consider $P$ as it ranges over point masses.

A: Assume you have a probability measure $P$ such that for every $i\in \mathbb{N}_{\geq 2}$ exists measurable sets $A_i$ such that $P(A_i)>0$ and $$\lim_{i\rightarrow \infty} P(A_i)=0.$$
Now define $X_i = \frac{2}{P(A_i)} 1_{A_i}$, $X_1=1$ and $X_0=0$. We have that $X_0$ has expectation $0$, $X_1$ has expectation $1$ and the rest has expectation $2$. So we would need
$$ g(1)=\int g(X_1) dP <\int g(X_i) dP = g(2/P(A_i)) P(A_i) + g(0) (1-P(A_i)).$$
Taking the limit $i\rightarrow \infty$ yields (as $g$ is bounded)
$$ g(1)=g(0).$$
However, we also have
$$ g(0)= \int g(X_0) dP < \int g(X_1) dP = g(1)$$
which gives a contradiction.
Of course we can do the exact same construction when we replace the word probability measure with finite measure.
For infinite measure we could require that those $A_i$ are contained in some $A$ with finite measure. Then we note that strict inequalities can only hold for $g(0)=0$ (otherwise most expectations will be $\pm\infty$) and everything reduces to the finite case.


text:
Q: pgfplots + animate + foreach: Starting with one plot I want to generate an animation where the number of lines increases one by one. It works very well but the start image always has two lines.
\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}

\usepackage{animate}

\begin{document}

\begin{animateinline}[controls]{10}
  \multiframe{5}{iIndex=0+1}{
    \begin{tikzpicture}
      \begin{axis}[
      ymin=0,
      ymax=100,
      xmin=0,
      xmax=10,
      ]
      \foreach \i in {0,1,...,\iIndex} {
        \addplot[
        mark=none,
        domain=0:10,
        ] {3*x+\i+5};
        }
      \end{axis}
    \end{tikzpicture}
  }
\end{animateinline}

\end{document}

I want that it starts with one line and not two as shown in the picture:

The animated PDF can be found here for a couple of days:
https://dl.dropboxusercontent.com/u/1833443/lala.pdf

A: Use \foreach \i in {0,...,\iIndex} instead. The 0+1 in the multiframe has set the increment to 1.

Code
\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}

\usepackage{animate}

\begin{document}

\begin{animateinline}[controls]{10}
  \multiframe{5}{iIndex=0+1}{
    \begin{tikzpicture}
      \begin{axis}[
      ymin=0,
      ymax=100,
      xmin=0,
      xmax=10,
      ]
      \foreach \i in {0,...,\iIndex} {
        \addplot[
        mark=none,
        domain=0:10,
        ] {3*x+\i+5};
        }
      \end{axis}
    \end{tikzpicture}
  }
\end{animateinline}

\end{document}


text:
Q: Why object is deallocated in a global map I am working on part of the program where I want to keep a map for a lifetime of the program that will hold an address to an object B.
I have a global map in a file
static std::map<A , B*> mapping_;

then I have a class and some initialization
bool NewItem::initialize() {
    Panel_ = 0;

    if (mapping_[let_] == 0){
      B* tabPanel = new B();
      mapping_[let_] = tabPanel;
    }

    Panel_ = mapping_[let_];

When I come second time in initialize() then it knows about this map so it will skip the if block but members of B object are all deallocated somehow (0xfeeefeee).
I don't think that I am deleting Panel_ anywhere so I don't know how it is possible it is deallocating.
Any ideas what could be happening, or what I am doing wrong, or how can I keep object B in cache until the program closes?
Note: This is just a really small part of the code.


text:
Q: C#. How do i turn a String into a Double array?
class Program {
 public static void Main (string[] args) {

 string S1 = Console.ReadLine();
 string S2 = Console.ReadLine();

 double [] D1 = Array.ConvertAll(S1.Split(' '), Double.Parse);
 double [] D2 = Array.ConvertAll(S2.Split(' '), Double.Parse);

The final part of it isn't working, for some reason. After i enter the imput, the console says

Unhandled exception. System.FormatException: Input string was not in a correct format.
at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type)
at System.Double.Parse(String s)
at System.Array.ConvertAll[TInput,TOutput](TInput[] array, Converter`2 converter)
at Program.Main(String[] args) in /home/runner/distancia-entre-dois-pontos/main.cs:line 9

Can anyone help?

A: Use some LINQ and Extension methods
static class Program
{
    static void Main(string[] args)
    {
        string text1 = "4376.0 4328.0 14.71 116.7 14.01 0.9912 46.74";
        double[] row1 = text1.ParseList();
        string text2 = "4376.0,4328.0,14.71,116.7,14.01,0.9912,46.74";
        double[] row2 = text2.ParseList(',');
    }
}

public static class Extensions
{
    public static double[] ParseList(this string text, char token = ' ')
    {
        return text.Split(token).Select((item) => ParseValue(item)).ToArray();
    }
    public static double ParseValue(this string text)
    {
        if (double.TryParse(text.Trim(), out double x))
        {
            return x;
        }
        return 0;
    }
}


text:
Q: What is the purpose of {" "} in react? I can't search on the web the purpose of {" "} in react? What does this do?

 Hello I a'm a {" "} programmer

A: It is useful if you want to insert variable's value
Example:
const name = "Messi"

Hello, my name is {name}

In your case, a whitespace will be inserted

A: Curly braces { } are special syntax in JSX. It is used to evaluate a JavaScript expression during compilation. A JavaScript expression can be a variable, function, an object, or any code that resolves into a value.
const isProgrammer  = true;

 Hello I am a {isProgrammer ? "programmer" : "non-propgrammer"}

In you case, it will executed and return a white space. There are have 3 white space but it will only show 1 because spaces are compacted in HTML.

 Hello I am a {" "} programmer
 the same with
 Hello I am a{" "}programmer


text:
Q: "CompileXaml" task failed unexpectedly in Visual Studio while develop Xamarin project I opened a Xamarin cross platform sample Project in Visual studio 2013 and When I build, it gives this error:-
This question is also same but no one reply any answer.
Error   2   The "CompileXaml" task failed unexpectedly.
System.IO.FileNotFoundException: Could not load file or assembly 'XamlServicesWP, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
File name: 'XamlServicesWP, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
Server stack trace:
   at Microsoft.Silverlight.Build.Tasks.CompileXaml.GenerateCode(ITaskItem item, Boolean isApplication)
   at Microsoft.Silverlight.Build.Tasks.CompileXaml.Execute()
   at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Object[]& outArgs)
   at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg)
Exception rethrown at [0]:
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at Microsoft.Build.Framework.ITask.Execute()
   at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
   at Microsoft.Build.BackEnd.TaskBuilder.d__20.MoveNext()
WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.

A: Finally , I got solution for this. I upgrade my Visual Studio from Update 2 to Update 4. When you Build your project it gives and error about Hyper - V Network adapter. To Solve that, allow to change in Hyper -V Network Adapter settings by click on "Retry" button in prompt. ( You can also upgrade Window phone SDK to 8.1 for better experience. It is optional not necessary to solve this error.)

A: I worked around this problem by going back to Visual Studio 2019, rather than sticking with Visual Studio 2022. It seems 2022 still has a few issues.


text:
Q: BigQuery giving "Function Not Found" error although the schema column title was copied directly from the dataset Screenshot of error msg & SQL query
Is my SQL query off? Is BigQuery off?
I attempted to copy the column title again [no R clicks needed, simply mouse click the schema title and it inserts into the query itself]


text:
Q: Lead Compensator for double integrator I am an autodidact in control engineering and I have been trying to design a lead compensator for double integrator system so that the closed loop poles have damping $$\zeta=0.5$$ and natural frequency $$\omega_n=1\,rad\cdot s^{-1}$$ while pole/zero ratio of the compensator would not be greater than 10.
Desired location of closed loop poles is $$s_d=-\zeta\cdot\omega_n\pm i\cdot\omega_n\cdot\sqrt{1-\zeta^2}=-0.5\pm i\cdot 0.866.$$ Transfer function of lead compensator is $$D(s)=K\cdot\frac{s+z}{s+p}.$$ I started with a pole at \$-10\$. Then I computed position of zero as $$\zeta\cdot\omega_n+\frac{wn\cdot\sqrt{1-\zeta^2}}{\tan(\phi)}=0.5\cdot 1+\frac{1\cdot\sqrt{1-0.5^2}}{\tan(65.21^{\circ})}=0.9.$$ According to the root locus I set the gain of the compensator $$K=10.$$ My problem is that this design doesn't fulfill the constraint of pole-zero ratio and also the percent overshoot is greater than I would expected according to $$\exp\left(\frac{-\pi\cdot\zeta}{\sqrt{1-\zeta^2}}\right)\cdot 100=16.3\%.$$ When I tried different pole locations I got approximately same results.

How can I solve this problem? Thanks for any ideas.

A: I got the position of the pole to be \$8.873\$ and the gain to be \$8.873\$.
First,

yields \$z = 0.8873\$. Next plug in \$z\$ into the transfer function above and you get \$-0.1127\$. The gain is then \$\frac{1}{0.1127} = 8.873\$.
Step response is as follows

I also had issues with the overshoot (about \$33 \%\$) but at least it meets the pole-zero relationship. I'm guessing it's an issue with the two poles at \$0\$.


text:
Q: Writing CSV file with complex list data I'm trying to write a complex list of dictionaries to CSV, but getting encoding and value errors. I haven't really worked with data in Python, so I'm new to this.
import csv

with open("output.csv", 'rb', encoding='utf-8-sig', newline='') as f:
    writer = csv.writer(f, delimiter=",")
    for row in row_num:
        writer.writerows(row_num)

 Traceback (most recent call last):
 File "<console>", line 1, in <module>
 ValueError: binary mode doesn't take a newline argument

If I remove the encoding, I get: io.UnsupportedOperation: write.
Here is a sample of the data that I want to write to a CSV file with header being the key like code and  hid:
 [OrderedDict([('code', '7nsdjfk'), ('hid', '220'), ('name', 'sdjlnj dkldk slkdlkd'), ('code2', '99'), ('description', 'dmldc skdlmls wsldfml'), ('average', '0'), ('ccr', '0.218'), ('ccr_price', '399'), ('dusk sdks', '603'), ('dcfl lldcml', '3847.9'), ('id', 'sdklcldkcdslkcmsdl202i')]), OrderedDict([ ...]), OrderedDict([...])]

A: Changing the mode to text-plain
CSV stands for comma-separated value. This format consists on plain text.
Moreover, 'rb' means read r file as a binary b, which is incongruent with plain-text.
Try with 'wt' or just 'w' to actually write a plain-text file.
Check the python docs to learn more about the open() function.
Edit: Write data into file
I have come up with this solution:

*

*csv.writer is replaced by csv.DictWriter, which intakes the keys

*writer.writeheader() inserts the keys as headers separated by commas

*writer.writerows(row_num) writes the values into the file, one line per OrderedDict
from collections import OrderedDict
import csv

row_num = [OrderedDict([('code', '7nsdjfk'), ('hid', '220'), ('name', 'sdjlnj dkldk slkdlkd'), ('code2', '99'), ('description', 'dmldc skdlmls wsldfml'),
                        ('average', '0'), ('ccr', '0.218'), ('ccr_price', '399'), ('dusk sdks', '603'), ('dcfl lldcml', '3847.9'), ('id', 'sdklcldkcdslkcmsdl202i')]),
           OrderedDict([('code', 'a'), ('hid', '1'), ('name', 'b'), ('code2', '1'), ('description', 'c'),
                        ('average', '1'), ('ccr', '0.123'), ('ccr_price', '133'), ('dusk sdks', '133'), ('dcfl lldcml', '1345.9'), ('id', 'abcde')]),
        ]

keys = row_num[0].keys()

with open("output.csv", 'wt', encoding='utf-8-sig', newline='') as f:
    writer = csv.writer(f, delimiter=",")
    writer = csv.DictWriter(f, keys)
    writer.writeheader()

    # write values
    writer.writerows(row_num)

The results in output.csv are:
code,hid,name,code2,description,average,ccr,ccr_price,dusk sdks,dcfl lldcml,id
7nsdjfk,220,sdjlnj dkldk slkdlkd,99,dmldc skdlmls wsldfml,0,0.218,399,603,3847.9,sdklcldkcdslkcmsdl202i
a,1,b,1,c,1,0.123,133,133,1345.9,abcde

A: 'rb' stands for 'read as binary'. So, it reads the data from the file considering equivalent of binary.
It does not take any extra arguments, as per doc.
Simply use:
with open("output.csv", 'w') as f:

You can try to use 'w' in place of 'rb' mode just to write the file.
Words from the documentation....

Files opened in binary mode (including 'b' in the mode argument)
  return contents as bytes objects without any decoding.

Modes:
'r' - open for reading (default)
'w' - open for writing, truncating the file first
'x' - open for exclusive creation, failing if the file already exists
'a' - open for writing, appending to the end of the file if it exists
'b' - binary mode
't' - text mode (default)
'+' - open a disk file for updating (reading and writing)


text:
Q: Bitbucket Container 'Build' exceeded memory limit - When taking android build I use bitbucket pipeline for build android app but every time i am taking memory limit error.
Error message:

Container 'Build' exceeded memory limit.

Bitbucket yml file:
image: java:8

pipelines:
  branches:
    feature/*:
      - step:
          name: BuildApp
          caches:
            - gradle
            - android-sdk
          script:
            - wget --quiet --output-document=android-sdk.zip https://dl.google.com/android/repository/sdk-tools-linux-3859397.zip
            - unzip -o -qq android-sdk.zip -d android-sdk
            - export ANDROID_HOME="/opt/atlassian/pipelines/agent/build/android-sdk"
            - export PATH="$ANDROID_HOME/tools:$ANDROID_HOME/tools/bin:$ANDROID_HOME/platform-tools:$PATH"
            - yes | sdkmanager "platform-tools"
            - yes | sdkmanager "platforms;android-29"
            - yes | sdkmanager "build-tools;29.0.2"
            - yes | sdkmanager "extras;android;m2repository"
            - yes | sdkmanager "extras;google;m2repository"
            - yes | sdkmanager "extras;google;instantapps"
            - yes | sdkmanager --licenses
            - echo "$KEY_BASE64" | base64 --decode > app/$KEY_FILE_PATH
            - chmod +x gradlew
            - ./gradlew assembleRelease --stacktrace
          artifacts:
            - app/build/outputs/**

definitions:
  caches:
    android-sdk: android-sdk

I tried to increase docker memory like this.
definitions:
  services:
    docker:
      memory: 7128

pipelines:
  branches:
    feature/*:
      - step:
          name: Build App
          size: 2x

This will actually double the build minutes. I want to avoid that.
My gradle properties
kotlin.code.style=official
org.gradle.jvmargs=-Xmx4096m -XX:MaxPermSize=4096m -XX:+HeapDumpOnOutOfMemoryError
android.useAndroidX=true
android.enableJetifier=true
org.gradle.daemon=true
org.gradle.parallel=true
org.gradle.configureondemand=true

Normally my project build times not short and not small project, using a lot of libraries and feature modules. i don't know how its effect memory.

A: First we tried to increase docker memory size 7128mb.
But with configuration, we allocated 7128mb for the docker service. This leaves only 1024mb for the build container, which is not sufficient for the successful completion of the build.
We did reduce the docker service memory to 1024mb as shown below.
definitions:
  services:
    docker:
      memory: 1024

But still we getting error.
We check which process is taking how much memory and what is causing the failure.
Here is the ps -aux output from build:
> .... root          78  2.3  1.1 4853812 381648 ?      Sl   07:47
> 0:09 /usr/lib/jvm/java-8-openjdk-amd64//bin/java
> -Dorg.gradle.app....... root         314  182 12.2 10295652 3970496 ?    Ssl  07:47  13:00 /usr/lib/jvm/java-8-openjdk-amd64/bin/java
> -XX:MaxPermSize=4096m -XX:+HeapDumpOnOutOfMemoryError -Xmx4096m -Dfile.encoding=UTF-8 -Duser........... root        2744  145 11.0 10389720 3591488 ?    Sl   07:48   8:52
> /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java -cp
> /root/.gradle........ ...

From the output above, java process has -XX:MaxPermSize=4096m which limits the process to go over the 4gb limit and the other java process is spun up without the limit (and has 4gb memory usage as well). These two processes use 4gb RAM each.
Therefore we try to lower org.gradle.jvmargs to 2gb.
org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=2048m -XX:+HeapDumpOnOutOfMemoryError

And added JAVA_OPTS environment variable.
script:
  - JAVA_OPTS="-Xmx2048m -XX:MaxPermSize=2048m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8"

Finally we've got a successful build.


text:
Q: MDX - How skip 0 values in MIN agregation and how exclude some percent of results? In my cube I have

*

*Earnings as measure with MIN aggregation

*Dimension: [Localization].[Type].&[center]

*Dimension: {[Date].[Year].&[2017], [Date].[Year].&[2018]}

My query is:
What are the minimum earnings of the person who decides to buy
apartments in the city center, excluding 5% of the lowest, within
last 2 years?

Now my mdx query looks like that:
SELECT
[Measures].[MinEarnings] ON COLUMNS
FROM [cube]
WHERE
(
    BottomCount ([Localization].[Type].&[center], 95, [Measures].[MinEarnings]),
    {[Date].[Year].&[2017], [Date].[Year].&[2018]}
)

I have two problems:

*

*Some earnings are 0 - how can I skip them in calculations?

*If my query correctly excludes 5% of the lowest earnings?

A: First of all you should use toppercent not bottomcount. you want the min salary of a person who is not in last 5% not last 5. Toppercent will give you the top 95%.
Secondly to filter 0 you can use the following syntax
toppercent (
filter([Localization].[Type].&[center], [Measures].[MinEarnings]>0)
, 95, [Measures].[MinEarnings])

Even now placing the code in the where clause might not work, however try it. I would suggest that you move the toppercent to rows , then order it, then take the top1
topcount(
order(
toppercent (
filter([Localization].[Type].&[center], [Measures].[MinEarnings]>0)
,95, [Measures].[MinEarnings])
,[Measures].[MinEarnings],asc)
,1)

I have an example which gives the minum sales amount of cities, notice i have replaced nulls with 0 to make it as close as possible to your case
with member [Measures].[Internet Sales Amount2]
as
case when ([Measures].[Internet Sales Amount])=null then 0 else [Measures].[Internet Sales Amount] end
select [Measures].[Internet Sales Amount2]
on columns ,
topcount(order(toppercent(filter([Customer].[City].[City],[Measures].[Internet Sales Amount2]>0),95,[Measures].[Internet Sales Amount2]),[Measures].[Internet Sales Amount2],asc),1)
 on rows
from [Adventure Works]
where [Customer].[Country].&[Canada]

in the picture below is the result before topcount 1


text:
Q: Facebook like button changes to a "confirm" button and jumps to the left when clicked I've embedded a facebook like button on our page http://makethecitysoundbetter.com
When i click it, it turns into a "confirm" button, and moves to the left. When i click the "confirm" i get the normal share box, and after that i works as it should.
I have copied the instructions exactly from facebook's Like button page: developers.facebook.com/docs/reference/plugins/like/
And i've even created an empty html page ONLY with facebooks code, copy pasted and placed exactly as they've written (http://makethecitysoundbetter.com/fb_test.html).
I've tried both the HTML5 and XFBML code, both with the same results..
Does anyone know what is going on, and how i can fix this?
It's very important that our share function works!
Thanks in advance!
Andy

A: I had the exact same problem. I ended up using the iframe version of the like button and now everything works great.


text:
Q: Material Design checklist: hiding app bar on scroll? Per the new Android Material Design checklist:
http://android-developers.blogspot.com/2014/10/material-design-on-android-checklist.html

Where appropriate, upon scrolling down, the app bar can scroll off the screen, leaving more vertical space for content. Upon scrolling back up, the app bar should be shown again.

I realize there are lots of questions/answers to implement this behavior for the ICS-style app bar, but I'm curious if the new Toolbar widget or Lollipop/AppCompat 21 have introduced a more standard way of achieving this effect.

A: Per Roman Nurik on Google+ (essentially what @tyczj mentioned)
https://plus.google.com/u/0/+RomanNurik/posts/3G8zYvN5oRC

It's not built in but relatively simple to implement. Just observe scrolling and animate the Y translation. Could also use the "quick return" sample +Nick Butcher and I published a few years ago

I believe that example referenced is:
https://code.google.com/p/romannurik-code/source/browse/misc/scrolltricks
UPDATE: I also just discovered a great library that does this, along with some other great tricks https://github.com/ksoichiro/Android-ObservableScrollView

A: Ref: https://material.io/develop/android/components/app-bars-bottom
hiding app bar on scroll:
<com.google.android.material.bottomappbar.BottomAppBar
    android:id="@+id/bottomAppBar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"

    app:hideOnScroll="true"

    app:navigationIcon="@drawable/ic_menu_color_control_normal_24dp"
    app:navigationContentDescription="Navigation icon"
    android:fitsSystemWindows="true"
    />

Kotlin: programmatically
  bottomAppBar.hideOnScroll = true


text:
Q: Combobox dinámico muestra Paises y Provincias pero no salen las Ciudades Dispongo de un combobox para hacer el típico formulario donde eliges el país (por ejemplo España), y en el desplegable de provincia ya sólo tienes para elegir las provincias de españolas, y una vez elegido por ejemplo Gipuzkoa (como provincia), en el desplegable de ciudades te salen sólo ciudades de Gipuzkoa como pueden ser Donostia y Irún o Hernani.
PAISES y PROVINCIAS funcionan, CIUDADES no sale nada en el desplegable.
Contenido: Base de datos de 3 tablas (países, provincias, ciudades), archivos de consulta paises.php, provincias.php y ciudades.php, y una función javascript para que se vean las select en el desplegable FUNCTION.JS
Creo que el error está en el FUNCTION.JS que me falta algo para que las ciudades también se visualicen. Paises y Provincias se ven perfectamente.
Tengo en la base de datos 3 tablas:

*

*Paises

*Provincias

*Ciudades

(Se han creado las tablas con algunos ejemplo de países, provincias y ciudades)
En el formulario HTML donde tendremos los desplegables de País, Provincia y Ciudad:

País

<select name="paises" id="paises">
  <option value="0">Seleccione</option>
</select>

Provincia

<select name="provincias" id="provincias">
  <option value="0">Seleccione</option>
</select>

Ciudad

<select name="ciudades" id="ciudades">
  <option value="0">Seleccione</option>
</select>

Después las consultas en varios archivos php: paises.php, provincias.php y ciudades.php:
PAISES.PHP
 <?php
include ('conexion.php');
$query = $conn->query("SELECT * FROM paises");
echo '<option value="0">Seleccione</option>';
while ( $row = $query->fetch_assoc() )
{
    echo '<option value="' . $row['id_pais']. '">' . $row['nombre_pais'] . '</option>' . "\n";
}
?>

PROVINCIAS.PHP
    <?php
include ('conexion.php');
$el_pais = $_POST['pais'];
$query = $conn->query("SELECT * FROM provincias WHERE id_pais = $el_pais");
echo '<option value="0">Seleccione</option>';
while ( $row = $query->fetch_assoc() )
{
    echo '<option value="' . $row['id_provincia']. '">' . $row['nombre_provincia'] . '</option>' . "\n";
}
?>

CIUDADES.PHP
    <?php

include ('conexion.php');
$la_provincia = $_POST['provincia'];
$query = $conn->query("SELECT * FROM ciudades WHERE id_provincia = $la_provincia");
echo '<option value="0">Seleccione</option>';
while ( $row = $query->fetch_assoc() )
{
    echo '<option value="' . $row['id_ciudad']. '">' . $row['nombre_ciudad'] . '</option>' . "\n";
}
?>

Y por último la función de llamada donde creo que está el error o falta algo para que las ciudades aparezcan:
FUNCTION.JS
$(function()
{

// Lista de Paises
$.post( 'paises.php' ).done( function(respuesta)
{
    $( '#paises' ).html( respuesta );
});

// lista de Provincias
$('#paises').change(function()
    {
        var el_pais = $(this).val();

    // Lista de Paises
    $.post( 'provincias.php', { pais: el_pais} ).done( function( respuesta )
    {
            $( '#provincias' ).html( respuesta );
        });
    });

// Lista de Ciudades
$( '#provincias' ).change( function()
{
        var pais = $(this).children('option:selected').html();
    alert( 'Lista de Provincias de ' + provincia );
});

})

¿Dónde está el error? ¿Qué falta?
Gracias de antemano.

A: Solo tienes que agregarle al change() de provincias la funcionalidad de buscar las ciudades te dejo mas o menos el ejemplo de como.
La idea es hacer la petición al hacer change() en provincias.
 $( '#provincias' ).change()

Luego pasarle como parametro al metodo $.post() el id de la provincia seleccionada que lo hacemos con
 { provincia: $( '#provincias' ).val()}

o también podría ser así
 { provincia: $(this).val()}

Y al final hay que obtener los valores que nos retorna la petición y agregarselos al select de ciudades
$( '#ciudades' ).html( respuesta );

$(function()
{

// Lista de Paises
$.post( 'paises.php' ).done( function(respuesta)
{
   $( '#paises' ).html( respuesta );
});

// lista de Provincias
$('#paises').change(function()
{
    var el_pais = $(this).val();

// Lista de Paises
$.post( 'provincias.php', { pais: el_pais} ).done( function( respuesta )
{
        $( '#provincias' ).html( respuesta );
     });
});

// Lista de Ciudades
$( '#provincias' ).change( function()
{
    //var pais = $(this).children('option:selected').html();

    //Nuevo codigo
    // Lista de Ciudades
   $.post( 'ciudades.php', { provincia: $( '#provincias' ).val()} ).done(
   function( respuesta )
    {
        $( '#ciudades' ).html( respuesta );
       alert( 'Lista de ciudades ' + respuesta);
     });

});

})

Espero te ayude amigo saludos.


text:
Q: Error on MSVC++ with extending iostream I'm writing an output manager class for my application and although my class works on g++ under linux, it won't compile under MSVC++ 2010.
Here is a SSCCE version of my program :
#include <iostream>
#include <malloc.h>
#include <sstream>
#include <fstream>

template<class cT, class traits=std::char_traits<cT> >
class BasicE3OutStream: public std::basic_ostream<cT, traits> {
    public:
        BasicE3OutStream() :
                std::basic_ios<cT, traits>(), std::basic_ostream<cT, traits>(0), mBuffer() {
            resetModifiers();
            mLineBuffer=(std::stringstream*) malloc(sizeof(std::stringstream));
            mLineBuffer=new (mLineBuffer) std::stringstream();
        }

        BasicE3OutStream(const BasicE3OutStream<cT,traits> &) {
        }

        virtual ~BasicE3OutStream() {
            delete mLineBuffer;
            mLineBuffer=NULL;
        }

        void resetModifiers() {
            mDebug=false;
            mMemory=false;
        }

        void open(const char* fileName) {
            mBuffer.open(fileName, std::stringstream::out);
        }

        void close() {
            mBuffer.close();
        }

        template<class T>
        BasicE3OutStream& operator<<(T val) {
            (*mLineBuffer)<<val;
            return (*this);
        }

        BasicE3OutStream& operator<<(char* val) {
            (*mLineBuffer)<<val;
            return (*this);
        }

        BasicE3OutStream& operator<<(std::string val) {
            (*mLineBuffer)<<val;
            return (*this);
        }

        void addLineFeed() {
            std::string modifier;
            modifier="";
            if (mDebug)
                modifier+="[DEBUG] ";
            else if (mMemory)
                modifier+="[MEMORY] ";

            mBuffer<<modifier<<mLineBuffer->str()<<"\n";
            mLineBuffer->~basic_stringstream();
            mLineBuffer=new (mLineBuffer) std::stringstream();
            resetModifiers();
        }

        void flush() {
            mBuffer.flush();
            resetModifiers();
        }

        void setFlag(int f) {
            if (f==0)
                mDebug=true;
            else if (f==1)
                mMemory=true;
        }
    public:
        std::basic_ofstream<cT, traits> mBuffer;
        std::stringstream* mLineBuffer;
        bool mDebug, mMemory;
};

template<class cT, class traits, class T>
BasicE3OutStream<cT, traits>& operator<<(BasicE3OutStream<char, traits>& str , T val) {
    str.operator <<(val);
    return (str);
}

typedef BasicE3OutStream<char> E3OutStream;

template<class charT, class traits>
BasicE3OutStream<charT, traits>& endl(BasicE3OutStream<charT, traits>& os) {
    os.addLineFeed();
    return (os);
}

template<class charT, class traits>
BasicE3OutStream<charT, traits>& flush(BasicE3OutStream<charT, traits>& os) {
    os.flush();
    return (os);
}

template<class charT, class traits>
BasicE3OutStream<charT, traits>& debug(BasicE3OutStream<charT, traits>& os) {
    os.setFlag(0);
    return (os);
}

template<class charT, class traits>
BasicE3OutStream<charT, traits>& memory(BasicE3OutStream<charT, traits>& os) {
    os.setFlag(1);
    return (os);
}

/**
 * Io manipulator, allows to use endl and other modificators
 */
template<class charT, class traits> BasicE3OutStream<charT, traits>& operator<<(
        BasicE3OutStream<charT, traits> &s
        , BasicE3OutStream<charT, traits>& (*iomanip)(BasicE3OutStream<charT, traits>&)) {
    return (iomanip(s));
}

int main() {
    E3OutStream s;
    s.open("output.txt");
    s<<debug<<"Debug info"<<endl;
    s<<flush;
    s<<memory<<"Memory info"<<endl;
    s<<flush;
    s.close();
}

It runs fine in g++ however on MSVC I get a compiler error :
1>------ Build started: Project: sscce, Configuration: Debug Win32 ------
1>  main.cpp
1>c:\users\guillaume\documents\visual studio 2010\projects\sscce\sscce\main.cpp(129): error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'overloaded-function' (or there is no acceptable conversion)
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(679): could be 'std::basic_ostream<_Elem,_Traits> &std::operator <<<char,std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,const char *)' [found using argument-dependent lookup]
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(726): or       'std::basic_ostream<_Elem,_Traits> &std::operator <<<char,std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,char)' [found using argument-dependent lookup]
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(764): or       'std::basic_ostream<_Elem,_Traits> &std::operator <<<std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,const char *)' [found using argument-dependent lookup]
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(811): or       'std::basic_ostream<_Elem,_Traits> &std::operator <<<std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,char)' [found using argument-dependent lookup]
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(937): or       'std::basic_ostream<_Elem,_Traits> &std::operator <<<std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,const signed char *)' [found using argument-dependent lookup]
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(944): or       'std::basic_ostream<_Elem,_Traits> &std::operator <<<std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,signed char)' [found using argument-dependent lookup]
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(951): or       'std::basic_ostream<_Elem,_Traits> &std::operator <<<std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,const unsigned char *)' [found using argument-dependent lookup]
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(958): or       'std::basic_ostream<_Elem,_Traits> &std::operator <<<std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,unsigned char)' [found using argument-dependent lookup]
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(1085): or       'std::basic_ostream<_Elem,_Traits> &std::operator <<<char,std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,const std::error_code &)' [found using argument-dependent lookup]
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          c:\users\guillaume\documents\visual studio 2010\projects\sscce\sscce\main.cpp(43): or       'BasicE3OutStream<cT> &BasicE3OutStream<cT>::operator <<(char *)'
1>          with
1>          [
1>              cT=char
1>          ]
1>          c:\users\guillaume\documents\visual studio 2010\projects\sscce\sscce\main.cpp(48): or       'BasicE3OutStream<cT> &BasicE3OutStream<cT>::operator <<(std::string)'
1>          with
1>          [
1>              cT=char
1>          ]
1>          while trying to match the argument list '(E3OutStream, overloaded-function)'
1>c:\users\guillaume\documents\visual studio 2010\projects\sscce\sscce\main.cpp(130): error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'overloaded-function' (or there is no acceptable conversion)
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(679): could be 'std::basic_ostream<_Elem,_Traits> &std::operator <<<char,std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,const char *)' [found using argument-dependent lookup]
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(726): or       'std::basic_ostream<_Elem,_Traits> &std::operator <<<char,std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,char)' [found using argument-dependent lookup]
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(764): or       'std::basic_ostream<_Elem,_Traits> &std::operator <<<std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,const char *)' [found using argument-dependent lookup]
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(811): or       'std::basic_ostream<_Elem,_Traits> &std::operator <<<std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,char)' [found using argument-dependent lookup]
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(937): or       'std::basic_ostream<_Elem,_Traits> &std::operator <<<std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,const signed char *)' [found using argument-dependent lookup]
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(944): or       'std::basic_ostream<_Elem,_Traits> &std::operator <<<std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,signed char)' [found using argument-dependent lookup]
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(951): or       'std::basic_ostream<_Elem,_Traits> &std::operator <<<std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,const unsigned char *)' [found using argument-dependent lookup]
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(958): or       'std::basic_ostream<_Elem,_Traits> &std::operator <<<std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,unsigned char)' [found using argument-dependent lookup]
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(1085): or       'std::basic_ostream<_Elem,_Traits> &std::operator <<<char,std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,const std::error_code &)' [found using argument-dependent lookup]
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          c:\users\guillaume\documents\visual studio 2010\projects\sscce\sscce\main.cpp(43): or       'BasicE3OutStream<cT> &BasicE3OutStream<cT>::operator <<(char *)'
1>          with
1>          [
1>              cT=char
1>          ]
1>          c:\users\guillaume\documents\visual studio 2010\projects\sscce\sscce\main.cpp(48): or       'BasicE3OutStream<cT> &BasicE3OutStream<cT>::operator <<(std::string)'
1>          with
1>          [
1>              cT=char
1>          ]
1>          while trying to match the argument list '(E3OutStream, overloaded-function)'
1>c:\users\guillaume\documents\visual studio 2010\projects\sscce\sscce\main.cpp(131): error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'overloaded-function' (or there is no acceptable conversion)
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(679): could be 'std::basic_ostream<_Elem,_Traits> &std::operator <<<char,std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,const char *)' [found using argument-dependent lookup]
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(726): or       'std::basic_ostream<_Elem,_Traits> &std::operator <<<char,std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,char)' [found using argument-dependent lookup]
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(764): or       'std::basic_ostream<_Elem,_Traits> &std::operator <<<std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,const char *)' [found using argument-dependent lookup]
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(811): or       'std::basic_ostream<_Elem,_Traits> &std::operator <<<std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,char)' [found using argument-dependent lookup]
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(937): or       'std::basic_ostream<_Elem,_Traits> &std::operator <<<std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,const signed char *)' [found using argument-dependent lookup]
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(944): or       'std::basic_ostream<_Elem,_Traits> &std::operator <<<std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,signed char)' [found using argument-dependent lookup]
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(951): or       'std::basic_ostream<_Elem,_Traits> &std::operator <<<std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,const unsigned char *)' [found using argument-dependent lookup]
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(958): or       'std::basic_ostream<_Elem,_Traits> &std::operator <<<std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,unsigned char)' [found using argument-dependent lookup]
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(1085): or       'std::basic_ostream<_Elem,_Traits> &std::operator <<<char,std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,const std::error_code &)' [found using argument-dependent lookup]
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          c:\users\guillaume\documents\visual studio 2010\projects\sscce\sscce\main.cpp(43): or       'BasicE3OutStream<cT> &BasicE3OutStream<cT>::operator <<(char *)'
1>          with
1>          [
1>              cT=char
1>          ]
1>          c:\users\guillaume\documents\visual studio 2010\projects\sscce\sscce\main.cpp(48): or       'BasicE3OutStream<cT> &BasicE3OutStream<cT>::operator <<(std::string)'
1>          with
1>          [
1>              cT=char
1>          ]
1>          while trying to match the argument list '(E3OutStream, overloaded-function)'
1>c:\users\guillaume\documents\visual studio 2010\projects\sscce\sscce\main.cpp(132): error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'overloaded-function' (or there is no acceptable conversion)
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(679): could be 'std::basic_ostream<_Elem,_Traits> &std::operator <<<char,std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,const char *)' [found using argument-dependent lookup]
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(726): or       'std::basic_ostream<_Elem,_Traits> &std::operator <<<char,std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,char)' [found using argument-dependent lookup]
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(764): or       'std::basic_ostream<_Elem,_Traits> &std::operator <<<std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,const char *)' [found using argument-dependent lookup]
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(811): or       'std::basic_ostream<_Elem,_Traits> &std::operator <<<std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,char)' [found using argument-dependent lookup]
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(937): or       'std::basic_ostream<_Elem,_Traits> &std::operator <<<std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,const signed char *)' [found using argument-dependent lookup]
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(944): or       'std::basic_ostream<_Elem,_Traits> &std::operator <<<std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,signed char)' [found using argument-dependent lookup]
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(951): or       'std::basic_ostream<_Elem,_Traits> &std::operator <<<std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,const unsigned char *)' [found using argument-dependent lookup]
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(958): or       'std::basic_ostream<_Elem,_Traits> &std::operator <<<std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,unsigned char)' [found using argument-dependent lookup]
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(1085): or       'std::basic_ostream<_Elem,_Traits> &std::operator <<<char,std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,const std::error_code &)' [found using argument-dependent lookup]
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>          c:\users\guillaume\documents\visual studio 2010\projects\sscce\sscce\main.cpp(43): or       'BasicE3OutStream<cT> &BasicE3OutStream<cT>::operator <<(char *)'
1>          with
1>          [
1>              cT=char
1>          ]
1>          c:\users\guillaume\documents\visual studio 2010\projects\sscce\sscce\main.cpp(48): or       'BasicE3OutStream<cT> &BasicE3OutStream<cT>::operator <<(std::string)'
1>          with
1>          [
1>              cT=char
1>          ]
1>          while trying to match the argument list '(E3OutStream, overloaded-function)'
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Any help would be greatly appreciated,
Guillaume
[EDIT]
Thanks to this adviceI was given, I was able to realize that extending iostream was not useful in that case since I already had an ofstream as a member variable. Since I don't know enough of the internal working of the std library, I made my class independant and it worked on both MSVC and g++ :
#include <iostream>
#include <malloc.h>
#include <sstream>
#include <fstream>

class BasicE3OutStream {
    public:
        BasicE3OutStream() :
                mBuffer() {
            resetModifiers();
            mLineBuffer=(std::stringstream*) malloc(sizeof(std::stringstream));
            mLineBuffer=new (mLineBuffer) std::stringstream();
        }

        BasicE3OutStream(const BasicE3OutStream &) {
        }

        virtual ~BasicE3OutStream() {
            delete mLineBuffer;
            mLineBuffer=NULL;
        }

        void resetModifiers() {
            mDebug=false;
            mMemory=false;
        }

        void open(const char* fileName) {
            mBuffer.open(fileName, std::stringstream::out);
        }

        void close() {
            mBuffer.close();
        }

        template<class T>
        BasicE3OutStream& operator<<(T val) {
            (*mLineBuffer)<<val;
            return (*this);
        }

        void addLineFeed() {
            std::string modifier;
            modifier="";
            if (mDebug)
                modifier+="[DEBUG] ";
            else if (mMemory)
                modifier+="[MEMORY] ";

            mBuffer<<modifier<<mLineBuffer->str()<<"\n";
            mLineBuffer->str("");
            resetModifiers();
        }

        void flush() {
            mBuffer.flush();
            resetModifiers();
        }

        void setFlag(int f) {
            if (f==0)
                mDebug=true;
            else if (f==1)
                mMemory=true;
        }
    public:
        std::ofstream mBuffer;
        std::stringstream* mLineBuffer;
        bool mDebug, mMemory;
};

BasicE3OutStream& endl(BasicE3OutStream& os) {
    os.addLineFeed();
    return (os);
}

BasicE3OutStream& flush(BasicE3OutStream& os) {
    os.flush();
    return (os);
}

BasicE3OutStream& debug(BasicE3OutStream& os) {
    os.setFlag(0);
    return (os);
}

BasicE3OutStream& memory(BasicE3OutStream& os) {
    os.setFlag(1);
    return (os);
}

/**
 * Io manipulator, allows to use endl and other modificators
 */
BasicE3OutStream& operator<<(
        BasicE3OutStream &s
        , BasicE3OutStream& (*iomanip)(BasicE3OutStream&)) {
    return (iomanip(s));
}

typedef BasicE3OutStream E3OutStream;

int main() {
    E3OutStream s;
    s.open("output.txt");
    s<<debug<<"Debug info"<<endl;
    s<<flush;
    s<<memory<<"Memory info"<<endl;
    s<<flush;
    s.close();
}

A: The core of the problem is that you're sending function pointers to your stream, which GCC seems to know how to handle, but MSVC++ doesn't.  Either way, I doubt you wanted to save the address of the debug/endl/flush/memory functions.
The next-step resolution is to make those objects instead of functions that you display.
However, there's a lot wrong with this code.  Namely, there already exist endl and flush objects, which you should be using.  Also, each BasicE3OutStream has three underlying streams, one it inherited from, that all the functions work on, (including endl and such, which I assume is why you replaced them), and mBuffer and mLineBuffer, (neither of the members is needed for what you're doing).  (Another side note, reset a stringstream with mLineBuffer.str("");, not placement new)
The easy way to do what you want is to overload each of the operator<< members of a basic_ostream, and wherever there is a newline, insert [DEBUG] or [MEMORY] as appropreate, there's no need to buffer.  (I've done this, it's not crazy hard)
There's probably a right way to do this by using a stream with different char traits, or overloading certain virtual functions, or replacing the buffer, but streams are complicated, and I don't know this right way.


text:
Q: A suitable database structure to use with this kind of project? I'm working on a site analysis project. Where users will be able to record/view their site traffic reports by using my API (like Google Analytics).
The problem is, I'm not sure how I should setup the database structure.
I already have some tables setup for user management purposes:
User table: || userID || userName || datReg ||
Account information table: || accountInfoID || userID || fName || lName || emailAddress ||
So I was thinking I could do something like:
Site analysis table: || analyID || userID || visitorIP || visitorCountry || pageviewCount || pageviewData
But would that be scalable? I mean, with that structure there could be tens of thousands of rows inserted every day, so would that not result to being very slow after a few months?
With the idea above, I would run a query similar to this, for each unique visit:
INSERT INTO siteAnaly (userID,visitorIP,visitorCountry,pageviewCount,pageviewData) VALUES ("the accounts holders user ID","the visitors IP","the visitors country","the visitors apge view count","a JSON array of the visitors pageview URI's")

and then, on every pageview, that row inserted fro the query above, would be updated. Incrementing the pageviewCount and appending to pageviewData
The other idea I had (which you may think is stupid) was to have a new table for every user, named with the users ID.
What do you think is the best approach to take with a project like this?

A: visitorIP and vistorCountry can be moved to different table. These values will surely repeat. What kind of data you want to keep in pageViewData?

A: It will indeed have lots of data input, what you will need to do in this case is to split data in different tables and even databases at one point to make sure you don't clutter your main datasource. Rarely will you need to query large portions of data that will not have been processed so your goal is to:

*

*Create a database that stores your unprocessed data for later reference

*Create a processed database that compiles all the possible data in aggregated tables

*Create a script that will generate the agregated data

*Create an application that can lookup data from today's unprocessed data if you absolutely need it live.

A good conference i went to see and did a review on it was posted on my blog, you might want to read it:
http://crazycoders.net/2012/03/confoo-2012-continous-data-processing/
Good luck


text:
Q: PHP Multiple foreach loop to insert object in array I want to add elements to an array with a condition, but with this code the $ready array only work with the first value of array. what did i miss ?
$data['garduinduk'] :
 Array ( [0] => stdClass Object (
            [id] => 1
            [id_app] => 2
            [id_basecamp] => 1
            [nama] => GI BOGOR BARU
            [room] =>
           )
        [1] => stdClass Object (
            [id] => 2
            [id_app] => 2
            [id_basecamp] => 1
            [nama] => GI CIAWI BARU
            [room] =>
          )
        [2] => stdClass Object (
            [id] => 3
            [id_app] => 2
            [id_basecamp] => 1
            [nama] => GI CIAWI
            [room] =>
          )

$ready :
Array ( [0] => stdClass Object (
            [lokasi] => 1
            [berlaku_dari] =>
            [berlaku_sampai] => 0000-00-00
            [status] => On_progress
            [file] =>
           )
        [1] => stdClass Object (
            [lokasi] => 16
            [berlaku_dari] =>
            [berlaku_sampai] => 0000-00-00
            [status] => On_progress
            [file] =>
           )
        [2] => stdClass Object (
            [lokasi] => 2
            [berlaku_dari] =>
            [berlaku_sampai] => 0000-00-00
            [status] => On_progress
            [file] => /assets/files/155bd035e88358b.PNG
           )
        [3] => stdClass Object (
            [lokasi] => 2
            [berlaku_dari] => 2019-02-27
            [berlaku_sampai] => 2019-02-28
            [status] => Selesai
            [file] => /assets/files/215c76691f12ae9.pdf
          )
     )

Code :
foreach ($data['garduinduk'] as $key => $gi){
            foreach ($ready as $rdy){
                if ($rdy->lokasi == $gi->id){
                    if ($rdy->status == 'On_progress'){
                        $gi->berlaku_dari = 'ON PROGRESS';
                        $gi->berlaku_sampai = 'ON PROGRESS';
                        $gi->file = 'ON PROGRESS';
                    }else{
                        $gi->berlaku_dari = $rdy->berlaku_dari;
                        $gi->berlaku_sampai = $rdy->berlaku_sampai;
                        $gi->file = $rdy->file;
                    }

                }else{
                    $gi->berlaku_dari = '';
                    $gi->berlaku_sampai = '';
                    $gi->file = '';
                }
            }
        }

A: Use reference on $gi
foreach ($data['garduinduk'] as $key => &$gi){

or use
$data['garduinduk'][$key]->

instead of
$gi->