text:
Q: Congruence with power We were given a congruence
$$
X=2^{2012} \mod{6}
$$
And we asked our professor what's the solution and she replied with
$$
X=2^{2012} \mod{2}
$$
$$
X=0^{2012} \mod{2}
$$
$$
X=0 \mod{2}
$$
My question is how did she get from mod6 to mod2, is there an actual rule for this or is it a mistake?

A: By CRT: $\ \ x\equiv 2^{\large 2N}\!\pmod{\!6}\iff \begin{align} &x\equiv 2^{\large 2N}\!\equiv 0\!\! \pmod{\!2}\ \ \ {\rm by}\ \  N > 0\ \ ({\rm here}\ 2N = 2012)\\ &x\equiv \color{#c00}2^{\large\color{#c00} 2N}\!\equiv 1\!\!\pmod{\!3}\ \ \ {\rm by}\ \ (\color{#c00}{2^{\large 2}})^N\equiv \color{#c00}1^N\!\equiv 1 \end{align}\ \ $
But $\,x\equiv 1\pmod{\!3}$ is redundant (same as first congruence in system) leaving only $\,x\equiv 0\pmod{\!2}$


text:
Q: How to manage a redirect request after a window.Open() I am using window.Open() to call a controller action. This will cause the popup of view to happen. All works well except if session times out. If that happens a popup of the login screen appears.
var windowHandel = window.open( bla bla bla);

Using windowHandel, is there a way to see if I got the logon screen?

A: This is generally easier to handle in the popup itself.  Rather than forwarding to the login screen directly, forward to a screen with some javascript which sets the location of window.opener (the original window) and then closes the popup.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Magento hacked even after applied patch Some days before my Magento community edition 1.8.1 site is hacked, because we are late to apply the patch. we found certain files were changed those are

*

*index.php [hackers added some code to it].

*get.php

*js/index.php

*js/lib/ccard.js

*lib/Varien/Autoload.php

And they also installed module called Magpleasure file system
But after applying the patch, and removing all the stuff what hackers added in our application problem is not solved.
hackers eventually changing 3 files

*

*get.php

*js/index.php

*js/lib/ccard.js

Is there anything that we are missing?
How to prevent them by attacking our files?
Is patch is working or not? How should I check that?

A: It seems your Magento setup is still compromised at some point so you should carefully check Magento + Webserver settings.
You cannot trust your installation if it was compromised. The ultimate way to go would be a new & clean setup of all files on a new host with the latest backup before you shop was compromised.
If this is not possible due to various reasons, you might check/do these things related to this issue:
Remove all detected changed/hacked files plus installed extensions
Even better: Do a clean (git) checkout from your development system with the lastest version. This will be the safest unless your dev/staging system hasn't been compromised also (which is not the case if you develop locally or in a protected environment).
Remove created backend admin accounts
Especially for SUPEE-5344, there will also be an admin account created in the backend. Remove all new/unnecessarry admin accounts.
Backup plan
Depending on your backup plan and strategy, you could maybe think about a rollback of your complete database.
Check file/folder permissions
Did you check your file/folder permissions?
There's no need to run everything with 777 or as root user. Depending on your server configuration 400/500 can be enough. See documentation here.
Check server logs
Check your webservers access/error log to trace accessed sites and suspicious URLs.
Maybe you find suspicious IP's to block on firewall level.

A: This is pretty usual I think. Patches come after Magento's security team discovers the vulnerability or someone reports it to them. But until then Magento stores remain a hackers' playground.
A few files to check which could have been modified too:

*

*app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Ccsave.php

*app/code/core/Mage/Customer/controllers/AccountController.php

*app/code/core/Mage/Payment/Model/Method/Cc.php

*app/code/core/Mage/Checkout/Model/Type/Onepage.php
Also, the following command comes handy in finding malware/backdoors/shell once you're SSH's in your server:
find /var/www -name "*.php" -exec grep -l "$_FILES[" {} \;

I took the above info from https://www.getastra.com/blog/911/how-to-remove-fix-magento-opencart-credit-card-malware-hack/
Might be useful to check directly.


text:
Q: Are macos Mojave Security Updates Cumulative? I had upgraded to macOS Mojave on April 2020 and am still on it.
The Software Installations list on System Information lists the following security updates installed:

*

*Security Update 2020-002

*Security Update 2020-003

*Security Update 2020-004

*Security Update 2020-005

*Security Update 2020-006

As you can see Security Update 2020-001, which was released on January 28, 2020 is missing from the list. I don't recall if I installed 2020-002 security update manually on it or through Software Update.
Now that Apple is releasing even Combo updates for the macOS, which are cumulative updates of point releases, is there any clarity on whether security updates are also now cumulative?

A: Yes, security updates are cumulative since the most recent point release. So, if you're downloading updates manually (to use with offline machines, or in some sort of automated deployment setup, etc), you'll want to install (1) the most recent "combo update" followed by (2) the most recent "security update".
Frustratingly, I have been unable to find any official confirmation of this from Apple, but I am relatively confident this is how things work based on my own use. If you try to install an OS X 10.9.5 security update (like 2016-004) before updating from 10.9.4 to 10.9.5, the installer will complain and won't run. However, installing security update 2016-001 followed by 2016-004 seems to have the same affect as just installing 2016-004—you end up on the same build version.


text:
Q: change a line with awk Im trying to make a substitution of a single line in a file with awk, for example
changing this:
e1 is (on)

e2 is (off)

to:
e1 is (on)

e2 is (on)

use command:
awk '/e2/{gsub(/off/, "on")};{print}' ~/Documents/Prueba > ~/Documents/Prueba

this makes the substitution but the file ends blank!

A: As explained by the other answers and in the question "Why reading and writing the same file through I/O redirection results in an empty file in Unix?", the shell redirections destroy your input file before it is read.
To solve that problem without explicitly resorting to temporary files, have a look at the sponge command from the moreutils collection.
awk '/e2/{gsub(/off/, "on")};{print}' ~/Documents/Prueba | sponge ~/Documents/Prueba

Alternatively, if GNU awk is installed on your system, you can use the in place extension.
gawk -i inplace '/e2/{gsub(/off/, "on")};{print}' ~/Documents/Prueba

A: You can also use cat to read the file first, then use pipe to redirect to stdout, then read with awk from stdin:
cat ~/Documents/Prueba | awk '/e2/{gsub(/off/, "on")};{print}' - > ~/Documents/Prueba

I believe the dash - is optional, since you're only reading stdin.
Some interesting documentation: https://www.gnu.org/software/gawk/manual/html_node/Naming-Standard-Input.html

A: Another answer, using a different tool (sed, and the -i (in place) flag)
sed -i '/e2/ s/off/on/' ~/Documents/Prueba

A: Your awk is correct, however you are redirecting to the same file as your original. This is causing the original file to be overwritten before it has been read. You'll need to redirect the output to a different file.
awk '/e2/{gsub(/off/, "on")};{print}' ~/Documents/Prueba > ~/Documents/Prueba.new

Rename Prueba.new afterwards if necessary.

A: You cannot redirect the output to the same file as the input file. Choose another file name.
The > will empty your file at the first place.

You can try sponge.


text:
Q: Can different endpoints be used for each resource in WSO2? I am trying to create an API proxy for a backend to restify the API.
I used the solution given below to map the requests.
https://apim.docs.wso2.com/en/latest/deploy-and-publish/deploy-on-gateway/api-gateway/message-mediation/mapping-the-parameters-of-your-backend-urls-with-the-api-publisher-urls/
I can map requests like this example:
From
localhost:XXXX/api/abc/5
To
xyz.com/api/?function=getabc&number=5
However,I need to create different endpoints for each resource to make this approach work. However, it seems like only one endpoint is used for the whole API. I also cannot create different APIs for each resource because the context would be different.
How can I create different request mappings for each resource. Is my approach wrong?

A: You can try dynamic endpoints feature. You can have multiple endpoints per API using this Feature. When creating the API you need to set the Endpoint Type as "Dynamic Endpoint" and upload a mediation in-sequence that sets the "To" header. Within the sequence, you can specify your logic to route to the correct endpoint (setting the correct "To" header) according to the request path.
https://apim.docs.wso2.com/en/latest/deploy-and-publish/deploy-on-gateway/api-gateway/message-mediation/adding-dynamic-endpoints/#adding-dynamic-endpoints
Here is a blog post explaining the same for 2.x versions of APIM.
https://lashan.medium.com/dynamically-setting-the-endpoint-uri-in-wso2-api-manager-83a3a6243ce


text:
Q: Why do I have to create a temporary reference to print something like: '(e1->next)->content' in C? #include <stdio.h>
#include <stdlib.h>

typedef struct ListElemStruct {
     int content;
     ListElem next;
} *ListElem;

ListElem mkListElem(int content);

int main(void) {
    ListElem e1 = mkListElem(1);
    e1->next = mkListElem(2);

    printf("%d\n", e1->next->content);

    return 0;
}

ListElem mkListElem(int content) {
    ListElem new = calloc(1, sizeof(*ListElem));
    new->content = content;
    new->next = NULL;
    return new;
}

error messages:
c(6): warning undefined type or identifier (assuming int):_ListElem
c(13): warning different types in assignment (possibly loss of data)
c(13): warning assigning pointer type to non-pointer type
c(15): error _content not a member of _e1

It works, if I write it like this instead:
    ListElem tmp = e1->next;
    printf("%d\n", tmp->content);

I don't understand the issue here.
Why does the option with the 2 '->' operators not work and is there an easier way to print the content of the next ListElem instead of using a 'ListElem tmp'?

I understand now why the option with the 2 '->' operators doesn't work and have been told, that I should not reference ListElem in my ListElemStruct declaration at the top.
So how do i declare my ListElemStruct instead?

A: As elaborated in the comments (@Eric Postpischil, @dialer), the error was due to using ListElem before it was even declared. This caused the Virtual-C compiler to assume that next was an ìnt, which was then implicitly cast to the correct type with ListElem tmp = e1->next;.
Solution for a better way to write my ListElemStruct (provided by @Eric Postpischil):
typedef struct ListElemStruct {
    int content;
    struct ListElemStruct *next;
} *ListElem;


text:
Q: Is this space $T_1$ and satisfies property $P$?. Question: let $X=\{1,2,3\}$ and $τ=\{\{1\},\{2\},\{1,2\},\{2,3\},\{1,2,3\}\}$. The topological space $(X,τ)$ is said to have property $P$ if for any two proper disjoint closed subsets $Y$ and $Z$ of $X$, there exists disjoint open sets $U$, $V$ such that $Y ⊆U, Z⊆V$. Then the topological space $(X,τ)$
(A) is $T_1$ and satisfies $P$
(B) is $T_1$ but does not satisfies $P$
(C) is not $T_1$ and satisfies $P$
(D) is not $T_1$ and not satisfies $P$
I am beginner of topology, and I don't have key of above problem , so please help me....
My attempt: what I know is , members of $τ$ are called open sets and I know $(X,τ)$  will be $τ_1$ if Singleton's are closed set, but there is no set in $τ$ such that whose complement is $\{2\}$ and hence $\{2\}$ is not closed set in $(X,τ)$ and hence space is not $τ_1$.
Now to see whether $(X,τ)$ satisfies $P$. Clearly I can see, $\{1\}$ and $\{2, 3\}$ are closed sets(because they are complement of open sets) and they are disjoint too and clearly there exists open sets $U, V$ such that $\{1\}$ and $\{2, 3\}$ are contained in $U$ and $V$ respectively(here $U$, $V$ are $\{1\}$ and $\{2, 3\}$ resp.) Hence $(X,τ)$ satisfies $P$.
Please check whether "my attempt" is correct or not! and is above solution by me is complete and correct? as i beginner and don't have key, I don't know I am correct or not.  please help me.

A: First of all, remember to add $\emptyset$ as open subset.
Your proof of $X$ not being $T_1$ is correct.
But, to prove that $X$ satisfies $P$, you have to show that every pair of disjoint closed subsets have disjoint open neighborhoods containing them. What you did is finding one pair with that property. So that part of the proof is not correct.

A: Your space is not $T_1$ since $$\{2\}^c = \{1,3\} \notin \tau$$
so $\{2\}$ is not a closed set.
All closed sets in your space are
$$\{\{2,3\}, \{1, 3\}, \{3\}, \{1\}, \{1, 2, 3\}, \emptyset\}$$
The only nontrivial disjoint pairs are $(\{2,3\}, \{1\})$ and $(\{3\}, \{1\})$ both of which can be separated by $\{2, 3\}, \{1\} \in \tau$.
Therefore, your space indeed satisfies $P$ so the correct option is $(C)$.

A: Your proof is correct but not complete.
You just found one example of two closed disjoint sets and their corresponding disjoint open sets.
Apparently there are other disjoint closed sets in your topology.
Try to find all of them.


text:
Q: Does J2ME support HTML5? I want to make an application for J2ME phones.
In that application I want to use HTML5,
how I can do this?
I worked on LWUIT. Does LWUIT support HTML5?
Or give me any other browser info.

A: LWUIT/Codename One support HTML5 but not on J2ME.

A: There's no built-in HTML5 (or any HTML version, for that matter) parser or renderer in J2ME. There's some sort of HTML viewer support in the LWUIT library, but I suspect it is reasonably limited in general, and also in particular regarding specifically HTML5 support. In any case, research LWUIT and see if it is enough for your needs or not (hard to say without knowing your real/actual requirements).
It is also not very practical to write your own HTML parser and renderer (especially if you also need to be able to handle CSS and JavaScript). In essence, you'd have to write your own complete web browser in J2ME.
You can, of course, use platformRequest() to launch the default browser, but not that many mobile phones have HTML5 support yet.
If you also manage the server-side (where the HTML5 pages come from), and all you really need is the data, then write the server code to return/send the data to your J2ME MIDlet as either XML or JSON, which are much easier to handle.


text:
Q: Manipulating and converting mixture ratios I am unable to understand the following calculation for the total-fat to total-mixture ratio (adding the numerator and denominator values and taking the ratio of the two values). Also I am unable to understand what is going on in the last line, and how they have calculated the values as per the given requirements from the ratio. I am really unable to decipher this so I am requiring some help and guidance.

A: Related questions:
if you mix in equal quantity drinks with alcohol content $40\%$ and $44\%$, what is the alcohol percentage of the mixture?
if you mix in equal quantity drinks with alcohol content $40\%$, $44\%$  and $51\%$, what is the alcohol content of the mixture?
in a drink with alcohol content $40\%$, what is the ratio of alcohol to water?
If you can reply to the above questions, you will understand your problem.

A: We are given that the three milks have fat:nonfat ratios $$4:5,\quad 5:6\;\;\text {and }\; 6:7,\tag{*}$$ and asked to find the fat:nonfat ratio of a mixture containing equal quantities of the three milks.

*

*Let's convert the milks' fat:nonfat ratios to a form in which
the milks' quantities (i.e., combined fat & nonfat contents) are
easier to compare and standardise: the respective
fat:TotalContents ratios are $$4:9,\quad 5:11\;\;\text {and }\; 6:13\tag1$$$$=572:1287,\quad 585:1287\;\;\text {and }\; 594:1287$$
$(1287$ is the lowest common multiple of $9, 11, 13).$
So, their fat:nonfat ratios are  $$572:715,\quad
585:702\;\;\text {and }\; 594:693.$$ So, a $1:1:1$ mixture of the
three milks has fat:nonfat ratio
$$(572+585+594):(715+702+693)$$$$=1751:2110.\tag2$$
Note that $(2)$ is just the weighted average
$$\frac{715}{2110}\left(\frac{572}{715}\right)+\frac{702}{2110}\left(\frac{585}{702}\right)+\frac{693}{2110}\left(\frac{594}{693}\right)$$
and alternatively derivable from the simple average of $(1):$
$$\frac13\left(\frac49+\frac5{11}+\frac6{13}\right)\;:\;1-\frac13\left(\frac49+\frac5{11}+\frac6{13}\right).$$
Note that taking neither the simple nor weighted average of $(*)$ results in the correct answer, because the three ratios' ratio units are not of the same size. To throw this into relief, here's an explicit formulation of the given problem:

*

*Given that $$(4+5)x=(5+6)y=(6+7)z,$$ evaluate
$$\frac{4x+5y+6z}{5x+6y+7z}.$$
To perform this evaluation, just express each of $y$ and $z$ in terms of $x,$ which will then get cancelled out to give the above numerical answer.


text:
Q: find all functions such that $f(x)\geq0$ for all $x$ and $f(x+t) = f(x) +f(t) +2\sqrt{f(x)f(t)}$ I have thought of $f(x)=x^2$, but it's not always positive and it doesn't work when $x$ or $t$ is negative.

A: We have $$f(x+t)=\left[\sqrt {f(x)}+\sqrt {f(t)}\right]^2$$which leads to$$\sqrt {f(x+t)}=\sqrt {f(x)}+\sqrt {f(t)}$$since $f(x)\ge 0$. By defining $g(x)=\sqrt {f(x)}\ge0$ we obtain $$g(x+t)=g(x)+g(t)$$Therefore the final answer becomes:

$f(x)=g^2(x)$ is the general solution, provided $g(x)$ is a non-negative additive function.

A: The equation at $x=t=0$ gives us: $f (0)=2*f (0) + 2×f (0) $.
So $0 <f (0)=0$.
Thus, there isn't any $f $ satisfying this.


text:
Q: cocoa: how to create single column table view with checkboxes and labels I have a fixed number of text items I want to display with checkboxes to select/deselect in a cocoa tableview.  Exactly like a listbox of items with checkboxes in Microsoft MFC.
If I drop the section labels and checkboxes into the TableView they don't seem to belong to the tableview.  Note: the labels are to divide/designate the sections for the checkbox items.
What are the correct steps?
Thanks.

A: You can make a CustomCell class: take a NSTextField and NSButton(for checkbox)-

set UIButton state in IB:

for default state - set non selected image.
 for selected state - set selected image.

In CustomCell.m file

-(void)setSelected:(BOOL)selected
{
    [checkBoxBTN setSelected:selected];
}

you can do this in also cellForRowAtIndex method in your tableView class.
  your table data source should be a ModelClass or a dictionary with two keys like title and its state(selected/nonSelected).
  In didSelectAtIndexPath method you need to update your dictionary like:

NSMutableDictionary * dic = [yourDataSourceArray objectAtIndex:indexPath.row];
NSNumber *state = [dic valueForKey:@"state"];
[dic setValue:![state boolValue]];

You need to modify your cellForRowAtIndexPath Method to show prev selected/nonSelected state

NSMutableDictionary * dic = [yourDataSourceArray objectAtIndex:indexPath.row];
NSNumber *state = [dic valueForKey:@"state"];
cell.title = [dic valueForKey:@"title"];
[cell.checkBoxBtn setSelected:[state boolValue]];

Edit
  To create Label:

NSTextField *textField = [[NSTextField alloc] initWithFrame:NSMakeRect(10, 10, 200, 17)];
    [textField setStringValue:@"My Label"];
    [textField setBezeled:NO];
    [textField setDrawsBackground:NO];
    [textField setEditable:NO];
    [textField setSelectable:NO];
    [cell addSubview:textField];


text:
Q: Django ChoiceField populated from database values I am having problems using a ChoiceField to create a drop down list of values in the database. Here is the snippet of code
from django import forms
from testplatform.models import ServiceOffering

class ContactForm(forms.Form):

    subject = forms.ChoiceField(queryset=ServiceOffering.objects.all())
    #subject = forms.ModelMultipleChoiceField(queryset=ServiceOffering.objects.all())

The #subject.... line works, but when I use the line ChoiceField(queryset....) I get the following error.
__init__() got an unexpected keyword argument 'queryset'

Any ideas?

A: if you want to populate dropdown list from database, I'll recommend you to pass all the values in single object from views.py to your template. You can do it this  way:
1] fetch all the values from database:
objectlist = ModelName.objects.all()

