text:
Q: Angular and Go on heroku I am trying to put my app on Heroku. I am using angular on the front-end and Go on the backend.
I followed this tutorial http://mmcgrana.github.io/2012/09/getting-started-with-go-on-heroku.html
However, when I go to the domain of my heroku app, I get the directory of my app (everything in the git). When I navigate to the /app folder, (where my angular app lives) it shows the app.
I don't want my app to be at
foobar.herokuapp.com/app/#/

I want it to be at
foobar.herokuapp.com

A simplified version of my app directory is:
foobar
 - /app
 - /server/server.go
 - .godir             // contains "app"
 - Procfile           // contains "web: server"

I ran "go get" from inside my /server folder
These work:
$ PORT=5000 demoapp

$ curl -i http://127.0.0.1:5000/

Here is my simple server.go
package main

import (
"github.com/gorilla/handlers"
"log"
"net/http"
"os"
)

func main() {
log.Println("Starting Server")
http.Handle("/", logHandler(http.FileServer(http.Dir("../app/"))))

log.Println("Listening...")
panic(http.ListenAndServe(":"+os.Getenv("PORT"), nil))
}

func logHandler(h http.Handler) http.Handler {
return handlers.LoggingHandler(os.Stdout, h)

}

A: Changing your FileServer directory from "../app/" to "app/" (relative) or "/app/app/" (absolute) should solve the issue.
http.Handle("/", logHandler(http.FileServer(http.Dir("app/"))))

Your project root is the work folder when Heroku executes the Procfile command. It has the absolute path /app which is why ../app brings you back to your project root.
Although your server.go is stored in the ./server subfolder it is still compiled into the project root with package main.


text:
Q: Sparse matrix linear and nonlinear equation solver I am looking for a C library to solve linear and, if possible, nonlinear matrix equation of the form Ax = b. It is important to me, that the packages are not too big and free of charge. Speed does not matter as much as simplicity and the sparse feature of the matrix storage. Also, it should be able to parallelize the calculations. Since I am fairly new in the blas/lapack/... field of numerical linear algebra, it would be great if it contained a nice documentation, possibly with examples. Are there any packages you can recommend? I am a bit overwhelmed by the google results and also don't know the names of the routines I would have to look for.
I just found SuperLu which seems to have a very nice documentation, even with code snippets. It is written in C and requires CBLAS.

A: You have a lot of different options.  Before you start, you should consider some guidelines for choosing a sparse linear solver.  I personally recommend PETSc, but see this curated list over on scicomp for a more comprehensive list of options.

A: I'd recommend looking at CUDA if you have a NVIDIA graphics card.  It has nice linear algebra libraries using C-like syntax for BLAS and sparse matricies.

A: You might want to try PETSc. There's a bit of a learning curve, but this is a high-perf, highly capable library. Look at the Documentation section and especially the examples (big link at the top of each doc page).

A: I found this little program here, consisting only of a source file and one header, that can not only iteratively solve sparse matrix linear equations but also comes with a preconditioner that makes everything very efficient. There are two examples and the sparse structures are well documented. It depends on no external library and is very easy to integrate into existing code. It does not handle distributed memory, parallelization and so on.

redpajama_set_name: RedPajamaStackExchange


text:
Q: jQuery Template Plugin or custom functions? What I've got are chunks of code that are used over and over again in HTML. For example:

Here we have a simple row that I use in forms. Naturally, this chunk of code happens over and over, page after page. I'm essentially writing this out with jQuery for my dynamic content.
Now, I ran across jQuery Templates and thought for a moment that this was my solution. However, the fact that you have to declare your templates within a script block WITHIN your .htm page... not good. I want total separation.
So what I'm asking is: what is the best way to accomplish essentially the same thing as a template but with a custom function or class? Or is this even necessary?

A: You can have your templates as separate html files that are loaded asynchronously (which you can set cache headers on appropriately), here's how to do it.

A: You could try to apply my solution: http://github.com/mpapis/jquery-pure-templates
I'm also interested in extending it for other uses if you are interested.


text:
Q: Problems when using Entity Framework 6 and SQL Server 2016 I was using VS2015 with EntityFramework 6 for mapping my SQL Server 2012 database with database first method. Everything worked fine until upgrade the SQL Server to 2016 version.
Now, when I update my database model Visual Studio crash. The only way I can update my EDMX is using SQL2016 with compatibility mode to 2012 version. With compatibility mode the update works fine. Anyone knows if are there differences between SQL2012 and SQL2016 that may cause this problem?
Thanks,


text:
Q: Can I integrate Microsoft Lens into my application? I like Office Lens's ability to automatically crop, focus, and align a picture... mainly for receipt and expense processing
I want to have an app flow that goes like this:

*

*User opens my app and clicks photograph receipt

*Lens opens (android intent, or similar in iOS)

*User takes picture

*Picture is returned to my application for processing

I am having trouble making that flow happen, and to make the data transfer (photo) between the camera and my app seamless.  What options do I have?

A: If you look at Androidmanifest.xml file, you will see this XML:
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.microsoft.office.officelens" platformBuildVersionCode="21" platformBuildVersionName="5.0.1-1624448">
    <uses-permission android:name="android.permission.CAMERA" android:required="true"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.GET_ACCOUNTS"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS"/>
    <uses-permission android:name="android.permission.ACCESS_DOWNLOAD_MANAGER"/>
    <uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION"/>
    <uses-permission android:name="android.permission.READ_CONTACTS"/>
    <uses-permission android:name="android.permission.READ_PROFILE"/>
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
    <uses-permission android:name="android.permission.RECEIVE_SMS"/>
    <uses-feature android:name="android.hardware.camera" android:required="true"/>
    <uses-feature android:name="android.hardware.camera.autofocus" android:required="false"/>
    <application android:allowBackup="true" android:icon="@drawable/ic_officelens" android:label="@string/officelens_app_name" android:largeHeap="true" android:name="com.microsoft.office.officelens.OfficeLensApplication" android:theme="@style/OfficeLensAppTheme">
        <activity android:label="@string/officelens_app_name" android:name="com.microsoft.office.apphost.LaunchActivity" android:theme="@style/OfficeLensSplashTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <activity android:configChanges="orientation|screenSize" android:label="@string/officelens_app_name" android:launchMode="singleTask" android:name="com.microsoft.office.officelens.MainActivity" android:theme="@style/FullscreenTheme"/>
        <activity android:label="@string/officelens_app_name" android:name="com.microsoft.office.officelens.SecureActivity" android:parentActivityName="com.microsoft.office.officelens.MainActivity" android:windowSoftInputMode="stateHidden"/>
        <activity android:label="@string/title_activity_settings" android:name="com.microsoft.office.officelens.SettingsActivity" android:parentActivityName="com.microsoft.office.officelens.MainActivity"/>
        <activity android:configChanges="orientation|screenSize" android:label="" android:name="com.microsoft.office.officelens.AboutActivity" android:parentActivityName="com.microsoft.office.officelens.SettingsActivity"/>
        <activity android:label="" android:name="com.microsoft.office.officelens.FirstRunActivity" android:parentActivityName="com.microsoft.office.officelens.MainActivity" android:screenOrientation="portrait" android:theme="@style/OfficeLensFirstRunTheme"/>
        <activity android:label="@string/title_activity_section_picker" android:name="com.microsoft.onenote.pickerlib.OneNotePickerActivity" android:theme="@style/Theme.AppCompat.Light"/>
        <activity android:exported="false" android:icon="@drawable/ms_logo" android:label="@string/webflow_header" android:name="com.microsoft.onlineid.authenticator.AccountAddPendingActivity" android:theme="@style/Theme.MSA"/>
        <activity android:configChanges="orientation|screenSize" android:exported="false" android:icon="@drawable/ms_logo" android:label="@string/webflow_header" android:name="com.microsoft.onlineid.internal.ui.WebWizardActivity" android:theme="@style/Theme.MSA" android:windowSoftInputMode="adjustResize">
            <intent-filter>
                <action android:name="com.microsoft.onlineid.internal.SIGN_IN"/>
                <action android:name="com.microsoft.onlineid.internal.RESOLVE_INTERRUPT"/>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
        </activity>
        <activity android:configChanges="orientation|screenSize" android:exported="false" android:icon="@drawable/ms_logo" android:label="@string/webflow_header" android:name="com.microsoft.onlineid.ui.AddAccountActivity" android:theme="@style/Theme.MSA" android:windowSoftInputMode="adjustResize">
            <intent-filter>
                <action android:name="com.microsoft.onlineid.internal.ADD_ACCOUNT"/>
                <action android:name="com.microsoft.onlineid.internal.SIGN_UP_ACCOUNT"/>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
        </activity>
        <activity android:configChanges="orientation|screenSize" android:exported="false" android:name="com.microsoft.onlineid.ui.SignOutActivity" android:theme="@style/Theme.MSA.Transparent"/>
        <activity android:exported="false" android:icon="@drawable/ms_logo" android:label="@string/webflow_header" android:name="com.microsoft.onlineid.internal.ui.AccountPickerActivity" android:theme="@style/Theme.MSA.Dialog">
            <intent-filter>
                <action android:name="com.microsoft.onlineid.internal.PICK_ACCOUNT"/>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
        </activity>
        <service android:exported="false" android:name="com.microsoft.onlineid.internal.MsaService">
            <intent-filter>
                <action android:name="com.microsoft.onlineid.internal.GET_TICKET"/>
                <action android:name="com.microsoft.onlineid.internal.UPDATE_PROFILE"/>
                <action android:name="com.microsoft.onlineid.internal.SIGN_OUT"/>
                <action android:name="com.microsoft.onlineid.internal.SIGN_OUT_ALL_APPS"/>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
        </service>
        <service android:enabled="true" android:exported="false" android:name="com.microsoft.onlineid.sso.service.MsaSsoService">
            <intent-filter>
                <action android:name="com.microsoft.msa.action.SSO_SERVICE"/>
            </intent-filter>
            <meta-data android:name="com.microsoft.msa.service.sso_version" android:value="1"/>
            <meta-data android:name="com.microsoft.msa.service.sdk_version" android:value="@string/sdk_version_name"/>
        </service>
    </application>
    <uses-permission android:name="com.android.vending.CHECK_LICENSE"/>
    <uses-permission android:name="android.permission.MANAGE_ACCOUNTS"/>
    <uses-permission android:name="android.permission.USE_CREDENTIALS"/>
    <uses-feature android:name="android.hardware.telephony" android:required="false"/>
</manifest>

