text:
Q: How to show beta equivalence of property of Y combinator How to show that $\underline{Y}f =_{\beta} f(\underline{Y}f)$ where $\underline{Y}$ is the usual Y combinator?
Thanks.

A: I'm assuming that by "the usual $Y$ combinator" you mean Curry's fixed point combinator:
$$ Y = \lambda f . (\lambda x . f (x x)) (\lambda x. f(x x)) $$
The property $Y F \equiv_\beta F(Y F)$ can be proven as follows:
$$\begin{aligned}
YF &\equiv_\beta^\star (\lambda x . F (x x)) (\lambda x. F(x x)) & (1)\\
&\equiv_\beta^\star F ((\lambda x . F (x x)) (\lambda x. F(x x)))& (2)\\
&\equiv F(YF)& (3)
\end{aligned}$$
Where $\equiv_\beta^\star$ is the transitive and reflexive closure of the beta-reduction.

*

*The $Y$ combinator is applied to $F$

*The recursion happens; the first $(\lambda x. F(x x))$ is applied to the second, obtaining exactly the expression from (1), but "wrapped" inside an $F$.

*Since what we had before was equivalent to $YF$, the result is $F(YF)$.


text:
Q: Syncing new folders created on server with Git I have an application on a server that is going to be creating new folders.  Though the environment itself uses Git as it's repository.  What is the best way for me to commit those folders and push them to the git repository so the server and the coders are not out of sync?
Thanks!

A: Write a bash script that runs a git add and push on file creation. I believe there are some free to use scripts that do just that if you google them too. I would include a link to one but as I don't know how your app will be creating them, I can't suggest one for your use case.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Send email alert on log file entry? Under Linux, what's a simple way to automatically watch a logfile, and email me if a certain string appears? I have an application that will log certain failures to a logfile, but has no built-in way of sending alerts or executing scripts on failure. I suppose I could rig something up with tail -f and some shell scripts, but I'd rather use an existing maintained tool if it exists.

A: Before we went to a heavyweight solution (Zenoss) we used to use logcheck which is a part of Debian but can easily be ported to other distros as well. I was using it on Gentoo. Distros like RHEL come with logwatch, which does something similar.

A: The best way is to use a log analysis program.
OSSEC, for example, is free/open source and allows you to watch as many log files as you want and to generate email alerts (or even active responses) for certain events.
Link: http://www.ossec.net
I know, hacking a shell script is fun, but way less stable than a mature program being developed for years. Plus, if in the future you need to extend your script or add more triggers, it becomes way more complicated. OSSEC (and other tools) have this framework done for you.

A: LoFiMo (Log File Monitor) on Sourceforge should get you started or
NuHe might work, but I am less familiar with it.

A: I found a tool called tenshi that appears to do exactly what I need it to do. It's included in the default Debian repos which is nice, unfortunately not in the RHEL/CentOS ones (I have a mix of both OS's as servers).

A: I know an answer has already been accepted but rsyslog is much more robust and has built-in filtering, SMTP alerts, and non-syslog based file-watching abilities for applications that do not use syslog.  It's now the standard syslog implementation on Ubuntu 10.x.

A: I checked out several of the options mentioned on this page, and ended up using something far simpler: swatch.
Those other systems are great for dealing with existing system logs, or with software where you don't have control over the output. I just didn't want to write a bunch of code to do email notifications just yet. So I just created a swatch file like this:
watchfor /./
    mail addresses=me\@example.com:other\@example.com,subject=log_alert

And then started it up with
swatch -c send-me-everything.swatch -t /my/app/urgentevents

It's crude, but since I control the logfile output, I don't need anything more complicated yet.


text:
Q: Checking user availability I have upgraded from php5.2 to php5.3. Before this my code was working fine. After up gradation I am getting the error " the email is already in use...." though the email is not exist in the database. Please help.
<?php
$request = trim(strtolower($_REQUEST['username']));

$query = "SELECT username FROM advt WHERE username = '$username';";
$result = mysql_query($query) or die(mysql_error());
$valid = 'true';

if (mysql_num_rows($result) != 0)
    $valid= '"The email is already in use, please choose another"';
{
    echo $valid;
}
?>

A: Here's an implementation in PDO. It might not be working because mysql functions are deprecated in php 5.5. replace dbname=test to your database name, and create a $user and $pass variable to access it with correct permission
$username = trim(strtolower($_REQUEST['username']));
try {
    $user = 'root';
    $pass = 'password';

    $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
    $stmt = $dbh->prepare("SELECT username FROM advt WHERE username = :username LIMIT 1;"); //Limit this to one result
    $stmt->bindParam(':username', $username); // bind the parameters to prevent sql injection
    $stmt->execute();

    $valid = 'true';
    //returns an array of results
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

    //If the array is empty, no results have been returned
    if (count($result) != 0) {
        $valid = '"The email is already in use, please choose another"';
    }

    $dbh = null;
    echo $valid;

} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}

A: $query = "SELECT username FROM advt WHERE username =
'{$username}';";


text:
Q: How can I get the text from Charsequence? thats my Strings file:
<resources>
<string name="app_name">Name</string>
    <string name="vp_locations">Locations</string>
    <string name="vp_client_area">Client Area</string>
    <string name="vp_menu">Menu</string>
</resources>

And I would like to get programmatically all these strings, I created an array to get all the string values that I need:
private CharSequence[] tbTitles = {
        getResources().getText(R.string.vp_locations),
        getResources().getText(R.string.vp_client_area),
        getResources().getText(R.string.vp_menu),
};

Now I would like to know how can I get the values, when I do this:
textView.setText(tbTitles[0]);

The application crashes
I already to convert from charsequence to string, doing this:
textView.setText(tbTitle[0].toString());

But nothing seems to work. Can you guys tell me what am I doing wrong?
Log:

java.lang.NullPointerException
                                                                                at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2311)
                                                                                at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2436)
                                                                                at android.app.ActivityThread.access$800(ActivityThread.java:157)
                                                                                at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1374)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:110)
                                                                                at android.os.Looper.loop(Looper.java:193)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5398)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:515)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:940)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
                                                                                at dalvik.system.NativeStart.main(Native Method)
                                                                                Caused by: java.lang.NullPointerException
                                                                                at android.content.ContextWrapper.getResources(ContextWrapper.java:89)
                                                                                at
  android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:78)
                                                                                at
  com.example.rd.app.Interface.MainActivity.(MainActivity.java:36)
                                                                                at java.lang.Class.newInstanceImpl(Native Method)
                                                                                at java.lang.Class.newInstance(Class.java:1215)
                                                                                at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
                                                                                at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2302)
                                                                                at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2436)
                                                                                at android.app.ActivityThread.access$800(ActivityThread.java:157)
                                                                                at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1374)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:110)
                                                                                at android.os.Looper.loop(Looper.java:193)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5398)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:515)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:940)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
                                                                                at dalvik.system.NativeStart.main(Native Method)

Thank you.

A: You can't call getResources() from a field initializer like you are doing in
private CharSequence[] tbTitles = {
    getResources().getText(R.string.vp_locations),
    getResources().getText(R.string.vp_client_area),
    getResources().getText(R.string.vp_menu),
};

At this moment context is not setup yet. Its done after calling onCreate.
Change your code like this
private CharSequence[] tbTitles = new CharSequence[3];

and add this in onCreate
tbTitles = new CharSequence[]{
    getResources().getText(R.string.vp_locations),
    getResources().getText(R.string.vp_client_area),
    getResources().getText(R.string.vp_menu),
};

And finally use the array like this
textView.setText(tbTitle[0].toString());

Note: If you are using this array in only one method then you can simply move the declaration inside that method.

A: I think you are doing unnecessary work.
You can declare an array in your xml file like this:
<string-array name="vp_arr">
    <item>Locations</item>
    <item>Client Area</item>
    <item>Menu</item>
</string-array>

Get it in your class:
String[] tbTitles= getResources().getStringArray(R.array.vp_arr);

And set it in your TextView:
textView.setText(tbTitles[0]);


text:
Q: How to run python scripts like cli commands? I want to create my own command line utility tools, that we can run at the command line by simply typing the command name. git is a great example of the sort of commands I want to create.
I want to achieve this using python.
I have followed:

*

*https://dev.to/pybash/how-to-create-a-command-line-utility-using-python-4ae6
I have tried this before from other sources, but cannot implement it.
For this one when I do:
C:\Users\username> search.py .py D:\Programming

I get nothing, nothing happens. Only the file search.py opens in VS code.
Note: I have tried adding #!/usr/bin/env python and #!/usr/bin/python to start of the file, it does not help.
#Expected output
D:\Programming\CLI-Utilities\search.py
D:\Programming\CLI-Utilities\calc.py
D:\Programming\etc.py
No. of files matched = 3

Code in search.py:
# search.py - CLI-Utilities - play4Tutorials.hashnode.dev, github.com/play4Tutorials
try:
    import os  # stdlib
    import sys  # stdlib
# Exception and Error Handling
except ImportError as e:
    print("Error: Some modules could not be imported from stdlib('sys' and 'os')")

keyword = sys.argv[1]  # Get the keyword that is to be searched for
path = " ".join(sys.argv[2:])  # Get the path where to search for the keyword

filesMatched = 0  # Initialize filesMatched as 0

# Function to search the keyword in a given directory
def search_files(keyword, path):
    filesFound = filesMatched
    for root, dirs, files in os.walk(
        path
    ):  # Use os.walk(path) to loop through the given directory and get the root, dirs, and files
        for file in files:  # Loop through all the files in the given directory.
            if keyword in file:  # Check if keyword is in filename
                filesFound += 1  # Counter to see how many files matched
                print(
                    " " + root + "\\" + str(file) + "\n"
                )  # Print out the full file path for every matching file
                if (
                    filesFound == 0
                ):  # Check if no files matched the given keyword and print the same
                    print(
                        "No matching files in the given directory! Try another directory!"
                    )
    # If 1 or more files are matched then print the same
    print(f"No. of files matched: {filesFound}")

try:
    search_files(keyword, path)  # Call the function
# Error and Exception Handling
except FileNotFoundError as e:
    print(
        "Error: FileNotFoundError occured! Make sure you entered the correct path and entered it correctly."
    )
except Exception as e:
    print(f"Error: Some Error occured! \nDetails: {e}")

Screenshot of my path variables, after following the "how to run it from anywhere" instructions


text:
Q: How do we convert a string into Array in hive? I am using hive 1.1
 hive> select country from releases limit 1;
 OK
 ["us","ca","fr"]

For now country  is of type string in hive . How do I convert that into Array[String]?
I tried the below, but it is throwing error
 hive> select country, cast(country as Array[String]) from releases limit 1;
 FAILED: ParseException line 1:48 cannot recognize input near 'Array' '[' 'String' in primitive type specification

Can someone help me to do the typecasting?

A: hive> with releases as (select '["us","ca","fr"]' as country)
    > select  split(regexp_extract(country,'^\\["(.*)\\"]$',1),'","')
    > from    releases
    > ;
OK
_c0
["us","ca","fr"]


