text:
Q: How to paginate search results? I want to paginate search results using Zend_Paginator. So I pass my data to a paginator instance:
$paginator = new Zend_Paginator (
           new Zend_Paginator_Adapter_DbSelect ( $data )
);

Data is returned this way
public function getData($idArray){
        $db = Zend_Db_Table::getDefaultAdapter();
        $selectProgramme = new Zend_Db_Select($db);

        $selectProgramme->from('programme')
                            ->order('id DESC')
                            ->where('id IN(?)', $idArray);

        return $selectProgramme;
}

$idArray is provided by my search implementations. This all works great and I get the correct data and pagination links displayed.
However I can't paginate the result because the pagination links are not valid. So normal pagination would have following link:
mysite.de/home/index/page/1

in search I now have
mysite.de/home/search/page/1

This does not work. Any suggestions how to implement search pagination?
EDIT: I have a HomeController with two actions, index and search action. IndexAction displays all data and I can paginate it.
public function indexAction(){
    //...
    $paginator = new Zend_Paginator(
                 new Zend_Paginator_Adapter_DbSelect($data)
    );
    $paginator->setItemCountPerPage(16)
              ->setPageRange(20)
              ->setCurrentPageNumber($this->_getParam('page', 1));

    $this->view->data = $paginator;
}

The searchActions handles the search process:
public function searchAction(){
    $response = $solr->search($this->getRequest()->getParam('search', null));
    //...if items found get the data exactly the same way as in the
    // index action, using Zend_Paginator_Adapter_DbSelect
    $paginator = new Zend_Paginator(
                 new Zend_Paginator_Adapter_DbSelect($data)
    );
    $paginator->setItemCountPerPage(16)
              ->setPageRange(20)
              ->setCurrentPageNumber($this->_getParam('page', 1));

    $this->view->data = $paginator;
}

So like you see in the search action there is a problem with the search process when I paginate. I need to decide somehow if to search or to paginate. Any suggestions on that?

A: Since search required the search parameter pagination will fail because when paginating the the search parameter is null.
$sreq = $this->getRequest()->getParam('search', null);

So we need to pass this parameter whenever we paginate our search. I solve this using Zend_Session:
//get search param
$sreq = $this->getRequest()->getParam('search', null);
//store search param in session for pagination
$search = new Zend_Session_Namespace('PSearch');

if($sreq != null){
    $search->psearch = $sreq;
}else{
   $sreq = $search->psearch;
}

I have this at the top of my searchAction and everything works.

A: Not sure I understand, but is your problem that the page parameter from the url is not making it's way to the Paginator - e.g. regardless of what page you are on, it is always showing the first 20 results?
If so, have you tried manually setting the page on the paginator:
$page = $this->_getParam('page', 1);
$paginator->setCurrentPageNumber($page);

A: public function search()

Are you sure that you didn't mistyped here? Should be
public function searchAction()

A: You put your search data into $response but create paginator instance using $data (which is null)


text:
Q: Get sum of values in database Hi I have searched and tried some right answers in Stackoverflow, but none works.
I tried
$query = "SELECT * FROM Temp";
$query_run = mysql_query($query);
$qty= 0;
While ($num = mysql_fetch_assoc ($query_run)) {
$qty += $num['Price'];
}
echo $qty;

or
$result = mysql_query('SELECT SUM(Price) AS value_sum FROM Temp');
$row = mysql_fetch_assoc($result);
$sum = $row['value_sum'];

Both saying

Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL
  result resource

Could someone help me? Thanks

redpajama_set_name: RedPajamaStackExchange


text:
Q: writing Excel file while using for loop I am trying to write data to an Excel file, during a for loop.
But what I am getting is a single line containing the last data received by the loop.
I have tried a couple of different methods but came short..
2 tries are list below
Any Ideas ?
def write_excel(x):
    workbook = xlsxwriter.Workbook('ID_Num.xlsx')
    worksheet = workbook.add_worksheet()

    df = pd.DataFrame(
        {'ID':[x],
         'mail_one':[Email],
         'second_mail':[second_mail],
         'Num':[Num],
         'date':[Date]})

    row_num = 0
    for key, value in df.items():
        worksheet.write(0, row_num, key)
        worksheet.write_row(1, row_num, value)
        row_num += 1

    workbook.close()

    #df = pd.DataFrame(
    #    {'ID':[x],
    #     'mail_one':[Email],
    #     'second_mail':[second_mail],
    #     'Num':[Num],
    #     'date':[Date]})

    # writer = ExcelWriter('ID_Num.xlsx')
    # df.to_excel(writer,'ID_Num',index=False)

    # writer.save()

if __name__ == "__main__":
    for x in List:
        my_dic = {}
        my_dict["ID"] = x
        my_dict["mail_one"] = Email
        my_dict["second_mail"] = second_mail
        my_dict["Num"] = str(Num)
        my_dict["date"] = Date
        print(my_dict)
        write_excel(x)

A: I don't have xlsxwriter so I cannot test. The documentation says that it cannot modify an existing file so I suspect that every iteration of for x in List: you are over-writing your file (workbook = xlsxwriter.Workbook('ID_Num.xlsx')).
You can make multiple files with these changes:
def write_excel(x,i):
    workbook = xlsxwriter.Workbook(f'ID_Num{i}.xlsx')
    ...
# and
for i,x in enumerate(List):
    ...
    write_excel(x,i)

Or you could accumulate multiple dictionaries and pass all of them to your function
data = []
for x in List:
    my_dic = {}
    ...
    data.append(my_dic)
write_excel(data)