If you read this file carefully you will see that this is impossible to interact this the other API's. Neither 'broadcast' no proper 'intent-filter' to interact this the other applications.
This is impossible nowadays.
Anyway, obviously, you can save to local storage and retrieve the data from SD card using your app.


text:
Q: Conditional dependency ignored in mobile In the midst of building a site, we've run into a conflict between VideoJS and Angular, such that Angular modules won't load in iOS7 when the VideoJS library is present. This is one hell of an edge case, and page content is much more important than a peripheral video, so we're opting to just nix VideoJS for our mobile users and use an image fallback.
Now, consider this relevant code excerpt from a requirejs module:
log("checkpoint 1");

var videojs, $ = require('jquery');

if($(".home").length && $(window).outerWidth() > 768){
    log("checkpoint 2a");
    videojs = require('videojs');
    log("checkpoint 2b");

    // video init code here
}

log("checkpoint 3");

In any mobile device, the log returns:
> checkpoint 1
> checkpoint 3

which indicates that the loop isn't penetrated in mobile, as expected. However, contrary to this, the videojs library is still being loaded - which defeats the whole purpose of conditionally including it.
We've confirmed that this is the only place the videojs library is being included, as the problem disappears when videojs = require('videojs'); is commented out - the library does not appear in the resources list, and the page renders normally.
Are we just setting up the conditional dependency poorly? Is there another way we can execute this, or are we stuck firmly in a known limitation of Require?

A: videojs = require('videojs')

I'll bet this is a line in a source (non-compiled file) that you then compile with browserify (or something similar before you release your app).
The problem is, of course, that your compiled files will ALWAYS require videojs (unless the line is commented out) because your conditional is based on determinants only available at run-time, not compile-time.
So, to answer your question:

Are we just setting up the conditional dependency poorly?

yes.
There are probably a bunch of ways to do this, but one that comes to my mind is to serve the videojs library as a separate asset. You'd use (ugh) User Agent parsing to determine if the device is running iOS7 something like the following (PHP example):
<?php if(!is_ios7()) { //pseudo code - UA parsing in here. ?>
 <script src="/path/to/videojs"></script>
<?php } ?>

And then in your main js file you can just detect if the videojs globals are present and then use it if required.