if you want sorted list in dropdown list, Do this:
objectlist = ModelName.objects.all().order_by('fieldname')

if you want distinctlist, do this:
objectlist = ModelName.objects.distinct('fieldname')

2] Pass this render this 'objectlist' with template
return render(request, 'template.html', {'objectlist': objectlist})

3] In template use a select tag , and in user for loop to iterate over the objectlist.
<select>

{% for element in objectlist %}

<option value={{ element.id }}>{{ element.name }}

     </select>

value in  option tag depends on what you need to process in your API

A: ChoiceField doesn't have a queryset. You're looking for ModelChoiceField

A: Use the ModelChoiceField Link Here
ChoiceField doesn't support queryset

A: view.py :-
This is my view.py file. And create below code.
def add_customer(request):
    objectlist = Vehicle.objects.values('brand_name').distinct().order_by('brand_name')
    if request.method == 'POST':
        form = CustomerForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('/show-customers')
    else:
        form = CustomerForm()
    return render(request, 'add-customer.html', {'form':form, 'objectlist':objectlist})

Customer.html
<select name="prefer_car_model" id="id_prefer_car_model" required>
                <option value="0" selected disabled> Select Car model </option>
                {% for obj in objectlist %}
                <option value="{{ obj.brand_name }}">{{ obj.brand_name }} </option>
                {% endfor %}
            </select>

Output

A: In Django 2+ you can use 'choices' instead of 'queryset'


text:
Q: Fortify "sourceanalyzer -show-build-ids" does now display any build id after successful build for .NET Core 3.1 x64 I have a solution contained 4 projects:
Console netcoreapp3.1,Standard Class Library 2.1,Worker Service netcoreapp3.1,xunit test project under netcoreapp3.1
I did:

*

*sourceanalyzer -b * -clean

*sourceanalyzer -b X.sln msbuild "C:\x\X.sln" /nologo /v:n /t:Rebuild

*sourceanalyzer -show-build-ids
No results

*sourceanalyzer.exe -scan -b x.sln -f "C:\x\Security\x.fpr"

Output:
[error]: Unable to load build session with ID "x.sln". See log file for more details.
I am using VS 2019 latest update Version 16.7.6,
Fortify Static Code Analyzer 20.1.0.0158 (using JRE 1.8.0_181)

A: Unable to load build session with ID error message has been thrown for many versions now if Fortify does not support the project's version of .NET Framework. Download and install the latest version of Fortify Source Code Analyzer and scan again. Be sure to close Visual Studio first.
Happened to me after upgrading a Visual Studio solution from .NET Core 2.2 (aka netcoreapp2.2 in csproj) to .NET Core 3.1 netcoreapp3.1. Removing Fortify 19.2 and installing 20.1 did the trick. In your case however it seems you have the latest Fortify version 20.1.
To confirm this is the problem:

*

*Verify Fortify Supported Languages for your version, v20.1 in this example

*Manually delete project "bin" and "obj" folders -- even after a Clean Solution some can remain

*Look for "netcoreapp" in log file (replace "20.1" here with your fortify version) C:\Users\MYUSER\AppData\Local\Fortify\sca20.1\log -- for me it showed .NET Core v2.2 references instead of my project's v3.1 tipping me off to the need for a Fortify upgrade