Changing the function to iterate over those dicts; making a new sheet for each one
def write_excel(data):
    workbook = xlsxwriter.Workbook('ID_Num.xlsx')
    for sht in data:
        worksheet = workbook.add_worksheet()
        df = pd.DataFrame(...

        row_num = 0
        for key, value in df.items():
            worksheet.write(...
            worksheet.write_row(...
            row_num += 1

    workbook.close()


text:
Q: How to correctly implement Amplify to Flutter for the last few days, I was trying to figure out how to fix the issues I was having with Amplify for Flutter: error: compiling for iOS 9.0, but module 'Starscream' has a minimum deployment target of iOS 11.0 and Target of URI doesn't exist: 'package:amplify_core/amplify_core.dart'
Things I tried:

*

*Following the tutorial of the doc https://docs.amplify.aws/start/getting-started/setup/q/integration/flutter. That resulted in: project directory/ios/Pods/AppSyncRealTimeClient/AppSyncRealTimeClient/Connection/AppSyncConnection/AppSyncSubscriptionConnection+ErrorHandler.swift:9:8: error: compiling for iOS 9.0, but module 'Starscream' has a minimum deployment target of iOS 11.0: project directory/build/ios/Debug-iphonesimulator/Starscream/Starscream.framework/Modules/Starscream.swiftmodule/x86_64-apple-ios-simulator.swiftmodule and Command CompileSwift failed with a nonzero exit code note: Using new build system note: Building targets in parallel note: Planning build note: Contructing build description.
I uncommented the line platform :ios, '9.0' on Podfile and changed it to platform :ios, '11.0', while also changing the development target to 11 on the projects xcworkspace. The same error happened.

*Following the tutorial of the doc https://aws.amazon.com/getting-started/hands-on/build-flutter-app-amplify/. That resulted in:Target of URI doesn't exist: 'package:amplify_core/amplify_core.dart' when I tried to import the core. Like that, I couldn't use the Amplify() class.

*Restarting the computer.

*Deleting the Amplify folder.

*Running amplify uninstall, and trying from the start again.

*Searching other posts on this and other websites.

*Running amplify clean.
Things to note:

*

*The Amplify installation, init, and configure steps returned no errors.

*If I delete the Amplify dependencies amplify_flutter: '<1.0.0' amplify_auth_cognito: '<1.0.0' amplify_analytics_pinpoint: '<1.0.0' the app runs on the simulator just fine. As soon as I put them back the errors return.

A: You want to change import 'package:amplify_core/amplify_core.dart' to import 'package:amplify_flutter/amplify.dart'; then when you add your plugins you'll wanna do it like this Amplify.addPlugins([authPlugin, storage]);
I also ran flutter upgrade before I did this as well just make sure you save all your changes. You can find more information in there example flutter app
https://github.com/aws-amplify/amplify-flutter/blob/master/example/lib/main.dart

A: If you are following this tutorial https://docs.amplify.aws/start/getting-started/setup/q/integration/flutter
then in the step of dependencies there is a correction:
https://docs.amplify.aws/start/getting-started/setup/q/integration/flutter#add-amplify-to-your-application
it should be like this :
dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2

dev_dependencies:

  amplify_flutter: <1.0.0
  amplify_datastore: <1.0.0
  amplify_api: <1.0.0
  amplify_auth_cognito: <1.0.0
  flutter_test:
    sdk: flutter

Then just run:
flutter clean
flutter pub get


text:
Q: Excel Data Validation not giving error message I am trying to get a simple data validation in a cell with VBA. For some reason, when I type something that is not in the selected list (Y or N), I dont receive the error message and Excel allows me to put whatever I want in the cell.
Any help appreciated!
Sub Data_Validation_Critical()

    'Critical:
    Range("B4").Select
        With Selection.Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
        xlBetween, Formula1:="=DVEmergentCritical"
        .IgnoreBlank = True
        .InCellDropdown = True
        .InputTitle = ""
        .ErrorTitle = "ERROR: Invalid Selection"
        .InputMessage = "Y or N"
        .ErrorMessage = _
        "You have entered and invalid seleciton. Please select Y or N."
        .ShowInput = True
        .ShowError = True
    End With

End Sub

A: Another way to validate data could be:
If Range("B4").Value = "Y" Then
   DoSomeStuff
ElseIf Range("B4").Value = "N" Then
   DoSomeStuff
Else
   DoNothing or Msgbox Error.
End If


text:
Q: SQLite Function that performs additional queries I have written a custom SQLite function that transforms a string as it is copied from one table to another. It's very basic and has does its job well for quite a while. The query looks like this:
INSERT INTO Table2 (field1) SELECT MYTRANSFORM(field2) FROM Table2;

Now I need to modify the behavior of that function so that it does a lookup on another table and factors the result into how it transforms the value. Is that possible? Has anyone done it successfully?

A: This is possible; you can execute other SQL queries from within your function, as long as you do not call your function recursively.


text:
Q: Linear Transformations in Linear Algebra We are given:
Show how to evaluate a linear transformation for a specific vector $x$ , when the transformation is defined in the form $$T(x) = y$$
We know that a linear transformation is defined as
$$T:\mathbb{R^n} \rightarrow \mathbb{R^m}$$
if there exists a real matrix $$ A = \left[\begin{array}{rrr}
    a_{11} & ... & a_{1n}\\
    ... & ... & ...\\
    a_{m1} & ... & a_{mn}
    \end{array}\right]
$$
Such that for every $x = (x_1, ..., x_n) \in \mathbb{R^n}$ we have $T(x_1, ..., x_n) = (y_1, ..., y_m)$ where
$$ y_1 = a_{11}x_1 + ... + a_{1n}x_n, $$
$$ ... $$
$$ y_m = a_{m1}x_1 + ... + a_{mn}x_n$$
But im confused and I don't know if this will fully answer the question.

A: Multiply the x column vector with the given matrix.


text:
Q: Store vars on first run / request I have a CRM application where I need to reference some lookups constantly in the code.  Eg: a certain team in CRM.
The issue is that the Guid's will be different in each environment.
So I am thinking about the first time a call is made to get a certain Guid it will check if the value is Guid.Empty.  If so, then go get the Guid.
There is like 20 Guids I need to do this with.
The way I am doing it at the minute is I have a single class file with all the Guids as Guid.Empty.
The first time the system goes to get the Guid it will see that it is Guid.Empty and so it gets the correct Guid from the database and assigns it.  All subsequent calls to get the same Guid will mean they can get it without calling the database.
But is that the correct / best way?


text:
Q: IS there a way to open a power bi file from Excel So here is the problem, I want to create a buttun onExcel that leads to a Power BI file and I have no clue of how to do it, i also looked for this on Youtube but nothing is close or related to my question.
Please help.

A: Please test this code, adapting the paths and file name:
Private Sub cmdOpen_Click()

    VBA.Shell "C:\Program Files\Microsoft Power BI Desktop\bin\PBiDesktop.exe c:\pathToYourFile.pbix"

End Sub

You can improve this code passing the pbix filename as a variable.

A: Problem solved,
Thanks to @AleXcel,
Here's the command
Sub cmdOpen_Click()
VBA.Shell "C:\Program Files\Microsoft Power BI
Desktop\bin\PBiDesktop.exe [C:\Users\nizar\Downloads\power
bi\HelloWorld.pbix]"
End Sub

The only difference between @AleXcel 's code is that the [ ] are necessary to open it.


text:
Q: Creating a 'git publish' alias, but need to store temporary variable Based on this article I wanted to create a similar alias (flow described below).  With the author/article's comments disabled, I thought I'd ask it here.  Assuming you are on a 'topic' branch, I'd like to modify the flow to do the following:

*

*Detect and store the current branch name in $branch (using alias from here)

*Switch back to master branch

*Pull from remote

*Switch back to $branch

*Rebase $branch against master

*Switch back to master

*Merge changes from $branch

*Run wtf

A psuedo alias might be something like (knowing that the references to $branch are most likely wrong):
branch-name = !git for-each-ref --format='%(refname:short)' git symbolic-ref HEAD
publish = !git branch-name > $branch && git checkout master && git pull && git checkout $branch && git rebase master && git checkout master && git merge $branch
Is there anyway to pull this off?  I've no idea how to store/use the $branch variable (note, coming from a windows/c#/VSS background so pretty green in git still).
Final note, I am using git from within a Windows Powershell console window.
Thanks in advance.

A: Git checkout -

will checkout the previous branch, so you don't need to store it.
When you do need it, you can get it from .git/HEAD
Hope this helps


text:
Q: How to send form data in POST request in Swift 3 I am trying to post form-data using webservice, userName & password, but in response it's showing an error stating "Could not connect to the server.".
Please help me to send form data in the POST request.
        let dict:[String:String] = ["userName": userName as! String, "password": password as! String]

        do {

            let jsonData = try JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)

            let url = URL(string: "(some url)")!

            var request  = URLRequest(url: url)

            request.httpMethod = "POST"

            request.setValue("application/x-www-form-urlencoded charset=utf-8", forHTTPHeaderField: "Content-Type")

            request.httpBody = jsonData

            let task = URLSession.shared.dataTask(with: request) { data, response, error in

                if error != nil {

                    print(error!.localizedDescription)

                    return

                }

                do {

                    let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

                    if let parseJSON = json {

                        let resultValue:String = parseJSON["success"] as! String;

                        print("result: \(resultValue)")

                        print(parseJSON)

                    }

                } catch let error as NSError {

                    print(error)

                }
            }

            task.resume()

        } catch {

            print(error.localizedDescription)

        }

I've tried adding values in the request, may be some values are missing in the request formed. Please help!
Thats the POSTMAN response

A: my calling api class
class ApiService
{
    static func getPostString(params:[String:Any]) -> String
    {
        var data = [String]()
        for(key, value) in params
        {
            data.append(key + "=\(value)")
        }
        return data.map { String($0) }.joined(separator: "&")
    }

    static func callPost(url:URL, params:[String:Any], finish: @escaping ((message:String, data:Data?)) -> Void)
    {
        var request = URLRequest(url: url)
        request.httpMethod = "POST"

        let postString = self.getPostString(params: params)
        request.httpBody = postString.data(using: .utf8)

        var result:(message:String, data:Data?) = (message: "Fail", data: nil)
        let task = URLSession.shared.dataTask(with: request) { data, response, error in

            if(error != nil)
            {
                result.message = "Fail Error not null : \(error.debugDescription)"
            }
            else
            {
                result.message = "Success"
                result.data = data
            }

            finish(result)
        }
        task.resume()
    }
}

and when use it
ApiService.callPost(url: url, params: params, finish: finishPost)

and the finish function
func finishPost (message:String, data:Data?) -> Void
{
    do
    {
        if let jsonData = data
        {
            let parsedData = try JSONDecoder().decode(Response.self, from: jsonData)
            print(parsedData)
        }
    }
    catch
    {
        print("Parse Error: \(error)")
    }
}


text:
Q: Why does time stop in black holes? Everyone says that time stops in the black hole. It's a "fact". However, I have never heard everyone explaining that.
Of course, I know that observer in weaker gravitational field sees that something in stronger gravitational field is experiencing slower time. However, slower and no at all is quite different.
I have no idea what equation is used to calculate dime dilatation, but it will use gamma and therefore division. And the only time division of non-zero constant yields zero is when you divide by infinity.
And although black holes are super heavy, super badass and super black, they posses finite energy and therefore finite gravitational acceleration (even at event horizon).
So shouldn't just the time be very slow, rather than just stop from our point of view?

A: Short answer: It doesn't stop.
Slightly longer answer: The case of a non-rotating, non-charged black hole is described by the Schwarzschild solution. It is now the case that, if you draw the worldline of a particle falling into a black hole, you will find that the coordinate time in the Schwarzschild metric grows infinite as the particle approaches the event horizon. Naively, this would seem to imply that a particle takes forever to fall into a black hole, which would mean that it becomes slower and slower as it approaches the event horizon. And as it would seem to imply that the particle comes to stop, some people say that "time stops at the event horizon". But this is just an artifact of the coordinates. The Schwarzschild coordinates are simply chosen badly.  The proper time, i.e. the time the falling particle/observer would perceive, is finite, and there are other coordinates in which there is also no singularity at the event horizon, so that all coordinates stay finite. Nothing particulary terrible happens at the event horizon from the view of the falling particle, it is just that no light-like paths connect the interior of the horizon the the exterior, so that nothing can cross the horizon from the inside.
Inside the horizon, some weird stuff happens when looked at from the Schwarzschild coordinates, like the former time-coordinate becoming space-like, but this is again rather an artifact of the coordinate system than a property of the true black hole. The are coordinates which cover the whole of the spacetime except for the center of the hole, where the is a true singularity. All bets are off as to what happens there.

A:
Why does time stop in black holes?

Time according to whom?
The fact is that, in special and general relativity, there is no universal time.  Indeed, time is a coordinate in relativity so one must be careful to specify the coordinate system when asking questions like this.
Now, every entity also has an associated proper time which is not a coordinate which means that it is coordinate independent (invariant).  Think of your proper time as the time according to your 'wrist watch'.
In the context of the static black hole (Schwarzschild black hole) solution, there is a coordinate system (Schwarzschild coordinates) that we can associate with the observer at infinity.  That is to say, the coordinate time corresponds to the proper time of a hypothetical entity arbitrarily far from the black hole.
In this coordinate system, we can roughly say that the coordinate time 'stops' at the event horizon (in fact, there is no finite value of this coordinate time to assign to events on the horizon).
However, there are coordinate systems with finite coordinate time at the horizon, e.g., Kruskal-Szekeres coordinates.
Moreover, for any entity falling freely towards the horizon, the proper time does not 'stop'.  Indeed, the entity simply continues through the horizon towards the 'center' of the black hole and then ceases to exist at the singularity.
We interpret the fact that the Schwarzschild coordinate time does not extend to the horizon as follows:  no observer outside the horizon can see an entity reach (or fall through) the horizon in finite time.  This is simply understood as the fact that light emitted from (or inside) the horizon cannot propagate to any event outside the horizon.
Why?  Because the spacetime curvature at the horizon is so great that there is no light-like world line the extends beyond the horizon.  Indeed, the horizon is light-like.  A photon emitted 'outward' at the horizon simply remains on the horizon.
Within the horizon, the spacetime curvature is such that there are no world lines that do not terminate on the singularity - the curvature is so great within the horizon that the future is in the direction of the singularity.

A: If someone is falling in a black hole, the nearer he/she gets to black hole the slower time will pass and when he/she reaches the edge of event horison, time it would take for an observer to see him/her to cross event horison will be infinite (in other words if their friend was watching him/her he would never see him/her crossing the event horison). Gravitational time dilation can be derived from Einstein field equations:
$$
G_{\mu\nu}+\Lambda g_{\mu\nu}=\frac{8\pi G}{c^4}T_{\mu\nu}
$$
Where $G_{\mu\nu}$ is Einstein Tensor, $\Lambda$ is cosmological constant, $g_{\mu\nu}$ is metric tensor and $T_{\mu\nu}$ is Stress energy momentum tensor, (for more info visit: Einstein Field Equations).
or you can use most famous solution of Einstein field equations called Schwarzschild solution:
$$
c^2d\tau^2=\left(1-\frac{r_s}{r}\right)c^2dt^2-\left(1-\frac{r_s}{r}\right)^{-1}dr^2-r^2(d\theta^2+\sin^2\theta\text{ }d\phi^2)
$$
and difference in proper time and time will be:
$$
\frac{\tau}{t} = \sqrt{\left(1-\frac{r_s}{r}\right)} \Rightarrow \tau = t\sqrt{1-\frac{2GM}{rc^2}}
$$
where $r_s$ is Schwarzschild radius and $r$ is distance of observer from a (in this case) black hole:
$$
r_s = \frac{2GM}{c^2}
$$
For more info see: This page.
Conclusion:
So as observer gets closer and closer to a black hole time passes more slowly relative to other observer and that other observer will never see him to cross event horison because it would take infinite amount of time and gravitational time dilation is calculated using this equation: $\tau = t\sqrt{1-\frac{2GM}{rc^2}}$ where $\tau$ is proper time

So shouldn't just the time be very slow, rather than just stop from our point of view?

If you will use time dilation equation for a black hole you will see that as you go to black hole ($r\to r_s$) time for an observer that is watching someone falling in black hole would be infinite (in other words observer will never see that someone crossing event horison) $t = \frac{\tau}{\sqrt{1-1}}=\frac{\tau}{0} = \infty$


text:
Q: display data on click of a button I have 2 buttons Start And Walk Away. I want that initially the walk away button should not appear but on the click of start button the walk away button should appear ( I do not want to use toggle).
I have 2 issues:
1) On the click of start button i am able to hide and display the second button but i am not able to hide the button initially.
2) after the Walk Away button appears on the click of Start button i wish that the walk away button should hide automatically after 2 minutes. i am not able to do so
At present the code that is running properly is . Code at fiddle

$("#start").click(function () {
    $("#walkaway").show();
});
<button type="submit" name="submit" id="start" value="Submit">Start</button>
<button type="submit" name="submit" id="walkaway" value="Submit">Walk Away</button>

A: To hide the button initially use CSS:
#walkaway {
    display: none;
}