A: for production and test ENV and for mobile/desktop vertion use can use this loader:(from this git hub project https://github.com/BoilerplateMVC/Marionette-Require-Boilerplate/blob/master/public/index.html )
    // Mobile/Desktop Detection script
            (function(ua, w, d, undefined) {
                // App Environment
                // ---------------
                //  Tip: Set to true to turn on "production" mode
                var production = true,
                        filesToLoad,
                //BoilerplateMVC Helper Methods
                        boilerplateMVC = {
                            loadCSS: function(url, callback) {
                                var link = d.createElement("link");
                                link.type = "text/css";
                                link.rel = "stylesheet";
                                link.href = url;
                                d.getElementsByTagName("head")[0].appendChild(link);
                                if(callback) {
                                    callback();
                                }
                            },
                            loadJS: function(file, callback) {
                                var script = d.createElement("script");
                                script.type = "text/javascript";
                                if (script.readyState) {  // IE
                                    script.onreadystatechange = function() {
                                        if (script.readyState == "loaded"
 || script.readyState == "complete") {
                                            script.onreadystatechange = null;
                                            callback();
                                        }
                                    };
                                } else {  // Other Browsers
                                    script.onload = function() {
                                        callback();
                                    };
                                }
                                if(((typeof file).toLowerCase()) === "object"
 && file["data-main"] !== undefined) {
                                    script.setAttribute("data-main",
file["data-main"]);
                                    script.async = true;
                                    script.src = file.src;
                                } else {
                                    script.src = file;
                                }
                                d.getElementsByTagName("head")[0].appendChild(script);
                            },
                            loadFiles: function(production, obj, callback) {
                                var self = this;
                                if(production) {
                                    // Loads the production CSS file(s)
                                    self.loadCSS(obj["prod-css"], function() {
                                        // If there are production JavaScript files to load
                                        if(obj["prod-js"]) {
                                            // Loads the correct initialization file (which includes Almond.js)
                                            self.loadJS(obj["prod-js"], callback);
                                        }
                                    });
                                } else {
                                    // Loads the development CSS file(s)
                                    self.loadCSS(obj["dev-css"], function() {
                                        // If there are development Javascript files to load
                                        if(obj["dev-js"]) {
                                            // Loads Require.js and tells Require.js to find the correct intialization file
                                            self.loadJS(obj["dev-js"], callback);
                                        }
                                    });
                                }
                            }
                        };
                // Mobile/Tablet Logic
                if((/iPhone|iPod|iPad|Android|BlackBerry|Opera Mini|IEMobile/).test(ua)) {
                    // Mobile/Tablet CSS and JavaScript files to load
                    filesToLoad = {
                        // CSS file that is loaded when in development mode
                        "dev-css": "css/mobile.css",
                        // CSS file that is loaded when in production mode
                        "prod-css": "css/mobile.min.css",
                        // Require.js configuration file that is loaded when in development mode
                        "dev-js": { "data-main": "js/app/config/config.js", "src": "js/libs/require.js" },
                        // JavaScript initialization file that is also loaded when in development mode
                        "dev-init": "js/app/init/MobileInit.js",
                        // JavaScript file that is loaded when in production mode
                        "prod-init": "js/app/init/MobileInit.min.js",
                        "prod-js": { "data-main": "js/app/config/config.js", "src": "js/libs/require.js" }
                    };
                }
                // Desktop Logic
                else {
                    // Desktop CSS and JavaScript files to load
                    filesToLoad = {
                        // CSS file that is loaded when in development mode
                        "dev-css": "css/desktop.css",
                        // CSS file that is loaded when in production mode
                        "prod-css": "css/desktop.min.css",
                        // Require.js configuration file that is also loaded when in development mode
                        "dev-js": { "data-main": "js/app/config/config.js", "src": "js/libs/require.js" },
                        // JavaScript initialization file that is loaded when in development mode
                        "dev-init": "js/app/init/DesktopInit.js",
                        // JavaScript file that is loaded when in production mode
                        "prod-init": "js/app/init/DesktopInit.min.js",
                        "prod-js": { "data-main": "js/app/config/config.js", "src": "js/libs/require.js" }
                    };
                }
                boilerplateMVC.loadFiles(production, filesToLoad, function() {
                    if(!production && window.require) {
                        require([filesToLoad["dev-init"]]);
                    } else if ( production ) {
                        require([filesToLoad["prod-init"]])
                    }
                });
            })(navigator.userAgent || navigator.vendor || window.opera, window, document);

and onother logic in this project :
    var App = new Backbone.Marionette.Application();

    function isMobile() {
        var userAgent = navigator.userAgent || navigator.vendor || window.opera;
        return ((/iPhone|iPod|iPad|Android|BlackBerry|Opera Mini|IEMobile/).test(userAgent));
    }

    App.mobile = isMobile();

require(["App", "jquery", "routers/AppRouter", "controllers/MobileController", "backbone", "marionette", "jquerymobile", "backbone.validateAll"],
    function (App, $, AppRouter, AppController) {
        // Prevents all anchor click handling
        $.mobile.linkBindingEnabled = false;
        // Disabling this will prevent jQuery Mobile from handling hash changes
        $.mobile.hashListeningEnabled = false;

        App.appRouter = new AppRouter({
            controller:new AppController()
        });

        App.start();
    });


text:
Q: Why do I get the error: Cannot run 'uic': "execvp: No such file or directory" for a PySide2 program under macOS Catalina? I want to execute a program which was written in python using PyQt5 and then migrated to PySide2 under MacOS Catalina.
With PyQt5 it was executing fine.
I have installed PySide2 like PyQt5:
python3 -m pip install PyQt5
python3 -m pip install PySide2

macOS was restarted afterwards.
Now, with PySide2 installed, I am getting an error in macOS when I am trying to load an Ui-file.
MRE which works under Linux, Windows and macOS Catalina:
#!/usr/bin/env python3

# Standard library imports
import sys

# Third party imports
from PySide2.QtCore import (QMetaObject,
                            Slot)
from PySide2.QtWidgets import (QApplication,
                               QWidget,
                               QPushButton,
                               QHBoxLayout,
                               QMessageBox)

def show_about():
    msg = QMessageBox()

    msg.setText("About this app.")
    msg.setStandardButtons(QMessageBox.Ok)

    msg.exec_()

class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        aboutButton = QPushButton("About")
        aboutButton.setObjectName("aboutButton")

        hbox = QHBoxLayout()
        hbox.addStretch(1)
        hbox.addWidget(aboutButton)

        self.setLayout(hbox)

        QMetaObject.connectSlotsByName(self)

        self.setWindowTitle('Buttons')

    @Slot()
    def on_aboutButton_clicked(self):
        show_about()

def main():
    app = QApplication(sys.argv)
    win = MainWindow()
    win.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

MRE which fails under macOS Catalina, but works in Linux and Windows:
#!/usr/bin/env python3

# Standard library imports
import sys

# Third party imports
from PySide2.QtWidgets import (QApplication,
                               QMainWindow)

from PySide2.QtUiTools import loadUiType

class MainWindow(QMainWindow, loadUiType("win_main.ui")[0]):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

def main():
    app = QApplication(sys.argv)
    win = MainWindow()
    win.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

Error:
Python 3.8.5 (/usr/local/bin/python3)
>>> %Run pyside2_win_main.py
Cannot run 'uic':  "execvp: No such file or directory"  -  Exit status  QProcess::NormalExit  ( 255 )
 Check if 'uic' is in PATH
Traceback (most recent call last):
  File "/Users/dee/ownCloud3/rma2/pyside2_win_main.py", line 12, in <module>
    class MainWindow(QMainWindow, loadUiType("win_main.ui")[0]):
TypeError: 'NoneType' object is not subscriptable

File structure for simplicity of test case:
/Users/dee/ownCloud3/rma2/pyside2_win_main.py
/Users/dee/ownCloud3/rma2/win_main.ui

PySide2 version 15.5.0, shiboken2==5.15.0.
macOS Calatina v10.15.06
Python 3.8.5 64bit (downloaded from here, no HomeBrew etc.

A: Don't use relative paths as they are susceptible to errors as it will depend on how the script is run, instead build an absolute path:
import os.path

CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
ui_file_path = os.path.join(CURRENT_DIR, "win_main.ui")

Ui_Class, _ = loadUiType(ui_file_path)

class MainWindow(QMainWindow, Ui_Class):
    # ...

Also add at the top of your file, since it seems that when python was installed, the option to add the necessary paths to the environment variables was not marked:
import PySide2
import os.path

uic_dir = os.path.dirname(PySide2.__file__)
os.environ["PATH"] += os.pathsep + uic_dir


text:
Q: Prove a summation equals to $n^n$ How to prove that $$\sum_{k=1}^n k \frac{(n-1)!}{(n-k)!} n^{n-k} = n^n$$
I have tried induction but changing from $n$ to $(n+1)$ even further complicate the formula and no way to extract the case $n$ for substitution as $n^n$.  I also considered the binomial expansion of $(z+n)^n$ and differentiate it to obtain the $k$ in the summation.  But I can't eliminate the $1/k!$ at the denominator so as to match the original RHS.


text:
Q: ansible, stop a service on all host that belongs to a group I writing an ansible role. I would like to stop a services on all host that belongs to a group.
How to manage this usecase with ansible?

A: Ansible Playbook will have scope for host group.
---
- hosts: host_group_name

Ansible role will have task for stopping service.
- name: stop service on host_group
  become: yes
    name: service_name
    state: stopped

Ansible adhoc command:
ansible host_group_name -i inventory -a "service service_name stop"

A: Use a when condition something like below.
    when: inventory_hostname in  groups['groupname']


text:
Q: Efficient use of conditional statements over dictionary in python I want to check in what combination do these values exist and one condition is that hashtag can not exit alone so the combination is 4C1 + 5C2 + 5C3 + 5C4 + 5C5 that makes up these conditional statements.
I want to know whether there is a more efficient way of doing this by using dictionary methods in python.
My Dictionary
data = { 'all_words': '', 'exact_phrase': '', 'any_words': '', 'not_words': '', 'hashtag': ''}

My conditional statements
        if data['all_words'] is not None and (data['any_words'], data['exact_phrase'], data['not_words'], data['hashtag'] is None):
            c.Search = data['all_words']
        elif data['any_words'] is not None and (data['all_words'], data['exact_phrase'], data['not_words'], data['hashtag'] is None):
            c.Search = data['any_words']
        elif data['exact_phrase'] is not None and (data['all_words'], data['any_words'], data['not_words'], data['hashtag'] is None):
            c.Search = data['exact_phrase']
        elif data['hashtag'] is not None and (data['all_words'], data['any_words'], data['not_words'], data['exact_phrase'] is None):
            c.Search = data['hashtag']

        elif (data['all_words'], data['any_words'] is not None) and (data['exact_phrase'], data['not_words'], data['hashtag'] is None):
            c.Search = data['all_words'] + " " + data['any_words']
        elif (data['all_words'], data['exact_phrase'] is not None) and (data['any_words'], data['not_words'], data['hashtag'] is None):
            c.Search = data['all_words'] + " " + data['exact_phrase']
        elif (data['all_words'], data['not_words'] is not None) and (data['any_words'], data['exact_phrase'], data['hashtag'] is None):
            c.Search = data['all_words'] + " " + data['not_words']
        elif (data['all_words'], data['hashtag'] is not None) and (data['any_words'], data['exact_phrase'], data['not_words'] is None):
            c.Search = data['all_words'] + " " + data['hashtag']
        elif (data['any_words'], data['exact_phrase'] is not None) and (data['all_words'], data['hashtag'], data['not_words'] is None):
            c.Search = data['exact_phrase'] + " " + data['any_words']
        elif (data['any_words'], data['hashtag'] is not None) and (data['all_words'], data['exact_phrase'], data['not_words'] is None):
            c.Search = data['any_words'] + " " + data['hashtag']
        elif (data['any_words'], data['not_words'] is not None) and (data['all_words'], data['exact_phrase'], data['hashtag'] is None):
            c.Search = data['any_words'] + " " + data['not_words']
        elif (data['exact_phrase'], data['hashtag'] is not None) and (data['all_words'], data['any_words'], data['not_words'] is None):
            c.Search = data['exact_phrase'] + " " + data['hashtag']
        elif (data['exact_phrase'], data['not_words'] is not None) and (data['all_words'], data['any_words'], data['hashtag'] is None):
            c.Search = data['exact_phrase'] + " " + data['not_words']
        elif (data['not_words'], data['hashtag'] is not None) and (data['all_words'], data['any_words'], data['exact_phrase'] is None):
            c.Search = data['not_words'] + " " + data['hashtag']

        elif (data['all_words'], data['any_words'], data['exact_phrase'] is not None) and (data['hashtag'], data['not_words'] is None):
            c.Search = data['all_words'] + " " + data['exact_phrase'] + " " + data['any_words']
        elif (data['all_words'], data['any_words'], data['not_words'] is not None) and (data['hashtag'], data['exact_phrase'] is None):
            c.Search = data['all_words'] + " " + data['any_words'] + " " + data['not_words']
        elif (data['all_words'], data['any_words'], data['hashtag'] is not None) and (data['not_words'], data['exact_phrase'] is None):
            c.Search = data['all_words'] + " " + data['any_words'] + " " + data['hashtag']
        elif (data['all_words'], data['exact_phrase'], data['not_words'] is not None) and (data['any_words'], data['hashtag'] is None):
            c.Search = data['all_words'] + " " + data['exact_phrase'] + " " + data['not_words']
        elif (data['all_words'], data['exact_phrase'], data['hashtag'] is not None) and (data['any_words'], data['not_words'] is None):
            c.Search = data['all_words'] + " " + data['exact_phrase'] + " " + data['hashtag']
        elif (data['all_words'], data['not_words'], data['hashtag'] is not None) and (data['any_words'], data['not_words'] is None):
            c.Search = data['all_words'] + " " + data['not_words'] + " " + data['hashtag']
        elif (data['exact_phrase'], data['any_words'], data['not_words'] is not None) and (data['hashtag'], data['all_words'] is None):
            c.Search = data['exact_phrase'] + " " + data['any_words'] + " " + data['not_words']
        elif (data['exact_phrase'], data['any_words'], data['hashtag'] is not None) and (data['not_words'], data['all_words'] is None):
            c.Search = data['exact_phrase'] + " " + data['any_words'] + " " + data['hashtag']
        elif (data['any_words'], data['not_words'], data['hashtag'] is not None) and (data['all_words'], data['exact_phrase'] is None):
            c.Search = data['any_words'] + " " + data['not_words'] + " " + data['hashtag']
        elif (data['exact_phrase'], data['not_words'], data['hashtag'] is not None) and (data['all_words'], data['any_words'] is None):
            c.Search = data['exact_phrase'] + " " + data['not_words'] + " " + data['hashtag']

        elif (data['all_words'], data['exact_phrase'], data['any_words'], data['not_words'] is not None) and (data['hashtag'] is None):
            c.Search = data['all_words'] + " " + data['exact_phrase'] + " " + data['any_words'] + " " + data['not_words']
        elif (data['all_words'], data['exact_phrase'], data['any_words'], data['hashtag'] is not None) and (data['not_words'] is None):
            c.Search = data['all_words'] + " " + data['exact_phrase'] + " " + data['any_words'] + " " + data['hashtag']
        elif (data['all_words'], data['any_words'], data['not_words'], data['hashtag'] is not None) and (data['exact_phrase'] is None):
            c.Search = data['all_words'] + " " + data['any_words'] + " " + data['not_words'] + " " + data['hashtag']
        elif (data['all_words'], data['exact_phrase'], data['not_words'], data['hashtag'] is not None) and (data['any_words'] is None):
            c.Search = data['all_words'] + " " + data['exact_phrase'] + " " + data['not_words'] + " " + data['hashtag']
        elif (data['exact_phrase'], data['any_words'], data['not_words'], data['hashtag'] is not None) and (data['all_words'] is None):
            c.Search = data['exact_phrase'] + " " + data['any_words'] + " " + data['not_words'] + " " + data['hashtag']

        elif (data['all_words'], data['exact_phrase'], data['any_words'], data['not_words'], data['hashtag']) is not None:
            c.Search = data['all_words'] + " " + data['exact_phrase'] + " " + data['any_words'] + " " + data['not_words'] + " " + data['hashtag']

A: First of all, you should learn to use variables to reduce repetition in code.
Also, go see the basic of python dict python dict
I try the rewrite your code tell if that you want the program to execute
def not_none_dict(d):
    new_d = {}
    for k, v in d.items():
        if d[k] is not None or d[k] == '':
            new_d[k] = d[k]
    return new_d

def format_dict(d):
    all_words = new_data.get('all_words', '')
    exact_phrase = new_data.get('exact_phrase', '')
    any_words = new_data.get('any_words', '')
    not_words = new_data.get('not_words', '')
    hashtag = new_data.get('hashtag', '')
    Search = '{}{}{}{}{}'.format(all_words, exact_phrase, any_words, not_words, hashtag)
    print(Search)
    Search = ' '.join(Search)
    return Search

data = {'all_words': '1', 'exact_phrase': '2', 'any_words': None, 'not_words': '4', 'hashtag': None}
new_data = not_none_dict(data)
print(new_data)

if len(new_data) == 0 or new_data is None:
    Search = 'error'
elif len(new_data) == 1:
    Search = list(new_data.values())[0]
elif len(new_data) == len(data):
    Search = format_dict(new_data)
else:
    Search = format_dict(new_data)

print (Search)


text:
Q: Triggering Intent using event in dialogflow I am trying to create a quiz-bot, in which I wish to verify the users answers. I have created an intent to show questions and then a follow up intent to verify answers. Following is the brief idea:
When the user is shown the question, he/she is also shown the one word options as suggestion tiles, the user selects the suggestion tile (which he/she thinks is a correct answer), then the follow up intent should be triggered to verify the answer and the bot should respond as correct or incorrect answer.
As of now, I am able to show the question and options in the chat box, but as soon as the user selects the option, default fallback intent is triggered.
Also I have included all the answers in the intent's training and these answers are of one word length.
Is there a way to trigger intent using user's input? Also if there is any other approach to create quiz-bot in dialogflow, please do comment?

A: I have also created a quiz on Google home.
The same problem occurred to me and I came up with the following solution:
The Default Welcome Intent has an output context of await_answer and I ask the question in this intent.
Then there is the getAnswerIntent that has the await_answer as input context and has the answerCodeEntity as trainingsphrase. This entity consists of:
A: 1, A, answer 1, answer A, first, first one, the first one
B: 2, 2nd answer, second answer, answer B, B, ...
C: ...
D: ...

E.g.: How far away is the moon from the earth?
A: 384.000km
B: 50.000km
or C: 1.000.000 km
This way users know how to answer. You will avoid having users that can't say the answer or just don't remember. Always try to expect how a user will respond.
This way you can handle the user's answer in the getAnswerIntent.
I hope this helps you!


text:
Q: Using Yahoo Finance API to obtain the stock price at a particluar time? I am developing Stock tracking software in Python. I am able to obtain the price of a given stock on a current day. Given a stock, I am able to obtain the real time price of that stock.
For analysis purpose, I am trying to obtain the price of a given stock on a particular day.
For example, is it possible that I can obtain the stock price of Apple (AAPL) on May 5th, 2015 at 11.30AM ?
I can get the data from Yahoo finance through the interactive chart tool : http://finance.yahoo.com/echarts?s=AAPL+Interactive#{"allowChartStacking":true}
I was wondering, if we have the API to do the same.
Thanks

A: The short answer with a quick google result is yes here. While you can use this API, Chris reeves go through datamining specifically the stock exchange in his tutorial here. What I prefer to use is (scrapy)[http://scrapy.org/]. There are other options including but not limited to BeautifulSoup4 and urllib. Each has its own strengths and weaknesses but I prefer Scrapy as I use it the most.


text:
Q: Excel rebooting while copying sheets from multiple books I built a program to copy sheet one from all books in a directory, and paste them into the active workbook. I have roughly 1200 books in the directory, and without fail each time I run it excel reboots after around #125. No error messages. Anyway of getting around this?
Sub GetSheets()
Path = "C:\Users\bdaly\Desktop\Formulas\smaller sample\"
Dim DestWB As Workbook

Set DestWB = ThisWorkbook

Filename = Dir(Path & "*.xls")
  Do While Filename <> ""
  Workbooks.Open Filename:=Path & Filename, ReadOnly:=True

     Sheets("Sheet1").Copy After:=DestWB.Sheets(DestWB.Sheets.Count)
     Application.DisplayAlerts = False
     Workbooks(Filename).Close
    Application.DisplayAlerts = True

     Filename = Left(Left(Filename, Len(Filename) - 4), 31)
     DestWB.Sheets(DestWB.Sheets.Count).Name = Filename
     Filename = Dir()
  Loop
End Sub

Edit: As advised I removed the offending file, Excel still reboots after 124 loops.

A: Not sure if this is going to address the problem at hand, but it will help in debugging or exposing the problem.
Put simply, qualify your source data.

*

*Include Dim SourceWB as Workbook. This could be done where you declare DestWB.

*Change Workbooks.Open Filename:=Path & Filename, ReadOnly:=True to Set SourceWB = Workbooks.Open(Filename:=Path & Filename, ReadOnly:=True, Editable:=True)

*Change Sheets("Sheet1").Copy After:=DestWB.Sheets(DestWB.Sheets.Count) to SourceWB.Sheets("Sheet1").Copy After:=DestWB.Sheets(DestWB.Sheets.Count)

*Change Workbooks(Filename).Close to SourceWB.Close
Unfortunately, the .Copy command is a Sub, not a Function - would be so much more neater if it provided a reference to the sheet that has just been created as you could then use it in DestWB.Sheets(DestWB.Sheets.Count).Name = Filename
I suggest, for debugging purposes, keeping the DisplayAlerts on for now. This may provide a clue as to where the fault is happening.
Also include some debug.print lines in your loop. Finding where in the loop it crashes could help diagnose the issue. Make them a little descriptive, the ones I would think of are:
debug.print "Entered loop"
debug.print "Copied file"
debug.print "renamed file"
'debug.print "new FileName is " & FileName`.
You get the idea.

A: Try the AddIn from the link below.

https://www.rondebruin.nl/win/addins/rdbmerge.htm


text:
Q: I cannot send PUT data with html form I have a form created in HTML
<form th:action="@{/forgotPassword}" th:object="${forgotPasswordDTO}" method="POST" role="form" id="forgotPasswordForm">
    <input type="hidden" name="_method" value="PUT"/>
...

and I want to send data to the controller
    @PutMapping("/forgotPassword")
    public ModelAndView recoverPassword(
            @ModelAttribute("forgotPasswordDTO") @Valid ForgotPasswordDTO forgotPasswordDTO,
            BindingResult result,
            ModelMap modelMap
    ) {
...

but BindingResult still returns errors to me because the fields of the @ModelAttribute object are null.
Can I send a PUT query using html form?

A: If you are using Spring Boot 1.5.6 then I did notice the Thymeleaf th:method="put", which you are emulating, seems to be broken. Replacing with th:method="post" and changing the controller method to a @PostMethod results in the form begin populated and validated correctly. Reverting back to version 1.5.4 corrected the problem for me. The same filters are being applied in both versions but the 1.5.6 version results in an empty form in the controller. I have checked two of my projects and they exhibit the same behavior.


text:
Q: A Hidden Markov model with covariates in the transition probabilities I would like to construct a Hidden Markov model with data about online customer journeys. A well-known concept related to the customer journey literature is the sales funnel. Consumers walk through the funnel and the probability to purchase increases while becoming more engaged. The latent variables from the Hidden Markov model are the following states: disengaged > active > engaged > conversion.
The data can roughly be divided into three parts:

*

*Observed behavior from the consumer while preparing for making a purchase, for example, different types of websites viewed, google search etc.

*Whether the consumer makes a purchase at the end of his/her customer journey

*Various kinds of ads

I was thinking about a multivariate HMM with observed behavior (1) and whether he or she converts (2) as output variables. Moreover, I would like to add the various kinds of ads (3) as covariates in the transition probabilities, however, I find it difficult to understand/interpret those covariates.
Can anyone explain how to incorporate covariates in the transition probabilities and how to interpret the covariates?


text:
Q: Is this an acceptable use case of the ternary operator? I was using the ternary operator to perform a very simple, conditional action. It worked well, but my IDE (PHPStorm) reported it as an error. The error I got was:
'void' method 'performAction' result used
The code I was using is this:
($this->doThis ? $class->performAction() : $class->performDifferentAction());

The error in PHPStorm is obviously wrong; I'm not using the result of the void method anywhere. I'm just calling the methods and that works as expected. I just used the ternary operator as a short-hand for this:
if($this->doThis)
{
    $class->performAction();
}
else
{
    $class->performDifferentAction();
}

I think this looks like a valid use case for the ternary operator. It's not obfuscated, easy to read and short.
Is this a design flaw nevertheless?

A: The ternary operator is an expression which returns a result. Its purpose is to be used when an "inline condition" is needed which would otherwise require you to create one or two additional variables. As such, whenever you use a ternary operator, you're kind of expected to use its result.
For example, you wouldn't write this, would you?
1 + 2;  // result not used, does nothing

What you're essentially doing there is write such code, but add a side effect to it:
1 + someFunc();  // soooo... does this do anything?

Your IDE therefore urges you to explicitly write side-effect code using if..else. It more directly expresses what you're doing there.
Having said all that, it's ultimately up to you and your style. PhpStorm has its preferences; if you want to override them, switch off that particular inspection. However, that inspection is there to help you write better code; it would warn you if you really forgot to assign a return value somewhere.


text:
Q: Unable to upload taiwind CSS in React project I am trying to use Tailwind CSS in the react project. I followed the steps given in the documentation from here. But after completing all the steps, I am unable to see the tailwind CSS changes.
I am adding the styles in the file Home.js like this,
import React from "react";
    .
    .
    .

  return (
    <>

      Hello world!

    </>
  );
};

export default Home;

But it is not showing anything

Following are the required files:
package.json
{
  "name": "authlogin-boilerplate",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.11.4",
    "@testing-library/react": "^11.1.0",
    "@testing-library/user-event": "^12.1.10",
    "express": "^4.17.1",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-router-dom": "^6.1.1",
    "react-scripts": "4.0.3",
    "web-vitals": "^1.0.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "autoprefixer": "^10.4.2",
    "postcss": "^8.4.5",
    "tailwindcss": "^3.0.11"
  }
}

tailwind.config.js
module.exports = {
  content: [
    "./src/**/*.{js,jsx,ts,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

App.js
import { useState } from "react";
import "./App.css";
import "./index.css";
import Navbar from "./components/Navbar";
import Home from "./components/Home";
import About from "./components/About";
import SignupPage from "./components/SignupPage";
import LoginPage from "./components/LoginPage";
import ForgotPasswordPage from "./components/ForgotPasswordPage";
import ChangePasswordPage from "./components/ChangePasswordPage";
import Alert from "./components/Alert";

import { BrowserRouter as Router, Routes, Route } from "react-router-dom";

function App() {
  const [alert, setAlert] = useState(null);

  const showAlert = (message, type) => {
    setAlert({ msg: message, type: type });
    setTimeout(() => setAlert(null), 1500);
  };

  return (
    <>
      <Router>
        <Navbar showAlert={showAlert} />
        <Alert alert={alert} />
        <Routes>
          <Route path="/" element={<Home showAlert={showAlert} />} />
         .
         .
      </Router>
    </>
  );
}

export default App;

index.css
@tailwind base;
@tailwind components;
@tailwind utilities;

Also, my project structure is

On thing I noticed that in my index.css, I am getting this warning

I don't know the reason, I have restarted the laptop twice but not working.

A: This is not working because you haven't added the CRACO layer to your React app. Your setup is fine, but something is still to be added, you just need to run npm install @craco/craco inside your react app root and change your package.json file with the new value of start, build and eject command as shown below in the image, and finally start your server again this will work.


text:
Q: Compare a character of a string with another character of a string I was given a task to write a simple post-fix to infix program.
The idea is that a user gives me an expression, say:

userInput = "(2)1+5*(2-1)"

I was planning to use another string to define my character priority through the index of said character, say:

charPrio= "()-+/*^)"

My idea was to iterate through the userInput with a for loop and then make the necessary comparisons on the charPrio using the character positions.
Something more or less like:
for (int i =0 ; i < userInput.length(); i++) {
      if (userInput[i]==charPrio[0]){
             //do something
      }
}

When using the if I get problems when doing the comparison, for the iteration 0 I get that userInput[0] = ""
Ideally, I would want to enter the if in this iteration given the userInput above.
But it doesn't, to my understanding indexes in c++ start at 0 so I believe that I am doing a comparison of userInput[0] == charPrio[0] which should be "("=="(".
Honestly, I'm not quite sure if I am using the strings correctly, or if there is a better way to do this.
I tried using constants for the comparison:
if (userInput[i]== "(" )

but I get an error saying I can't use different data types (operand types are incompatible (char and const char))
Is there a better way to compare characters of a string, or am I using the indexes wrong?


text:
Q: Different Results for Same SELECT Query When Executing on phpmyadmin and SQL Fiddle I wrote a query to fetch latest tax of all countries in a MySQL Table. Same Query Executed in phpmyadmin(localhost) and SQL Fiddle. Both results are different. But SQL Fiddle Producing the Correct Result.
I Could able to find same question Posted on Stack Overflow Earlier at this Link
I didn't get any help from the post. My Issue is how get the correct result on phpmyadmin(localhost) for the SELECT Query I wrote below; is there any problem with my SELECT Query?
Select Query: (Which I Executed on Both Phpmyadmin and SQL Fiddle)
SELECT
  t1.id, t1.country,
  t1.tax, t1.created_by,
  t1.created_on, t1.modified_by, t1.modified_on
FROM tax t1
INNER JOIN
(
   SELECT country, MAX(created_on) AS latest
   FROM tax GROUP BY country
) t4 ON t1.created_on=t4.latest AND t1.country=t4.country;

Table
+-------------+--------------+------+-----+-------------------+-----------------
------------+

| Field       | Type         | Null | Key | Default           | Extra
            |

+-------------+--------------+------+-----+-------------------+-----------------
------------+

| id          | int(11)      | NO   | PRI | NULL              | auto_increment
            |

| country     | int(11)      | NO   |     | NULL              |
            |

| tax         | decimal(8,5) | NO   |     | NULL              |
            |

| created_by  | int(11)      | NO   |     | NULL              |
            |

| created_on  | timestamp    | NO   |     | CURRENT_TIMESTAMP |
            |

| modified_by | int(11)      | YES  |     | NULL              |
            |

| modified_on | timestamp    | YES  |     | NULL              | on update CURREN
T_TIMESTAMP |

+-------------+--------------+------+-----+-------------------+-----------------
------------+

Create Table Query: (Which I tried in SQL Fiddle)
CREATE TABLE tax ( id int(11) NOT NULL AUTO_INCREMENT, country int(11) NOT NULL, tax decimal(8,5) NOT NULL, created_by int(11) NOT NULL, created_on timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, modified_by int(11) DEFAULT NULL, modified_on timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (id) );

INSERT INTO tax(country, tax, created_by, created_on) VALUES (1,7,51,'2015-06-26 16:26:20');
INSERT INTO tax(country, tax, created_by, created_on) VALUES (1,7,51,'2015-06-26 16:26:20');
INSERT INTO tax(country, tax, created_by, created_on) VALUES (1,7,49,'2015-06-26 16:26:20');
INSERT INTO tax(country, tax, created_by, created_on) VALUES (1,7,50,'2015-06-26 16:26:20');
INSERT INTO tax(country, tax, created_by, created_on) VALUES (1,7,48,'2015-06-26 16:26:20');
INSERT INTO tax(country, tax, created_by, created_on) VALUES (6,9.45450,51,'2015-06-26 16:26:20');
INSERT INTO tax(country, tax, created_by, created_on) VALUES (3,8.88900,49,'2015-06-26 16:26:20');
INSERT INTO tax(country, tax, created_by, created_on) VALUES (2,9.08989,49,'2015-06-26 16:26:20');
INSERT INTO tax(country, tax, created_by, created_on) VALUES (2,4.00087,49,'2015-06-26 16:26:20');
INSERT INTO tax(country, tax, created_by, created_on) VALUES (1,1.88900,49,'2015-06-26 16:26:20');
INSERT INTO tax(country, tax, created_by, created_on) VALUES (4,5.54656,51,'2015-06-26 16:26:20');
INSERT INTO tax(country, tax, created_by, created_on) VALUES (5,7.45435,50,'2015-06-26 16:26:20');
INSERT INTO tax(country, tax, created_by, created_on) VALUES (1,43.88776,46,'2015-06-26 17:30:18');
INSERT INTO tax(country, tax, created_by, created_on) VALUES (2,5.67,46,'2015-06-26 17:39:12');
INSERT INTO tax(country, tax, created_by, created_on) VALUES (12,0.009,46,'2015-06-26 17:48:35');
INSERT INTO tax(country, tax, created_by, created_on) VALUES (11,3,46,'2015-06-26 17:55:14');
INSERT INTO tax(country, tax, created_by, created_on) VALUES (1,5,46,'2015-06-26 17:55:39');

Please find SQL Fiddle Result @
Result Produced in phpmyadmin(localhost)
+----+---------+---------+------------+---------------------+-------------+-----
--------+

| id | country | tax     | created_by | created_on          | modified_by | modi
fied_on |

+----+---------+---------+------------+---------------------+-------------+-----
--------+

|  3 |       3 | 7.00000 |         49 | 2015-06-26 16:26:20 |        NULL | NULL
        |

|  5 |       5 | 7.00000 |         48 | 2015-06-26 16:26:20 |        NULL | NULL
        |

|  6 |       6 | 9.45450 |         51 | 2015-06-26 16:26:20 |        NULL | NULL
        |

|  7 |       3 | 8.88900 |         49 | 2015-06-26 16:26:20 |        NULL | NULL
        |

| 11 |       4 | 5.54656 |         51 | 2015-06-26 16:26:20 |        NULL | NULL
        |

| 12 |       5 | 7.45435 |         50 | 2015-06-26 16:26:20 |        NULL | NULL
        |

| 14 |       2 | 5.67000 |         46 | 2015-06-26 17:39:12 |        NULL | NULL
        |

| 15 |      12 | 0.00900 |         46 | 2015-06-26 17:48:35 |        NULL | NULL
        |

| 16 |      11 | 3.00000 |         46 | 2015-06-26 17:55:14 |        NULL | NULL
        |

| 17 |       1 | 5.00000 |         46 | 2015-06-26 17:55:39 |        NULL | NULL
        |

+----+---------+---------+------------+---------------------+-------------+-----
--------+

A: Check out this link to see what the error log is saying.
This is very wrong because those results dont even make sense. where can I find mysql logs in phpmyadmin?
Also see if simple select statements are working as they should.


text:
Q: Alternatives to y4mstabilizer; deshaking video "Deshaking" means fixing the video captured from camera hold in hands.
Is there open source video deshaker apart from y4mstabilizer from mjpegtools? Patch for mencoder is preferred.
My current command line for processing video looks like:
mplayer  video_from_camera.avi -nosound -vo yuv4mpeg:file=/dev/stdout -really-quiet | y4mstabilizer -n -a 0.8 -r 30 -s 100 | mplayer -cache 1000 /dev/stdin -noconsolecontrols -vf crop=500:380:70:50,denoise3d=3:3:5:5 -vo yuv4mpeg:file=temporary.yuv

y4mstabilizer is itself very unstable and often crashes (and it didn't work at all until I have patched memory allocation in it).

A: Use transcode with "stabilize" and "transform" plugin pair. http://www.transcoding.org/
transcode -i temporary1.yuv -J  stabilize=maxshift=100=fieldsize=20 -y null,null -o /dev/null
transcode -i temporary1.yuv -J transform=smooth=50,denoise3d=luma=3:chroma=3:luma_strength=5:chroma_strength=5 -y yuv4mpeg -o temporary2.yuv

A: Use ffmpeg with the same filter as in transcode:
# create deshaking profile, with a preview
ffmpeg -i inputvideo.mkv -pix_fmt yuv420p -vf vidstabdetect=show=1:result=inputvideo.trf -vcodec libx264 -preset ultrafast -crf 0 -an -f matroska - | ffplay  -

# preview the transformed video
ffmpeg -i inputvideo.mkv -pix_fmt yuv420p -vf vidstabtransform=input=inputvideo.trf:smoothing=5  -vcodec libx264 -preset ultrafast -crf 0 -an -f matroska -  | ffplay -


text:
Q: Difference between Attachment and AttachmentData As per title, what is the difference between an Attachment and an AttachmentData?
I see the example at https://github.com/Microsoft/BotBuilder-Samples/blob/master/CSharp/core-SendAttachment/SendAttachmentDialog.cs and it is not clear when we should use the first or the second.

A: The AttachmentData class is basically the model that is sent when you use the Connector API to upload attachments to the channel.
In the readme of that sample, you will find the different scenarios related to attachments.
Unless you are generating an image dynamically based on user input you might not need to go that route. If you already have an URL for the image, you can just use it.
More information also on https://learn.microsoft.com/en-us/bot-framework/rest-api/bot-framework-rest-connector-api-reference#objects


text:
Q: Error while importing module app using from Flask.app import db I'm new to flask, and have problem with importing db while running from python console/cmd.
I'm facing this error :
In[67]: os.getcwd()
Out[67]: 'C:\\Users\\Desktop\\Python\\Flask'
In[68]: os.listdir()
Out[68]:
['app',
 'app.db',
 'config.py',
 'Flask.py',
 'migrations',
 'venv',
 '__init__.py',
 '__pycache__']

In[69]: from Flask.app.models import User,Post
Traceback (most recent call last):
  File "C:\Users\AppData\Local\Continuum\anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3326, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-69-dca3714f084d>", line 1, in <module>
    from Flask.app.models import User,Post
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.3\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import
    module = self._system_import(name, *args, **kwargs)
  File "C:\Users\Desktop\Python\Flask\app\models.py", line 1, in <module>
    from Flask.app import db
ImportError: cannot import name 'db' from 'Flask.app' (C:\Users\Desktop\Python\Flask\app\__init__.py)

The tree of my project :
Flask/
  app/
    __init__.py
    forms.py
    models.py
    routes.py
  __init__.py
  config.py
  Flask.py

Flask/init.py

app/init.py
from flask import Flask
from Flask.config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate

app = Flask(__name__)
app.config.from_object(Config)

db = SQLAlchemy(app)
migrate = Migrate(app, db)

from Flask.app import routes, models

app/models.py
from Flask.app import db
from datetime import datetime

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), index=True, unique=True)
    email = db.Column(db.String(120), index=True, unique=True)
    password_hash = db.Column(db.String(128))

    def __repr__(self):
        return '<User {}>'.format(self.username)

When running flask run via command it's working fine. But I when I'm trying to run via python console or cmd I'm not able to run successfully.
Thanks

A: there is a problem when importing module fix this....
inside Flask remove the __init_.py here u didnt want a init file.if the Flask folder is the root folder others are sub folders inside it I guess your main file is Flask.py. So
change the
from Flask.app import db

to
from app import db

considering  db is declared inside app/init.py


text:
Q: Sublime Text 2 - Auto Refreshing I'm using the Sublime Text 2. My problem is that when I create a new file or folder, while using submline. It does not refresh and update immediately.
I have to quit out of sublime and restart it, I use the terminal to open folders. Once I reopen it then, I see the new file or folder I created.
I have looked for solutions, but I could not find one with an answer.
Thanks

A: For auto refresh you should install Autorefresh

*

*press crtl+shift+p

*package control : install package
wait for few seconds.

*type autorefresh and press enter
https://packagecontrol.io/packages/Auto%20Refresh

A: Instead of auto refresh we can do this

*

*Open Sublime Text.

*Select Preferences from the top menu and click Key
Bindings – User.

*Add the following entry between the brackets.
{ "keys": ["f5"], "command": "refresh_folder_list" }
You should be able to refresh the folders with F5.


text:
Q: Can initiate jquery dialog, but when opening get Uncaught TypeError: $(...).dialog is not a function I have an ecommerce site where I allow users to add to cart via ajax. When the add to cart succeeds I show a dialog with a success message.
At some point, and I don't know when, the dialog stopped displaying.
I've done some digging and debugging, and here is what I came up with.

*

*The line of code that initializes the dialog is running with no errors.
$('#cart_popup').dialog({
  autoOpen: false,
 modal: true,
width:600,
show: {
    effect: "blind",
    duration: 1000
  },
  hide: {
    effect: "fade",
    duration: 1000
  }
});

*The actual dialog is being set up on the page.
Original Html:

After page load:

 <button type="button" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-icon-only ui-dialog-titlebar-close" role="button" title="Close">Close</button>

*When the user clicks add to cart, the call is being sent, and the dialog is being updated as expected.

*When the callback gets to the line
$('#cart_popup').dialog('open');

it generates the following error:
jquery.min.js:4 Uncaught TypeError: $(...).dialog is not a function

I am including jquery & jquery-ui js, and jquery-ui css.

A: Is this working the way you are expecting (I simulated the ajax call, see comments in code)

var ajaxCall = function() {
  // simulate ajax call here,
  // trigger callBack
  $('#cart_popup').dialog('open');
};

$(document).ready(function() {

  $('#cart_popup').dialog({
    autoOpen: false,
    modal: true,
    width: 600,
    show: {
      effect: "blind",
      duration: 1000
    },
    hide: {
      effect: "fade",
      duration: 1000
    }
  });

  $('#cart_content').html('

');

  $('#add-to-cart').on('click', function(e) {
    ajaxCall();
  });

});
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />

<button id="add-to-cart">Add to Cart Simulation</button>


text:
Q: Apply format function to all table rows based on column tag in JS I would like to define a column formatter based on the header tag.
As a simple example, if I have in the header of the table:
4 Decimal Place Rounded Numbers
0 Decimal Place Rounded Numbers

I need some JS/JQuery code that calls and applies the 'data-formatter' function (defined elsewhere) to each row of that column.
I have seen some posts that consider getting all cells from a column (Datatable get the values of all rows of a specific column) but I cannot see how I iterate of those cells and apply the function name extracted from the data-formatter parameter.
Any help would be greatly appreciated.
Ultimately, I am just trying to display a datatable that has dates, and a number of different number formats required within the one table (0dp, 2dp and 4dp) so I need to format each column a little differently.

A: You can use columns render in order to get the formatter and run it when defined:

function roundTo4dp(data) {
    return parseFloat(data).toFixed(4);
}
function roundTo0dp(data) {
    return parseFloat(data).toFixed(0);
}

$('#myTable').DataTable({
    columns: [
        {data: 'Name'},
        {data: 'Position'},
        {data: 'Office'},
        {data: 'Age',
            render: function (data, type, row, meta) {
                var formatter = $(meta.settings.nTHead).find('th').eq(meta.col).data('formatter');
                return (formatter == undefined ? data : window[formatter](data));
            }},
        {data: 'Start date'},
        {
            data: 'Salary',
            render: function (data, type, row, meta) {
                var formatter = $(meta.settings.nTHead).find('th').eq(meta.col).data('formatter');
                return (formatter == undefined ? data : window[formatter](data));
            }
        }]
});

<link rel="stylesheet" href="//cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">

        Name
        Position
        Office
        Age
        Start date
        Salary

        Tiger Nixon
        System Architect
        Edinburgh
        61
        2011/04/25
        320,800

        Garrett Winters
        Accountant
        Tokyo
        63
        2011/07/25
        170,750

        Ashton Cox
        Junior Technical Author
        San Francisco
        66
        2009/01/12
        86,000

        Cedric Kelly
        Senior Javascript Developer
        Edinburgh
        22
        2012/03/29
        433,060

        Airi Satou
        Accountant
        Tokyo
        33
        2008/11/28
        162,700

        Brielle Williamson
        Integration Specialist
        New York
        61
        2012/12/02
        372,000

        Name
        Position
        Office
        Age
        Start date
        Salary


text: Q: What is the correct way of versioning in Xcode projects or frameworks I got a little confused about versioning my projects in Xcode, I can see an option from Targets > General > Version also another versioning method in Targets > Info > Bundle version string (short) so I really get confused why would we need both there? and it can be an issue if we forgot one of them to update, so which one is telling my project/framework version and why these 2 exists?


text:
Q: Duality approaches in functional programming I'd like to know what kind of real life problems can be tackled by "duality methods" in functional programming. More precisely, I'd like to know whether someone did actually use a duality method like the ones I present below, or whether there are other interesting examples. I'd be particularly interested in existing implementations, probably in Haskell.
[Since the majority of people which will be interested in this question likely know Haskell, let me please add the Haskell tag, even if the question is quite language independent]
Let me explain what I mean by duality (by lack of a better name) through a few examples. The first one is the real numbers. Assume the existence of a Integer and a Rational type, and define a real number as a function (pardon my Haskell, I'm no hardcore haskeller)
type Real = Integer -> Rational

such that whenever x :: Real denotes the real number x, x n yields a rational number which is within 2^(-n) of x.
Now one can do
(+) :: Real -> Real -> Real
(+) x y n = (x $ n + 1) + (y $ n + 1)

or likewise for other arithmetic operations. Given a continuous real function f, one can also compute f x as soon as one can compute a modulus of continuity for f.
This has the advantage that one can write natural looking code, and at the end, get a result at the desired level of precision automatically. However, it is no longer possible to compare real numbers for equality. The only kind of comparison possible between x and y  is x < y + eps.
Another example of duality is this question on probability measures, which triggered the present question in my head. Let us write
type Measure a = (a -> Double) -> Double

and define measures as integration procedures against functions. In the linked question, I show how natural it is in this framework to express concepts like convolution or pushforward which are much more difficult (computationally, but also theoretically) to define at the level of probability densities.
It allows one to compose building blocks from probability theory, and in principle allows one to build complex Monte Carlo procedures, and even allows one to work with explicit probability densities (at the expense of numerical integration). I'd be especially interested in any attempt at a real world library on this topic.
Another example that I have in mind, but did not quite formalize yet is the notion of vector fields (from differential geometry), that one can express as differentiation operators. For this, one needs a suitable type of "smooth real valued functions", and then a vector field is like this:
type VectorField = SmoothFunction -> SmoothFunction

such that v (f * g) = f * (v g) + g * (v f).
Of course, describing a sheaf of regular functions in say Haskell should not be easy. But by doing that, we could express all the stuff from differential geometry in a totally coordinate independant way, and plug coordinates at the very end.
There are other examples, eg. Taylor series have been discussed in Sigfpe's blog (I can't find this particular post though), where an analytic function is the following type:
type AnalyticFunction = Double -> Integer -> [Double]

and where f x n returns the n first partial sums of the Taylor expansion of f around x. This allows us to seamlessly write all kind of arithmetic on analytic functions, including stuff like f / g where f and g both can vanish at a point (along with some of their derivatives), or even f^(-1) (provided f' does not vanish). At the end, only the necessary terms of the intermediate series are computed to yield the value of a given expression.

A: The common feature of your example is the representation of some (mathematical) object by functions. This is common in functional languages, but not as practical as in mathematics because functions in programs are used extensionally (you cannot inspect their definitions, only observe their actions on arguments), and only with computable operations (you can only observe a finite number of arguments).
In mathematics, you don't bother with such stuff, for example you very often say "if f is analytic, then let's (a_n) be its sequence of coefficients, and...". In a computer language, if you start with a function of type Double -> Integer -> [Double], it will be painful to convert it to a representation where you can easily recover the coefficients. In programming languages, function really are black boxes.
For this reason, programmers often try to use explicit data representations instead of function black boxes. You can easily obtain a function from a data representation (its a kind of evaluation or interpretation), while the other way around can be more difficult, less efficient, etc. See Conal Elliott's "Everything is a function" in Haskell?.
Functions are however still used in cases where we really want extensional objects, that can only be observed instead of inspected. For each possible observation on the object you want to define, you give a function that realize this observation. In your example, you only have one function because you only have one observation. This is the core idea of Object Oriented Programming as defined by William Cook in his On Understanding Data Abstraction, Revisited paper.
I think the reason why you relate this to the term "duality" (a term that is, in the Haskell intelligentsia, rather related to category-theoretic concepts) is that the shift from an object to some particular form of observation of it is sometimes called duality in maths, and has the effect of adding functions everywhere. For example, there is the classical example of the dual of a vector space, and in particular the bidual construction which is really a conversion from a vector to its observations by linear functions : you switch from V to (V -> K) -> K, for K the field underlying your vector space.
(Would one think of continuations reading my last example ? Of course those are related, as this representation of continuations is really an "observation" of concrete evaluation contexts, represented by their action on values.)
Your representation of probability measures is actually used to define probability measure monads in functional languages. There are different ways to define probability monads. See for example http://www.cs.tufts.edu/~nr/pubs/pmonad-abstract.html by Norman Ramsey and Avi Pfeffer. Most real-world implementation of probability DSL however use a more concrete representation such as a [(prob,event)] list of pair (Haskell probability library and OCaml HANSEI).
Finally, for an example of representation of real number as functions, see Russel O'Connor's A Monadic, Functional Implementation of Real Numbers. Numerous representation of "computable" numbers exist and have different merits, and most of them are based on sequences and may therefore be represented as Integer -> ... functions.


text:
Q: Accordion is not working properly in angular 8 Trying to fix the accordion issue in angular 2 but it is not working properly.
I am expecting like

If I click section 1, section 1 will be expand.     If I click
section2, section 2 will be expand.

But in my code If I click section 1 or section 2 both are expanding. So, How to fix this issue?
app.component.html:

<button class="accordion" (click) = "expand(i)">{{section.name}}</button>

{{section.content}}

{{section.content}}

app.component.ts:
export class AppComponent {
currentIndex;

sections = [
{
  name: 'Section 1',
  content: 'Section 1 Content',
},
{
  name: 'Section 2',
  content: 'Section 2 Content',
}
];

 expand(index) {
    this.currentIndex = index;
}
}

Demo: https://stackblitz.com/edit/angular-accordion-eg-xk1c5a?file=src%2Fapp%2Fapp.component.ts


text:
Q: How to run chef cookbooks in terraform script? I am provisioning aws infrastructure with the help of terraform script.
For example, I am creating four unix ec2 instance, Now I want to install tomcat in all 4 instance throw chef cookbook.
I want to run chef cookbook in terraform script and I tried with below code but it gives me errors.
resource "aws_instance" "LG" { ami = "XXXXXXXXXXXXX" instance_type = "XXXXXXXX" chef_role_name = ["../tomcat.json"]

Error: Unsupported argument

  on LG.tf line 16, in resource "aws_instance" "LG":
      chef_role_name  = ["../tomcat.json"]

Is this is correct way to call cookbook? can some one plz suggest.

A: You need to add a provisioner to the resource. Something like this:
resource "aws_instance" "LG" {
    provisioner chef {
          chef_role_name  = ["tomcat"]
    }
}

A: I came across this page. interesting one.
https://miirojuuso.com/blog/terraform-chef-quick-start
please feel free to check for your scope.


text:
Q: Por que o código não está executando o laço for, mesmo o compilador não mostrando erro? Estava fazendo um exercício sobre vetores, em que o objetivo era construir um programa que recebia um número n pelo input que definiria o tamanho do vetor, para depois receber, também por input, outros n números para serem alocados nesse vetor.
Após isso deve-se utilizar um método para encontrar o maior número entre esses últimos. Mas o problema que encontrei está justamente na maneira que encontrei para pegar e alocar esses n números no meu vetor.
Após testar meu programa várias vezes vi que o método é chamado, mas o laço for, que estava antes nem é iniciado. Realmente não sei o que pode ser.

O código:
import java.util.Scanner;
//bubble sort array
public class EP6_1 {

    public static int maiorNumero(int array[]) {
        int resposta;
        for (int x = 0; x == array.length - 1; x++) {
            if (array[x] >= array[x+1]) {
                for ( int c = 0; c == array.length - 1; c++ ) { //c é o contador
                    int temp = array[c];
                    array[c] = array[c+1];
                    array[c+1] = temp;
                }
            }
        }
        resposta = array[array.length-1];
        return resposta ;
    }

    public static void main(String[] args) {

        Scanner leitor = new Scanner(System.in);

        int lista[];

        System.out.println("Digite o tamanho do vetor"); //numero de elementos
        int N = leitor.nextInt();                        //da lista

        lista = new int[N];

        for (int i = 0; i == N - 1; i++) { //i é o contador
            System.out.println("teste");
            lista[i] = leitor.nextInt();
        }
        System.out.println(">>>>>>>");
        System.out.println(maiorNumero(lista));

    }

}

A: A condição do for é i == N - 1, portanto o laço executará sempre que essa condição for verdadeira. Ele não precisa executar se a condição de cara já for falsa. Logo antes você disse que i é igual a 0, portanto a condição só será verdadeira se o N for 1 (lógica básica matemática), em nenhuma outra situação isto é verdadeiro, então qualquer número que seja digitada e colocada em N que não seja 1 a condição será falsa e o laço não executará, nem uma vez sequer.
Provavelmente o que queria fazer seria algo assim:
for (int i = 0; i < N; i++)

Coloquei no GitHub para referência futura.
Isso pelo menos seria o que todo mundo faz. Dessa forma será verdadeiro sempre que o valor de i for menor que N, portanto faz sentido para um contador, ele vai de 0 até o valor antes no número total. Só cuidado para não fazer i < N - 1 porque isto não iria até o último item, ou fazer i <= N porque iria um além e daria erro. Poderia, mas não é ideal fazer i <= N - 1, está fazendo uma operação aritmética desnecessária e em algumas arquiteturas o <= é mais lento que o <.

A: O erro está na linha 35
Substitua:
for (int i=0; i == N - 1; i++) {

por
for (int i=0; i < N; i++) {

A variável i está comparando com N e na verdade ela tem que ser menor que N (i < N).
Outra questão é que o laço inicia em 0 e vai até ele ser menor a variável N. A partir do momento que ele for verificar e i for igual a N ele não executará o bloco. Então se deixar o i < N - 1; ele vai contar sempre um menos.


text:
Q: Is it Possible to Change the text color for columns in Grid View based upon search item? Note: i need to change in different columns based upon search request.

A: Yes you can do it in GridView.RowDataBound event
Like this
protected void yourGridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Cells[0].BackColor = Color.Beige;
            // 0 could be any valid cell index in your row
        }
    }

for more info Go here


text:
Q: Batch update returned unexpected row count from update [0]; actual row count: 9; expected: 1 Getting this exception while trying to delete record using hibernate.
org.hibernate.jdbc.BatchedTooManyRowsAffectedException: Batch update returned unexpected row count from update [0]; actual row count: 9; expected: 1
I am using an entity which updates records in another table (I have a one to many relation - one "primary" object with a list of "secondary" objects from a separate table). The settings I have in place are trying to update the other table. This worked fine on create and update methods, but when I attempted to delete an object, I got the BatchedTooManyRowsAffectedException exception.
any idea why is it happening?
org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:95)
org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:70)
org.hibernate.jdbc.NonBatchingBatcher.addToBatch(NonBatchingBatcher.java:47)
org.hibernate.persister.entity.AbstractEntityPersister.delete(AbstractEntityPersister.java:2691)
org.hibernate.persister.entity.AbstractEntityPersister.delete(AbstractEntityPersister.java:2895)
org.hibernate.action.EntityDeleteAction.execute(EntityDeleteAction.java:97)
org.hibernate.engine.ActionQueue.execute(ActionQueue.java:268)
org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:260)
org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:184)
org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1206)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:344)
$Proxy679.flush(Unknown Source)

