text:
Q: Genus formula for a curve in a $2$-dimensional complex torus? For a curve $C$ in a $2$-dimensional complex torus $T$, is there any formula to compute the genus of $C$? Say, in terms of self-intersection number?
For a curve in $\mathbb{P}^2$ or a K3 surface, there is a genus formula in terms of the self-intersection number. I wonder if there is a similar formula for a $2$-dimensional complex torus.

A: My answer will be for the case where both the curve $C$ and the surface $S$ are smooth (and connected), though I'm sure the result holds more generally.

Note that $\chi(C) = \langle e(TC), [C]\rangle$ where $e$ denotes the Euler class and $[C]$ is the fundamental class. As $C$ is (complex) one-dimensional, $e(TC) = c_1(TC)$. Note that we have an exact sequence of vector bundles $0 \to TC \to TS|_C \to NC \to 0$ where $NC$ is the normal bundle of $C$ in $S$. Therefore $c_1(TS|_C) = c_1(TC) + c_1(NC)$. By the adjunction formula, $NC = L(C)|_C$ where $L(C)$ is the line bundle associated to the divisor $C$. Rearranging, we see that
$$c_1(TC) = c_1(TS|_C) - c_1(L(C)|_C) = c_1(i^*TS) - c_1(i^*L(C)) = i^*c_1(TS) - i^*c_1(L(C))$$
where $i : C \hookrightarrow S$ is the inclusion. Therefore
\begin{align*}
\chi(C) &= \langle i^*(c_1(TS) - c_1(L(C))), [C]\rangle\\
&= \langle c_1(TS) - c_1(L(C)), i_*[C]\rangle\\
&= \langle c_1(TS) - c_1(L(C)), \gamma\cap[S]\rangle\\
&= \langle \gamma\cup(c_1(TS) - c_1(L(C))), [S]\rangle.
\end{align*}
where $\gamma$ is the Poincaré dual of $i_*[C]$. But the Poincaré dual of $i_*[C]$ is $c_1(L(C))$ so
$$\chi(C) = \langle c_1(L(C))\cup (c_1(TS) - c_1(L(C))), [S]\rangle.$$
As $\chi(C) = 2 - 2g(C)$, you can rearrange this equation to obtain a formula for the genus of $C$.

Example: If $S = \mathbb{CP}^2$ and $C$ is given by the zero set of $f(x, y, z) = x^4 + y^4 + z^4$. As $T\mathbb{CP}^2 = \mathcal{O}(3)$ and $L(C) = \mathcal{O}(4)$ we have $c_1(T\mathbb{CP}^2) = 3a$ and $c_1(L(C)) = 4a$ where $a = c_1(\mathcal{O}(1))$. Therefore we obtain
$$2 - 2g(C) = \langle 4a\cup(3a - 4a), [\mathbb{CP}^2]\rangle = \langle 4a\cup(-a), [\mathbb{CP}^2]\rangle = -4\langle a^2, [\mathbb{CP}^2]\rangle = -4.$$
So we can see that $C$ has genus $3$.

In terms of algebraic geometry, one may prefer to use the notion of intersection number in which case the formula becomes
$$2 - 2g(C) = -C\cdot K_S - C\cdot C$$
where $K_S$ is the canonical divisor associated to $\omega_S$, the canonical bundle.
If $S$ is a complex two-dimensional torus, then $K_S = 0$ so $2 - 2g(C) = - C\cdot C$ and hence $g(C) = 1 + \frac{1}{2}C\cdot C$. Note, this implies that $C\cdot C$ is even for every divisor in the torus.


text:
Q: Finding Convergence for Series I would appreciated any pointers or tips on how to find the convergence for
$$
\sum_{n=0}^{\infty} 10\cdot(0.99)^{n}
$$
I know that this series converges to 1000, but I need some guidance on how this can be demonstrated.

A: $$=\sum _{n=0}^{\infty \:}\:\left(10\cdot \left(0.99\right)^n\right)$$
$$ $$
$$\mathrm{Apply\:the\:constant\:multiplication\:rule}:\quad \sum c\cdot a_n=c\cdot \sum a_n$$
$$=10\cdot \sum _{n=0}^{\infty \:}0.99^n$$
$$ $$
$$\mathrm{Apply\:Series\:Geometric\:Test}:$$
$$\mathrm{If\:the\:series\:is\:of\:the\:form\:}\sum _{n=0}^{\infty }r^n$$
$$\mathrm{If\:}|r|<1\mathrm{,\:then\:the\:geometric\:series\:converges\:to\:}\frac{1}{1-r}$$
$$\mathrm{If\:}|r|\ge \:1\mathrm{,\:then\:the\:geometric\:series\:diverges}$$
$$r=0.99,\:|r|=0.99<1,\:\mathrm{by\:the\:geometric\:test\:criteria}$$
$$ $$
$$=10\cdot\frac{1}{1-\left(0.99\right)}$$
$$=1000$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: SOLR double quotes in edge_ngram field A field in the SOLR indexes for an application I'm working on is defined as follows:
 <field name="text" type="edge_ngram" indexed="true" stored="true" multiValued="false" />

...and, elsewhere in schema.xml:
 <fieldType name="edge_ngram" class="solr.TextField" positionIncrementGap="1">
     <analyzer type="index">
        <tokenizer class="solr.NGramTokenizerFactory" minGramSize="3" maxGramSize="15" />
        ...

This works nicely for most searches the users wish to do, e.g. it turns up 'twowords' if they search for 'two words', and so on.
However, some users also wish to search for exact strings. For example, exactly one record contains 'this exact string' amongst the many other words in the text field. If users search for that string using quotes, i.e. "this exact string", a search will turn up nothing:
http://localhost:8983/solr/collection1/select?q=%22this%20exact%20string%22

Omit the quotes, and they will get plenty of hits, for example anything with 'string' in it.
Presumably, therefore, my choice of field type is not the best. Can anyone suggest a way around this?


text:
Q: How to set a pragma to constrain Ada's functionality to Pascal I intend to use Ada for some programs. I remember reading somewhere that with pragmas you can set compiler instructions to optimize your program. More specifically, I remember reading that if you need only a limited subset of Ada functionality (basically corresponding to Pascal, but with Ada's strong typing), you can use pragmas to specify a sort of 'Pascal-like mode' (I use this term for lack of a better expression). My aim is disabling those runtime checks that I don't need (since I only need basic functionality), thus reducing the size of the executable and enhancing the performance.
My question is: how do I set such a pragma? What parameters/options should I specify?
Thank you

A: This perhaps comes from a misunderstanding.
Ada is not a superset of Pascal. It is a fair bit more accurate to view them as sibling languages of the parent language Algol 60. Pascal was orginally developed by Niklaus Wirth to be a simplified version of Algol 60. The Algol folks instead went the other way with what became Algol 68.
Ada was instead a new language designed from scratch that borrowed from Algol 60's syntax (in much the way that Java borrows from C's syntax). It is however much more complex (some would use the word "functional") than even Algol 68.
So asking for a "Pascal flag" in your Ada compiler is much like asking for a "C++ flag" in your Java compiler.
If you are just looking for a free Pascal compiler, you might instead look at using Free Pascal or GNU Pascal.
If you are just looking to decrease the overhead of unused runtime facilities, you should look into Annex H, which lets you to use pragma Restrictions() to selectively disallow access to parts of the Ada runtime. That allows you to get rid of things like floating-point, dynamic allocation, dynamic dispatch, tasking, exceptions/runtime constraint checks, etc.

A: I'm sorry, but this is a Bad Idea. If you want to avoid any possible overhead from tasking constructs, then don't use tasking! People often want to suppress constraint checking (which you can do in GNAT by compiling with -p) but - in my experience - you rarely get more than a small improvement.
Ada now has pragma Restrictions, which prevents you using certain features; you can see GNAT's here. The aims are to support production of high-integrity software, portable software, or efficient tasking runtimes.

A: That {'Pascal-like mode'} sounds like a implementation-specific pragma, unless I'm misunderstanding you.
Though there are the 'optimize[time or space] andrestriction` pragmas that might impact your final size.


text:
Q: SSL_ERROR_SYSCALL error when updating packages from git via composer Когда пытаюсь обновить модули с github через composer командой composer update выпадает ошибка error fatal: unable to access 'https: // ***************': OpenSSL SSL_connect: SSL_ERROR_SYSCALL in connection to proxy.pdsggg.com.ua:8080'
Данные полученные командой composer diag
Checking composer.json: WARNING
require.php-amqplib/php-amqplib : exact version constraints (2.7.0) should be avoided if the package follows semantic versioning
Checking platform settings: OK
Checking git settings: OK
Checking http connectivity to packagist: OK
Checking https connectivity to packagist: OK
Checking HTTP proxy: OK
Checking HTTP proxy support for request_fulluri: OK
Checking HTTPS proxy support for request_fulluri: OK
Checking github.com rate limit: OK
Checking disk free space: OK
Checking pubkeys:
Tags Public Key Fingerprint: 57815BA2 7E54DC31 7ECC7CC5 573090D0  87719BA6 8F3BB723 4E5D42D0 84A14642
Dev Public Key Fingerprint: 4AC45767 E5EC2265 2F0C1167 CBBB8A2B  0C708369 153E328C AD90147D AFE50952
OK
Checking composer version: You are not running the latest stable version, run composer self-update to update (1.10.7 => 2.0.9)
Composer version: 1.10.7
PHP version: 7.4.7
PHP binary path: D:\Users\fghf\php\php-7.4.7\php.exe
OpenSSL version: OpenSSL 1.1.1g  21 Apr 2020
С чем может быть связана эта ошибка?

A: Вопрос закрыт. В переменных среды ОС был прописан неправильный прокси сервер. Его удаление убрало ошибку.


text:
Q: Brock Allen MembershipReboot with SPA(Single Page Application) Breeze Application Authorization Redirect I have integrated MembershipReboot with a Breeze SPA application and the login and authorisztion work as expected. In the BreezeController.cs I have added the code below to capture an authorization failure.
[AttributeUsageAttribute(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class AuthorizeAttribute : System.Web.Http.Filters.AuthorizationFilterAttribute
    {

        public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            base.OnAuthorization(actionContext);

            ////check authentication and return if not authorized
            if (actionContext != null)
            {
                if (!actionContext.RequestContext.Principal.Identity.IsAuthenticated)
                {
                    actionContext.Response = actionContext.ControllerContext.Request.CreateResponse(System.Net.HttpStatusCode.Redirect);
                    System.Web.HttpContext.Current.Server.ClearError();
                    System.Web.HttpContext.Current.Response.Redirect("/UserAccount/Home",true);
                    //***********
                    //REDIRECT BEING CAUGHT BY ANGULAR ERROR HANDLER!!!
                    //**********
                    System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest();

                }

            }
        }
    }

The lack of Authorization is caught when the code below is called:
[System.Web.Http.HttpGet]
        [ValidateAntiForgeryToken]
        [Authorize]
        public string Metadata()
        {
            return _repository.Metadata;
        }
However the redirect code is being loaded into the Toast error handler and displayed as an error and the redirect is not working.
Any ideas how I can get the code to run as opposed to being loaded into the error screen?

A: Handle the failed promise and examine the error object. You should find the status code in there that tells you this is an authorization failure. Now redirect as appropriate for your app rather than reporting the error to screen.
I think I'd put this "interceptor" inside my "DataService"/"DataContext" abstraction so that all Breeze calls make use of it. Who know, you might extend the EntityManager with it. Haven't thought about it much.
You might want to share this "interceptor" with all of us when you get it working. The community loves contributions. :-)

A: I noticed app/config.exceptionHandler.js is trapping all my errors creating log errors. I have looked for exception 401 (unauthorised access) and if spotted called my login module.
The code is simply:
var app = angular.module('app');