To hide button after 2 seconds use delay:
$(document).ready(function () {
    $("#start").click(function () {
        $("#walkaway").fadeIn().delay(2000).fadeOut();
    });
});

Demo: http://jsfiddle.net/tusharj/saytq920/2/
Docs: http://api.jquery.com/delay/

Set a timer to delay execution of subsequent items in the queue.

A: Try this way:
<button type="submit" name="submit" id="walkaway" value="Submit" style="display:none">Walk Away</button>

A: use this using pure jquery
$(document).ready(function () {
    $("#walkaway").hide();

    $("#start").click(function () {
        $("#walkaway").show();
        setTimeout(function () {
            $("#walkaway").hide();
        }, 120000);
    });

});

A: To initially hide the start button you could use css and set it to:
#walkaway {
    display: none;
}

or
#walkaway {
    visibility: hidden;
}

depending on your layout and what you want to achieve.
To hide the button after 2 minutes you need to use delay
$(document).ready(function () {
    $("#start").click(function () {
       $("#walkaway").fadeIn().delay(120000).fadeOut();
    });
});

delay takes milliseconds as an argument, so 120 seconds = 2 minutes = 120.000 milliseconds.

A: Or you can use set timeOut function as following code :

$(document).ready(function () {
    $("#walkaway").hide();

    $("#start").click(function () {
        $("#walkaway").show();
        setTimeout(function () {
            $("#walkaway").hide();
        }, 2000); // <-- change to 120000 for 2 minutes
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="submit" name="submit" id="start" value="Submit">Start</button>
<button type="submit" name="submit" id="walkaway" value="Submit">Walk Away</button>

A: you can try this
$(document).ready(function () {
    test = function () {
        $("#walkaway").show();
    };

    test1 = function () {
        $("#walkaway").hide();
    };

    test1();

    $("#start").click(function () {
        test();
        setTimeout(test1, 120000);
    });

});


text:
Q: package and distribute exe for Java application with DB and third party lib using netbeans I have create an application (in java swing ) using netbeans, There are a database connectivity using derby and more external jar file included in project.
I want to create setup of java app
I followed these steps:

*

*Create jar for project (Clean and build project from tools)

*Goto project and open dist folder, here is no DB folder so I copied DB folder (APPDATA) and paste it to dist folder.

*Now I create .exe from third party tools

*When my Database folder places in same directory then exe run perfectly.
But my question is how I can package .jar with APPDATA(Database folder) which can run reliably and independently in other systems as exe.
So I can able to make installer in future for same product.
Only window exe creation and packaging solution is enough.

A: You can use tools like Install Shield or NSIS for installation to build your exe which can open a zip file , extract and execute batch \ shell scripts in which you can do whatever you want like installing your third party database & running your application jar.
I personally like NSIS
as it is completely script based and open source .


text:
Q: How to forward request from servlet to action of struts1.x I have a Servlet in web.xml, as below with URL pattern.
<servlet-name>ApplicationLoader</servlet-name>
<servlet-class>com.test.ApplicationLoaderServlet</servlet-class>

<servlet-mapping>
    <servlet-name>ApplicationLoader</servlet-name>
    <url-pattern>*.loader</url-pattern>
</servlet-mapping>

I have an Action in struts-config.xml as below
<action  path="/settings"   type="com.test.SettingsAction"
 scope="request"
>
<forward name="successful" path="/SuccessSettings.jsp" />
<forward name="failure" path="/Fail.jsp" />
</action>

Tried below approach for forward, but did not work. got 404 Page
request.getRequestDispatcher("/settings").forward(request, response);

or
    getServletContext().getRequestDispatcher("/settings").forward(request, response);
How do i forward request from Servlet to Struts action. old version of struts framework is used.
I got a solution below for struts 2 but not for 1.1.
How to forward request from servlet to action of struts2?
Any help on this please???

A: Does it change anything if you add ".do" at the end of the path? I vaguely remember that request paths had to end in ".do" in Struts 1.x, e.g.:
request.getRequestDispatcher("/settings.do").forward(request, response);


text:
Q: how to find client system mac address in web application I need to find client MAC address who is accessing my website. I have tried with java code.
try {

    Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
    while(networkInterfaces.hasMoreElements())
    {
        NetworkInterface network = networkInterfaces.nextElement();
        System.out.println("network : " + network);
        byte[] mac = network.getHardwareAddress();
        if(mac == null)
        {
            System.out.println("null mac");
        }
        else
        {
            System.out.print("MAC address : ");

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < mac.length; i++)
            {
                sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
            }
             val = sb.toString();
            System.out.println(sb.toString());
            break;
        }
    }
} catch (SocketException e){

    e.printStackTrace();

}

But it display as "network : name:eth0 (eth0)
MAC address : EC-A8-6B-77-A9-AD" for all client system.
how can i do this?

A: Server side Java code will never return the client's MAC address.
For that you would need a code running at the client. For example in IE you could get that with Javascript+ActiveX. In other browsers (including IE) you could do that with a Java Applet, but security restraints might prevent the applet to access system information including the MAC address.


text:
Q: Ctrl-Backspace not working in ReSharper's "Navigate to Everything/Type" I'm not sure if I'm doing something wrong, or if this is a known bug, but when I open "Navigate to Everything/Type" via CtrlT in Visual Studio 2013 Ultimate, type something and then try to delete it via CtrlBackspace, it will just insert a box character.

A: As of JetBrains' guy's comment in here

Guys, fix will be available in the upcoming R# 9.1 EAP4 build

It's really already fixed! Tried Resharper 9.2 and... Hallelujah!

A: Looks to already be a known bug.  Seems to have been introduced around version 6 according to a commenter there, and still exists to the latest version, 8.2.1. has been fixed in 9.1.


text:
Q: radio group not listening inside of a dialog in android I can't listen to the RadioGroup from my DialogFragment class. I don't get eny errors, but
the Log doesn't show me anything. Please help me...
public class SimpleDialog extends DialogFragment{

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    LayoutInflater inflater = getActivity().getLayoutInflater();
    View view = inflater.inflate(R.layout.radio, null);

    builder.setTitle(R.string.dialog_name)
            .setView(inflater.inflate(R.layout.radio, null))
            .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
               }
           });

    RadioGroup radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup);
    radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener()
    {
        public void onCheckedChanged(RadioGroup group, int checkedId) {

            Log.v("Dialog", "checked");
        }
    });

    return builder.create();
}

}

A: I just figured it out, I have to pass to builder.setView(view)


text:
Q: Converting media content into string in Java I'm using Oracle-MAF for mobile app development (Android and IOS). Having a requirement to capture media (image, audio and video) in the application and want to store into Oracle DB usually CLOB column.
So for I converted the captured media into base64 string (using commons-codec-1.10.jar) and passing through Rest webservice (Accept JSON/XML) to store into DB.
For image and audio length of the base64 string is fine, but for video it is consuming around 6.4 million of characters even for 2 sec video (2MB Rear camera) and this cause slow down the application and resulting Java heap space error.
Is there any other way to convert the media content into String using Java which gives feasible solution?

A: If it's really necessary to save the videos in CLOB/BLOB column of a table in DB then first save the content in a file and then have an asynchronous scheduler to save it in the DB. The best would be to have this scheduler running in another Java VM not to interfere with the app server running your server side.
If you can save all binary content as binary in a file and a path in the DB. File systems are the best solution for serving binary data anyway.


text:
Q: When can one find holomorphic sections vanishing at a point to a certain order? Let $X$ be a compact complex manifold (say of dimension $2$) and $L \rightarrow X $ a holomorphic line bundle. Consider the following statements:
Statement $A_0$: Given any point $p\in X$, there exists a homolorphic section $f_{00} \in H^0(X,L)$, such that $f_{00}(p) \neq 0$.
Statement $A_1$: Given any point $p\in X$, there exists two
homolorphic sections $f_{10}, ~~f_{01} \in H^0(X,L)$, such that
$$ f_{10}(p), ~~~f_{10}(p) =0 $$
and $\nabla f_{10}\big{|}_p$ and $\nabla f_{01}\big{|}_p$
are linearly independent in $TX_p^* \otimes L_p$.
$\textbf{Question:}$ Give a sufficient criteria on the line bundle
$L \rightarrow X $ to guarantee that statement $A_0$ and $A_1$ are true.
For example, does being "sufficiently ample" guarantee this?
$\textbf{Edit:} $ Statement $A_1$ was incorrectly stated before. I have also
removed the remaining statements, since they were not what I wanted.


text:
Q: Forward email using EWS managed api keeping the headers I am looking for a sample code on how to forward an existing email message (one that is already in my inbox) using the managed api.
When forwarded is there some way to keep a message original headers while forwarding it?
for example someone sent an email to me -i would like that ews will forward it to another recipient without changing the headers (original receive time from ,bcc etc...).

A: Given an EmailMessage object, you can just call the CreateForwareMessage() method:
var forwareMessage = item.CreateForward();

Regarding the other question: Get the MIME content of the mail and attach it to a new message:
item.Load(new PropertySet(BasePropertySet.IdOnly, ItemSchema.MimeContent));
var mail = new EmailMessage(service);
var attachment = mail.Attachments.AddFileAttachment("Original message.eml", item.MimeContent.Content);
attachment.ContentType = string.Format("message/rfc822; charset={0}", item.MimeContent.CharacterSet);
mail.ToRecipients.Add("hkrause@infinitec.de");
mail.Subject = "testmail";
mail.SendAndSaveCopy();

EDIT:
Create forward message and set reply to header:
var fw = item.CreateForward();
var fwMsg = fw.Save(WellKnownFolderName.Drafts);
fwMsg.ReplyTo.Add("personA@company.com");
fwMsg.SendAndSaveCopy();


text:
Q: Using the same codes in all test cases I want to create a header to use in all of my test cases. For example:
WebUI.openBrowser(GlobalVariable.appURL)
WebUI.maximizeWindow()
WebUI.waitForPageLoad(0)

Lets say I use these 3 lines in every test case I have. How can I put this in a single block(method, class etc) so that I can call it in all of my cases?

A: I think best way would be to create a test case for this and call it for example openBrowser. The main content you can put in another test case, and both together in a test suite. So you can re-use your test case for all other test suites.

A: You can go to Report Listeners and add:
@BeforeTestCase
def setupBeforeTestCase(TestCaseContext testCaseContext){
    WebUI.openBrowser(GlobalVariable.appURL)
    WebUI.maximizeWindow()
    WebUI.waitForPageLoad(0)
}

This will run before each test case. You could also add a tear down method, like this:
@AfterTestCase
def tearDownAtfetTestCase(TestCaseContext testCaseContext){
    WebUI.closeBrowser()
}


text:
Q: Java : Why is changing a local variable affecting a global variable original copy? I'm trying to assign a global variable's data and alter the local variable's data, but then when I change the local variable's structure, the global variable gets changed as well.
private void remove(Message M) {
      int           p = list.lastIndexOf(M);
      List<Message> x = list;
      list.remove(p);
      indexedMessages.remove(M.getMessageid());
      notifyItemRemoved(p);
      notifyItemRangeChanged(p, list.size());

// Removing the following items from "x" also causes the elements to be removed from recycleView.
      x.remove(0);
      x.remove(x.size() - 1);
}

Two things I don't understand :

*

*Why is "x" affecting "list"

*And why is "notifyItemRemoved" triggered again.

Anyway, on the original "list" (private List list), the first & last items are just placeholders. When an item is removed from this list, I want to store a new copy of that list without the placeholder.
The placeholders get added every time the adapter is created.