I am using SqlServer 2008.
     <hibernate-mapping>
<class name="com.send.ReportStock" table="COM_REPORT_STOCK">

    <id name="reportID" type="long">
        <column name="ReportID" />
        <generator class="assigned" />
    </id>

    <property name="Stock" type="java.math.BigDecimal">
        <column name="Stock" scale="9" not-null="true" />
    </property>
    <property name="Live" type="java.math.BigDecimal">
        <column name="Live" scale="9" not-null="true" />
    </property>

    <property generated="never" lazy="false" name="NotLiveStatic"
        type="java.lang.String">
        <column name="NotLiveStatic" />
    </property>

</class>
  </hibernate-mapping>

Class code:
 ReportStock reportStock= this.getReportStock(reportId);
 session.get().delete(reportStock);
 session.get().flush();


text:
Q: Solving a variable for an exponential function So I have the following problem:

A person puts 1,100 dollars in an account that he expects will make 5% interest in periods of three months. He then realizes a year later he was wrong about the interest rate and has $50 less than expected. What is the actual interest rate?

So I was able to get an equation out of that:
$$A_1 = 1100(1 + \frac{0.05}{4})^{4t}$$
$$A_1 - 50 = 1100(1 + \frac{r}{4})^{4t}$$
$$1100(1 + \frac{0.05}{4})^{4t} - 50 = 1100(1 + \frac{r}{4})^{4t}$$
Now there is where I get stuck on how to simplify the equation for r?