// Configure by setting an optional string value for appErrorPrefix.
// Accessible via config.appErrorPrefix (via config value).

app.config(['$provide', function ($provide) {
    $provide.decorator('$exceptionHandler',
        ['$delegate', 'config', 'logger', extendExceptionHandler]);
}]);

// Extend the $exceptionHandler service to also display a toast.
function extendExceptionHandler($delegate, config, logger) {
    var appErrorPrefix = config.appErrorPrefix;
    var logError = logger.getLogFn('app', 'error');
    return function (exception, cause) {
        $delegate(exception, cause);
        if (exception.status == 401) {
            window.location.href = "/UserAccount/Home";
        }
        if (exception.message == "undefined") { return; }
        if (appErrorPrefix && exception.message.indexOf(appErrorPrefix) === 0) { return; }

        var errorData = { exception: exception, cause: cause };
        var msg = appErrorPrefix + exception.message;
        logError(msg, errorData, true);
    };
}

})();
The BreezeController.cs was modified to generate the 401 error like so:
[AttributeUsageAttribute(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class AuthorizeAttribute : System.Web.Http.Filters.AuthorizationFilterAttribute
{
    public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        base.OnAuthorization(actionContext);

        ////check authentication and return if not authorized
        if (actionContext != null)
        {
            if (!actionContext.RequestContext.Principal.Identity.IsAuthenticated)
            {
            actionContext.Response =
                new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized) { RequestMessage = actionContext.ControllerContext.Request };
            }
        }
    }
}

The entries in the controller were given the attributes [Authorize] to trap any unauthorized access like so:
    [System.Web.Http.HttpGet]
    [ValidateAntiForgeryToken]
    [Authorize]
    public string Metadata()
    {
    return _repository.Metadata;
    }

It might be dirty but it does the trick.


text:
Q: Reading file contents from another directory? I am trying to read the contents of a file in a subdirectory
here is my attempt :
$entityBody = "123456"
$vval= file_get_contents(__DIR__."/../data/names/$entityBody");
echo("$vval");

here is the directory outlook:

Issue: issue is when i run the script echo("$vval"); it doesnt echo anything on the screen.
what am I doing wrong ?

A: If you set
ini_set('display_errors', '1');
error_reporting(E_ALL);

In your PHP script you will see something like

PHP Warning:  file_get_contents(/var/www/html/myData/../data/names/123456):
Failed to open stream: No such file or directory

Now since both your PHP script and data dir are sharing the same __DIR__ you don't need ..
So
$vval = file_get_contents(__DIR__ . "/data/names/$entityBody");

Will solve the problem for you.


text:
Q: Replacing an id (integer) with a string? I have a tex document that contains sections that are automatically generated.  These sections have strings that are observation IDs.  I would like to have latex replace all occurrences of an ID with a string containing the star's name.
For example:
\caption{SED of \OID1342263516}

Would become:
\caption{SED of FR Tau}

My first thought was to have a macro, something like this:
\newcommand{\OID1342263516}{FR Tau}

However, I have learned that macros can't have numbers in their name.  Is there a good way to go about doing what I want?  Thanks.

A: It's with a bit of plain e-TeX to make it without the extra braces. The maximal value allowed here is 1073741823000, the minimal one is 1000 (or less if you make it at least 4 digits, I hope you fit in that. In can be extended by x digits, but only in case that all your numbers have at least x digits.
\documentclass{article}

\newcount\OIDcounta
\newcount\OIDcountb
\def\useOID{\csname OID\the\OIDcounta\the\OIDcountb\endcsname}
\protected\def\OID#1#2#3{\OIDcounta#1#2#3\afterassignment\useOID\OIDcountb}
\def\newOID#1#2{\expandafter\def\csname OID#1\endcsname{#2}}

\newOID{123456}{Tau 456 epsilon}

\begin{document}

\tableofcontents

\section{ABC \OID123456\ DEF}

Star number hundred twenty three is \OID123456\ for sure.

\typeout{\number\maxdimen}

\end{document}

If you're fine with the braces, then it's easy, and will work for even very large numbers (tens of digits):
\documentclass{article}

\makeatletter
\protected\def\OID#1{\@ifundefined{OID#1}{\GenericError{}{OID#1 not defined!}{}{}}{\csname OID#1\endcsname}}
\def\newOID#1#2{\expandafter\def\csname OID#1\endcsname{#2}}
\makeatother

\newOID{123456}{Tau 456 epsilon}

\begin{document}

\tableofcontents

\section{ABC \OID{123456} DEF}

Star number hundred twenty three is \OID{123456} for sure.

\end{document}


text:
Q: Can the wiki-edit reject algorithm be softened? Inspired by the Redesigned Tags Page blog post, I edited a bunch of previously blank or terse tag wiki over at Photo-SE.
Maybe I was a little obsessive, but I wrote about 25, most of which were accepted, and some of which were rejected. I'm not complaining about not having these contributions accepted per se, although it sure would be nice to have feedback on what wasn't liked, so I could clean it up and try again. (Or maybe we could have something a little more quorum-based?)
The issue, though: although I wasn't trying somehow "game the system" or being  malicious, I got stuck in the Reject Users list, so that if I try to edit a tag wiki, I get a bare white page with the text:

Too many of your edits were rejected, try again in 7 days.

Wow, really? This makes me kind of disinclined to contribute.
Could the algorithm be changed so that it is softened for higher-rep users? Or weighted by the number of accepted contributions?
Or should I just let someone else worry about the tag wikis?
Edit: part of the additional problem is that there were actually only three real edits rejected, but for two of them, I had edited both the excerpt and the tag wiki proper, so I got two rejects counted for each of them.
Edit: I've gotten the reply that the the tag wiki excerpts I propose are not good because they describe how to use the tag rather than defining the word. Please read the blog post linked above and also Should tag wikis answer the "what is this" question?

A: I don't mean to be harsh, but maybe the solution is to write better edits that don't get rejected? Take a break for a week, look at the accepted edits/tag wiki pages and see how you can make your rejected ones more like those.
I agree that it'd be nice to have feedback on rejections, though. It's hard to improve without knowing what was wrong in the first place.

Looking at the rejections in question, it sounds like the issue isn't the severity of the penalty, but rather the visibility and feedback given on approvals/rejections.

On sites that require at least two people to approve an edit, this is more or less taken care of. On sites where only one person is needed to reject an edit, we could require a reason... with the implication that if one can't think of a coherent reason to reject an edit, they should either approve it or leave it for another person to judge.

A: This edit describes suggested use for an unrelated tag that is a bad tag, IMO.
This edit looks OK, except that you are editorializing in the tag wiki excerpt about how the tag should be used. I much prefer the current version: https://photo.stackexchange.com/tags/photo-editing/info
To keep them clean, tag wiki excerpts should be confined to clear, terse descriptions of the tag only.  Elaborate descriptions of how the tag should be used can be placed in the tag wiki body, if necessary.
If a tag really needs this much explanation to be used properly, it should probably just be removed from the system.


text:
Q: Creating JSON string in AngularJS I want to create a JSON string in the following format as below using AngularJS:
{
    "userid": 100,
    "fleetid": 506,
    "comments": "This is a test comment",
    "fleetcheckdate": "29/10/1976",
    "options": [{
        "fleetcheckid": "1",
        "fleetcheckvalueid": "1"
    }, {
        "fleetcheckid": "2",
        "fleetcheckvalueid": "1"
    }, {
        "fleetcheckid": "3",
        "fleetcheckvalueid": "1"
    }]
}

Where

*

*"userid"

*"fleetid"

*"comments"

*"fleetcheckdate"

are all separate values know to me.
For "options" I have a multi-dimensional array that stores the values for "fleetcheckid" and "fleetcheckvalueid" that I create as follows:
$scope.selectedRadioArray = [];

$scope.doSomething = function(fleetCheckItemID, fleetCheckID)
{
    $scope.selectedIDS = [fleetCheckItemID, fleetCheckID];
    $scope.selectedRadioArray.push($scope.selectedIDS);
    console.log("Array: " + $scope.selectedRadioArray); // Prints e.g. 4,3,8,6,34,8
}

The doSomething() method is fired each time the user interacts with a button and this generates the 2 values "fleetcheckid" and "fleetcheckvalueid". In the example above the user has clicked the button 3 times. The button can be clicked any number of times.
How do I convert the information above into a JSON string as per the example that I can send to my Database via a $http.post()?

A: When sending information to the server via $http, it's generally a good idea to use JSON.  Don't convert it to a string.
Simply format your payload like this:
var payload = {
    userId: $scope.userId,
    /* etc.... */
    options: $scope.optionsArray
};

Then, when sending to the server, do this:
$http.post('path/to/api', payload, { headers: { /* etc... */ }}).then(successCallback).catch(errorCallback);

A: you can use in the $http someething like this
$http({
        url: uri,
        method: 'post',
        data: angular.toJson(categoria),
        headers: {
            'Authorization': 'Bearer ' + token.data.access_token,
            'Content-type': 'application/json'
        }
    }).then(function successCallback(response) {
        datosRecu = response;
        deferred.resolve(datosRecu);
    }, function errorCallback(response) {
        datosRecu = response;
        deferred.resolve(datosRecu);
    });

in this case `angularToJson` convert it on a JSON and send it in the body


text:
Q: In Reactjs, how to send and respond to user defined event? In reactjs, how to send user defined event? and response to user defined event? Can you please give an example? e.g. user.newItemAddToCart
Below code is example for responding standard DOM event.
var AddFriend = React.createClass({
  getInitialState: function(){
    return {
      newFriend: ''
    }
  },
  updateNewFriend: function(e){
    this.setState({
      newFriend: e.target.value
    });
  },
  handleAddNew: function(){
    this.props.addNew(this.state.newFriend);
    this.setState({
      newFriend: ''
    });
  },
  render: function(){
    return (

          <input type="text" value={this.state.newFriend} onChange={this.updateNewFriend} />
          <button onClick={this.handleAddNew}> Add Friend </button>
           does this work?

    );
  }
});


text:
Q: Finding all normal subgroups Stuck on finding the normal subgroups of the symmetry group of a cube. Trying to find 9 normal subgroups not too sure how to get the rest. Since I'm given 5 homomorphisms and I know the kernel of a homomorphism is a normal subgroup, I've identified.

*

*ker($\phi$)

*ker($det$)

*ker($p$)

*ker($q$)

*ker($f$)

Now for 6, 7, 8 and 9. I know if H and K are normal subgroups, HK is.
So,

*$HK$ where $H = \operatorname{ker}(\phi)$ and $K = \operatorname{ker}(p)$

*$HK$ where $H = \operatorname{ker}(p)$ and $K = \operatorname{ker}(\phi)$

*$HK$ where $H  = \operatorname{ker}(det)$ and $K = \operatorname{ker}(\phi)$

*$HK$ where $H  = \operatorname{ker}(det)$ and $K = \operatorname{ker}(p)$
Now while this is what I got, I'm skeptical if I really approached this right. Would appreciate any assistance. Especially because I have to organize this in a lattice after and if the subgroups are wrong, all the subsequent questions are wrong.

A: As an addition to my other answer as well as the various comments, here's a drawing of the lattice of normal subgroups of the group $S(C))$:

Note that the three maximal normal subgroups intersect in a normal subgroup of order $12$ (which is, by the way, isomorphic to an $A_4$), and the intersection of that subgroup with $\ker(\phi)$ is an elementary abelian group of order $4$.