text:
Q: storing values in db if selected question was updated thanks for ur help this code works fine but when i click Confirm Choices the booked count should increase in db and if the user select booked img it should display room has been booked can u please help..
<?php
mysql_connect("localhost","root","");
mysql_select_db("hotel");
error_reporting(E_ALL ^ E_NOTICE);
$notify = "";
$sql = "SELECT * FROM room";
$getquery = mysql_query($sql);
$submit=$_POST['submit'];
if($submit)
{
if($booked)
{
    $insert=mysql_query("INSERT INTO room (booked) VALUES ('$taken')");
    echo $insert;
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org   /TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>sample</title>

<form action="s2.php" method="POST">

hotel Room

Your room Selection:

Total

Avilable

Booked

Vacated

     <?php
     while($row = mysql_fetch_array($getquery)) {
       echo '
';
        echo '
' . $row['total'] .'
';
       echo '
' . ' '.' '.' '.' '.' '.' '.' '.'
';
         echo '
' . $row['avilable'] .' '.' '.'
';
echo '
' . ' '.' '.' '.' '.' '.' '.' '.'
';
echo '
' . $row['booked'] .' '.' '.' '.' '.' '.'
';
echo '
' . ' '.' '.' '.' '.' '.' '.' '.'
';
echo '
' . $row['vacated'] .'
';
echo '
';
      }
    ?>

   = Available;  = Mine;
                     = Taken;  = vacated;

Raised Premium Rooms

Regular Seats Rooms

                <input type="button" value="Confirm Choices" id="confirm" />
                <input type="submit" name="submit" value="book">
                <input type="reset" id="btnReset" value="Reset" />

    </form>

A: One cannot use javascript to connect to a db. You have to use something like php or jsp on this page to connect to a db

A: just do with ajax, and use PHP to store in db

A: *

*Connect Javascript to PHP using AJAX

*Connect PHP to MySQL

A: First,
you need to write a file similar to  <myServer.php> and put on the server. And make it accessible to client calls. Generally, if you put <index.php> in your apache htdocs folder with php.exe installed and configured to run for .php files, your browser call to localhost will generally bring this parsed with php executable.
Second,
You need to put php code in your client code (the one you pasted above) something similar to this...
<?php
// Create connection
$con=mysqli_connect("localhost","your username to mysql","password for it","your mysql db instance name");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  } else {
 // execute the queries you intend DDL or DML statements
  }
?>

Note This process will take at least a day to finally debug and make everything work.

A: You can use Jquery Ajax, to send and get the response.
$.ajax({
        type:'POST',
        url: 'confirm.php',
        data: "really=yes&sure=yes",
        success:function(data){
                //Need to split data here
        }
    });

And then use response (in JSON) to do some rules.


text: Q: Dell E5450 laptops will not recognize any internal HDD I have updated the BIOS, defaulted the settings in the BIOS. I have also changed out the MB for a new one along with the proprietary SATA connection. We have tested out parts from a fully functional e5450 but with no results. I even tried powering down the system by disconnecting the battery and the power supply and holding down start for a while. We have also taken it apart and put it back together again just to make sure nothing was amiss. We are out of options that we know of outside of shipping it back to the warranty people and let them have a try at it. This is not the first time this issue has occurred and the last issue was resolved by shipping it off, having them fix it without telling us how they did it.


text:
Q: How to know when window control styling completed I have a window.xaml which has components with different kind of styling( border color red, opacity changed and so on). In one moment I want to create a screenshot and save to folder. But before that the window background should be transparent and someCanvas should be hidden.
How do I know when the styling method finished so I can take a screenshot?
public void SomeMethod()
{
    ChangeWindowControlStyles();

    //TODO: waint till 'ChangeWindowControlStyles' finished

    TageScreenshotAndSave();
}

public void ChangeWindowControlStyles()
{
     this.Background.Opacity = 0;

     this.someCanvas.Visibility = Visibility.Collapsed;

     //Some other stuff related to window content styling
}

public void TakeScreenshotAndSave()
{
    //No multithreading happening here

    //Just taking screenshot and saving to folder
}

EDIT
The window itself is transparent WindowStyle="None", that means it has no borders. In the start the window's Background.Opacity is set to 0.1 and all controls are visible (there are other controls than someCanvas that should always be visible).
Before screenshot is taken someCanvas is hidden and the Background.Opacity is set to 0.
Window.xaml
<Window
    WindowStartupLocation="CenterScreen"
    ResizeMode="NoResize"
    WindowState="Maximized"
    WindowStyle="None"
    AllowsTransparency="True" >

   <Window.Background>
        <SolidColorBrush Opacity="0.1" Color="White"/>
    </Window.Background>

        <Grid Name="mainGrid" Background="Transparent" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Margin="0">

            <!--Main canvas, function holder-->
            <Canvas Name="canvasAlwaysVisible" Margin="0" Panel.ZIndex="5">
                <!-- Controls that are always visible -->
            </Canvas>

            <Canvas x:Name="someCanvas" Margin="0" Background="Transparent" Visibility="Visibility">
                <!-- Controls with styling -->
            </Canvas>

        </Grid>
</Window>

EDIT 2
Another thing to mention is that inside TakeScreenshotAndSave there is also System.IO operations like - get all folders in directory, creation new directory and so on. Maybe .NET sees that and it is ran asynchronously.

A: Looks like I found the solution. I don't know why it works, will need to investigate more. That TakeScreenshotAndSave method that I mentioned in code sample was somehow running on different thread. When wrap that method inside Application.Current.Dispatcher it worked!
public void SomeMethod()
{
    ChangeWindowControlStyles();

    var m_dispatcher = Application.Current.Dispatcher;

    m_dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.ApplicationIdle,
    new System.Threading.ThreadStart(delegate
    {

        TakeScreenshotAndSave(); //Now running on UI thread

    }));
}


text:
Q: SQL join 2 same columns in a result So I tried to made s query
SELECT FA.code, FA.standing,FA.connection, RE.code, RE.technology
FROM FA, RE
WHERE FA.code = RE.code

Which created a result
code standing connection code technology
XXX   XXX      XXX        XXX    XXX

And I need to join the 2 code columns together and join the duplicates as well.
There is very likely an easier way to join these 2 tables without duplicate columns so please I am open to suggestions.
EDIT: for samples I am expecting
code standing connection technology
XXX    XXX     XXX          XXX
I want to join the second code column into the first one (both code has mostly the same results so I dont want to show duplicates)
or find completely different way with JOINs

A: Are you expecting something like this?
SELECT F.code, F.standing, F.connection, R.technology
FROM FA AS F
INNER JOIN RE AS R ON F.code = R.code

A: this will work:
SELECT FA.code, FA.standing,FA.connection, RE.code, RE.technology
FROM  table_Name1 FA, table_Name2 RE
WHERE FA.code = RE.code


text:
Q: How to know the importance of all the variables and levels in them using Random Uniform Forest in R? I have a dataset containing 3 parameters (Region( factors - say US,UK,Aus,NZ),Domain or Industry( factors - say IT,Electrical,Mechanical) and Scope - good or bad). Using Random Uniform Forest package in R gives importance of Region and Domain on the Scope(variable to be predicted), but it does not end up showing importance of all the categories  i.e, it calculates the importance of Region US,UK,NZ,AUS and Domain IT,Electrical and Mechanical individually on the scope. While showing it shows only top 6 or a few parameters, not all.
Is there any way to get all the importance values being calculated.
Thanks in advance  0


text:
Q: Running ASP.NET 5 Cross-Platform I'm interested in ASP.NET 5 on my Windows and Mac OS machines. To get started, I installed Visual Studio 2015 RC on my Windows machine. I created a new, empty web site for ASP.NET 5 (aka vNext). I updated the template with a Views directory and included the MVC and Static Files nuget packages. I can successfully run this "Hello World" app. I also was successful in checking it into GitHub and automatically deploying it to Azure as a Website.
Then, I cloned the repository on my Mac OS machine. I successfully ran dnu restore to get the packages. I then ran dnx . run. When I do this, I get an error though. The error is:
'Website' does not contain a static 'Main' method suitable for an entry point

What am I doing wrong? I have a Startup.cs file. I know it works based on the fact that it runs on Windows and in Azure. Yet, I can't figure out what I'm missing. My Startup.cs file looks like this:
Startup.cs
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.DependencyInjection;

namespace Test.Site.Web
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app)
        {
            app.UseErrorPage();
            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute("default",
                  "{controller}/{action}/{id}",
                  defaults: new { controller = "Home", action = "Index" });
            });

            app.UseMvc();
            app.UseWelcomePage();
        }
    }
}

What did I do wrong?

A: In your project.json file, there should be a set of commands to run the project. By default, one of those is web and one is kestrel. Kestrel is the server for OS X and Linux, it's based on libuv, the same library that powers Node.
"commands": {
    "gen": "Microsoft.Framework.CodeGeneration",
    "kestrel": "Microsoft.AspNet.Hosting --server Kestrel --server.urls http://localhost:5004",
    "web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5002"
},

(I don't have VS 2015 in front of me at the moment, so I'm not 100% sure of the default commands in an "empty" project, so you may need to add the kestrel command).
So run this command to start your server on OS X or Linux:
dnx . kestrel

If you were starting it from the command prompt on Windows, you'd use:
dnx . web

Note you can customize the commands however you like. For example, one command might generate the database. Another might analyze the server for system requirements. One might even uninstall the application!


text:
Q: Sort SQL result by date greater than today (d-M-Y) In my sql query I output dates in chronological order.
The dates in my database are stored in d-M-Y format.
What I want to do is sort the results by dates equal to or greater than today to be output first.
In my query I have this sort in my query
...From $db ORDER BY STR_TO_DATE(sortdate, '%d-%M-%Y') ASC

Can anyone tell me if I can do a comparison on todays date as each record is output from the db?
This will give me todays date
$todaysdate = date("d-M-Y", time());

but can anyone tell me if I can build that into my query?
Thanks in advance.

A: check mysql DATEDIFF in combination with CURRENT_DATE ==>
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_current-date

A: You really should be storing the dates in a dateTime format. That will make it much easier to do all sorts of orders, comparisons and plenty of other things. You could for example, then use the mysql now() function to only get the results you need?
...From $db where sortDate>=now() ORDER BYsortdate ASC

A: My guess is that you saved the date in a VARCHAR column. Please don't do that, you make it very complicated for yourself when you want to do stuff (like this) with the date. I'd suggest that you convert the column to a DATE field and then just use:
SELECT * FROM my_table WHERE my_date_field >= CURDATE()

And if you want to output the date in the d-m-Y format, you can use DATE_FORMAT()

A: Assuming sortdate is datetime field, in order to display dates equal to or greater than today first,could use UNION.
SELECT * FROM my_table WHERE sortdate>= CURDATE()
UNION
SELECT * FROM my_table WHERE sortdate< CURDATE()

A: You can use WHERE sortdate >= $todaysdate

A: Just put this condition in where like date_column >= curdate()/$todaysdate
thanks


text:
Q: uwsgi_master_fifo()/mkfifo(): Permission denied Well I am trying to get django aplication on a prodaction server using uwsgi and docker. On production server nginx is started but it does not configured for uwsgi. I install uwsgi using pip without virtual environment into docker. However when I try up service with django app I get uwsgi_master_fifo()/mkfifo(): Permission denied [core/fifo.c line 112].
My uwsgi.ini:
[uwsgi]
http-socket    = :8000
chmod-socket   = 777
chdir          = /api/
module         = MenStore.wsgi:application
static-map     = /staticfiles=static

master          = true
processes       = 4
offload-threads = 4
vacuum          = true
harakiri        = 30
max-requests    = 10000
stats           = :9191

memory-report  = true
enable-threads = true
logger         = internalservererror file:/tmp/uwsgi-errors.log