text:
Q: $A=(A_1,\ A_2)^T$ is a square matrix such that $N(A_1)=R(A_2^T)$, prove that A must be nonsingular. As the title says.
I seem to be proving the opposite which I doubt is correct.
Proof:
Choose arbitrary $y\in N(A_1)$.
Then, by $N(A_1)=R(A_2^T)$, $y\in R(A_2^T)$ as well.
Thus,
$$ Ay = (A_1y,\ A_2y)^T $$
$$ = (0,\ A_2y)^T $$
However, $y\in R(A_2^T)$ as well. If $y\neq 0$, then $N(A_1) \neq 0$ in which case $R(A_2^T) \not\ni \{0\}$ which is absurd.
Thus, it must be that $y=0$ which in turn implies $N(A_1)=0$.
However, this implies that $R(A_2^T)=0$, in which case $A_2=0$.
If $A_2=0$, $A$ must be singular.

A: We have
$$
A = \pmatrix{A_1\\A_2}
$$
Note that for a vector $x$, we have
$$
Ax = \pmatrix{A_1x\\A_2x}
$$
We note that $A_1 x = 0$ iff $x \in N(A_1)$.  Similarly, $A_2 x = 0$ iff $x \in N(A_2) = R(A_2^T)^\perp = N(A_1)^\perp$.  It follows that
$$
N(A) = N(A_1) \cap N(A_2) = N(A_1) \cap N(A_1)^\perp = \{0\}
$$
Since $A$ is a square matrix with a trivial kernel, we conclude that it is non-singular.


text:
Q: Handler / Looper / send message to Thread i wrote a test app to understand the comunication mechanism between Threads.
my sources :

http://techtej.blogspot.de/2011/02/android-passing-data-between-main.html,
  send message to Thread which is listening for data from network

I don't understand how to use the Handler and the Looper.

Here : (every step should give his state : Log.v(TAG, "..."))

*

*MainActivity create and start Thread (Runnable "r")

*MainActivity --> Message to --> r

*MainActivity <-- modified Message <-- r

package com.example.desktop.testhandlerlooper;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MyActivity";
    private Handler mHandler2;
    private Handler mHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                Log.v(TAG, (String)msg.obj);
            }
        };

        mHandler.post(r);
    }

    @Override
    protected void onStart() {
        super.onStart();
        for(int i = 10; i>=0; i--)
        {
            Message msg = mHandler2.obtainMessage();
            msg.arg1 = 3;
            msg.obj = String.valueOf(i);
            mHandler2.sendMessage(msg);
        }
    }

    Runnable r = new Runnable() {
        private static final String TAG = "Thread";
        @Override
        public void run() {
            Log.v(TAG, "Before the looper");
            Looper.prepare();
            //=======================================
            mHandler2 = new Handler() {
                public void handleMessage(Message msg) {
                    synchronized (this) {
                       Message m = mHandler.obtainMessage();
                        //Message message = Message.obtain();
                        m.obj = "ACK:" + msg.obj;
                        Log.v(TAG, (String)m.obj);
                        //message.sendToTarget();

                        mHandler.sendMessage(msg);
                    }
                }
            };
            //=======================================
            Looper.loop();
            Log.v(TAG, "After the looper");
        }
    };
}

Logcat :

--------- beginning of crash E/AndroidRuntime: FATAL EXCEPTION: main
  Process: com.example.desktop.testhandlerlooper, PID: 2872
  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.desktop.testhandlerlooper/com.example.desktop.testhandlerlooper.MainActivity}:
  java.lang.NullPointerException: Attempt to invoke virtual method
  'android.os.Message android.os.Handler.obtainMessage()' on a null
  object reference
                        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
                        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                        at android.app.ActivityThread.-wrap11(ActivityThread.java)
                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                        at android.os.Handler.dispatchMessage(Handler.java:102)
                        at android.os.Looper.loop(Looper.java:148)
                        at android.app.ActivityThread.main(ActivityThread.java:5417)
                        at java.lang.reflect.Method.invoke(Native Method)
                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Message
  android.os.Handler.obtainMessage()' on a null object reference
                        at com.example.desktop.testhandlerlooper.MainActivity.onStart(MainActivity.java:35)
                        at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1237)
                        at android.app.Activity.performStart(Activity.java:6253)
                        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
                        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                        at android.app.ActivityThread.-wrap11(ActivityThread.java)
                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                        at android.os.Handler.dispatchMessage(Handler.java:102)
                        at android.os.Looper.loop(Looper.java:148)
                        at android.app.ActivityThread.main(ActivityThread.java:5417)
                        at java.lang.reflect.Method.invoke(Native Method)
                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
  Application terminated.

Beside what i am trying to do, i understand the error but don't know how to fix it. Maybe Synchronization between both, MainThread and ChildTread ?

A: you are trying to use mHandler2 variable before initialization as you can see at log line at:
com.example.desktop.testhandlerlooper.MainActivity.onStart(MainActivity.java:35)
you should first declare and initialize variables and then start to use them.


text:
Q: Weblogic Proxy-Plugin I am new to Weblogic.I was experimenting on the load balancing capabilities of WLS.I used a proxy plugin provided by default as a load balancer.
I want to check which server in a cluster gets the request from the proxy server every time I reload my site.
When I use "request.getServerPort()"  I am getting the proxy server's port, but what I want is the managed server's port.

A: Have you tried request.getLocalPort()?


text:
Q: Calculating the limit $ \lim_{n \to \infty} \frac{n}{4} \cdot \sin(4 \pi/n) $. I would like to calculate
$$\lim_{n\rightarrow \infty}\frac{n}{4} \sin \left(\frac{4 \pi}{n} \right)$$
Clearly this is a limit of the type $\infty \cdot 0$, so I'm thinking there is probably some way to turn it to $\infty / \infty$ or $0 / 0 $ and then use L'Hopital but I can't think of any such trick. I cannot think of a way to do it without L'Hoptial either. Thanks for any input.

A: HINT: If you can prove that
$$
\lim_{x\to 0}\frac{\sin x}{x}=1,
$$
then you are almost done by writing $x=4/n$ and letting $n\to \infty$.

A: HINT: Write your expression as
$$\lim_{n\to\infty} \dfrac{\sin(\pi(4/n))}{4/n}$$ and make use of the fact that
$$\lim_{x \to 0} \dfrac{\sin(ax)}{x} = a$$

A: you can use the taylor of $\sin(4\pi/n)$ as follow
$$y=x-\frac{x^3}{3!}+\frac{x^5}{5!}+\cdots$$
$$y=\frac{4\pi}{n}-\frac{(4\pi)^3}{3!n^3}+\frac{(4\pi)^5}{5!n^5}+\cdots$$
so
$$\lim_{n\rightarrow \infty }\frac{n}{4}(\frac{4\pi}{n}-\frac{(4\pi)^3}{3!n^3}+\frac{(4\pi)^5}{5!n^5}+\cdots)=\pi$$

A: We know $\sin \theta = \theta + \mathcal{O}(\theta^3)$ for $\theta \approx 0$. Then it becomes $\frac{n}{4}\frac{4\pi}{n} + \mathcal{O}(n^{-2})$.
O notation can be handy.


text:
Q: how to use ubuntu server virtualization feature? I have downloaded and installed ubuntu 11.10 server on a high end dell power edge server.
i have another desktop for my development which is windows 7
How do I create VM's etc on ubuntu 11.10 server ? I would like to do it from my development desktop i mean all the VM management etc from Windows 7
Can someone suggest which would be better option ? I am new to Virtualisation , i want some simple GUI based tools to do , am not a CLI Geek .
Regards
sashank

A: Of course it is possible to run a virtual machine on a remote server without the need of installing a GUI there to control and manage the VM. You can even create a virtual machine on your Windows desktop to export it to the server, run it there, and use your Windows for display of the VM. However you will need a cross-platform solution that will run on both Windows, and Ubuntu.
In case you want to try out Virtual Box you will need the closed source (PUEL) but free version available from Oracle (see this question on how to install for Ubuntu and the user manual for installation on Windows) to get support for the Virtual Box remote desktop display feature.
There is a nice tutorial from the Virtual Box user manual on how to set this up and how to run virtual box in "headless" mode on a server to use a remote machine's display via VRDP.


text:
Q: What's the parenthesized number next to "featured" in the mobile version of a tag's page?
Question: What does that number in the screenshot mean?

To see this,

*

*Go to the Featured tab of any tag's page on Stack Overflow (such as branch-prediction, google-glass, or php),

*If you're on the full site, go to the mobile site (click the "mobile" link on the footer of the page, between "advertising info" and "contact us")

*As you can see, in the order by dropdown on the right, there's a number next to "featured", in parenthesis (e.g. featured (36)).

The funny thing is, if I refresh the page, the number seems to change randomly.
It doesn't seem related to anything.

Seen on:

*

*Chrome 31.0.1650.18 (on iOS 7.0.4)

*Safari (on iOS 7.0.4)

*Opera 12.16 (on Mac OS 10.9)

*Chrome 31.0.1650.63 (on Mac OS 10.9)


text:
Q: MultiDict Error Django Im using Django and trying to get a response by using AJAX. I have two forms, the first one works just fine. Though I use the same logic in my second form handling it does not work well.
models.py
class AskMe(models.Model):
    name = models.CharField(max_length=1000)

views.py
def AskMeQ(request):
    if request.method == POST:
        name = request.POST['name']

        AskMe.objects.create(name=name)

urls.py
url('r^askmeQ/$', views.AskMeQ)

ajax logic
$('.former').on('submit', '.ajaxform', function(event) {
    event.preventDefault();
    $.ajax({
        url: '/askmeQ/',
        type: 'POST',
        data: {name: $('#name').val(),
                csrfmiddlewaretoken: csrftoken
        }
    })
    .done(function() {
        console.log("success");
        $('.formset').slideToggle(400)
        });
    })
    .fail(function() {
        console.log("error");
    })
    .always(function() {
        console.log("complete");
    });
});

ERROR
Traceback:

File "/usr/local/lib/python3.6/dist-packages/django/utils/datastructures.py" in __getitem__
  77.             list_ = super().__getitem__(key)

During handling of the above exception ('name'), another exception occurred:

File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py" in inner
  35.             response = get_response(request)

File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response
  128.                 response = self.process_exception_by_middleware(e, request)

File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response
  126.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/home/pc/Django_Projects/vikas/vikas/views.py" in askmeQ
  40.         name = request.POST['name']

File "/usr/local/lib/python3.6/dist-packages/django/utils/datastructures.py" in __getitem__
  79.             raise MultiValueDictKeyError(key)

Exception Type: MultiValueDictKeyError at /askmeQ/
Exception Value: 'name'

The logic I use above used to work in all the previous forms, but here it throws me an error. The SQLite3 table has been created as projectname_model.name.
How can I correct this?

A: It seems that the name was not posted with the request. Due to which, you name = request.POST['name'] will throw an error since the key won't be part of the POST dict.
To correct this, alter your code to:
def AskMeQ(request):
    if request.method == POST:
        name = request.POST.get('name')
        if name:
            AskMe.objects.create(name=name)
        # else:
        #     error condition handling

A: Try to use path() instead of url() in urls.py


text:
Q: Getting a file from current package This code runs well in my locally but gives file not found exception when we build using bamboo. Any idea/workaround?
final static String FILE_NAME ="/src/test/java/com/statement/SamplePDFStatementFile.txt";
file = new File(FILE_NAME);
FileInputStream fis = new FileInputStream(file);

I basically want to test a class which reads a file.  Here is the Complete Code.
//Main Class
public class PdfRenderer {