A: You are looking for $r$ which makes $$f(r,t)=1100\left(1 + \frac{0.05}{4}\right)^{4t} - 50 - 1100\left(1 + \frac{r}{4}\right)^{4t}=0$$ The solution  depends on $t$.
There is no explicit solution of this equation except if $t=1$ (just as Doug M commented) and numerical methods are required. This would be "simple" since the solution should be "close" to $r=0.05$ if $t$ is sufficiently large (as it uses to be in investment problems).
Assuming it (and making all numbers rational), we can use Taylor series limited to first order and get as a very first approximation $$r=\frac 1 {20}-\frac{2^{16 t-5} \left(\frac{81}{5}\right)^{1-4 t}}{11 t}\tag 1$$ Better would be the simplest Padé approximant which would give $$r=\frac 1 {20}-\frac{81\ 2^{16 t-1} 5^{4 t-1}}{\left(176\ 81^{4 t}-2^{16 t+2} 5^{4 t}\right)
   t+2^{16 t} 5^{4 t}}\tag 2$$ But the rigorous way would be to use a numerical method (such as Newton) starting using $r_0=0.05$.
I give you below a table of results
$$\left(
\begin{array}{cccc}
 t & (1) & (2) & \text{exact} \\
 1 & 0.0062083 & 0.0054863 & 0.0054795 \\
 2 & 0.0291655 & 0.0287835 & 0.0287805 \\
 3 & 0.0367837 & 0.0365421 & 0.0365404 \\
 4 & 0.0405683 & 0.0404006 & 0.0403994 \\
 5 & 0.0428204 & 0.0426974 & 0.0426966 \\
 6 & 0.044307 & 0.0442135 & 0.0442129 \\
 7 & 0.0453568 & 0.0452838 & 0.0452834 \\
 8 & 0.0461342 & 0.0460761 & 0.0460758 \\
 9 & 0.0467303 & 0.0466834 & 0.0466832 \\
 10 & 0.0471999 & 0.0471616 & 0.0471615 \\
 11 & 0.0475779 & 0.0475463 & 0.0475462 \\
 12 & 0.0478873 & 0.0478611 & 0.047861 \\
 13 & 0.0481444 & 0.0481225 & 0.0481224 \\
 14 & 0.0483605 & 0.048342 & 0.0483419 \\
 15 & 0.0485439 & 0.0485283 & 0.0485283
\end{array}
\right)$$

