text:
Q: A good counter text on nonlinear optimization I am currently taking a nonlinear optimization course and the textbook is Bertsekas's Nonlinear Programming (2nd edition). I think the book does a decent job, but I am a much more "hands-on" and visual learner so I'm looking for an additional book with worked examples, visuals explaining concepts, etc.
I've done some searching myself but I thought I'd get some recommendations from real mathematicians-- or people that share my learning disability. :)
Thanks!

A: Some good books on nonlinear optimization:
1. Boris T. Polyak, Introduction to Optimization
The field of nonlinear optimization has benefited from several important
ideas developed in the Soviet Union. Some of these ideas underwent a
parallel development in the West, but others received inadequate attention
in English language textbooks. For this reason the publication of the
present book by a principal Soviet contributor is particularly valuable.
It represents what is probably the first comprehensive synthesis of the
nonlinear programming methodologies that are popular in the West and the
Soviet Union.
The reader will find here a systematic treatment of both classical
subjects, and topics little covered elsewhere—such as nondifferentiable
optimization, degenerate problems, and stochastic optimization methods.
Beyond this, however, this text has many significant merits. It gives
careful attention to both mathematical rigor and practical relevance. The
convergence analysis of numerical methods is done in a unified manner. A
systematic effort is made to chart the limits of the methodology by
providing performance analysis on difficult problems. There is a thoughtful
discussion of the practical solution process. A wealth of new or little
known material is included in the text and the exercises. Above all, the
book is written by a true expert with a refined understanding of the nature,
purpose, and limitations of nonlinear optimization and applied mathematics
in general.
2. Olvi L. Mangasarian, Nonlinear Programming
Twenty-five years have passed since the original edition of this book appeared; however, the topics covered are still timely and currently taught at the University
of Wisconsin as well as many other major institutions. At Wisconsin
these topics are taught in a course jointly listed by the Computer
Sciences, Industrial Engineering, and Statistics departments. Students
from these and other disciplines regularly take this course. Each
year I get a number of requests from the United States and abroad
for copies of the book and for permission to reproduce reserve
copies for libraries. I was therefore pleased when SIAM approached
me with a proposal to reprint the book in its Classics series. I believe
that this book is an appropriate choice for this series inasmuch as
it is a concise, igorous, yet  accessible account o ' the fundamentals
of constrained optimization theory that is useful to both the beginning
student as well as the active  researcher. I am appreciative that SIAM
has chosen to publish the book and to make the corrections that I
supplied. I am especially grateful to Vickie Kearn and Ed Block for their friendly and professional handling of the publication process. My hope is that the mathematical
programming community will benefit from this endeavor.
3. David G. Luenberger, Linear and Nonlinear Programming
This book is intended as a text covering the central concepts of practical optimization
techniques. It is designed for either self-study by professionals or classroom work at
the undergraduate or graduate level for students who have a technical background
in engineering, mathematics, or science. Like the field of optimization itself,
which involves many classical disciplines, the book should be useful to system
analysts, operations researchers, numerical analysts, management scientists, and
other specialists from the host of disciplines from which practical optimization applications
are drawn. The prerequisites for convenient use of the book are relatively
modest; the prime requirement being some familiarity with introductory elements
of linear algebra. Certain sections and developments do assume some knowledge
of more advanced concepts of linear algebra, such as eigenvector analysis, or some
background in sets of real numbers, but the text is structured so that the mainstream
of the development can be faithfully pursued without reliance on this more advanced
background material.
Although the book covers primarily material that is now fairly standard, it
is intended to reflect modern theoretical insights. These provide structure to what
might otherwise be simply a collection of techniques and results, and this is valuable
both as a means for learning existing material and for developing new results. One
major insight of this type is the connection between the purely analytical character
of an optimization problem, expressed perhaps by properties of the necessary conditions,
and the behavior of algorithms used to solve a problem. This was a major
theme of the first edition of this book and the second edition expands and further
illustrates this relationship.
As in the second edition, the material in this book is organized into three
separate parts. Part I is a self-contained introduction to linear programming, a key
component of optimization theory. The presentation in this part is fairly conventional,
covering the main elements of the underlying theory of linear programming,
many of the most effective numerical algorithms, and many of its important special
applications. Part II, which is independent of Part I, covers the theory of unconstrained
optimization, including both derivations of the appropriate optimality conditions
and an introduction to basic algorithms. This part of the book explores the
general properties of algorithms and defines various notions of convergence. Part III
extends the concepts developed in the second part to constrained optimization problems. Except for a few isolated sections, this part is also independent of Part I.
It is possible to go directly into Parts II and III omitting Part I, and, in fact, the
book has been used in this way in many universities. Each part of the book contains
enough material to form the basis of a one-quarter course. In either classroom use
or for self-study, it is important not to overlook the suggested exercises at the end of
each chapter. The selections generally include exercises of a computational variety
designed to test one's understanding of a particular algorithm, a theoretical variety
designed to test one's understanding of a given theoretical development, or of the
variety that extends the presentation of the chapter to new applications or theoretical
areas. One should attempt at least four or five exercises from each chapter. In
progressing through the book it would be unusual to read straight through from
cover to cover. Generally, one will wish to skip around. In order to facilitate this
mode, we have indicated sections of a specialized or digressive nature with an
asterisk∗.
There are several features of the revision represented by this third edition. In
Part I a new Chapter 5 is devoted to a presentation of the theory and methods
of polynomial-time algorithms for linear programming. These methods include,
especially, interior point methods that have revolutionized linear programming. The
first part of the book can itself serve as a modern basic text for linear programming.
Part II includes an expanded treatment of necessary conditions, manifested by
not only first- and second-order necessary conditions for optimality, but also by
zeroth-order conditions that use no derivative information. This part continues to
present the important descent methods for unconstrained problems, but there is new
material on convergence analysis and on Newton's methods which is frequently
used as the workhorse of interior point methods for both linear and nonlinear
programming. Finally, Part III now includes the global theory of necessary conditions
for constrained problems, expressed as zero-th order conditions. Also interior
point methods for general nonlinear programming are explicitly discussed within
the sections on penalty and barrier methods. A significant addition to Part III is
an expanded presentation of duality from both the global and local perspective.
Finally, Chapter 15, on primal–dual methods has additional material on interior
point methods and an introduction to the relatively new field of semidefinite
programming, including several examples.
We wish to thank the many students and researchers who over the years have
given us comments concerning the second edition and those who encouraged us to
carry out this revision.
4. A. D. Ioffe, V. M. Tikhomirov, Theory of Extremal Problems
In recent years, the efforts of many mathematicians have been directed
toward investigating the subject of extremal problems from a unified
viewpoint, selecting common features in the methods for treating these
problems, and developing the necessary mathematical apparatus. As a
result, it has become possible to speak of the development of the general
theory of extremal problems.
Three topics in this theory have now acquired fully developed outlines.
These are the questions of the mathematical foundations of the theory, the
necessary conditions for an extremum, and - although to a lesser extent -
the existence of solutions. The part of the theory that is devoted to
numerical optimization methods is rapidly developing. The theory of
sufficient conditions has not yet reached its finished stage, although there
too certain results of a general nature have been obtained.
In this book, we tbuch upon all of the above mentioned basic topics in
the theory of extremal problems except numerical methods. The first five
chapters of the book are devoted to the mathematical apparatus and to
necessary conditions for an extremum. Sufficient conditions are studied in
the seventh chapter. In the eighth and ninth chapters, we present theorems
on the existence of solutions of problems in the calculus of variations and
optimal control, together with the mathematical apparatus necessary for
the proofs of these theorems. In the sixth chapter, we derive from the
general theory developed in the preceding chapters consequences for
classes of problems with special structure, namely, for linear, convex,
quadratic, and discrete problems. The last, tenth chapter is devoted to
certain applications of the theory to the solution of specific problems. We
have also included a separate collection of problems, many of which are
given with solutions In choosing the material, we did not try to encompass all the latest
results. The main purpose of the book is to explain and review the methods
that have arisen in the theory of extremal problems, and to show how these
methods are applied in particular areas, such as mathematical programming,
calculus of variations and optimal control.
The initial stimulus to create a general theory of extremal problems was
provided by the efforts to place the Pontrjagin maximum principle within
an abstract framework. These efforts brought about the investigation of
problems with a mixed, partly smooth and partly convex, structure. In this
book, problems of this type are investigated in detail. There are also other
possible approaches to these problems, and time will show which of them
will prove to be most fruitful.
This book is intended primarily for graduate and postgraduate students,
and for scientists who work in the area of solving optimization problems. In
writing it, we have utilized the experience of teaching in the Department of
Mathematics and Mechanics at Moscow State University. We hope that the
book can be used as a text in VF-;OUS courses related to optimization given
in universities and technical colleges.
In order to fully understand all parts of the book, one should have a
university course in functional analysis, but much of its contents are
intended for a broader audience.
The point is that the formulations of a majority of the most important
theorems, which give recipies for solving problems, can be mastered with
substantially less mathematical background than required for the understanding
of proofs. Therefore, we have tried to organize the presentation in
such a way that the formulations of the main results, the general remarks
concerning them, and the solutions of prablems, be separate from the
proofs.
It is not necessary to read the chapters in their given order. Many
subjects can be studied independently of the other material. Let us indicate
several such possibilities. Sections 2.1, 2.2,2.4, and 6.4 form an elementary
course in the calculus of variations. In essence, these sections are based
only on facts from classical analysis. An initial course in linear and convex
programming is contained in 000.3, 1.3, 6.1, and 7.3. Chapter 1 and
007.1-7.3 are devoted to the subject "Necessary and sufficient conditions
for an extremum in minimization problems in linear spaces." Sections
2.1-2.3, 6.3, 7.4, 10.4, and Subsection 9.2.4 form an extended course in the
calculus of variations, although insufficient attention is given here to
Hamilton-Jacobi theory. In Chapter 8 and 449.1 a d 9.2, we treat the
questions of the existence of a solution to optimal control problems.
Chapter 8 together with 49.3 gives an idea of duality methods in optimal
control theory. Chapters 1-5, 8, and 9 form an extended course in optimal
control theory. Finally, Chapters 3, 4, and 8 contain a reasonably detailed
introduction to infinite-dimensional convex analysis.
At first, we planned to include in the book a number of other subjects,
such as extensions of variational problems, sliding and singular regimes,
and numerical methods. However, we have been unable to treat these
matters for lack of space. We should also mention several other problems
of importance which are not touched upon in the book. These concern
primarily the relationships between the calculus of variations and classical
mechanics, Hamilton-Jacobi theory, and dynamic programming.
In the remarks which conclude the Introduction, we indicate monographs
and articles that pertain to subjects which remain outside the scope
of this book.
In conclusion, we would like to express our gratitude to B.T. Poljak, who
kindly provided certain materials that helped in the development of our
approach to the classification of extremal problems. Our thanks go to M.A.
Krasnosel'skii, who looked over the manuscri,pt and made a number of
useful suggestions, and to V.M. Alekseev and S.V. Fomin, with whom we
discussed various matters related to the presentation of the material.
Numerous discusdons with A.A. Miljutin were of great importance to us.
We are grateful to A.V. Barykin, B. Luderer, G.G. Magaril-Il'jaev, E.S.
Polovinkin, M.A. Rvachev, V.M. Safro, M.I. Stesin, and to M. Tagiev, who
helped us with the preparation of the manuscript.