    public void render(PdfFile pdfFile) throws IOException {
        FileInputStream fis = new FileInputStream(pdfFile.getFile());

        final HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
        response.setHeader("Content-Disposition", " attachment; filename=" + pdfFile.getAttachmentName());

        byte[] buff = new byte[2048];
        int bytesRead;
        while (-1 != (bytesRead = fis.read(buff, 0, buff.length))) {
            response.getOutputStream().write(buff, 0, bytesRead);
        }

        response.getOutputStream().flush();

    }
}

//Test

public class PdfRendererTest{

    PdfFile pdfFile;
    File file;

    @Test
    public void test_DetailStatementsByAccountNumber() throws Exception {
        new AbstractSeamTest.ComponentTest() {

            PdfRenderer actionBean = new PdfRenderer();

            URL url = this.getClass().getResource("/SamplePDFStatementFile.txt");
            final String FILE_NAME = url.getFile();

            protected void testComponents() throws Exception {

                file = new File(FILE_NAME);

                context.checking(new Expectations() {{
                    one(pdfFile).getFile();
                    will(returnValue(file));
                    one(pdfFile).getAttachmentName();
                    will(returnValue(file.getName()));
                }});

                actionBean.render(pdfFile);
            }

        }.run();
    }
}

I want to set an expectation that pdfFile.getFile() returns SamplePDFStatementFile.txt. If I use getResourceAsStream, am not sure how to convert it to a File Object.
OK.. so now I am using. Looks like thats the answer :)
public void inputStreamToFile() throws Exception{
                InputStream inputStream =  this.getClass().getResourceAsStream("/SamplePDFStatementFile.txt");

                file = File.createTempFile("abc","def");
                OutputStream out = new FileOutputStream(file);

                int length = 0;
                byte[] bytes = new byte[1024];

                while ((length = inputStream.read(bytes)) != -1) {
                       out.write(bytes, 0, length);
                }

                inputStream.close();
                out.flush();
                out.close();
            }

A: There are no reliable ways to reference files relative to the project root folder.
You need to reference this file as a resource instead. As far as I see, you use Maven. If so, you need to put this file into /src/test/resources rather than /src/test/java (perhaps you can also configure Maven to get resources from /src/test/java, but it would be a violation of Maven directory layout convention).
After that you can load this file as
InputStream fis = getClass()
    .getResourceAsStream("/com/statement/SamplePDFStatementFile.txt");

Or, if the current class is in the com.statement package, as
InputStream fis = getClass().getResourceAsStream("SamplePDFStatementFile.txt");


text:
Q: Over-riding style won't effect from flip-clock cdn I'm trying to use flip-clock in my nuxt project. It's working but when i try tocustomize the style, it doesn't reflect the changes
the HTML
<template>

      <flip-clock @timer-stop="stopTimer"></flip-clock>

</template>

the style
.flip-clock-wrapper {
  width: auto;
  margin: auto !important;
  padding: 0 !important;
  display: flex !important;
  justify-content: center !important;
  align-items: center !important;
  height: 100%;
}

.flip-clock-divider,
.flip-clock-label {
  color: #7e92b5 !important;
  font-size: 25px !important;
}

.flip-clock-wrapper ul {
  width: 100%;
  height: 100%;
  margin: auto !important;
}

I'm trying to change the flip-clock label in particular

A: .flip-clock-label[data-v-f3eg9whatever] does not exist ;)
Put global CSS class in  and only the ones that should be scoped to the component in  (you can have both)


text:
Q: Basic HTML5 caching I am a little slow to the HTML5 caching,  I have just some simple questions though.
1) How long is data in a caching manifest cached?
2) If I update the data, how can I make sure the client checks for a newer version when it is available, or is this already done?
3) Also, is this completely useless for a non-0mobile environment or can it speed up load times on a desktop?
<html lang="en" manifest="offline.manifest">

offline.manifest
CACHE MANIFEST
index.html
style.css
image.jpg
image-med.jpg
image-small.jpg
notre-dame.jpg

A: 1) As long as the user cares to cache it.  The only way to completely get rid of the cache is to go into the browser settings and explicitly remove it.
2) If you update the manifest file, the client will download new versions of all the files.  This download is still governed by 'old' HTTP caching rules, so set headers appropriately, also make sure you send a 'no-cache' header on the manifest file itself.  The rules from HTML5 Boilerplate are probably a good place to start.
3) Remember desktops can lose connectivity too.  Also, having files in application cache means they are always served locally so, providing you're sensible about what you put in it, the application cache can reduce bandwidth and latency.  What I mean by sensible is: if most visitors only see a couple of pages of your site and you update the manifest of your entire site every week, then they could end up using more bandwidth if you're forcing them to cache a load of static files for pages they never look at.
To really cut down on bandwidth and latency in your HTML5 website of the future: use the application cache for all your assets and a static framework; use something like mustache to render all your content from JSON; send that JSON over Web Sockets instead of HTTP, saving you ~800 bytes and a two way network handshake per request; cache data with Local Storage to save you fetching it again, and manage navigation with the History API.

A: 1) How long is data in a caching manifest cached?
Once an application is cached, it remains cached until one of the following happens:
The user clears the browser's cache
The manifest file is modified
The application cache is programatically updated
2) If I update the data, how can I make sure the client checks for a newer version when it is available, or is this already done?
you can specify witch files not to cache (NETWORK:)
If you want to update your cached files, you should modify something in the manifest file, the best way is to put comment in the file and change it when you want the browser to update the cache
3) Also, is this completely useless for a non-mobile environment or can it speed up load times on a desktop?
Yes it is useful, cause the internet can cut on all devices


text:
Q: Interpreting dummy variable interaction terms I am attempting to model monthly retail electricity sales. To account for both the effects of seasonality and weather, I created an interaction term by multiplying 12 monthly dummy variables by the corresponding month's max temperature, such that:
Jan_dum_temp = Jan_dum * Jan_max_temp,
Feb_dum_temp = Feb_dum * Feb_max_temp,
.
.
.
Dec_dum_temp = Dec_dum * Dec_max_temp
When adding these interaction terms to the regression, I omitted one dummy variable interaction term (Jan_dum_temp) to avoid the dummy variable trap.
The resulting model is:
y(hat) = b1 + b2Feb_dum_temp + ... + b12Dec_dum_temp +
  other explanatory variables
How do I estimate/interpret the effects of January's seasonality and temperature (Jan_dum_temp)?

A: It is generally inappropriate to leave out the components of an interaction term in a regression.
At the very least you should include a plain "temperature" term in your model.  Whichever dummy variable you leave out is your reference category.  So b2 should be the effect of temperature in February relative to January.  But without the uninteracted temperature term, your model does not allow temperature to have any effect in January.


text:
Q: Usernames not getting saved on signup I'm using Devise to manager users and i'm getting a strange error. I have the categories of email, username, and password on my signup page, the email and password get passed to the database just fine but i can't get the username to save there. If i edit the user after signup, the username displays just fine.
Here is my signup page code:

Sign up

    <%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
      <%= devise_error_messages! %>

        <%= f.label :email %>
        <%= f.email_field :email, autofocus: true, class: "form-control" %>

        <%= f.label :username %>
        <%= f.text_field :username, class: "form-control" %>

        <%= f.label :password %>
        <%= f.password_field :password, class: "form-control" %>

        <%= f.submit "Continue" %>

    <% end %>

    <%= render "devise/shared/links" %>

Am i missing putting in username somewhere?

A: Solved this by adding
devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:username, :email, :password, :password_confirmation) }

to my applications controller


text:
Q: Approximate (but as accurate as it can) location of sound I quess that this is relatively easy question, but I have been struggling this for a two days now (basicly investigating different formulas) and couldn't find a solution.
So, let's think this case: Three (or more) internet nerds from same area (like in 10 kilometer radius) listens for a thunder. When each one hears that lightning strike, they tell to server that 'Wow now I heard it!' (clicks a button). Then server somehow calculates that where that lightning was. Let's assume that there is zero lag between what user hears and server got the info (network, human reflexes).
Things we know:

*

*We know listeners Latitude and Longitude.

*Also we know speed of sound in that horrible thunder.

*Time differences between each person. (For example Listener 1 hears it first, then Listener 2 after 1.2 seconds and then Listener 3 after 2.3 seconds)

I know it can be made easily when you know how far that was (by hearing and seeing), and my awesome brain simulation tells me that it can be done with only hearing OR seeing.

A: If you have two listeners who see the lightning, you can calculate the distance of the strike from each one.  Then just swing a circle of that radius around each one.  The circles will intersect in two points (unless they are tangent) and you know the location up to that ambiguity.
If you have three listeners you have just enough data to resolve it, but I don't know an easy way.  Let the listeners be at points $A,B,C$ and the time of day that they hear the thunder be $a,b,c$.  Then if the strike is at $D,d$ and the speed of sound is $s$ you have $|D-A|=s(a-d)$ and two more equations like it.  The three unknowns are the two coordinates of $D$ and the time $d$.  Three equations in three unknowns.  You generally will not have an ambiguity.  If the data (positions and times) are perfect the solution will be exact.

A: A "simple" way to do it would be solve the following equations.
First, WLOG, assume that the person who heard the first sound is at the location $(0,0,0)$ and the second is $(x_{P_2},y_{P_2},z_{P_2})$ and the third is $(x_{P_3},y_{P_3},z_{P_3})$. Let $P_2$ have heard it $t_1$ seconds later, and $P_3$ have heard it $t_2$ seconds later. Then, you have the equalities
Note: speed of sound is 340 m/s and the coordinates are in meters.
$$ 340t_1 + \sqrt{x^2+y^2+z^2} = \sqrt{(x-x_{P_2})^2+(y-y_{P_2})^2+(z-z_{P_2})^2} $$
$$ 340t_2 + \sqrt{x^2+y^2+z^2} = \sqrt{(x-x_{P_3})^2+(y-y_{P_3})^2+(z-z_{P_3})^2} $$
However, note that you don't have enough info with just this.. you need another person. (because 2 equations and 3 unknowns)
EDIT: An simplifying criteria is $z=0$, which is valid if you assume that the sound originated from the ground. Note, this assumes that $z_{P_2}=z_{P_3}=0$.


text:
Q: Bluetooth printing via SPP from microcontroller We've got a self-built mobile device which can transfer data via Bluetooth SPP to a PC. On the market there are numerous devices acting as mobile printers via Bluetooth. Some of them use a custom ASCII-based printing language, e.g. the label printers from Zebra.
So there is the idea of printing via SPP from our device.
Sadly there is not too much usable information on the internet on this special topic.
Can you recommend any printer (at least A4) capable of printing via Bluetooth SPP with publicly available protocol specs?
Or do you have any hints where to start?

A: Bluetooth printers typically use profiles other than SPP.  There are several flavors, some printers will support a variety of them:
1) BPP - Basic Print Profile can send simple text-based data, no need for printer-specific drivers
2) HCRP - Hard Copy Cable Replacement Profile is used to send the same data format as you would over a wire, typically requires printer-specific drivers to format the data.
3) BIP - Basic Imaging Profile allows transfer of photos, etc.
4) OPP - Object Push Profile is also sometimes used to transfer files
So in general, you are not going to be able to just use SPP to talk to a normal printer, although these other profiles may sit on top of SPP.


text:
Q: Give 'image address' of an img in javascript I want to get image address of an img tag in the javascript
note: I don't want to get src attribute of img tag
In google chrome, if you right-click on an img tag then click on 'Copy image address' chrome will give you address like this
'http://127.0.0.1/mycms/images/img.jpg'

but if I use this code
$('#myImgElement').attr('src');

jquery  give me something like this
../../images/img.jpg