A: My previous answer was just stupid ! Not to hide how much it is, I add another one.
$$f(r,t)=1100\left(1 + \frac{0.05}{4}\right)^{4t} - 50 - 1100\left(1 + \frac{r}{4}\right)^{4t}=0$$
This implies
$$\left(1 + \frac{r}{4}\right)^{4t}=\left(1 + \frac{0.05}{4}\right)^{4t} -\frac 1 {22}$$
$$r=4\left(\sqrt[4t]{\left(1 + \frac{0.05}{4}\right)^{4t} -\frac 1 {22}}-1\right)$$ which is exact.


text:
Q: Serving up images under mod_perl using file::copy fails I have a CGI script that serves up images using the File::Copy CPAN module:
use File::Copy;
.... (set appropriate content header)
binmode STDOUT;
copy $imageFile, \*STDOUT || die "Image delivery failed: $!";

This works fine under CGI but when run under mod_perl I get:
[File::Copy::copy 140]  stat() on unopened filehandle STDOUT at /usr/share/perl/5.14/File/Copy.pm line 140.

I'm not sure if this is expected behaviour or if there's a bug somewhere. I'm new to mod_perl and find I am drowning in a sea of documentation at the moment. Is there any way to change my script so it runs fine under CGI or mod_perl without changes?