text:
Q: Possible number of L-tetrominoes in covering an $8 \times 8$ chessboard Assuming that we do not have T-tetrominoes in our play, what are the possible numbers of L-tetrominoes that can appear in a covering with tetrominoes?
I have proven that the number can be any even number, of course, there cannot be more than 16 since each tetromino has 4 grids and we have 64 grids.
I doubt the number can be odd but having a hard time proving it.
Any help?
Picture for all types of tetrominoes (Omitting T-tetromino):

A: Two L-tetrominoes can be used to cover a $2\times 4$ grid completely and a chessboard can be broken into such rectangles.

Color the columns of the $8\times 8$ chessboard alternatingly white and black.
The tetrominoes will cover the following number of colored squares in such a coloring.
$L$-tet covers $1\ W$, $3\ B$ or $3\ W,1\ B$.
$\mathrm{Straight}$-tet covers $4\ B/W$ or $2\ B,2\ W$
$\mathrm{Square}$-tet covers $2\ B,2\ W$.
$\mathrm{Skew}$-tet covers $2\ B,2\ W$.
Since the number of white and black squares to be colored will be $32$ each, there can't be an odd number of $L$-tetrominoes because they will cover an odd number of black, white squares.
Every other even number $0 \le n=2k \le 16$ is possible. Just cover $k$ '$2 \times 4$ grids' with them and arrange.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Finding recurrence relation on a problem I need a little bit help finding a recurrence relation. So it goes like this:
"A one-sided pavement is being made with tiles that come in 5 different colors. There are 3 light colors (light-yellow, light-green and light-red) and then there are 2 dark colors (dark-red and dark-blue). It is required that the total of tiles in light colors are an odd-number.
a) Find $a_1$ og $a_2$
b) Put forth a recurrence relation along with initial conditions for $a_n$.
c) Use the recurrence relation to calculate $a_5$
I am really stranded and don't know to do this. I have been trying to look at similar examples but can't seem to find this out. How many valid pavement can I make with the requirement met?

A: HINT: If you use only one tile, it must be a light-colored tile, so that you have an odd number of light-colored tiles; thus, $a_1=3$. If you use two tiles, exactly one must be light-colored, and you can arrange your two tiles in either order, so $a_2=\ldots\;$?
Now suppose that $n\ge 3$, and $T_1T_2\ldots T_n$ is an acceptable string of $n$ tiles, i.e., one with an odd number of light-colored tiles. Look at $T_n$, the last tile. If it's dark-colored, then $T_1T_2\ldots T_{n-1}$ is an acceptable string of $n-1$ tiles. There are $a_{n-1}$ of those, and there are $2$ dark colors, so this accounts for $2a_{n-1}$ acceptable strings of $n$ tiles, all those that end in a dark tile. What if $T_n$ is a light-colored tile? Then $T_1T_2\ldots T_{n-1}$ is an unacceptable string of $n-1$ tiles.

*

*How many strings of $n-1$ tiles are there altogether? Subtract $a_{n-1}$ from that to get the number of unacceptable ones.

*How many possibilities are there for $T_n$ in this case?

*In terms of $a_{n-1}$ how many acceptable strings of $n$ tiles are there in which the last tile is light-colored?

If you've answered all of those correctly, you should be able to write down the desired recurrence. (The numbers $a_n$ increase quite rapidly with $n$, but it's not hard to calculate $a_3$ and even $a_4$ directly to provide a check on the recurrence that you find.)


text:
Q: Thread exiting with uncaught exception, no errors I've been trying to implement in-app purchases to my app, but for some reason the app exits to homescreen everytime I try to start my test purchase.
08-04 18:01:00.659: W/dalvikvm(10597): threadid=17: thread exiting with uncaught exception (group=0x40fd32a0)
08-04 18:01:00.659: D/AndroidRuntime(10597): Shutting down VM
08-04 18:01:00.659: W/dalvikvm(10597): threadid=1: thread exiting with uncaught exception (group=0x40fd32a0)

This is my logcat, I do not get an error, so I don't know what I did wrong here..
Here's the .java that probably causes the error:
package com.mitonanetherlands.buttonchooser;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.IntentSender.SendIntentException;
import android.content.ServiceConnection;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.vending.billing.IInAppBillingService;
import com.mopub.mobileads.MoPubView;

public class BuyPremium extends Activity {

    public static int calculateInSampleSize(BitmapFactory.Options options,
            int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            // Calculate ratios of height and width to requested height and
            // width
            final int heightRatio = Math.round((float) height
                    / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);

            // Choose the smallest ratio as inSampleSize value, this will
            // guarantee
            // a final image with both dimensions larger than or equal to the
            // requested height and width.
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }

        return inSampleSize;
    }

    public static Bitmap decodeSampledBitmapFromResource(Resources res,
            int resId, int reqWidth, int reqHeight) {

        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res, resId, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth,
                reqHeight);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeResource(res, resId, options);
    }

    MoPubView ad1;
    SharedPreferences completedLevels;
    Bundle querySku = new Bundle();
    Bundle skuDetails;
    String sku;
    String price;
    Bundle buyIntentBundle;
    IInAppBillingService mService;
    ServiceConnection mServiceConn = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            mService = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mService = IInAppBillingService.Stub.asInterface(service);
        }
    };

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

        ImageView thankyou = (ImageView) findViewById(R.id.thankyou);
        thankyou.setImageBitmap(decodeSampledBitmapFromResource(getResources(),
                R.drawable.thank_you, 450, 600));
        ad1 = (MoPubView) findViewById(R.id.adviewpremium);
        ad1.setAdUnitId("d95782d0c22011e295fa123138070049");
        ad1.loadAd();
        bindService(new Intent(
                "com.android.vending.bulling.InAppBillingService.BIND"),
                mServiceConn, Context.BIND_AUTO_CREATE);

        Button backtomain = (Button) findViewById(R.id.BackToMenu);
        backtomain.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                startActivity(new Intent(
                        "com.mitonanetherlands.buttonchooser.MAINMENU"));
            }
        });

        Button BuyPremium = (Button) findViewById(R.id.BuyButton);
        BuyPremium.setOnClickListener(new View.OnClickListener() {

            @SuppressWarnings("unused")
            @Override
            public void onClick(View arg0) {
                ArrayList<String> skuList = new ArrayList<String>();
                skuList.add("pemiumUpgrade");

                querySku.putStringArrayList("premium_apartment_life", skuList);
                Thread myThread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Bundle skuDetails = mService.getSkuDetails(3,
                                    getPackageName(), "inapp", querySku);
                        } catch (RemoteException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                });
                myThread.start();
                int response = skuDetails.getInt("RESPONSE_CODE");
                if (response == 0) {
                   ArrayList<String> responseList
                      = skuDetails.getStringArrayList("DETAILS_LIST");

                   for (String thisResponse : responseList) {
                      JSONObject object = null;
                    try {
                        object = new JSONObject(thisResponse);
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                      try {
                        String sku = object.getString("productId");
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                      try {
                        String price = object.getString("price");
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                   }
                }
                try {
                    Bundle buyIntentBundle = mService.getBuyIntent(3, getPackageName(), sku, "inapp","Premium is aangekocht!");
                } catch (RemoteException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT");
                try {
                    startIntentSenderForResult(pendingIntent.getIntentSender(), 1001, new Intent(), Integer.valueOf(0),Integer.valueOf(0), Integer.valueOf(0));
                } catch (SendIntentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ad1.destroy();
        if (mServiceConn != null) {
            unbindService(mServiceConn);
        }
    }
    @SuppressWarnings("unused")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       if (requestCode == 1001) {
        int responseCode = data.getIntExtra("RESPONSE_CODE", 0);
          String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");
          String dataSignature = data.getStringExtra("INAPP_DATA_SIGNATURE");

          if (resultCode == RESULT_OK) {
             try {
                JSONObject jo = new JSONObject(purchaseData);
                String sku = jo.getString("productId");
                Toast.makeText(this,"You have bought the " + sku + ". Excellent choice!", Toast.LENGTH_LONG).show();
                SharedPreferences.Editor editor = completedLevels.edit();
                editor.putBoolean("Paid", true).commit();

              }
              catch (JSONException e) {
                    Toast.makeText(this,"Failed to Parse data", Toast.LENGTH_LONG).show();
                 e.printStackTrace();
              }
          }
       }
    }
}

Any Ideas?

A: There are several thing in your code that could have gone wrong.
One thing that is guaranteed to crash your app:
Bundle skuDetails = null;

public void onClick(View arg0) {
    int response = skuDetails.getInt("RESPONSE_CODE");
}

That's a guaranteed NullPointerException whenever you click. You intended that the thread assigns something to skuDetails already but does not:

*

*It uses it's own local variable: Bundle skuDetails = mService.get..

*Even if you would use the correct variable from within the thread it would not finish assigning a value to skuDetails at that point. It runs in parallel and there is no guarantee when it's done.

What you want to do here is either to do all the processing within that background thread (everything that's done in onclick after starting the thread) or to use an AsyncTask that reads and processes in background (doInBackground) then uses the processed data within the UI thread to do final steps (onPostExecute(data returned from doInBackground)).
There are also other problematic things. For example mService could still be null or null again because the service was unbound.
IInAppBillingService mService = null;
bindService(...); -> causes assignment to `mService` at unknown time in future.

There is no guarantee when mService is safe to use. Some time after the app is initialized but that could still be after user presses a button and your thread could die because of a NullPointerException. Check that you don't access a null.


text:
Q: Adding dropbox to my ios app I am adding Dropbox support to my iOS application. Using the official Dropbox API and the tutorials  here .And, once authenticated, How can I save a file present in my dropbox to the user's Dropbox??

A: Well, if I get it right, then there are two possible solutions.
OPTION 1  (easiest and guaranteed to work)
Easiest solution is to make a share link of the file you want to download from your drobox.
In the app then send a request and download the file using the link.
After that, use the methods from dropbox tutorial to upload the file to the user's dropbox.
OPTION 2  (faster, better)
Use copy_ref to just copy a reference to the file between two accounts, instead of downloading and reuploading. Look at this entry in Dropbox API - https://www.dropbox.com/developers/reference/api#copy_ref


text:
Q: Entire silver light screen in Light Switch Is it possible to create a entire screen in silver light and use it in my light switch application.I find it very difficult to create custom page design as per client requirement in light switch..Can any one suggest me some ideas or point me to some useful links..Thank you.

A: Yes, see:
Help Desk: An Advanced Visual Studio LightSwitch Application
http://lightswitchhelpwebsite.com/Blog/tabid/61/EntryId/86/Help-Desk-An-Advanced-Visual-Studio-LightSwitch-Application.aspx

A: Here is a step by step guide on how to use Silverlight controls with lightswitch. http://dearmusings.wordpress.com/tag/custom-control/ I am using a scheduler control in the demo but it could be pretty much anything else that's Silverlight.


text:
Q: Is it possible to change a queryset using AJAX? I have querysets for comments which looks like this:
comment_list = Comment.objects.filter().order_by('-score__upvotes')
new_comments_list = Comment.objects.filter().order_by('-timestamp')

Then my template is
{% for comment in comment_list %}
    {{ comment }}

...

Is there any way to change {% for comment in comment_list %} to {% for comment in new_comments_list %} using AJAX (no page refresh)?
Or possibly changing the value of comment_list to equal Comment.objects.filter().order_by('-timestamp')?

A: AJAX requests occur when the developer (you) says so. If, for example, you have set an event listener on "Clicking" a specific button to make an AJAX request then an AJAX request will be made.
Lets say you have an event listener that "listens" on a click event on a specific button with id=my-button.
{# Place this as a separate html file, say "ajax_comments.html" #}
<div id="my-placeholder">
    {% for comment in comments %}
        {{ comment }}
    {% endfor %}

    <button id="my-button">Update comments</button>
</div>
{# END OF PLACE THIS #}

{# ############################################################### #}

{# Begin of your main HTML template, say "my_template.html" #}

....

{% include 'path/to/ajax_comments.html' %}

....

// make an Ajax call (GET request) to the same url, using jQuery.
$(document).ready(function() {
    $('#my-button').on('click', function() {
        $.ajax({
            'method': 'GET',  // defaults to GET. Set POST if you like, but be aware of the CSRF token submission too!
            'url': '.',  // submit to the same url
            'data': {},  // pass here any data to the server. You can omit it.
            success: function(dataReturned) {
                // This function will run when server returns data
                $('#my-placeholder').replaceWith(dataReturned);
            }
        });
    });
});

{# END OF "my_template.html" #}

Done with HTML, JS. Now to your views.py.
def my_view(request):
    if request.is_ajax():
        # If you have passed any data through the 'data' property
        #you can get it here, according to the method used.
        my_data = request.GET.get('data-name')
        comments = Comment.objects.filter().order_by('-timestamp')
        # Note that we are passing the 'ajax_comments.html' template.
        return render(request, 'ajax_comments.html', {'comments': comments})

    comments = Comment.objects.filter().order_by('-score__upvotes')
    return render(request, 'my_template.html', {'comments': comments})

*

*The button is pressed in your template

*An AJAX request is made to your server

*Inside your views, you handle this kind of request and you return an HTML portion with the new queryset.

*This return is not rendered directly to the template but goes to the $.ajax() function which awaits for this.

*Once received, it does what we have wrote to do (replace the div's data with the new ones)

Hope this helps you!


text:
Q: app dont appear when device is unlocked I just create a simple android project to show in a textview a text written in a edit view when a button is clicked.
The issue is that when I click to run the app, I select the available virtual device and then "ok", the emulator starts, I unlock the device but the app dont appear. Do you know why?
The code is here:
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView tview = (TextView) findViewById(R.id.textView);
        EditText input_text = (EditText) findViewById(R.id.editText);
        String message = input_text.getText().toString();
        tview.setText(message);
    }

content_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.ricardorei.myapplication.MainActivity"
    tools:showIn="@layout/activity_main">

        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button"
            android:layout_marginBottom="8dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            android:layout_marginTop="8dp"
            app:layout_constraintVertical_bias="0.4000002"
            android:layout_marginRight="8dp"
            app:layout_constraintRight_toRightOf="parent" />

        <EditText
            android:id="@+id/editText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="textPersonName"
            android:text="Name"
             />

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView"
            android:layout_marginBottom="8dp"

             />

    </android.support.constraint.ConstraintLayout>

A: Things you can do to track this:
1-check whether the gradle successfully build the app.
2-keep track of stop button on toolbar what it indicates.
3-check logs for possible errors.


text:
Q: Only show an element when it's inside another element I've been trying to create a box and two elements that would slide in upon click, switching one for the other, but I want them only to be visible inside the box.
Here's my lousy, stupid, stinkin' code, please assist.
HTML
<input id="toggle" type="checkbox">

  <button>switch</button>

        Soundcloud
        Mixcloud
        Bandcamp
        Hearthis.at
        Archive

        1111111111111
        222222
        333333
        4444444444
        5555555

CSS.
#box {
    height: 50px;
    width: 100%;
    border: 1px solixyzd #ccc;
}
#slider {
    -webkit-transition: all .5s cubic-bezier(0.42,0,0.58,1);
    transition: all .5s cubic-bezier(0.42,0,0.58,1);
}
#toggle {
    position: absolute;
  visibility: hidden;
}
#toggle + label {
    cursor: pointer;
}
#slider2 {
  margin-top: -100px;
    overflow-y: hidden;
    -webkit-transition: all .5s cubic-bezier(0.42,0,0.58,1);
    transition: all .5s cubic-bezier(0.42,0,0.58,1);
}
#toggle:checked ~ #box > #slider {
  margin-top: -80px;
}
#toggle:checked ~ #box > #slider2 {
  margin-top: 50px;
}

https://codepen.io/pen/xdeevd

A: Adding overflow:hidden to the box should work.
#box {
    overflow: hidden;
    height: 50px;
    width: 100%;
    border: 1px solid #ccc;
}

A: use a parent and child class, Child for default is hidden. Like this example.
Css :
.child{display:none}
.parent .child{ display:block }

Html :

 Visible Division

Hidden Division

A: You hide your in such a way that, its not working.
So change below CSS it will work
#toggle {
position: absolute;
opacity: 0;
}
#toggle:checked ~ #box > #slider2{
    margin-top: 10px;
    display: block;
}
#toggle:checked ~ #box > #slider{
    display: none;
}

Rest you can use your own idea for more animation and yes click on left corner
so that checkbox work or you can google for hiding checkbox at the same time make it work.
Thanks,
Debashis


text:
Q: Focused the next Texbox1 to Textbox17 I have a Class(ChorNumbers) and in this class i have a Function that test textbox1...17 is a Character or a Number.
I create a WindowsForm that have 9 textboxs. And if i enter 1 in the textbox1 that must jump to next textbox2 (that do this) If i enter A in the textbox2  that must jump to textbo3, but they does not jump. Where is the Problem why it doesnt not Jump??
And i want a use one textbox1_TextChanged Function.
 private void textbox1_TextChanged(object sender, EventArgs e)
 {
        TextBox myText = (TextBox)sender;
        ChorNumbers myNR = new ChorNumbers();

        bool _focused = false;
        if (myNR.CheckTextbox(myText.Name, myText.Text) == false)
            foreach (Control ctrtb in base.Controls)
                if (ctrtb is TextBox && _focused == false)
                {
                    _focused = ctrtb.Focused;
                }
                else if (ctrtb is TextBox && _focused == true)
                    ctrtb.Focus();
 }

I have solution that i dont wanna use that. I want only one textbox1 function for the other textboxs
    private void textbox3_TextChanged(object sender, EventArgs e)
    {
        TextBox myText1 = (TextBox)sender;
        ChorNumbers myNR1 = new ChorNumbers();

        if (myNR1.CheckTextbox(myText1.Name, myText1.Text) == false)
        {
            textbox4.Focus();
        }
    }

A: Why don't you try:
if textbox2.text = "A" then
    'whatever you want, for exapmple:
    textbox3.text = textbox2.text
end if

Instead of if textbox2.text = "A" then you can also use thing like:
if not textbox2.text = nothing then
end if