A: Before local variable x is made,

After local variable x is made,

After you removed an element from x,

Because the variable x is a pointer/reference to an object of type List<Message> called list. Therefore, changes to x will simultaneously be applied to list since they both point to the same object.
If you want to make changes to x without affecting the global variable, then you have to make x pointing to a new object and copy all the contents of the global variable into x. Note that this can be redundant. For example, this will work,
List<Message> x = new ArrayList<Message>();
//modify x here

For reasons pointed out in the comments, this is redundant because

*

*Local variables are lost after the method is finished

*List<Message> x = ArrayList<Message>() can be rewritten as List<Message> x = ArrayList<>() since the object type can be inferred from List<Message> so there's no need to restate it

Also if we have :
List<String> a = new ArrayList<String>();
a.add("a");
a.add("b");
a.add("c");

We can copy "a"'s contents into "b" as follows.
List<String> b = new ArrayList<>(a);


text:
Q: Xamarin Froms and SkiaSharp, Hightlight an Area on Image I use the below code to show image on a from.
<ContentPage>
        <ContentPage.Content>
                <Grid>
                      // Row definitions here
                      // Column definitions here
                      <Image
                            Grid.Column="0"
                            Grid.Row="0"
                            x:Name="myStoryPage"
                            Grid.ColumnSpan="3">
                      </Image>

                      <!-- Next, previous buttons here -->

                      <skiaforms:SKCanvasView x:Name="canvasView"
                                PaintSurface="canvasView_PaintSurface"
                                Grid.Row="3"
                                Grid.Column="0"
                                Grid.ColumnSpan="3"
                                AbsoluteLayout.LayoutBounds="10, 0, 5, 65"/>

                </Grid>
        </ContentPage.Content>
</ContentPage>

Now I need to highlight an area in the image using SkiaSharp.
I could do drawing a line under the grid using the SKCanvasView. But I want to draw over the image.
I thought to use use AbsoluteLayout but as my page is a ContentPage, I could not use the AbsoluteLayout outside of the content.
If I could use  AbsoluteLayout, I can dynamically position it using C# in code behind.


text:
Q: WPF SharedSizeGroup colum width changes for visible elements when scrolling How can I make one shared columns size for all elements in the listbox, also for elements that are outside of view. SharedSizeGroup working only for visible elements, but when I scroll down and elements in one of the columns becomes wider then the column becomes wider and opposite. How can I make shared size calculate max width of all elements also not visible and adjust the width one time? Excuse for my English. I hope someone can help me.

A: This is likely due to UI virtualization:

To improve performance, a ListBox uses UI virtualization by default.  UIElement-based objects are created only for the items currently being displayed in the list.  New UIElements are then created as additional items are scrolled into view.

Since the item isn't created yet, neither is the Grid inside, and so the SharedSizeGroup doesn't see it.
You can fix this by turning off UI virtualization for that ListBox:
<ListBox VirtualizingPanel.IsVirtualizing="False"/>

Note: you'll also lose all the performance benefits of UI virtualization, but that only becomes apparent if you have a large enough number of items you're displaying.


text:
Q: What is the optimum SQL for producing the below output? The input column has comma separated integer values like
Sample input 1)
1,2,200000,2345323,1200000

Sample Output 1)
1,2,2345323

Sample input 2)
546^515,400000,657180,3

Sample Output 2)
546^515, 657180,3

The output string should filter out all integers which have "5" trailing zeros.

A: Excising the five-zero numbers is straightforward with regexp_replace(). But it seems we also need to tidy up the commas left behind. This solution has another regexp_replace() to catch the ,, when the excised number is inside the string, and a simple trim() for when the number is the first or last in the string:
with cte as (
    select '1,2,200000,2345323,1200000' as str from dual union all
    select '546^515,400000,657180,3' as str from dual union all
    select '546^515,400000,1200000,657180,3' as str from dual union all
    select '54000000,400000,1200000,657180,300000000' as str from dual
    )
select trim(both ',' from regexp_replace(regexp_replace(str, '([0-9]+)00000', null),',(,+)',',')) as new_str
from cte
/


text:
Q: i used DateTimePicker in react-native I want to show Selected Date I am new to react native. I want to show My selected date it show in console. now in below code of dateTimePicker .what do you think the best solution  please help. thanks
import React, { Component } from "react";
import DateTimePicker from "react-native-modal-datetime-picker";
export default class booking extends React.Component {
showDateTimePicker = () => {
    this.setState({ isDateTimePickerVisible: true });
  };

  hideDateTimePicker = () => {
    this.setState({ isDateTimePickerVisible: false });
  };

  handleDatePicked = date => {
    console.warn("A date has been picked: ", date);

    this.hideDateTimePicker();
  };
}
 render(){

        return (
          <View style={styles.container}>

              <Text style={styles.selectDate}>Select Date:</Text>
            <Button title="click:" onPress={this.showDateTimePicker} />
            <Text>ateTime: {String(this.state.date)}</Text>

        <DateTimePicker

         maximumDate={new Date(2022, 10, 20)}
         minimumDate={new Date(2021, 5, 2)}
          isVisible={this.state.isDateTimePickerVisible}
          mode="date"
          onChange={ date => this.setState({ date }) }
          onConfirm={this.showDateTimePicker}
          onCancel={this.hideDateTimePicker}

        />
}

A: You were not using DateTimePicker properly. The simplest way to implement the DateTimePicker is to create a function that will trigger the Calendar or the Clock inside an input field when user click on the button or Text.
<TextInput
    placeholder=""
    onFocus={()=>RenderStartClock()}
/>

The function may be as below:
const RenderStartClock = () => {
         <DateTimePicker
               testID="dateTimePicker"
               value={startTime}
               mode={timeMode}
               is24Hour={true}
               display="clock"
               onChange={onChangeStartTime}
                                         />
                                  }


text:
Q: Two bodies of finite size treated as two point masses in Newtonian gravity When discussing gravitation between two bodies of finite size, for instance Earth around the Sun, we suppose the mass of Earth and the Sun to be perfectly localized at the center of each body. Is this a "useful" "good" "approximation" or the "absolute truth"?

A: This is certainly not the absolute truth, since every human on this planet is a living witness to the fact that Earth is not pointlike: It has finite volume.
However, there's a very good mathematical reason why we can consider the sun and Earth as pointlike when doing calculations in celestial mechanics: It's because the gravitational field due to a spherical body like the sun, when seen from outside of the sun, is identical to that of a pointlike gravitational charge with the same mass as the sun. This is called the shell theorem, and it is a consequence of Gauss' law for gravity, and a very similar result holds in the context of electromagnetism (where the name Gauss' law is most famous). This is an elementary exercise that many undergraduates are asked to derive in their first E&M course.
The relevant equations are:
$$\vec \nabla \cdot {\rm \vec g}= -4\pi G\rho(\vec r)\ ({\rm gravity})\hspace{1cm}\vec\nabla\cdot \vec E =\frac{\rho(\vec r)}{\epsilon_0}\ ({\rm electrostatics})$$
One can immediately see that they are essentially telling you the same thing, up to some proportionality constants, so a similar result is expected to hold for both.
There is one big caveat: Planets and stars are of course not perfectly spherically symmetric, so we're really dealing with an approximation after all. In fact, as pointed out in the comments, it is practically impossible to achieve perfect spherical symmetry, so our result should not be expected to hold exactly in reality - even though it's often extraordinarity close. However, this is not due to the fact that the bodies are not pointlike, but rather due to their lack of symmetry.

A: All finite-sized objects act like point masses at sufficiently large distances. A finite-sized three dimensional object of mass $M$ has a unique minimal bounding sphere with some radius $r$ and center $c$. For any distance $R>r$ from the center, the magnitude of the gravitational force on a small test body of mass $m$ is bounded by $\frac {GMm}{(R+r)^2} \le F \le \frac {GMm}{(R-r)^2}$, and the force is directed toward the center object, plus or minus $\arcsin\left(\frac r R\right)$. As $R$ grows ever larger, this converges to the gravitational force exerted by a point mass of mass $M$ located at $c$.
An object with a spherical mass distribution (density is a function only of distance from the center of the object) looks like a point mass everywhere outside the object. Other objects don't look quite like point masses at close distances. For example, a rotating large object will have shape that is more or less that of oblate spheroid (i.e., it will have an equatorial bulge). At close distances, that equatorial bulge will result in departures from a point mass model. These departures can be significant and important. For example, the Earth's equatorial bulge is what enables us to have satellites in sun-synchronous orbits.
This equatorial bulge is but the first of an infinite number of terms in the spherical harmonic expansion of an object's gravitational field. Using spherical harmonics is a commonly used approach to modeling a non-spherical object. That there are, in theory, an infinite number of terms presents a challenge with regard to modeling. Typically, a spherical harmonics approximation is truncated to some degree and order. For objects of extreme interest (e.g., the Earth), that degree and order can be rather high. The GRACE gravity model of the Earth is complete to degree and order 360. A formerly highly classified US agency, the National Geospatial Intelligence Agency, takes this even further. They have developed a 2190x2159 spherical harmonics gravity model of the Earth.
Even that 2190x2159 is a bit coarse compared to items of interest to a geophysicist. Academia churns out a lot more geophysicists than are needed by academia, and much of that surplus finds work in the petrochemical or mining industries. Local deviations from the gravitational acceleration suggested by an oblate spheroid are key indicators that there's oil, gold, or some other precious resource hiding underground. These deviations can also be of academic interest. For example, gravitational anomalies form one of the key pieces of evidence that the North American continent almost split in two 1.1 billion years ago at the Midcontinent Rift System.
Further afield, the Moon too does not look anything like a point mass at close distances. For example, the Apollo 16 mission released a small object, PFS-2, in orbit about the Moon, the intent of which was to orbit the Moon and measure charged particles and the Moon's magnetic field. PFS-2 was intended to be in a more or less circular low lunar orbit about the Moon. That's not what happened. Instead, something bizarre happened. After 35 days of weird changes to its orbit, PFS-2 crashed into the Moon.
A truncated spherical harmonics approximation works quite nicely for large bodies because the higher order terms quickly tend to zero for large bodies. Only a handful of terms are needed to describe a gas giant or a star. Significantly more terms are needed to accurately describe an Earth-sized body, and even more terms to describe a Moon-sized body. Ever smaller objects exhibit ever more deviations from sphericality. At some point, the spherical harmonics approach just doesn't work that well. An alternate approach used for small solar system bodies is to use a 3D picture of the object. Computer graphics models tend to use polyhedra to describe the 3D shape of an object. Starting with Barnett, "Theoretical modeling of the magnetic and gravitational fields of an arbitrarily shaped three-dimensional body," Geophysics 41.6 (1976): 1353-1364, these polyhedral gravity models turn out to be rather useful for describe the gravity of a small (asteroid-sized) body.

A: Point masses are merely an approximation of the motion of an extended body by the motion of its center of mass. It's a good approximation for small, mostly homogeneous (at least spherically layered) bodies, e.g. planets moving around the sun. But even for the orbital motion of the Moon around the Earth it's not a good approximation anymore.


text:
Q: Any way to make an anchor tag clickable if it's placed inside router-link? I have this component:
<template>

    <router-link class="news-card" :to="{ name: 'news-article'}">
      www.facebook.com
    </router-link>

</template>

and I want to make the anchor tag clickable so that it opens the URL https://www.facebook.com.
I've tried lifting it in priority with z-index but it doesn't seem to work:

The hover effect on the anchor works, but not the href property. Any idea how to do that?

A: router-link is basically a a tag, so you basically have an a tag inside of an a tag. I assume when clicking on www.facebook.com it would take you to  { name: 'news-article' } instead of facebook.
This is what you wanna do I guess..
<template>

    <router-link class="news-card" to="https://www.facebook.com">
         www.facebook.com
    </router-link>

</template>


text:
Q: The Preview Doesn't Displayed At The Launching (Android Studio) I started learning the Android SDK and I have a problem.
I launched the studio and the android screen didn't show up (YES, I know where the preview tool bar and how to switch).
Quote:
"Rendering Problems The following classes could not be found:
- android.support.v7.internal.widget.ActionBarOverlayLayout (Fix Build Path, Edit XML, Create Class)
 Tip: Try to build the project."
*Sometimes there is another rendering problem and this is showed :
"Rendering Problems The following classes could not be instantiated: - android.support.v7.internal.widget.ActionBarOverlayLayout (Open Class, Show Exception, Clear Cache)"

A: I'm pretty sure its the "appcompat_v7", which is automatically generated in eclipse when setting up an android project. It imports unnecessary features and causes a bunch of build errors.

*

*Delete "appcompat_v7" folder

*
*

*go to your MainActivity

*Delete the import "android.support.v7.app.ActionBarActivity";

*change "MainActivity extends ActionBarActivity" to  "MainActivity extends Activity"

*
*

*add import android.app.Activity;

*add import android.os.Bundle;

*add import android.view.Menu;

*add import android.view.MenuItem;

*go to res folder and then go to your values folder...delete styles.xml

*delete values-v11 folder

*delete values-v14 folder

*go to menu folder, and click on main.xml...go to "item" tag and delete app:showAsAction="never"

*go to AndroidManifest.xml...go to "application" tag...delete  android:theme="@style/AppTheme"

*go to project at the top...clean and build...you should have no more errors.


text:
Q: How to use comma as tmux's prefix Under screen, I used:
bindkey , command to use the comma as the prefix instead of Ctrla.
If I do set -g prefix in tmux, it complains saying: unkown key
At first, I believed that tmux did not support single keys as prefix, However, I managed to use  \ as a prefix successfully!
How can I do so for the ,?
[Edit] Apparently this works under tmux 1.6, haven't tried it though. Thx  jasonwryan for the hint :)


text:
Q: How to switch between Android apps programmatically I want to switch quickly between two running Android apps, a Client and a Server, for debugging purposes. The two are connected by a socket connection.  Ideally, I'd like to add a button to both to toggle to the other (preserving the connection) so I can easily see what's going on at both ends.
Here's what I tried:

*

*Using "Recent Apps" button
This worked fine but is a bit awkward, especially if the stack is big.

*Using Split Screens
This also worked fine but the small screens were problematic

*Tried Third-Party App Switchers but didn't like these.

*Tried startActivity by package name (on button click)
This would be my preferred solution but had problems. Switched Ok but each time a fresh task was created, started and pushed onto the stack (not preserving the connection).  Code below:
void switchToClient()       // from Server (on Button click)
{
    // Alternative Flags Tried: none, FLAG_ACTIVITY_SINGLE_TOP, FLAG_ACTIVITY_NEW_TASK, other
    Intent intent;
    intent = this.getPackageManager().getLaunchIntentForPackage( "com.example.Client" );
    intent.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK );
    startActivity( intent );
}

A: I finally figured out how to switch between apps
programatically (preserving their state). In each app, I used 'getTaskId()' to get its task id and saved it to a file on /sdcard/.
Then, in each app, on a button click, I call
void switchTask()
{
  int tid;
  ActivityManager am;
  am = (ActivityManager)Ctx.getSystemService( Context.ACTIVITY_SERVICE );
  tid = getPkgTaskId();  // read task id of *other* app from file
  am.moveTaskToFront( tid, 0, null );
}

Note: These need permissions:

*

*READ_EXTERNAL_STORAGE

*WRITE_EXTERNAL_STORAGE

*REORDER_TASKS


text:
Q: ./src/Firebase.js Module not found: Can't resolve 'firebase' in 'C:\Users\HP\Desktop\React\clones\disney-plus-clone\src' I am working on a react project and I need firebase for authentication I have installed firebase using "npm i firebase" & firebase-tools using "npm i firebase-tools" also the path is correct. There is no problem in defining the path. Everything from my side is correct then also it is showing the above error.
--- Please help -----

A: Why this is happening?
If you give a look at firebase package version(inside package.json) then it's version 9. Now firebase has added a new compatibility option so can use the /compat folder in your imports.

I have made some changes in Firebase.js file please replace your code
with the given below and then start your dev server.

import firebase from "firebase/compat/app"
import "firebase/compat/auth"
import "firebase/compat/firestore"
import "firebase/compat/storage"

const firebaseConfig = {
  apiKey: "AIzaSyA9BnlX96fMf7XiUVCFRsoQzG8DGERJkeY",
  authDomain: "disneyplus-clone-a33d5.firebaseapp.com",
  projectId: "disneyplus-clone-a33d5",
  storageBucket: "disneyplus-clone-a33d5.appspot.com",
  messagingSenderId: "37918794208",
  appId: "1:37918794208:web:dbe9842dfe1dda522a4b85",
  measurementId: "G-DRVLJKWRWG",
};

firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
const auth = firebase.auth();
const provider = new firebase.auth.GoogleAuthProvider();
const storage =firebase.storage();

export { auth,provider,storage};
export default db;


text:
Q: how to unzip an image in the iphone code to unzip an image file sent after gzipping it on the server side i know i have to use gzopen.
i want to know if there is a more direct and simple way to do this with 'compressiontype' or something related that once i have the 'zipped image data' received from the server using NSURLconnection can i load an imageview using an easier method.

A: The zip library you are using will dictate how you can unzip the received data.
I haven't found a zip library that will unzip directly from an NSData object; I've found that the data needs to be written to a file (in the documents directory) and then unzipped.
I use 'ziparchive' available http://code.google.com/p/ziparchive/wiki/PageName


text:
Q: How to get returned object from JPA EntityManager as customized bean I am trying to join 3 tables to get required info using entityManager.createQuery.
Code littlepet as follows:
List<Object[]> o=entityManager.createQuery("SELECT u.loginId,ui.emailId,u.userId,ui.firstName,up.password,ui.phoneNunber,u.roleTypeId"  + " From Users as u,UserInfo ui, UserPassword as up where u.userId = up.userId "    + "AND u.userId=ui.userId").getResultList();

I have a bean with the above returned fields UserDetails.
public class UserDetails
{
    String LoginId;
    String Email;
    String UserId;
    String FirstName;
    String Password;
    String Mobile;
    String RoleTypeId;
    int Status;

getters() & setters()
}

But when I am trying to use List of UserDetails instead List of Object[] it says ClassCastException.
How to get/convert the returned object with customized bean?

A:  List<UserDetails> o=entityManager.createQuery("SELECT new package.UserDetails( u.loginId,ui.emailId,u.userId,ui.firstName,up.password,ui.phoneNunber,u.roleTypeId)"  + " From Users as u,UserInfo ui, UserPassword as up where u.userId = up.userId "    + "AND u.userId=ui.userId").getResultList();

You need to have constructor with parameters in the same order as the fields are selected in the query, thus UserDetails(loginId, emailId, userId, firstName, password, phoneNunber, roleTypeId)
Or you can use your code and then write a converter which converts an array of objects into UserDetails.
 List<Object[]> retrievedObjects = //yourCode.
 for (Object[] objs : retrievedObjects) {
      //write convert method which populates **UserDetails** fields from the objects.
      UserDetails ud = convert(objs);
 }

A: You can use a result transformer. Result transformer is a Hibernate feature (not JPA). So you need to use Session or Query from Hibernate.
Something like this:
List<UserDetails> result = entityManager.createQuery(
  "SELECT u.loginId as loginId, ui.emailId as emailId ..."
).unwrap(org.hibernate.query.Query.class)
 .setResultTransformer(new AliasToBeanResultTransformer(UserDetails.class))
 .list();

You need to have aliases in the HQL: u.loginId as loginId and corresponding properties in the UserDetails:
class UserDetails
{

  private String loginId;

  public String getLoginId() {
    return loginId;
  }

  public void setLoginId(String loginId) {
    this.loginId = loginId;
  }

}

Examples of transformers:
http://jpwh.org/examples/jpwh2/jpwh-2e-examples-20151103/examples/src/test/java/org/jpwh/test/querying/advanced/TransformResults.java


text:
Q: Mean value theorem inside the Expectation Consider a stochastic process $X_t$ with continuous paths. I'd like to apply the mean value theorem inside the expectation, i.e. write something like
$$ \operatorname{E} \left[ \int_0^t X_s \, \mathrm{d}s\right] = t \operatorname{E} [X_{\xi_{\omega}}] \leq  t \operatorname{E} \left[ \sup_{\xi_{\omega} \in (0,t)} X_{\xi_{\omega}}\right].$$
Is it enough to require something like $\operatorname{E} [ \sup_{s \in (0,t)} |X_s|] < \infty$ for this reasoning to be valid or does one need additional assumptions? I'm concerned about the measurability of $\omega \mapsto X_{\xi_{\omega}}(\omega)$.

A: The mapping $\omega \mapsto X_{\xi(\omega)}(\omega)$ is measurable if the corresponding process is jointly measurable, i.e. if
$$(t,\omega) \mapsto X(t,\omega) \tag{1}$$
is $\mathcal{B}([0,T]) \otimes \mathcal{A} /\mathcal{B}(\mathbb{R})$-measurable for $T>0$. This can be proved in the following way:
Let $f$ be a continuously differentiable function, then by Taylor's formula
$$f(t)-f(s) = f'(\xi) \cdot (t-s)$$
for some intermediate value $\xi \in (s,t)$. This is the Lagrange form of the remainder term. On the other hand, we can also write
$$f(t)-f(s) = \int_s^t f'(r) \, dr.$$
This shows that
$$f'(\xi) = \frac{1}{t-s} \int_s^t f'(r) \, dr. \tag{2}$$
In your case, we have $f(t) = \int_0^t X_r(\omega) \, dr$; hence, by $(2)$,
$$X_{\xi(\omega)}(\omega)= f'(\xi(\omega)) = \frac{1}{t} \int_0^t X_r(\omega) \, dr.$$
Now it follows from $(1)$ and Fubini's theorem that
$$\omega \mapsto \frac{1}{t} \int_0^t X_r(\omega) \, dr$$
is measurable for each $t>0$. Finally, note that condition $(1)$ is automatically satisfied since the process has continuous sample paths. (Hint: Approximate the process with simple functions.)


text:
Q: Flexlm license option file entry Can we keep License reservations and max lines together in the same option file for the same feature ?
for example
GROUP ABC xyz1 xyz2 xyz3
RESERVE 20 feature USER xyz
MAX 3 feature GROUP ABC
in the above case we have all 20 license reserved for the user xyz and then we tried to keep limit of 0 to group ABC - in this case what would happen ? how does flexlm works ?
any suggestion or solution is appreciated .

