text:
Q: Incomprehensible expression in Stack ADT implementation There is a stack ADT implementation below. In this implemantation, programmer has used linked list.
struct Node {
    char *elem;
    struct Node *next;
};

static struct Node *new_node(void *elem, int elem_size)
{
    struct Node *n = malloc(sizeof(struct Node));
    n->elem = malloc(elem_size);
    memcpy(n->elem, elem, elem_size);
    n->next = NULL;

    retrun n;
}

struct Stack {
    int elem_size;
    int n_elems;
    struct Node *top;
}

I got it, except the code block as shown below.
void stack_push(struct Stack *s, void *elem)
{
    struct Node *n = new_node(elem, s->elem_size);
    n->next = s->top;
    s->top = n;

    s->n_elems++;
}

I did not understand that
n->next = s->top;
s->top = n;

Would anyone like to help me to understand this statements. I will appreciate.

A: The push operation adds a new item to the top of the stack. In this implementation, the top of the stack is s->top. The second item on the stack is s->top->next, the third is s->top->next->next, and so on.
I think it is easier to think of
n->next = s->top;
s->top = n;

as
s->top = n;
n->next = s->top;

The first statement is making the new node n the top of the stack. But the second item of the stack is NULL while it should be the old top of the stack. The second statement fixes this, making the old top of the stack the second item of the stack.

A: Let's try my Paint skillz:
Before:

After:

NULL indicates that the node points to nothing, i.e., it is the last node inserted.
Note that next points to the next node, not to that node's next, I just had no better way of showing this here.


text:
Q: Como encontrar a média pelo número de vetores preenchidos? Preciso calcular a média de um vetor, mas considerando apenas aqueles que tiveram os campos preenchidos.
Por exemplo:
HTML:
Valor:
<input type="text" id="Cmes222" name="Tmes222">

Valor:
<input type="text" id="Cmes444" name="Tmes444">

Valor:
<input type="text" id="Cmes666" name="Tmes666">

Valor:
<input type="text" id="Cmes888" name="Tmes888">

O PHP:
$salbasetar[0] = $_POST ["Tmes222"];
$salbasetar[1] = $_POST ["Tmes444"];
$salbasetar[2] = $_POST ["Tmes666"];
$salbasetar[3] = $_POST ["Tmes888"];

$salbasetarm = ($salbasetar[0] + $salbasetar[1] + $salbasetar[2] + $salbasetar[3]) / 4;

Então ao invés de 4, quero dividir pelo número de vetores que foram preenchidos. Já pesquisei bastante mas nada serviu. Penso que deve dar pra fazer com count ou foreach, mas não consegui fazer... alguém poderia dar um exemplo?

A: Encontrei a resposta nesta pergunta do SOen.
Basicamente, o que funcionou foi:
$result = count(array_filter($salbasetar));

$salbasetarm = ($salbasetar[0] + $salbasetar[1] + $salbasetar[2] + $salbasetar[3]) / $result;

redpajama_set_name: RedPajamaStackExchange


text:
Q: DomPDF > Allowed memory exhausted
Possible Duplicate:
Allowed memory size of X bytes exhausted

I'm hitting a very tricky issue.

*

*As per phpInfo, the memory limit set for this script is 256M. However, domPDF gets only 64M

*When I run the PDF creation action from the frontend, it works like a charm. When a cron calls a sfTask to do it, I get this:

[28-Sep-2012 10:41:03] PHP Fatal error:  Allowed memory size of
  67108864 bytes exhausted (tried to allocate 76 bytes) in
  /home3/myspace/public_html/prasad/myapp/lib/vendor/dompdf/include/frame_decorator.cls.php
  on line 30

And for the record, its printing one simple page whose PDF size is < 5K
Can someone help?

A: To make from vstms comment an awnser because Prasad solved his problem:

No, 64M is not sufficient hence the "Allowed memory"-error. You have
  to find the php.ini of the CLI and change it there. The alternative is
  to change the setting via command line - like php -d memory_limit=256M
  /path/to/your/php-file. A segmentation fault occurs when a program
  tries to access invalid memory. It's likely a problem with the
  PHP-interpreter itself. It would be hard to find the reason, even with
  shell-access.


text:
Q: Create File at user defined path I am creating a file in java using
BufferedWriter out = new BufferedWriter(new FileWriter(FileName));
StringBuffer sb=new StringBuffer();
sb.append("\n");
sb.append("work");
out.write(sb.toString());
out.close();

But this file is getting created inside the bin folder of my server.I would like to create this file inside a user-defined folder.
How can it be achieved.

A:
I would like to create this file inside a user-defined folder.

The simplest approach is to specify a fully qualified path name. You could select that as a File and build a new File relative to it:
File directory = new File("/home/jon/somewhere");
File fullPath = new File(directory, fileName);
BufferedWriter writer = new BufferedWriter(
    new OutputStreamWriter(
        (new FileOutputStream(fullPath), charSet));
try {
    writer.write("\n");
    writer.write("work");
} finally {
    writer.close();
}

Note:

*

*I would suggest using a FileOutputStream wrapped in an OutputStreamWriter instead of using FileWriter, as you can't specify an encoding with FileWriter

*Use a try/finally block (or try-with-resources in Java 7) so that you always close the writer even if there's an exception.

A: To create a file in a specific directory, you need to specify it in the file name.
Otherwise it will use the current working directory which is likely to be where the program was started from.
BTW: Unless you are using Java 1.4 or older, you can use StringBuilder instead of StringBuffer, although in this case PrintWriter would be even better.


text:
Q: The study of Hausdorff distance as a pseudometric. In hyperspace theory, if $(X,d)$ is a metric space, then the Hausdorff distance between nonempty subsets $A$ and $B$ of $X$ can be defined as $$H(A,B)=\text{max}\{\text{sup}\{d(a,B): a\in A\},\text{sup}\{d(b,A): b\in B\} \}$$ This is "the farthest distance any point of $B$ is from the set $A$, or the farthest
any point of $A$ is from $B$, whichever is greater." In general, $H$ is not a metric, but a pseudometric (for $H(A,B)=0$ if and only if $\overline{A}=\overline{B}$, where overline denotes closure.)
Every article I've read about the Hausdorff distance only studies it in the hyperspace of closed sets, because it is a metric there, however I am interested in its properties as a (possibly extended) pseudometric in the power set of $X$ minus the empty set. I find the property I mentioned above incredibly useful and interesting, so I was wondering if there are any texts that address this topic any further. Pseudometric spaces seem more exotic and attractive to me lately.
Does anyone know more about Hausdorff distance as a pseudometric?


text:
Q: First time going Serverless - how is the learning curve? Do you recommend using a third party framework? Currently looking into setting up a personal project on a Serverless model. Considering AWS Lambda, but open to other providers. The question is, does anyone have experience using serverless component frameworks (i.e. Serverless:  https://serverless.com/framework/) in addition to going directly through AWS or a similar provider? If so, do you have a recommendation for someone who has not setup a serverless model before (whether or not to use a framework)? For reference, I've worked with traditional cloud services in the past, and this project involves financial data and machine learning, and has a client facing front end.

A: First and foremost, you'll want to make sure serverless is right for the project. Serverless architecture is fantastic, but bear in mind it's not always the right solution.
To answer your question, I have experience with both AWS Lambda on its own and with Serverless (the specific framework you linked). Serverless (the framework) handles a lot of the complexity for you, and is definitely worth looking into if you're building data pipelines (which it appears you are). That being said, I would recommend getting familiar with the serverless architecture first, and then using a framework like Serverless after you know what you're doing. Learning curve isn't too bad.


text:
Q: Выдаёт ошибку при попытке реализовать Router в React У меня есть функция
function App() {
  return (
    <BrowserRouter>
      <Route path="/about">
        <About />
      </Route>
      <Route path="/about">
        <Posts />
      </Route>
    </BrowserRouter>
  )
}

Выдаёт ошибку:

A  is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route>

A: Ваша функция роута должна выглядеть так
function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/about" element={<About />} />
        <Route path="/posts" element={<Posts />} />
      </Routes>
    </BrowserRouter>
  )
}

Все ваши Route должны быть обернуты в <Routes>, а компоненты, которые должны отображаться необходимо указывать в element.


text:
Q: Java Selenium - How to Click a Button that has no ID or ng-class in AngularJS based page The following code I've used is not clicking the button and showing the error message.
WebElement clickNextButton = webDriver.findElement(By.cssSelector("button[ng-class='btn-success']"));
clickNextButton.click();

Error message shows "no such element: Unable to locate element. {"method":"css selector","selector":"button[ng-class='btn-success']"}

I've also tried the following code segments without success:

*

*  WebElement clickNext1 = webDriver.findElement(By.cssSelector("button[ng-class='pccCTRL.pow.Page1InputsValid() ? 'btn-success' : 'btn-default'']"));
  clickNext1.click();

* webDriver.findElement(By.partialLinkText("Next")).click();

*  webDriver.findElement(By.cssSelector("button[type='button']")).click();

Here is the screenshot showing the html code segment of the button I'm trying to

Hoping to get feedback. Thank you.

A: Ok, I was able to solve this issue by using By.xpath
Here is the code segment that solved it:
WebElement clickNextButton = webDriver.findElement(By.xpath("//button[contains(text(),'Next')]"));

clickNextButton.click();


text:
Q: How to remove the joins in this slow SQL I have the following (obfuscated) SQL running on SQL Server 2012 and need to significantly improve its performance. It works, but sometimes takes more than 60s to return.
I would like to extract the JOINS but this post seems to indicate that this will not be possible (because of things like MIN and MAX) - so how can improve the performance and get these joins simplified/improved?
SELECT
    wm.id, wm.uid, wm.em, wm.fn, wm.ln, c, y, RTRIM(LTRIM(yCode)) AS yCode, wm.d1, ISNULL(wm.ffn, wm.pp) as ffn, wm.ada,
    case
        when wm.mss & 2=2
        then 'false'
        else 'true'
    end AS isa,
    (
        SELECT ', '+RTRIM(p1.cKey)
        FROM profile p1
            inner join loc stl on p1.cKey=stl.cKey
        WHERE p1.id = wm.id and p1.s = 'A'
        FOR XML PATH('')
    ) [lst],
    lishc.[lstCount],
    TotalCount = COUNT(*) OVER(),
    la.lsa, wskp.cKey AS pid
FROM wmm wm
    LEFT JOIN profile p1 ON wm.id = p1.id
    LEFT JOIN (
        SELECT UA.id, CONVERT(datetime, UA.ins, 1) As lsa
        FROM actlog UA
            INNER JOIN (
                select id, max(ins) as laa
                from actlog
                group by id
            ) UAJ on UA.id=UAJ.id and UA.ins=UAJ.laa
    ) la on la.id=wm.id
    LEFT JOIN (
        SELECT id, cKey FROM (
            SELECT *, ROW_NUMBER() OVER (PARTITION BY id ORDER BY d1 desc) AS ROWNUM
            FROM keypro where sc = 'SAP' AND cKeyDesc = 'SAP Agent ID'
        ) x WHERE ROWNUM = 1
    ) wskp ON wskp.id = wm.id
    LEFT JOIN (
        (SELECT p1.id ,COUNT(p1.cKey) AS [lstCount]
        FROM profile p1
            inner join loc stl on p1.cKey=stl.cKey
        where p1.s = 'A'
        GROUP BY p1.id)
    ) lishc ON lishc.id = wm.id
WHERE (@id = 0 OR wm.id = @id)
    AND (@uid IS NULL OR wm.uid LIKE '%' + @uid + '%')
    AND (@c IS NULL OR wm.c LIKE '%' + @c + '%')
    AND (@fn IS NULL OR wm.fn LIKE '%' + @fn + '%')
    AND (@ln IS NULL OR wm.ln LIKE '%' + @ln + '%')
    AND (@em IS NULL OR wm.em LIKE '%' + @em + '%')
    AND (@ffn IS NULL OR (wm.ffn LIKE '%' + @ffn + '%' OR wm.pp LIKE '%' + @ffn + '%'))
    AND (@pid IS NULL OR wskp.cKey LIKE '%' + @pid + '%' )
    AND (@Date1 IS NULL OR (CAST(wm.d1 AS DATE) BETWEEN CAST(@Date1 AS DATE) AND CAST(@Date2 AS DATE)))
    AND (@lsa1 IS NULL OR (CAST(la.lsa AS DATE) BETWEEN CAST(@lsa1 AS DATE) AND CAST(@lsa2 AS DATE)))
    AND (@Active IS NULL OR (wm.mss & 2 != 2))
    AND (@Inactive IS NULL OR (wm.mss & 2 = 2))
    AND (@External IS NULL OR (wm.ada = 'biz'))
    AND (@Internal IS NULL OR (wm.ada <> 'biz'))
    AND (@ApplyyFilter =0  OR (wm.yCode IN (SELECT @yCode WHERE 1 = 0)))
    AND (@ApplylstFilter = 0 OR(p1.cKey IN (SELECT @ShipToList WHERE 1 = 0)))
    AND (@ApplylstFilter = 0 OR(p1.s = 'A'))
    AND (@ApplyNoFilter = 0 OR (lishc.[lstCount] is null))
    AND (@lstCount = 0 OR lishc.[lstCount] = @lstCount)
    AND (@ApplyLimitedFilter = 0 OR (wm.id IN (0)))
    AND (@ApplyMoreFilter = 0 OR (wm.id IN (SELECT @idss WHERE 1 = 0)))