Isn't that much more easier than what you tried?

A: *

*Write an event-handler that handles TextChanged event for all
textboxes:
 private void textbox_TextChanged(object sender, EventArgs e)
 {
        TextBox txtBox = (TextBox)sender;

        // Either write your own character/number and focus moving logic here
        // Or the following
        char ch = txtBox.Text.Trim()[0];
        switch(txtBox.Name){
            case "textbox1":
                if(Char.IsDigit(ch))
                    textbox2.focus();
            break;
            case "textbox2":
                if(Char.IsLetter(ch))
                    textbox3.focus();
            break;

            ... // rest of the cases
        }
 }

*On design time, select textbox1, go to Properties > Events >
TextChanged and bind textbox_TextChanged there. Do the same for
rest of the textboxes.

A: By

I have solution that i dont wanna use that. I want only one textbox1
  function for the other textboxs

Do you mean that you only want a single call back function to be called by each textbox that then (if populated correctly) passes along to the next? If so, then that part is easy, just point each event handler to the same method (it may get complex though, unless the validation is exactly the same for each - therefore, it may be better to have one per textbox).
I think your problem is going to be a standard one - you are trying to change focus during an event called by that control before that control is finished processing. That is, textbox1, on being populated, fires the event which you catch - in your catchment (callback) method you change the focus - now processing returns to textbox1 (on return/end of you callback method) and focus is switched bach as a by-product (because the carat is being placed ready for next update by textbox1).
One solution is call a timed event for a few milliseconds later, then after processing returns to the textbox and it goes back into waiting for a message state, the timed event kicks off a focus (jump).
You could also try setting enabled to force and seeing if that forces the current control to pass anyway (will need to have sorted tab stops though)

A: Thats my Function ChorNumbers
 public bool ChorNumbers(string Name, string _Text)
        {
            bool error = false;
            if (_Text.Length < 1)
            {
                error = true;
                return error;
            }

                if (Name == "textbox1" && _Text.Length == 1)
                {
                    if (!Regex.IsMatch(_Text, "^[0-9\\s]"))
                    {
                        MessageBox.Show("Only Number and Space!");
                        error = true;
                    }
                }
                if (Name == "textbox2" && _Text.Length==1)
                {
                    if (!Regex.IsMatch(_Text, "^[a-zA-z]"))
                        {
                            MessageBox.Show("Only Character!");
                            error = true;
                        }
                 }

           // textbo3 ... textbox17

    return error;
  }


text:
Q: Wildfly Custom auth-method How do you add a custom authenticator in Wildfly?  I used to do this in JBoss 4.2:
In <JBoss>\jboss-as\server\production\deploy\jboss-web.deployer\META-INF\jboss-service.xml, add the following in :
 <java:property>
      <java:key>MY-CUSTOM-AUTH</java:key>
      <java:value>com.test.MyCustomAuthenticator</java:value>
 </java:property>

In <JBoss>\jboss-as\server\production\deploy\jboss-portal-ha.sar\portal-server.war\WEB-INF\web.xml, modify :
...
 <login-config>
      <auth-method>MY-CUSTOM-AUTH</auth-method>
...

Wildfly does not have jboss-service.xml anymore.

A: I found the answer.  We need to create an Undertow ServletExtension (io.undertow.servlet.ServletExtension) in the META-INF/services to register the authentication mechanism .  My extension class looks like this:
public class NtlmServletExtension implements ServletExtension {
    @Override
    public void handleDeployment(DeploymentInfo deploymentInfo, ServletContext servletContext) {
        deploymentInfo.addAuthenticationMechanism("NTLM", new NtlmAuthenticationMechanism.Factory());
    }
}

Check this for more details:  http://undertow.io/documentation/servlet/security.html
Here's a sample:
https://github.com/dstraub/spnego-wildfly
You can now refer to this in your web.xml:
...
 <login-config>
      <auth-method>NTLM</auth-method>
...

A: In WildFly you have to use a security realm for that :

*

*https://docs.jboss.org/author/display/WFLY8/Security+Realms for reference.

*http://www.radcortez.com/custom-principal-and-loginmodule-for-wildfly/ as an example


text:
Q: Json file replaces the data instead of adding I have a Json file which i'm using for my website, however when I fill out the form and send it over to my Json file it somehow replaces the old data with the new one instead of adding it with an increment.
my json/php set-up:
 $id = '';

if(isset($_POST['submit'])) {
 if(file_exists('json_files/database.json')) {
        $current_data = file_get_contents('json_files/database.json');
        $array_data = json_decode($current_data, true);
        $last_item = end($array_data);
        $last_item_id = $last_item['id'];
        $arrExercise = array(
            'id' => ++$last_item_id,
            'exerciseTitle' => $Title,
            'exerciseWord' => $question_takeAudio_exerciseWord,
            'syllables' => $Syllables
            );
         $array_data[] = $extra;
         $final_data = json_encode($array_data, JSON_PRETTY_PRINT);
            if(file_put_contents('json_files/database.json', $final_data)) {
                  header("Location: exercise_CMS.php");
        } else {
             echo "Oopsie! Something went wrong!";
             exit();
       }
   }
}

my json:
{
"id": 1,
"exerciseTitle": "Huisss",
"exerciseWord": [
    "Huisarts"
],
"syllables": [
    "Huis",
    "arts"
]
}

now, if I would fill out my form again, the above would be REPLACED for the new data send over to my json file. I want it however, to add it underneath with the increment of +1. Am I missing out on something?
EDIT: the json/php set-up has been updated. but most likely I am still missing parts out because now it returns a "0 null" value. however it doesn't overwrite the old data.

A: The default behavior of file_put_contents is to replace the file. According to the docs, "the existing file is overwritten, unless the FILE_APPEND flag is set."
However, as @deceze pointed out, you don't actually want to append to your JSON file because it won't be valid JSON. You'll need to read in your existing JSON file, update it and then overwrite. You'll also need to add your objects to a top level array like this:
{
    "exercises": []
}


text:
Q: UITableView blank space not working? so I was trying to align the text in UITableView using.
cell.textLabel?.text = sometext
I have two part in sometext first part is words, second part is number, such as "apple 45" "pear 23", "banana 34"so when they are showing in tableview cell, I want the left side of the words align with each other and the left side the number align with each other. and I can not post a picture here.
so according to the first part word length I added some blank space in the string by appending
let appStr = String(count: 22-cnt, repeatedValue: ( " " as Character))
print("append string is" + appStr + "end")
nameHere = name + appStr + number

I printed out to console in the program and it works fine, but when showing in the simulator it is not aligned.

A: Don't attempt to align numbers using spaces. Set the label's attributedText, not its text, and use the fact that an NSAttributedString can have tab stops to perform the alignment.


text:
Q: Custom components that can extend beyond their container's bounds - how? Let's say you have a JPanel size 200 x 200, with a custom combo-box-type component whose dropdown list should be able to extend outside of the 200 x 200 JPanel.
The problem I'm facing is that the dropdown either doesn't 'paint' outside the bounds of the container, or the container is sized according to the dropdown.
How can I add a component to a container which allows that component to extends beyond the bounds of the container? How does the Java JComboBox do that internally?

A: Simply use a JPopupMenu for the dropdown. JPopupMenu internally will handle painting at and beyond the edges.

A: if you continue with development of aplication that screenshots you posted here, you have to look for how to use JWindow (undecorated Top-Level Container), as example some of the best of JCalendar, SwingX, for full_workaround about setVisible / toFront / FocusSubsystem / on focusGained/focusLost
there no issue set JWindow to the Point with setSize that you can returns from any of JComponent


text:
Q: Element rendered differently in Firefox vs Opera I am working on a website and I have encountered a problem that borders of elements are rendered differently on Firefox then on Opera.
I will be thankful for any suggestion on how to fix this.
Picture (Opera on the left, Firefox on the right)
EDIT: CodePen
HTML:

CSS:
.red-bordered-bottom-bar {
    position: relative;
    border-width: 0px 0px 15px;
    border-color: transparent;
    border-style: solid;
    border-image: url("../Resources/primary_bottom.svg") 15 15 15 15 round round;
    background-color: #33393E;
}

.red-bordered-bar {
    position: relative;
    background-color: #FE634A;
}

.red-bordered-top-bar {
    position: relative;
    border-width: 15px 0px 0px;
    border-style: solid;
    border-color: transparent;
    border-image: url("../Resources/primary_top.svg") 15 15 15 15 round round;
    background-color: #33393E;
}

A: Try to change 15 15 15 15 border image slice value :
//top
-moz-border-image: url("https://dl.dropboxusercontent.com/u/35123963/primary_top.svg") 11 15 15 15 round round !important;

//bottom
-moz-border-image: url("https://dl.dropboxusercontent.com/u/35123963/primary_bottom.svg") 15 15 11 15 round round !important;

-moz for mozilla browser


text:
Q: How do I set an UIImage through a animated UIView to another View Controller in SWIFT I currently have View Controller 1 which has UIImageView and a button placed over the top, when that button is clicked I animate a PopUpViewController which is basically w UIView with buttons, this animates over the top of View Controller 1
var popViewController : PopUpViewControllerSwift! //popViewController declared in View Controller 1

 @IBAction func changePicture(sender: UIButton) {

            self.popViewController = PopUpViewControllerSwift(nibName: "PopUpViewController_iPhone6", bundle: nil)
            self.popViewController.showInView(self.view, animated: true)
    }

The popUpViewController now pops up over the ViewController 1, which then the user presses a button and that presents the ImagePickerController photo library. code here:
@IBAction func goToPhotoLibary(sender: UIButton) {

        self.removeAnimate()
        var image = UIImagePickerController()
        image.delegate = self
        image.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
        image.allowsEditing = true
        presentViewController(image, animated: true, completion: nil)

    }