I want give image address like 'Copy image address' of google chrome and thanks for your helps and excuse me if I have grammar problems in my texts

A: Maybe like this:

console.log($('#test_img')[0].src) ;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<img id="test_img" src="../../images/img.jpg"/>


text:
Q: Books/notes recommendation for a rigorous explanation of Classical Linear Regression So far I have been following Econometrics text books which while intuitively clear, due to their lack of rigour and hence, poorly explained and maybe even contradictory notation, I am having a lot of trouble trying to understand the core math behind it which is unsurprising; they are books meant to teach you to put data into practice. What I am having trouble trying to understand is which ones are the vectors, variables and constants, conditional and unconditional expectation.
There is no upper limit to the rigour or prerequisites, they may use measure theory, group theory or quantum physics, the more the merrier, provided the concepts are either defined in the book or are concepts which can be easily found in some other pure math book. Also, they need not contain proofs.
They must contain explanation for the regression functions and equations of Simple and Multiple Linear Rigouression Model, rest like LS estimation, goodness of fit etc., I will understand on my own after the rigour is clear, they are not necessary. I would prefer if the simple linear regression chapters avoid matrix algebra and uses it later for the multiple case, though that is not necessary.
The recommendations need not be self contained or limited to one book.
(EDIT)
I want the book to avoid matrix notation for SLRM only, and then introduce matrix notation. Also, the difference between PRF and SRF should be explained.
Examples of some poorly explained notation I can think of right now is I have read books defining $Y$ and $X$ as variables, and $Y_i$ and $X_i$ as the value of the variable at the $i$th observation where $Y_i$ is a random variable. Then, at least from what I believe $Y$ should not be defined as just a variable but a multivariate random variable. Yet in the same books, the unconditional $\mathbb E[Y]$ is defined as the sum of all possible $Y$ values times their probability i.e., the mean of the population, but the expectation of a vector as far as I know should be a vector of constants, not just a constant, I don't think it even be a scalar of all-one-vectors.
I also struggle with the assumptions of non stochasticity. Using same notation, is $X_i$ assumed to be constant values that $X$ a random variable takes, or is $X$ itself a non-stochastic vector which consists of elements $X_i$

A: You ask for clear definitions of concepts, coverage of linear models and their applications, and to avoid matrix algebra.  These requirements suggest the following:
Michael J. Wichura, The Coordinate-Free Approach to Linear Models.  2009. Very geometric flavor.
Mervyn Stone, Coordinate-Free Multivariable Statistics. 1987.  Very geometric.  Requires substantial mathematical sophistication.
Ronald Christensen, Plane Answers to Complex Questions. 1996 (last updated 2020). Classic.  Emphasizes vector space geometry.  Wide array of applications.

A: Staying in econometrics land you could give Econometric Analysis of Cross Section and Panel Data by Wooldridge a shot. My grad school book and I found it sufficient. Alternatively, I have heard great things about Elements of Statistical Learning and have referenced it for several things although I am unsure of it's rigor for linear regression.


text:
Q: Flask csrf: key is missing with Blueprint Hello everyone I have this issue I am not able to correct:
KeyError: 'A secret key is required to use CSRF.'
I am now using Flask with Blueprint.
I am not using CSRF at all but I think the LoginForm is.
I structured my project with Blueprint.
Before that, everything was find.
Here is my init.py file:
from flask import Flask
from flask_login import LoginManager
from flask_bcrypt import Bcrypt
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
from flask.config import Config
from flask_wtf.csrf import CSRFProtect

db = SQLAlchemy()
migrate = Migrate(db)
bcrypt = Bcrypt()
csrf = CSRFProtect()

login_manager = LoginManager()
login_manager.login_view = "login"
login_manager.login_message_category = "info"

from Flask import models
from Flask.models import User

admin = Admin(name='Admin')

def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(Config)

    admin.init_app(app)
    db.init_app(app)
    csrf.init_app(app)

    login_manager.init_app(app)
    migrate.init_app(app)
    bcrypt.init_app(app)
    db.init_app(app)

    from Flask.users.routes import users
    app.register_blueprint(users)

    return app

This is my config.py file:
import os

class Config:
    SECRET_KEY = "ef2006629e09b70e55a6fb95c4e3a538"
    SQLALCHEMY_DATABASE_URI = "sqlite:///site.db"
    # WTF_CSRF_SECRET_KEY= "bjk567nvhbvj63vg363vghvghv3768vgfbkijvr784"
    # CSRF_ENABLED = True

Thank you for your help !

A: You should create a SECRET_KEY=<Your secret key here> property in your configuration. It must be a difficult string.

A: I found the problem
I was not calling properly my config.py file
In my init.py file I change the line:
from flask.config import Config
with the line:
from Flask.config import Config
Flask is the name of my file, which is different from flask.
I should have found another name


text:
Q: Finding an irreducible polynomial over the rationals I'm very confused by a homework question.
"Find the irreducible polynomial for $ \sin{2\pi/5}$ over Q.
I found that $16t^{4}-20t^{2}+5=0$ but this is not monic? This is also irreducible by Eisenstein, but minimal polynomials are always monic?

A: If you want a monic polynomial, you can divide by $16$.  Of course it won't have integer coefficients any more.  A number that is a root of a monic polynomial with integer coefficients is an algebraic integer.  $\sin(2\pi/5)$ is not an algebraic integer.

A: $p(t)=t^{4}-5/4t^{2}+5/16$ is the minimal polynomial of $\sin 2\pi/5$ over $\mathbb Q$. It is irreducible in $\mathbb Q[x]$ according to Gauss's lemma as $16t^{4}-20t^{2}+5$ is irreducible in $\mathbb Z[x]$.


text:
Q: Rebuilding a C++ program with OpenCV on a VM I need to switch from an ubuntu 20.04 to a Windows 7 workstation.
I'm writing a program for Raspberry PI that needs pthread, so I need a linux test environment.
I installed an ubuntu 20.04 VM and reinstalled all the libraries used in my program :

*

*OpenCV 4.2

*Libtorch

*NumCpp

Here is my CMakeLists.txt :
cmake_minimum_required(VERSION 3.15)
project(POC_V4)

set(CMAKE_CXX_STANDARD 14)

# Specifying we are using pthread for UNIX systems.
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${TORCH_CXX_FLAGS} -pthread -Wall")

find_package(OpenCV REQUIRED)
find_package(Torch REQUIRED)

if(NOT Torch_FOUND)
    message(FATAL_ERROR "Pytorch Not Found!")
endif(NOT Torch_FOUND)

message(STATUS "Pytorch status :")
message(STATUS "    libraries: ${TORCH_LIBRARIES}")

message(STATUS "OpenCV library status :")
message(STATUS "    version: ${OpenCV_VERSION}")
message(STATUS "    libraries: ${OpenCV_LIBS}")
message(STATUS "    include path: ${OpenCV_INCLUDE_DIRS}")

add_executable(POC_V4 <all_my_sources_and_headers>)
target_link_libraries(POC_V4 ${TORCH_LIBRARIES} ${OpenCV_LIBS})
target_link_libraries(POC_V4 pthread dl util)