A: Just a few hints:
First of all, there are two trivially normal subgroups, namely $1$ and the group $S(C)$ itself.
Second, since (as the comment indicates) $f$ is an automorphism of $S(C)$, its kernel is trivial.
Third, it is a good idea to compute the orders of $\ker(\phi)$, $\ker(\det)$, $\ker(p)$ and $\ker(q)$.
Fourth: Show that $\ker(\phi)\le\ker(p)$ and that $\ker(\det)\cap\ker(p)\le\ker(q)$. What is the order of $\ker(\det)\cap\ker(p)$? Can you construct another nontrivial normal subgroup which involves $\ker(\det)\cap\ker(p)$?
And finally: What does $Z(S(C))$ look like?


text:
Q: Issue getting a Date from a query stored to a Variable im having an issue with a date that im getting from a sql query and storing in variable.
<?php
$data=mysqli_query($mysqli,"SELECT fe_ultima_act, DATE(fe_ultima_act) AS fecha FROM t012_caso WHERE estatus='cerrado' AND grupo_soporte='primer nivel' AND fuente='telefono' AND (SELECT MAX(fe_ultima_act) FROM t012_caso) GROUP BY WEEK(fe_ultima_act) DESC");
?>
var semanas1= [<?php
while($info=mysqli_fetch_array($data))
    echo ''.$info['fecha'].','; /* */
?>];

So if a run the query in the mysql console, i get a results like this "2015-04-20" and so on. But when it get stored in the var semanas1 is a value "1991"; Its actually making a subtraction of 2015 minus 04 minus 20.
How can i avoid that? i want to store the date like "2015-04-20".
Thank you in advance for any suggestions.

A: That's because you're dumping PHP's output into another language.
e.g.
<?php
$foo = '1-2-3-4';
?>
var semanas1 = <?php echo $foo; ?>

when the above code is executed on the server and output to the client, the client only sees the OUTPUT of the code:
var semanas1 = 1-2-3-4;

That's just plain mathematical subtraction as far as Javascript is concerned. In other words, you have to generate output in PHP that's semantically correct for the environment PHP's output is going into. I'm guessing that's javascript, so you'd need something more like:
var semanas1 = ['<?php echo ... ?>'];
                ^-----------------^---note the quotes

or
var semanas1 = [<?php echo json_encode($date_string) ?>];

note the usage of json_encode, which guarantees that whatever comes out of php will be proper javascript.
Both of those would generate
var semanas1 = ['1-2-3-4'];


text:
Q: System.Windows.Forms.Timer in windows server Could someone please provide me with an example on how to use the System.Windows.Forms.Timer in a windows service. The timer should 'invoke' a non-static windows service method every 10 seconds. I have (unsuccessfully) tried this in my OnStart method:
_timer.Tick += new EventHandler(StartProcessingItems);
_timer.Interval = 10000;
_timer.Enabled = true;
_timer.Start();

Here StartProcessingItems is my on-static windows service method.

A: use instead System.Threading.Timer:
var t = new Timer(o =>
{
   Console.WriteLine("Hello from the past! " + (DateTime)o);
}, DateTime.Now, TimeSpan.FromSeconds(10), TimeSpan.FromMinutes(1));

It will execute the delegate 10s after, and then with a frequency of 1min
http://msdn.microsoft.com/fr-fr/library/system.threading.timer%28v=vs.80%29.aspx


text:
Q: Lot of pages under one node sitecore We have a requirement of storing 1000 location pages under one location folder in sitecore. I was looking best practice/suggestion of implementing.
Thinking of item buckets. but not sure how far it is feasible for content authors to design the page. Note, these location pages are not consistent in design. they often based on the location.

A: Best practice in Sitecore no more than 100 items per folder.
What often works well is a folder structure
Example: continent/country/{location}
or something alphabetical or by year/month.
A bucket can easy hold 1000+ item in Sitecore.
But a folder structure is automatically created that also ends up in the url.
so if it about the url should be location/{name} for all the items.
you need add a custom httpRequestBegin pipeline processor see:
https://sitecore.stackexchange.com/questions/9812/are-items-converted-to-bucket-items-still-accessible-via-the-original-path/9814
One more thing to mention a wildcard url can also work, if all have the same layout. See
https://doc.sitecore.com/en/users/102/sitecore-experience-platform/create-a-dynamic-url-with-a-wildcard-item.html


text:
Q: How does Microsoft Office doesn't require .NET 3.5 or 4.5, while VSTO addins require them? When building any addin (in Visual Studio) for Microsoft Office, we have to choose the target .NET FRAMEWORK.
Actually, on several PCs, where I've installed MS OFFICE 2010 it required neither .NET 3.5 nor 4.5. However, while trying to install my add-in on that same PC, it requests .NET.
Is it not possible to make the addin to work like MS-OFFICE works (without requesting the .NET framework) ?

A: To answer the stated question:

How does Microsoft Office doesn't require .NET 3.5 or 4.5, while VSTO
  addins require them?