Now the user picks an image, I then want to be able to place that image in the original UIImageView which the user pressed with the button over in View Controller 1 the code I am using is crashing with the error fatal error: unexpectedly found nil while unwrapping an Optional value code used:
var VC1 : ProfileViewController! //Reference to View Controller 1

    func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage imagePicked: UIImage!, editingInfo: [NSObject : AnyObject]!) {

            self.dismissViewControllerAnimated(true, completion: nil)
             self.VC1.profilePic.image = imagePicked //CRASHES HERE

}

I am trying to pass the imagePicked from one ViewController to the next which I assume why it is crashes.
Can anyone add any input into how to do this?
Thanks

A: First i would try to set your image then dismiss the controller.
func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage imagePicked: UIImage!, editingInfo: [NSObject : AnyObject]!) {
    self.VC1.profilePic.image = imagePicked //CRASHES HERE
    self.dismissViewControllerAnimated(true, completion: nil)
}

Now what you need to do is to check which variable is nil.
Check you are passing VC1 correctly and is not nil. Check you have profilePic connected to outlet in storyboard(if you are using storyboards). Check if imagePicked is not nil.
You can do it by:
if let value = imagePicked{
    println("image is not nil")
}
if let value = self.vc1{
    println("vc1 is not nil")
    if let profilepic = self.vc1.profilePic{
        println("profile pic is not nil")
    }
}


text:
Q: How to send nested values in postman i have a conflict in some point , i need to receive this representation after consuming my endpoint .
the response is like that  :
{"6451":{"option":1,"note":""},"6460":{"option":1,"note":""}}

How can i send the above format but in the correct way please  through postman application , i don't have an imagination for forming the parameters which i will receive in my PHP controller

A: You can set the raw format in your body request, set application/json and paste your json:
{
  "6451": {
    "option": 1,
    "note": ""
  },
  "6460": {
    "option": 1,
    "note": ""
  }
}


text:
Q: Error al importar "ValueError: Attempted relative import in non-package" PYTHON Soy un poco novato aun en Python , ya que estoy empezando su aprendizaje. Me he encontrado con un problema a la hora de hacer un "import" bastante basico. He buscado informacion en Google , pero no entiendo muy bien las soluciones que he visto , por eso recurro a vuestra sabiduria.
El error es el siguiente ;
ValueError: Attempted relative import in non-package

Traceback (most recent call last)
File "/Users/usuario/Desktop/miproyecto/hello.py", line 4, in <module>
from .forms import LoginForm # importamos login
ValueError: Attempted relative import in non-package

Bien , la carpeta de mi proyecto tiene la siguiente estructura :

Y este es el codigo de mi archivo Hello.py ;
from flask import Flask  # Creamos objeto flask
app = Flask(__name__)
from flask import render_template, flash, redirect # Creamos objeto
plantilla , flash , etc
from .forms import LoginForm # importamos login

app.config.from_object('config') # Leemos configuracion creada

@app.route('/')
@app.route('/index')
def hello_world():
 return 'Hello, World!'

@app.route('/templates')
 def templates():
  user = {'nickname': 'juan'}
  return render_template('index.html',
                       title='Home',
                       user=user)

# index view function suppressed for brevity

@app.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
return render_template('login.html',
                       title='Sign In',
                       form=form)

Y este el de mi archivo forms.py ;
from flask.ext.wtf import Form
from wtforms import StringField, BooleanField
from wtforms.validators import DataRequired

class LoginForm(Form):
openid = StringField('openid', validators=[DataRequired()])
remember_me = BooleanField('remember_me', default=False)

Muchas gracias de antemano! Un saludo!


text:
Q: Rails thinks my join table has different column names I'm trying to create a many-to-many relationship between photos and albums in a Rails app. My join table looks like this in the MySQL database:
+---------+------------------+------+-----+---------+-------+
| Field   | Type             | Null | Key | Default | Extra |
+---------+------------------+------+-----+---------+-------+
| photoID | int(10) unsigned | NO   | MUL | NULL    |       |
| albumID | int(10) unsigned | NO   | MUL | NULL    |       |
+---------+------------------+------+-----+---------+-------+

However, when I go into the rails console and query:
photo = Photo.find(1)
photo.albums

I get an Unknown column 'albums_photos.photo_id' in 'where clause' error because of the generated MySQL query, which was:
SELECT `albums`.*
FROM `albums`
INNER JOIN `albums_photos`
ON `albums`.`albumID` = `albums_photos`.`album_id`
WHERE `albums_photos`.`photo_id` = 1

As you can see from the database, the keys are not album_id and photo_id , but are actually albumID and photoID. Where should I look first to find the cause of this problem? Here are my models for the three.
Album:
class Album < ApplicationRecord
    has_and_belongs_to_many :photos
end

Photo:
class Photo < ApplicationRecord
    has_and_belongs_to_many :albums
end

AlbumPhoto:
class AlbumPhoto < ApplicationRecord
    belongs_to :photo
    belongs_to :album
end

(Note: I imported this database directly into MySQL from a .sql file, not via a migration, if that information helps.)

A: Try this:
class Album < ApplicationRecord
    has_and_belongs_to_many :photos, :association_foreign_key => 'photoID'
end

class Photo < ApplicationRecord
    has_and_belongs_to_many :albums, :association_foreign_key => 'albumID'
end

EDIT
Does your migration looks like this:
create_table :albums_photos do |t|
  t.integer :album_id
  t.integer :photo_id

  t.timestamps
end


text:
Q: javascript not loaded in php file on nginx server I set up a nginx server on a VPS, and trying to make website base on this setting. The problem I have is that the external js file (stored in server) seems cannot be loaded when accessing the php page.
This is my nginx.conf, server_name and root's name is changed for privacy reason:
  server {
listen 80;
server_name example.com;
root /var/www/example;
index index.html index.htm index.php;
location ~ [^/]\.php(/|$) {
  #fastcgi_pass remote_php_ip:9000;
  fastcgi_pass unix:/dev/shm/php-cgi.sock;
  fastcgi_index index.php;
  include fastcgi.conf;
}

location ~ \.(js|jpg|png|css)(.*)$  {
  expires 30d;
}

}
this is my php test page
<!doctype html>
<html lang="en">
  <head>
    <!-- update aob -->
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.slim.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://cdn.bootcss.com/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
    <script scr="example.js"></script>

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <title>test page</title>
  </head>
  <body>
    <script>
      console.log("hello");
    </script>
  </body>
</html>

and this is my javascript, example.js, which located at the same root of the php file:
console.log('print something');

What I expect to see when I access the example.php is that the console will shows:
print something
hello
but when I access the page I only have the inline script executed. I've used the chrome inspector and I found that js file is not loaded at all, but all other CDN provided scripts can be loaded normally.
I've tried to find a solution for this, what I suspect is that my nginx.conf have something wrong, but I couldn't find any that would solve my cases. Please help.

A: Found by @esqew, I wrote the
scr=

instead of
src=

After fixing everything is fine now.


text:
Q: What does 'Whitman's poet' in the passage? I think 's  generally indicates possession, but in the following passage, the usage evades me. Does it mean 'Whitman's poetry' or 'a poet like Whitman'?

Long before Walt Whitman wrote Leaves of Grass, poets had addressed
  themselves to fame. Horace, Petrarch, Shakespeare, Milton, and Keats
  all hoped that poetic greatness would grant them a kind of earthly
  immortality. Whitman held a similar faith that for centuries the world
  would value his poems. But to this ancient desire to live forever on
  the page, he added a new sense of fame. Readers would not simply
  attend to the poet's work; they would be attracted to the greatness of
  his personality. They would see in his poems a vibrant cultural
  performance, an individual springing from the book with tremendous
  charisma and appeal. Out of the political rallies and electoral
  parades that marked Jacksonian America, Whitman defined poetic fame in
  relation to the crowd. Other poets might look for their inspiration
  from the goddess of poetry. Whitman's poet sought the approval of
  his contemporaries. In the instability of American democracy, fame
  would be dependent on celebrity, on the degree to which the people
  rejoiced in the poet and his work.

This article is from the preface of Walt Whitman and the Culture of American Celebrity by David Haven Blake.


text:
Q: Mapping multiple simple JSON fields to complex POJO with Jackson I am trying to map a JSON structure to a specific POJO that doesn't really match the JSOM, here is a simple example:
JSON
{
    "strA": "MyStr",
    "Street": "1st Lane",
    "Number": "123"
}

POJO
@JsonIgnoreProperties(ignoreUnknown = true)
public class ClassA {

    @JsonProperty("strA")
    private String strA;