post-buffering = 1

buffer-size = 16383

uid            = 1000
gid            = 1000

touch-reload = uwsgi-reload
master-fifo = uwsgi-fifo

My django app service into docker-compose file:
api: &api
    build:
      context: Backend
      dockerfile: Dockerfile
    ports:
      - "8000:8000"
    volumes:
      - "/root/MenStore/media/:/api/media/:rw"
    command: uwsgi --ini /api/uwsgi.ini
    depends_on:
      postgres:
        condition: service_healthy
      redis:
        condition: service_started

A: I found solution. I added RUN chmod 0777 [work_directory] into my Dockerfile.


text:
Q: Assigning a variable to pasted name of column in R I have a few data frames with the names:
Meanplots1,
Meanplots2,
Meanplots3 etc.
I am trying to write a for loop to do a series of equations on each data frame.
I am attempting to use the paste0 function.
What I want to happen is for x to be a column of each data set. So the code should work like this line:
x <- Meanplots1$PAR

However, since I want to put this in a for loop I want to format it like this:
for (i in 1:3){
   x <- paste0("Meanplots",i,"$PAR")
   Dmodel <- nls(y ~ ((a*x)/(b + x )) - c, data = dat, start = list(a=a,b=b,c=c))
}

What this does is it assigns x to the list "Meanplots1$PAR" not the actual column. Any idea on how to fix this?

A: We can get all the data.frame in a list with mget
lst1 <- mget(ls(pattern = '^MeanPlots\\d+$'))

then loop over the list with lapply and apply the model
DmodelLst <- lapply(lst1, function(dat) nls(y ~ ((a* PAR)/(b + PAR )) - c,
         data = dat, start = list(a=a,b=b,c=c)))

Replace 'x' with the column name 'PAR'.

In the OP's loop, create a NULL list to store the output ('Outlst'),  get the value of the object from paste0, then apply the formula with the unquoted column name i.e. 'PAR'
Outlst <- vector("list", 3)
ndat <- data.frame(x = seq(0,2000,100))

for(i in 1:3) {
   dat <- get(paste0("MeanPlots", i))
   modeltmp <- nls(y ~ ((a*PAR)/(b + PAR )) - c,
          data = dat, start = list(a=a,b=b,c=c))
   MD <- data.frame(predict(modeltmp, newdata = ndat))
   MD[,2] <- ndat$x
   names(MD) <- c("Photo","PARi")
   Outlst[[i]] <- MD

  }

Now, we extract the output of each list element
Outlst[[1]]
Outlst[[2]]

instead of creating multiple objects in the global environment


text:
Q: Delphi JEDI JCL crash Windows 7 on installation I search for a solution.
We have Delphi 6 Prof on Win7/X64.
When I tried four times to install JCL, the Windows crash with Blue Death.
I set the installer.exe to "Windows XP mode" but nothing happens.
How can I install JCL to my Delphi, and what CAN cause full crash in Win7?
Thanks:
   dd

A: Most likely this is a hardware fault. Run diagnostics on your disk. Hope that your backup works!


text:
Q: Where do I obtain the Rocketfish RF-AFHD35 Card Reader driver? I've got a RocketFish SATA enclosure, model number RF-AHD35.  It has a card reader on it.  Windows doesn't see the card reader.  I figure it's a driver problem.  But, I don't have the CD that came with it anymore, nor is it available from their site.  As a matter of fact, their site looks like my 8 year old made it.
Does anyone have access to this driver?

A: Before this gets moved to Super User (which is where it belongs), I would suggest www.driverguide.com - I've been using them since the late 1990s and they're pretty good, just be careful about which download link you click because the real ones can sometimes be hidden among fake advertisements pretending to be the real links.

A: RocketFish is a company that rebrands a products made by companies that no one's ever heard of. That way Best Buy (who owns RocketFish) can sell products that look like they are backed by a large company, but still don't look like the 'Store Brand'.
It might be possible to find out what the product or model number originally was and get drivers from the actual manufacturer, though the actual manufacturer's webpage is likely in Chinese.

A: The product page doesn't list a CD as being included in the package, which makes me suspect that it's not so much a driver problem as a defective unit.  Have you successfully used the card reader on a different computer?


text:
Q: jmockit of HttpURLConnection throws NullPointerException I am using JMockit to mock HttpURLConnection.  My initial two test cases (fileNotFoundResponse, badMimeType) work find, but my third test case (contentDisposition) generates NPE within the Expectations block and I don't know why.
Here is the Junit test class:
@RunWith(JMockit.class)
public class TestHttpGET1 { @Before
    public void setUp() throws Exception {
    }

    @After
    public void tearDown() throws Exception {
    }

    public final class MockURL extends MockUp<URL> {
        @Mock
        public void $init(String strURL) {}
        @Mock
        public URLConnection openConnection() throws IOException {
        //System.out.println(">>mockURL.openConnection");
            return mockCon;
        }
    }

    @Mocked HttpURLConnection mockCon;
    @Mocked LoggerFactory mockLoggerFactory;
    @Test
    public void fileNotFoundResponse() {
//      new MockUp<URL> (){
//          @Mock
//          public void $init(String strURL) {}
//          @Mock
//          public URLConnection openConnection() throws IOException {
//              //System.out.println(">>mockURL.openConnection");
//              return mockCon;
//          }
//      };
        new MockURL();
        String contents = "";
        try {
            new NonStrictExpectations() {{
                    LoggerFactory.getLogger(TestHttpGET1.class); result = null;
                mockCon.getResponseCode(); result = 404;
            }};
            contents = Main.httpGETFile("http://bogus");
        } catch (IOException e) {
            e.printStackTrace();
        }
        assertEquals("Contents should be null", null, contents);
    }

    @Test
    public void badMimeType() {
        new MockURL();
        String contents = "";
        try {
            new NonStrictExpectations() {{
                    mockCon.getResponseCode(); result = 200;
                    mockCon.getHeaderField("Content-Disposition"); result = null;
                    mockCon.getContentType(); result = "bogus-mime-type";
                    mockCon.getContentLength(); result = 1000;
            }};
            contents = Main.httpGETFile("http://bogus.m3u8");
        } catch (IOException e) {
            e.printStackTrace();
    }
        assertEquals("Contents should be null", null, contents);
    }