A: The 'RESERVE' option attach the increments/feature to USER , HOST , DISPLAY , INTERNET , PROJECT , GROUP , or HOST_GROUP according with the manual. If you make a lmutil lmstat -c <port@server> -f <feature>, you'll see something like below. The RESERVATION are seen like some used increments. In any case, a limitation imposed to a group could be inferior to a RESERVATION that consume the increments.
With a previous version of LMGRD, I've tried to use the both directives in the same time with no success.
I don't know how the daemon vendor can modify the LMGRD's behaviour.
    Users of a-increment:  (Total of 188 licenses issued;  Total of 160 licenses in use)

  "a-increment" v2015.1231, vendor: daemon-vendor
  floating license

  4 RESERVATIONs for GROUP GROUP-OF-PEOPLE_Group (license-server/27000)

  "a-increment" v2016.0331, vendor: daemon-vendor
  floating license

  28 RESERVATIONs for GROUP GROUP-OF-USER_Group (license-server/27000)
  20 RESERVATIONs for GROUP GROUP-OF-USER_Group (license-server/27000)
    tom peanut peanut (v2015.0312) (license-server/27000 1431), start Fri 11/20 9:53, 8 licenses

  "a-increment" v2015.1231, vendor: daemon-vendor
  floating license

  "a-increment" v2016.0331, vendor: daemon-vendor
  floating license

  88 RESERVATIONs for GROUP OTHER-GROUP_Group (license-server/27000)
  12 RESERVATIONs for GROUP OTHER-GROUP_Group (license-server/27000)


text: Q: MATLAB - convert from normalised figure units to axis data units I am manually drawing an annotation onto a figure in MATLAB (via insert --> line) and I would like to know how to convert from its position in normalised figure units to axis data units. This is the reverse of an operation that is commonly solved by functions around the internet. However, I am unclear as to how MATLAB converts from axis data units to normalised figure units.


text:
Q: TestCaseA teardown runs 4 seconds after TestCaseB starts is this a bug? We are using ReadyAPI 3.6.0, we use Jenkins with testrunner to execute our testsuites. I am trying to understand if I have found a bug in ReadyAPI or if it is user error.
My scenario is I have a TestSuite with TestCase A and TestCase B. For Test A in the teardown tab with Groovy script I call two testcases (TestCaseX and TestCaseY) both are needed to reset my environment before TestCaseB executes.
I have an intermittent issue, for a one of my builds, TestCase A finishes executing (as well as TestCase X from the teardown) , TestCase B  starts to execute then 4 seconds later  TestCase Y is executed from the teardown script of Test Case A. I was expecting the entire teardown script of Test Case A to finish executing before testrunner launches Test Case B. Is this a defect or something wrong in my teardown code?  Many thanks for your support and advice.
My Groovy code in TestCase A Teardown tab is below:
// get Reset Environment Test Suite X
def resetTestSuiteX= testRunner.testCase.testSuite.project.getTestSuiteByName("Reset Test Suite X")
// get Reset Environment Test Case X
def resetTestCaseX= resetTestSuiteX.getTestCaseByName("Reset Test Case X")
// set a property in context required to execute testcase A
context.setProperty("in.opt.filename","filename1.json")
// run the testCase Y passing the context
def contextMap = new StringToObjectMap( context )
resetTestCaseX.run(contextMap,true);

// get Reset Environment Test Suite Y
def resetTestSuiteY= testRunner.testCase.testSuite.project.getTestSuiteByName("Reset Test Suite Y")
// get Reset Test Case Y
def resetTestCaseY= resetTestSuiteY.getTestCaseByName("Reset Test Case Y")
// run the testCase Y passing the contextMap (but it ignores it as it doesn't need any property to run)
resetTestCaseY.run(contextMap,true);

A: This is untested code!
TestCase.run() returns a TestCaseRunner, which I believe is non-blocking. You might want to wait for it to finish. Something like:
//...
def runner = resetTestCaseX.run(contextMap, true)
runner.waitUntilFinished()

// similarly for your resetTestCaseY.run()

API reference, as sparse as it is, might be helpful.


text:
Q: Creating a user controlled data service with Google App engine I am designing a to-do list manager for the iPhone using GAE as the back end. My end goal is to create user sharable lists, and I was looking for some advice/examples of how to go about designing something like that. I know the google user API provides functionality for authenticating users, but from what I can tell any additional user management would be something I would need to implement myself.
Can something like this be done by simply adding usernames to a list that is a property of the data I want to share? I am guessing I am oversimplifying things, but any suggestions would be appreciated.
Thanks

A: you're right, app engine doesn't have any built in support for user ACLs or permissions, and a few quick web searches didn't immediately turn up any obvious open source libraries.
how to implement full-fledged permissions and ACLs for group sharing is definitely a nontrivial design question. there are a number of other questions here about it.
having said that, as a very rough first pass, you're probably on the right track with storing lists of users. i'd suggest that you abstract the list into separate Group entities, and attach those to yor data instead, so that users can define groups once instead of for every piece of data. i'd also consider storing separate lists of groups that can read vs write. finally, i'd store User properties in the group entities, instead of string usernames or email addresses.


text:
Q: PHP PDO MS SQL Server SELECT LIMIT I am converting my project from MySQL based to MS SQL using PHP PDO, The below code allows to thread thought records (left and right)and if the record lets say #1 then it should stay on #1 same for the last record. I get error:

Notice: Trying to access array offset on value of type bool in
  C:\inetpub\wwwroot\dxbase\DB_Project\private\supplierschoice.php on
  line 96

Line 96 is where:
<?php echo "<input type='text' id='CSupplierCode' value='" . $row['SupplierCode'] . "'>"; ?>