A: From the mod_perl documentation

Under mod_perl, CORE::print( ) (using either STDOUT as a filehandle argument or no filehandle at all) will redirect output to Apache::print( ), since the STDOUT file handle is tied to Apache.

And from the BUGS section if perltie

Tied filehandles are still incomplete. sysopen(), truncate(), flock(), fcntl(), stat() and -X can't currently be trapped.

You can read more about this in the bug report at https://rt.perl.org/rt3//Public/Bug/Display.html?id=112164 if you wish.

A: Not unless you're willing to change File::Copy or mod_perl (in negative ways). File::Copy expects a file handle associated with a system file handle, but STDOUT is a tied file handle.


text:
Q: Risk of exposing an ID of entry in DRF framework I'm building an API and I've started using the GenericAPIViews. In this example
class InsertActivityChange(UpdateAPIView):
    authentication_classes = []
    permission_classes = []
    serializer_class = ActivitiesSerializer
    lookup_field = 'id'

    def get_queryset(self):
        return Activities.objects.filter(id=self.kwargs['id'])

    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)

   path('insertactivitychange/<int:id>', views.InsertActivityChange.as_view(), name='insertactivitychange'),
I've used a generic class to do updates for an object. My concern is if I'm risking much by allowing the ID to be directly inputted after the URL. Obviously, I'd further mitigate the risk by properly configuring the authentication and permission class, so is the ID of the entry even a security risk?