GROUP BY wm.id, wm.uid, wm.em, wm.fn, wm.ln, y, yCode,c,wm.d1,wm.ffn,wm.mss,wm.ada, la.lsa, wskp.cKey, lishc.[lstCount], wm.pp
ORDER BY lsa DESC
OFFSET @PageOffset ROWS FETCH NEXT @PageSize ROWS ONLY

A: The quick hit here is to add OPTION (RECOMPILE) so SQL Server can eliminate the predicates that correspond to null parameters and create a new plan for each search.
And see, generally Dynamic Search Conditions in T‑SQL
The next thing to do is to get rid of the wildcard searches wherever possible.
And transform this
 (CAST(la.lsa AS DATE) BETWEEN CAST(@lsa1 AS DATE) AND CAST(@lsa2 AS DATE)))

into a SARGable pattern like
 la.lsa >= @lsa1 and la.lsa < @lsa2

Then start to pull this query apart, and hand-write separate queries for the most common or critical cases.


text:
Q: Using jQuery with Other Libraries My home page contains:
<script src="js/Config/jquery-1.4.3.min.js"></script>
<script src="js/Config/jquery.mobile-1.0a1.min.js"></script>

then, a button that leads me to another page test.html that contains:
<script type="text/javascript">
    jQuery.noConflict();
    jQuery(document).ready(function()
    {
        getCategories();
        getnameCategories();
    });
</script>
</head>
<body >...