Microsoft Office is COM-based and written using C-languages (C, C+, C++, but not C#), so the .NET Framework is not required. Office pre-dates .NET by more than a decade!
If you develop an Add-in using Visual Studio .NET then it will require the version of the .NET Framework selected for the .NET project to be installed on the  machine. This is the case with VSTO, for example.
Classic VB6 used to be a common tool for creating Office Add-ins. It didn't require .NET because it was a COM programming language - and that's why it wasn't maintained or updated so that its programs could run on more recent versions of Windows (64-bit). So it's fallen into disuse.
Any programming language that can leverage the IDTExtesibility2 Interface that builds the basis of Office COM Add-ins can (in theory, at least) be used to write a COM Add-in for Office. It's necessary to research and understand that Interface, as well as how the chosen programming language relates to the Windows COM environment, in order to program an Office Add-in.
Microsoft Add-ins of the type you're thinking about canNOT be developed using VBA (as has been suggested in a comment) - VBA must run in a host application and is contained in a document belonging to the host application. VBA is able to automate other Office applications, but this does not qualify as an Add-in. In most Office applications VBA can be used as an "add-in" for that application by loading the code-container document in a certain manner, making the code available to all files opened in the Office application.


text:
Q: What happened to "order by: interesting"? My normal mode of visiting the site is to refresh the start page and scroll down looking for interesting questions.
This has degraded significantly recently, and the reason seems to be that the start page has reverted to "order by: new" when previously I had it set to "order by: interesting". The dropdown no longer offers this option.

Why was it removed? Could it be brought back?
(Do my search skills suck? I could only find questions about interesting tags, and then Interesting questions on top from 2010.)

A: Did you accidentally end up on stackoverflow.com/questions instead of just stackoverflow.com?
The former has a "newest" sort order tab while the latter doesn't. The latter has the "interesting" sort order that is deliberately missing from the /questions page but that otherwise still exists.


text:
Q: How to confirm Apple ID on Apple TV without iOS16 device I have to confirm an Apple ID on my Apple TV. However, the only option it gives me is with an iOS16 (or iPadOS16) device. The Apple ID is only available on an iPhone 7 which has no iOS16. Is there any other option to confirm this Apple ID?
Best


text:
Q: How to sum data without group by in mysql I want to do sum of number_of_count data based on body_corporate field, here i have put my query, here i have put my result of data
userid body_corporate number_of_count
 1     bodycorporate1     1
 1     bodycorporate1     5
 0     Unassigned        732

SELECT
    IF(tblclients.userid IS NULL,
        0,
        tblclients.userid) AS userid,
    IF(tblmeter.body_corporate_id IS NULL,
        'Unassigned',
        tblclients.company) AS body_corporate,
    COUNT(DISTINCT tbltransactions.description) AS number_of_count,
    SUM(IF(tbltransactions.post_type = 'Collection',
        tbltransactions.transaction_amount,
        0)) AS total_sales,
    IF(tblmeter.body_corporate_id IS NULL,
        0,
        tblclients.commission) AS commision,
    (SUM(IF(tbltransactions.post_type = 'Collection',
        tbltransactions.transaction_amount,
        0) * IF(tblmeter.body_corporate_id IS NULL,
        0,
        tblclients.commission)) / 100) AS totalCommission,
    CONCAT(MONTHNAME(tbltransactions.date_time),
            '-',
            YEAR(tbltransactions.date_time)) AS billing_period
FROM
    tbltransactions
        LEFT JOIN
    tblmeter ON tblmeter.id = tbltransactions.meter_id
        LEFT JOIN
    tblclients ON tblclients.userid = tblmeter.body_corporate_id
GROUP BY tblmeter.body_corporate_id , YEAR(tbltransactions.date_time) , MONTH(tbltransactions.date_time)
ORDER BY IF(tblclients.userid IS NULL,
    0,
    tblclients.userid) DESC
LIMIT 0 , 25

i want result like this
userid body_corporate number_of_count
     1     bodycorporate1     6
     1     bodycorporate1     6
     0     Unassigned        732

can anyone please help me how to get this output ?

A: Start from MySQL 8 you can use window function SUM() OVER ():
SELECT
    userid,
    body_corporate,
    SUM(number_of_count) OVER(PARTITION BY body_corporate) AS s
FROM
    test;

For previous DB version GROUP BY & JOIN can be used:
SELECT
    test.userid,
    test.body_corporate,
    summary.number_of_count
FROM
    test
JOIN (
    SELECT
        body_corporate,
        SUM(number_of_count) AS number_of_count
    FROM test
    GROUP BY body_corporate
) AS summary ON summary.body_corporate = test.body_corporate;

See SQL example db<>fiddle


text:
Q: Question about Birthday Problem My first intuition was to think $P(\{\text{No two bdays coincide}\}) = \displaystyle{\frac{\binom{365}{n}}{365}}$ given $365 \ge n$. Turns out $P(\{\text{No two bdays coincide}\}) = \displaystyle{\frac{365 \cdot 364 \cdots (365 - n + 1)}{365^n}}$. Why is it important we line up the people instead of simply dealing with subsets? What do we undercount when we solve this problem according to my initial intuition? Thanks.
Edit: Came here to understand the combinatorial reasoning behind the question, but I got a much better (obviously, personal opinion) answer based on probabilistic reasoning. That answer might be beneficial to future students struggling to grok the classical solution to this problem. Here it is below:
Let $A_i$ be an event where the $i$th person shares bday with none of the $n−1$ people. Then we have $P(\bigcap_{i-1}^n A_i) = P(A_1)P(A_2\mid A_1)P(A_3\mid A_1, A_2)\cdots P(A_n\mid A_1,\ldots A_{n-1}) = \frac{365}{365} \cdot \frac{364}{365} \cdots \frac{365 - n + 1}{365}$


text:
Q: Entity Framework 6.1 RTM Licensing We upgraded our project to EF 6.1 because there was a serious query bug in 6.0 and now we are nearing our production release date and EF 6.1 is still RTM.  I was gambling that EF 6.1 would hit full release before we did, and I lost.
Am I allowed to release my application using EF 6.1 RTM?  Are there any licensing considerations I need to be aware of since it is RTM and not fully released?

A: This is the official information about EF licensing at codeplex:
https://entityframework.codeplex.com/license


text:
Q: Grid Renderers updating without updateDisplayList being called I have an item renderer for a grid that has a fairly basic updateDisplayList function:
override protected function updateDisplayList( w : Number, h : Number ) : void
{
    super.updateDisplayList( w, h );

    var labelWidth : Number = Math.min( _labelDisplay.measuredWidth, w );
    var labelHeight : Number = Math.min( _labelDisplay.measuredHeight, h );

    _labelDisplay.setActualSize( labelWidth, labelHeight );

    var labelX : Number = ( w - _labelDisplay.width ) / 2;
    var labelY : Number = ( h - _labelDisplay.height ) / 2;

    _labelDisplay.move( labelX, labelY );

    //this is just for debugging
    graphics.clear();
    graphics.beginFill( 0xFF0000, 0.5 );
    graphics.drawRect( labelX, labelY, labelWidth, labelHeight );
    graphics.endFill();
}

where _labelDisplay is a spark label. When I scroll the grid (this is a cuatom grid, not mx:Grid or AndvancedDataGrid) when new rows appear at the bottom of the grid updateDisplayList is called and the code to re-draw the background and move / resize the label executes.
The problem is that these chanegs are not reflected in the view. The text is mis-aligned as a label that used to display a large string now displays a short string so the measuredWidth has changed.
The next time I scroll the renders update to look like they should - but updateDisplayList is NOT called here (on the renderes). All that happens is that the renderers are re-positioned in the grid.
Both the background and the label are displayed incorrectly initially so it's not just the label mis-behaving.
Anyone got any idea why this is happening?
Thanks

A: Just a guess, but does this make any difference?
override protected function updateDisplayList( w : Number, h : Number ) : void
{
    var labelWidth : Number = Math.min( _labelDisplay.measuredWidth, w );
    var labelHeight : Number = Math.min( _labelDisplay.measuredHeight, h );

    _labelDisplay.setActualSize( labelWidth, labelHeight );

    var labelX : Number = ( w - _labelDisplay.width ) / 2;
    var labelY : Number = ( h - _labelDisplay.height ) / 2;

    _labelDisplay.move( labelX, labelY );

   super.updateDisplayList( w, h ); // Call updateDisplayList after moving / resizing _labelDisplay
}


text:
Q: n-tier architecture solution. How better? I need to create n-tier application with the following parts:

*

*Data server

*Business logic server

*Lightweight client with custom features for each customer

Data server(1) and l/w client(3) will be placed on customer server.
Application will be as service and all business logic(2) will work on my servers.
That is simple, yes. But! Data server owned by customer and data is secret for each customer. I can't hold data on my servers, but i want to publish lightweight clients on customer's side. All clients from all customers will use the same business logic from my server.
Question is:
How can i connect clients(3) with business logic(2) and protect the data to be transferred from customers?
My first solution is VPN or SSH tunnel, but may be there is another way?
Or may be another approach.
Also data transfer between data server and business logic server may be so slow, that because i'm trying to find another approach for this architecture.
Thanks!

A: I think you are mixing two things here:
-The architecture: I think you'd better google "Multi-Tenant application" designs as this matches the description of your system.
-Security concerns: If this is a web application (which I think it is as you mentioned lightweight) you're better off with a SSL certificate which encrypts all traffic to/from your server by using HTTPS. If that is not applicable, you can chose SSH or VPN as they have almost the same requirements and affect the application the same.


text:
Q: Spring controller - send html as response I have a loaded jsp page with products and addtocart link against it. I am trying to show the cart in a div in the same page. I want to send html as response. This is what i have done. It just returns the string
output
. Can someone show me how i should do it.
Controller
    @RequestMapping(value="/addtocart{id}",  produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String addToCart(@PathVariable("id") int id, @ModelAttribute("cart") Cart cart,Model model)
    {
        Product product = productService.getProductById(id);
        if (product != null) {
            CartLine line = new CartLine();
            line.setProduct(product);
            line.setQuantity(1);
            productService.updateProduct(product);
        }
        return "
output
";
    }

JSP
Add To Cart

$('#demo4').click(function() {

                $.ajax({
                url : '/addtocart{id}',
                dataType: 'json',
                contentType: "text/html",
                type : 'GET',
                data :{id:id},
                success : function(response) {
                    $('#output').html(response);
                   }
                 });
        });

Cart Content(s):

A: I also favor the approach with using the view, and separate page even on ajax call. Nevertheless what you're asking is possible, simply change your  produces = "text/plain;charset=UTF-8" to produces
produces = "text/html;charset=UTF-8"

There are many other aspects that appear wrong, not related to Spring MVC, so even with the produces corrected you still have to do few corrections to get what you're expecting.

*

*I think that you're not sending an ajax call at all. You're most likely doing a complete browser redirect. When first read, I was confused that "text/plain" vs "text/html" makes a difference in an ajax response, but now I believe that you're actually redirecting via browser. Change this Add To Cart into something like this Add To Cart and add return false to the end of your function. This will execute the function, and the return will make sure that the link is not followed

*When you do this you'll notice a few issues with your ajax call as well; firstly, url : '/addtocart{id}' should be  url : '/addtocart${product.id}

*Capture your response in complete function not in success, and get the output as response.responseText, the response will return fine, but the browser will attempt to parse it as json and fail.

*Your div will remain invisible, you should add some js to toggle that

*One Spring MVC gotcha, your Cart bean seems to have a property called id as well. Because of this, your id path variable should be renamed, otherwise it'll be ignored
This would be something that, if not completly, than much closer to working
Add To Cart

Renaming PathVariable
@RequestMapping(value="/addtocart{productId}",  produces = "text/plain;charset=UTF-8")
public String addToCart(@PathVariable("productId") int productId, @ModelAttribute("cart") Cart cart,Model model)

A: You can do it with AJAX and still return a separate page for your Card, as Slava suggested.
JSP page cart.jsp:
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

${cart.headline}

${cart.otherProperty}

Controller:
@RequestMapping(value="/addtocart{id}")
public String addToCart(@PathVariable("id") int id, @ModelAttribute("cart") Cart cart, Model model) {
    doSomethingWithCart(cart);

    model.addAttribute("cart", cart); // add cart to model after doing some custom operations
    return "cart"; // resolved to cart.jsp by your view resolver
}

This way you are using AJAX but still you are returning dynamic html content (
   adjusted to one specific cart).


text:
Q: Directus headless CMS - Display attributes from 3rd table in dropdown One-To-Many
Table A = {Student_ID,Student_Name}, Table B = {Teacher_ID,Teacher_Name}, Table C = {Relationship_ID,Student_ID,Teacher_ID}

Table C captures a relationship between A and B and therefore has a many-to-one relationship with both Table A and B. Here we create a visible drop down column with the names of the students and teachers
When creating a table D which has a many-to-one relationship with table C, how can we create a visible drop down column that captures the relationship from table C but with the student- and teacher names when it's not contained in table C?

A: A great question. Which version of Directus are you using?
This was a bit more complex in v6.x and required some custom code I think. But in the new v7 (which is in RC.3 right now and will be released in the next few days) you can accomplish it with dot notation.
v7: In the options of the dropdown, you can choose what data to make visible. If it is not a field on the actual item, then you can reference the relational data like this: actual-field.related-field-to-show
Using this method you can go as deep as you need: eg root.level-1.level-2 ... but the more complex and deeper the data, the more time it will take to fetch.


text:
Q: Find Intersection Of 2 Sub-spaces $U=span((1,1 ,0),(2 ,0 ,1))$ $W=span((1,1,1),(5,3,1))$
what is $U \cap W$?
can I find the rref of them both and to find the intersections? that mean
$U= \begin{pmatrix}
1 & 0 & 0.5 \\
0 & 1 & -0.5
\end{pmatrix}$
$W= \begin{pmatrix}
1 & 0 & -1 \\
0 & 1 & 2
\end{pmatrix}$
so is $U \cap W$=$Span \begin{pmatrix}
1 & 0 & 0 \\
0 & 1 & 0
\end{pmatrix}$

A: Well, $U \cap W$ is the space consisting of all vectors that can be formed both as a linear combination of the elements of U and V. So, for any $\vec v \in U \cap W$: $$ \vec v = c_1 (1, 1, 0) + c_2 (2, 0, 1) $$ and
$$ \vec v = d_1(1, 1, 1) + d_2(5, 3, 1)$$
where $c_1, c_2, d_1, d_2 \in \mathbb{R}$. Does that help?

A: From the rrefs you calculated, you know that $\dim U=2$ and $\dim V=2$. (And this can be also seen without calculating rref: We have only two vectors generating a subspace, and neither of these vectors is a multiple of the other one, so they are linearly independent.)
If you make rref from the matrix containing all four vectors, you will find out, that $\dim(U+V)=3$.
$$\begin{pmatrix}
1 & 0 & \frac12\\
0 & 1 & -\frac12\\
1 & 0 & -1\\
0 & 1 & 2
\end{pmatrix}\sim
\begin{pmatrix}
1 & 0 & 0\\
0 & 1 & 0\\
0 & 0 & 1\\
0 & 0 & 0
\end{pmatrix}
$$
So from the formula $\dim(U)+\dim(V)=\dim(U+V)-\dim(U\cap V)$ we can calculate
$$\dim(U\cap V)=1.$$
So the intersection is generated by single vector.
If we notice that
$$(5,3,1)=5(1,0,\frac12)+3(0,1,-\frac12) = 3(1,1,0)+(2,0,1)$$
then we see that the vector $(5,3,1)$ belongs to both $U$ and $V$, i.e., $(5,3,1)\in U\cap V$.
So now, without any other calculations, we can say that
$$U\cap V = \operatorname{span}\{(5,3,1)\}$$

However, in this case we were simply lucky that we only needed one vector and we were able to guess a vector which belongs to both given subspaces.
If we want to avoid guesswork, a reasonable way to go is to solve a system of equations as suggested in Toxicz's answer.


text:
Q: ASP.NET MVC retain query parameter across all requests For development purposes, I want to always retain a certain query parameter on every single URL request if the hostname is localhost.
So for example if I have: http://localhost:12345/Home?myParam=myVal, then for every single request, I want to append the myParam=myVal onto the querystring if the hostname == "localhost".
Is there a way in my BaseController class to preserve this parameter?  The reason I want to do this is so that after the developer rebuilds the project, since the FormsAuthentication is still active (which is a good thing), I want to also retain this parameter.
Thanks.

A: Custom Route class
That's the answer. Inherit from existing Route class and change your GetVirtualPath according to your needs (append parameter).
IN case you don't want your users to see/change the query value you should rather change the GetRouteData method and append your custom value (as always the same) when request comes from localhost.


text:
Q: Support for DEVPATH I have a question about support for DEVPATH (http://msdn.microsoft.com/en-us/library/cskzh7h6.aspx) in the future. As I have read Microsoft considered deprecating it in the past but decided not to. Do you know if there are plans of deprecating it in .NET 4.0 or further? Or is it going to be supported?
Thank You
Kuzu

A: This came up on a course I did with Wintellect recently, who have quite close links with MS. Apparently no, there's no longer plans to deprecate it as it's too useful for development purposes.
Link to John Robbins' recent blog article mentioning it (about 2/3 of the way through).

By the way, if you search for DEVPATH in any internet search engine one of the top entries
  is an out of date blog entry by Suzanne Cook saying Microsoft was getting rid of DEVPATH. That is no longer true. As with any blog entry, look at the date on Suzanne's blog: 2003. That's the equivalent of 1670 in internet years.


text:
Q: Activity Change with OnGestureListener (GestureDetector) I have a Question.is that possible. Can we do with ongesturelistener event other activity change.
if so, how can i make.
I was thinking how to change the view flipper pictures
But i will activity change
Thanks
I've done, maybe someone needs also
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
        float velocityY) {
    try {
        if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
            return false;
        // recht zur links swipe
        if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
                && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
             startActivity(new Intent("de.blalbla.blalbla.BLALBLALALB")); // package name and action name
            // links zur recht swipe
        } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
                && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
            //other action
        }
    } catch (Exception e) {
        // nothing
    }

    return true;
}


text:
Q: Xunit Debug is Flaky I'm using Xunit for my unit tests. The application is using ASP.NET Core. I noticed some strange behaviors when I debug:

*

*Variables in the actual method (not the test method) shows null when it is not supposed to, and it has values after a while of debugging

*Another example is when debugged in the if statement, even though the if condition is return false, which means it shouldn't go inside the if statement, the debugger still goes inside..