    private Address address;
//Constructor, getter,setter

@JsonRootName("Address")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Address {

    private String address;

    public Address() {
    }

    public String getAddress() {
        return address;
    }

    @JsonAnySetter
    public void setAddress(@JsonProperty("Street") String street, @JsonProperty("Number")String number) {
        this.address = number + " " + street;
    }
}

Now, Address is properly created from the sample JSON (only made it work with the JsonAnySetter unfortunately), but I can't get ClassA to be created properly.
I've tried annotating the Address property of it, but to no avail.
How can I achieve this in a "simple" way? This is important as this example is simple, but my real use cases involves several composed classes that need information from the JSON root + from complex JSON elements with different names.
Thank you for your time.


text:
Q: WPF, MVVM IoC: Alternative to Service Locator Pattern. Need dependency in View code behind Following several guides I have a application layout like below using WPF .NET 4.7.1 and MVVM-Light. I'm totally new to WPF btw.
App.xaml:
<Application x:Class="My.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:viewmodel="clr-namespace:My.ViewModel"
         StartupUri="View\MainView.xaml">
<Application.Resources>
    <ResourceDictionary>
        <viewmodel:ViewModelLocator x:Key="Locator" />
    </ResourceDictionary>
</Application.Resources>

That registers the "ViewModelLocator" class as a resources and sets the WPF startup to "View/MainView.xaml".
MainView.xaml:
<Window x:Class="My.View.MainView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

<Window.DataContext>
    <Binding  Path="Main" Source="{StaticResource Locator}"/>
</Window.DataContext>

Where the ViewModelLocator is used like a Service Locator Pattern. Here setting the DataContext to my "MainViewModel" (not shown). As much as I do not like this, I can live with it in the WPF XAML context. However now it turns out that I need a dependency in the code-behind of the view (not the ViewModel).
MainView.cs:
public partial class MainView : INotifyPropertyChanged
{
   public MainView()
   {
       // Need to access dependency here.
   }
}

Now I could just call the ViewModelLocator directly in that constructor and have that resolve from my IoC container - but then I've completely given in and accepting that pattern.
I would prefer to have the dependency injected in the ctor of course, and if that is possible, I would also leave the ViewModelLocator entirely and inject the ViewModel here.
So question is, are there some standard way of instructing WPF application to use my container? And if yes, is it adviceable to go down that path and not use the ViewModelLocator thing?

A: You absolutely do not have to use the ViewModelLocator (Side note, the service locator pattern has had it's fair share of criticism lately as an anti-pattern, but I'll let you form your own opinion). MVVM Light and other Libraries basically give you access to a tool kit. You don't need to use all of the tools, and you should only use what is necessary for your specific domain.
Outside of the ViewModelLocator, there are two patterns known as ViewModel First and View First both have their pro's and cons.  However both provide a means to decouple your code, which means it's not difficult to switch later.
As for constructing an application using MVVM Light without the service locator, my implementation of the View First method looks something like this.
I've heard the opinion that ViewModel First is preferred, however I find View First to be more simplistic for Test Driven Development (TDD)
App.xaml.cs (Application Code Behind)
public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        var bootStrapper = new BootStrapper();
        //Container Builder
        var container = bootStrapper.BootStrap();
        var mainWindow = container.Resolve<MainWindow>();
        mainWindow.Show();
    }
}