But jQuery(document).ready(function() is not working!!
And if I made just one call to a single library, either jquery.mobile-1.0a1.min.js or jquery-1.4.3.min.js on the home page, the code work well, but I loss the graphic effect of jquery!!!! What is the problem??

A: Your new page test.html should also contain a reference to the jquery-mobile library.
Also, when using jQuery Mobile, use pageInit rather than jQuery's ready(...) function. See the documentation here.

A: I think, you need to check the dependent Jquery libraries of "jquery.mobile-1.0a1.min.js" and need to call that dependent jquery libraries links to your page.
i mean you should call the libraries like,
<script src="js/Config/jquery.mobile.themeswitcher.js"></script>
<script src="js/Config/jqm-docs.js"></script>

A: your jQuery(document).ready(function() won't fire coz when jquery mobile load external pages it looks for  the first page of your document and it don't load the associate scripts specified in the head section.
what you have to do is to load all your java script in your first html page and also put you code in $("#test").live("pageshow",function(){} where test is the id of the first page located in test.html
it should look like this in your .js:
$("#test").live("pageshow",function(){
    jQuery.noConflict();
    getCategories();
    getnameCategories();

}

and like this in test.html:
    <!DOCTYPE html>
<html >
<head>
</head>
<body>
  <div id="test" data-role="page">

 </div>

</body>
</html>


text:
Q: Use Hurwitz theorem to show that the equation $cos(z)=\frac{i}{n} + exp(z/n)$ has a solution in $B(0,\delta)$ Let $\delta>0$. Use Hurwitz theorem to show that the equation $cos(z)=\frac{i}{n} + exp(z/n)$ has a solution in  $B(0,\delta)$ for $n$ large enough.
What I have tried: I have shown that $\frac{i}{n} + exp(z/n)$ converges to 1 uniformly. However, that doesn't help much because this is a constant function. I thought that maybe since $cos(0)=1$ and $cos(z)$ is analytic and would be close to $1$ in $B(0,\delta)$ for small $\delta$ it might be possible to show that $\frac{i}{n} + exp(z/n)$  converges locally uniformly to $cos(z)$. But this seems to be a stretch and I haven't been able to prove the latter formally. I am having trouble getting a useful estimation of $|\frac{i}{n} + exp(z/n)-cos(z)|$ for $n$ large enough.
I would prefer a hint rather than a full answer.
Thank you.

A: Using wikipedia:
$f_{n}(z)=exp(z/n) - cos(z) + \frac {i} {n} $ is holomorphic for every $k \in \mathbb N$ (you can prove that) in sn open conected set, $B(0, \delta)$.
$f_{n}(z)=exp(z/n) - cos(z) + \frac {i} {n} $ converges to $f(z)=1 - cos(z)$ as n aproaches $\infty$. f is holomorfic too.
f(0)=0 of order 2 (you can proof that).
then $\exists \rho , k \in \mathbb N / f_{k}$ has 2 zeros (counting multiplicity) in $B(0, \rho) $ counting multiplicity.


text:
Q: React redux - change property on individual state item I have a reducer with a list of characters. This list gets displayed in another component in the app. However, there is also a separate container that has an SVG illustration of various characters. The individual characters in the illustration have an id attribute that corresponds with the id property in the characters array seen here:
reducers/reduce_characters.js
export default function(state =  null, action) {
    var characters = [
        {
            id: '_x30_1-A-RussellStringerBell',
            name: 'Stringer Bell',
            found: false
        },
        {
            id: '_x31_1-A-JimmyMcNulty',
            name: 'Jimmy McNulty',
            found: false
        }
    ];

    switch(action.type) {
        case 'BOARD_CLICKED':

        // here we will update the found property of the item in characters array with matching ID

    }

    return characters;
}

action.payload equals the id of the element clicked. in the action creator, I want to loop through the characters array and set the found property to true if the id is equal to that of the element clicked (in this case, the value of action.payload)
actions/index.js
export function boardClicked(event) {
    console.log(event.target.id);

    return {
        type: 'BOARD_CLICKED',
        payload: event.target.id
    };
}

I'm very new to React, feel like this shouldn't be that difficult, but want to figure out the best way to do this the React/Redux "way" and update the state accordingly.
Here is my container as well:
containers/board.js
import React, { Component } from 'react';
import SVGInline from "react-svg-inline";
import { connect } from 'react-redux';
import { boardClicked } from '../actions/index';
import { bindActionCreators } from 'redux';

class Board extends Component {
    render() {
        return (
            <div id="board" onClick={(event) => this.props.boardClicked(event)}>
                <SVGInline svg={'<?xml version="1.0" encoding="utf-8"?><svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 2500 2623" style="enable-background:new 0 0 2500 2623;" xml:space="preserve"><image style="overflow:visible;enable-background:new ;" width="2500" height="2624" id="Background_1_" xlink:href="/img/2A6DA3D578C05349.jpeg" transform="matrix(1 0 0 0.9996 0 0.5)"></image><image style="overflow:visible;enable-background:new ;" width="2500" height="1876" id="Illustration" xlink:href="/img/2A6DA3D578C0534B.jpeg" transform="matrix(1 0 0 1 0 185)"></image><image style="overflow:visible;enable-background:new ;" width="122" height="164" id="_x30_1-B-RussellStringerBell" xlink:href="/img/2A6DA3D578C05349.png" transform="matrix(1 0 0 1 728 686)"></image><image style="overflow:visible;enable-background:new ;" width="122" height="164" id="_x30_1-A-RussellStringerBell" xlink:href="/img/2A6DA3D578C0534F.png" transform="matrix(1 0 0 1 728 686)"></image><image style="overflow:visible;enable-background:new ;" width="102" height="144" id="_x30_2-B-Kenard" xlink:href="/img/2A6DA3D578C0534A.png" transform="matrix(1 0 0 1 1322 869)"></image><image style="overflow:visible;enable-background:new ;" width="102" height="151" id="_x30_2-A-Kenard" xlink:href="/img/2A6DA3D578C0534B.png" transform="matrix(1 0 0 1 1322 862)"></image><image style="overflow:visible;enable-background:new ;" width="86" height="144" id="_x30_3-B-MarloStanfield" xlink:href="/img/2A6DA3D578C05346.png" transform="matrix(1 0 0 1 570 1274)"></image><image style="overflow:visible;enable-background:new ;" width="86" height="144" id="_x30_3-A-MarloStanfield" xlink:href="/img/2A6DA3D578C05347.png" transform="matrix(1 0 0 1 570 1274)"></image><image style="overflow:visible;enable-background:new ;" width="79" height="132" id="_x30_4-B-CalvinCheeseWagstaff" xlink:href="/img/2A6DA3D578C05359.png" transform="matrix(1 0 0 1 2 1556)"></image><image style="overflow:visible;enable-background:new ;" width="79" height="132" id="_x30_4-A-CalvinCheeseWagstaff" xlink:href="/img/21D8ADDA73CC0992.png" transform="matrix(1 0 0 1 2 1556)"></image><image style="overflow:visible;enable-background:new ;" width="138" height="207" id="_x30_5-B-MauriceLevy" xlink:href="/img/21D8ADDA73CC0995.png" transform="matrix(1 0 0 1 600 1695)"></image><image style="overflow:visible;enable-background:new ;" width="138" height="207" id="_x30_5-A-MauriceLevy" xlink:href="/img/21D8ADDA73CC0996.png" transform="matrix(1 0 0 1 600 1695)"></image><image style="overflow:visible;enable-background:new ;" width="100" height="165" id="_x30_6-B-SpirosVondasVondopoulos" xlink:href="/img/21D8ADDA73CC0994.png" transform="matrix(1 0 0 1 289 1394)"></image><image style="overflow:visible;enable-background:new ;" width="100" height="165" id="_x30_6-A-SpirosVondasVondopoulos" xlink:href="/img/21D8ADDA73CC0993.png" transform="matrix(1 0 0 1 289 1394)"></image><image style="overflow:visible;enable-background:new ;" width="118" height="195" id="_x30_7-B-The_Greek" xlink:href="/img/21D8ADDA73CC098D.png" transform="matrix(1 0 0 1 192 1373)"></image><image style="overflow:visible;enable-background:new ;" width="118" height="195" id="_x30_7-A-The_Greek" xlink:href="/img/21D8ADDA73CC098E.png" transform="matrix(1 0 0 1 192 1373)"></image><image style="overflow:visible;enable-background:new ;" width="171" height="180" id="_x30_8-B-PropositionJoe" xlink:href="/img/21D8ADDA73CC098C.png" transform="matrix(1 0 0 1 527 565)"></image><image style="overflow:visible;enable-background:new ;" width="174" height="181" id="_x30_8-A-PropositionJoe" xlink:href="/img/21D8ADDA73CC09B2.png" transform="matrix(1 0 0 1 527 564)"></image><image style="overflow:visible;enable-background:new ;" width="140" height="161" id="_x30_9-B-BriannaBarksdale" xlink:href="/img/21D8ADDA73CC09B5.png" transform="matrix(1 0 0 1 1142 605)"></image><image style="overflow:visible;enable-background:new ;" width="149" height="175" id="_x30_9-A-BriannaBarksdale" xlink:href="/img/21D8ADDA73CC09A9.png" transform="matrix(1 0 0 1 1133 591)"></image><image style="overflow:visible;enable-background:new ;" width="126" height="186" id="_x31_0-B-DeLondaBrice" xlink:href="/img/21D8ADDA73CC09AB.png" transform="matrix(1 0 0 1 253 1243)"></image><image style="overflow:visible;enable-background:new ;" width="126" height="186" id="_x31_0-A-DeLondaBrice" xlink:href="/img/21D8ADDA73CC09A8.png" transform="matrix(1 0 0 1 253 1243)"></image><image style="overflow:visible;enable-background:new ;" width="186" height="376" id="_x31_1-B-JayLandsman" xlink:href="/img/21D8ADDA73CC09D7.png" transform="matrix(1 0 0 1 1989 915)"></image><image style="overflow:visible;enable-background:new ;" width="186" height="376" id="_x31_1-A-JayLandsman" xlink:href="/img/21D8ADDA73CC09D9.png" transform="matrix(1 0 0 1 1989 915)"></image><image style="overflow:visible;enable-background:new ;" width="109" height="247" id="_x31_2-B-AvonBarksdale" xlink:href="/img/21D8ADDA73CC09DB.png" transform="matrix(1 0 0 1 450 1338)"></image><image style="overflow:visible;enable-background:new ;" width="109" height="247" id="_x31_2-A-AvonBarksdale" xlink:href="/img/21D8ADDA73CC09D8.png" transform="matrix(1 0 0 1 450 1338)"></image><image style="overflow:visible;enable-background:new ;" width="125" height="190" id="_x31_3-B-BeadieRussell" xlink:href="/img/21D8ADDA73CC09DF.png" transform="matrix(1 0 0 1 1583 1673)"></image><image style="overflow:visible;enable-background:new ;" width="133" height="197" id="_x31_3-A-BeadieRussell" xlink:href="/img/21D8ADDA73CC09DA.png" transform="matrix(1 0 0 1 1575 1666)"></image><image style="overflow:visible;enable-background:new ;" width="139" height="350" id="_x31_4-B-WilliamRawls" xlink:href="/img/21D8ADDA73CC09E6.png" transform="matrix(1 0 0 1 1694 1597)"></image><image style="overflow:visible;enable-background:new ;" width="139" height="351" id="_x31_4-A-WilliamRawls" xlink:href="/img/21D8ADDA73CC09FC.png" transform="matrix(1 0 0 1 1694 1596)"></image><image style="overflow:visible;enable-background:new ;" width="99" height="194" id="_x31_5-B-NickSobotka" xlink:href="/img/21D8ADDA73CC09C3.png" transform="matrix(1 0 0 1 315 1867)"></image><image style="overflow:visible;enable-background:new ;" width="99" height="194" id="_x31_5-A-NickSobotka" xlink:href="/img/21D8ADDA73CC09C4.png" transform="matrix(1 0 0 1 315 1867)"></image><image style="overflow:visible;enable-background:new ;" width="120" height="309" id="_x31_6-B-ClarenceRoyce" xlink:href="/img/21D8ADDA73CC09C7.png" transform="matrix(1 0 0 1 1185 1736)"></image><image style="overflow:visible;enable-background:new ;" width="120" height="324" id="_x31_6-A-ClarenceRoyce" xlink:href="/img/21D8ADDA73CC09C5.png" transform="matrix(1 0 0 1 1185 1721)"></image><image style="overflow:visible;enable-background:new ;" width="152" height="217" id="_x31_7-B-TommyCarcetti" xlink:href="/img/21D8ADDA73CC09C2.png" transform="matrix(1 0 0 1 2217 1844)"></image><image style="overflow:visible;enable-background:new ;" width="154" height="219" id="_x31_7-A-TommyCarcetti" xlink:href="/img/21D8ADDA73CC09CC.png" transform="matrix(1 0 0 1 2215 1842)"></image><image style="overflow:visible;enable-background:new ;" width="125" height="152" id="_x31_8-B-ThomasKlebanow" xlink:href="/img/21D8ADDA73CC09CF.png" transform="matrix(1 0 0 1 1917 1909)"></image><image style="overflow:visible;enable-background:new ;" width="127" height="153" id="_x31_8-A-ThomasKlebanow" xlink:href="/img/21D8ADDA73CC09CD.png" transform="matrix(1 0 0 1 1917 1908)"></image><image style="overflow:visible;enable-background:new ;" width="137" height="153" id="_x31_9_x5F_B-ScottTempleton" xlink:href="/img/21D8ADDA73CC09C1.png" transform="matrix(1 0 0 1 1823 1908)"></image><image style="overflow:visible;enable-background:new ;" width="137" height="153" id="_x31_9_x5F_A-ScottTempleton" xlink:href="/img/21D8ADDA73CC0A2F.png" transform="matrix(1 0 0 1 1823 1908)"></image><image style="overflow:visible;enable-background:new ;" width="108" height="193" id="_x32_0-B-ClayDavis" xlink:href="/img/21D8ADDA73CC0A21.png" transform="matrix(1 0 0 1 1589 553)"></image><image style="overflow:visible;enable-background:new ;" width="108" height="193" id="_x32_0-A-ClayDavis" xlink:href="/img/21D8ADDA73CC0A23.png" transform="matrix(1 0 0 1 1589 553)"></image><image style="overflow:visible;enable-background:new ;" width="115" height="236" id="_x32_1-B-ChrisPartlow" xlink:href="/img/21D8ADDA73CC0A26.png" transform="matrix(1 0 0 1 413 1070)"></image><image style="overflow:visible;enable-background:new ;" width="115" height="236" id="_x32_1-A-ChrisPartlow" xlink:href="/img/21D8ADDA73CC0A27.png" transform="matrix(1 0 0 1 413 1070)"></image><image style="overflow:visible;enable-background:new ;" width="106" height="145" id="_x32_2-B-SnoopPearson" xlink:href="/img/21D8ADDA73CC0A22.png" transform="matrix(1 0 0 1 2015 462)"></image><image style="overflow:visible;enable-background:new ;" width="106" height="145" id="_x32_2-A-SnoopPearson" xlink:href="/img/21D8ADDA73CC0A3D.png" transform="matrix(1 0 0 1 2015 462)"></image><image style="overflow:visible;enable-background:new ;" width="66" height="107" id="_x32_3-B-RolandPryzbylewski" xlink:href="/img/21D8ADDA73CC0A3E.png" transform="matrix(1 0 0 1 158 1660)"></image><image style="overflow:visible;enable-background:new ;" width="66" height="107" id="_x32_3-A-RolandPryzbylewski" xlink:href="/img/21D8ADDA73CC0A3F.png" transform="matrix(1 0 0 1 158 1660)"></image><image style="overflow:visible;enable-background:new ;" width="125" height="199" id="_x32_4-B-BodieBroadus" xlink:href="/img/21D8ADDA73CC0A24.png" transform="matrix(1 0 0 1 892 1331)"></image><image style="overflow:visible;enable-background:new ;" width="125" height="199" id="_x32_4-A-BodieBroadus" xlink:href="/img/21D8ADDA73CC0A1E.png" transform="matrix(1 0 0 1 892 1331)"></image><image style="overflow:visible;enable-background:new ;" width="67" height="140" id="_x32_5-B-Wallace" xlink:href="/img/21D8ADDA73CC0A19.png" transform="matrix(1 0 0 1 1371 663)"></image><image style="overflow:visible;enable-background:new ;" width="67" height="140" id="_x32_5-A-Wallace" xlink:href="/img/21D8ADDA73CC0A1A.png" transform="matrix(1 0 0 1 1371 663)"></image><image style="overflow:visible;enable-background:new ;" width="171" height="248" id="_x32_6-B-WilliamBunkMoreland" xlink:href="/img/21D8ADDA73CC0A18.png" transform="matrix(1 0 0 1 1951 1698)"></image><image style="overflow:visible;enable-background:new ;" width="171" height="248" id="_x32_6-A-WilliamBunkMoreland" xlink:href="/img/21D8ADDA73CC0A06.png" transform="matrix(1 0 0 1 1951 1698)"></image><image style="overflow:visible;enable-background:new ;" width="120" height="292" id="_x32_7-B-DukieWeems" xlink:href="/img/21D8ADDA73CC0A09.png" transform="matrix(1 0 0 1 1482 1174)"></image><image style="overflow:visible;enable-background:new ;" width="120" height="292" id="_x32_7-A-DukieWeems" xlink:href="/img/21D8ADDA73CC0A0A.png" transform="matrix(1 0 0 1 1482 1174)"></image><image style="overflow:visible;enable-background:new ;" width="106" height="291" id="_x32_8-B-RandyWagstaff" xlink:href="/img/21D8ADDA73CC0A08.png" transform="matrix(1 0 0 1 1424 1109)"></image><image style="overflow:visible;enable-background:new ;" width="106" height="291" id="_x32_8-A-RandyWagstaff" xlink:href="/img/21D8ADDA73CC0A0E.png" transform="matrix(1 0 0 1 1424 1109)"></image><image style="overflow:visible;enable-background:new ;" width="129" height="246" id="_x32_9-B-MichaelLee" xlink:href="/img/21D8ADDA73CC0A0B.png" transform="matrix(1 0 0 1 1281 1129)"></image><image style="overflow:visible;enable-background:new ;" width="129" height="246" id="_x32_9-A-MichaelLee" xlink:href="/img/21D8ADDA73CC0A6D.png" transform="matrix(1 0 0 1 1281 1129)"></image><image style="overflow:visible;enable-background:new ;" width="115" height="223" id="_x33_0-B-NamondBrice" xlink:href="/img/21D8ADDA73CC0A6F.png" transform="matrix(1 0 0 1 1342 1098)"></image><image style="overflow:visible;enable-background:new ;" width="115" height="223" id="_x33_0-A-NamondBrice" xlink:href="/img/21D8ADDA73CC0A6C.png" transform="matrix(1 0 0 1 1342 1098)"></image><image style="overflow:visible;enable-background:new ;" width="97" height="248" id="_x33_1-B-FrankSobotka" xlink:href="/img/21D8ADDA73CC0A6B.png" transform="matrix(1 0 0 1 1789 483)"></image><image style="overflow:visible;enable-background:new ;" width="97" height="248" id="_x33_1-A-FrankSobotka" xlink:href="/img/21D8ADDA73CC0A15.png" transform="matrix(1 0 0 1 1789 483)"></image><image style="overflow:visible;enable-background:new ;" width="90" height="248" id="_x33_2-B-RhondaPearlman" xlink:href="/img/21D8ADDA73CC0A17.png" transform="matrix(1 0 0 1 1955 296)"></image><image style="overflow:visible;enable-background:new ;" width="90" height="248" id="_x33_2-A-RhondaPearlman" xlink:href="/img/21D8ADDA73CC0A14.png" transform="matrix(1 0 0 1 1955 296)"></image><image style="overflow:visible;enable-background:new ;" width="117" height="159" id="_x33_3-B-EllisCarver" xlink:href="/img/21D8ADDA73CC0A1B.png" transform="matrix(1 0 0 1 1963 1291)"></image><image style="overflow:visible;enable-background:new ;" width="117" height="159" id="_x33_3-A-EllisCarver" xlink:href="/img/21D8ADDA73CC0A1D.png" transform="matrix(1 0 0 1 1963 1291)"></image><image style="overflow:visible;enable-background:new ;" width="111" height="192" id="_x33_4-B-ThomasHercHauk" xlink:href="/img/21D8ADDA73CC0A1F.png" transform="matrix(1 0 0 1 1875 1274)"></image><image style="overflow:visible;enable-background:new ;" width="111" height="192" id="_x33_4-A-ThomasHercHauk" xlink:href="/img/21D8ADDA73CC0A30.png" transform="matrix(1 0 0 1 1875 1274)"></image><image style="overflow:visible;enable-background:new ;" width="118" height="154" id="_x33_5-B-AugustusHaynes" xlink:href="/img/21D8ADDA73CC0A3C.png" transform="matrix(1 0 0 1 2119 1604)"></image><image style="overflow:visible;enable-background:new ;" width="118" height="154" id="_x33_5-A-AugustusHaynes" xlink:href="/img/21D8ADDA73CC0A31.png" transform="matrix(1 0 0 1 2119 1604)"></image><image style="overflow:visible;enable-background:new ;" width="120" height="184" id="_x33_6-B-LesterFreamon" xlink:href="/img/21D8ADDA73CC0A33.png" transform="matrix(1 0 0 1 1658 567)"></image><image style="overflow:visible;enable-background:new ;" width="120" height="184" id="_x33_6-A-LesterFreamon" xlink:href="/img/21D8ADDA73CC0A36.png" transform="matrix(1 0 0 1 1658 567)"></image><image style="overflow:visible;enable-background:new ;" width="136" height="200" id="_x33_7-B-CedricDaniels" xlink:href="/img/21D8ADDA73CC0A37.png" transform="matrix(1 0 0 1 2262 1523)"></image><image style="overflow:visible;enable-background:new ;" width="136" height="200" id="_x33_7-A-CedricDaniels" xlink:href="/img/21D8ADDA73CC0A32.png" transform="matrix(1 0 0 1 2262 1523)"></image><image style="overflow:visible;enable-background:new ;" width="129" height="202" id="_x33_8-B-SlimCharles" xlink:href="/img/21D8ADDA73CC0A2D.png" transform="matrix(1 0 0 1 1921 1058)"></image><image style="overflow:visible;enable-background:new ;" width="129" height="202" id="_x33_8-A-SlimCharles" xlink:href="/img/21D8ADDA73CC0A2E.png" transform="matrix(1 0 0 1 1921 1058)"></image><image style="overflow:visible;enable-background:new ;" width="133" height="159" id="_x33_9-B-HowardBunnyColvin" xlink:href="/img/21D8ADDA73CC0A2C.png" transform="matrix(1 0 0 1 1050 1902)"></image><image style="overflow:visible;enable-background:new ;" width="133" height="159" id="_x33_9-A-HowardBunnyColvin" xlink:href="/img/21D8ADDA73CC0ACB.png" transform="matrix(1 0 0 1 1050 1902)"></image><image style="overflow:visible;enable-background:new ;" width="194" height="280" id="_x34_0-B-D_x27_AngeloBarksdale" xlink:href="/img/21D8ADDA73CC0ACD.png" transform="matrix(1 0 0 1 815 742)"></image><image style="overflow:visible;enable-background:new ;" width="194" height="280" id="_x34_0-A-D_x27_AngeloBarksdale" xlink:href="/img/21D8ADDA73CC0ACF.png" transform="matrix(1 0 0 1 815 742)"></image><image style="overflow:visible;enable-background:new ;" width="126" height="330" id="_x34_1-B-RolandWee-BayBrice" xlink:href="/img/21D8ADDA73CC0ACA.png" transform="matrix(1 0 0 1 606 1016)"></image><image style="overflow:visible;enable-background:new ;" width="126" height="330" id="_x34_1-A-RolandWee-BayBrice" xlink:href="/img/21D8ADDA73CC0AC9.png" transform="matrix(1 0 0 1 606 1016)"></image><image style="overflow:visible;enable-background:new ;" width="129" height="211" id="_x34_2-B-DennisCuttyWise" xlink:href="/img/21D8ADDA73CC0AF5.png" transform="matrix(1 0 0 1 1028 430)"></image><image style="overflow:visible;enable-background:new ;" width="129" height="211" id="_x34_2-A-DennisCuttyWise" xlink:href="/img/21D8ADDA73CC0AF7.png" transform="matrix(1 0 0 1 1028 430)"></image><image style="overflow:visible;enable-background:new ;" width="120" height="264" id="_x34_3-B-KimaGreggs" xlink:href="/img/21D8ADDA73CC0AFA.png" transform="matrix(1 0 0 1 1974 728)"></image><image style="overflow:visible;enable-background:new ;" width="120" height="264" id="_x34_3-A-KimaGreggs" xlink:href="/img/21D8ADDA73CC0AFB.png" transform="matrix(1 0 0 1 1974 728)"></image><image style="overflow:visible;enable-background:new ;" width="122" height="161" id="_x34_4-B-ReginaldBubblesCousins" xlink:href="/img/21D8ADDA73CC0AFD.png" transform="matrix(1 0 0 1 10 1785)"></image><image style="overflow:visible;enable-background:new ;" width="122" height="161" id="_x34_4-A-ReginaldBubblesCousins" xlink:href="/img/21D8ADDA73CC0A9A.png" transform="matrix(1 0 0 1 10 1785)"></image><image style="overflow:visible;enable-background:new ;" width="122" height="365" id="_x34_5-B-BrotherMouzone" xlink:href="/img/21D8ADDA73CC0A9D.png" transform="matrix(1 0 0 1 1602 1019)"></image><image style="overflow:visible;enable-background:new ;" width="122" height="365" id="_x34_5-A-BrotherMouzone" xlink:href="/img/21D8ADDA73CC0A9E.png" transform="matrix(1 0 0 1 1602 1019)"></image><image style="overflow:visible;enable-background:new ;" width="144" height="283" id="_x34_6-B-JimmyMcNulty" xlink:href="/img/21D8ADDA73CC0A9C.png" transform="matrix(1 0 0 1 910 715)"></image><image style="overflow:visible;enable-background:new ;" width="144" height="283" id="_x34_6-A-JimmyMcNulty" xlink:href="/img/21D8ADDA73CC0A9B.png" transform="matrix(1 0 0 1 910 715)"></image><image style="overflow:visible;enable-background:new ;" width="126" height="185" id="_x34_7-B-OmarLittle" xlink:href="/img/21D8ADDA73CC0AA5.png" transform="matrix(1 0 0 1 1289 1291)"></image><image style="overflow:visible;enable-background:new ;" width="126" height="185" id="_x34_7-A-OmarLittle" xlink:href="/img/21D8ADDA73CC0AA6.png" transform="matrix(1 0 0 1 1289 1291)"></image></svg>'} />
            </div>
        );
    }

    componentDidMount() {
        this.props.characters.map((character) => {
            if(character.found === true) {
                document.getElementById(character.id).style.display = 'none';
            }
        });
    }
}

function mapStateToProps(state) {
    return {
        characters: state.characters
    };
}

function mapDispatchToProps(dispatch) {
    // Whenever selectCharacter is called, the result should be passed to all reducers
    return bindActionCreators({ boardClicked: boardClicked }, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(Board);

A: Okay, you're right, this isn't too hard to do in React/Redux. Are your initial characters always the same? You can look at passing them into your store as an initalState parameter, but in the meantime, I would pull them out of my reducer and pass them in like so:
const characters = [
        {
            id: '_x30_1-A-RussellStringerBell',
            name: 'Stringer Bell',
            found: false
        },
        {
            id: '_x31_1-A-JimmyMcNulty',
            name: 'Jimmy McNulty',
            found: false
        }
    ];

export default charactersReducer(state = characters, action) {

  switch(action.type) {
    case 'BOARD_CLICKED':
      return state.map((character) => {  // map over the characters, returning a new array
        if (character.id === action.id) { // if character id matches action id, change that character
          return {
            ... character, // this uses the proposed object destructuring, make sure your babel lets you use it
            found: !character.found // this toggles the view, but you could just set it to true
          }
        } else { // if the id doesn't match, return the original character
          return character
        }
      });

    }
    default:
      return state; // return the state, not the characters on default
  }
}


text:
Q: Why base current changes with collector emitter voltage? There are two questions in stack exchange similar to mine, but I though mine was more basic and also more specific.
I tried doing some SPICE simulations in order to understand transistor characteristics described here, but using a real transistor, i.e., 2N2222. I tried two circuits as shown below. As you can see, both circuits are very similar with Vbe, Vcc being exactly the same between the two. The only difference is that the one on the right has 100 ohms more between Vcc and the collector. I expected Ib to have the same waveform between the two circuits - but when I saw the simulated waveform, Ib on the right circuit (blue color) seems to different from the Ib of the left circuit (green hiding behind the blue signal for the most part). The red signal is the Vce of the left circuit and the blue green signal is the Vce of the right circuit.
What I have read in many books, literature online (including the one I have referred here), is that Vce has no effect on Ib. And yet, my observation is different! Can anyone kindly explain this strange behavior of Ib? Many thanks in advance.

A: When you saturate Vce (down near zero), the transistor's current gain drops greatly. So the base-emitter junction becomes "just a diode". Green curve hasn't quite reached Vce saturation. Blue curve ventures into saturation.
Perhaps you are trying to investigate the "early effect" as G36 has suggested. This effect addresses a linearly-operating transistor. While your circuit is driving this transistor hard, the green-curve drive is at the very upper edge of linearity. The blue-curve drive is over the edge of linearity.


text:
Q: MySQL's AUTO_INCREMENT behavior in a multiple row insert I think the answer to my question is obvious but since I could not find any documentation to support it, I thought it's worth asking. At least for the record.
As we all know AUTO_INCREMENT fields are incremented each time an INSERT statement is executed. And its value can be retrieved by LAST_INSERT_ID() function. It is also mentioned in MySQL's Manual that with multiple-row inserts, LAST_INSERT_ID() will return the first ID of the  inserted rows. Which I think is a good idea (really useful).
So here goes my question:
Can I assume in an INSERT IGNORE INTO statement with multiple-rows, the inserted IDs of an AUTO_INCREMENT field will always be sequential? Keep in mind that due to IGNORE modifier and the multi-user nature of MySQL server, different scenarios might happen.
Thanks.

A: No you can not assume that. One scenario where ID's would not be sequential is in replicated multi-master setup. If for example two servers exist in such setup, one will only generate even auto IDs, and the other only odd IDs (keep in mind it's just an example).
However if your setup is not something like that, then yes. At least in InnoDB inserts are atomic and are queued when targetting same table, so ID's from two different INSERT's will not interlace. (it's not documented though, so relying on it is... a bit risky)

How I tested IGNORE INSERT ID generation:
mysql> CREATE TABLE  `ignoreinsert` (
    ->   `ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
    ->   `uq` int(10) unsigned NOT NULL,
    ->   PRIMARY KEY (`ID`),
    ->   UNIQUE KEY `uq` (`uq`)
    -> ) ENGINE=InnoDB;
Query OK, 0 rows affected (0.19 sec)

mysql> INSERT INTO ignoreinsert VALUES (null,1),(null,2);
Query OK, 2 rows affected (0.10 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> SELECT * FROM ignoreinsert;
+----+----+
| ID | uq |
+----+----+
|  1 |  1 |
|  2 |  2 |
+----+----+
2 rows in set (0.00 sec)

mysql> INSERT IGNORE INTO ignoreinsert VALUES (null,3),(null,1),(null,4),(null,2),(null,5);
Query OK, 3 rows affected (0.08 sec)
Records: 5  Duplicates: 2  Warnings: 0

mysql> SELECT * FROM ignoreinsert;
+----+----+
| ID | uq |
+----+----+
|  1 |  1 |
|  2 |  2 |
|  3 |  3 |
|  4 |  4 |
|  5 |  5 |
+----+----+
5 rows in set (0.00 sec)


text:
Q: Printing to a Thermal Receipt Printer using PHP I have the following code that was supposed to make it able to print something to a thermal receipt printer.
if ($_GET['action'] == 'print')
{
    $printer = "\\\\localhost\\zebra";

    // Open connection to the thermal printer
    $fp = fopen($printer, "w");
    if (!$fp){
      die('no connection');
    }

    $data = " PRINT THIS ";

    // Cut Paper
    $data .= "\x00\x1Bi\x00";

    if (!fwrite($fp,$data)){
      die('writing failed');
    }

}

Although, when I run it nothing happens along with no errors. How does one print from PHP?

A: try this ...
<?php
if ($_GET['action'] == 'print')
{
$printer = "\\\\localhost\\zebra";
if($ph = printer_open($printer))
{
   $data = " PRINT THIS ";
   // Cut Paper
   $data .= "\x00\x1Bi\x00";
   printer_write($ph, $data);
   printer_close($ph);
}
else die('writing failed');
}
?>


text:
Q: need to route the traffic through a specific network card I have two network cards and they both have a different network. I need the outgoing connections to go only through a specific network card. Any help ?
Update:
I ran a route -n command and got this OP
  Kernel IP routing table
  Destination  Gateway        Genmask        Flags Metric Ref Use Iface
  0.0.0.0      192.168.1.100  0.0.0.0        UG    0      0   0   eth1
  169.254.0.0  0.0.0.0        255.255.0.0    U     1000   0   0   eth0
  192.168.1.0  0.0.0.0        255.255.255.0  U     1      0   0   eth1
  192.168.3.0  0.0.0.0        255.255.255.0  U     1      0   0   eth0

A: All your Internet traffic will go out through eth1 as that is connected to your router.
If you want to route traffic via eth0 and have a router on that subnet (192.168.3.nnn), you can change the default route accordingly. See man route
 route del default
 route add default gw 192.168.3.254

A: Your /etc/network/interfaces file looks something like this:
auto eth0 eth1
iface eth0 inet static
        address 192.168.1.x
        netmask 255.255.255.0
        gateway 192.168.1.100

iface eth1 inet static
        address 192.168.3.x
        netmask 255.255.255.0

The gateway directive lets the system know where connections should go out.  You want to change it to the other interface, with the router IP that is there:
auto eth0 eth1
iface eth0 inet static
        address 192.168.1.x
        netmask 255.255.255.0

iface eth1 inet static
        address 192.168.3.x
        netmask 255.255.255.0
        gateway 192.168.3.1


text:
Q: How can I set the frequency of a pandas index? So this is my code basically:
df = pd.read_csv('XBT_60.csv', index_col = 'date', parse_dates = True)
df.index.freq = 'H'

I load a csv, set the index to the date column and want to set the frequency to 'H'. But this raises this error:
ValueError: Inferred frequency None from passed values does not conform to passed frequency H

The format of the dates column is: 2017-01-01 00:00:00
I already tried loading the csv without setting the index column and used pd.to_datetime on the dates column before I set it as index, but still i am unable to set the frequency. How can I solve this?
BTW: my aim is to use the seasonal_decompose() method from statsmodels, so I need the frequency there.

A: You can't set frequency if you have missing index values:
>>> df
            val
2019-09-15    0
2019-09-16    1
2019-09-18    3

>>> df.index.freq = 'D'
...
ValueError: Inferred frequency None from passed values does not conform to passed frequency D

To find missing index, use:
>>> df = df.resample('D').first()
            val
2019-09-15  0.0
2019-09-16  1.0
2019-09-17  NaN
2019-09-18  3.0

>>> df.index.freq
<Day>

To debug, find missing indexes:
>>> pd.date_range(df.index.min(), df.index.max(), freq='D').difference(df.index)
DatetimeIndex(['2019-09-17'], dtype='datetime64[ns]', freq=None)


text:
Q: Messenger API Attachment using PHP Curl (Upload from File) Hi guys I'm getting trouble uploading attachment in facebook messenger API
https://developers.facebook.com/docs/messenger-platform/reference/attachment-upload-api/
I'm using php code but I tried all possible action to upload but my code didn't work every time I send a post request I received this error

"message":"(#100) Incorrect number of files uploaded. Must upload
exactly one file.","type":"OAuthException","code":100"

I tried this curl pattern from the documentation
curl  \
  -F 'message={"attachment":{"type":"image", "payload":{"is_reusable":true}}}' \
  -F 'filedata=@/tmp/shirt.png;type=image/png' \
  "https://graph.facebook.com/v12.0/me/message_attachments?access_token=<PAGE_ACCESS_TOKEN>"

and here's my code PHP code
function uploadFromFile($psid,$file) {
        $reply_message['message']['attachment'] = array(
            'type' => 'image',
            'payload' => array(
                'is_reusable' => true
            )
     );

    $reply_message['filedata'] = "@".$file['tmp_name].";type=image/png";

    $url = "https://graph.facebook.com/v12.0/me/message_attachments?access_token=" . $this->accessToken;
    $ch = curl_init();
    $headers = array("Content-type: application/json");
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
    curl_setopt($ch,CURLOPT_POST,1);
    curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode($reply_message));
    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,$false);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    $st = curl_exec($ch);
    curl_close($ch);
    file_put_contents("errormessage-api.txt",$st);
    $result = json_decode($st,TRUE);
    $this->send($psid,$result['attachment_id']);
    return $result['attachment_id'];
}

I know the error is on my payload I don't know the right syntax. Thank you guys!


text:
Q: Fetch specific values from string I have following string
var a = "{gallery: 'gal', smallimage: '/uploads/photo/image/3256/big_1303-1.jpg', largeimage: '/uploads/photo/image/3256/zoom_1303-1.jpg'}";

What is the best way to fetch largeimage value which is "/uploads/photo/image/3256/zoom_1303-1.jpg"
Let me tell you guyz currently i am using this.(which is very basic)
var a = "{gallery: 'gal', smallimage: '/uploads/photo/image/3256/big_1303-1.jpg', largeimage: '/uploads/photo/image/3256/zoom_1303-1.jpg'}";
var b = a.split('largeimage:')[1].split("'")[1];

A: Have only this idea.
var a = "{gallery: 'gal', smallimage: '/uploads/photo/image/3256/big_1303-1.jpg', largeimage: '/uploads/photo/image/3256/zoom_1303-1.jpg'}";

var b = a.split(',');

var c = b[2].split("'");

var img = c[1];

console.log(img););     // "/uploads/photo/image/3256/zoom_1303-1.jpg"

JSFIDDLE.

A: You have two choice here:

*

*Make your string a valid JSON - to do this you will need to wrap gallery, largeimage, smallimage with apostrophe.
so it would look like this:
var validJSONstring = '{"gallery": "gal", "smallimage": "/uploads/photo/image/3256/big_1303-1.jpg", "largeimage": "/uploads/photo/image/3256/zoom_1303-1.jpg"}';

var validJSONObject = JSON.parse(validJSONstring);
console.log(validJSONObject.largeimage);

Then you have to parse it to JSON and get the property name.

*Split the string where separator sign is "," comma, loop through results and split each result when separator sign is ":" and check for the property you are looking for.

A: Here's a rough implementation of parsing a valid JS object. It doesn't support nested objects, but for the sample string it will work correctly.
function parseObject(objString) {
    var obj = {},
        parts,
        part,
        splitPart;

    // Remove leading and trailing {}s
    objString = objString.trim().replace(/^{|}$/g, '');
    parts = objString.split(','); // split properties into an array

    for (part in parts) {
        splitPart = parts[part].split(':'); // split key/value

        // .join for values containing ':', then the regex removes leading and trailing quotes and spaces
        obj[ splitPart[0] ] = splitPart.slice(1).join(':').replace(/^\s*['|"]\s*|\s*['|"]\s*$/g, '');
    }

    return obj;
}

A: var a = "{gallery: 'gal', smallimage: '/uploads/photo/image/3256/big_1303-1.jpg', largeimage: '/uploads/photo/image/3256/zoom_1303-1.jpg'}";

var jsontemp = a.replace((/([\w]+)(:)/g), "\"$1\"$2");
var correctjson = jsontemp.replace((/'/g), "\"");
var obj = JSON.parse(correctjson);
var c = obj.largeimage;

JSFiddle
For turning into valid json, I used the solution from this post: https://stackoverflow.com/a/24462870/888177


text:
Q: disc access really slow It has been over a year me using my machine (a laptop), and these days disk access has become really slow.

*

*I am using Windows Vista Home Premium.

*The disc fragmentation (checked using Defraggler) is only 9%.

*Also, there is plenty of space free left in the partition. So, that is not a problem either.

What can the problem be and what should I do to get the fast accesses back?

A: Defrag. ASAP.  9% doesn't sound like much, but for Windows that's a lot.  This will make it "better" but may not "cure" the problem.
Next step (assuming you're not satisfied with result of defrag) is to upgrade to Windows 7.
Yes, it's that much better.  Vista falls into the same category as Windows ME.  It was released before it was ready (my personal opinion). Unlike Vista, Win7 is actually pretty good.  Stable. Reasonably fast. Lower/better resource usage compared to Vista.  Whether it's worth the $150 to upgrade is up to you, but I thought it was worth the money.
Hotei

A: Here's two possible causes:

*

*Too much disk access from some programs you may not know are there (malware, rootkits, etc.)
or

*Your disk is getting old and it is starting to run into errors, bad sectors, etc.  Run a disk integrity check and make sure that the physical hardware is fine.  You shouldn't hear any clicks, clunks, pops, etc. coming from the drive itself.  Such noises is commonly an indication of a drive failure which is about to happen.

A: If this didn't happen before and the disk seems very busy and slow lately, then it could be a virus/spyware or a newly installed software that keeps the drive busy. Maybe an update on a program you're using introduced new features that change the way it accesses the drive. It could be an antivirus/antispyware software you are using keeping the drive busy more than they should. You could try the new Soluto software to scan the boot process and maybe spot a slow program.


text:
Q: singular or plural : doctor's bills? Should I use "doctor's bills" or "doctors' bills" in the following?

All the money went on doctor's bills.

I'd appreciate your help.

A: There are four scenarios, where three and four are semantically equivalent:

*

*All my money went to a doctor's bills. [one doctor, many bills from  him]

*All my money went to a doctor's bill. [one doctor sending an expensive bill]

*All my money went to doctors' bills. [generic]

*All my money went to doctor bills. [generic]

Nota bene: If there is one doctor and many bills, the determiner "a" must be used, as in Line One.
The last one is the use of a noun as adjective. Sentence three and four can express the idea of more than one doctor and more than one bill.
You can use went on, but I prefer went to.


text:
Q: Nginx self-signed certificate Here's my question, If I want to transport the self-signed certificate from another server to the Nginx server, do I have to choose the public certificate or the encrypted one with a key?
I mean when I export the certificate there was 2 options
1- key pair < after I enter the key then it's looks like this self-signed_cert.p12
2- public certificate < no key to enter and looks like this self-signed_cert.crt
Which one is the correct one to use? I tried both and I got this error
failed (SSL: error:0909006C:PEM routines:get_name:no start line:Expecting: TRUSTED CERTIFICATE)

I edit the second one .crt to look like this
-----BEGIN TRUSTED CERTIFICATE-----
         cert
-----END TRUSTED CERTIFICATE-----

The one that ends with .p12 looks so different to me so I didn't change anything
And the second question, if the public certificate was exported without entering any key then how can I create the file .key?
I tried to use the self.signed.p12 certificate with key TEST the I used
openssl genrsa -des3 -out self.signed.key 2048

And enter TEST
But didn't work with me


text:
Q: ReferenceError when using 'let' to declare variable through a ternary operator I've seen code where a ternary operator is used to check whether or not a variable has been declared, and declare it if it has not been. For example:
var num = (typeof num === 'undefined' ? 1 : num);
console.log(num); //1

However, this does not work when using 'let' instead of 'var':
let num = (typeof num === 'undefined' ? 1 : num); //Uncaught ReferenceError: num is not defined

I know that compared to 'var', 'let' has block scoping and prevents redeclaration. I'm unsure how this would cause the ReferenceError in the case above. Could anyone shed some light as to what's going on here? Thanks!

A: You've run into something called hoisting.
Hoisting affects var declaration, but not let or const.
In short words, hoisting moves every var declaration to the top of the code. Meaning for this code:
x = 1;
var y = x + x;
var x;

It is translated to:
var y;      // y is declared, but undefined (thus y === undefined)
var x;      // x is declared, but undefined (thus x === undefined)
x = 1;      // x is defined
y = x + x   // y is defined

Which is why you don't get an error, because x is declared, then defined.
But that is not the case for let and const:
x = 1;
let y = x + x;
let x;

will throw an error, because you used x before it is declared.
EDIT
Read Felix's comment below for details.

A: Not the best way to check variable existence. You should not do it by accessing variable.
If you have to do it do it using:
var barIsDeclared = true;
try{ bar; }
catch(e) {
    if(e.name == "ReferenceError") {
        barIsDeclared = false;
    }
}

You get reference error in case of constand let variables. It may appear that they are not hoisted in the first iteration phase but that is not true.
Anyway, this is how I test variable existence and it works with no issues.

A: You're just trying to access to it before initializing it.
let num;
num = (typeof num === 'undefined' ? 1 : num);
console.log(num); //1

this is the actual answer you want.


text:
Q: POST data sent with ajax doesn't trigger ($_SERVER["REQUEST_METHOD"] == "POST") in 2nd PHP File I'm trying to make some sort of simple text chat.
I have two PHP files (index.php and send.php) and a javascript script (script.js).
In index.php, i got the following form:
<form id="formSend" method="post">
  <input id="inputMsg" class="form-control input-msg" type="text" name="msg" autocomplete="off">
  <button id="btnSend" class="btn btn-success button-send" type="submit" name="send">Send</button>
</form>

To prevent the page from reloading, the data is sent with a ajax request in my javascript file:
$('#formSend').submit(function(e){
  e.preventDefault();
  var url="send.php";
  var posting = $.post(url, {msg: $('#input-msg').val() });
  posting.done(function(data){
    $('#inputMsg').val('');
    console.log('success');
  });
});

The ajax request works (success is logged in the console), but in send.php
nothing happens.
Im using the following code in send.php:
if ($_SERVER["REQUEST_METHOD"] == "POST"){
  if(isset($_POST['msg']) && !empty(trim($_POST['msg']))){
    $msg = htmlspecialchars(trim($_POST["msg"]));
    $check = true;
  }
  else{
    $check = false;
  }

  if ($check = true) {
    $query = "INSERT INTO chat(message) values (?)";
    $stmt = $mysqli->prepare($query);
    if($stmt===false){
      $error = 'Database error';
    }
    if(!$stmt->bind_param('s', $msg)){
      $error = 'Database error';
    }
    if(!$stmt->execute()){
      $error = 'Database error' . $mysqli->error;
    }
    if(empty($error)){
      $mysqli->close();
      $success = 'Success';
    }
  }
}

Am i missing something? I really don't know why its not working...

A: <input id="inputMsg" class="form-contr .... >

And
var posting = $.post(url, {msg: $('#input-msg').val() });

Does not match.
Remove the - and Capitalize M


text:
Q: How to import compressed AVRO files to Impala table? In my work, I import AVRO files into impala tables by copy the files into HDFS then execute "refresh " in impala.
But when I want to do it with compressed files, it didn't work.
The only document I've found about enable compress with avro tables is this link: http://www.cloudera.com/documentation/archive/impala/2-x/2-1-x/topics/impala_avro.html#avro_compression_unique_1 .
Here is what I do:

*

*Enable Hive compress in hive shell:
hive> set hive.exec.compress.output=true;
hive> set avro.output.codec=bzip2;

*Create a table:
CREATE TABLE log_bzip2(
  timestamp bigint COMMENT 'from deserializer',
  appid string COMMENT 'from deserializer',
  clientid string COMMENT 'from deserializer',
  statkey string COMMENT 'from deserializer',
  expid string COMMENT 'from deserializer',
  modid string COMMENT 'from deserializer',
  value double COMMENT 'from deserializer',
  summary string COMMENT 'from deserializer',
  custom string COMMENT 'from deserializer')
PARTITIONED BY (
  day string)
ROW FORMAT SERDE
  'org.apache.hadoop.hive.serde2.avro.AvroSerDe'
STORED AS INPUTFORMAT
  'org.apache.hadoop.hive.ql.io.avro.AvroContainerInputFormat'
OUTPUTFORMAT
  'org.apache.hadoop.hive.ql.io.avro.AvroContainerOutputFormat'
TBLPROPERTIES (
  'avro.schema.url'='hdfs://szq2.appadhoc.com:8020/user/hive/log.avsc');

*Load the compressed AVRO file into HDFS:
hdfs dfs -put log.2016-03-07.1457184357726.avro.bz2 /user/hive/warehouse/adhoc_data_fast.db/log_bzip2/2016-03-07

*Add partition and refresh in Impala shell:
alter table log_bzip2 add partition (day="2016-03-07") location '/user/hive/warehouse/adhoc_data_fast.db/log_bzip2/2016-03-07/';
refresh log_bzip2;

*Query it but not work:
select * from log_bzip2 limit 10;
Query: select * from log_bzip2 limit 10
WARNINGS: Invalid AVRO_VERSION_HEADER: '42 5a 68 39 '
How can I do it right? Thanks!

A: It turns out the avro format has its own way to compress data instead of compress the generated avro file manually. So what we need to do is add the compress option to the AVRO writer while writing the file, then the generated file is compressed by the avro encoder. Put this file into Hive is OK. Nothing else need to config.


text:
Q: Failed to install matplotlib package I've been trying to install matplotlib package but I end up with this error...
Any help please?
Thank you

A: Try run command from terminal (if you use windows, press Win+R, in showed window type "cmd.exe" and run)
then write your command. try:
pip install matplotlib

if not workong, try:
pip3 install matplotlib

my be it will help.

A: I thank you all for your replies, in fact I had a problem with Pycharm I had to reinstall it in order to get it working.
Seems like I had some contradicting files of some sort...


text:
Q: How to place a Google Plus +1 button inside cordova/ionic app? I've added a +1 button in my app:

I've used this code:

and
(function() {
    var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
    po.src = 'https://apis.google.com/js/platform.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();

I've also allowed the api:
index.html:
<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://apis.google.com">

config.xml:
<allow-navigation href="https://apis.google.com" />

The problem:
This works on the browser (ionic serve) but It doesn't work on the app...
When I click nothing happens... (no errors...)
Anyway I can make this work on the app? (ionic run)
More information/debug info:

*

*If I've clicked the +1 button on the web it doesn't show me the red button on the app (Read means I've already shared that link)(It doesn't know who I am..)

*I don't want to make a login/signup, just a +1 button...

If I add:
<allow-navigation href="*" />

in config.xml, it asks me to login when I click the +1 button: (It shouldn't)

This means the +1 button doesn't work because is "in an anonymous browser", not authenticated with the OS...
I also created a demo pure Android app following this instructions: https://developers.google.com/+/mobile/android/recommend
It works perfectly... (I can +1 the link...)
My possibilites:

*

*Some way to make a native Android view with the +1 button appear on the webview.

*Make a fake +1 button and when it's clicked it calls a plugin that makes some king of request/click on the real +1 button....

*Any suggestion on how to do it?
Are any of these two possibilities possible?
Thanks for your help!

A: Your problem is that the user isn't logged in with their Google account inside the cordova browser, so obviously, you see a login prompt when clicking the +1 button.
I understand you want to access the global Google account connected to the user's phone/OS and use this one inside your app. First, your app needs credentials to access this data, then those need to be accessible from within the cordova browser. There's this plugin which does that for you.
In your initialization code, you can then call window.plugins.googleplus.login(...), which will prompt the user for confirmation (if necessary) and log in.
Make sure that the +1 button is initialized after logging in, so the state is indicated correctly. For instance (assuming you're using jQuery):
$(document).ready(function() {
  loginToGoogle();
  initPlusOneButton();
}

function loginToGoogle() { ... }

function initPlusOneButton() {
    var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
    po.src = 'https://apis.google.com/js/platform.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
}

A: If you don't want to handle the login, you can build a plugin to add a native PlusOneButton.
I'm working on it right now, I'll try to release it this afternoon, but as moderators don't like "link only asnwers" I'll explain here how to build the plugin, and I'll add the link once I finish developing it.
First of all, read the guide about how to build a cordova plugin, I'm not going to enter into that level of detail.
Your CordovaPlugin subclass will need this variables:
private PlusOneButton mPlusOneButton;
private String URL;

Your execute method should be like this:
public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException {
    if (action.equals("show")) {//show is the name of the method you call from javascript
        URL = "http://www.phonegap.es";//you should pick it from the plugin params
        mPlusOneButton =  new PlusOneButton(cordova.getActivity());
        mPlusOneButton.initialize(URL, null);

        //you have to run this part making sure you run it on the UI Thread
        cordova.getActivity().runOnUiThread(new Runnable() {
            public void run() {
                cordova.getActivity().addContentView(mPlusOneButton,new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT));

                //position the button wherever you want, you should pick the values from the plugin params
                mPlusOneButton.setX(300);
                mPlusOneButton.setY(300);

            }
        });

    } else {
        return false;
    }
    return true;
}

Finally add the onResume method to keep the button status up to date.
@Override
public void onResume(boolean multitasking) {
    super.onResume(multitasking);
    mPlusOneButton.initialize(URL, null);
}

The plugin will have to add the com.google.android.gms:play-services-plus dependency
You can do that adding this line to the plugin.xml
<framework src="com.google.android.gms:play-services-plus:+" />

EDIT: The plugin is ready https://github.com/jcesarmobile/plusOneButtonPlugin
To install it
cordova plugin add https://github.com/jcesarmobile/plusOneButtonPlugin

To use it:
var params = {};
params.url = "http://www.example.com";
params.position = {x:100,y:100};
plusOneButton.show(params);

Or
plusOneButton.show("http://www.example.com");


text:
Q: Getting value from  statement from jsp to Action class I have the following <select>..</select> in my code:
<select name="approvername">
    <option value="first name">my first name</option>
    <option value="second name">my second name</option>
    <option value="third name">my third name</option>
    <option value="fourth name">my fourth name</option>
</select>

When I try to get the value in my action class,like String approvername = request.getParameter("approvername") it shows null when I try to print it.
How to get the value?

A: In the action class instead of using
String approvername = request.getParameter("approvername")

I've changed it to
String approvername = (String)areq.getParameter("approvername");

And it works!!

A: The correct way to do this for this type of select is to use getParameterValues. You will get an array of strings with all the values selected, in your case it will only be an array with 1 element.
String approvername = request.getParameterValues("approvername")[0].


text:
Q: Looking for Artifactory Query Language example in Java I'm trying to use the Artifactory REST API (and in particular, the Artifactory Query Language) from a Java client but the examples on the site are written in Groovy (snippets) and it's not immediately clear how a Java client would work.
A Java example that uses the REST API (or the Artifactory Java Client API) to execute an AQL query would be very much appreciated.
For what it's worth, here's a link to the Artifactory Query Language site...
https://www.jfrog.com/confluence/display/RTF/Artifactory+Query+Language

A: The Artifactory Java Client does not support AQL queries natively.
You can however use the generic Rest call interface it provides to create an ArtifactoryRequest pointing to the AQL API endpoint.
The examples in the wiki you linked are not in Groovy they are in AQL syntax - you simply construct a String of whatever query you'd like and send it as the body of the request - roughly something like

String aqlQuery = "items.find({\"name\": {\"$match\" : \"*test.*\"}})";
Artifactory artifactory = Artifactory.create(url, userName, password);
ArtifactoryRequest aqlRequest = new ArtifactoryRequestImpl()
            .method(ArtifactoryRequest.Method.POST)
            .apiUrl("/api/search/aql")
            .requestBody(aqlQuery);
 //Parse this string as json
 String aqlResponse = artifactory.restCall(aqlRequest);

The response is a JSON you can parse and work on - check the example from the API link I provided.

A: @fundeldman Thanks for suggesting the answer above. After a few minor tweaks, the code is now working. Here's the latest and greatest...
String aqlQuery = "items.find({\"name\": {\"$match\" : \"*rup-receipt*\"}}).include(\"repo\", \"path\", \"name\")";
Artifactory artifactory = ArtifactoryClient.create(artifactoryUrl, username, password);
ArtifactoryRequest aqlRequest = new ArtifactoryRequestImpl()
            .method(ArtifactoryRequest.Method.POST)
            .apiUrl("api/search/aql")
            .requestType(ArtifactoryRequest.ContentType.TEXT)
            .responseType(ArtifactoryRequest.ContentType.JSON)
            .requestBody(aqlQuery);
Map<String, ?> aqlResponse = artifactory.restCall(aqlRequest);


text:
Q: ExtJS 4.1.1: Evaluating a field in a grid I'm struggling with a ExtJS 4.1.1 grid that has editable cells (CellEditing plugin).
A person should be able to type a mathematic formula into the cell and it should generate the result into the field's value. For example: If a user types (320*10)/4 the return should be 800. Or similar if the user types (320m*10cm)/4 the function should strip the non-mathematical characters from the formula and then calculate it.
I was looking to replace (or match) with a RegExp, but I cannot seem to get it to work. It keeps returning NaN and when I do console.log(e.value); it returns only the originalValue and not the value that I need.
I don't have much code to attach:
onGridValidateEdit : function(editor,e,opts) {
    var str = e.value.toString();
    console.log(str);
    var strCalc = str.match(/0-9+-*\/()/g);
    console.log(strCalc);
    var numCalc = Number(eval(strCalc));
    console.log(numCalc);
    return numCalc;
},

Which returns: str=321 strCalc=null numCalc=0 when I type 321*2.
Any help appreciated,
GR.

Update:
Based on input by Paul Schroeder, I created this:
onGridValidateEdit : function(editor,e,opts) {
    var str = e.record.get(e.field).toString();
    var strCalc = str.replace(/[^0-9+*-/()]/g, "");
    var numCalc = Number(eval(strCalc));
    console.log(typeof numCalc);
    console.log(numCalc);
    return numCalc;
},

Which calculates the number, but I am unable to print it back to the grid itself. It shows up as "NaN" even though in console it shows typeof=number and value=800.

Final code:
Here's the final code that worked:
onGridValidateEdit : function(editor,e,opts) {
    var fldName = e.field;
    var str = e.record.get(fldName).toString();
    var strCalc = str.replace(/[^0-9+*-/()]/g, "");
    var numCalc = Number(eval(strCalc));
    e.record.set(fldName,numCalc);
},

A: Lets break this code down.
onGridValidateEdit : function(editor,e,opts) {
    var str = e.value.toString();

What listener is this code being used in?  This is very important for us to know, here's how I set up my listeners in the plugin:
listeners: {
            edit: function(editor, e){
                var record = e.record;
                var str = record.get("your data_index of the value");
            }
        }

Setting it up this way works for me, So lets move on to:
   var strCalc = str.match(/0-9+-*\/()/g);
    console.log(strCalc);

at which point strCalc=null, this is also correct. str.match returns null because your regex does not match anything in the string.  What I think you want to do instead is this:
var strCalc = str.replace(/[^0-9+*-]/g, "");
console.log(strCalc);

This changes it to replace all characters in the string that aren't your equation operators and numbers.  After that I think it should work for whole numbers.  I think that you may actually want decimal numbers too, but I can't think of the regex for that off the top of my head (the . needs to be escaped somehow), but it should be simple enough to find in a google search.


text:
Q: A random number with 3 digit and try to guess every digit one by one I am new in Java and for the moment basic with methods, classes and constructors. For practice I am trying to write a basic game (safecracker). So my logic is get a 3 digit random number and try to guess it.
private static int takeRandomSafeCode(int min, int max) {
    Random random = new Random();
    int result = random.nextInt(max - min) + min;
    return result;

 private static void playGame() {
    int safeCode = takeRandomSafeCode(100, 999);
    int guess = takeGuess();

These are my random number methods. But if player guess a number and first digit is correct but on a wrong place I want to say "1 digit is correct but on a wrong position" or if one digit is correct "1 digit is correct and correct position"
I need to use here if-else statement i guess but I get my numbers int variable. What is the way of checking numbers one by one? Do I need to use a String? I am a little bit lost at this point. I would appreciate with your help.

A: It may be preferable - and result in simpler code - if you generate an integer array with three elements. Logically, the safe code 1-2-3 is not one hundred and twenty three but actually 1 followed by 2 followed by 3.
private static int takeRandomDigit() {
    Random random = new Random();
    int result = random.nextInt(10);
    return result;
}

private static void playGame() {
    int[] safeCode = {takeRandomDigit(), takeRandomDigit(), takeRandomDigit()};
    int guess = takeGuess();

    for (int safeDigit : safeCode) // for each digit in the safe code
    {
        // if the digit matches the guess, do something
    }
}

A: You can use some math to take the numbers for example if your number is:
d=253
d % 10 -> gives you 3
d / 10 % 10 -> gives you 5
d / 100 -> gives you 2

Changing it to string is also an option because you can then access the different characters using the string functions like charAt etc.
But if you want to make it the Java and OOP way in order to learn you can make an object and add the 3 numbers as properties of that object and input some of the logic for checking there instead of doing some magic tricks like the above. For example:
class Combination {
  private  int firstPos;
  private  int secondPos;
  private  int thirdPos;

  public  Combination(){
    firstPos=random.nextInt(10);
    secondPos=random.nextInt(10);
    thirdPos=random.nextInt(10);
 }

 public boolean checkCombination(Combination testedCombination){
       .............
 }
 some methods, getter, setters etc
}


text:
Q: RedirectToAction in Loop process [.Net Core 3.1] I've been struggling to finish the app I'm developing,
here is the scenario:

*

*I have a Razor page where the user will input customer number, Company Code, and Date. Users can input multiple customer numbers and the app will split them by comma.

*once the user inputted the details a button with asp-action pointed to the action named GenerateSoa, it will run a foreach statement that will RedirectToAction for every customer that is inputted on the GUI

The problem starts here when the loop runs it only opens one tab even if there are 3 customers inputted.
It should open 3 tabs with their details for 3 different customers. below is my code
I did not however include the SoaLooper cshtml file.
SoaController.cs
public IActionResult GenerateSoa()
{
    ClearAmounts();

    #region Date management for SOA

    // First day of Current Month
    var FirstDateOfCurrentMonth = new DateTime(SD.DateToday.Year, SD.DateToday.Month, 1);
    var PreviousMonthFirstDay = FirstDateOfCurrentMonth.AddMonths(-1);
    var PreviousMonthLastDay = DateTime.DaysInMonth(SD.DateToday.Year, PreviousMonthFirstDay.Month);

   ****** Ommitted some code *****

    // Get last day of Previews month
    var PreviewsBalanceDate = PreviousMonthFirstDay.Month.ToString() + "/" +
        PreviousMonthLastDay.ToString() + "/" + PreviousMonthFirstDay.Year.ToString();

    #endregion Date management for SOA

    //SD.GuiCustomerNum = customer.ToString();

    var bsid_unpaid_payments = _context.BSIDs.Where(l =>
       (l.UMSKZ == "" || l.UMSKZ != "C") && l.BLART == "DJ");
    foreach (var payments in bsid_unpaid_payments)
    {
        SD.PAmount += Convert.ToDouble(payments.DMBTR);
    }
    SD.UPTotalAmount = SD.UPAmount - SD.PAmount;

    return View();
}

public IActionResult SoaLooper(string customer, int company, DateTime asof)
{
    string[] customerNum = customer.Split(',');
    SD.GuiCompany = company.ToString();
    SD.DateToday = asof;

    foreach (var item in customerNum)
    {
        SD.GuiCustomerNumSelected = item.ToString();
        RedirectToAction(nameof(GenerateSoa));
    }

    return View();
}

Index.cshtml

        <form method="post" class="col-12 text-center">

Statement of Account

                        Customer

                        <input id="customer" name="customer" class="form-control" />

                        Company Code

                        <select id="company" name="company" class="form-control">
                            <option value="">Select a number</option>
                            <option value="2000">2000</option>
                            <option value="3000">3000</option>
                        </select>

                        Statement as of

                        <input id="asof" name="asof" type="date" class="form-control" />

                                <button type="submit" formtarget="_blank" id="btnCheck"
                                 class="btn btn-primary form-control" asp-action="SoaLooper">Generate</button>

        </form>

A: RedirectToAction doesn't open a new tab, it just returns a status code of 302 to tell the client to redirect.
If you really want to open multiple new tabs, you should do something like return a list of urls and then use window.open when the page loads.
I haven't tested it but you could do something like this:
Add your url to a list:
SoaController.cs
var newTabUrls = new List<string>();

foreach (var item in customerNum)
{
    SD.GuiCustomerNumSelected = item.ToString();

    newTabUrls.Add(nameof(GenerateSoa));
}

return View(newTabUrls);

Index.cshtml

Open a URL in a new tab (and not a new window)
how to open a page in new tab on button click in asp.net?


text:
Q: Cup product in Morse cohomology Dualizing the Morse complex, we obtain the Morse cohomology, which is isomorphic to the usual singular cohomology and thus admits a cup product.
Does anybody know how this cup product would look like in terms of critical points of a Morse function? What is the geometric picture?

A: It is given by counting Y-shaped flowlines, using Morse functions along each of the three edges. For more info:
Morse Homotopy, $A_\infty$-Category, and Floer Homologies (by Fukaya)
Googling around also helps for such questions!

A: I want to expand a little bit on Chris' answer. The cup product in singular homology arises from the composition
$$
H^*(M)\otimes H^*(M)\rightarrow H^*(M\times M)\rightarrow H^*(M)
$$
Here the first map is the cross product map, and the second map is the pullback $\Delta^*$ of the diagonal embedding $M\rightarrow M\times M$. This can also be interpreted Morse theoretically.
The cross product map can be computed in Morse homology as follows. Choose two critical points $x$ and $y$ of Morse functions $f_1$ and $f_2$ on $M$. Let $\eta_x$ be the map that sends $x$ to $1$ and all other critical points to zero (this is a basis of the dual complex). Then $\eta_x\otimes \eta_y$ is a generator of $C^*(M)\otimes C^*(M)$. Sending this to $\eta_{(x,y)}$ where $(x,y)$ is the critical point of $f(p,q)=f_1(p)+f_2(q)$ on $M\times M$ defines the cross product map.
In general a map $h:M\rightarrow N$ (equipped with Morse-Smale pairs $(f_M,g_M)$ and $(f_N,g_N)$ induces under the transversality assumption that $h|_{W^u(x;f_M,g_M)}\pitchfork W^s(y;f_N,g_N)$ a map $h^*:HM^*(N)\rightarrow HM^*(M)$ defined on the generators by
$$
h^*\eta_y=\sum_{y}\#(W^u(x;f_M,g_M)\cap h^{-1}(W^s(y;f_N,g_N))\eta_x.
$$
Applying this to the diagonal embedding $\Delta$, and composing this with the cross product we can compute the cup product map via
$$
\eta_x\cup\eta_y=\sum_z \#(W^s(x;f_1,g_1)\cap W^s(y;f_2,g_2)\cap W^u(z;f_3,g_3))\eta_z.
$$
Here the $(f_i,g_i)$ are Morse-Smale pairs such that the stable manifolds and unstable manifolds intersect mutually transversely. These are exactly the $Y$ shaped flowlines of Chris' answer. The transversality condition required for the diagonal map implies that the intersection above is transverse. It is not too hard to see that the expected dimension is what it should be.
A reference for point of view are the appendices to Abbondandolo Schwarz: Floer homology of cotangent bundles and the loop product.


text:
Q: unexpected error on inserting values and error with implode() I am inserting the values using PDO but i am getting error as:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc,price,nick_name,gender,size,color,birth_date,uname,uphone,ucountry,ustate,u' at line 1' in C:\wamp\www\aa\abc.php:58 Stack trace: #0 C:\wamp\www\www\aa\abc.phpphp(58): PDOStatement->execute(Array) #1 {main} thrown in C:\wamp\www\www\aa\abc.php.php on line 58
also getting Warning: implode() [function.implode]: Bad arguments for implode function
Code:
foreach ($_POST['pcheck'] as $p_check) ////storing checkbox values
{
    $pcheckp[] = $p_check;
}   $finalcheck = implode(',', $pcheck);
foreach ($_POST['pinc'] as $p_inc) ////storing inputfield values
{
    $pinc[] = $p_inc;
}   $finalpinc = implode(',', $pinc);

$sql = "INSERT INTO list (u_id,list_type,list_ff,breed,title,desc,price,nick_name,gender,size,color,birth_date,uname,uphone,ucountry,ustate,ucity,usite,pcheck,pinc,photo)
VALUES(:uid,:list_type,:list_ff,:breed,:title,:desc,:price,:nick_name,:gender,:size,:color,:date,:uname,:uphone,:ucountry,:ustate,:ucity,:usite,:pcheck,:pinc,:p_photo)";
$q = $db->prepare($sql);
$q->execute(array(':uid'=>dd,
                ':list_type'=>$list_type,
                ':breed'=>$breed,
                ':title'=>$title,
                ':desc'=>$desc,
                ':price'=>$price,
                ':list_ff'=>$list_ff,
                ':nick_name'=>$nick_name,
                ':gender'=>$gender,
                ':size'=>$size,
                ':color'=>$color,
                ':date'=>$date,
                ':uname'=>$uname,
                ':uphone'=>$uphone,
                ':ucountry'=>$ucountry,
                ':ustate'=>$ustate,
                ':ucity'=>$ucity,
                ':usite'=>$usite,
                ':pcheck'=>$finalcheck,
                ':pinc'=>$finalpinc,
                ':p_photo'=>$p_photo));

$_POST['pcheck'] and $_POST['pinc'] is used to get checkbox and input values which i am going to store in column in mysql.
I have checked many times to find the syntax error in insert query but nothing wrong is in it
Hoping to get help
Thanks!

A: for Warning: implode()
$finalcheck = implode(',', $pcheck);

should be
$finalcheck = implode(',', $pcheckp);

also desc is reserved for mysql you need to use it with `
    $sql = "INSERT INTO list (`u_id`,`list_type`,`list_ff`,`breed`,`title`,`desc`,`price`,`nick_name`,`gender`,`size`,`color`,`birth_date`,`uname`,`uphone`,`ucountry`,`ustate`,`ucity`,`usite`,`pcheck`,`pinc`,`photo`)
VALUES(:uid,:list_type,:list_ff,:breed,:title,:desc,:price,:nick_name,:gender,:size,:color,:date,:uname,:uphone,:ucountry,:ustate,:ucity,:usite,:pcheck,:pinc,:p_photo)";


text:
Q: Export Azure VM Tags along other details to CSV Is there a way to get all tags assigned to VM in 1 cell when exported as CSV along other details of the VM?
In the column where Tags are supposed to go all I get is a single curly bracket "{"
Import-Module Az.Automation
Import-Module Az.Compute
Import-Module Az.Storage
$resourceGroup = "rg-ServerList"
$storageAccount = "stxxxxxxxxxxxxx"
$subscriptionid = "xxxxxxxxxxxxxxxxxxxxx"
$storageAccountContainer = "azure2"

#Connect-AzAccount -Identity

$date = get-date -format dd-MM-yyyy

    Set-AzContext -SubscriptionId $subscriptionid
        get-azVM -Name "MyServer" | Select @{Name="ID"; Expression={$_.vmid}},
        @{N='Subscription'; E={$Subscription}},
        @{Name="VM Name"; Expression={$_.name}},
        @{ N='Tags'; E={$_.tags | ConvertTo-Json | Out-String}} | export-csv C:\temp\Azure-servers.csv -notypeinformation

Set-AzContext -SubscriptionId $subscriptionid
Set-AzCurrentStorageAccount -StorageAccountName $storageAccount -ResourceGroupName $resourceGroup
Set-AzStorageBlobContent -Container $storageAccountContainer -file Azure-servers.csv -force

A: You would have to form a string from the tags property which is a hashtable.
Below I use GetEnumerator() to iterate over each key value pair and create a string in <key> = <value> format then join each of the strings with a ,
Get-AzVM |
    Select-Object -Property (
        @{name='ID' ; expression={$_.VmId}},
        @{name='Subscription' ; expression={$subscription}},
        @{name='VMName' ; expression={$_.Name}},
        @{name='Tags'; expression = {($_.tags.GetEnumerator().ForEach({ '{0} = {1}' -f $_.key, $_.value }) -join ',')}}
    )


text:
Q: How can I convert some columns of a pandas dataframe to categorical? This is my code:
l1 = list(train)
for i in (0,len(l1)):
    if train[l1[i]].dtypes == object:
        train[l1[i]] = pd.Categorical(train[l1[i]])

train.info(verbose=True)

But this just makes the first variable change and nothing else. The rest of the 62 object variables aren't converted to object.
How do you do it?

A: Get all object columns by DataFrame.select_dtypes, convert to dict and pass to DataFrame.astype:
train = train.astype(dict.fromkeys(train.select_dtypes('object').columns, 'category'))


text:
Q: C# - Access select query using Date/Time So I'm making a database for a school project regarding Movies / Actors (2 different tables).
In the Microsoft Access database one of the field's type is Date/Time and I want to create a select query that will return me all movies from the year given for example:

public static DataSet GetByYear(string actorYear)

It needs to like something like this:

string sQuery = SELECT * FROM ActorsTable WHERE ActorsTable.actorDate.Year = actorYear

Something like that +-
Also, can anyone please show me how can I make a select that will return me all actors (select * from ...) but sorted by their age?

A: Query based on the year of a date:
SELECT *
FROM ActorsTable
WHERE YEAR(actorDate) = actorYear

Actors ordered by age:
SELECT * FROM
(
  SELECT a.*, DateDiff('yyyy', a.ActorDate, Now()) +
              Int(Format(Now(), 'mmdd') < Format(a.ActorDate, 'mmdd'))
              AS AgeOfActor
  FROM ActorsTable AS a
) AS m
ORDER BY m.AgeOfActor


text:
Q: PUT request to update data in a website I want to update price field in a website using Curl PUT request. But I am not being able to figure out the error in my code. It will be great help if you can find the error. Below is my code.
$api_request_url = 'http://example.com/variants/SOMETHING';

$method_name = 'PUT';

$header = array(
"Accept: application/json, text/plain",
"Content-Type: application/json;charset=utf-8",
"Connection: keep-alive",
"Accept-Language: en-US,en;q=0.5",
"Accept-Encoding: gzip, deflate",
"Content-Length: 82",
"Referer: http://seller.example.com/catalog",
"Cache-Control: max-age=0, private, must-revalidate"
);

$payload = array(
//"variant:  'YEL510044' , 6",//
'price' => '600',
//"original_price: 999"//
);
$data_string = json_encode($payload);
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);

curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

curl_setopt($ch, CURLOPT_URL, $api_request_url);

curl_setopt($ch, CURLOPT_HEADER, TRUE);

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

$api_response = curl_exec($ch);

$api_response_info = curl_getinfo($ch);
echo "$api_response";

curl_close($ch);

A: You try change code:
$data_string = json_encode($payload);

to
$data_string = http_build_query($payload);

A: you should try:
curl_setopt($ch, CURLOPT_PUT,  true);
in place of
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');


text:
Q: Draw text around circle with C++ MFC functions I have problem with text drawing around Circle.
I found great sample in C# http://www.codeproject.com/Articles/30090/Text-On-A-Path-in-WPF
Bu I need to implement this in VC 6.0 and C# sample isn't working for me for that reason.
Maybe exist some basic algorithm to implement this?
All drawings must be drawn in CDC.

A: CDC is a thin wrapper around GDI.  GDI doesn't provide much support for what you want to do, so it will be a lot of work.  Here are a couple of approaches:

*

*Draw the text normally (in a straight line) to an off-screen DIB section, and then do a pixelwise transformation to make another off-screen DIB section with the text in a circle.  Then you can blit the transformed DIB section to the output device.

*For each character, create a logical font with the escapement and orientation set to the appropriate angle for the current position, then draw the character with that font.  Repeat for each character.  The problem here is that, even with TrueType or OpenType fonts, the rotations aren't always very good, depending on the quality of the font, hinting, etc.

*Use a TrueType or OpenType font and get GDI to give you the vectors (line segments and bezier curves) that define the actual character shapes.  Assemble these into a straight row, and then apply a Cartesian to polar coordinate transform.  Draw the result using one of the path functions.


text:
Q: On number configurations coprime to $p_k\#$ on $[1, p_k\#]$ Being a non-mathematician, I seek guidance and commentary regarding the formula discussed here:
Numbers $n$ with $n,n+2$ coprime to $p_k\#$ on $[1, p_k\#]$
Repeating it here:

The number of $n$ such that $n, (n+2)$ are coprime to $p_k\#$ for $n=1,2,...,~p_k\#$ is  $\prod_{i=2}^k (p_i-2).$

I'm glad I finally did the search and found out that somebody else had found this formula, that I have also been playing with for some considerable time.
List of questions.

*

*Is "$p_k\#$" a generally adopted notation for the product of a sequence of primes? (I think I like it.)

*The formula can be generalized, and I assume this is known?
[For plain numbers (potential primes in the interval)]The number of $n$ that are coprime to $p_k\#$ for $n=1,2,...,~p_k\#$ is $\prod_{i=1}^k (p_i-1).$
[For odd number pairs (potential twin primes)]: as above, $\prod_{i=2}^k (p_i-2).$
[For potential "quad primes"]The number of $n$ such that $(n, n+2, n+6, n+8)$ are coprime to $p_k\#$ for $n=1,2,...,~p_k\#$ is $\prod_{i=3}^k (p_i-4).$
[etc...?]

*I suppose this "law" is not established or important enough to have a name?

*I would like to have a short name for the concept of a "potential prime" or "prime candidate" obtained by establishing it coprime against $p_k\#$ (or against a more general set of divisor primes). I personally called it "prime candidate with respect to $p_k$" in my private notes. (OK, "coprime to $p_k\#$" is pretty short and is perhaps the term I was looking for. Are there other names for it?)

*I assume the following is also well known (please confirm).
The classical proof of infinite primes: Assume the last and largest prime is $p_k$. Observe that $p_k\#-1$ is coprime to $p_k\#$. Demonstrate the contradiction and conclude the assumption is false.
The point: The plain version of the discussed formula generalises this by demonstrating that there are many numbers above $p_k$ coprime to $p_k\#$; any one of them leads to the proof.
In particular, the first such number larger than $p_k$ has to be a true prime since no other divisors can exist.

*I assume the following observation is also well known?
In the hunt for twin primes; if a number pair is found to be coprime to $p_k\#$, larger than $p_k$ and smaller than $p_{k+1}^2$, then it is a true twin prime. (Which obviously means $n >= p_{k+1}$.)
Proving that such a pair can always be found would prove the twin prime conjecture.

*Is there a "quad prime conjecture"?

*Is there a generalised conjecture that given any pattern of numbers that are all prime, this pattern is going to repeat itself an infinite number of times? Or a weaker conjecture of non-uniqueness: any pattern will eventually repeat.


text:
Q: form in php using javascript, ajax, jquery I have created a form with HTML and process the data via a PHP page and I want to receive/display "inserted/failed" notification on same page(index.html). I'm using javascript, ajax and jquery. Data is updated in the database but I'm getting result on the process.php page. I want to insert result notification on index.html page itself.
index.html

<title>Registration form</title>

<form id="myForm" action="process.php" method="POST">
Username: <input type="text" name="username">

Password: <input type="password" name="pass">

First name: <input type="text" name="fname">

Last name: <input type="text" name="lname">

<button id="submit" name="submit">Register</button>
</form>

Acknowledge

my_script.js
$("#submit").click( function(){

    $.post( $("#myForm").attr("action"),
            $("#myForm :input").serializeArray(),
            function(info){
            $("#ack").empty();
            $("#ack").html(info);
            clear();
            });
$("#myForm").submit( function(){
    return false;
    });
});

function clear(){

    $("#myForm:input").each( function()){
        $(this).val("");
    }
}

A: Try this:
$("#submit").on('click',function(e){
    e.preventDefault();
    $.post(
            $("#myForm").attr("action"),
            $("#myForm :input").serializeArray(),
            function(info,status,xhr){
                $("#ack").empty();
                $("#ack").html(info);
                clear();
            }
    );
});

function clear(){
    $("#myForm:input").each(function(){
        $(this).val("");
    });
}

PHP page(I'm echoing "success" in the PHP page, so the same content will reflect in the HTML page):
<?php echo "success";?>

Output:
success


text:
Q: How can I align entries in the column? I have drawn the following picture in xypic
and I would like to align in the right column the Hom term in the first row as well as direct product guys in the 2nd and 3rd rows exactly together. How can I do this? Because right now the diagram is looking odd. For those interested, here is my code:
\[\begin{xy} \xymatrix@C=5em@R=4em{  \Hom(X,\spec A) \ar[r]^\alpha \ar[d] &  \operatorname{Hom}(A,\Gamma(X,\mathcal{O}_X)) \ar[d] \
\prod_i \Hom(U_i,A) \ar[r]^-{\beta_i} \ar@<-0.5ex>[d] \ar@<0.5ex>[d] &\prod_i \operatorname{Hom}\Big(A,\Gamma(U_i,\mathcal{O}_X|_{U_i}) \Big)  \ar@<-0.5ex>[d] \ar@<0.5ex>[d] \
\prod_{i,j} \Hom(U_i \cap U_j,A) \ar[r]^-{\beta_{i,j}} & \prod_{i,j}  \operatorname{Hom}\Big(A,\Gamma(U_i \cap U_j,\mathcal{O}_X|_{U_i\cap U_j}) \Big)   }\end{xy}\]

A: This is a first cut.  I'm sure something can be done better with the arrows than just stretching them (as I did).
\documentclass{article}
\usepackage{stackengine}
\usepackage{scalerel}
\def\spec{\mathrm{Spec}}
\def\Hom{\mystrut\mathrm{Hom}}
\def\bigdownarrow{\stretchto{\downarrow}{6ex}}
\def\bigrightarrow{\protect\hstretch{5}{\rightarrow}}
\def\nobigdownarrow{\protect\phantom{\bigdownarrow}}
\newcommand\rarrow[1]{\mystrut\smash{\stackon{$\bigrightarrow$}{$#1$}}}
\def\hgapa{\hspace{5ex}}
\def\hgapb{\hspace{4.5ex}}
\def\mystrut{\protect\vphantom{\Big(}}
\begin{document}
\[
\Shortstack[r]{{} {$\nobigdownarrow$} {$\prod_{i,j}\mystrut$}
 {$\nobigdownarrow$} {$\prod_{i,j}\mystrut$}}
\Shortstack[l]{{$\Hom(X, \spec A)$} {$\hgapa\bigdownarrow$} {$\Hom(U_i, A)$}
  {$\hgapb\bigdownarrow\bigdownarrow$} {$\Hom(U_i \cap U_j,A)$}}
\Shortstack[c]{{$\rarrow{\alpha}$} {$\nobigdownarrow$} {$\rarrow{\beta_i}$}
  {$\nobigdownarrow$} {$\rarrow{\beta_{i,j}}$}}
\Shortstack[r]{{} {$\nobigdownarrow$} {$\prod_{i,j}\mystrut$}
 {$\nobigdownarrow$} {$\prod_{i,j}\mystrut$}}
\Shortstack[l]{{$\Hom(A,\Gamma(X,\mathcal{O}_X))$} {$\hgapa\bigdownarrow$}
  {$\Hom\Big(A,\Gamma(U_i,\mathcal{O}_X|_{U_i}) \Big)$}
  {$\hgapb\bigdownarrow\bigdownarrow$}
  {$\Hom\Big(A,\Gamma(U_i \cap U_j,\mathcal{O}_X|_{U_i\cap U_j}) \Big)  $}}
\]
\end{document}


text:
Q: Is (Document) an object in javascript? In this code :
document.getElementById()

Is document an object that has properties and methods?
If yes, is getElementById() a method on this object?
If no, What are document and getElementById considered?

A: Yes, document is an object.
typeof document; // "object"

And getElementById is a property on that object.

A: In browser, document is a instance of Document.
document instanceof Document =>true.
It represents the whole HTML page.
And document is a property of window.
window.document === document => true.
So it can used as global object.