On the real PC and on the VM, the cmake output is the same:
-- Pytorch status :
--     libraries: torch;torch_library;/usr/lib/libc10.so
-- OpenCV library status :
--     version: 4.2.0
--     libraries: opencv_calib3d;opencv_core;opencv_dnn;opencv_features2d;opencv_flann;opencv_highgui;opencv_imgcodecs;opencv_imgproc;opencv_ml;opencv_objdetect;opencv_photo;opencv_stitching;opencv_video;opencv_videoio;opencv_aruco;opencv_bgsegm;opencv_bioinspired;opencv_ccalib;opencv_datasets;opencv_dnn_objdetect;opencv_dnn_superres;opencv_dpm;opencv_face;opencv_freetype;opencv_fuzzy;opencv_hdf;opencv_hfs;opencv_img_hash;opencv_line_descriptor;opencv_optflow;opencv_phase_unwrapping;opencv_plot;opencv_quality;opencv_reg;opencv_rgbd;opencv_saliency;opencv_shape;opencv_stereo;opencv_structured_light;opencv_superres;opencv_surface_matching;opencv_text;opencv_tracking;opencv_videostab;opencv_viz;opencv_ximgproc;opencv_xobjdetect;opencv_xphoto
--     include path: /usr/include/opencv4
-- Configuring done
-- Generating done
-- Build files have been written to: <path_where_i_build>```

On my real Ubuntu PC, the build works properly, but it fails during linkage on the VM :
/usr/bin/ld: CMakeFiles/POC_V4.dir/src/communication.cpp.o: in function `Communication::showImage(cv::Mat, Box, std::string)':
communication.cpp:(.text+0x208): undefined reference to `cv::imshow(std::string const&, cv::_InputArray const&)'
/usr/bin/ld: CMakeFiles/POC_V4.dir/src/communication.cpp.o: in function `Communication::showImage(cv::Mat, std::string)':
communication.cpp:(.text+0x393): undefined reference to `cv::imshow(std::string const&, cv::_InputArray const&)'
/usr/bin/ld: CMakeFiles/POC_V4.dir/src/communication.cpp.o: in function `Communication::fps(cv::Mat, std::string)':
communication.cpp:(.text+0x655): undefined reference to `cv::putText(cv::_InputOutputArray const&, std::string const&, cv::Point_<int>, int, double, cv::Scalar_<double>, int, int, bool)'
/usr/bin/ld: CMakeFiles/POC_V4.dir/src/communication.cpp.o: in function `Communication::Communication()':
communication.cpp:(.text+0x816): undefined reference to `cv::namedWindow(std::string const&, int)'
/usr/bin/ld: CMakeFiles/POC_V4.dir/src/imageGetter.cpp.o: in function `ImageGetter::ImageGetter()':
imageGetter.cpp:(.text+0x342): undefined reference to `cv::VideoCapture::VideoCapture(std::string const&, int)'
collect2: error: ld returned 1 exit status
make[2]: *** [CMakeFiles/POC_V4.dir/build.make:285: POC_V4] Error 1
make[1]: *** [CMakeFiles/Makefile2:76: CMakeFiles/POC_V4.dir/all] Error 2

TLDR :

*

*Same OS

*Same library versions (OpenCV 4.2)

*Same CMakeLists.txt file

Linkage problem with OpenCV...
Any ideas ?

A: I finally managed to make it work, thanks to @squareskittles :
I needed to uninstall OpenCV, and rebuild it from source to the good version, with C++14 standard.
If you have linking problems related to OpenCV when building, uninstall OpenCV and build it yourself :
sudo apt remove libopencv-dev && sudo apt autoremove

cd ~/Downloads
git clone https://github.com/opencv/opencv.git
git clone https://github.com/opencv/opencv_contrib.git
cd opencv_contrib
git checkout 4.2.0
cd ../opencv
git checkout 4.2.0
mkdir build

Open the CMakeLists.txt and add the following line at the beginning of the file :
add_definitions(-D_GLIBCXX_USE_CXX11_ABI=0)

Then build OpenCV :
cd build
cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr/local OPENCV_EXTRA_MODULES_PATH=~/Downloads/opencv_contrib/modules/ ..
make
sudo make install
sudo ldconfig

Install potentially missing libraries for graphical output handling.
sudo apt install libgtk2.0-dev pkg-config libcanberra-gtk-module libcanberra-gtk3-module

Try re-building the project, that should work !
Thx again @squareskittles !


text:
Q: How to convert to $('#' + $(this).val()).show() vanilla javascirpt How to convert this code to vanilla?
$('#optionselector').change(function(){
    $('.option-type').hide();
    $('#' + $(this).val()).show();
});

I cannot figure out the last line:
function addEventHandler(elem, eventType, handler) {
  if (elem.addEventListener)
    elem.addEventListener(eventType, handler, false);
  else if (elem.attachEvent)
    elem.attachEvent('on' + eventType, handler);
}

addEventHandler(document, 'DOMContentLoaded', function() {
  addEventHandler(document.getElementById('optionselector'), 'change', function() {
    document.querySelector('.option-type').style.display = 'none';

  });
});

Here is the jsfiddle

A: Probably just:
document.querySelector('#' + this.value).style.display = 'block';

See below for live example:

function addEventHandler(elem, eventType, handler) {
  if (elem.addEventListener)
    elem.addEventListener(eventType, handler, false);
  else if (elem.attachEvent)
    elem.attachEvent('on' + eventType, handler);
}

addEventHandler(document, 'DOMContentLoaded', function() {
  addEventHandler(document.getElementById('optionselector'), 'change', function() {
    document.querySelectorAll('.d-none').forEach(e => e.style.display = 'none');
    if(this.value !== "")
      document.querySelector('#' + this.value).style.display = 'block';
  });
});
.d-none {
  display:none;
}
<select name="option_type" class="option-type form-control mb-4" id="optionselector">
<option value="" selected="selected"></option>
<option value="text_type">Text Input</option>
<option value="select_type">Select Dropdown</option>
<option value="radio_type">Radiobox</option>
</select>

TEXT

SELECT

RADIO


text:
Q: Do non volatile fields in volatile object have the same effect with volatile primitive variable? In this code, shutdown is a non volatile variable in Holder class. In Test object, an holder object is declared as volatile. If I update the shutdown variable, would it have the same effect as a volatile variable in Test class? that is to say, Will other threads immediately see the change after it is updated in one thread.
class Test {
    volatile Holder holder = new Holder();

    public void func() {

        List<Thread> list = new ArrayList<Thread>();
        for (int i = 0; i < 10; i++) {
            list.add(new Thread() {

                public void run() {
                    while (holder.shutdown) {
                        if (...) {
                            holder.shutdown = true;
                        }
                    }
                }
            });
        }
        for (Thread thread : list) {
            thread.start();
        }

    }

    class Holder {
        boolean shutdown = false;
    }

}


text:
Q: How to flush right but align left? I am writing an introduction, and I need to put my name at the end of it at the right side of the page, but it should be aligned left:
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem
I psum has been the industry's standard dummy text ever since the 1500s, when an
unknown printer took a galley of type and scrambled it to make a type specime n
book. It has survived not only five centuries, but also the leap into electronic
typesetting, remaining essentially unchanged. It was popularised in the 1960s w
ith the release of Letraset.

                                                                  Andriy D.
                                                                  Toronto, 2009

What is the best way to achieve this? Any tips appreciated!

A: One way to do it in Plain TeX:
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem
I psum has been the industry's standard dummy text ever since the 1500s, when an
unknown printer took a galley of type and scrambled it to make a type specimen
book. It has survived not only five centuries, but also the leap into electronic
typesetting, remaining essentially unchanged. It was popularised in the 1960s
with the release of Letraset.

{
  \parindent=0em
  \setbox0=\hbox{Toronto, 2009}
  \hfill\vbox{\hsize=\wd0
  Andriy D.\par
  \box0\par}
}

\bye

A: One simple way to do this is with a tabular environment:
\documentclass{article}
\usepackage{lipsum}
\pagestyle{empty}
\begin{document}

\lipsum[1]

\hfill
\begin{tabular}{@{}l@{}}
Andriy D.\\
Toronto, 2009
\end{tabular}

\end{document}


text:
Q: How replace native order by clause on JPA equivalent? I use JPA 2.0 criteria builder. I need get data from one table and sort them by column from other. This tables have relations OneToMany:
 class Club{
   @OneToMany(mappedBy = "club")
    private List<Address> addresses;
    ...
    }

class Address{
@JoinColumn(name = "club_id", referencedColumnName = "id")
@ManyToOne(fetch = FetchType.LAZY)
private Club club;

@Column(name = "type")
private Long type;

@Column(name = "full_address")
    private String full_address;
    ...
        }

May be several address of some type but I need only one row of this specific address.
I write native queries with subquery, but it's has problem because subquery doesn't use in order clause and in select clause in JPA 2.0.
select c.full_name from club c
  ORDER BY (select a.full_address from address a WHERE c.id= a.club_id and a.type=1 LIMIT 1)

select c.full_name, (select a.full_address from address a WHERE a.type=1 AND c.id=a.club_id LIMIT 1) as full_address FROM club c
ORDER BY fullAddress;

How I can replace native order by clause on JPA equivalent?
Thanks!

A: This native query also resolve problem and it can replace by JPA query
select c.full_name, min(a.full_address) FROM club c LEFT JOIN address a on c.id = a.club_id
where a.id is null or a.type=1 or not exists(SELECT  1 from address aSub WHERE aSub .club_id=c.id AND aSub.type=1)
GROUP BY  c.id, c.full_name ORDER BY min(a.full_address);

JPA equivalent
 CriteriaBuilder builder = em.getCriteriaBuilder();
        CriteriaQuery<ClubItem> query = builder.createQuery(ClubItem.class);

    Root<Club> root = query.from(Club.class);
    Join<Club, Address> addressJoin = root.join(Club_.address, JoinType.LEFT);

query.select(builder.construct(ClubItem.class, root.get(Club_.id), root.get(Club_.fullName), builder.function("min", String.class, addressJoin.get(Address_.fullAddress))));

    Subquery<Address> subquery = query.subquery(Address.class);
    Root<Address> addressRoot = subquery.from(Address.class);

    subquery.select(addressRoot);
    subquery.where(
            builder.and(
                    builder.equal(addressRoot.get(Address_.type), 1),
                    builder.equal(addressRoot.get(Address_.clubId), root.get(Club_.id))));

    query.where(builder.or(builder.isNull(addressJoin), builder.equal(addressJoin.get(Address_.type), builder.literal(new Long(1))),
            builder.not(builder.exists(subquery))));

    query.groupBy(root.get(Club_.id), root.get(Club_.fullName))

            Order order = builder.asc(builder.function("min", String.class, addressJoin.get(Address_.fullAddress)));

            query.orderBy(order);

    TypedQuery<ClubItem> contentQuery = em.createQuery(query);

A: It's not terribly elegant, but it gets the job done...
Make your "Club" class implement Comparable.  Put the order-by logic into the Comparable.  Then use Collections.sort(unsortedList) to get the list into sorted form.   There's also a Collections.sort(unsortedList, Comparable) method which could be useful, especially if you are doing a bunch of similar methods that just vary on order-by.


text:
Q: How to iterate a column in QTableWidget and check if a check box is checked? How can I iterate one column in QTableWidget and check if a checkbox is checked?

When I clicked the button in the left, I want to iterate the column in the picture and check if a checkbox is checked.
As of now, I've tried this function but the function only return None:
def checkBoxcheck(self):
    print("checkBoxcheck started")
    for row in range(self.rowCount()):
        print(self.cellWidget(1, 1))
        if not self.cellWidget(1, 1) is None:
            if self.cellWidget(row, 1).isChecked():
                #others to do

This is the code to use in order to reproduce this problem (I already removed those unnecessary parts of the code):
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QTableWidget, \
                        QTableWidgetItem, QVBoxLayout, QHBoxLayout
from PyQt5.QtCore import Qt
from PyQt5 import QtCore, QtWidgets
import sys

class TableWidget(QTableWidget):
    def __init__(self):
        super().__init__(10, 3)
        self.verticalHeader().setDefaultSectionSize(10)
        self.horizontalHeader().setDefaultSectionSize(200)

        for rows in range(self.rowCount()):
            item = QtWidgets.QTableWidgetItem()
            item.setCheckState(QtCore.Qt.Unchecked)
            self.setItem(rows, 1, item)

    def checkBoxcheck(self):
        print("checkBoxcheck started")
        for row in range(self.rowCount()):
            print(self.cellWidget(1, 1))
            if not self.cellWidget(1, 1) is None:
                if self.cellWidget(row, 1).isChecked():
                    #others to do
                    pass

class AppDemo(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(700, 500)

        mainLayout = QHBoxLayout()
        table = TableWidget()
        mainLayout.addWidget(table)
        buttonLayout = QVBoxLayout()

        button_new = QPushButton('Check if checked')
        button_new.clicked.connect(table.checkBoxcheck)
        buttonLayout.addWidget(button_new)

        mainLayout.addLayout(buttonLayout)
        self.setLayout(mainLayout)

def app():
    app = QApplication(sys.argv)
    demo = AppDemo()
    demo.show()
    sys.exit(app.exec_())

app()

I hope you can help me with this problem

A: A "cell widget" is a QWidget that is added to an index of the view, as much as it's done using setIndexWidget() for any QAbstractItemView. It can be any widget, a checkbox, a combo, a custom widget, or even another item view.
If the requirement is to have checkable items, there's no need for that, since Qt models already provide the feature, which you're already using when doing item.setCheckState().
So, the solution is much simpler: look for the item(), and then verify the state:
for row in range(self.rowCount()):
    item = self.item(row, 1)
    if item is not None and item.checkState():
        # ...

Remember that:

*

*QTableWidget can have empty cells, which are items for which no QTableWidgetItem has been set yet and no data has been inserted by the user (even if their index exist), that's why I had to check if the item is not None;

*don't confuse item(row, col) with itemAt(x, y), which is based on pixel coordinates on the view;

*if an item has no checkState explicitly set, its value is also None.

*don't use booleans to set and verify the states, because Qt check states are tristate: Unchecked (0), PartiallyChecked (1) and Checked (2); by default their mouse behavior is boolean, but you have to consiser this before doing any "basic" action like you'd do with a basic bool (for QCheckBox, though, as for any button, you can use isChecked() and setChecked(), which are normal boolean based functions); this means that if you try to do setCheckState(True), the result will be a partially checked item, since for python True is the same as 1 (so, in Qt terms, PartiallyChecked): if you want to set a fully checked state, you should to do setCheckState(Qt.Checked);


text:
Q: Create a tree data structure faster for creating a interactive treemap using highcharter Objective: To transform data to a tree data structure with custom aggregated values in different hierarchy levels to feed in as input to highcharter package for r, to create a interactive treemap
I have created the tree manually using data.tree package as it helps with easier manipulation. Here is the code
data
> dput(df)
structure(list(Costcenter = c("N1", "N1", "N1", "N1", "N1", "N1",
"N1", "N1", "N2", "N2", "N2", "N2", "N2", "N2", "N3", "N3", "N4",
"N5", "N5", "N6"), Vendor = c("L2", "L2", "L2", "L2", "L2", "L2",
"L2", "L2", "L1", "L2", "L2", "L2", "L3", "L3", "L2", "L2", "L2",
"L2", "L2", "L2"), absDiff = c(103.0776, 37.9086, 269.7629, 6.0888,
515.388, 27.2604, 27.2604, 6.3608, 4.5434, 88.5966, 982.2193,
139.4249, 0.5452, 722.9811, 130.3381, 147.8434, 271.8786, 88.5966,
327.4065, 366.564), value = c(103.0776, 37.9086, 269.7629, 6.0888,
515.388, 27.2604, 27.2604, 6.3608, 4.5434, 88.5966, 982.2193,
139.4249, 0.5452, 722.9811, 130.3381, 147.8434, 271.8786, 88.5966,
327.4065, 366.564), Tool = c("M1", "M2", "M4", "M5", "M6", "M9",
"M10", "M11", "M8", "M5", "M9", "M10", "M3", "M7", "M4", "M5",
"M5", "M5", "M10", "M5")), .Names = c("Costcenter", "Vendor",
"absDiff", "value", "Tool"), row.names = c(NA, -20L), class = "data.frame")

Code
    #specify the tree hierarchy
df$pathString <- paste("Root" ,df$Costcenter, df$Vendor, df$Tool,   sep = "/")

library("data.tree")
s <- as.Node(df ,mode="table") #<-performance problem

#create values for parent nodes, by aggregation of children values
s$Do(function(node) node$value <- Aggregate(node , attribute = "value", aggFun = sum), traversal = "post-order")

# assign ids to all nodes
s$Set(id = 1:s$totalCount)
# calculate parent ids for all children, using parent1 as parent is system reserved by data.tree
s$Set(parent1 = c(function(self) GetAttribute(self$parent, "id", format = identity)))

#copy the data tree structure to a data.frame
test <- ToDataFrameTree(s,"value", "level", "id","parent1")#<-performance problem

test <- data.table(test)
test[,parent:= as.character(parent1)] # parent and ids should be of character for highcharts
test[,id:=as.character(id)] # parent and ids should be of character for highcharts

test[,value:= as.numeric(trimws(value))]

library(rCharts)
#convert each row to a list
list <- toJSONArray2(test,FALSE)

library(highcharter)
highchart() %>%
  hc_add_series(
    type = "treemap",
    layoutAlgorithm = "squarified",
    allowDrillToNode = TRUE,
    levels = list(
      list(
        level = 1,
        dataLabels = list(
          enabled = TRUE
        ),
        borderWidth = 3
      ),
      list(
        level = 2,
        dataLabels = list(
          enabled = TRUE
        ),
        borderWidth = 2
      )
    ),
    data= list
  )

This code works fine for smaller data sets. However when my data goes into 100s of nodes, the runtime goes upto 70 seconds. I have pinpointed the area of concern to as.node() and ToDataFrameTree() functions. Please help me to bring down the runtime. Thanks in advance.


text:
Q: Indexed CollectionView in Swift I have a largely populated collectionView running in my project with a collectionView cell name in Alphabetic order.I am trying to achieve a indexed collectionView like how the index function works in tableView.Please someone point me a direction where to start...
Thanks in Advance.

A: The BDKCollectionIndexView would be a great solution to your problem.
https://github.com/kreeger/BDKCollectionIndexView
This basically create a similar indexing UI to that of the UITableview.
This is an example code posted by the creator.
override func viewDidLoad() {
    super.viewDidLoad()

    let indexWidth = 28
    let frame = CGRect(x: collectionView.frame.size.width - indexWidth,
        y: collectionView.frame.size.height,
        width: indexWidth,
        height: collectionView.frame.size.height)
    var indexView = BDKCollectionIndexView(frame: frame, indexTitles: nil)
    indexView.autoresizingMask = .FlexibleHeight | .FlexibleLeftMargin
    indexView.addTarget(self, action: "indexViewValueChanged:", forControlEvents: .ValueChanged)
    view.addSubview(indexView)
}

func indexViewValueChanged(sender: BDKCollectionIndexView) {
    let path = NSIndexPath(forItem: 0, inSection: sender.currentIndex)
    collectionView.scrollToItemAtIndexPath(path, atScrollPosition: .Top, animated: false)
    // If you're using a collection view, bump the y-offset by a certain number of points
    // because it won't otherwise account for any section headers you may have.
    collectionView.contentOffset = CGPoint(x: collectionView.contentOffset.x,
        y: collectionView.contentOffset.y - 45.0)
}

This question is also a possible duplicate:
SectionIndexTitles for a UICollectionView


text:
Q: Emoji not showing in Swift I am trying to show emojis coming from JSON response. It work fine when we don't have 0⃣1⃣3⃣5⃣ in below string and does not work with below string.
var titleLabelString = \ud83d\ude0a\ud83d\ude18\u2626\ufe0f 0⃣1⃣3⃣5⃣

Function I am using:
extension String {
    var decodeEmoji: String? {
      let data = self.data(using: String.Encoding.utf8,allowLossyConversion: false);
      let decodedStr = NSString(data: data!, encoding: String.Encoding.nonLossyASCII.rawValue)
      if decodedStr != nil{
        return decodedStr as String?
    }
      return self
}
}

Using it like:
titleLabelString = titleLabelString.decodeEmoji!

What is wrong in this?

A: The code points you have shown in the comment:
U+005C U+0075 U+0064 U+0038 U+0033 U+0064 U+005C U+0075 U+0064 U+0065 U+0030 U+0061 U+005C U+0075 U+0064 U+0038 U+0033 U+0064 U+005C U+0075 U+0064 U+0065 U+0031 U+0038 U+005C U+0075 U+0064 U+0038 U+0033 U+0064 U+005C U+0075 U+0064 U+0065 U+0030 U+0032 U+0035 U+FE0F U+20E3 U+0033 U+FE0F U+20E3 U+0031 U+FE0F U+20E3 U+0030 U+FE0F U+20E3

represents a string like this:
\ud83d\ude0a\ud83d\ude18\ud83d\ude025⃣3⃣1⃣0⃣
(Seems you have chosen another string than in your question.)
As a valid String literal in Swift, it becomes:
"\\ud83d\\ude0a\\ud83d\\ude18\\ud83d\\ude02\u{0035}\u{FE0F}\u{20E3}\u{0033}\u{FE0F}\u{20E3}\u{0031}\u{FE0F}\u{20E3}\u{0030}\u{FE0F}\u{20E3}"

Anyway, you have a string where non-BMP characters are represented with JSON-string like escaped sequence. And your decodeEmoji cannot convert them into valid characters.
You can forcefully convert such strings:
extension String {
    var jsonStringRedecoded: String? {
        let data = ("\""+self+"\"").data(using: .utf8)!
        let result = try! JSONSerialization.jsonObject(with: data, options: .allowFragments) as! String
        return result
    }
}

(If your string may contain some more meta-characters, you may need to modify this code.)
var titleLabelString = "\\ud83d\\ude0a\\ud83d\\ude18\\ud83d\\ude02\u{0035}\u{FE0F}\u{20E3}\u{0033}\u{FE0F}\u{20E3}\u{0031}\u{FE0F}\u{20E3}\u{0030}\u{FE0F}\u{20E3}"

print(titleLabelString.jsonStringRedecoded) //->5⃣3⃣1⃣0⃣

But generally, usual JSON decoder can decode non-BMP characters (including emojis). So, if you get this sort of string from JSON response,

*

*Your server may be sending invalid JSON response

or

*

*You may be using a broken JSON decoder

You should better check these things before using forced re-decoding.


text:
Q: Plot a function with very small values, close to zero I want to plot a function with very small values, close to zero, but even though the limit is -3/2 as x->0, I can't get any graphs. So I'm wondering if I could really get any graphs with any modifications in the Plot command options.
Limit[15 Integrate[Cos[t^2] - 1, {t, 0, x^ 3}]/x^15, x -> 0, Direction -> "FromAbove"]
(* Ans: -3/2*)
Plot[{15 NIntegrate[(Cos[t^2] - 1), {t, 0, x^3}, MinRecursion -> 4]/x^15, -3/2}, {x, -0.001, 0}]

Edit: The function and  series representation is
$\dfrac{15\int_{0}^{x^3}(\cos (t^2)-1)\, dt  }{x^{15}}=-\dfrac{3}{2}+\dfrac{5 x^{12}}{72}+O\left(x^{16}\right)$


text:
Q: How to make () become [] in the environments of theorem, definition and example in beamer? A MNW is as follows:
\documentclass[notheorems]{ctexbeamer}
\usetheme{Antibes}
\usepackage{amsmath,amsfonts,amssymb,comment}
\theoremstyle{theorem}
\newtheorem{theorem}{定理}
\newtheorem{lemma}[theorem]{引理}
\newtheorem{corollary}[theorem]{推论}
\newtheorem{proposition}[theorem]{命题}
\newtheorem{exercise}[theorem]{习题}
\theoremstyle{definition}
\newtheorem{definition}[theorem]{定义}
\theoremstyle{example}
\newtheorem{remark}[theorem]{评注}
\newtheorem{example}[theorem]{示例}
\setbeamertemplate{theorems}[numbered]

\begin{document}
\begin{frame}\frametitle{experiment}
\begin{theorem}[外国人]
    定理的本质意义呢?many 2
\end{theorem}

\begin{definition}
    令其有限。
\end{definition}

\begin{remark}[中国]
    $\mathbb{N}$是一个无穷集。
\end{remark}

\end{frame}

\end{document}

It is compiled as

My QUESTION is:

*

*How to make () containing theorem notes become [] in the environments of theorem, definition and example?

I tried a lot but failed. So any help is welcome!

A: To answer your first question:
The () are hard coded in the theorem begin template. To change it, redefine the template.
\documentclass[notheorems]{beamer}

\usetheme{Antibes}
\usepackage{amsmath,amsfonts,amssymb,comment}
\newtheorem{theorem}{Theorem}

\setbeamertemplate{theorems}[numbered]

\makeatletter
\setbeamertemplate{theorem begin}
{%
  \begin{\inserttheoremblockenv}
    {%
      \inserttheoremname
      \inserttheoremnumber
      \ifx\inserttheoremaddition\@empty\else\ [\inserttheoremaddition]\fi%
    }%
}

\makeatother

\begin{document}
\begin{frame}
\frametitle{experiment}

\begin{theorem}[name]
    text
\end{theorem}

\end{frame}
\end{document}


text:
Q: Error in Android Studio for library not solved UNEXPECTED TOP-LEVEL EXCEPTION: My gradle file code is here.
 apply plugin: 'com.android.application' android {
     compileSdkVersion 23
     buildToolsVersion "23.0.1"

     defaultConfig {
         applicationId "com.preciseit.trackusdown"
         minSdkVersion 14
         targetSdkVersion 23

     }

     buildTypes {
         release {
             minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
         }
     } } dependencies {
     compile files('libs/activation.jar')
     compile files('libs/additionnal.jar')
     compile files('libs/ksoap2-android-assembly-2.5.8-jar-with-dependencies.jar')
     compile files('libs/mail.jar')
     compile project(":library")    // compile project(":backend")    // compile 'com.nineoldandroids:library:2.4.0'

     compile 'com.android.support:appcompat-v7:23.1.1'
     compile 'com.android.support:support-v4:23.1.1'
     //compile 'com.daimajia.androidanimations:library:1.0.3@aar'
     compile 'com.android.support:recyclerview-v7:23.1.1'
     compile 'com.google.android.gms:play-services:8.1.0'
     compile 'com.squareup.retrofit:retrofit:1.9.0'
     compile 'com.loopj.android:android-async-http:1.4.9'    // compile 'com.squareup.picasso:picasso:2.5.2'
     //compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.1'

 }

Error is :
Information:Gradle tasks
[:app:generateDebugSources, :app:generateDebugAndroidTestSources, :app:assembleDebug] :app:preBuild
UP-TO-DATE :app:preDebugBuild
UP-TO-DATE :app:checkDebugManifest :app:preReleaseBuild
UP-TO-DATE :library:compileLint :library:copyReleaseLint
UP-TO-DATE :library:preBuild
UP-TO-DATE :library:preReleaseBuild
UP-TO-DATE :library:checkReleaseManifest :library:preDebugAndroidTestBuild
UP-TO-DATE :library:preDebugBuild
UP-TO-DATE :library:preDebugUnitTestBuild
UP-TO-DATE :library:preReleaseUnitTestBuild
UP-TO-DATE :library:prepareComAndroidSupportSupportV42221Library
UP-TO-DATE :library:prepareReleaseDependencies :library:compileReleaseAidl \n
UP-TO-DATE :library:compileReleaseRenderscript
UP-TO-DATE :library:generateReleaseBuildConfig
UP-TO-DATE :library:generateReleaseAssets
UP-TO-DATE :library:mergeReleaseAssets
UP-TO-DATE :library:generateReleaseResValues
UP-TO-DATE :library:generateReleaseResources
UP-TO-DATE :library:mergeReleaseResources
UP-TO-DATE :library:processReleaseManifest
UP-TO-DATE :library:processReleaseResources
UP-TO-DATE :library:generateReleaseSources
UP-TO-DATE :library:processReleaseJavaRes
UP-TO-DATE :library:compileReleaseJavaWithJavac
UP-TO-DATE :library:extractReleaseAnnotations
UP-TO-DATE :library:mergeReleaseProguardFiles
UP-TO-DATE :library:packageReleaseJar
UP-TO-DATE :library:compileReleaseNdk
UP-TO-DATE :library:packageReleaseJniLibs
UP-TO-DATE :library:packageReleaseLocalJar
UP-TO-DATE :library:packageReleaseRenderscript
UP-TO-DATE :library:packageReleaseResources
UP-TO-DATE :library:bundleRelease
UP-TO-DATE :app:prepareComAndroidSupportAppcompatV72311Library
UP-TO-DATE :app:prepareComAndroidSupportMediarouterV72220Library
UP-TO-DATE :app:prepareComAndroidSupportRecyclerviewV72311Library
UP-TO-DATE :app:prepareComAndroidSupportSupportV42311Library
UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServices810Library
UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesAds810Library
UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesAnalytics810Library
UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesAppindexing810Library
UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesAppinvite810Library
UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesAppstate810Library
UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesBase810Library
UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesBasement810Library
UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesCast810Library
UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesDrive810Library
UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesFitness810Library
UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesGames810Library
UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesGcm810Library
UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesIdentity810Library
UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesLocation810Library
UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesMaps810Library
UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesMeasurement810Library
UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesNearby810Library
UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesPanorama810Library
UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesPlus810Library
UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesSafetynet810Library
UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesVision810Library
UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesWallet810Library
UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesWearable810Library
UP-TO-DATE :app:prepareTrackerFinalLibraryUnspecifiedLibrary
UP-TO-DATE :app:prepareDebugDependencies :app:compileDebugAidl
UP-TO-DATE :app:compileDebugRenderscript
UP-TO-DATE :app:generateDebugBuildConfig
UP-TO-DATE :app:generateDebugAssets
UP-TO-DATE :app:mergeDebugAssets
UP-TO-DATE :app:generateDebugResValues
UP-TO-DATE :app:generateDebugResources
UP-TO-DATE :app:mergeDebugResources
UP-TO-DATE :app:processDebugManifest
UP-TO-DATE :app:processDebugResources
UP-TO-DATE :app:generateDebugSources
UP-TO-DATE :app:preDebugAndroidTestBuild
UP-TO-DATE :app:prepareDebugAndroidTestDependencies :app:compileDebugAndroidTestAidl
UP-TO-DATE :app:processDebugAndroidTestManifest
UP-TO-DATE :app:compileDebugAndroidTestRenderscript
UP-TO-DATE :app:generateDebugAndroidTestBuildConfig
UP-TO-DATE :app:generateDebugAndroidTestAssets
UP-TO-DATE :app:mergeDebugAndroidTestAssets
UP-TO-DATE :app:generateDebugAndroidTestResValues
UP-TO-DATE :app:generateDebugAndroidTestResources
UP-TO-DATE :app:mergeDebugAndroidTestResources
UP-TO-DATE :app:processDebugAndroidTestResources
UP-TO-DATE :app:generateDebugAndroidTestSources
UP-TO-DATE :app:processDebugJavaRes
UP-TO-DATE :app:compileDebugJavaWithJavac
UP-TO-DATE :app:compileDebugNdk
UP-TO-DATE :app:compileDebugSources
UP-TO-DATE :app:preDexDebug warning: Ignoring InnerClasses attribute for an anonymous inner class

(org.ksoap2.transport.KeepAliveHttpsTransportSE$1) that doesn't come with an associated EnclosingMethod attribute. This class was probably produced by a compiler that did not target the modern .class file format. The recommended solution is to recompile the class from source, using an
UP-TO-DATE compiler and without specifying any "-target" type options. The consequence of ignoring this warning is that reflective operations on this class will incorrectly indicate that it is *not* an inner class. :app:dexDebug UNEXPECTED TOP-LEVEL

EXCEPTION: com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536
at com.android.dx.merge.DexMerger$6.updateIndex(DexMerger.java:502)
at com.android.dx.merge.DexMerger$IdMerger.mergeSorted(DexMerger.java:277)
at com.android.dx.merge.DexMerger.mergeMethodIds(DexMerger.java:491)
at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:168)
at com.android.dx.merge.DexMerger.merge(DexMerger.java:189)
at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:502)
at com.android.dx.command.dexer.Main.runMonoDex(Main.java:334)
at com.android.dx.command.dexer.Main.run(Main.java:277)
at com.android.dx.command.dexer.Main.main(Main.java:245)
at com.android.dx.command.Main.main(Main.java:106) Error:Execution failed for task ':app:dexDebug'.

com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.7.0_79\bin\java.exe'' finished with non-zero exit value 2 Information:BUILD FAILED Information:Total time:
50.233 secs Information:1 error Information:0 warnings Information:See complete output in console

A: You have problem of multidex file so please add below dependency to your app Gradle file.
compile 'com.android.support:multidex:1.0.1'

Also add this line:
defaultConfig {

    applicationId 'pkg'
    minSdkVersion
    targetSdkVersion
    versionCode
    versionName

    // Enable MultiDexing:  https://developer.android.com/tools/building/multidex.html
    multiDexEnabled true
}

Also add below in Manifest.xml :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.multidex.myapplication">
    <application
        ...
        android:name="android.support.multidex.MultiDexApplication">
        ...
    </application>
</manifest>

Edited :
Try the following:

*

*Change setting

Ctrl + Alt + S -> Compiler -> Gradle

InVM Options field write:

-Xmx2048m -XX:MaxPermSize=512m

*Add in gradle

dexOptions {
          javaMaxHeapSize "2g"
      }

Thanks..!!


text:
Q: How to best tackle sharing of state between components in same view I have a projects view that contains 3 components, <project-item>, <project-list> and <project-view>. All of these components need to be aware of the selected projects.

*

*<project-item> holds the state for a particular project. This component has a property called selected which determines if the project is selected or not.

*<project-list> houses one or more project-items and has a computed property which checks the children are of type <project-item> and which items are selected.

*<project-view> is the general view which just contains navigation and logic associated UAC.

The hierarchy looks like this...
<project-view>
    <project-list>
        <project-item selected></project-item>
    </project-list>
</project-view>

What would be the best way of sharing that state as i feel vuex is the wrong choice here as it's not global state.
I also have tried to use a computed property on the <project-view> component to get the selected items on the <project-list> component but it throws errors despite existing and being in scope.

A: If you think that Vuex is overkill, then check my answer here - pretty same topic
VueJS access child component's data from parent

A: Vuex is your answer.
https://vuex.vuejs.org/en/intro.html
This is the solution for the sharing of states.
You will create the store, connect your states with store and use actions/mutations to work with them.
It will give you great foundation for state sharing which, if you will need to, you will easily scale up.
Good luck!


text:
Q: sns.pairplot shows density curve instead of histogram My understanding is that the below code shall produce histograms in the diagonal boxes. Instead, I am getting density curves? Why is this? If I remove 'hue','palette' and 'diag_kws', it produces histograms as expected. Any inputs?
sns.pairplot(data=ins_pre,
        vars=["fatal_collisions", "premiums",'insurance_losses'],
        kind='scatter',
        hue='Region',
        palette='RdBu',
        diag_kws={'alpha':.5})

plt.show()
plt.clf()

Plot the same data but remove 'hue','palette' and 'diag_kws'
sns.pairplot(data=ins_pre,
        vars=["fatal_collisions", "premiums",'insurance_losses'],
        kind='scatter')

plt.show()
plt.clf()

A: from the documentation:

seaborn.pairplot(data, hue=None, hue_order=None, palette=None, vars=None, x_vars=None,
y_vars=None, kind='scatter', diag_kind='auto', markers=None, height=2.5, aspect=1,
corner=False, dropna=True, plot_kws=None, diag_kws=None, grid_kws=None, size=None)

[...]

diag_kind{'auto', 'hist', 'kde', None}, optional
Kind of plot for the diagonal subplots. The default depends on whether "hue" is used or not.

So, you should call the function like so:
sns.pairplot(data=ins_pre,
        vars=["fatal_collisions", "premiums",'insurance_losses'],
        kind='scatter',
        hue='Region',
        palette='RdBu',
        diag_kind='hist')


text:
Q: Android ksoap2 namespace prefix I am writing an Android application that needs to use a wcf SOAP web service using ksoap2.
The data being passed to the web service needs to match that data being sent from ASP.Net
ASP.Net SOAP
<v:Envelope xmlns:i="http://www.w3.org/1999/XMLSchema-instance" xmlns:d="http://www.w3.org/1999/XMLSchema" xmlns:c="http://schemas.xmlsoap.org/soap/encoding/" xmlns:v="http://schemas.xmlsoap.org/soap/envelope/">
  <v:Header />
  <v:Body>
    <SaveWaybill xmlns="ClearNamespace">
      <crossWayBill xmlns:n0="http://schemas.datacontract.org/2004/07/CrossWCFService">
        <n0:WayNo>095-090317-1133</n0:WayNo>
        <n0:FinishDateTime>2017-03-09T11:36:03.000Z</n0:FinishDateTime>
        <n0:StartDateTime>2017-03-09T11:33:56.000Z</n0:StartDateTime>
      </crossWayBill>
      <crossWayBillBreakdownItems xmlns:n1="http://schemas.datacontract.org/2004/07/CrossWCFService">
        <n1:CrossService.CrossWaybillBreakdownItem>
          <n1:WayBillItemId>1</n1:WayBillItemId>
          <n1:Quantity>10</n1:Quantity>
        </n1:CrossService.CrossWaybillBreakdownItem>
        <n1:CrossService.CrossWaybillBreakdownItem>
          <n1:WayBillItemId>2</n1:WayBillItemId>
          <n1:Quantity>20</n1:Quantity>
        </n1:CrossService.CrossWaybillBreakdownItem>
        <n1:CrossService.CrossWaybillBreakdownItem>
          <n1:WayBillItemId>3</n1:WayBillItemId>
          <n1:Quantity>30</n1:Quantity>
        </n1:CrossService.CrossWaybillBreakdownItem>
        <n1:CrossService.CrossWaybillBreakdownItem>
          <n1:WayBillItemId>4</n1:WayBillItemId>
          <n1:Quantity>40</n1:Quantity>
        </n1:CrossService.CrossWaybillBreakdownItem>
        <n1:CrossService.CrossWaybillBreakdownItem>
          <n1:WayBillItemId>5</n1:WayBillItemId>
          <n1:Quantity>50</n1:Quantity>
        </n1:CrossService.CrossWaybillBreakdownItem>
      </crossWayBillBreakdownItems>
    </SaveWaybill>
  </v:Body>
</v:Envelope>

Java code
SoapObject waybill = new SoapObject("", "crossWayBill");
waybill.addProperty("WayNo", WaybillNumber);
waybill.addProperty("FinishDateTime", FinishDateTime);
waybill.addProperty("StartDateTime", StartDateTime);

SoapObject breakdown = new SoapObject("", "crossWayBillBreakdownItems");
SoapObject counter;
for (XmlNode node : xmlNodes) {
    if (node.node.equalsIgnoreCase("WaybillItemCount")) {
        if (node.nodeHasAttriute()) {
            counter = new SoapObject("", "CrossService.CrossWaybillBreakdownItem");
            counter.addProperty("WayBillItemId", WayBillItemId);
            counter.addProperty("Quantity", Quantity);
            breakdown.addSoapObject(counter);
        }
    }
}

SoapSerializationEnvelope envelope;
try {
    String returnValue = "";
    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

    request.addProperty("crossWayBill", waybill);
    request.addProperty("crossWayBillBreakdownItems", breakdown);

    envelope = new SoapSerializationEnvelope(SoapEnvelope.VER10);

    envelope.dotNet = true;
    envelope.implicitTypes = true;
    envelope.setOutputSoapObject(request);
    envelope.setAddAdornments(false);

    MarshalDate md = new MarshalDate();
    md.register(envelope);

    HttpTransportSE androidHttpTransport = new HttpTransportSE(URI);
    androidHttpTransport.debug = true;
    try {
        androidHttpTransport.call(SOAP_ACTION, envelope);
        Log.d(">>----> request dump", androidHttpTransport.requestDump);
        Log.d("<----<< response dump", androidHttpTransport.responseDump);
    } catch (HttpResponseException ex) {
        Log.e("androidHttpTransport", "doInBackground: Error:\n" + ex.getMessage());
    } catch (XmlPullParserException e1) {
        e1.printStackTrace();
    }

    SoapPrimitive result = (SoapPrimitive) envelope.getResponse();
} catch (Exception e) {
    Log.e("GeneralError", "doInBackground: Error:\n" + e.getMessage());
}

With the above code, I get the following: -
<v:Envelope xmlns:i="http://www.w3.org/1999/XMLSchema-instance" xmlns:d="http://www.w3.org/1999/XMLSchema" xmlns:c="http://schemas.xmlsoap.org/soap/encoding/" xmlns:v="http://schemas.xmlsoap.org/soap/envelope/">
  <v:Header />
  <v:Body>
    <SaveWaybill xmlns="ClearNamespace">
      <crossWayBill>
        <WayNo>095-090317-1133</WayNo>
        <StartDateTime>09-Mar-2017 11:33:56</StartDateTime>
        <FinishDateTime>09-Mar-2017 11:36:03</FinishDateTime>
      </crossWayBill>
      <crossWayBillBreakdownItems>
        <CrossService.CrossWaybillBreakdownItem>
          <WayBillId>0</WayBillId>
          <WayBillItemId>1</WayBillItemId>
          <Quantity>0</Quantity>
        </CrossService.CrossWaybillBreakdownItem>
        <CrossService.CrossWaybillBreakdownItem>
          <WayBillId>0</WayBillId>
          <WayBillItemId>2</WayBillItemId>
          <Quantity>0</Quantity>
        </CrossService.CrossWaybillBreakdownItem>
        <CrossService.CrossWaybillBreakdownItem>
          <WayBillId>0</WayBillId>
          <WayBillItemId>3</WayBillItemId>
          <Quantity>0</Quantity>
        </CrossService.CrossWaybillBreakdownItem>
        <CrossService.CrossWaybillBreakdownItem>
          <WayBillId>0</WayBillId>
          <WayBillItemId>4</WayBillItemId>
          <Quantity>0</Quantity>
        </CrossService.CrossWaybillBreakdownItem>
        <CrossService.CrossWaybillBreakdownItem>
          <WayBillId>0</WayBillId>
          <WayBillItemId>5</WayBillItemId>
          <Quantity>0</Quantity>
        </CrossService.CrossWaybillBreakdownItem>
      </crossWayBillBreakdownItems>
    </SaveWaybill>
  </v:Body>
</v:Envelope>

When I specify a namespace on the following 2 lines,
SoapObject waybill = new SoapObject(CROSS_NAMESPACE, "crossWayBill");
SoapObject breakdown = new SoapObject(CROSS_NAMESPACE, "crossWayBillBreakdownItems");

I get: -
<v:Envelope xmlns:i="http://www.w3.org/1999/XMLSchema-instance" xmlns:d="http://www.w3.org/1999/XMLSchema" xmlns:c="http://schemas.xmlsoap.org/soap/encoding/" xmlns:v="http://schemas.xmlsoap.org/soap/envelope/">
  <v:Header />
  <v:Body>
    <SaveWaybill xmlns="ClearNamespace">
      <n0:crossWayBill xmlns:n0="http://schemas.datacontract.org/2004/07/CrossWCFService">
        <WayNo>095-090317-1133</WayNo>
        <StartDateTime>09-Mar-2017 11:33:56</StartDateTime>
        <FinishDateTime>09-Mar-2017 11:36:03</FinishDateTime>
      </n0:crossWayBill>
      <n1:crossWayBillBreakdownItems xmlns:n1="http://schemas.datacontract.org/2004/07/CrossWCFService">
        <CrossService.CrossWaybillBreakdownItem>
          <WayBillId>0</WayBillId>
          <WayBillItemId>1</WayBillItemId>
          <Quantity>0</Quantity>
        </CrossService.CrossWaybillBreakdownItem>
        <CrossService.CrossWaybillBreakdownItem>
          <WayBillId>0</WayBillId>
          <WayBillItemId>2</WayBillItemId>
          <Quantity>0</Quantity>
        </CrossService.CrossWaybillBreakdownItem>
        <CrossService.CrossWaybillBreakdownItem>
          <WayBillId>0</WayBillId>
          <WayBillItemId>3</WayBillItemId>
          <Quantity>0</Quantity>
        </CrossService.CrossWaybillBreakdownItem>
        <CrossService.CrossWaybillBreakdownItem>
          <WayBillId>0</WayBillId>
          <WayBillItemId>4</WayBillItemId>
          <Quantity>0</Quantity>
        </CrossService.CrossWaybillBreakdownItem>
        <CrossService.CrossWaybillBreakdownItem>
          <WayBillId>0</WayBillId>
          <WayBillItemId>5</WayBillItemId>
          <Quantity>0</Quantity>
        </CrossService.CrossWaybillBreakdownItem>
      </n1:crossWayBillBreakdownItems>
    </SaveWaybill>
  </v:Body>
</v:Envelope>

How can I get the namespace declaration (xmlns:n0="...") to appear on the crossWayBill & crossWayBillBreakdownItems nodes and have the prefix (n0:) appear on all child nodes but not on the crossWayBill & crossWayBillBreakdownItems nodes?

A: I got what I wanted by cheating...
Instead of specifying a namespace, I added an attribute to the SoapObject and hard coded the prefix onto the child nodes.
SoapObject waybill = new SoapObject("", "crossWayBill");
waybill.addAttribute("xmlns:n0", "http://schemas.datacontract.org/2004/07/CrossWCFService");
waybill.addProperty("n0:WayNo", WaybillNumber);
waybill.addProperty("n0:FinishDateTime", FinishDateTime);
waybill.addProperty("n0:StartDateTime", StartDateTime);

This gives me the below and my soap request is accepted by the web service
<SaveWaybill xmlns="ClearNamespace">
  <crossWayBill xmlns:n0="http://schemas.datacontract.org/2004/07/CrossWCFService">
    <n0:WayNo>095-090317-1133</n0:WayNo>
    <n0:FinishDateTime>2017-03-09T11:36:03.000Z</n0:FinishDateTime>
    <n0:StartDateTime>2017-03-09T11:33:56.000Z</n0:StartDateTime>
  </crossWayBill>


text:
Q: My database won't accept strings with letters I'm using Mariadb and have the table setup with VARCHAR(30). When I insert a string containing numbers like "192" and then select it I'm able to print out 192. When I insert a string like "a48" it just seems to be ignored. I've tried inserting a complete letter string "a" and I still get nothing. In the Mariadb documentation for VARCHAR(M) I found this:
"If a unique index consists of a column where trailing pad characters are stripped or ignored, inserts into that column where values differ only by the number of trailing pad characters will result in a duplicate-key error"
I'm not sure if that could have anything to do with it? I am using letters just to make it easier to parse the data on my client side program. If I don't find a solution I will probably just pad it on the server after selecting.
Does anybody have any suggestions on what's going on here, or things I could try to find the problem?

A: Assuming that melon is the column to receive the string, then you should put single quotes around the $melon variable in the query, like this:
query("REPLACE INTO state (id, melon, image) VALUES (1, '$melon', $image)");

String values should be surrounded by single quotes; numeric values don't need to be.
Because the target column is a varchar(30) the value should always be surrounded by single quotes.  MariaDB works out what you mean when you supply a numeric value, but it doesn't understand an alphanumeric value without single quotes.  Both will work if you use single quotes, as shown.
To avoid SQL injection errors, it is better to use prepared statements, as described at https://www.w3schools.com/php/php_mysql_prepared_statements.asp.


text:
Q: Can someone help me why my program is printing a random number? I am learning to code in C and I need to create a program which sorts out numbers in an array by even numbers first and then the uneven. The numbers don't have to be sorted smallest to largest. The first entered numbers is supposed to be the size of the array. I managed to figure it out but one number is always missing and presented with a random number. Am i missing something ?
int a[101], a2[101], i, j, n, k = 0;
scanf ("%d", &n);

for (i = 0; i < n; i++)
scanf ("%d", &a[i]);

for (i = 0; i < n; i++)
{
    if (a[i]%2 == 0)
        {
        if (a[i] == 0)
            {
                a2[k] = a[i];
                k++;
                continue;
            }
        a2[k] = a[i];
        k++;
        }
}

for (i = 0; i < n; i++)
{
    if (a[i]%2 != 0)
    {
        a2[k] = a[i];
        k++;
    }
}

for (i = 0; i < n; i++)
    printf ("%d ", a2[i]);

return 0;

I enter the following numbers:
6
1 3 2 5 8 10
I should get:
2 8 10 1 3 5
What I'm getting:
2 8 10 1 3 508
I tried with other combinations too, problem persists but with different number.

A: Checked your code several time its written well and worked well too. The extra 08 after 5 may be printed by something else. You can use a newline after printing all the element of ara2 to make sure the 08 is printed form any element of ara2 or not. like this:
for (i = 0; i < n; i++)
    printf ("%d ", a2[i]);
printf("\n");

And one more thing. There are no need to add the bellow portion in your code. The code will work same even if you don't add this.
    if (a[i] == 0)
        {
            a2[k] = a[i];
            k++;
            continue;
        }

Happy Coding.