BootStrapper.cs (I'm using AutoFac in this case, but you can easily substitute.)
public class BootStrapper
{
    public IContainer BootStrap()
    {
        var builder = new ContainerBuilder();
        builder.RegisterType<MainWindow>().AsSelf();
        builder.RegisterType<MainWindowViewModel>().AsSelf();
        return builder.Build();
    }
}

MainWindowViewModel.cs
//I rolled my own ViewModelBase, but you can use MVVM Light's ViewModelBase
public class MainWindowViewModel : ViewModelBase
{
    public string DisplayProgram
    {
        get { return _displayProgram; }
        //MVVM Light's ViewModelBase uses RaisePropertyChanged();
        set { _displayProgram = value; OnPropertyChanged(); }
    }

    public void Initialize()
    {
        //Called from view code behind.
    }
}

MainWindow.xaml.cs (MainWindow Code Behind)
//When MainWindow.Show()..
public partial class MainWindow : Window
{
    private readonly MainWindowViewModel _viewModel;
    //Container resolves dependencies
    public MainWindow(MainWindowViewModel viewModel)
    {
        //Let base Window class do its thing.
        InitializeComponent();

        //Handle loaded event
        Loaded += MainWindowLoaded;

        //Hold on to the MainWindowViewModel, and set it as the windows DataContext
        _viewModel = viewModel;
        DataContext = _viewModel;
    }

    private void MainWindowLoaded(object sender, RoutedEventArgs e)
    {
        _viewModel.Initialize();
    }
}


text:
Q: Why is a histogram for normal samples rougher near the mode than near the tail? I am trying to understand a particular behavior of the histogram of samples generated from rnorm.
set.seed(1)
x1 <- rnorm(1000L)
x2 <- rnorm(10000L)
x3 <- rnorm(100000L)
x4 <- rnorm(1000000L)

plot.hist <- function(vec, title, brks) {
  h <- hist(vec, breaks = brks, density = 10,
            col = "lightgray", main = title)
  xfit <- seq(min(vec), max(vec), length = 40)
  yfit <- dnorm(xfit, mean = mean(vec), sd = sd(vec))
  yfit <- yfit * diff(h$mids[1:2]) * length(vec)
  return(lines(xfit, yfit, col = "black", lwd = 2))
}

par(mfrow = c(2, 2))
plot.hist(x1, title = 'Sample = 1E3', brks = 100)
plot.hist(x2, title = 'Sample = 1E4', brks = 500)
plot.hist(x3, title = 'Sample = 1E5', brks = 1000)
plot.hist(x4, title = 'Sample = 1E6', brks = 1000)

You will notice that in each case (I am not making cross comparison; I know that as sample size gets larger the match between histogram and the curve is better), the histogram approximates the standard normal better towards the tails, but poorer towards the mode. Simply put, I'm trying to understand why each histogram is rougher in the middle compared to the tails. Is this an expected behavior or have I missed something basic?

A: Our eyes are fooling us. The density near the mode is high so that we can observe the variation more evidently. The density near the tail is so low so that we can not really spot anything. The following code performs sort of a "standardization", allowing us to visualize the variation on a relative scale.
set.seed(1)
x1 <- rnorm(1000L)
x2 <- rnorm(10000L)
x3 <- rnorm(100000L)
x4 <- rnorm(1000000L)

foo <- function(vec, title, brks) {
  ## bin estimation
  h <- hist(vec, breaks = brks, plot = FALSE)
  ## compute true probability between adjacent break points
  p2 <- pnorm(h$breaks[-1])
  p1 <- pnorm(h$breaks[-length(h$breaks)])
  p <- p2 - p1
  ## compute estimated probability between adjacent break points
  phat <- h$count / length(vec)
  ## compute and plot their absolute relative difference
  v <- abs(phat - p) / p
  ##plot(h$mids, v, main = title)
  ## plotting on log scale is much better!!
  v.log <- log(1 + v)
  plot(h$mids, v.log, main = title)
  ## invisible return
  invisible(list(v = v, v.log = v.log))
  }

par(mfrow = c(2, 2))
v1 <- foo(x1, title = 'Sample = 1E3', brks = 100)
v2 <- foo(x2, title = 'Sample = 1E4', brks = 500)
v3 <- foo(x3, title = 'Sample = 1E5', brks = 1000)
v4 <- foo(x4, title = 'Sample = 1E6', brks = 1000)

The relative variation is the lowest near the middle (toward 0), but very high near the two edges. This is well explained in statistics:

*

*We have more samples near the middle, so (sample sd) : (sample mean) there is lower;

*We have few samples near the edge, maybe 1 or 2, so (sample sd) : (sample mean) there is big.

a little explanation on the log-transform I take
v.log = log(1 + v). Its Taylor expansion ensures that v.log is close to v for very small v around 0. As v gets larger, log(1 + v) gets closer to log(v), thus the usual log-transform is recovered.

A: This is not just true for normal samples. If we had fixed bins (rather than data-determined ones as we normally do) and we  condition on the total number of observations, then the counts would be multinomial.
The expected value of the count in bin i is then n·p(i) where p(i) is the proportion of the population density that falls in bin (i).
The variance of the count in bin i would then be n·p(i)·(1-p(i)). With many bins and a smooth non-peaky density like a normal, (1-p(i)) will be very close to 1; p(i) will typically be smallish (much smaller that 1/2).

The variance of the count (and hence the standard deviation of it) is an increasing function of the expected height:
With a fixed bin width the height is proportional to the expected count and the standard deviation of the bin-height is an increasing function of the height.
So this motivates exactly what  you see.
In practice it's not the case that the bin boundaries are fixed; as you add observations or generate a new sample they will change, but the number of bins changes fairly slowly as a function of the sample size (typically as the cube root, or sometimes as the log) and a more sophisticated analysis than the one here is required to get the exact form. However, the outcome is the same -- under commonly observed conditions the variance of the height of a bin typically increases monotonically with the height of the bin.

A: rnorm() draws a random sample from a normal distribution.  The size of the sample is the first argument to rnorm().  So if you do hist(rnorm(10)) you will of course get something that doesn't look much like the normal bell curve because your sample size is so small.  If you do hist(rnorm(1000)) it will be better and if you do hist(rnorm(1e8)) your sample should approximate the curve quite well.


text:
Q: Get SharePoint Web App Url programatilly from WindowsFormTool I developing a simple Windows Forms Application that using a PowerShell script to add WSP solutions to multiple SharePoint front ends automatically.
I am not a SharePoint developer but it's required task from me, i worked also on SharePoint 2010
PowerShell script take one parameter $webUrl so i need to foreach on every Front End and get it's Web Application URL then pass it to script.
The above is too easy, i done all required steps except that i didn't know how to get Web Application URL from only the front end server name.
i think i want to check if this front end server have SharePoint installed in it, then i get the Web Application URL.
I know that SharePoint can have multiple web application URL configured on IIS.
I think the result should be some thing like that:
http://vmserver:2222/

A: I don't think it'll be possible to get a list of web applications only from the server name. You'll have to run the script from the server to get the local farm instance and then iterate through the web applications in the farm. Steps are outlined here : http://blog.falchionconsulting.com/index.php/2009/04/getting-an-spwebapplication-object-using-powershell/
Though if multiple servers are connected to a farm you'll have to run this on only one server.


text:
Q: How to upload only csv files into the server in Java I have an application in which there is a requirement of Uploading csv files.
Everything is working fine. I am uploading files successfully with extension .csv.
Now here is the problem. someone may try to upload exe file  by changing its extension to .csv and upload to server. It is perfectly uploading. Some one suggested me to upload file by using mimetype. I follow this tutorial.
I am getting mimetype null for csv files.
So can you please help me how to upload only csv files.
Thanks in Advance

A: Well, you are ont he right track. You need to do some kind of file inspection instead of just trusting the file extension.
Either you have to program your own, or use a third party library (which is what you are doing).
If you keep with the third party framework, you must eb having a configuration issue. What the issue is I can't tell from your description, as I don't know the library.
If you are only interested in recognizing CSV files I would recommend something simple that at least you understand and can control. Such as this approach:
Assume that CSV files consist of 0..n lines with the same number of elements pr. line, separated by one of these characters: , ;
It's quite unlikely that an EXE file would have this structure, unless somebody deliberately attack your system with knowledge of your implementation.
Read the first couple of lines.
Split them on the regexp ([,;]).
Check that the results have the same number of elements.
For extra safety, check that they split on the same character.

A: Even if you set the mimetype, I'm guessing that is only determined from the file extension. so setting .csv most likely will still bypass it.
What I would do is simply read the file for ASCII data if you find anything other than character data throw an error or ignore the file. Loop and compare via numeric range, or you can read it as a string and used a regular expression like [^\\p{ASCII}]

A: As far as I know, you can't prevent someone to upload any file type to your server, specially due to the problem you stated like changing the extension. The only possibility you have is to, after receiving the file, try to parse it as a *.csv. If you successfully parse it, you store it in your repository and respond with a success message, if not, you ignore the file and respond with a error message.
Obviously you can parse the csv file client side with Javascript but you should always validate your files server side.
Myme type only tells your server what type to expect, but that won't prevent someone to send you a non csv file.


text:
Q: flutter sizing and rotating a widget with gestures I am trying to implement resizing and rotation capabilities to a container with some text in it.
It's pretty basic. I want to rotate it if the user taps with two fingers and rotates. I want to resize it if the user taps with two fingers and move them away or closer.
I was able to find some partially related questions/guides but for a total beginner to these gestures, what should I do, is there a good resource I can check out?


text:
Q: python print double Bracket "{{}}" using .format on it By using print("""{{1}} {}""".format("x")) I want to print this:

{{1}} x

But I get this:

{1} x

But after using print("""{{{1}}} {}""".format("x"))(three brackets rather than two) I get IndexError: tuple index out of range
So how can I print double brackets using .format on it?
Thanks in advance.

A: Quadruple brackets print("""{{{{1}}}} {}""".format("x")) as double bracket prints one bracket in output so 4 prints two


text:
Q: Lebesgue-Stieltjes Integral (Several Variables) Let $\mathcal F$ be a convex set of probability measures or distribution functions and $F, G$ be two elements in $\mathcal F$. Let $T$ be a functional on $\mathcal F$ defined as follows. Note that $h$ is symmetric. $$T(F):= \int \cdots \int h(x_1, \dots, x_c) dF(x_1) \cdots dF(x_n).$$ Then how to derive the following result, please? Thank you!

$$T[F+\lambda(G-F)] = \sum_{j=0}^c {c \choose j} \lambda^{c-j} \int \cdots \int h(x_1, \dots, x_c) \prod_{i=1}^j dF(x_i) \prod_{i=j+1}^c d[G(x_i) - F(x_i)].$$

Moreover, what is the convention for the following formula, please? Thank you!

$$\prod_{i=1}^0dF(x_i) := ?$$

A: When it comes down to it, this is really just a multiplication problem. First,
\begin{equation*}
\prod_{i=1}^{n}dF(x_i)=dF(x_1)\dots dF(x_n)
\end{equation*}
Now,
\begin{align*}
T(F+\lambda(G-F))&=\int\!\dots\!\int h(x_1,\dots,x_c)\prod_{i=1}^{c}d(F(x_i)+\lambda(G(x_i)-F(x_i)))\\
&=\int\!\dots\!\int h(x_1,\dots,x_c)\prod_{i=1}^{c}(dF(x_i)+\lambda(dG(x_i)-dF(x_i)))
\end{align*}
Now you just want to rewrite the last part. To make typing easier, I'm going to use $f_i=dF(x_i)$, and $g_i=dG(x_i)$. So,
\begin{align*}
\prod_{i=0}^{c}(f_i+\lambda(g_i-f_i))&=(f_1+\lambda(g_1-f_1))\dots(f_c+\lambda(g_c-f_c))\\
&=\sum_{j=0}^{c}\binom{c}{j}f_1\dots f_j (\lambda g_{j+1}-\lambda f_{j+1})\dots(\lambda g_{c}-\lambda f_{c})\\
&=\sum_{j=0}^{c}\binom{c}{j}f_1\dots f_j \lambda^{c-j}(g_{j+1}-f_{j+1})\dots(g_{c}-f_{c})
\end{align*}
since you're "choosing" how many of the "first" ($a$ in $(a+b)$) elements you're multiplying and how many of the "second" ($b$ in $(a+b)$), but each term in the summation must be the product of $c$ terms in total. The last line is what you're looking for. Think cubic or quartic if that's easier.
P.S. I suspect that I haven't actually done anything!
Sorry, I misread the last part of your question:
\begin{equation*}
\prod_{i=1}^{0}dF(x_i)=1,
\end{equation*}
for all intents and purposes. We just skip it--it means only the $\lambda(g_i-f_i)$ terms are being multiplied. It's the same with
\begin{equation*}
\prod_{i=c+1}^{c}(dG(x_i)-dF(x_i))=1
\end{equation*}


text:
Q: Can TeX be used in programming? I heard that TeX is a Turing complete language. Does it mean that one can use TeX for example to write operating systems or games like Tetris or Hangman? I don't mean that one writes a source code of Tetris but I mean, can one play Tetris somehow by writing a document and compiling it?

A: "Turing-complete" means that, in theory, a TeX engine with enough memory could run a simulation of any of those things.  It wouldn't be practical.
The game of Tetris would not actually be playable, because TeX is not designed to read a controller and update pictures in real time, but it might come closest.  However, you might write code (let's say, in TikZ) that produce an animation of a Tetris game based on a given input file.  It's also possible to imagine making a simulation of the memory of some 8-bit computer, like an Apple II, including the CPU and the memory, as a state machine.  You could then run a simulated operating system in the document and draw what would appear on the screen when the simulated program finished.
LuaTeX provides hooks to insert arbitrary Lua modules, but that's somewhat different from doing it in TeX.

A: I used LaTeX to create and solve sudoku puzzles (> texdoc sudokubundle) although I don't recommend using (La)TeX for this.


text:
Q: Is there an $F \in L^2({\mathbb{T}})$ s,t $\hat{F} = 1/\sqrt{n}$ for $n \geq 1$? I am unsure of where to start with this. Is it a matter of showing:
$$\int_{\mathbb{T}}|F(n)|^2\mathrm d\lambda < \infty$$
So must I derive $\hat{F} = 1/\sqrt{n}$ ? Or should I be using Bessel's inequality?


text:
Q: Navigating Plunkr code Most of the code in the Angular 2 documentation is provided through Plunkr. I find this really frustrating, because if I have a plunkr window with the example code open for a long time, it will eventually go blank and refreshing it will not bring it back--you have to find where you launched it from and launch it again. Is there a way to open the plunkr so that the parameters that launched it are persevered (ie so you could bookmark it)?
Another problem is that I don't see a way to search a Plunkr project to find where code in one file is used in other files, which really makes it hard for me to follow the flow of code. Is there a way to get back to where the files are stored (a GitHub repo or...?) so that it's possible to do such a search?

A: I'm still not sure how, given a plunker, you can work backward to find the repo it's connected to. I think most plunks are not connected to a repo at all.
However, when I commented on a bug at the Angular documentation GitHub repo, someone mentioned in passing that the plunks were automatically generated from GitHub when you click the link. I still haven't been able to find specifics on how this works, but it was enough for me to discover where the GitHub files for the testing docs are. These are searchable so it's easier to follow the dependencies.


text:
Q: How to add a text under the icon in toolbar? I want to add a text under the icon in toolbar.
Now I can just add or title, or image.
Can I make that I will have image and under the image label of text?
I did add label in the bottom of image, but how can I cantralize it like I do it with images by Flexible Space Bar Button Item?

A: First you need to create an extension of UIButton, this post give the solution. Then, you can embed a UIButton as a custom view inside your UIBarButtonItem
extension UIButton {
    func centerLabelVerticallyWithPadding(spacing:CGFloat) {
        // update positioning of image and title
        let imageSize = self.imageView!.frame.size
        self.titleEdgeInsets = UIEdgeInsets(top:0,
            left:-imageSize.width,
            bottom:-(imageSize.height + spacing),
            right:0)
        let titleSize = self.titleLabel!.frame.size
        self.imageEdgeInsets = UIEdgeInsets(top:-(titleSize.height + spacing),
            left:0,
            bottom: 0,
            right:-titleSize.width)

        // reset contentInset, so intrinsicContentSize() is still accurate
        let trueContentSize = CGRectUnion(self.titleLabel!.frame, self.imageView!.frame).size
        let oldContentSize = self.intrinsicContentSize()
        let heightDelta = trueContentSize.height - oldContentSize.height
        let widthDelta = trueContentSize.width - oldContentSize.width
        self.contentEdgeInsets = UIEdgeInsets(top:heightDelta/2.0,
            left:widthDelta/2.0,
            bottom:heightDelta/2.0,
            right:widthDelta/2.0)
    }
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let customButton : UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
        customButton.setImage((UIImage(named: "Image")), forState:UIControlState.Normal)
        customButton.setTitle("Button", forState: UIControlState.Normal)
        customButton.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)
        customButton.sizeToFit()
        customButton.centerLabelVerticallyWithPadding(5)
        let customBarButtonItem = UIBarButtonItem(customView: customButton as UIView)
        self.navigationItem.rightBarButtonItem = customBarButtonItem;

    }
}


text:
Q: Stop mplayer thread in django With a django button, I need to launch multiples music (with random selection).
In my models.py, I have two functions 'playmusic' and 'playmusicrandom' :
class Player()
    def playmusic(self, music):
    if self.isStarted():
        self.stop()

        command = ("sudo /usr/bin/mplayer "+music.path)
        p = subprocess.Popen(command+str(music.path), shell=True)
        p.wait()

    def playmusicrandom(request):
        conn = sqlite3.connect(settings.DATABASES['default']['NAME'])
        cur = conn.cursor()
        cur.execute("SELECT id FROM webgui_music")
        list_id = [row[0] for row in cur.fetchall()]

        ### Get three IDs randomly from the list ###
        selected_ids = random.sample(list_id, 3)

        for i in (selected_ids):
            music = Music.objects.get(id=i)
            player.playmusic(music)

    def stop(self):
        """
        Kill mplayer process
        """
        p = subprocess.Popen("sudo killall mplayer", shell=True)
        p.communicate()