I also have $row = $result->fetch(); before that.
Code that runs on "LEFT" button:
<?php
$sql = "SELECT s.SupplierID, ..., l.StreetAddress, ... FROM Suppliers s LEFT JOIN Locations l ON s.SupplierID = l.RefID WHERE l.LocGroup = 1 AND s.SupplierID < '" . $tID . "' ORDER BY s.SupplierID DESC LIMIT 1";
$result = $conn->prepare($sql);
$result->execute();
if (!$result) {
   $sql = "SELECT s.SupplierID, ..., l.StreetAddress, ... FROM Suppliers s LEFT JOIN Locations l ON s.SupplierID = l.RefID WHERE l.LocGroup = 1 AND s.SupplierID = '" . $tID . "'";
   $result = $conn->query($sql);
   if (!$result) { echo "Error creating a record: " . $sql . "
" . $conn -> errorInfo();}
}
?>

The code does NOT get to the second part (!$result), so it gives a warning and empty inputs.
UPDATE:
Tried to use SELECT TOP 1
$sql = "SELECT TOP 1 s.SupplierID, s.SupplierCompany, s.SupplierCode, s.Currency, s.PaymentTerm, s.ShippingTerm, s.TMode, s.Agent, s.Carrier, s.Warehouse, l.StreetAddress, l.Suite, l.City, l.Locality, l.State, l.PostalCode, l.Country FROM Suppliers s LEFT JOIN Locations l ON s.SupplierID = l.RefID WHERE l.LocGroup = 1 AND s.SupplierID < '" . $tID . "' ORDER BY s.SupplierID DESC";
    $result = $conn->query($sql);
    if (!$result) {
        $sql = "SELECT s.SupplierID, s.SupplierCompany, s.SupplierCode, s.Currency, s.PaymentTerm, s.ShippingTerm, s.TMode, s.Agent, s.Carrier, s.Warehouse, l.StreetAddress, l.Suite, l.City, l.Locality, l.State, l.PostalCode, l.Country FROM Suppliers s LEFT JOIN Locations l ON s.SupplierID = l.RefID WHERE l.LocGroup = 1 AND s.SupplierID = '" . $tID . "'";
        $result = $conn->query($sql);
        if (!$result) { echo "Error creating a record: " . $sql . "
" . $conn -> errorInfo();}
    }

it is still does not get to the 2nd part after ID less then #1 and it seems like (!$result) is not working here..

A: OK! After 100 trial and errors I got the following code working properly
for moving left and right in MS SQL Server
} elseif ($tID > 0 && $Order == 3) {
    $sql = "SELECT TOP 1 s.SupplierID, s.SupplierCompany, s.SupplierCode, s.Currency, s.PaymentTerm, s.ShippingTerm, s.TMode, s.Agent, s.Carrier, s.Warehouse, l.StreetAddress, l.Suite, l.City, l.Locality, l.State, l.PostalCode, l.Country FROM Suppliers s LEFT JOIN Locations l ON s.SupplierID = l.RefID WHERE l.LocGroup = 1 AND s.SupplierID < '" . $tID . "' ORDER BY s.SupplierID DESC";
    $result = $conn->query($sql);
    $row = $result->fetch(PDO::FETCH_ASSOC);
    if (!$row) {
        $sql = "SELECT s.SupplierID, s.SupplierCompany, s.SupplierCode, s.Currency, s.PaymentTerm, s.ShippingTerm, s.TMode, s.Agent, s.Carrier, s.Warehouse, l.StreetAddress, l.Suite, l.City, l.Locality, l.State, l.PostalCode, l.Country FROM Suppliers s LEFT JOIN Locations l ON s.SupplierID = l.RefID WHERE l.LocGroup = 1 AND s.SupplierID = '" . $tID . "'";
        $result = $conn->query($sql);
        $row = $result->fetch(PDO::FETCH_ASSOC);
    }
} elseif ($tID > 0 && $Order == 7) {
    $sql = "SELECT TOP 1 s.SupplierID, s.SupplierCompany, s.SupplierCode, s.Currency, s.PaymentTerm, s.ShippingTerm, s.TMode, s.Agent, s.Carrier, s.Warehouse, l.StreetAddress, l.Suite, l.City, l.Locality, l.State, l.PostalCode, l.Country FROM Suppliers s LEFT JOIN Locations l ON s.SupplierID = l.RefID WHERE l.LocGroup = 1 AND s.SupplierID > '" . $tID . "' ORDER BY s.SupplierID ASC";
    $result = $conn->query($sql);
    $row = $result->fetch(PDO::FETCH_ASSOC);
    if (!$row) {
        $sql = "SELECT s.SupplierID, s.SupplierCompany, s.SupplierCode, s.Currency, s.PaymentTerm, s.ShippingTerm, s.TMode, s.Agent, s.Carrier, s.Warehouse, l.StreetAddress, l.Suite, l.City, l.Locality, l.State, l.PostalCode, l.Country FROM Suppliers s LEFT JOIN Locations l ON s.SupplierID = l.RefID WHERE l.LocGroup = 1 AND s.SupplierID = '" . $tID . "'";
        $result = $conn->query($sql);
        $row = $result->fetch(PDO::FETCH_ASSOC);
    }


text:
Q: Check for Apostrophe in Regex Pattern in Element Added with jQuery (Single-Quote in Single-Quote in Double-Quote) I am trying to create an input for a company name using jQuery. I am also using the Bootstrap Validator plugin by 1000hz in order to add validation for this input. I am specifically trying to use the "pattern" attribute in order to validate the input with a regex. An example of what I'm trying to accomplish is below:
var name = "<input type='text' pattern='^[a-zA-Z0-9]+(?:[&'\-. ]+[a-zA-Z0-9., ]+)*$'>";

....

$("#list").after(name);

I'm trying to include an apostrophe into the pattern so that a company name like "McDonald's" would be valid. However, since the pattern is within single-quotes the symbol winds up being treated as the end of the pattern string. I can't use double-quotes because they're being used for the variable, and trying to use escape characters doesn't change it from being treated as the end of the string.
Does anyone know how I go about fixing this?


text:
Q: How to write this meaning in a MySQL query? How to write this meaning in a MySQL query?
where ((location/'$location'<2) and (location/'$location'>=1))

A: where location/'$location' between 1 and 2

Edit: Since it should only match those that are precisely 2, then this should work:
where location div '$location' = 2

A: If you want floating-point division, that should be fine, but if you want integer division:
WHERE location DIV '$location' IN (1, 2)

A: I would have to know a bit more about your database but are you trying to select something such as:
select location from -- some table
where ((location/'$location'<2) and (location/'$location'>=0))


text:
Q: Create a shared folder in Dropbox with dropbox-core-sdk-2.0-beta-4 and then add a member to it I am trying to create a shared folder in a dropbox account, from a Java desktop application by using the dropbox-core-sdk-2.0-beta-4, with the code below, but I am getting these exceptions:
java.lang.NoSuchMethodError:     com.dropbox.core.json.JsonWriter.writeFields(Ljava/lang/Object;Lcom/fasterxml/jack son/core/JsonGenerator;)V
at com.dropbox.core.v2.DbxFiles$CreateFolderArg$1.write(DbxFiles.java:5337)
at com.dropbox.core.v2.DbxFiles$CreateFolderArg$1.write(DbxFiles.java:5332)
at com.dropbox.core.json.JsonWriter.writeToStream(JsonWriter.java:23)
at com.dropbox.core.json.JsonWriter.writeToStream(JsonWriter.java:33)
at com.dropbox.core.v2.DbxRawClientV2.rpcStyle(DbxRawClientV2.java:82)
at com.dropbox.core.v2.DbxFiles.createFolder(DbxFiles.java:8459)
at com.dropbox.core.v2.DbxFiles.createFolder(DbxFiles.java:8479)

My code is the following:
DbxRequestConfig dbxRequestConfig = new DbxRequestConfig("test/1.0",     Locale.getDefault().toString());
DbxClientV2 dbxClient = new DbxClientV2(dbxRequestConfig, my_access_token);

FolderMetadata md = dbxClient.files.createFolder("/test");

ArrayList<AddMember> list = new ArrayList();
DbxSharing.AddMember a1 = new       DbxSharing.AddMember(DbxSharing.MemberSelector.email("xxxxxx@gmail.com"),
DbxSharing.AccessLevel.editor);

list.add(a1);
dbxClient.sharing.addFolderMember(md.parentSharedFolderId, list);

My code is heating at:
FolderMetadata md = dbxClient.files.createFolder("/test");

I have already search for any solution to create a shared folder and add a member to it, but I am not finding anything useful to my case.
Could anyone tell me what I am doing wrong?


text:
Q: search through a List with a Comma separated string I have a comma separated string FacultyList="1,2,3,4...1004,1005..."

Then there is a List of applicants of type "InitialApplicantModel". FacultyList is a property of InitialApplicantModel.
public class InitialApplicantModel
{
  public int applicantID {get;set}
  public string FacultyList {get; set;}
}

I want to get a list of applicants where their FacultyList contains the value 4.

EX: applicantID 1 has the FacultyList=1,2,30,4,..100 / applicantID 2 has
  the FacultyList=200,301,.... / applicant 3 has the
  FacultyList=101,2,31,4,..110

So the final list should return applicant 1 and 3.
I tried the code below but doesn't seem to return the correct result.
foreach (InitialApplicantModel item in applicants)
{
    if (item.FacultyList != null)
    {
        string[] array = item.FacultyList.Split(',');
        array = array.Where(x => !string.IsNullOrEmpty(x)).ToArray();
        applicants = applicants.AsEnumerable().Where(o => array.Any(b =>(b)== "4")).ToList();
    }
}

A: You just need Where() method to filter datas as you want. These method accepts anonymous method as input. These method must return boolean value. Inside this method, you must split the value by ',' and then search if the returned array contains 4 or not.
var result = applicants
             .Where(x => x.FacultyList.Split(',').Contains("4"))
             .ToList();

Update1:
If the string is null, .Split() will  throw a NullReferenceException.
var result = applicants
             .Where(x => !String.IsNullOrEmpty(x.FacultyList) ?
                          x.FacultyList.Split(',').Contains("4") : false)
             .ToList();

Update2:
var result = applicants
             .Where(x => !String.IsNullOrEmpty(x.FacultyList) ?
                          x.FacultyList.Split(',').Equals("4") : false)
             .ToList();

A: You don't need the foreach loop:
applicants = applicants
            .AsEnumerable()
            .Where(o => o.FacultyList.Split(',').Contains("4")).ToList();


text:
Q: Is it bad practice to connect a heatsink to my PCB's ground plane? So, basically, I have this LED project which is going to dissipate lots of heat (I am assuming close to 50W) inside a case. The LEDs themselves are on a separate aluminum board which will be attached to a heat pipe CPU cooler with a fan. The control circuitry for which I am designing a PCB will also get kind of hot based on formulas from the datasheet for the buck drivers (though theoretically still well below the ratings they give and assuming the low end of efficiency from component tolerances) and I'm wanting to help move that heat onto the cooler rather than sitting inside a closed case. I had the thought of connecting the cooler's heatpipes to the ground plane of the PCB with some exposed copper and using kapton tape to protect any vias that could short through the heatpipes if the solder mask were to be compromised.
Is this a bad idea? Is this something that people do often? To me it seems like it may reduce any noise because it would effectively make the ground plane bigger. I don't really see what would be problematic about it since any non-ground paths would be isolated from the heatpipes. The cooler itself will also be covered by a 3D-printed cage.


text:
Q: Eigenvalues of matrix with linear dependent rows Why is it that, if a matrix has a linear dependent row, e.g.:
$$
A=\begin {pmatrix} 1 \ 2 \\ 2 \ 4 \end {pmatrix},
$$
at least one eigenvalue is zero?

A: Ok, so I found an answer with the help of Bye_World's comment and want to provide it in case anybody else is also wondering: In order to find eigenvalues of a matrix, we need its characteristic polynomial, which is calculated as follows:
$$
\det (\lambda I-A)=\det \begin {pmatrix} \lambda -a_{11} & -a_{12} \\ -a_{21} & \lambda -a_{22} \end{pmatrix}=\lambda ^2 - (a_{11}+a_{22}) \lambda + a_{11}a_{22}-a_{12}a_{21}=0,
$$
where
$$
\det (A)= a_{11}a_{22}-a_{12}a_{21}.
$$
So we can see that if $det (A)=0$, which is the case if there is a linear dependent row, then $\lambda=0$ is a solution.

A: If λ=0, then A=A-λI, and det(A)=det(A-λI).
There's a linear dependent row (as you said) in A, and that implies that det(A)=0. But det(A)=det(A-λI), so det(A-λI)=0, and λ=0 is an eigenvalue of A.


text:
Q: How to print all POST variables from form from python controller NOTE: I have no idea how the other post sited answers this question.  I did discover the following:
if you want to print to the browser you can just add:
return jsonify(request.form)

if you want to print to the console you can add:
my_data = request.form
for key in my_data:
    print ('form key '+key+" "+my_data[key])
return render_template("some.html")

I'm trying to print all POST variables with the following controller:
from flask import Flask, render_template, request

app = Flask(__name__)

@app.route("/")
def index():
    return render_template("index.html")

@app.route("/register", methods=["POST"])
def register():

dict = request.form
for key in dict:
    print ('form key '+dict[key])

but am getting the error:
ValueError: View function did not return a response

here is my form:
{% extends "layout.html" %}

{% block title %}
Frosh IMs
{% endblock %}

{% block body %}

Register for Frosh IMs

<form action="{{ url_for('register') }}" method="post">
    Name: <input name="name" type="text"/>

    Dorm:
    <select name="dorm">
      <option value=""></option>
      <option value="Apley Court">Apley Court</option>
      <option value="Canaday">Canaday</option>
      <option value="Grays">Grays</option>
      <option value="Greenough">Greenough</option>
      <option value="Hollis">Hollis</option>
      <option value="Holworthy">Holworthy</option>
      <option value="Hurlbut">Hurlbut</option>
      <option value="Lionel">Lionel</option>
      <option value="Matthews">Matthews</option>
      <option value="Mower">Mower</option>
      <option value="Pennypacker">Pennypacker</option>
      <option value="Stoughton">Stoughton</option>
      <option value="Straus">Straus</option>
      <option value="Thayer">Thayer</option>
      <option value="Weld">Weld</option>
      <option value="Wigglesworth">Wigglesworth</option>
    </select>

    <input type="submit" value="Register"/>
</form>
{% endblock %}

A: you need flask to return something to the browser:
from flask import jsonify

@app.route("/register", methods=["POST"])
def register():
    # this line goes to the console/terminal in flask dev server
    print request.form
    # this line prints out the form to the browser
    return jsonify(request.form.to_dict())

Multidict to_dict() method returns a normal python dict from the MultiDict.


text:
Q: Swift 3: Authenticate with custom token(s), managing requests with server (node.js) There is not much information in the Firebase Docs on dealing with custom tokens.
I have set up a server with node.js, but I don't know how to manage requests to the server to send the information back to the app and vice-versa. Any resources on how to achieve this?
This is the code for the node.js server
var serviceAccount = require('./service-account.json');
var firebase = require('firebase');
var path = require("path");
var admin = require('firebase-admin');
var FirebaseTokenGenerator = require("firebase-token-generator");
var refreshToken;

var uid = 'clientId';
var additionalClaims = {
  admin: true, manager: true, menuAccess: true
};
var clientIdToken = firebase.auth().createCustomToken(uid, additionalClaims);

console.log(clientIdToken)

firebase.initializeApp({

    serviceAccount: path.resolve(__dirname, '/Users/myUserName/Desktop/nodeClient/service-account.json'),
    databaseURL: "https://<firebase-project>.firebaseio.com/",
    databaseAuthVariableOverride: {
      uid: "clientId"
    }

});

In xcode:
    func login (email: String, password: String, onComplete: Completion?) {
        self.showActivityIndicatory(uiView: self.uiView)
            FIRAuth.auth()?.signIn(withEmail: email, password: password, completion: { (user, error) in

            if error != nil {

                self.handleFirebaseError(error: error! as NSError, onComplete: onComplete)

                self.stopAnimating()

            } else {

                // User successfully logged in

                FIRAuth.auth()?.addStateDidChangeListener { auth, user in
                    if user != nil {

                        let userUpdate = ["provider": String(describing:FIRAuth.auth()?.currentUser?.providerID), "email": "email": String(describing: FIRAuth.auth()?.currentUser?.email!) ]
                        DataService.instance.registerUsers(uid: (user?.uid)!, user: userUpdate)

                        FIRAuth.auth()?.signIn(withCustomToken: "clientIdToken") {(user, error) in

                            if user != nil {
                                print("Got here somehow..")
                                print(user?.uid)

// as I create a custom token, this user?.uid should be "clientId", right?

                            } else {
                                print(error)

// I get an error here
                            }

                        }

                        print("Signed in")

                    } else {
                        print("NOT SIGNED IN")
                    }
                }

                let deadlineTime = DispatchTime.now() + .seconds(1)
                DispatchQueue.main.asyncAfter(deadline: deadlineTime) {

                    self.performSegue(withIdentifier: "HomeSegue", sender: nil)

                }

                }

            })

    }

Optional(Error Domain=FIRAuthErrorDomain Code=17000 "The custom token format is incorrect. Please check the documentation." UserInfo={NSLocalizedDescription=The custom token format is incorrect. Please check the documentation., error_name=ERROR_INVALID_CUSTOM_TOKEN})

How shall I proceed? I know I have to send the credentials to my server from the app, but how do I achieve this? I am thinking of digging into JWT and Alamofire, and I have searched for days to solve this particular problem. I have encountered other programmers tackling the same issue.


text:
Q: create additional users in mysql kubernetes pods I'm trying to create additional users for MySQL pod.
i used the env variable- MYSQL_USER to create additional users. after the creation of the pod. I'm able to only use the second user not the first user.
is there a way i can achieve this ?

A: You can use the /docker-entrypoint-initdb.d

When a container is started for the first time, a new database with
the specified name will be created and initialized with the provided
configuration variables. Furthermore, it will execute files with
extensions .sh, .sql and .sql.gz that are found in
/docker-entrypoint-initdb.d. Files will be executed in alphabetical
order. You can easily populate your mysql services by mounting a SQL
dump into that directory and provide custom images with contributed
data. SQL files will be imported by default to the database specified
by the MYSQL_DATABASE variable.

You can mount your files at that path
volumes:
      - ./<your-path-to-create-user.sql>:/docker-entrypoint-initdb.d

create-user.sql
CREATE USER 'root'@'%' IDENTIFIED BY 'password';
CREATE USER 'user1'@'%' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%';

so after initializing the above SQL script will get executed and create the users to database,you can edit it as per need.
If you are on Kubernetes you can use the configmap
apiVersion: extensions/v1beta1
kind: Pod
metadata:
  name: mysql
spec:
  containers:
  - name: mysql
    image: mysql
    .....
    env:
    - name: MYSQL_ROOT_PASSWORD
      value: "root"
    .....
    volumeMounts:
      - name: mysql-inituser
        mountPath: /docker-entrypoint-initdb.d
  volumes:
  - name: mysql-inituser
    configMap:
      name: users
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: users
data:
  create-user.sql: |-
    CREATE USER 'root'@'%' IDENTIFIED BY 'password';
    CREATE USER 'user1'@'%' IDENTIFIED BY 'password';
    GRANT ALL PRIVILEGES ON *.* TO 'root'@'%';


text:
Q: 'Unresolved external symbol' errors I am using an example program that is supposed to allow control of MIDI devices using a protocol called OSC.
What I have done is downloaded the SDK from here: http://mac.softpedia.com/get/Development/Libraries/oscpack.shtml
The 'examples' folder contains a file called 'SimpleSend.cpp'. The code for this is as follows:
#include "osc/OscOutboundPacketStream.h"
#include "ip/UdpSocket.h"

#define ADDRESS "127.0.0.1"
#define PORT 7000

#define OUTPUT_BUFFER_SIZE 1024

int main(int argc, char* argv[])
{
    UdpTransmitSocket transmitSocket( IpEndpointName( ADDRESS, PORT ) );

    char buffer[OUTPUT_BUFFER_SIZE];
    osc::OutboundPacketStream p( buffer, OUTPUT_BUFFER_SIZE );

    p << osc::BeginBundleImmediate
        << osc::BeginMessage( "/test1" )
        << true << 23 << (float)3.1415 << "hello" << osc::EndMessage
        << osc::BeginMessage( "/test2" )
        << true << 24 << (float)10.8 << "world" << osc::EndMessage
        << osc::EndBundle;

    transmitSocket.Send( p.Data(), p.Size() );
}

I have opened Visual C++ and created a new (CLR console application) project, called 'osctemp'. I copy the code from the 'SimpleSend.cpp' file and paste this into the main cpp file that is created for my project, keeping the following lines of code from the default project file:
#include "stdafx.h"

using namespace System;

I then navigate to the stdafx.h header file and notice that it contains at the bottom the line:
// TODO: reference additional headers your program requires here

...So I obediently move the includes and defines from my main cpp file to here.
I also notice that I need to add the includes to my project so in Windows Explorer I copy the folders 'osc' and 'ip' into my project folder.
Upon running, I receive the following errors:
1>------ Build started: Project: osctemp, Configuration: Debug Win32 ------

1>  stdafx.cpp

1>  AssemblyInfo.cpp

1>  osctemp.cpp

1>  Generating Code...

1>  .NETFramework,Version=v4.0.AssemblyAttributes.cpp

1>osctemp.obj : error LNK2028: unresolved token (0A00000A) "public: char const * __thiscall osc::OutboundPacketStream::Data(void)const " (?Data@OutboundPacketStream@osc@@$$FQBEPBDXZ) referenced in function "int __cdecl main(int,char * * const)" (?main@@$$HYAHHQAPAD@Z)

1>osctemp.obj : error LNK2028: unresolved token (0A00000B) "public: unsigned int __thiscall osc::OutboundPacketStream::Size(void)const " (?Size@OutboundPacketStream@osc@@$$FQBEIXZ) referenced in function "int __cdecl main(int,char * * const)" (?main@@$$HYAHHQAPAD@Z)

1>osctemp.obj : error LNK2028: unresolved token (0A00000C) "public: void __thiscall UdpSocket::Send(char const *,int)" (?Send@UdpSocket@@$$FQAEXPBDH@Z) referenced in function "int __cdecl main(int,char * * const)" (?main@@$$HYAHHQAPAD@Z)

...(And many more like this)...

1>D:\Temp\OSCTEMP\osctemp\Debug\osctemp.exe : fatal error LNK1120: 40 unresolved externals

What have I missed?

A: From your problem description I can't find anything about how you link towards the SDK libraries. Have you done so?
To link with the SDK libraries you need one or more .lib files. Even if the SDK is distributed as DLL you need a lib file for the build-time linkage. You should read through the SDK documentation and look for guidelines about link dependencies.
If you can't seem to find any lib-files in the SDK distribution it could very well be that you need to first build the SDK to produce a library and then link towards it. Alternatively, if the SDK comes with a ready VS project you can add it to your solution and set your own project to depend on it (i.e. VS does the work of finding the output lib and linking with it).
Again, if the SDK is of any descent standard, there should be docs about building the SDK yourself if that's necessary.
Good luck.

A: You're either not pulling in the correct library, or your prototype is not defining the library function correctly according to what's actually in it.


text:
Q: How to change the shape, colour and contour of an arrow in r? I'm trying to put a series of arrows on top of a dot plot. After hacking ggplot a bit, I got to put the arrows in place:
library(ggplot2)
library(grid)
N_seq <- rep(seq(1,50,by=1),2)
Y_seq <- rnorm(100)
Speci <- c(rep("Sample1",50),rep("Sample2",50))
Arrow_tail_x <- c(rep(0,20),rep(20,20),rep(30,10))
Arrow_head_x <- c(rep(20,20),rep(30,20),rep(50,10))
Arrow_tail_y <- c(rep(max(Y_seq)*0.25 + max(Y_seq),50))
Arrow_head_y <- c(rep(max(Y_seq)*0.25 + max(Y_seq),50))

data <- data.frame(N_seq,Y_seq,Speci,Arrow_tail_x,Arrow_tail_y,Arrow_head_x,Arrow_head_y)

p <- ggplot(data=data,aes(x=N_seq,y=Y_seq)) +
  theme_bw() + theme(panel.border = element_blank(), panel.grid.major=element_blank(), panel.grid.minor= element_blank(),axis.line=element_line(colour="black")) +
  ylim(min(Y_seq),max(Y_seq)*0.25 + max(Y_seq)) +
  scale_x_continuous(breaks=c(0,10,20,30,40,50),labels=c(0,100,200,300,400,500)) +
  geom_segment(aes(x=Arrow_tail_x,xend=Arrow_head_x,y=Arrow_head_y , yend=Arrow_tail_y),arrow = arrow(length=unit(20,"mm"),type='closed')) +
  geom_point(aes(color=Speci))

png("segment.png")
p
dev.off()

However, this code produces the standard black arrow with very narrow stalk. So far I have been unable to find how to change the arrows beyond using a different colour. How can I produce more stylish arrows? Does R has only one type of arrow? How can I control the width of the stalk? I want to get to something like this, but I haven't found any hint on how to do it:


text:
Q: javascript setting attributes in a for loop I've been developing an app and I've gotten the formatting to work using the following javascript:
$('td:eq(1)', nRow).attr('title', full_text);
$('td:eq(1)', nRow).css('cursor', 'pointer');
$('td:eq(2)', nRow).attr('title', full_text);
$('td:eq(2)', nRow).css('cursor', 'pointer');
$('td:eq(3)', nRow).attr('title', full_text);
$('td:eq(3)', nRow).css('cursor', 'pointer');
$('td:eq(4)', nRow).attr('title', full_text);
$('td:eq(4)', nRow).css('cursor', 'pointer');
$('td:eq(5)', nRow).attr('title', full_text);
$('td:eq(5)', nRow).css('cursor', 'pointer');
$('td:eq(6)', nRow).attr('title', full_text);
$('td:eq(6)', nRow).css('cursor', 'pointer');
$('td:eq(7)', nRow).attr('title', full_text);
$('td:eq(7)', nRow).css('cursor', 'pointer');
$('td:eq(8)', nRow).attr('title', full_text);
$('td:eq(8)', nRow).css('cursor', 'pointer');
$('td:eq(9)', nRow).attr('title', full_text);
$('td:eq(9)', nRow).css('cursor', 'pointer');
$('td:eq(10)', nRow).attr('title', full_text);
$('td:eq(10)', nRow).css('cursor', 'pointer');
$('td:eq(11)', nRow).attr('title', full_text);
$('td:eq(11)', nRow).css('cursor', 'pointer');
$('td:eq(12)', nRow).attr('title', full_text);
$('td:eq(12)', nRow).css('cursor', 'pointer');

I actually build this in R as I'm not an expert in javascript. The entire table to which this applies has a total of 250 columns so I generate a very large string and then use that in my app. How would I do it directly if the datatable has 250 columns?
Apologies if it's a simple question, I'm more of a statistician...
Here is full_text:
var full_text = 'ID: ' + aData[2] + '\\n' + 'NAME: ' +aData[4] + '\\n' + 'CRNCY: ' +aData[5] + '\\n' + 'Type: ' +aData[6] + '\\n' + 'Type2: ' +aData[7] + '\\n' + 'Sector: ' +aData[8] + '\\n' + 'Industry: ' +aData[9] + '\\n' + 'Security: ' +aData[10] + '\\n' + 'Stype2: ' +aData[11] + '\\n';

aData is a data.table that is made by my RShiny app.

A: Try this one
    var full_text = 'ID: ' + aData[2] + '\\n' + 'NAME: ' +aData[4] + '\\n' + 'CRNCY: ' +aData[5] + '\\n' + 'Type: ' +aData[6] + '\\n' + 'Type2: ' +aData[7] + '\\n' + 'Sector: ' +aData[8] + '\\n' + 'Industry: ' +aData[9] + '\\n' + 'Security: ' +aData[10] + '\\n' + 'Stype2: ' +aData[11] + '\\n';
    $('td').each(function(){
        $(this).css('cursor', 'pointer');
        $(this).attr('title', full_text);
    });

or, probably, $('td', nRow) will be better then $('td').
I work with jquery around 3 or 4 years ago, and I forgot couple of details. When I look into your code, I can see $('td:eq(3)', nRow). Most probably, second argument display context, where search should be applied. So,
   $('td')//will find all 'td' elements on page`
   $('td', nRow)//will find all td inside of nRow element

If you will have two or more tables on your webpage, search by $('td') will bring elements that should not appear inside of your script.