A: Let me try to answer this question.

One can't ensure security just by hiding things

One of my mentor always emphasized on this line whenever I had asked similar questions.
To answer you question, according to me no you don't expose any security flaws by exposing IDs, in fact it's one of the most common way of allowing users to interact with resources over APIs.
You will be surely required to have authentication and authorisation in place to safeguard the resource manipulation by malicious sources. In context of DRF and django you can achieve this by using authentication and permissions.
Hope this answers your question.

A: If you're worried about access, remember to add permissions and filters. If you're focused on security and hiding resources, make sure they will 404 instead of 401 or 403. Have a look at DRF filtering section and in serializers use PrimaryKeyRelatedField queryset where you filter based on user.
If you're worried about exposing pks, just use UUIDs. It will still be visible but a human can't predict what the next id is.
So even if 3rd party knows the id of a resource, it should return 404 if you want to hide a resource. That way you expose a meaningless value to the attacker.


text:
Q: Can Mathematica be configured to not lazy-evaluate by default? I notice that VerificationTest will see False for a function in cell 1
f[x_] :=(x - 1) (x - 3) / (x + 2)

referred to in cell 2:
VerificationTest[Limit[f[x], Rule[x, -2]], \[Infinity]]

after hitting Shift+Enter in cell 2 only (in a newly-opened notebook with many, many cells) —but Evaluation > Evaluate Notebook will cause  VerificationTest to see True. Is there some default option or something I am missing here or is this just the way it is for now?

A: I think you improperly copied your function

*

*You wrote: f[x_] :=(x - 1) (x - 3) / x + 2

*I think you meant to write: f[x_] :=(x - 1) (x - 3) / (x + 2)
When you define you function in the latter form, this is what the code yields when you click Shift+Enter:


text:
Q: mysqldump dies on the same row. Analyze is fine. Timeouts are long I have an innodb table with about 70M rows. Recently a cron job to back it up with mysqldump started failing at the same row.
Mysqlcheck also fails.
Mysqlanalyze runs fine and prints OK.
Alter table also fails with an orphan temporary table starting with # which I need to nuke later.
Here is the configuration:
skip-external-locking
event_scheduler = ON
innodb_buffer_pool_size = 6G
**wait_timeout = 3600**
sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
innodb_flush_log_at_trx_commit  = 1
sync_binlog     = 1
bind-address            = 192.168.0.100
key_buffer_size         = 32M
max_allowed_packet      = 64M
thread_stack            = 192K
thread_cache_size       = 8
tmp_table_size          = 3G
max_heap_table_size     = 3G
myisam-recover-options  = BACKUP
max_connections        = 500

Host is on ubuntu 16.04.1, MySQL  Ver 14.14 Distrib 5.7.19, for Linux (x86_64) using  EditLine wrapper.
Any insight is highly appreciated.


text:
Q: Android app launcher icon size issue Our app manifest launcher icon in xml file drawable\icon.xml:
<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/icon_beta"/>

The xml file gets modified at build time to point to either icon_beta or icon_prod.
<application android:icon="@drawable/icon"

Both icon_beta.png and icon_prod.png exist in all resolutions. However, we found that on xhdpi device hdpi icon is used instead of xhdpi. If we reference the icon directly without xml file
<application android:icon="@drawable/icon_beta"

then correct xhdpi icon is used.
Why using the xml drawable affects which resolution is used?

A: I found that, specifically for the Nexus 7, specifying a resource in drawable-tvdpi the same dimensions as drawable-hdpi (72p) fixes this issue.  I don't know why :(.

A: The nexus 7 is not an xhdpi device, it has a PPI of 216 and is well within the hdpi 240 DPI bucket.
See this image (fig 1 from http://developer.android.com/guide/practices/screens_support.html )


text:
Q: erlang mnesia create table error I am trying to create mnesia table from Erlang shell. I got error and the same error for the below syntax copied from mnesia help documents.
mnesia:create_table(employee,
    [{attributes, record_info(fields, employee)}]).

got the error

record employee undefined

tried various combinations, getting same error. mnesia already started.

A: You need to have the record employee defined before you can do record_info on it. In the shell use can use rr(FileName). command which will find all the record definitions in the file and remember them. In a module you would either define the record directly in the module or include a file which contains the record definition.
The reason for having to do this special handling in the shell is that records are purely a compile-time feature so a record definition doesn't really "exist" anywhere.
EDIT:
If you want to define the record directly in shell then you can't use the standard -record(...). syntax. That is only valid in modules. The shell sees that as a call to the record/2 function. You need to use the rd shell command. It your case it would become:
3> rd(employee, {emp_no, name, salary, sex, phone, room_no}).
employee
4> record_info(fields, employee).
[emp_no,name,salary,sex,phone,romm_no]
5>

Then record_info works. If you already have the record definitions in a file then use the shell rr(File). command instead as it is easier. I think.

A: You can try
rd(employee, {emp_no, name, salary, sex, phone, room_no}). in the erlang shell.

rd(RecordName, RecordDefinition) Defines a record in the shell.
  RecordName is an atom and RecordDefinition lists the field names and
  the default values. Usually record definitions are made known to the
  shell by use of the rr commands described below, but sometimes it is
  handy to define records on the fly.

Please see this link:http://www.erlang.org/doc/man/shell.html


text:
Q: What's the best to way to manage a singleton? I am messing around with different PHP logging frameworks.  I am currently trying PEAR::Log.  I figured that I would use its singleton function to make sure there was only one instance of the class around.
I have a small daemon-like script I wanted to add logging to because it was probably the simplest script in the system to test.  This script has several functions.  I will probably want to log things inside the functions.
The question I have is how do I best manage this singleton?
To me calling this:
&Log::singleton($handler, $name, $ident, $conf, $maxLevel);

in every function doesn't seem ideal especially since I already specified all of the options in the initial call.  Pear::Log serializes this info, but from what it looks like you still have to provide all of those variables to get the instance.
Another alternative is passing the instance into every function.  Again, seems like it's less than ideal.
I suppose you could make the instance a 'global' as well.
What do you in this situation?  Are there better solutions?

A: Better yet, if your end goal is to just be able to blindly call
Logger::Write("Something happened");

wherever you need it, you can take Michal's solution one step further with
class Logger {
    private static $log = null;

    public static function init(Log $log) {
        self::$log = $log;
    }

    public static function Write(String $str) {
        if($log == null)
            init(Log::singleton(...));

        $this->log->Write($str);
    }
}

That way, your log will be initialized once, the first time it's used.

A: I don't know much about PEAR::Log, but why not create another singleton that wraps/simplifies logging.
class Logger {

    private static $log;

    private function __construct() { }

    public static function init(Log $log) {
        self::$log = $log;
    }

    public static function get() {
        return self::$log;
    }

}

Once you initialize Logger with Log instance you can access it via Logger::get. Since dereference is possible in PHP you can then do
Logger::get()->doSomething($foo, $bar);

A: Just use a global instance. Somewhere you must have a file that all other files must include. Just instantiate it there. If you have something against global variables you probably shouldn't be programming in PHP.

A:
Another alternative is passing the instance into every function. Again, seems like its less than ideal.

Basically you have the choice of passing dependencies per function, per object instance or in one of the global scopes. I find that using the object instance scope usually hits a good balance of flexibility. Generally, you should try to limit the scope of variables as much as possible, so if it makes sense, by all means pass through function parameters.


text:
Q: How to insert composite objects into SQL table using NodeJS? I'm learning Node and I used Spring Boot before where I used Hibernate ORM which enabled me to map objects like
{
 name:"John",
 salary:50000,
 address:{
  city: "Houston",
  state: "Texas"
 }
}

into 2 separate tables for example Employee and Address and insert it. I wonder how it can be done in NodeJS and whats the best practice to map such data.

A: If you want to keep the Hibernate ORM habit on NodeJS, you can use bookshelfjs or sequelize. You have to make an insert process yourself regarding the json you shared.
var data = {
 name:"John",
 salary:50000,
 address:{
  city: "Houston",
  state: "Texas"
 }
};

connection.query('INSERT INTO Employee (NAME, SALARY) VALUES(?,?)', [data.name, data.salary], function (err, result, fields) {
    if (err) throw err;

    var lastInsertID = result.insertId;
    connection.query('INSERT INTO ADDRESS (CUSTOMER_ID, CITY, STATE) VALUES(?,?,?)', [lastInsertID, data.address.name, data.address.state], function (err, result, fields) {
        if (err) throw err;

    });
});