In my views, I use a Thread to call 'playmusicrandom':
def playmusicrandom(request):
player = Player()
#player.playmusicrandom()
t = threading.Thread(target=player.playmusicrandom)
t.setDaemon(True)
t.start()

return redirect('homepage')

So, when I click Play,  three musics are played (one after the other).
But when I click Stop, obviously, the current mplayer process is killed, and the 2nd process is played...
I've read it was not a good idea, but is there a solution in my case to stop a thread launched in views  ?
Thanks.
PS : I want to avoid to change stop to 'kill, sleep, kill, etc...'

A: In my experience, the best way to have background process in django apps is to use celery. Take a look at http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html to see what would you need to include it in your setup.


text:
Q: My thread closes while the program is running I'm programming a gmae in c++.net, it's like the space impact. I start the game form and on its load event I create a thread to play a music in the background of the application.
The problem is that when I press the space bar to shoot it also plays a sound, and it stops the main music.
I've already had this issue, but I was told that threads should fix the problem.
I've created the thread and my problem stands. Some help would be appreciated.
    private: System::Void GameForm_Load(System::Object^  sender, System::EventArgs^  e)
{

    Thread^ newThread = gcnew Thread(gcnew ThreadStart(PlayMusic));
    newThread->Name = "MusicaImperio";
    newThread->IsBackground = true;
    if(newThread->IsBackground == true)
    newThread->Start();
    //Sleep(3000);

}

This is the load event, and this is the Playmusic method:
    static void PlayMusic()
{
    PlaySound(TEXT("../Musicas/Game.wav"), NULL, SND_ASYNC | SND_LOOP);
}

A: if you try to not run it on the background.
Does it work then or still nothing ?
maybe you can see what happens


text:
Q: Error occured processing XML 'Unable to load class [org.springframework.transaction.annotation.AnnotationTransactionAttributeSource] Please i need configuration of the file applicationcontext.xml, I use hibernate 5.2.10 and spring 3.1.1.
I already have this configuration but there is an error :

"Error occured processing XML 'Unable to load class [org.springframework.transaction.annotation.AnnotationTransactionAttributeSource].
  Are you running on Java 1.5+?   Root cause:
  java.lang.NoSuchMethodError:
  org.springframework.util.ClassUtils.forName(Ljava/lang/String;)Ljava/lang/Class;'.
  See Error Log for more details"

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">

        <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
            <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
            <property name="url" value="jdbc:mysql://localhost/training"></property>
            <property name="username" value="root"></property>
            <property name="password" value=""></property>
        </bean>

        <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
            <property name="dataSource" ref="dataSource"></property>
            <property name="annotatedClasses">
                <list>
                    <value>co.ma.training.entity.Stagiaire</value>
                </list>
            </property>
            <property name="hibernateProperties">
                <props>
                    <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                </props>
            </property>
        </bean>

        <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
            <property name="sessionFactory" ref="sessionFactory"></property>
        </bean>
        <tx:annotation-driven transaction-manager="transactionManager" />

        <context:annotation-config></context:annotation-config>
        <context:component-scan base-package="co.ma.training"></context:component-scan>

</beans>

A: Please make sure to use latest compatible Java version to the frameworks in your project. (1.5 +)
If you're using Maven try using the properties below.
<properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>


text:
Q: Identifying the components in a English sentence that do not make sense I'm wondering is there an algorithm or a library which helps me identify the components in an English which has no meaning? e.g., very serious grammar error? If so, could you explain how it works, because I would really like to implement that or use that for my own projects.
Here's a random example:
In the sentence: "I closed so etc page hello the door."
As a human, we can quickly identify that [so etc page hello] does not make any sense. Is it possible for a machine to point out that the string does not make any sense and also contains grammar errors?
If there's such a solution, how precise can that be? Is it possible, for example, given a clip of an English sentence, the algorithm returns a measure, indicating how meaningful, or correct that clip is? Thank you very much!
PS: I've looked at CMU's link grammar as well as the NLTK library. But still I'm not sure how to use for example link grammar parser to do what I would like to do as the if the parser doesn't accept the sentence, I don't know how to tweak it to tell me which part it is not right.. and I'm not sure whether NLTK supported that.
Another thought I had towards solving the problem is to look at the frequencies of the word combination. Since I'm currently interested in correcting very serious errors only. If I define the "serious error" to be the cases where words in a clip of a sentence are rarely used together, i.e., the frequency of the combo should be much lower than those of the other combos in the sentence.
For instance, in the above example: [so etc page hello] these four words really seldom occur together. One intuition of my idea comes from when I type such combo in Google, no related results jump out. So is there any library that provides me such frequency information like Google does? Such frequencies may give a good hint on the correctness of the word combo.

A: Yes, such things exist.
You can read about it on Wikipedia.
You can also read about some of the precision issues here.
As far as determining which part is not right after determining the sentence has a grammar issue, that is largely impossible without knowing the author's intended meaning. Take, for example, "Over their, dead bodies" and "Over there dead bodies". Both are incorrect, and could be fixed either by adding/removing the comma or swapping their/there. However, these result in very different meanings (yes, the second one would not be a complete sentence, but it would be acceptable/understandable in context).
Spell checking works because there are a limited number of words against which you can check a word to determine if it is valid (spelled correctly). However, there are infinite sentences that can be constructed, with infinite meanings, so there is no way to correct a poorly written sentence without knowing what the meaning behind it is.

A: I think that what you are looking for is a language model. A language model assigns a probability to each sentence of k words appearing in your language. The simplest kind of language models are n-grams models: given the first i words of your sentence, the probability of observing the i+1th word only depends on the n-1 previous words.
For example, for a bigram model (n=2), the probability of the sentence w1 w2 ... wk is equal to
P(w1 ... wk) = P(w1) P(w2 | w1) ... P(wk | w(k-1)).

To compute the probabilities P(wi | w(i-1)), you just have to count the number of occurrence of the bigram w(i-1) wi and  of the word w(i-1) on a large corpus.
Here is a good tutorial paper on the subject: A Bit of Progress in Language Modeling, by Joshua Goodman.

A: I think what you are looking for is a well-established library that can process natural language and extract the meanings.
Unfortunately, there's no such library. Natural language processing, as you probably can imagine, is not an easy task. It is still a very active research field. There are many algorithms and methods in understanding natural language, but to my knowledge, most of them only work well for specific applications or words of specific types.
And those libraries, such as the CMU one, seems to be still quite rudimental. It can't do what you want to do (like identifying errors in English sentence). You have to develop algorithm to do that using the tools that they provide (such as sentence parser).
If you want to learn about it check out ai-class.com. They have some sections that talks about processing language and words.


text:
Q: How to calculate unique, 3D component vectors from 3D resultant vector knowing the component vector's unique lengths and fixed order? I'm trying to write a program that can calculate a user's 3D finger pose from only knowing the 3D position of the finger's tip and the lengths of the finger's proximal, middle, & distal phalanx.
I'm having trouble finding information or examples of this calculation online with this given constraint.

If I have 4, 3D vectors with these relationships and properties:

*

*A, B, C, R

*R = A + B + C (order of addition is fixed)

*|A| > |B| > |C|

How can I (or can I) calculate the component vectors if I only know their unique magnitudes and fixed order, as well as knowing the resultant vector thats formed from the combination of these component vectors?
or can someone point me in the direction of information that may help me figure this out?

A: You can't get the unique values of $A,B,C$ with that information given, since there are too many degrees of freedom. For example, you can rotate the construction around vector $R$ and although vectors $A,B,C$ will be rotated, their sum and absolute values won't change.
However, you can still try to guess in what "pose" the finger is, by assuming that the angle $\alpha$ between $A,B$ is the same as between $B,C$ and solving
$$(|A|+|B|\cos\alpha+|C|\cos2\alpha)^2+(|B|\sin\alpha+|C|\sin2\alpha)^2=|R|^2$$
which is a quadratic equation on $\cos\alpha$. If $\alpha=0$, the finger is straight. If $\alpha$ is close to $90°$, the finger is retracted. In addition, if you can guess the plane of the finger, you can construct vectors $A,B,C$ in it.


text:
Q: add class visible to grid-item but not those items that has class new I tried to add a class visible to .grid-items but not those hasClass('new').
I wrote this code but it doesn't seem to be working.
What is wrong here please?
html code:

//some code here

//some code here

//some code here

//some code here

//some code here

//some code here

//some code here

//some code here

js code:
var visibleTrue = $('.grid-item').hasClass('new');
if(visibleTrue){
  $('.grid-item').removeClass('visible');
}
else{
  $('.grid-item').addClass('visible');
}

A: I'm not sure what you wanna do.
Anyway, I suppose you have many .grid-item elements in your DOM, var visibleTrue become true when find one .grid-item with class "new".
At this point, visibleTrue still true and your code doesn't work for other divs.
I think you wanna cycle all the elements to check if they have the new class and in case add or remove "visible" class.
Try this:
$(document).ready(function(){
    $( ".grid-item" ).each(function() {
      if(!$(this).hasClass('new')){
        $(this).addClass('visible');
      }
    });
});

Here you can find .each reference https://api.jquery.com/each/

A: Add class visible where class .grid-item is there but not .new:
$(".grid-item").not('.new').addClass('visible');

Fiddle

A: Try this.
$('.grid-item').each(function(){
   if(!$(this).hasClass('new')){
        $(this).addClass('visible');
   }

});

Fiddle Link