    @Test
    public void contentDisposition() {
        new MockURL();
        String contents = "";
        try {
            new Expectations() {{
                    String str = "Hello World";
                    mockCon.getResponseCode(); result = 200;
                    mockCon.getHeaderField("Content-Disposition"); result = "filename=test.m3u8";
                    mockCon.getContentType(); result = "application/x-mpegURL";
                    mockCon.getContentLength(); result = 11;
System.out.println("getContentLength");
                    mockCon.getInputStream(); result = (InputStream) new ByteArrayInputStream(str.getBytes("UTF8"));
System.out.println("getInputStream");
            }};
            contents = Main.httpGETFile("http://bogus.m3u8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        assertEquals("Contents should match", "Hello World", contents);
    }

}

The NPE is generated on this line:
                    mockCon.getInputStream(); result = (InputStream) new ByteArrayInputStream(str.getBytes("UTF8"));

Here is the stack trace:
java.lang.NullPointerException
    at java.net.URLClassLoader.getResourceAsStream(URLClassLoader.java:237)
    at java.net.URLConnection.getInputStream(URLConnection.java)
    at edu.psu.gv.sweng861.TestHttpGET1$3.<init>(TestHttpGET1.java:97)
    at edu.psu.gv.sweng861.TestHttpGET1.contentDisposition(TestHttpGET1.java:90)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

I have no idea why the code is executing within java.net.URLClassLoader.getResourceAsStream.
I am using the latest version of JMockit v.1.19.

A: Here is the correct answer from Rogério. Note that answer shows only one test case.
    @Mocked URL mockURL;
    @Mocked HttpURLConnection mockCon;
    @Mocked LoggerFactory mockLoggerFactory;

    @Test
    public void contentDisposition() {
        //new MockURL();
        String contents = "";
        try {
            new Expectations() {{
                    String str = "Hello World";
                    mockCon.getResponseCode(); result = 200;
                    mockCon.getHeaderField("Content-Disposition"); result = "filename=test.m3u8";
                    mockCon.getContentType(); result = "application/x-mpegURL";
                    mockCon.getContentLength(); result = 11;
System.out.println("getContentLength");
                    mockCon.getInputStream(); result = (InputStream) new ByteArrayInputStream(str.getBytes("UTF8"));
System.out.println("getInputStream");
            }};
            contents = Main.httpGETFile("http://bogus.m3u8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        assertEquals("Contents should match", "Hello World\n", contents);
    }


text:
Q: jQuery.Deferred exception: Kendo is not defined ReferenceError: Kendo is not defined I am trying to populate data to a kendo datagrid using MVC5. Although ,I have referenced the javascript files correctly, I get the error message jQuery.Deferred exception: Kendo is not defined ReferenceError: Kendo is not defined.
When i see in the console window, the error is on the following line
  var carsDataSource = new Kendo.Data.DataSource({ data: cars });

Please see the code below
The head section in the layout mage

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>

    @Styles.Render("~/Content/css")
    <link href="http://kendo.cdn.telerik.com/2017.1.118/styles/kendo.common.min.css" rel="stylesheet" />
    <link href="http://kendo.cdn.telerik.com/2017.1.118/styles/kendo.default.min.css" rel="stylesheet" />

    @Scripts.Render("~/bundles/modernizr")
    @Scripts.Render("~/bundles/jquery")

    @**@

DataGridController
 public class DataGridController : Controller
    {
        // GET: DataGrid
        public ActionResult Index()
        {
            return View();
        }
    }

Index.html
@{
    ViewBag.Title = "Index";
}

Index

A: *

*you have mis-spelled the constructor

*as well as look like you have commented out kendo.all.min.js javascript file

*The major reason when this error show up is misconfiguration of resources needed look into the running sample provided and see if you are missing some kendo related javascript file and add it into your bundle . Most probably there is something wrong with the included resources.

Below is the minimum required configuration of kendo grid

    <title></title>
    <link rel="stylesheet" href="styles/kendo.common.min.css" />
    <link rel="stylesheet" href="styles/kendo.default.min.css" />
    <link rel="stylesheet" href="styles/kendo.default.mobile.min.css" />

Also unless you set the grid auto bind to false you don't need to initiate a read() function. look into this documentation read method of kendo grid
Here is live version of your code .
Dojo sample here working dojo sample
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Untitled</title>

  <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2017.1.118/styles/kendo.common.min.css">
  <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2017.1.118/styles/kendo.rtl.min.css">
  <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2017.1.118/styles/kendo.default.min.css">
  <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2017.1.118/styles/kendo.mobile.all.min.css">


text:
Q: The required rows not removed from JTable here's my ui:

As I soon as uncheck  the checkbox "single" the following rows in the table which has room type as "Single" needs to be removed.
here's how I attempted:
 private void singlecheckboxActionPerformed(java.awt.event.ActionEvent evt) {

      if (!singlecheckbox.isSelected()) {
        for (int i = 0; i <roomtable.getRowCount(); i++) {
            if (((DefaultTableModel)roomtable.getModel()).getValueAt(i, 1).equals("Single")) {
               ((DefaultTableModel) roomtable.getModel()).removeRow(i);

            }

        }
    }

}

But the issue is only the first row is removed, not first and the second..

A: Once the first row is removed, the rowCount changes...
For example, this is what's going on your loop
i = 0
rowCount = 2
delete Row at i
rowCount = 1;
i = 1 ... 1 > rowCount, exit...

Instead you could try something more like...
((DefaultTableModel) roomtable.getModel()).setRowCount(0);

I know, massive cheat...
For future reference, when deleting this from some kind list (and there's no removeAll or clear method), it might be better to use something more like...
while (count > 0) {
    remove first element from list...
}

Updated...
Okay, so you need to remove "certain" items...you can use a for-loop as the automatically changes the index value, you need more control over the index value and increment only when you need it to change, like when you want to keep the row, for example...
DefaultTableModel model = (DefaultTableModel)roomtable.getModel();
int row = 0;
while (row < model.getRowCount()) {
    if ((model).getValueAt(row, 1).equals("Single")) {
        model.removeRow(row);
    } else {
        row++;
    }
}


text:
Q: Ember.JS view not rendering? Maybe I'm missing something, but I'm really confused as to why this isn't working:
// The Javascript
App.UsersView = Ember.View.extend({
    templateName: 'user-list'
});

// The HTML

Nothing is displaying?
(The application view displays so it's not a problem with the way ember.js is loaded. Just when trying to use custom views.)

A: The only view/template that is automatically appended to the dom is application. To include UsersView on the page, try:

Working example here: http://jsbin.com/iluvik/1/edit
Typically the view helper is not necessary as most of the views/templates your application will get created by the ember router. Have a look at the Ember Routing Guide for a better understanding of how to wire things up.


text:
Q: is there a defaultValue property for radio select? I am wondering if there is a way to reset a radio to it's originally selected option. I know of defaultValue for inputs but is there a way to make it so that I can reset the radios back to their originally selected value on page load?
I am not wanting to simply unselect all radios. I am trying to put them back to their originally selected value.
Thanks for any info.

A: Yes, radio inputs do have defaultValue property, but what you are looking for is the defaultChecked property:
$('input[type=radio]').prop('checked', function() {
   return this.defaultChecked;
});

That being said, if you want to reset the form you can use the reset method of the HTMLFormElement object:
$('#formElement').get(0).reset();

A: I think you want this
<form action="">
    <input type="radio" name="gender" value="male" checked="true"/>Male
    <input type="radio" name="gender" value="female"/>Female
    <input type="reset" value="reset"/>
</form>

Any time you will reset the form, the male radio button will be selected.

A: I will rather make a jQuery plugin like this:
$.fn.defaultVal = function (checked) {
    if(checked === true || checked === false) {
        $(this).attr("data-default", checked);
        return;
    }
    if(!$(this).attr("data-default")) {
        console.log("No default value assigned!");
        return;
    }
    return $(this).attr("data-default");
}

JSFIDDLE LINK UPDATE
Working Demo is here: JSFIDDLE


text:
Q: How to fit the  video to the parent container's width and height <div id="player" width='2000px' height='600px'>
<object  id="pl" classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6">
    <param name='url' value='Video/3.mp4'/>
    <param name='ShowControls' value='-1' />
    <param name='ShowDisplay' value='-1' />
    <param name='ShowStatusBar' value='-1' />
    <param name='stretchToFit' value='0' />
    <param name='uiMode' value='none' />
</object>
 </div>

how can I fit the video's width and height to the container "player" ?
I want to stretching the video.

A: It works with the following CSS lines:
#player {
    width: 2000px;
    height: 600px;
}
#pl {
    height: 100%;
    width: 100%;
}

Attention, you set a width and a height attributes on a div element.
This will not work, you can only size a div element with CSS rules or via the style attribute.
You can play with my solution on this jsfiddle.
Cheers,
Thomas.


text:
Q: include values in a javascript string with '+=' I've following function:
function generateJSONstringforuncheckedfilters(){
    jsonstring = '';
    jsonstring = "[";
    $('body').on('click', 'input', function(){
        jsonstring += "[{'OrderGUID': '"+ $(this).attr('data-orderguid') +"' 'FilterGUID': '"+ $(this).attr('data-filterguid') +"', 'nValue': 0, 'Value': '"+ $(this).attr('value') +"', 'Operator': 'NULL', 'Unit': 'NULL'}";
    });
    jsonstring += "]";
    console.log(jsonstring); // Output: []
}

My output is this = [ ]
But I want to achieve this:
[{'OrderGUID': '46dd8c82-44a6-4dc5-9517-320c31645211' 'FilterGUID': '17caabea-c313-48c9-b965-739ef8d09a1f', 'nValue': 0, 'Value': 'volladressierbar', 'Operator': 'NULL', 'Unit': 'NULL'}]

And if I click again into a checkbox field the jsonstring have to expand like this:
[
{'OrderGUID': 'aaaaaa' 'FilterGUID': '17caabea-c313-48c9-b965-739ef8d09a1f', 'nValue': 0, 'Value': 'volladressierbar', 'Operator': 'NULL', 'Unit': 'NULL'},
{'OrderGUID': 'bbbbbb' 'FilterGUID': '17caabea-c313-48c9-b965-739ef8d09a1f', 'nValue': 0, 'Value': 'volladressierbar', 'Operator': 'NULL', 'Unit': 'NULL'}
]

I hope you understand my problem.
Edit:
These are my checkboxes:
<input type="checkbox" checked="checked" id="check1" value="volladressierbar" name="volladressierbar" data-filterguid="17caabea" data-orderguid="aaaa" count="1"> volladressierbar
<input type="checkbox" checked="checked" id="check1" value="teiladressierbar" name="teiladressierbar" data-filterguid="18cagbea" data-orderguid="bbbb" count="1"> teiladressierbar

A: You could try something like so:
var uncheckedFilters = [];

function generateJSONstringforuncheckedfilters(){
    $('body').on('click', 'input', function() {
        var checkboxSelector = $(this);
        var checkboxFilterGUID = checkboxSelector.attr('data-filterguid');
        if(checkboxSelector.is(':checked')) {
            uncheckedFilters.forEach(function(filter) {
                if(filter.FilterGUID === checkboxFilterGUID) {
                    var filterIndex = uncheckedFilters.indexOf(filter);
                    if(filterIndex > -1) {
                        uncheckedFilters.splice(filterIndex, 1);
                    }
                }
            });
        } else {
            uncheckedFilters.push({
                OrderGUID: checkboxSelector.attr('data-orderguid'),
                FilterGUID: checkboxFilterGUID,
                nValue: 0,
                Value: checkboxSelector.attr('value'),
                Operator: 'NULL',
                Unit: 'NULL'
            });
        }
        console.log(JSON.stringify(uncheckedFilters));
    });
}

This way you are generating an array of filter objects which you could simply convert to json using JSON.stringify like in my example above.
JSFiddle:
https://jsfiddle.net/7j4g0ddb/

A: try this
  $('body').on('click', 'input', function(){
    var jsonstring = '';
    jsonstring = "[";
     $( 'body' ).find( "input[type='checkbox']:checked" ).each( function(){
       jsonstring += generateJSONstringforuncheckedfilters( $( this )  ) ;
     } );
     jsonstring += "]";
     console.log(jsonstring);
  });

function generateJSONstringforuncheckedfilters( $thisObj )
{
       return "{'OrderGUID': '"+ $thisObj.attr('data-orderguid') +"' 'FilterGUID': '"+ $thisObj.attr('data-filterguid') +"', 'nValue': 0, 'Value': '"+ $thisObj.attr('value') +"', 'Operator': 'NULL', 'Unit': 'NULL'}";
}

A: First, for information, all element are juste one similiar Id on your HTML document (you can see W3C normes for that) it's for your HTML Code :
<input type="checkbox" checked="checked" id="check1" value="volladressierbar" />
<input type="checkbox" checked="checked" id="check1" value="teiladressierbar" />
<!--  Id of both Elements is similar -->

That is correct :
<input type="checkbox" checked="checked" id="check1" value="volladressierbar" />
<input type="checkbox" checked="checked" id="check2" value="teiladressierbar" />

Also, you can check that for the javascript code:
$('body').on('click', 'input', function(){
        var arrayJson = [];
        // get all input checked
        $( 'body' ).find( "input[type='checkbox']:checked" ).each( function(){
            var recupObject = "{'OrderGUID': '"+ $(this).attr('data-orderguid') +"' 'FilterGUID': '"+ $(this).attr('data-filterguid') +"', 'nValue': 0, 'Value': '"+ $(this).attr('value') +"', 'Operator': 'NULL', 'Unit': 'NULL'}";
            arrayJson.push(recupObject);
        });

        // create a json with all data input getted.
        if (arrayJson.length > 0){
            var jsonOutput = "[";
            for (index = 0; index < arrayJson.length; index++) {
              jsonOutput += arrayJson[index] + ",";
            }
            jsonOutput = jsonOutput.substring(0, jsonOutput.length-1); // remove last ','
            jsonOutput += "]";
        }
        console.log(jsonOutput ); // Log the Json output
    });


text:
Q: parfor index what is the initval for each work ID? I met a problem when using parfor in matlab:
I know parfor will divide the work to several workers and each worker has its own index range as parfor idx=initval: endval <body> end;
The problem is for each worker, I need to do something when idx==initval, which is different from other index value (such as print something so that I know roughly what it's doing now, but I don't need to do it for every index value).
In the for...end procedure, I clearly know where the index begins, but I don't know how to do it in parfor.
Do you have any suggestions? thanks in advance.
for i=1:n
  if(i==1)
    fprintf('I am at the beginning of this loop\n!');
  end
end


text:
Q: What is the sync interval of Google fit data with their backend servers ( REST api)? I use Google Fit Rest API to get data about user activities, but the data is different if I look at my app and google fit app at the same time. Everything is synchronized only after a while - sometimes it takes 15 minutes, which is pretty good, but sometimes it can take several hours or even more.
I just want to know how exactly Google Fit synchronizes with the server and is it possible to speed up this process?
Thanks a lot!


text:
Q: Limit of Variant of Geometric Sequence with Common Ratio any Real Number Between 0 and 1 I was wondering if the result that the limit of a geometric sequence with common ratio $r\in(0,1)$ is 0 held if successive terms were multiplied by any real number between $0$ and $1$. In a recursion this would be $a_{n+1} = r_n a_n$, where $a_1 =1$ and $r_n$ is any real number between $0$ and $1$. Thanks.

A: No. Take $r_n = 1-\frac{1}{(n+1)^2}$, i.e. $$
a_{n+1} = \left(1-\frac{1}{(n+1)^2}\right) a_{n}.
$$
You have $$
a_n = \prod_{k=2}^{n}\left(1-\frac{1}{k^2}\right) = e^{\sum_{k=2}^n \ln\left(1-\frac{1}{k^2}\right)}.
$$
However, $\sum_{k=2}^n \ln\left(1-\frac{1}{k^2}\right)$ converges to
$$
\ell = \sum_{k=2}^\infty \ln\left(1-\frac{1}{k^2}\right) \in (-\infty, 0)
$$
so that $a_n\xrightarrow[n\to\infty]{} e^\ell > 0$.
(One can even prove this limit $e^\ell$ is equal to $\frac{1}{2}$, rewriting $$
\sum_{k=2}^\infty \ln\left(1-\frac{1}{k^2}\right) = \sum_{k=2}^\infty \left(\ln\frac{k+1}{k} - \ln\frac{k}{k-1}\right) = -\ln 2
$$
as a telescopic series.)


text:
Q: Fetch API data with react and filter search input with autocomplete I have a question regarding a React filter search input.
I have two Components the the moment.
FirstPageComponent.js
import React from "react"
import AutoComplete from "./AutoComplete"

export class FirstPageComponent extends React.Component {
  constructor() {
    super()
    this.state = {
      rows: [],
      loading: true,
    }
  }
  async componentDidMount(searchTerm = "marvel") {
    await fetch(
      "https://api.themoviedb.org/3/search/movie?api_key=&query=" +
        searchTerm
    )
      .then(response => response.json())
      .then(responseData => {
        this.setState({
          rows: responseData.results,
          loading: false,
        })
      })
      .catch(error => {
        console.log("Error fetching and parsing data", error)
      })
  }
  render() {
    console.log(this.state.rows)
    return <AutoComplete movies={["hej"]} />
  }
}

and
AutoComplete.js
import React from "react"

export default class AutoComplete extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      rows: [],
      loading: false,
      userInput: "",
    }
  }

  onChange = e => {
    const { movies } = this.props
    const userInput = e.currentTarget.value

    const rows = movies.filter(
      suggestion =>
        suggestion.toLowerCase().indexOf(userInput.toLowerCase()) > -1
    )

    this.setState({
      rows,
      loading: true,
      userInput: e.currentTarget.value,
    })
  }

  onClick = e => {
    this.setState({
      rows: [],
      loading: false,
      userInput: e.currentTarget.innerText,
    })
  }

  render() {
    const {
      onChange,
      onClick,
      state: { rows, loading, userInput },
    } = this
    let moviesListComponent
    if (loading && userInput) {
      if (rows.length) {
        moviesListComponent = (

            {rows.map((movie, index) => {
              return (

                  {movie}

              )
            })}

        )
      } else {
        moviesListComponent = (
          <>

Couldn't find any movies. Try searching for another movie.

          </>
        )
      }
    }

    return (
      <React.Fragment>
        <input type="search" onChange={onChange} value={userInput} />
        {moviesListComponent}
      </React.Fragment>
    )
  }
}

*

*I basically want to know if i'm approaching this the right way. I want to make a dynamic request for movie titles from fetch("https://themovie.db") API.

*Send down the movie titles as props and then filter the values in autocomplete component if the user input is similar to the movie title props.
Am i thinking about this the right way? I've tried to have the fetch call in the same component as AutoComplete but haven't gotten it to work as i want it to. How would you setup the component structure if you'd be solving this issue for example?
Feel free to ask if there're any confusions.
Thanks

A: These are my assumptions about the above code, let me know if any are incorrect.

*

*You're doing an initial API request for a list of movies by search term. That search term is given outside of the code above and doesn't change by any mechanism above.

*You're further filtering the data returned by the API request dynamically via the AutoComplete component.

Most of your React code here looks pretty good, but I've got some recommendations:

*

*In general, I find it's best to keep the list of things completely separate, so I would create a separate MovieList function component that simply takes an array of movie objects, and a titleFilter string and renders them.

*componentDidMount doesn't take arguments. searchTerm should be a prop of FirstPageComponent (presumably set by the parent component by some kind of selection or user input)

*I'd rename AutoComplete to TitleFilter or the like. It's not really auto-completing, it's more of a filter field.

*This line: if (loading && userInput) { will result in displaying no movies when the user hasn't yet filled in text into the filter field. I'm not sure that is what you would want.

*This line is a bit misleading:
Couldn't find any movies. Try searching for another movie.
 because you could have just filtered out all the results returned. In this case, it wasn't that you couldn't find movies, it's that your filter is too restrictive.

*For the onClick handler, I'm not sure such a general approach is best. It could create a strange interaction if you were to somehow click on the
, for example. To improve this, I'd recommend each movie row component implement its own onClick and call a function to set the filter.

*You're going to have to deal with pagination on this, I'd bet. Check your API and see what it does for that and make sure you're accounting for it.

Small nits:

*

*userInput: e.currentTarget.value, could be shortened to userInput,, which is shorthand for userInput: userInput, (you already have a variable named userInput.)

*For key props, an actual unique id would be better, in the case you change your filtering and index numbers don't line up with the unique rows you're rendering anymore.

*I like to go ahead and create a separate component for each row, so I'd make a MovieRow function component which takes a movie object and renders it. It just keeps the code a bit cleaner. (and makes #6 above easier to implement)


text:
Q: Trouble passing req to authenticate function in app.js In the app.js file of an express app I'm getting undefined on req.params.company.  Here's the relevant code...
var mongoose = require( 'mongoose' );
var authenticate = express.basicAuth(function(user, pass, req, res, next, callback) {
    Auth = mongoose.model('Auth');
    Auth.findOne({ token: user }, function(err, authObject){
            if (err) return next(err);
        //The next line is where the problem lies.  Req.params.company is undefined.
            var result = (user === authObject.token && req.params.company === authObject.companyName);
            console.log('result = ' +result);
            return result;
            //callback(null /* error */, result);
            })
});

app.get('/api/:company', authenticate, api.company);

I don't think it's relevant to the question, but just in case here is the code from my auth.js model.
var mongoose = require( 'mongoose' );

function toLower (v) {
  return v.toLowerCase();
}

var authSchema = new mongoose.Schema({
    token : { type : String, required : true, unique : true, index: true, set: toLower },
    companyName : { type : String, set: toLower },
    brandName : { type : String, set: toLower },
    active : Boolean
});

var Auth = mongoose.model('Auth', authSchema);

And finally for context, the objective of this code is simply to authenticate a token that is being passed as the user variable in http basic auth (password is null).  I also attempt to authorize the token for the company name that is given as a route parameter.
Can someone help me to understand why req.params.company would be coming back as undefined? If I log "req" by itself I get back "[Function]".

A: Looks like you're looking for code in the wrong place. Maybe do a console.log(arguments). Also, here's a link to code that could help: http://blog.modulus.io/nodejs-and-express-basic-authentication


text:
Q: How to Publish on my facebook page from my facebook app? I want to publish images to my facebook page from my application/website. How can I do this? Can anyone help me out with a php code?

A: Use the Feed API
eg: from javascript you can do like this-
var obj =   {
                link: URL,
                message: MESSAGE,
                access_token: ACCESS_TOKEN,

            };

FB.api('/PAGE_ID/feed', 'post',obj);

Note- the ACCESS_TOKEN is the user's token for the APP.
In this way the feed will be published on PAGE through the APP


text:
Q: I can't get my launch daemon to run my shell script For some reason, I am unable to get my shell script to run when the computer boots.  My script fine by itself, but for some reason my Launch Daemon is not starting the job.  Please help.
My launch daemon is saved in /Library/LaunchDaemons/local.pingtest.plist
My Launch Daemon Plist:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
    <dict>
    <key>Label</key>
    <string>local.pingtest</string>
    <key>ProgramArguments</key>
    <array>
        <string>/bin/sh</string>
        <string>/pingtest/pingtest.sh</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
</dict>
</plist>

my shell script:

/usr/bin/nohup /sbin/ping -i 5 ipaddress | /usr/bin/xargs -L 1 -I '{}' date '+%Y-%m-%d %H:%M:%S: {}' >> /pingtest/Ryan-lou.txt &

/usr/bin/nohup /sbin/ping -i 5 www.google.com | /usr/bin/xargs -L 1 -I '{}' date '+%Y-%m-%d %H:%M:%S: {}' >> /pingtest/Ryan-int.txt &

/usr/bin/nohup /sbin/ping -i 5 ipaddress | /usr/bin/xargs -L 1 -I '{}' date '+%Y-%m-%d %H:%M:%S: {}' >> /pingtest/Ryan-fcc.txt &

A: First I'd check the path of pingtest.sh relative to how it's defined in local.pingtest.plist.
I've not played around with the launch daemon on Macs yet but there may be some special need for it to be in /System/Library/LaunchDaemons instead. Not sure why it'd end up ignoring the other location by the time you're logged in and looking at it but I've seen specifications ignored before on systems so worth a try.
Next I'd check for things like conflicting Label identifiers and that my other keys mean what I think they mean.
Doesn't look like your script is dependent on non-launchd daemons, but those are things to keep in mind.

A: "Parsing" the script launchctl throws an error "nohup: can't detach from console: Inappropriate ioctl for device" and expects another command after the last &.
Add a proper shebang and remove the /usr/bin/nohup part as well as the last & in your shell script and it works:
#!/bin/sh

/sbin/ping -i 5 www.google.com | /usr/bin/xargs -L 1 -I '{}' date '+%Y-%m-%d %H:%M:%S: {}' >> /pingtest/Ryan-lou.txt &
/sbin/ping -i 5 ip1 | /usr/bin/xargs -L 1 -I '{}' date '+%Y-%m-%d %H:%M:%S: {}' >> /pingtest/Ryan-int.txt &
/sbin/ping -i 5 ip2 | /usr/bin/xargs -L 1 -I '{}' date '+%Y-%m-%d %H:%M:%S: {}' >> /pingtest/Ryan-fcc.txt


text:
Q: Help with a general solution for $\int \tan^a \theta$ Working out the integrals of $\tan^6 \theta$ I saw a pattern.  I would like to put it in series representation. The pattern is as follows:
$$\int \tan^a d\theta= \int\tan^{a-2}\theta(\sec^2\theta-1)\ d\theta= $$ $$ \int \tan ^{a-2}\theta\sec^2\theta\ d\theta-\int\tan^{a-2}\theta\ d\theta=$$ solving the first integral, let $u=\tan \theta, du=\sec^2\theta\ d\theta$ so $$ \int u^{a-2} du=\frac{1}{a-2+1}u^{a-2+1}=$$ $$\frac{1}{a-1}u^{a-1}= $$$$\frac{1}{a-1}\tan^{a-1}\theta-\int \tan^{a-2}\theta\ d\theta $$
then $$ \int u^{(a-2)-2} du=\frac{1}{(a-2)-1}u^{(a-2)-1}=$$ $$\frac{1}{a-3}u^{a-3}= $$$$\frac{1}{a-3}\tan^{a-3}\theta-\int \tan^{a-4}\theta\ d\theta $$ It goes on like this forever
$$\frac{1}{a-1}\tan^{a-1}\theta-\frac{1}{a-3}\tan^{a-3}\theta-\frac{1}{a-5}\tan^{a-5}\theta \text {....} \theta\ d\theta $$ So then my series should be....$$\frac{1}{a-1}\tan^{a-1}\theta-\big[\sum_{n=3}^{a-2} {\frac{1}{a-n}\tan^{a-n}\theta}\big] -\int \tan^{2}\theta\ d\theta\space \text{if a is even. OR}$$
$$\frac{1}{a-1}\tan^{a-1}\theta-\big[\sum_{n=3}^{a-2} {\frac{1}{a-n}\tan^{a-n}\theta}\big] -\int \tan\ d\theta\space \text{if a is odd}.$$
I am having problems tweaking this series so it only includes the odd values of "n"?
$addendum$
For those not reading the entire thread as discussed below. the value of n is $n=2k-1$.
The lower limit should be $k=1$ and the upper limit should be $\frac {a}{2}-1$ for even "a"'s and $\frac {a-1}{2}$ for odd. Thanks again to SemSem.

A: Simply you have
$$I_a=\int \tan^a d\theta= \int\tan^{a-2}(\sec^2-1)d\theta
\\=\frac{1}{a-1}\tan^{a-1}\theta-\int \tan^{a-2} d\theta
\\ I_a=\frac{1}{a-1}\tan^{a-1}\theta-I_{a-2}$$from this last one you can start by applying it many times to get your required formula. If $n$ is even we get
$$I_a=\frac{1}{a-1}\tan^{a-1}\theta-\frac{1}{a-3}\tan^{a-3}\theta+ \frac{1}{a-5}\tan^{a-5}\theta ....I_{2}
\\=\sum_{k\ =\ 1}^{\frac{a}{2}-1}(-1)^{k+1}\frac{1}{a-(2k-1)}\tan^{a-(2k-1)}\theta+(-1)^{\frac{a}{2}}I_2$$
If $n$ is odd we get
$$I_a=\frac{1}{a-1}\tan^{a-1}\theta-\frac{1}{a-3}\tan^{a-3}\theta+ \frac{1}{a-5}\tan^{a-5}\theta ....I_{1}
\\=\sum_{k\ =\ 1}^{\frac{a-1}{2}}(-1)^{k+1}\frac{1}{a-(2k-1)}\tan^{a-(2k-1)}\theta+(-1)^{\frac{a+1}{2}}I_2$$

A: $\newcommand{\+}{^{\dagger}}%
 \newcommand{\angles}[1]{\left\langle #1 \right\rangle}%
 \newcommand{\braces}[1]{\left\lbrace #1 \right\rbrace}%
 \newcommand{\bracks}[1]{\left\lbrack #1 \right\rbrack}%
 \newcommand{\ceil}[1]{\,\left\lceil #1 \right\rceil\,}%
 \newcommand{\dd}{{\rm d}}%
 \newcommand{\down}{\downarrow}%
 \newcommand{\ds}[1]{\displaystyle{#1}}%
 \newcommand{\equalby}[1]{{#1 \atop {= \atop \vphantom{\huge A}}}}%
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}%
 \newcommand{\fermi}{\,{\rm f}}%
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}%
 \newcommand{\half}{{1 \over 2}}%
 \newcommand{\ic}{{\rm i}}%
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}%
 \newcommand{\isdiv}{\,\left.\right\vert\,}%
 \newcommand{\ket}[1]{\left\vert #1\right\rangle}%
 \newcommand{\ol}[1]{\overline{#1}}%
 \newcommand{\pars}[1]{\left( #1 \right)}%
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}%
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,#2\,}\,}%
 \newcommand{\sech}{\,{\rm sech}}%
 \newcommand{\sgn}{\,{\rm sgn}}%
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}%
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$
Whenever we use your 'recurrence' we are left with an integral likes, for example,
$\ds{\int_{0}^{\mu}\tan^{a}\pars{\theta}\,\dd\theta}$ where $\ds{0 \leq \verts{\Re\pars{a}} < 1}$ and, because $\ds{\tan\pars{\theta}}$is periodic of period $\ds{\pi}$, $\ds{0 < \mu < \pi}$.

With $\ds{t \equiv \sin\pars{\theta}}$ and $\ds{\Lambda = \sin\pars{\mu}}$:
  \begin{align}
\int_{0}^{\mu}\tan^{a}\pars{\theta}\,\dd\theta&=\int_{0}^{\mu}
{\sin^{a}\pars{\theta} \over \cos^{a + 1}\pars{\theta}}\,\cos\pars{\theta}\dd\theta
=-\int_{0}^{\Lambda}{t^{a} \over \pars{1 - t^{2}}^{a/2 + 1/2}}\,\dd t
\\[3mm]&=-\int_{0}^{\Lambda^{1/2}}
{t^{a/2} \over \pars{1 - t}^{a/2 + 1/2}}\,\half\,t^{-1/2}\,\dd t
=-\,\half\int_{0}^{\Lambda^{1/2}}t^{a/2 - 1/2}\pars{1 - t}^{-a/2 - 1/2}
\,\dd t
\\[3mm]&=-\,\half\,{\rm B}_{\Lambda^{1/2}}\pars{{a \over 2} + \half,-\,{a \over 2} + \half}
\end{align}
  where $\ds{{\rm B}_{x}\pars{p,q}}$ is the Incomplete Beta Function.

$$
\color{#00f}{\large\int_{0}^{\mu}\tan^{a}\pars{\theta}\,\dd\theta
=
-\,\half\,{\rm B}_{\root{\sin\pars{\mu}}}
\pars{{a \over 2} + \half,-\,{a \over 2} + \half}}\,,\quad
\left\vert%
\begin{array}{c}
\quad\verts{\Re\pars{a}} < 1
\\[2mm]
\quad0 < \mu <  \pi
\end{array}\right.
$$


text:
Q: I cannot found modules in Django I'm trying to connect my Django with my MongoDB.
So, first of all, I install this:
pip install djongo

And all go fine, no errors.
But If you see my models.py archive:

It's like Django it's not finding and I can't import the models.
I tried to install again Django, but it says to me that it's already installed.

I think I'm installing this in another path or something like that, but I don't know how to solve this.
My Django archive its in C:\PROYECTOS\PageSpeed_Insights__Selenium-Python\miweb

A: It seems that you are installing djongo in your virtualenv paginaweb, you have to configure PyCharm (or whatever IDE you are using) to look for the packages in that virtualenv, here you can see how to do it for PyCharm. It should work after that.


text:
Q: Group, Collectors, Map (Int to String), Map (Map to Object) This is a continuation of my previous question at Group, Sum byType then get diff using Java streams.
As suggested, I should post as a separate thread instead of updating the original one.
So with my previous set of question, I have achieved that, and now, with the continuation.
Background:
I have the following dataset
Sample(SampleId=1, SampleTypeId=1, SampleQuantity=5, SampleType=ADD),
Sample(SampleId=2, SampleTypeId=1, SampleQuantity=15, SampleType=ADD),
Sample(SampleId=3, SampleTypeId=1, SampleQuantity=25, SampleType=ADD),
Sample(SampleId=4, SampleTypeId=1, SampleQuantity=5, SampleType=SUBTRACT),
Sample(SampleId=5, SampleTypeId=1, SampleQuantity=25, SampleType=SUBTRACT)
Sample(SampleId=6, SampleTypeId=2, SampleQuantity=10, SampleType=ADD),
Sample(SampleId=7, SampleTypeId=2, SampleQuantity=20, SampleType=ADD),
Sample(SampleId=8, SampleTypeId=2, SampleQuantity=30, SampleType=ADD),
Sample(SampleId=9, SampleTypeId=2, SampleQuantity=15, SampleType=SUBTRACT),
Sample(SampleId=10, SampleTypeId=2, SampleQuantity=35, SampleType=SUBTRACT)

I am currently using this:
sampleList.stream()
    .collect(Collectors.groupingBy(Sample::getTypeId,
        Collectors.summingInt(
            sample -> SampleType.ADD.equalsIgnoreCase(sample.getSampleType())
                ? sample.getSampleQuantity() :
                -sample.getSampleQuantity()
            )));

And also this
sampleList.stream()
        .collect(Collectors.groupingBy(Sample::getSampleTypeId,
                Collectors.collectingAndThen(
                    Collectors.groupingBy(Sample::getSampleType,
                        Collectors.summingInt(Sample::getSampleQuantity)),
                            map -> map.getOrDefault(SampleType.ADD, 0)
                                    - map.getOrDefault(SampleType.SUBTRACT, 0))));

as the accepted answer to get the desired output to group in a Map<Long, Integer>:
{1=15, 2=10}

With that, I was wondering, if this could be expanded into something more.
First, how could I have it return as a Map<String, Integer> instead of the original Map<Long, Integer>. Basically, for the SampleTypeId; 1 refers to HELLO, 2 refers to WORLD.
So I would need like a .map (or maybe other function) to transform the data from 1 to HELLO and 2 to WORLD by calling a function say convertType(sampleTypeId)?. So the expected output would then be {"HELLO"=15, "WORLD"=10}. Is that right? How should I edit the current suggested solution to this?
Lastly, I would like to know if it is also possible to return it to a Object instead of a Map. So let's say I have a Object; SummaryResult with (String) name and (int) result. So it returns a List<SummaryResult> instead of the original Map<Long, Integer>. How can I use the .map (or other) feature to do this? Or is there other way to doing so? The expected output would be something along this line.
SummaryResult(name="hello", result=15),
SummaryResult(name="world", result=10),

Would really appreciate it with the explanation in steps as given previously by @M. Prokhorov.
Update:
After updating to
sampleList.stream()
        .collect(Collectors.groupingBy(sample -> convertType(sample.getSampleTypeId()),
                Collectors.collectingAndThen(
                    Collectors.groupingBy(Sample::getSampleType,
                        Collectors.summingInt(Sample::getSampleQuantity)),
                            map -> map.getOrDefault(SampleType.ADD, 0)
                                    - map.getOrDefault(SampleType.SUBTRACT, 0))));

private String convertType(int id) {
    return (id == 1) ? "HELLO" : "WORLD";
}

A: For first part, considering you have somewhere the method
String convertType(int typeId)

You simply need to change first classifier from this
groupingBy(SampleType::getTypeId)

to this
groupingBy(sample -> convertType(sample.getTypeId()))

Everything else remains the same.
Latter type is a little trickier, and technically doesn't benefit from it being a stream-related solution at all.
What you need is this:
public List<SummaryResult> toSummaryResultList(Map<String, Integer> resultMap) {
  List<SummaryResult> list = new ArrayList<>(resultMap.size());
  for (Map.Entry<String, Integer> entry : resultMap.entrySet()) {
    String name = entry.getKey();
    Integer value = entry.getValue();

    // replace below with construction method you actually have
    list.add(SummaryResult.withName(name).andResult(value));
  }
  return list;
}

You can use this as part of collector composition, where your whole collector will get wrapped into a collectingAndThen call:
collectingAndThen(
  groupingBy(sample -> convertType(sample.getTypeId()),
     collectingAndThen(
       groupingBy(Sample::getSampleType,
         summingInt(Sample::getSampleQuantity)),
         map -> map.getOrDefault(SampleType.ADD, 0)
                - map.getOrDefault(SampleType.SUBTRACT, 0))),
  result -> toSummaryResultList(result))

However, as you can see, it is the whole collector that gets wrapped, so there is no real benefit in my eyes to the above version to a simpler and easier to follow (at least to me) version below that uses an intermediate variable, but isn't so much of a wall of code:
// do the whole collecting thing like before
Map<String, Integer> map = sampleList.stream()
    .collect(Collectors.groupingBy(sample -> convertType(sample.getTypeId()),
            Collectors.collectingAndThen(
                Collectors.groupingBy(Sample::getSampleType,
                    Collectors.summingInt(Sample::getSampleQuantity)),
                        map -> map.getOrDefault(SampleType.ADD, 0)
                                - map.getOrDefault(SampleType.SUBTRACT, 0))));

// return the "beautified" result
return toSummaryResultList(map);

Another point to consider in above is: convertType method will be called as many times as there are elements in sampleList, so if convertType call is "heavy" (for example, uses database or IO), then it's better to call it as part of toSummaryResultList conversion, not as stream element classifier. In which case you will be collecting from map of type Map<Integer, Integer> still, and using convertType inside the loop. I will not add any code with this in consideration, as I view this change as trivial.

A: You could indeed use a map() function
sampleList.stream()
        .collect(Collectors.groupingBy(Sample::getSampleTypeId,
                Collectors.collectingAndThen(
                        Collectors.groupingBy(Sample::getSampleType,
                                Collectors.summingInt(Sample::getSampleQuantity)),
                        map -> map.getOrDefault(SampleType.ADD, 0)
                                - map.getOrDefault(SampleType.SUBTRACT, 0))))
        .entrySet()
        .stream()
        .map(entry->new SummaryResult(entry.getKey()),entry.getValue())
        .collect(Collectors.toList());

A: ToIntFunction<Sample> signedQuantityMapper= sample -> sample.getQuantity()
    * (sample.getType() == Type.ADD ? 1 : -1);

Function<Sample, String> keyMapper = s -> Integer.toString(s.getTypeId());

Map<String, Integer> result = sampleList.stream().collect(
    Collectors.groupingBy(
        keyMapper,
        Collectors.summingInt(signedQuantityMapper)));


text:
Q: How to convert hour extracted from date to hour + (date in hours)?        0   1
0      6   7
1     11  13
2      7   8
3     16  17
4      5   6
5     18  20
6      8   9
7     13  13
8      3   4
9     13  14
10     5   6
11    17  17
12    11  12
13    21  22
14    19  20
15     6   7
16    13  14
17    12  13
18     3   4
19     3   4
20    11  13
21    12  13
22     4   5
23     5   6
24    13  14
25    13  14
26     1   3
27     6   6
28     4   5
29    12  14
  ..  ..
9689  10  11
9690  16  17
9691  13  13
9692   8   8
9693   8   9
9694  12  13
9695  13  13
9696  19  19
9697  14  14
9698  13  13
9699  14  14
9700  19  19
9701  13  13
9702  19  19
9703  14  14
9704  13  13
9705   8   9
9706   7   8
9707   7   8
9708  17  18
9709  22  22
9710  12  12
9711   7   8
9712  20  22
9713  11  12
9714  16  17
9715   7   7
9716  24   2
9717   8  10
9718   8  10

I have this dataframe where the columns correspond to an hour of the 24hour clock (1 to 24). These are currently extracted from the date using:
time = datetime.datetime.strptime(POXTime, '%d/%m/%Y %H:%M')
POXHour = time.hour

I am wondering if anyone can tell me a way I can add 24 to each entry that is a day subsequent (based on the first date that appears in the list being 1 to 24 hours). For example the first 1000 or so rows of this dataframe are from 01/05/2018, then it goes on to 02/05/2018 but still says "17" for the 17th hour where I want it to say "41" (17+24)... and so on for each subsequent day. Hope this makes sense! Can anyone help?
EDIT
Here is the first few rows of the data without the date/time being stripped for just the hour:
   POETime           POXTime
0     01/05/2018 05:33  01/05/2018 06:31
1     01/05/2018 10:56  01/05/2018 12:18
2     01/05/2018 06:22  01/05/2018 07:21
3     01/05/2018 15:17  01/05/2018 16:40
4     01/05/2018 04:19  01/05/2018 05:16
5     01/05/2018 17:41  01/05/2018 19:02
6     01/05/2018 07:56  01/05/2018 08:51

EDIT2
Here is an example of where the date changes...
1360    01/05/2018 02:18    01/05/2018 02:18
1361    01/05/2018 21:47    01/05/2018 21:47
1362    01/05/2018 11:50    01/05/2018 11:50
1363    01/05/2018 07:28    01/05/2018 07:52
1364    01/05/2018 00:09    01/05/2018 00:09
1365    01/05/2018 15:52    01/05/2018 17:36
1366    01/05/2018 08:27    01/05/2018 09:32
1367    01/05/2018 04:57    01/05/2018 06:06
1368    01/05/2018 09:58    01/05/2018 11:44
1369    01/05/2018 16:32    01/05/2018 17:22
0   02/05/2018 02:17    02/05/2018 03:24
1   02/05/2018 12:08    02/05/2018 13:28
2   02/05/2018 06:31    02/05/2018 07:39
3   02/05/2018 15:20    02/05/2018 16:57
4   02/05/2018 04:06    02/05/2018 05:13
5   02/05/2018 17:18    02/05/2018 18:53
6   02/05/2018 08:32    02/05/2018 09:24
7   02/05/2018 02:36    02/05/2018 03:30
8   02/05/2018 03:40    02/05/2018 04:30

which I want to output as...
1360    01/05/2018 02:18    01/05/2018 02:18        3   3
1361    01/05/2018 21:47    01/05/2018 21:47        10  10
1362    01/05/2018 11:50    01/05/2018 11:50        12  12
1363    01/05/2018 07:28    01/05/2018 07:52        8   8
1364    01/05/2018 00:09    01/05/2018 00:09        1   1
1365    01/05/2018 15:52    01/05/2018 17:36        16  18
1366    01/05/2018 08:27    01/05/2018 09:32        9   10
1367    01/05/2018 04:57    01/05/2018 06:06        5   7
1368    01/05/2018 09:58    01/05/2018 11:44        10  12
1369    01/05/2018 16:32    01/05/2018 17:22        17  18
1   02/05/2018 02:17    02/05/2018 03:24        27  28
2   02/05/2018 12:08    02/05/2018 13:28        37  38
3   02/05/2018 06:31    02/05/2018 07:39        31  32
4   02/05/2018 15:20    02/05/2018 16:57        40  41
5   02/05/2018 04:06    02/05/2018 05:13        29  30
6   02/05/2018 17:18    02/05/2018 18:53        42  43
6   02/05/2018 08:32    02/05/2018 09:24        33  34
7   02/05/2018 02:36    02/05/2018 03:30        27  28
8   02/05/2018 03:40    02/05/2018 04:30        28  29

A: There is different option, one way is:
ref_date_POE = min(df['POETime']) # or any date you want
df['POEHours'] = (df['POETime'] - ref_date_POE).dt.days*24 + df['POETime'].dt.hour +1

Here (df['POETime'] - ref_date_POE).dt.days give you the number of days between the date in df['POETime'] and ref_date_POE, so *24 give you what you want. For the +1, it seems that you have 3 when it's 2:18 and df['POETime'].dt.hour would give you 2, so just add 1.


text:
Q: Casting & Inheritance in Java I encountered a piece of code similar to the one below and was sure that its output would be B, since the variable y is cast to class B before calling x(), but instead, the program prints C. So I have two questions:

*

*Why is C.x() called instead of B.x()? Why does Java remember a variable's original type after it's been cast to a new type?

*How would I call B.x()?

class A {
    public void x() {
        System.out.println("A");
    }
}

class B extends A {
    @Override
    public void x() {
        System.out.println("B");
    }
}

class C extends B {
    @Override
    public void x() {
        System.out.println("C");
    }
}

public class Main {
    public static void main(String args[]) {
        A y = new C();
        ((B)y).x();
    }
}


text:
Q: Start Activity only if e-mail was sent I'm having a little bug in my code, but the app goes like this:
User clicks on a button and that button launches an Intent for sending an e-mail. Now, if user sucessfully sends that e-mail, he should be taken to PaymentCompleteActivity and if not, MainActivity should be launched.
My idea was to check if the email was sent in onActivityResult() but it's not working, even on successfull email sent, it redirects to MainActivity
Here's my code:
 Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", "xxxxxxxx@gmail.com", null));
emailIntent.putExtra(Intent.EXTRA_TEXT, myTextFiles);
startActivityForResult(Intent.createChooser(emailIntent, "Send email..."), 1);

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1) {
            if (resultCode == Activity.RESULT_OK) {
                startActivity(new Intent(ProceedActivity.this, PaymentCompleteActivity.class));
            finish();
            }
            if (resultCode == Activity.RESULT_CANCELED) {
                startActivity(new Intent(ProceedActivity.this, MainActivity.class));
                finish();
            }

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

A: Email is not part of the API. startActivityForResult will return the  once you pressed the send button even if it is not sent. SO it will always call resultCode == Activity.RESULT_CANCELED


text:
Q: Race condition allowing multiple transactions; will locking on objects in a dictionary cause issues? We have a MVC Web API that is called to write transactions for a specific amount, where the amount is debited or credited to a user's balance. This records the balance pre-transaction (PreAmount), the amount, and the balance post-transaction (PostAmount). We noticed from a simple query using SQL Server's LAG and LEAD functions that there were instances of transactions being added from the API were being 'entered too fast' (partially due to the lack of resources put towards buying good hardware for the server, and IIS and SQL running on the same box). We have a mechanism to prevent the transaction from being entered if it exists, but it seems that the method call is being called really quickly, which results in the record being added multiple times due to a race condition.
The way I am going to try to fix this is by using a Dictionary<long, object>. The assumption here is that, we want transactions for a customer to be entered sequentially at all times, but I don't want to lock concurrent requests for multiple customers. The dictionary would contain a customer ID # and the value would be an object I can lock on. When a transaction is about to be entered, I will check to see if there is a customer ID # entry, and if not, enter it in there):
private static Dictionary<long, object> customerLocker = new Dictionary<long, object>();
private static object dictLocker = new object();

Then, when a request to check a balance, or to enter a transaction is requested, I would then lock on that object, and perform the work needed:
lock (dictLocker)
{
    if (!customerLocker.ContainsKey(customerID))
        customerLocker.Add(customerID, new object());
}
lock (customerLocker[customerID])
{
    // ... do the work needed for this customer
}

Is this a good solution to the issue I am having? Will locking on elements inside of a dictionary cause issues? I'm going to try it, but while I'm putting this together, I'd like to see input from others on this scenario.

A: It's not safe for you to be searching through the dictionary outside of a lock, because by doing so another dictionary could be writing to it at the same time, so your read could end up being corrupted.  You need to fetch the value for the key inside of the lock.
Alternatively, you could just use a ConcurrentDictionary to store the objects for each customer instead of locking around access to a Dictionary.  This would let you write:
private static ConcurrentDictionary<long, object> customerLocker =
    new ConcurrentDictionary<long, object>();

lock (customerLocker.GetOrAdd(customerID, () => new object()))
{
    // ... do the work needed for this customer
}


text:
Q: web app make db on first run of python code I have an aiohttp app where when ran the first time it will attempt to create an sqlite db if it doesnt exist on a try_make_db() function. I also don't think an exception error is a good way to do this either...
Could someone give me a tip on how to make this better?
When run the file I get a traceback:
Traceback (most recent call last):
  File "app.py", line 280, in <module>
    try_make_db()
  File "app.py", line 250, in try_make_db
    with sqlite3.connect(my_path) as conn:
sqlite3.OperationalError: unable to open database file

I dont think this has anything to do with aiohttp or sqlite but more of a PATH question.
This isn't the entire code but only near the bottom, here's a gist of the entire script:
def try_make_db() -> None:
    my_path = './form_data.db'
    with sqlite3.connect(my_path) as conn:
        cur = conn.cursor()
        print("Trying to connect to the db!")
        try:
            cur.execute("SELECT 1 FROM posts LIMIT 1;")
            cur.close()
            print("Good enough DB should be Ok")
        except Exception as e:
            print("Table 'posts' does not exist")
            cur.execute(
                """CREATE TABLE posts (
                Date TEXT PRIMARY KEY,
                starttime TEXT,
                endtime TEXT,
                Weekends NUMBER,
                Weekdays NUMBER,
                setpoint NUMBER)
            """
            )
            print("DB TABLE CREATED")
            conn.commit()

async def init_db(app: web.Application) -> AsyncIterator[None]:
    sqlite_db = 'form_data.db'
    db = await aiosqlite.connect(sqlite_db)
    db.row_factory = aiosqlite.Row
    app["DB"] = db
    yield
    await db.close()

try_make_db()

web.run_app(init_app()  , host='0.0.0.0', port=8080)

Any tips greatly appreciated not a lot of wisdom here. Would anyone have a tip on how I could modify the try_to_make_db function maybe something like this:
import os.path
if os.path.exists(PATH_TO_DB): # replace the path here
  print("Path exists")

A: check write permissions on form_data.db also you don't need to use ./ to explicitly state your current working directory, just using the name form_data.db will create the file in same dir as your main program.


text:
Q: A Good Solution for Drag n Drop I am looking into solutions for Drag N Drop of items(images, textareas, etc). I need something that will also give the coordinates of the location the item was dropped on screen, saved, and later can be placed in that exact location.
I am looking for an end result of something similar to this: https://gomockingbird.com/mockingbird/#
So far I have come up two possible solutions:
Cappuccino - http://cappuccino.org/
HTML5
What are other thoughts on either of these solutions and if they know any others that are worth taking a look at?

A: Take a look at jQuery --> http://jqueryui.com/demos/draggable/#handle

A: For HTML5's canvas element you can use the fantastic kinetic for all your drag and drop needs. Here's a tutorial to get you started.