*When the break point hits the helper method, it immediately ignores the helper method and jump to the next line. But it goes back to that helper method after a while.
Here's the dependencies of the unit tests project.

Does anyone see this behavior before?

A: I figured out the issue. It is because the runsettings.json file contains some attributes that could break the debugger. Removing the following code works for me.
 <DataCollector friendlyName="Code Coverage" uri="datacollector://Microsoft/CodeCoverage/2.0" assemblyQualifiedName="Microsoft.VisualStudio.Coverage.DynamicCoverageDataCollector, Microsoft.VisualStudio.TraceCollector, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
</DataCollector>


text:
Q: Advantage of Bootstrapping Confidence Intervals over Standard Error I want to compare means from samples of varying size, plug them into a bar graph and have appropriate values to plug in for the error bars. My sample sizes are:
A = 1
B = 3
C = 14
D = 7
E = 13
F = 190
G = 33

I intended to use the typical standard error calculation
Standard Error = Standard Deviation/number of sample^1/2

but because many of my samples are so small, a colleague suggested I use bootstrapping to compute confidence intervals instead. He's smarter than me so I found some software that did that (scikits.bootstrap==0.3.1 for python in a pandas environment), computed my bootstrapping confidence intervals and used them to put error bars on my graph.
What I want to know is WHY exactly bootstrapping is more appropriate than standard error in this case? I understand that bootstrapping works by creating many alternative versions of your sample by sampling-with-replacement and computing some descriptive statistics on that large population of hypothetical samples but I don't understand when and why you should use it instead of using the standard error.
NOTE: I'm not applying these calculations to sample A because its just a single value; I'm actually dismissing it from consideration. I only included it here because it was easier to copy and paste the whole list rather than remove A and change all the letters

A: With your small samples, your estimate of standard deviation will be very biased (low). With bootstrapping, you can approximate the sampling distribution of your estimators by treating your sample as an approximation of the true distribution of your data. The more samples you have, the closer your empirical distribution will be to the actual distribution, hence allowing ever more accurate error estimates.
That is why boostrapping works. The standard deviation approach only works when you know the true standard deviation and the distribution of the estimator is approximately normal. Boostrapping is just monte carlo simulation using your data as the input distribution, and so the more representative your sample, the better your inferences.
Also, I would highly recommend a parametric boostrap for samples <20 points. This requires assuming some underlying distribution for your data and then simulating boostrap samples from the fitted distribution. If your data are strictly positive, then try a lognormal, if they can be both positive and negative, try the normal distribution.


text:
Q: Java - Find a process responsible for editing a file & kill it if possible? I've been working on Java's WatchService API to monitor a file directory to see when files have been modified within it. (On Windows). I've got it so that I can see when files are modified.
How can I see which process is responsible for file modification, and kill the process, even perhaps create a dump file too?


text:
Q: Sed substitution with back reference not working I receive output from a program as tab separated values, of which I am trying to obtain the second only using sed. I am currently using this:
sed -r -e "s/(^[^\t]+\t)([^\t]+\t)(.*$)/\2/"

However it does not seem to find matches. I have tried it in rubular were it does give me the match I want.

A: There is a specialized tool for selecting columns from text files called cut:
cut -f2 file

Here we instruct it to select only the second column, see the manpage for more information. Tab is the default column separator.


text:
Q: Post data to API with React JS I am new at React and trying to post data to some API but I can't manage to do that. This is the way I tried
import React, { Component } from "react";

class Apinew extends Component {
  constructor() {
    super();
    this.state = {
      id: '',
      name: '',
      quote: '',
      created_on: ''
    };
  }
  change = e => {
    this.setState({
      [e.target.name]: e.target.value
    });
  };
  onSubmit = e => {
    e.preventDefault();
    console.log(this.state);

    fetch('someAPI', {
      method: 'post',
      headers: { 'Content-Type': 'application/json' },
      body: {
        id: this.id.value,
        text: this.quote.value,
        author: this.name.value,
        created_on: this.createdOn.value
      }
    });
  };
  render() {
    return (

        <form>
          <input
            name="id"
            ref={ref => {
              this.id = ref;
            }}
            placeholder="Enter ID"
            value={this.state.id}
            onChange={e => this.change(e)}
          />

          <input
            name="name"
            ref={ref => {
              this.name = ref;
            }}
            placeholder="Enter Name"
            value={this.state.name}
            onChange={e => this.change(e)}
          />

          <input
            name="quote"
            ref={ref => {
              this.quote = ref;
            }}
            placeholder="Enter Quote"
            value={this.state.quote}
            onChange={e => this.change(e)}
          />

          <input
            name="created_on"
            ref={ref => {
              this.createdOn = ref;
            }}
            placeholder="Created On"
            value={this.state.created_on}
            onChange={e => this.change(e)}
          />

          <button onClick={e => this.onSubmit(e)}>Submit</button>
        </form>

    );
  }
}

export default Apinew;

and I am getting this error:

OPTIONS someAPI 405 (Method Not Allowed)
Failed to load someAPI: Response for preflight has invalid HTTP
  status code 405.
Uncaught (in promise) TypeError: Failed to fetch

What is the problem? What should I do?
Thanks

A: First you should understand that 405 error means :

The HyperText Transfer Protocol (HTTP) 405 Method Not Allowed response
  status code indicates that the request method is known by the server
  but has been disabled and cannot be used.

There is probably nothing wrong with your fetch call, however you must look at the api requirement, maybe you lack of permissions but it is most likely the method is private and thus cannot be used.


text:
Q: Mysql : reset id start from 1 if day change I make an unique id, which contain of CURRENT_DATE and character like :
SELECT CONCAT(DATE_FORMAT(CURRENT_DATE,'%Y%m%d'),'Q',
      LPAD(MAX(RIGHT(idreport,3))+1,3,'0'))
FROM record.report

result :
20140723Q001

I want every day it start from 001. So, if the query above is correct I would get result like 20140724Q001 today. But I get a wrong result 20140724Q002.
How to reset 3 digit behind the id if the day change?

complete syntax :
$sql="SELECT CONCAT(DATE_FORMAT(CURRENT_DATE,'%Y%m%d'),'Q',LPAD(MAX(RIGHT(idreport,3))+1,3,'0'))
                FROM record.report";
  $res=mysql_query($sql) or _doError(_ERROR30 . ' (' . htmlspecialchars($sql) . '): ' . mysql_error() );
  $dat1=mysql_fetch_array($res, MYSQL_NUM);
  if($dat1 == 0){
        $sql = "SELECT DATE_FORMAT(CURRENT_DATE,'%Y%m%d')";
        $res1=mysql_query($sql) or _doError(_ERROR30 . ' (' . htmlspecialchars($sql) . '): ' . mysql_error() );
        $dat2=mysql_fetch_array($res1, MYSQL_NUM);
        // first number
        $RegNum = $dat2[0]."Q001";
        } else {
                $RegNum = $dat1[0];
                }

A: Although we can have a more optimized solution, this should do your job-
SELECT CONCAT(DATE_FORMAT(CURRENT_DATE,'%Y%m%d'),'Q',
      LPAD(MAX(RIGHT(CASE WHEN LEFT(idreport,8)=DATE_FORMAT(CURRENT_DATE,'%Y%m%d') THEN idreport ELSE '000' END,3))+1,3,'0'))
FROM record.report;

Incase any query, please let me know.


text:
Q: Grabbing a reference to the element closest to scrollTop I'm wondering how to grab a reference to whatever DOM node happens to be closest to document.body.scrollTop at any given time.
Let's say I had 10 paragraphs inside a div, and the scrollTop at 400px is on p child 5.
I want to store that information and return the user to that paragraph when they come back. Of course I could simply reset the scrollTop to a given value, but if the browser is resized or the orientation is changed, this isn't a reliable method (and media queries might alter the size of elements).
However, if I could store the value of the node at the top, I can use .scrollIntoView() and be sure the user is in the correct location.
Any thoughts?
Thank you.

A: Easy enough if you know the document structure. To continue your example:
// div is the parent <div> element
var el, top, min = Number.MAX_VALUE, els = div.getElementByTagName('p');
for (var i=0; i<els.length; i++) {
    top = Math.abs(els[i].getBoundingClientRect().top);
    if (top < min) {
        min = top;
        el = els[i];
    }
}

// el now holds the <p> whose top is closest to the top of the window


text:
Q: Using a class constructor to handle images tkinter Hi i'm trying to create a class constructor to handle images in tkinter, since i'll be using many images in my code so I need a way to use images without using so much line of code.
I keep getting the error:
   return _modes[mode]
KeyError: 'picture.png'

Here's the code:
from tkinter import *
import tkinter
from random import randint

from PIL import Image
from PIL import ImageTk

root = tkinter.Tk()
root.geometry('700x700')

class PhotoHandler:
    def __init__(self,imagepath):
        self.imagepath = imagepath
        self.image = Image.open(self.imagepath)
        self.image = ImageTk.PhotoImage(self.imagepath)

    def returnn(self):
        return self.image

search = PhotoHandler('picture.png').returnn()

root.mainloop()

A: You passed a string to the tkinter image. It expects a PIL image or mode. Since you passed a string, it thinks you're using an invalid mode. Pass the image instead:
class PhotoHandler:
    def __init__(self,imagepath):
        self.imagepath = imagepath
        self.image = Image.open(self.imagepath)
        self.image = ImageTk.PhotoImage(self.image)

    def returnn(self):
        return self.image

search = PhotoHandler('picture.png').returnn()

# add label for background image
background_label = tkinter.Label(root, image=search)
background_label.place(x=0, y=0, relwidth=1, relheight=1)

root.mainloop()

Here's the documentation:
https://pillow.readthedocs.io/en/4.2.x/reference/ImageTk.html


text:
Q: ANTLR ERROR : The following token definitions can never be matched because prior tokens match the same input I am new to ANTLR and I am trying the following .From the error it seems that I am defining something generic and the rule below it is unreachable/redundant.Redundant ones the ANTLR complains about is  MAPPING,STROPS,UNARYOPS,ARITHEMATICOPS,MATHLOGICALOP,LOGICALOP,OP1,OP2,OP3,OP4 .I don't understand where exactly am I going wrong. Please let me know the issue and the concept behind it.
 grammar RA;

options {
  language = Java;
  output = AST;
  k=3;
}

DIVIDE : '/';
PLUS : '+';
MINUS : '-';
STAR : '*';
MOD : '%';
LPAREN : '(';
RPAREN : ')';
COMMA : ',';
COLON : ':';
LANGLEBRACKET : '<';
RANGLEBRACKET : '>';
EQ : '=';
NOT : '!';
UNDERSCORE : '_';
DOT : '.';
GRTRTHANEQTO : RANGLEBRACKET EQ;
LESSTHANEQTO : LANGLEBRACKET EQ;
NOTEQ         : NOT EQ;

fragment A:('a'|'A');
fragment B:('b'|'B');
fragment C:('c'|'C');
fragment D:('d'|'D');
fragment E:('e'|'E');
fragment F:('f'|'F');
fragment G:('g'|'G');
fragment H:('h'|'H');
fragment I:('i'|'I');
fragment J:('j'|'J');
fragment K:('k'|'K');
fragment L:('l'|'L');
fragment M:('m'|'M');
fragment N:('n'|'N');
fragment O:('o'|'O');
fragment P:('p'|'P');
fragment Q:('q'|'Q');
fragment R:('r'|'R');
fragment S:('s'|'S');
fragment T:('t'|'T');
fragment U:('u'|'U');
fragment V:('v'|'V');
fragment W:('w'|'W');
fragment X:('x'|'X');
fragment Y:('y'|'Y');
fragment Z:('z'|'Z');

AND     :   A N D;
OR      :   O R;
COUNT       :   C O U N T;
AVG     :   A V G;
COUNTDISTINCT   :   C O U N T D ;
CAST        :   C A S T;
CORRESPONDING   :   C O R R E S P O N D I N G;
ANY     :   A N Y;

MAPPING     :   (CORRESPONDING|ANY);
MATCHCASE       :   I;

EQUALS      :   E Q U A L S;
LIKE        :   L I K E;
NOTEQUALS       :                     N O T E Q U A L S;
NOTLIKE     :   N O T L I K E;
NOTNULL     :   N O T N U L L;

STROPS      :   (EQUALS | LIKE | NOTEQUALS | NOTLIKE | NOTNULL);
UNARYOPS        :   (COUNT | AVG | COUNTDISTINCT);
ARITHEMATICOPS  :   (DIVIDE|PLUS|MINUS|STAR|MOD);
MATHLOGICALOP   :   (LANGLEBRACKET|RANGLEBRACKET|EQ|GRTRTHANEQTO|LESSTHANEQTO|NOTEQ);
LOGICALOP       :   (AND|OR);

SECATTR     :   ('a'..'z' | 'A'..'Z') UNDERSCORE? ('a'..'z' | 'A'..'Z')* DOT ('a'..'z' | 'A'..'Z') UNDERSCORE? ('a'..'z' | 'A'..'Z')*;
BRACEDSECATTR   :   LPAREN SECATTR RPAREN;
UNOPSECATTR :   OP1 BRACEDSECATTR;

OP1     :   (UNARYOPS | CAST) ;
OP2     :   (ARITHEMATICOPS|MATHLOGICALOP|STROPS);
OP3     :   (MAPPING|MATCHCASE);
OP4     :   (LOGICALOP);
//fragment Letter : 'a'..'z' | 'A'..'Z';
//Alphanumeric      :   (('a'..'z' | 'A'..'Z')| '0'..'9')* ('a'..'z' | 'A'..'Z') (('a'..'z' | 'A'..'Z')| '0'..'9')* ;
SINGLERULE      :   (SECATTR|BRACEDSECATTR|UNOPSECATTR) OP2 ((('a'..'z' | 'A'..'Z')| '0'..'9')|SECATTR|BRACEDSECATTR|UNOPSECATTR);
BRACEDSINGLERULE    :   LPAREN SINGLERULE RPAREN;
UNOPSINGLERULE  :   BRACEDSINGLERULE OP3;

Expr        :   SINGLERULE|UNOPSINGLERULE|((SINGLERULE|UNOPSINGLERULE)OP4(SINGLERULE|UNOPSINGLERULE))+;

A: ANTLR assigns one, and only one, token type (name starting with uppercase letter) to each non-overlapping sequence of characters in the input. In your case, the ANY rule matches a sequence, and the MAPPING rule defined after it is also defined to match ANY (as one of its alternatives). When the input is any, your lexer will always assign the token type ANY to it since that rule is defined first.
While you have allowed the input any to be a MAPPING, ANTLR is warning you that it will never assign the type MAPPING to this input, so the current definition of MAPPING is misleading. You should update your lexer rules so each sequence only matches one token type.


text:
Q: runtime error (SIGABRT) - SPOJ My code runs fine in code blocks but, when I submit it shows runtime sigabrt error, what does this error mean?
When I initialize the size of pointer array as 200 it works fine but I want to know what is this error?
link for question is: http://www.spoj.com/problems/FCTRL2/
Here is the code:
    #include <iostream>

    using namespace std;
    void multiply(int x,int *nums,int &len){
        int carry=0;
        int prod;
        for (int j=0;j<len;j++){
            prod=nums[j]*x+carry;
            carry=prod/10;
            nums[j]=prod%10;
        }
        while (carry){
            nums[len]=carry%10;
            carry=carry/10;
            len++;
        }

   }

   int main()
   {
   int t,n;

   cin>>t;
   int arr[100];
   for (int i=0;i<t;i++){
         cin>>arr[i];
   }
   for (int i=0;i<t;i++){
         n=arr[i];
         if (n==0){cout<<0<<endl;}
         else{
        int *nums= new int[0];
        nums[0]=1;
    int len=1;
    for (int i=2;i<=n;i++){
        multiply(i,nums,len);

    }

    for (int i=len-1;i>=0;i--){

        cout<<nums[i];

    }
    cout<<endl;}
}
return 0;
}

A: Change int *nums = new int[0]; to int *nums = new int[x], where x is the maximum size of the array (depending on the number of digits you're expecting in the factorial). According to the constraints (1 <= n <= 100) A suitable value of x would be 158.
int *nums = new int[n] allocates memory for an n element array.


text:
Q: How to cite a book chapter written by an author who is not the editor or author of the book with BibTeX? I don't know how to cite a chapter written by an author who is not the editor or author of the book.
How can I get the following citation?

Grandstrand, O. (2004), 'Innovation and Intellectual Property Rights', in J. Fagerberg, D.C. Mowery and R.R. Nelson (Eds.), Oxford Handbook of Innovation. Oxford University Press: Oxford.

A: Perhaps not exactly how you want it to appear (that requires probably selecting the right bibtex style) but here is something close with the standard:
\begin{filecontents}{test.bib}
@inbook{ X,
author = {O. Grandstrand},
chapter = {Innovation and Intellectual Property Rights},
crossref = {Y}
}

@book{ Y,
editor = {J. Fagerberg and D.C. Mowery and R.R. Nelson},
title      = {Oxford Handbook of Innovation},
booktitle = {Oxford Handbook of Innovation},
publisher = {Oxford University Press},
address = {Oxford},
year = 2004
}
\end{filecontents}

\documentclass{article}

\begin{document}

\nocite{*}

\bibliographystyle{plain}
\bibliography{test}

\end{document}

This results in

There are two reference here (both the chapter and the book) because I use \notcite on all antries. If just the chapter is cited then the result would be

The problem is that most if not all styles (that I know of) do not use both author and editor in a single entry even though it would make a lot of sense here. They only do that for @inproceedings and @incollection (I see that you found the latter by now yourself).
By default, BibTeX adds a separate citation to the whole book cross referenced when there are 2 or more different citations that crossref a complete work (even if the complete work is not explicitly cited anywhere. On modern BibTeX implementations this can be customized when running BibTeX by using the switch --min-crossref=<number>.

A: I tried using CROSSREF, but I found that the \nocite{*} generated too many entries.  I don't want all entries in my BIB file to show up in the References section of my paper.  The problem is that, without \nocite{*}, the book which contains the chapter/section that I'm citing does not show up.  I managed to solve this by citing the book from within the \phantom command.  So in the context of Frank Mittelbach's example, I would have the commend \phantom{\cite{Y}} somewhere in my document.  I placed it before the \cite{X} (the chapter/section within book Y in Frank Mittelbach's example).
Afternote: Darn.  It didn't really have the desired effect.  I have unwanted white space where the citation would have been made.  This is exactly how \phantom should work, so I don't know what I was thinking.  Can anyone suggest another way to hide the dummy citation to Y?  The only reason why it's there is so that the CROSSREF in X is properly handled.  Maybe a way to impose a zero-size font onto the dummy citation?  Using \fontsize and \selectfont to specify 0pt causes an error, so I tried making the dummy citation white: \textcolor{white}{ \fontsize{1pt}{1pt}\selectfont \cite{Y} }.  This only makes the square brackets around the bibliography entry number white.
I guess @incollection is the way to go.

A: I believe that the entry type you want to use is called @incollection.
Back-filling information for the author's and editors' first names as well as the chapter and pages fields, the full entry could be as follows:
@incollection{grandstrand:2004,
  author      = "Ove Grandstrand",
  title       = "Innovation and Intellectual Property Rights",
  editor      = "Jan Fagerberg and David C. Mowery and Richard R. Nelson",
  booktitle   = "The Oxford Handbook of Innovation",
  publisher   = "Oxford University Press",
  address     = "Oxford",
  year        = 2004,
  pages       = "266-290",
  chapter     = 10,
}

Using the plain bibliography style would generate the following typeset entry:

Addendum: If you use the chicago bibliography style, you'll get:

Here's the code used to generate the two preceding screenshots:
\RequirePackage{filecontents}
\begin{filecontents}{mybib.bib}
    @incollection{grandstrand:2004,
      author      = "Ove Grandstrand",
      title       = "Innovation and Intellectual Property Rights",
      editor      = "Jan Fagerberg and David C. Mowery and Richard R. Nelson",
      booktitle   = "The Oxford Handbook of Innovation",
      publisher   = "Oxford University Press",
      address     = "Oxford",
      year        = 2004,
      pages       = "266-290",
      chapter     = 10,
    }
\end{filecontents}

\documentclass{article}
\bibliographystyle{plain} % or: "chicago"
\usepackage{natbib} % a citation management package

\begin{document}
\nocite{*}
\bibliography{mybib}
\end{document}

A: use
@inbook{test,
  author={Grandstrand, O.},
  year= 2004,
  chapter={Innovation and Intellectual Property Rights},
  editor = {J. Fagerberg and D. C. Mowery and R. R. Nelson},
  title= {Oxford Handbook of Innovation},
  publisher= {Oxford University Press},
  address= {Oxford},
}

with biblatex and style authoryear I'll get:


text:
Q: Iterating an experiment with bounded non-constant probability of success Assume that we have an experiment $A$ which has the outcome "success" or "failure". Each time we try $A$ the probability of getting a success is different but always less than or equal to a given constant $p~(0<p<1$). The probability of success for every trial does not depent on previous trials.
Let $X$ be the random variable representing the number of times we have to repeat $A$ until we get the first success. Let $Y$ be a random variable that follows the geometric distribution with parameter $p$, i.e. $\Pr (Y=k) = (1-p)^{k-1} \cdot p$.
Does $X \geq_{\text{st}} Y$ hold? Why?
Remarks

*

*According to this link independent trials with non-constant probability are called "Poisson Trials".

*$\geq_{\text{st}}$ is the stochastic ordering. See the wikipedia page on Stochastic Ordering.

*The straightforward way to approach the problem is as follows:
If the probability of success in the $i$-th trial is $p_i \leq p$ it should hold that (for $k \geq 1$):
$$
\Pr (X=k) = (1-p_1) \cdot \dots \cdot (1-p_{k-1}) \cdot p_k~.
$$
Now we have that
\begin{align*}
& X \geq_{\text{st}} Y & \Leftrightarrow\\
& (\forall a) \Pr (X \geq a) \geq \Pr (Y \geq a) & \Leftrightarrow\\
& (\forall a) \Pr (X < a) \leq \Pr (Y < a)\\
\end{align*}
Since the probability of getting a success in $A$ is always at most equal to $p$, the fact that $(\forall a) \Pr (X < a) \leq \Pr (Y < a)$ seems "reasoble", but I am unable to prove it.

A: The event $\{X \ge a\}$ is simply the event that the first $a-1$ trials are failures, so it has probability $$P(X \ge a) = \prod_{k=1}^{a-1} (1-p_k).$$
It's clear that this is greater than $P(Y \ge a) = (1-p)^{a-1}$.
To see it another way, let's for simplicity write $q_k = 1-p_k$, and let $Q_n = \prod_{k=1}^n q_n$.  Then we have $$\begin{align*}P(X \ge a) &= \sum_{n=a}^\infty P(X=n) \\ &= \sum_{n=a}^\infty \prod_{k=1}^{n-1} q_k (1-q_n) \\
&= \sum_{n=a}^\infty Q_{n-1} (1-q_n) \\ &= \sum_{n=a}^\infty (Q_{n-1} - Q_n).\end{align*}$$
This is a telescoping sum (since $Q_n \to 0$) so $P(X \ge a) = Q_{a-1}$.


text:
Q: Dropdown menu hover class not removing The current implementation allows the use of select boxes and converts them into list items so they can be styled.
When you actually click on the dropdown menus and start hovering over the list item elements, a hover class is added to the ul. Now if the user clicks on the close button clicks on the body, it will close the dropdown and remove the hovering class.
Problem: When the user clicks on the item within the list, the hover class is not removed - until the document is clicked to close it.

var jq = jQuery.noConflict();
(function(jq) {

}(jQuery));

jq('.').selectBox();
.options li:hover {
  background-color: #000;
  color: #fff;
}
.options li.selected {
  background-color: #000;
  color: #fff;
}

  <select class="selectBoxStyle">
    <option value="">Choose Size</option>
    <option value="aye">Aye</option>
    <option value="eh">Eh</option>
    <option value="ooh">Ooh</option>
    <option value="whoop">Whoop</option>
  </select>

<select class="selectBoxStyle">
  <option value="">Month…</option>
  <option value="january">January</option>
  <option value="february">February</option>
  <option value="march">March</option>
  <option value="april">April</option>
  <option value="may">May</option>
  <option value="june">June</option>
  <option value="july">July</option>
  <option value="august">August</option>
  <option value="september">September</option>
  <option value="october">October</option>
  <option value="november">November</option>
  <option value="december">December</option>
</select>

A: As I understood you need this one.

var jq = jQuery.noConflict();
(function(jq) {

  jq.fn.selectBox = function() {

    // Cache the number of options
    var sthis = jq(this),
      numberOfOptions = jq(this).children('option').length;

    // Hides the select element

    if (jq('html').hasClass('touch')) {

      jq('.options').addClass('s-hidden');

      sthis.wrap('

');
      // Insert a styled div to sit over the top of the hidden select element
      sthis.wrap('

');

    } else {

      sthis.addClass('s-hidden');

      // Wrap the select element in a div
      sthis.wrap('

');

      // Insert a styled div to sit over the top of the hidden select element
      sthis.after('

');

      // Cache the styled div
      var styledSelect = sthis.next('div.styledSelect');

      // Insert an unordered list after the styled div and also cache the list
      var slist = jq('
', {
        'class': 'options'
      }).insertAfter(styledSelect);

      // Insert a list item into the unordered list for each select option
      for (var i = 0; i < numberOfOptions; i++) {
        jq('
', {
          text: sthis.children('option').eq(i).text(),
          "data-value": sthis.children('option').eq(i).val(),
          "class": sthis.children('option').eq(i).attr('class'),
          "data-sku": sthis.children('option').eq(i).data('sku'),
          "data-stock": sthis.children('option').eq(i).data('stock'),
          "data-backorder": sthis.children('option').eq(i).data('backorder'),
          "data-preorder": sthis.children('option').eq(i).data('preorder')
        }).appendTo(slist);
      }

      // Cache the list items
      var slistItems = slist.children('li');

      slistItems.hover(function() {
        slist.addClass('hovering');
      });

      // Show the unordered list when the styled div is clicked (also hides it if the div is clicked again)

      styledSelect.click(function(e) {
        e.stopPropagation();
        var closeClicked = jq(this).hasClass("active");

        jq('div.styledSelect.active').each(function() {
          slist.removeClass('hovering');
          jq(this).removeClass('active').next('ul.options').hide();

        });

        if (!closeClicked) {
          jq(this).toggleClass('active').next('ul.options').toggle();
        }
      });

      // Hides the unordered list when a list item is clicked and updates the styled div to show the selected list item
      // Updates the select element to have the value of the equivalent option
      slistItems.click(function(e) {
        e.stopPropagation();
        styledSelect.text(jq(this).text()).removeClass('active');
        jq(this).addClass("selected").siblings().removeClass("selected");
        sthis.val(jq(this).data('value'));
        sthis.addClass('THIS');
        slist.removeClass('hovering').hide();
      });

      // Show the first select option in the styled div
      if (sthis.val()) {
        var currentSelect = sthis.find("option:selected").val();

        styledSelect.text(sthis.find("option:selected").text());

        slist.find("li[data-value='" + currentSelect + "']").each(function() {
          jq(this).addClass('selected');
          slist.removeClass('hovering');
        });

      } else {
        styledSelect.text(sthis.children('option').eq(0).text());
      }

      // Hides the unordered list when clicking outside of it
      jq(document).click(function() {
        styledSelect.removeClass('active');
        slist.removeClass('hovering').hide();
      });
      jq('#addtoBag, .wishListBtn').click(function() {
        styledSelect.removeClass('active');
        slist.removeClass('hovering').hide();
      });
    }

  };

}(jQuery));

jq('.selectBoxStyle').selectBox();
.selectSizeMain {
  width: 56.77966%;
  float: none;
  margin: 2.1875rem auto auto;
}
.s-hidden {
  visibility: hidden;
  padding-right: 10px;
}
.select {
  cursor: pointer;
  display: inline-block;
  position: relative;
  color: black;
  font-family: GibsonRegular, HelveticaNeue, Helvetica, sans-serif;
  font-size: 14px;
  font-size: .875rem;
  height: 40px;
  width: 100%;
}
.styledSelect {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  padding: 11px 13px;
  border: 1px solid #ddd;
  background-color: #fff;
}
.styledSelect:after {
  content: "";
  width: 0;
  height: 0;
  border: 5px solid transparent;
  border-color: black transparent transparent transparent;
  position: absolute;
  top: 17px;
  right: 9px;
}
.styledSelect.active:after {
  content: "";
  width: 0;
  height: 0;
  border: 5px solid transparent;
  border-color: green transparent transparent transparent;
  position: absolute;
  top: 17px;
  right: 9px;
}
.options {
  display: none;
  position: absolute;
  max-height: 280px;
  overflow-y: scroll;
  top: 100%;
  right: 0;
  left: 0;
  z-index: 999;
  margin: 0 0;
  padding: 0 0;
  list-style: none;
  border: 1px solid #ccc;
  border-top: none;
  background-color: white;
}
.options li {
  padding: 11px 13px;
  margin: 0 0;
}
.options li:hover {
  background-color: #000;
  color: #fff;
}
.options li.selected {
  background-color: #fff;
  color: #000;
}

  <select class="selectBoxStyle">
    <option value="">Choose Size</option>
    <option value="aye">Aye</option>
    <option value="eh">Eh</option>
    <option value="ooh">Ooh</option>
    <option value="whoop">Whoop</option>
  </select>

<select class="selectBoxStyle">
  <option value="">Month…</option>
  <option value="january">January</option>
  <option value="february">February</option>
  <option value="march">March</option>
  <option value="april">April</option>
  <option value="may">May</option>
  <option value="june">June</option>
  <option value="july">July</option>
  <option value="august">August</option>
  <option value="september">September</option>
  <option value="october">October</option>
  <option value="november">November</option>
  <option value="december">December</option>
</select>


text:
Q: Adding Values From 2 TextBoxes Without A Button In React i am trying to create an accounting page wherein I try to add percentage and net to get the get value as well as the total value however I don't know how to implement a function without a button I don't have any examples to go through as well if anyone can help me that would be really grateful
the code is as follows
import React, { Component } from 'react';

import { connect } from "react-redux";
import { getData } from "../actions/company"
import "./css/InvoiceAdd.css"
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import "./css/Togglebox.css"

export class InvoiceSales extends Component {
    constructor(props) {
        super(props);
        this.state = {
            Invoice_Date: '',
            company_name: '',
            GSTIN: '',
            invoice_no: '',
            percentage: 0,
            net: 0,
            igst: 0,
            cgst: 0,
            sgst: 0,
            total_invoice: 0,

        };
        console.log(this.state);
        this.onChange = this.onChange.bind(this);
        this.onCreate = this.onCreate.bind(this);
        this.handlenum1Change = this.handlenum1Change.bind(this);
        this.handlenum2Change = this.handlenum2Change.bind(this);
    }

    componentDidMount() {
        document.body.classList.add("background-black");
    }

    componentDidMount() {
        this.props.getData();

    }

    componentWillUnmount() {
        document.body.classList.remove("background-black");
    }

    onChange = event => {
        this.setState({ [event.target.name]: event.target.value });
    };

    handlenum1Change = evt => {
       console.log(evt.target.value);
       this.setState({percentage:Number(evt.target.value) });
    }
    handlenum2Change = evt => {
        console.log(evt.target.value);
        this.setState({net:Number(evt.target.value) });

    };

    onCreate(e) {
        e.preventDefault();
        let Invoice = {
            Invoice_Date: this.state.Invoice_Date,
            company_name: this.state.company_name,
            GSTIN: this.state.GSTIN,
            invoice_no: this.state.invoice_no,
            percentage: this.state.percentage,
            net: this.state.net,
            igst: this.state.igst,
            sgst: this.state.sgst,
            total_invoice: this.state.total_invoice
        };
        console.log(Invoice);
        this.props.postData(Invoice);
        this.setState({
            Invoice_Date: '',
            company_name: '',
            GSTIN: '',
            invoice_no: '',
            percentage: 0,
            net: 0,
            igst: 0,
            cgst: '',
            sgst: '',
            total_invoice: ''

        });
    }

    render() {
        return (

                <form className="masterfileadd-form">

                        Invoice Date :
                          <DatePicker dateFormat="dd-MM-yyyy" selected={this.state.date} onChange={this.handleDateChange} className="itextbox1" />

                        Company Name:
                              < select value={this.state.company} onchange={this.onChange} name="company_name" className="itextbox2">
                            {this.props.company.map(company => {
                                return <option value={company.company_name}>{company.company_name}</option>
                            })}
                        </select>

                        GSTIN :
                        <input type="text" name="GSTIN" value={this.state.GSTIN} onChange={this.onChange} className="itextbox3"></input>

                        Invoice No :
                        <input type="text" name="invoice_no" value={this.state.invoice_no} onChange={this.onChange} className="itextbox4"></input>

                        Percentage:
                        <input type="number" step="0.1" name="percentage" value={this.state.percentage} handlenum1Change={this.handlenum1Change}  className="itextbox5"></input>

                        NET :
                        <input type="number" name="net" value={this.state.net} handlenum2Change={this.handlenum2Change}  className="itextbox6"></input>

                        IGST :
                      <input type="text" value={this.state.igst} readOnly />

                        CGST :
                        <input type="text" name="cgst" value={this.state.opening_balance} onChange={this.onChange} className="itextbox8"></input>

                        SGST:
                        <input type="text" name="sgst" value={this.state.opening_balance} onChange={this.onChange} className="itextbox9"></input>

                        Total Invoice :
                              <input type="text" name="total_invoice" value={this.state.head_of_account} onChange={this.onChange} className="itextbox10"></input>

<input type="submit" value="Submit" onChange={this.onChange} onClick={this.onCreate} className="mButtonAdd" />

                </form>

        )
    }
}

const mapStateToProps = state => ({
    company: state.companyReducer.company,
    error: state.journalReducer.error
});

export default connect(
    mapStateToProps,
    { getData }
)(InvoiceSales)

A: Hı ,
in onchange event
if(event.target.name =="input1" || event.target.name=="input2")
{
 this.setState({result: Number(this.state.input1)+ Number(this.state.input2)})
}

try something like this. input1 and input2 are your textboxes. And be sure textbox value is number .may be you can check.


text:
Q: What does this mean "scanf("%[^\n]",buf);" ? What is its equivalent C++ syntax? I am new to the C programming language. I have done some programming in C++ and I know that scanf is used to take input and \n means next line, but I cannot understand the complete expression.
And what would be the equivalent C++ syntax?

A: This means "read everything until you encounter an end-of-line character, and store the result in the provided char* pointer". An equivalent C++ syntax is exactly the same (you need to include <cstdio> for that), but in C++ you should prefer a string-based API to scanf:
string buf;
getline(cin, buf);

The reason for this is that scanf with the format string that you provided is prone to buffer overruns: if end-user types in more characters than the size of the buf, C or C++ will continue writing the data to the memory, causing undefined behavior. You can fix the format string (highly recommended) to limit the input to the size of the buffer, like this:
char buf[100];
scanf("%99[^\n]", buf);

but now you are limited to strings of 99 characters or less. std::getline with a std::string, on the other hand, is free from this limitation.


text:
Q: Hibernate - Using Distinct Select query in Criteria Hope all of you are fine. Well I am quite new to all this Hibernate stuff and I am having a difficulty getting a Select Distinct query to work. The Query I'm trying to work is as follows,
Select Distinct user_type from Users

The users table has values as follows,
---------------------------------------
| user_id  |  user_name  | user_type  |
---------------------------------------
|    1     | mark taylor | admin      |
|    2     | bill paxton |co-ordinator|
|    3     | tony brooks | admin      |
|    4     | ali jahan   | developer  |
---------------------------------------

The result I'm expecting at the end of the query is,
admin,co-ordinator,developer

What I'm hoping to get is a list of user_types as a return statement, the function i've written after searching for help is as follows,
public List<User> findDistinctUserType() throws HibernateException {
    Criteria c = this.createCriteria();
    c.setProjection(Projections.distinct(Projections.property("user_type")));
    return (List<User>) (User) c.uniqueResult();
}

I've looked at another example and tried this as well,
public List<User> findDistinctUserType() throws HibernateException {
    Criteria c = this.createCriteria();
    ProjectionList projectionList = Projections.projectionList();
    ProjectionList projectionList2 = Projections.projectionList();

    projectionList2.add(Projections.distinct(projectionList
            .add(Projections.property("user_type"),"user_type")));

    c.setProjection(projectionList2);
    c.setResultTransformer(Transformers.aliasToBean(User.class));

    return (List<User>) (User) c.uniqueResult();
}

But for odd reason, it's always failing and I'm not getting through, if you could please provide me with a good solution, that'll be great. Looking forward to your help.
Thanks in advance
EDIT
The output I am expecting is as follows,
admin,co-ordinator,developer

What I am currently getting without this code is,
admin,co-ordinator,admin,developer

The above mentioned function is called in the following manner,
List<User> userList = userDao.findDistinctUserType();

User is an object which contains the following information,
private int id;
private String userName;
private String userType;

further down the code we have where User object is defined, we have,
@Column(name="user_type", nullable=false)
public String getUserType() {
    return userType;
}

A: Thank you all for all your feedback, I was able to solve the problem. As per your suggestion, I did this and this worked for me,
public List<String> findDistinctUserName() throws HibernateException {
    List<String> returnVal = new ArrayList<String>();

    Criteria c = this.createCriteria();
    c.setProjection(Projections.distinct(Projections.property("userType")));
    c.addOrder(Order.asc("userType"));

    List<String> userTypeList = c.list();

    for(String userType : userTypeList) {
        if(!userType.equalsIgnoreCase("")) {
            returnVal.add(userType);
        }
    }

    return returnVal;
}

Thanks for all your answers. Be ready I might be asking more as I go along lol !!!


text:
Q: nodejs - passport.use callback return dataValues and _previousDataValues instead of a normal object I am using passport.js module for Authentication and Sequelize mysql for database management.
error occurs when authenticating user:
{
    "errors": {
        "message": "WHERE parameter \"id\" has invalid \"undefined\" value",
        "error": {}
    }
}

When authenticating the user, console.log(jwtPayload) in file passport.js shows below results.
{
  dataValues: {
    id: '06c19eb0-995f-45f4-81d7-26ec3b401234',
    email: 'CCCC@gmail.com',
    createdAt: '2021-05-14T01:51:31.000Z',
    updatedAt: '2021-05-14T01:51:31.000Z'
  },
  _previousDataValues: {
    id: '06c19eb0-995f-45f4-81d7-26ec3b401234',
    email: 'CCCC@gmail.com',
    createdAt: '2021-05-14T01:51:31.000Z',
    updatedAt: '2021-05-14T01:51:31.000Z'
  },
  _changed: {},
  _options: {
    isNewRecord: false,
    _schema: null,
    _schemaDelimiter: '',
    raw: true,
    attributes: [ 'id', 'email', 'createdAt', 'updatedAt' ]
  },
  isNewRecord: false,
  iat: 1620961695
}

instead of
  {
    id: '06c19eb0-995f-45f4-81d7-26ec3b401234',
    email: 'CCCC@gmail.com',
    createdAt: '2021-05-14T01:51:31.000Z',
    updatedAt: '2021-05-14T01:51:31.000Z'
  }

passport.js
var passport = require('passport');
const passportJWT = require("passport-jwt");
const JWTStrategy   = passportJWT.Strategy;
var LocalStrategy = require('passport-local').Strategy;
const ExtractJWT = passportJWT.ExtractJwt;

const bcrypt = require('bcryptjs');

var User = require('../models/Users')

module.exports = function(passport) {

passport.use(new JWTStrategy({
  jwtFromRequest: ExtractJWT.fromAuthHeaderAsBearerToken(),
  secretOrKey   : 'your_jwt_secret'
},
function (jwtPayload, done) {
  console.log(jwtPayload)
  return User.findOne({where: {id:jwtPayload.id}})
      .then(user => {
          return done(null, user);
      })
      .catch(err => {
          return done(err);
      });
}
));

};

A: Sequelize returns dataValues and _previousDataValues properties by design. You can pass the current values with a small modification.
return User.findOne({where: {id:jwtPayload.id}})
      .then(user => {
          return done(null, user.dataValues);
      })


text:
Q: error al almancenar la base datos en php mysql Tengo un error al compilar el codigo de php a mysql:
archivo de conexion con la base de datos:
    <?php

        $dbname = "hostienda_prueba";
        $user = "adrian";
        $password = "admin";
        $host = "localhost";

        $conexion = mysqli_connect($host, $user, $password,$dbname) or die ("no se pudo conectar a la base datos").mysqli_connect_error();
        mysqli_set_charset($conexion,"utf8");
        echo " conexion exitosa.";

        ?>

parte de HTML5
      <title>caja de comentarios</title>

    <form action="datos.php" method="POST" enctype="multipart/form-data" >

    fecha:
    <input type="date" name="fecha">

     <input name="Imagen" type="file" >

    hora:
    <input type="time" name="hora">

    Nombre:

    <input type="text" name="nombre">

    Comentario:

    <textarea type="text" name="comentario" cols="30" rows="10"></textarea>

    <input type="submit" value="enviar">

    </form>

    </form>

Parte lógica de ingreso de datos->
?php
include("conexion.php");
if($_SERVER['REQUEST_METHOD'] == "POST"){

    $nombre = $_POST['nombre'];
    $Imagen = addslashes(file_get_contents($_FILES['Imagen']['tmp_name']));
    $comentario = $_POST['comentario'];
    $fecha = $_POST['fecha'];
    $hora = $_POST['hora'];

  //insercion de los datos
  $query = "INSERT in to comentarios(nombre,Imagen,comentario,fecha,hora)
            VALUES('$nombre','$Imagen','$comentario','$fecha','$hora')";
  $resultado = $conexion->query($query);

  if($resultado){
      echo " se inserto la base de datos";
  }else{
      echo " no se inserto la base de datos :/";
  }

}

el error que muestra al compilar

conexion exitosa. Warning: mysqli::query(): MySQL server has gone away
  in C:\xampp2\htdocs\hostienda\datos.php on line 13
Warning: mysqli::query(): Error reading result set's header in
  C:\xampp2\htdocs\hostienda\datos.php on line 13 no se inserto la base
  de datos :/

he trato de varias formas pero no encuentro como solucionar el error.

A: Fijate que creo que tu codigo no está bien. La forma correcta sería:
$query = "INSERT INTO comentarios(nombre,Imagen,comentario,fecha,hora)
            VALUES('$nombre','$Imagen','$comentario','$fecha','$hora')";

El error está en que escribiste "in to" en vez de "INTO".

A: En la parte lógica tienes un error de sintaxis en tu query para insertar pusiste in to en vez de INTO quitale el espacio y vuelve a intentar quedando el script de esta manera.
<?php
include("conexion.php");
if($_SERVER['REQUEST_METHOD'] == "POST"){

    $nombre = $_POST['nombre'];
    $Imagen = addslashes(file_get_contents($_FILES['Imagen']['tmp_name']));
    $comentario = $_POST['comentario'];
    $fecha = $_POST['fecha'];
    $hora = $_POST['hora'];

  //insercion de los datos
  $query = "INSERT into comentarios(nombre,Imagen,comentario,fecha,hora)
            VALUES('$nombre','$Imagen','$comentario','$fecha','$hora')";
  $resultado = $conexion->query($query);

  if($resultado){
      echo " se inserto la base de datos";
  }else{
      echo " no se inserto la base de datos :/";
  }

}
?>


text:
Q: Can't open localhost after configuring httpd.conf  I've installed Zend Framework, and I've created my project "zendy" to the path: D:\wamp\www\zendy. So I modified the file "httpd.conf" (I use WAMPSERVER) by adding:
NameVirtualHost 127.0.0.1
<VirtualHost 127.0.0.1>
     ServerName zendy
     DocumentRoot D:\wamp\www\zendy\public
     <Directory D:\wamp\www\zendy\public>
         DirectoryIndex index.php
         AllowOverride All
         Order allow,deny
         Allow from all
     </Directory>
</VirtualHost>

And then I restarted all the services of WAMPSERVER. I add a line "127.0.0.1 zendy" in the file C:\Windows\System32\divers\etc\hosts
Then I type "zendy/" or "localhost" in my navigator but it displays something like:
"Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your request."
I totally follow the tutorial for installing zend frameline like :
http://www.youtube.com/watch?v=m7svJHmgJqs and http://framework.zend.com/manual/en/learning.quickstart.create-project.html
Who can help me?? Thanks a lot!!

A: Verify virtual configuration syntax using "httpd -S"
Also find something like this in httpd.conf and uncomment it by removing the preceding # sign before Include
#Virtual hosts
Include conf/extra/httpd-vhosts.conf

Please don't remove the # sign before Virtual hosts as depicted above.
Also, add
Options Indexes FollowSymLinks

before
AllowOverride All

and restart wamp

A: Here is the correct configuration:
<VirtualHost *:80>
    ServerName zendy
    DocumentRoot D:\wamp\www\zendy\public
</VirtualHost>

You do not need to mention directory under this.
Try and revert! :)
PS: Also, check for AllowOverride in your main httpd.conf or apache2.conf file. Hope it helps!


text:
Q: Two navbars collapsed into 1 for mobile? I have two menus in Bootstrap 3 - a Social Menu and a Main Menu.
When collapsed on mobile, I get two menu open/toggle buttons to open the corresponding menu items.
Is there any way when collapsed, I can move the Social Menu Items into the Main Menu and use just one toggle/menu button and list? Code is Below...

         <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-social">
         Toggle navigation

         </button>

Social Menu Item 1

Social Menu Item 2

Social Menu Item 3

Social Menu Item 4

         <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-main-menu">
         Toggle navigation

         </button>

Main Menu Item 1

Main Menu Item 2

Main Menu Item 3

Main Menu Item 4

Using Bootstrap 3

A: Copy the 2nd nav bar into the same list as the main nav bar.  Then add classes to the main nav bar to hide them on large desktops.

         <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-main-menu">
         Toggle navigation

         </button>

Main Menu Item 1

Main Menu Item 2

Main Menu Item 3

Main Menu Item 4

Social Menu Item 1

Social Menu Item 2

Social Menu Item 3

Social Menu Item 4