text:
Q: Stepping through the Roslyn C# compiler I've built the Roslyn source as described here.
I'd like to add a breakpoint in the C# compiler and step through the compliation of this simple program:
using System;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            var result = 1 + 2;

            Console.WriteLine(result);
        }
    }
}

Where should I set a breakpoint? It should be early in the compilation process as I'd like to step through parsing and even lexing.
If I set CompilerExtension as the startup project and hit F5 (Start Debugging), a copy of Visual Studio is launched running the newly built compiler. I'd like to avoid having to launch a new instance of Visual Studio each time I'd like to step through the compiler. What's a good way to setup a small program which invokes the compiler code on the above source directly?

A: Here's one approach as suggested by Josh in a comment above.

*

*Add a new "Console Application" project to the Roslyn solution.

*Add these two references to the project:

A simple program to test the parser:
using Microsoft.CodeAnalysis.CSharp;

namespace TestCompiler
{
    class Program
    {
        static void Main(string[] args)
        {
            var program_text = @"

                using System;

                namespace ConsoleApplication2
                {
                    class Program
                    {
                        static void Main(string[] args)
                        { var result = 2 + 3; Console.WriteLine(result); }
                    }
                }
            ";

            var result = CSharpSyntaxTree.ParseText(program_text);
        }
    }
}

*

*Add a breakpoint to the line that calls ParseText.

*"Start Debugging" and step into that line to delve into the parser.
A simple program to test the compiler via Emit:
using System;
using System.IO;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;

namespace TestCompiler
{
    class Program
    {
        static void Main(string[] args)
        {
            var program_text = @"

                using System;

                namespace ConsoleApplication2
                {
                    class Program
                    {
                        static void Main(string[] args)
                        { var result = 2 + 3; Console.WriteLine(result); }
                    }
                }
            ";

            var syntax_tree = CSharpSyntaxTree.ParseText(program_text);

            var compilation = CSharpCompilation.Create(
                Guid.NewGuid().ToString("D"),
                new[] { syntax_tree },
                new[] { MetadataReference.CreateFromFile(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5.2\mscorlib.dll") });

            var emit_result = compilation.Emit(new MemoryStream());
        }
    }
}

A: If you want to have a simple program that invokes the compiler, just consider using csc as your startup project. You can specify the arguments to pass (like source files) from the debug settings on the project.


text:
Q: SQL - Display columns from two tables with where clause, preform count and GROUP BY COLUMNS in one table I have two tables. One table is the main  registered Boat table that holds most of the information. it has many columns one of them is [MFR CODE].
The other table is a reference table that contains all the records associated with only Business Boats and it has only 3 columns : [MFR CODE], [MFR NAME] & [MODEL]
I'm trying to find how many times (count) Business Boats appear in the Registered boat tables.
 SELECT
  Count(*) As 'TotalNumberBoats'
  , [BoatsReg].[dbo].[MASTER].[MFR MDL CODE]
  ,[BoatsReg].[dbo].[BusinessBoats].[MFR]
  ,[BoatsReg].[dbo].[BusinessBoats].[MODEL]
 FROM [BoatsReg].[dbo].[MASTER],[BoatsReg].[dbo].[BusinessBoats]
 Where [BoatsReg].[dbo].[MASTER].[MFR MDL CODE] =  [BoatsReg].[dbo].[BusinessBoats].[CODE]
  group by [BoatsReg].[dbo].[BusinessBoats].[CODE]
  order by TotalNumberBoats asc

*

*How do i get rid of all the square brackets, it's annoying.

*why do i get an error ?

A: Well when you aggregate a result, you have to specify all other fixed columns in the GROUP BY clause
(Answer edited to add total row with a UNION ALL and add a sort field to put the total row as last one)
In your case:
 SELECT 1 as sorted,
  ,Count(*) As TotalNumberBoats
  ,MASTER.[MFR MDL CODE]
  ,BusinessBoats.MFR
  ,BusinessBoats.MODEL
 FROM BoatsReg, BusinessBoats
 Where MASTER.[MFR MDL CODE] = BusinessBoats.CODE
 Group by
  ,MASTER.[MFR MDL CODE]
  ,BusinessBoats.MFR
  ,BusinessBoats.MODEL

 UNION ALL
 SELECT 2 as sorted,
  ,Count(*) As TotalNumberBoats
  ,'','',''
 FROM BoatsReg

 Order by sorted, TotalNumberBoats

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a tool/hack that enables dragging windows from one monitor to the other in Mission Control? Right now I have dual monitor set-up as shown below.

When I activate Mission Control it looks like this:

Now I want to drag the Finder windows to the other monitor as indicated by the arrow.
However, the window just jumps back to the original monitor.
I know ways of moving windows to other monitors outside of Mission Control, but doing this in Mission Control allows for moving groups of windows to different monitors.
Also I would like to keep the task of window arrangement in Mission Control.
I'm on the latest Mountain Lion. Is there some sort of hack, plugin or tool that will allow me to do this move in Mission Control?


text:
Q: Read ZIP file from cloud storage via the streaming library I need to read a zip file, located in the Google Storage Bucket, without unzipping using airflow. I am using a library called stream-unzip.
from stream_unzip import stream_unzip
import httpx

def zipped_chunks():
    # Iterable that yields the bytes of a zip file
    with httpx.stream('GET', "<google_bucket_file_path>") as r:
        yield from r.iter_bytes(chunk_size=65536)

for file_name, file_size, unzipped_chunks in stream_unzip(zipped_chunks(), password=b'my-password'):
    # unzipped_chunks must be iterated to completion or UnfinishedIterationError will be raised
    for chunk in unzipped_chunks:
        print(chunks)

The error which I got when I tried with above code is:
stream_unzip.TruncatedDataError

This zip file contains a text-file that have millions of lines. I need to stream these lines and get the data in each line on the fly. The airflow is deployed in the composer environment.
Please suggest a good solution for this.
Thank you


text:
Q: Can't change UITableViewCell size in Interface Builder Does anyone have the same problem as I do? ... I've upgraded to the iPhone SDK 3.2 and I am unable to resize UITableViewCell object in my XIB file (usually I've been just resizing the view but now the cell has the same size and there is just a grey are around) ... btw, I've tried to reinstall twice including one deep reinstall.

A: Hey I had this same issue. This is old, so maybe you found a solution already, but for those who haven't...
Select the cell in IB, and bring up the size panel (by clicking to it or with command-3). Under size & position, set to frame, and edit the height box there.
Easy, huh. Don't know how we missed this.

A: The tableviewcell size can be set by dragging the cell frame in the interface builder.
Then implement then tableview delegate tableView heightForRowAtIndexPath for the particular cell you want to have a different height.

A: I have 3.2 installed and don't have that issue.  Check that you are returning the correct cell height for heightForRowAtIndexPath.  So for a cell at section zero, row zero (that uses a custom UITableViewCell), use the height of the cell defined in the XIB:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0 && indexPath.row == 0)
        return m_customCell.frame.size.height;
    else
        return 44;
}

A: first tab (Attributes) -> subtab(Simulated User Interface Elements) -> Status Bar: set(Unspecified) .  Worked for me

A: The accepted answer (selecting the TableCell) and using the inspector did not work for me with XCODE 5.
This worked:
- In interface builder, select the TABLE VIEW (NOT the TableViewCell).
- Then in inspector (Size Inspector), notice at the top "Row Height". Set that as desired.
- Also notice Section Height can be set here too!
Final note, the table cell can definitely be drag/resized as well.


text:
Q: How to send and receive a large image using tcp (VB.NET) I need to send and receive a large image between programs running on different machines within the same network.
I've looked at using upd. However, I ran into problems with the size of the packets and (after breaking the image into smaller pieces to get past this problem) the number of packets needing to be processed all at once - and ultimately packet loss.
I've also thought of sending the image by storing it in a common file folder and receiving it by using file watcher as a trigger. However, this just adds further complexities in setup where common folders don't already exist.
Assuming I'm barking up the right tree looking at TCP, can someone point me to/provide an example of how to send an image file using it (VB.NET would be ideal). Also, are there practical limits to TCP package sizes?
If I am not barking up the right tree, and there is an easier way to do this I'd surely appreciate some guidance/examples.

A: Take a look at Socket.SendFile Method (MSDN).

A: Consider using WCF (Windows Communication Foundation) with TCP binding. You can even use streaming mode. You don't need to worry about packet size, etc. You only need to be careful about the size of the image. You will need to modify some settings in the service configuration file to allow large messages to be sent.
You can make a proof-of-concept application within a day (no fancy UI, just the absolute minimum functionality). And that is because you are new to the technology. Someone that has worked with WCF beore can do it in about one hour at normal speed.


text:
Q: Test if elements of one array are included in another I have the following arrays:
passing_grades = ["A", "B", "C", "D"]
student2434 = ["F", "A", "C", "C", "B"]

and I need to verify that all elements in the student array are included in the passing_grades array. In the scenario above, student2434 would return false. But this student:
student777 = ["C", "A", "C", "C", "B"]

would return true. I tried something like:
if student777.include? passing_grades then return true else return false end

without success. Any help is appreciated.

A: PASSING_GRADES = ["A", "B", "C", "D"]

def passed?(grades)
  (grades - PASSING_GRADES).empty?
end

similar to what CDub had but without bug. more readable in my opinion

A: You could have a method that does the difference of the arrays, and if any results are present, they didn't pass:
PASSING_GRADES = ["A", "B", "C", "D"]

def passed?(grades)
  grades.all? {|grade| PASSING_GRADES.include?(grade)}
end

Example:
1.9.3-p484 :117 > student777 = ["C", "A", "C", "C", "B"]
 => ["C", "A", "C", "C", "B"]
1.9.3-p484 :118 > passed?(student777)
 => true
1.9.3-p484 :118 > passed?(student2434)
 => false


text:
Q: Finding number of nonnegative solutions for the equation $x_1+ x_2+ x_3+ x_4+ x_5=9$ when $x_1 \geq 1, x_5 \leq 5$ I need to find the number of nonnegative solutions for the equation $$x_1+ x_2+ x_3+ x_4+ x_5=9$$ when  $x_1 \geq 1, x_5 \leq 5$.
I know I need to use $\binom{n+k-1}{k-1}$ and Inclusion–exclusion, but I'm not sure how to use it properly with the conditions.
It will be great if someone will explain to me how to choose the $n,k$.

A: In general with stars and bars we find that there are $\binom{n+k-1}{k-1}$ solutions for:$$y_1+\cdots+y_n=k$$where the $y_i$ are nonnegative integers.
In your case we can at first hand go for $n=5$, $y_1=x_1-1$, $y_i=x_i$ for $i=2,3,4,5$ and $k=9-1=8$.
Then however we overlooked the constraint $y_5=x_5\leq5$.
This can be repaired by subtracting the number of solutions that satisfy $y_5\in\{6,7,8\}$ or equivalently: $$y_1+y_2+y_3+y_4\in\{0,1,2\}$$
Again using stars and bars (3 times) we can find these numbers.

A: The number of non negative solutions is equal to the coefficient by $z^9$ in the series
$$
\frac{z(1+z+z^2+z^3+z^4+z^5)}{(1-z)^4}=z+5\,{z}^{2}+15\,{z}^{3}+35\,{z}^{4}+70\,{z}^{5}+126\,{z}^{6}+209\,{z}^{7}+325\,{z}^{8}+480\,{z}^{9}+\cdots
$$
Thus the aswer is $480.$

A:
Find the number of nonnegative integer solutions of the equation $$x_1 + x_2 + x_3 + x_4 + x_4 + x_5 = 9$$ satisfy the restrictions $x_1 \geq 1$ and $x_5 \leq 5$.

If $x_1 \geq 1$, $x_1' = x_1 - 1$ is a nonnegative integer.  Substituting $x_1' + 1$ for $x_1$ in the equation
$$x_1 + x_2 + x_3 + x_4 + x_4 + x_5 = 9 \tag{1}$$
yields
\begin{align*}
x_1' + 1 + x_2 + x_3 + x_4 + x_5 & = 9\\
x_1' + x_2 + x_3 + x_4 + x_5 & = 8 \tag{2}
\end{align*}
Equation 2 is an equation in the nonnegative integers with
$$\binom{8 + 5 - 1}{5 - 1} = \binom{12}{4}$$
solutions, each of which is a solution of equation 1 that satisfies the requirement that $x_1 \geq 1$.
However, they include solutions of equation 1 in which $x_5 > 5$.  Since the variables represent integers, if $x_5 > 5$, then $x_5 \geq 6$.  Hence, we can eliminate those solutions which violate the restriction that $x_5 > 5$ by subtracting those solutions of equation 2 in which $x_5 \geq 6$.
Suppose $x_5 \geq 6$.  Let $x_5' = x_5 - 6$.  Then $x_5'$ is a nonnegative integer.  Substituting $x_5' + 6$ for $x_5$ in equation 2 yields
\begin{align*}
x_1' + x_2 + x_3 + x_4 + x_5' + 6 & = 8\\
x_1' + x_2 + x_3 + x_5 + x_5' & = 2 \tag{3}
\end{align*}
Equation 3 is an equation in the nonnegative integers with
$$\binom{2 + 5 - 1}{5 - 1} = \binom{6}{4}$$
solutions.
Hence, the number of solutions of equation 1 which satisfy the restrictions $x_1 \geq 1$ and $x_5 \leq 5$ is
$$\binom{12}{4} - \binom{6}{4}$$


text:
Q: Does the definite article change the meaning? What is the difference
On the biggest issue facing our country since the second world war, Labour should be committed to providing the opportunity for people to change their mind.
VS
On the biggest issue facing our country since the second world war, Labour should be committed to providing an opportunity for people to change their mind.

A: A search against news sources will show that they are used interchangeably.
However, many years ago, I remember being taught that there was a subtle difference - that the definite article was to be used where it was linked to a specific action:

Labour should commit to a 2% increase in spending in order to provide
  people with the opportunity to...

While the indefinite article fitted better where the situation was more generalised:

Housing affordability is a major problem, Labour should do more to
  provide people with an opportunity to buy their first home

But, I can find absolutely no evidence to support this and suspect that it was more to do with a particular teacher's preferences.
For completeness, it's worth noting that, often, the article is not required if you can use a plural:

Labour should be committed to providing opportunities for people to
  change their mind.


text:
Q: Zeroing an Unusual Array I have a bit of C code, reproduced below. It is my understanding that it is setting certain bits of the BootPML4 array to a certain value. Could someone please explain how the BootPML4 array below is filled? Also, how do I ensure that unused values in the array are zeroed, while ensuring that the two settings below remain intact?
typedef uint64_t pml4_entry_t;
#define PML4_PROT (INTEL_PTE_VALID | INTEL_PTE_WRITE)
pml4_entry_t BootPML4[PTE_PER_PAGE] __attribute__((section("__HIB, __bootPT"))) = {
    [0]                 = ((uint64_t)(PAGE_SIZE) | PML4_PROT),
    [KERNEL_PML4_INDEX] = ((uint64_t)(PAGE_SIZE) | PML4_PROT),
};

A: This is using designated initializers which was added in C99, The Forward section of the C99 draft standard in paragraph 5 says:

[...] Major changes from the previous edition include:

and has the following bullet:

— designated initializers

and the details are covered in section 6.7.8 Initialization and provides the following example in paragraph 36 and 37:

EXAMPLE 12 Space can be ''allocated'' from both ends of an array by using a single designator:
int a[MAX] = {
  1, 3, 5, 7, 9, [MAX-5] = 8, 6, 4, 2, 0
};

In the above, if MAX is greater than ten, there will be some zero-valued elements in the middle; if it is less
  than ten, some of the values provided by the first five initializers will be overridden by the second five.

The gcc doc on designated initializers has a better example:

To specify an array index, write '[index] =' before the element value. For example,
int a[6] = { [4] = 29, [2] = 15 };
is equivalent to
int a[6] = { 0, 0, 15, 0, 29, 0 };
The index values must be constant expressions, even if the array being initialized is automatic.


text:
Q: passing data from data set to a dictionary Basically I have a data set with some data a data base table, I want to pass the data to a dictionary, what could be a good way yo accomplish my goal. Assuming that the dictionary have this structure
Dictionary<int,string>

I'm looking for some method to bind the rows of the dataset with the key and value of the dictionary.

A: Your question is pretty vague, if your dataset implements IEnumerable or IQueryable you can use the ToDictionary extension method:
Dictionary<int, string> dict = data.ToDictionary(e => e.id, e => e.name);


text:
Q: Why is the center of buoyancy located at the center of mass of the displaced fluid volume? Consider Archimedes' principle

Any object, wholly or partially immersed in a fluid, is buoyed up by a force equal to the weight of the fluid displaced by the object.

I do not understand why the center of buoyancy is the center of mass of the volume of the displaced fluid.
In principle it could be another point, for istance the center of mass of the object (not the displaced fluid) or maybe a point of the displaced fluid but not the center of mass.
Is there an simple way to understand why the center of buoyancy located in the center of mass of the displaced volume of fluid?

A: Let us suppose we remove the object and fill the space left (in the fluid) with the same fluid. Assume this portion of fluid become solid without changing its volume or density. It will be in equilibrium with the fluid. Now suppose the buoyancy force on this solidified portion is off the center of mass. This would imply non vanishing resultant force or torque and the solidified portion would not be in equilibrium. A kind of inverse argument can also be given. Suppose the center of buoyancy coincides with the center of mass of an object immersed in a fluid. Then you would never observe resultant torque (by means of rotations) on any object. And that is empirically not true.


text:
Q: Parse directive from text returned from ajax - angularjs I have a directive in angularjs, and success to use it like below:

can show
Hello

When I load it from an ajax call. For example, my data returned from ajax call:
$scope.ajaxData = {title: 'Title', data = '
load from directive like this: <div

'}

and in my template.

Title: {{ajaxData.title}}

But it not bind to directive, just show html code:

Would you please tell me how to bind the directive from text like my case
Thank you very much.


text:
Q: What is the meaning of this expression I am trying to push a integer that is stored in a string to a stack of type int I was trying to do the same by using stack.push(str[i]) which resulted in some weird values in the final outcome
Github copilot suggeted to do it this way which was succesfull
else
       {
           temp.push(exp[i]-'0');
       }

what is the meaning of -'0' here

A: The char '0' has ascii value 0x30 (48 decimal).
The char '9' has ascii value 0x39 (57 decimal).
If you do '9' - '0' = 57 - 48 = 9.
So you are converting a digit from its ascii number '9' = 57 to its numeric value 9.
This is often used when fast-converting a string of integers to its numeric value.


text:
Q: How to determine the signature of a Hermitian form When tasked to find the rank/signature of say $16xy-z^2$ over $\mathbb{R}$, I proceed by writing it in the form $(2x+2y)^2-(2x-2y)^2-z^2$, and concluding that the rank is $3$, say.
For Hermitian forms, does this equivalent procedure involve using modulus brackets, or standard square brackets? I.e. if I can write a Hermitian form as $\psi(x, x) = a|A(x)|^2+b|B(x)|^2+c|C(x)|^2$ (where $a, b, c$ are all $+1$ or $-1$), can I conclude that the rank is $3$? As an example, consider Finding the rank and signature of a hermitian form


text:
Q: MySQL pattern replace Would it be possible to do a little more 'advanced' string replacing in a MySQL query? I read about the REPLACE() method, but as far as I know, it cannot be used for fancy stuff.
Basically, what I'm trying to do is remove all HTML tags from a specific column in a large dataset. Being able to do this in a single query would be a lot cooler than having to use PHP to do the processing in between. Can I do something elegant in order to remove everything encapsulated in < >?
I just realized there's another small catch to it... due to some improper data conversions before, some of the tags now contain < and > themselves... Worst cases look like <(><<)>b>. Don't even ask how, but something seems to have gone terribly wrong. Anyhow, great minds with great ideas on this?

A: Short answer: no, this cannot be done in SQL.  This is the sort of work you'd need to do in a programming language — any programming language you have handy, really.
Given that this isn't proper HTML, parsing it with traditional methods may even be out of the question.  Perhaps some horribly hackish regular expressions would help, or perhaps you'll get some mileage out of finding particular "buggy" strings (e.g., if (><<)> appears commonly) and deleting them witha  traditional REPLACE().
The details, of course, would depend on your data and what tools you have available, but MySQL won't be able to do the bulk of that work.

A: You can hack up a function, but I don't think that's the way to go.
CREATE FUNCTION strip_tags( String VARCHAR(9999) )
RETURNS VARCHAR(9999)
DETERMINISTIC
BEGIN
  DECLARE start, end, len INT;
    SET start = LOCATE('<', String);
    SET end = LOCATE('>', String, start);
    WHILE start> 0 AND end > 0 DO
      BEGIN
        SET String = INSERT(String, start, end, '');
        SET start = LOCATE('<', String);
        SET end = LOCATE('>', String, start);
      END;
    END WHILE;
  RETURN String;
END;

Disclaimer: the code is untested.

A: Sorry, you're out of luck.  MySQL has no regex or comparable replacement faculty.


text:
Q: Running a process in an external cmd window and then exiting it after a time I'm trying to write a batch script to start docker service, but I want that service to stop and restart every hour or so.
But how do I make the exit command override the running docker service?
start "s1" cmd /c ""C:\Program Files\Docker\Docker\resources\dockerd" -H tcp://0.0.0.0:2375 && timeout 5 & exit"


text:
Q: Cakephp 2.4 isn't reading .po files I created the following file :
/Locale/fra/LC_MESSAGES/default.po
Content:
msgid "delete"
msgstr "effacer"

I set the the default language to fra in core.php
Configure::write('Config.language', 'fra');

when i use

<?php echo __("delete"); ?>

the output should be "effacer" which isn't the case
I tried importing i18n class and setting i10n manually but the issue persist
App::import('I18n', 'i18n');
$I18n =& I18n::getInstance();
$I18n->l10n->get($this->params['lang']);

When i check the persistent cache "myapp_cake_core_default_fra" i find an empty array

A: Set this language code with language parameter
 Configure::write('Config.language','en_Us');


text:
Q: Resources on exterior algebra, wedge product, geometric product and tensors I would like to learn exterior algebra, wedge product and geometric product along with their applications in physics. Is there a good source you can recommend? Should I study differential geometry in order to grasp them? I started studying tensor analysis but even the concept of contravariance and covariance is not explained well enough in most of the textbooks. I would be grateful if you point at a source that guides one well and assumes no prior knowledge of the topics except calculus and linear algebra.

A: Personally, when I came to the subject of exterior algebra I found no better a text than R.W.R Darling's Differential Forms and Connections: see link here


text:
Q: Two questions about the package enumitem I am not very good in LaTeX, so sorry for my silly question. ;)
I've just added the package enumitem to my tex-file for having a line break after each label of \begin{description}. That works very fine!
Problem 1)
I just saw, that the "dots" of my \begin{itemize} items disappeared
Problem 2)
Without the use of the package enumitem the labels of the description are colored. How can I get this colored labels while using the package?
Thank you very much for your help!!
Here is my MWE:
\documentclass{beamer}

\usetheme{Boadilla}

\usepackage{enumitem}
\setlist{
    style=nextline
}

\begin{document}

\begin{frame}

\begin{description}
    \item[Item1] Description of item 1.
    \item[Item2] Description of item 2.
\end{description}

\begin{itemize}
    \item Where are
    \item the dots?
\end{itemize}

\end{frame}

\end{document}


text:
Q: Why I can't access the servlet after the session time out? I have a JSP, Servlet, Hibernate application. In this application I have a very weird problem. That is, if the session got expired (in other words "time out") and when the user click on a link the page will be redirected to the index page, but after that the user is not able to log in and access the last link he clicked. I will describe it step by step in below.

*

*User log into the application. Session get created.

*He access the path /Passport

*User is now idle, session get expired.

*User come back and click on link to access /Visa . Since the session is now idle, user will be redirected to index page.

*User log in.

*Click on the link to access /Visa (from anywhere where the link is available)
. The link is an  where it links to its path like
Visa?idEmployee=1

*Now the problem. User is redirected back to index page.
I have Filter to monitor whether the session is null and whether the required session attributes are not null. If the request do not fulfill the mentioned 2 conditions, the request will be sent back to the index.
The filter code is below.
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package Filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author user
 */
public class AuthenticationFilter_Level1 implements Filter
{

    @Override
    public void init(FilterConfig filterConfig) throws ServletException
    {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException
    {
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)res;

        HttpSession session = request.getSession(false);
        Integer attribute = null;

        if(session!=null && session.getAttribute("idSubUser")!=null)
        {
            chain.doFilter(req, res);

        }
        else
        {
            //response.sendRedirect("index.html");
            RequestDispatcher dispatch = request.getRequestDispatcher("index.html");
            dispatch.forward(req, res);
        }

    }

    @Override
    public void destroy()
    {

    }

}

In web.xml, I have added the filter from servlet to servlet, like below.
 <filter-mapping>
        <filter-name>AuthenticationFilter_Level1</filter-name>
        <url-pattern>/RegSrvlt</url-pattern>
        <url-pattern>/AdminPopulateSrvlt</url-pattern>
        <url-pattern>/AgentPopulate</url-pattern>
......

Filter session timeout is configured as below.
<session-config>
        <session-timeout>
            1
        </session-timeout>
    </session-config>

So, what is happening here?
Update
When the above error happens, the URL actually looks like http://localhost:8080/xxx/Visa?idEmployee=1 even though it is redirected!
UPDATE
I found this has no connection with the filter. Then what can make this?

A:     else
    {
        if (session != null) {
            session.invalidate();
        }
        ...

And check the where sessions are created (i.e. public JSPs/servlets).

A: Another possible cause could be a problem of caching in browser :

*

*client browser asks for /Visa

*server sends index.html => browser caches it as it is a nice html page

*...

*on same browser session, user clicks on a /Visa links

*without even asking anything to server, browser displays cached index.html page

How do confirm :

*

*server side, by looking the server logs to see if the page was actually requested

*client or server side by using a network spy such as wireshark and look if a request is sended

*client side by emptying the cache and not the cookies

How to fix :

*

*try to add a header asking not to cache the page before forwarding to index.html - it should be possible but I do not exactly know the proper header configuration

*replace the forward to index.html with a redirection. That way the browser should not cache index.html for the /Visa URL


text:
Q: nested queries in laravel Here is my sql, i am struggling to translate this to laravel 5.8 query builder syntax.
    SELECT CC AS CountOfVisits, Count(CC) AS Users
    FROM
        (
        SELECT user_id, count(user_id) AS CC FROM mytable
        GROUP BY user_id
        ) AS CC
    GROUP BY CC;

I tried this:
     $frequency= DB::connection('mysql2')
            ->select(DB::raw('CC AS CountOfVisits'), DB::raw('Count(CC) AS Users'))
            ->from(function($sq)
            {
               $sq->select(DB::raw('user_id, count(user_id) AS CC FROM '))
                    ->from('mytable')
                    ->groupBy('user_id');
            })
            ->groupBy('CC')
            ->get();

it errors with

Argument 1 passed to Illuminate\Database\Connection::prepareBindings()
  must be of the type array, object given, called in
  /var/app/portal/vendor/laravel/framework/src/Illuminate/Database/Connection.php
  on line 665

Any help would be great thanks

A: I think the problem you're having is that the returned connection is expecting string for the full query with additional bindings on the second parameter. You can still build it using illuminate's query builder first if you like, then run the select using the generated string.
$query = DB::query()
    ->select('CC AS CountOfVisits', DB::raw('count(CC) AS Users'))
    ->fromSub(function (\Illuminate\Database\Query\Builder $query) {
        $query->select('user_id', DB::raw('count(user_id) AS CC '))
            ->from('mytable')
            ->groupBy('user_id');
    }, 'CC')
    ->groupBy('CC');

$result = DB::connection()->select($query->toSql());


text:
Q: Uncertain_conversion_exception in Nef polyhedra I an using Nef Polyhedra for some 3D boolean operation. I first convert a bunch polyhedron_3 meshes into Nef_polyhedron_3 meshes and then perform the boolean operation. However, almost any manipulation of the Nef polyhedra results in a bunch of Uncertain_conversion_exception. I tried running CGAL with CGAL_PROFILE profile. This told me that the I get this exception on two different types. These are
GCAL::Uncertain<enum CGAL::Sign>
CGAL::Uncertain<bool>

Especially the second is thrown a lot. They are throw both when converting meshes into Nef polyhedra and during the boolean operations them selves. The call that that throws the exception is made in Filtered_predicate. The exceptions are being handled here and the boolean operation returns the expected result. However, the exceptions seems to slow down the operations quite a bit.
I am experiencing this with CGAL 4.7 on windows using visual studio 2015.I have the following symbols defined for the preprocessor
WIN32;
_WINDOWS;
_CRT_SECURE_NO_DEPRECATE;
_SCL_SECURE_NO_DEPRECATE;
_CRT_SECURE_NO_WARNINGS;
_SCL_SECURE_NO_WARNINGS;
_DEBUG;CGAL_USE_MPFR;
CGAL_USE_GMP;
BOOST_ALL_DYN_LINK;
CMAKE_INTDIR="Debug";
CGAL_EXPORTS;

CGAL is built with the flags: /GR, /EHsc, fp:strict,  fp:except-, /wd4503 and /bigobj.
Additionally the project that includes CGAL is build with the flags: /GS /Zc:wchar_t /Zc:inline /fp:precise /Zc:forScope /clr /MDd /EHa
I left out a bunch flags that didn't seem relevant like include flags.
Is this expected behavior or can i do something to avoid it?


text:
Q: Trying to understand the /etc/resolv.conf I am trying to understand the entries in the /etc/resolv.conf file in linux systems.
The file contains a list of keywords and values.
This is an example of the contents of the /etc/resolv.conf:
domain xxx.net
search xxx.net
nameserver 192.168.1.254

I understand that the nameserver entry is the default nameserver that the OS uses to resolve DNS queries.
My question is what is the domain and search keyworks and their associated values??

A: You can get the information you are looking for in the man pages:
man resolv.conf
...
   domain Local domain name.
          Most queries for names within this domain can  use  short  names
          relative to the local domain.  If set to '.', the root domain is
          considered.  If no domain entry is present, the domain is deter‐
          mined  from  the  local hostname returned by gethostname(2); the
          domain part is taken to  be  everything  after  the  first  '.'.
          Finally,  if  the  hostname  does not contain a domain part, the
          root domain is assumed.

   search Search list for host-name lookup.
          The search list is normally determined  from  the  local  domain
          name;  by default, it contains only the local domain name.  This
          may be changed by listing the desired domain search path follow‐
          ing the search keyword with spaces or tabs separating the names.
          Resolver queries having fewer than ndots dots (default is 1)  in
          them  will  be attempted using each component of the search path
          in turn until a match is found.  For environments with  multiple
          subdomains  please  read  options ndots:n below to avoid man-in-
          the-middle attacks and unnecessary  traffic  for  the  root-dns-
          servers.  Note that this process may be slow and will generate a
          lot of network traffic if the servers for the listed domains are
          not local, and that queries will time out if no server is avail‐
          able for one of the domains.

          The search list is currently limited to six domains with a total
          of 256 characters.

So in your case where you have domain xxx.net it means you could reference things in that domain without listing it: ping server_name.xxx.net or ping server_name would both resolve correctly.
search is a list of other domains to try to make the short name resolve after domain has failed. The main difference is that if no domain is listed it will be guessed based on the local hostname, search names necessarily need to be explicitly listed.


text:
Q: How to get specific node values from SOAP XML response I want to get the value of the following nodes:
ResponseMessage, Response Result and VelocitiHotLeadID
from this SOAP XML response:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<SubmitHotLeadDetailsResponse xmlns="http://tempuri.org/">
<SubmitHotLeadDetailsResult xmlns:a="http://schemas.datacontract.org/2004/07/Velociti.Webservice.VelocitiHotLead" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <a:ResponseMessage>1:VendorID Does Not Exist 2:IDNumber is invalid.</a:ResponseMessage>
    <a:ResponseResult>false</a:ResponseResult>
    <a:VelocitiHotLeadID>0</a:VelocitiHotLeadID>
</SubmitHotLeadDetailsResult>
</SubmitHotLeadDetailsResponse>
</s:Body>
</s:Envelope>

I've tried to use this code but it did not work:
$xml = simplexml_load_string($result, NULL, NULL, "http://schemas.xmlsoap.org/soap/envelope/");
$xml->registerXPathNamespace('s', 'http://schemas.xmlsoap.org/soap/envelope/');
$xml->registerXPathNamespace('a', 'http://schemas.datacontract.org/2004/07/Velociti.Webservice.VelocitiHotLead');
$xml->registerXPathNamespace('i', 'http://www.w3.org/2001/XMLSchema-instance');
foreach($xml->xpath('//a:ResponseMessage') as $response)
{
   echo $response;
}


text:
Q: Scala - control structure I am entirely new to Scala world and trying to understand few Scala concepts. From here I got below piece of Scala Code.
def twice(op: Double => Double, x: Double) = op(op(x))

and by calling twice(_ + 1, 5) returning the result Double = 7.0. But I couldn't able to understand what _ + 1 and op: Double => Double really means. Can someone able to explain me the above piece of code?

A: op: Double => Double

op is a function that takes a value of type Double and returns a new value of type Double.
_ + 1

_ is the placeholder for an argument to this anonymous function (i.e. this function is described but has no name. Once it is received in the twice method it has the name op.)  So this function takes an argument, adds 1 to it, and returns the new value.
If you call twice(_ + 1, 5) you can think about it like this: op(op(x)) --> op(op(5)) --> op(5 + 1) --> op(6) --> 6 + 1 --> 7 (or 7.0 because it is of type Double)


text:
Q: Why does /(red|green)/g.exec('red, green, red, green') return ["red", "red"]? In my javascript console I typed
/(red|green)/g.exec('red, green, red, green')
And it returned an array with two results:
["red", "red"]
Shouldn't it return an array with 4 results? As in:
["red", "green", "red", "green"]?

A: As the comment states you want the string method match:
> 'red, green, red, green'.match(/(red|green)/g)
["red", "green", "red", "green"]

A: The exec returns only the first match even if you specify g global flag.

The exec() method executes a search for a match in a specified string. Returns a result array, or null.

Because the first element in the array is the complete match string and second element of the array is the capturing group which is enclosed inside () in the regex.
If you try this regex:
/(red|green),/g.exec('red, green, red, green')

You'll get
["red,", "red"]

A: The way exec works is by returning an array* of results AND modifying the regex object.
*) returns null if no match found.
The returned array contains the entire matched string at index 0, and 1 entry per matched group.
In your example, the returned result is:
[0] = "red" <-- The entire match
[1] = "red" <-- The match for the first group
For example, the next snippet returns THE SAME RESULT:

alert(JSON.stringify(/(red|green)/g.exec('red, green, red, green, red, green, red, green')))

And the next one returns an array with 3 entries (Whole match, 2 groups):

alert(JSON.stringify(/(red|green), (red|green)/g.exec('red, green, red, green, red, green, red, green')))

A: Given the following string and regex
var str = "red, green, red, green";
var re = /(red|green)/g;

With exec()
var m;
while ((m = re.exec(str)) !== null) {
  console.log(m);
}

Output:
["red", "red"]
["green", "green"]
["red", "red"]
["green", "green"]

The returned array has the matched text as the first item, and then one item for each capturing parenthesis

and

If your regular expression uses the "g" flag, you can use the exec() method multiple times to find successive matches in the same string. (ref)

With match()
console.log( str.match(re) );

Output:
["red", "green", "red", "green"]


text:
Q: I want my loop to run until the result of the equation equals the previous result I am writing a code in FORTRAN to calculate the position of the planets. I need to solve Kepler's equation using newtons numerical method and I am having trouble with my loop. The code is shown below. I can compile it with no error messages, but it wont run. It just gets stuck in a forever loop. I want the loop to run until E(i) and the following result are equal. Any help would be greatly appreciated.
do while (E(i)/=E(i+1))
    E(1)=M
    E(i+1)=E(i)-((M-E(i)+(p*sin(E(i))))/((p*cos(E(i)))-1))
end do

Also, how do i define the variable 'E' at the beginning of my program. I currently have this but the '11' is only because I originally had my loop run 10 times. If I don't specify the number of times I want the loop to run, how do i define the variable?
double precision :: E(11)

A: I did not check if your convergence implementation is correct, but you definitely do not want to check for exact equality. You must allow for some inexactness, because floating point calculations are inexact
     (abs(E(i)-E(i+1))<eps)

where eps is some small number.
As @agentp suggests you don't change i, so you always work with 2 values E(i) and E(i+1) (i being whatever you set it before the loop). You do not use any other elements of your array.
For the array which can have any length, depending on your need, you could theoretically use
     double precision, allocatable :: E(:)

but you probably do not want to use an array at all and you just want two scalar values
 double precision :: E1, E2

 E1 = M
 do
    E2 = E1 - ((M-E1+(p*sin(E1))) / ((p*cos(E1))-1))

    if (abs(E1-E2) < eps) exit
    E1 = E2
 end do

Note that the kind notation (real(....)) is preferable in new code instead of the old double precision.


text:
Q: How to calculate the gradient of log det matrix inverse? How to calculate the gradient with respect to $X$ of:
$$
\log \mathrm{det}\, X^{-1}
$$
here $X$ is a positive definite matrix, and det is the determinant of a matrix.
How to calculate this? Or what's the result? Thanks!

A: I assume that you are asking for the derivative with respect to the elements of the matrix. In this cases first notice that
$$\log \det X^{-1} = \log (\det X)^{-1} = -\log \det X$$
and thus
$$\frac{\partial}{\partial X_{ij}} \log \det X^{-1} = -\frac{\partial}{\partial X_{ij}} \log \det X = - \frac{1}{\det X} \frac{\partial \det X}{\partial X_{ij}} = - \frac{1}{\det X} \mathrm{adj}(X)_{ji} = - (X^{-1})_{ji}$$
since $\mathrm{adj}(X) = \det(X) X^{-1}$ for invertible matrices (where $\mathrm{adj}(X)$ is the adjugate of $X$, see http://en.wikipedia.org/wiki/Adjugate).

A: Or you can check section A.4.1 of the book Stephen Boyd, Lieven Vandenberghe, Convex Optimization for an alternative solution, where they compute the gradient without using the adjugate.

A: The simplest is probably to observe that
$$-\log\det (X+tH) =  -\log\det X -\log\det(I+tX^{-1}H)
\\= -\log\det X - t \textrm{Tr}(X^{-1}H) + o(t),$$
where is used the "obvious" fact that $\det(I+A) = 1+\textrm{Tr}(A)+o(|A|)$ (all the other terms are quadratic expressions of the coefficients of $A$).
Notice that $\textrm{Tr}(X^{-1}H)=(X^{-T},H)$ in the Frobenius scalar product, hence $\nabla [-\log\det(X)] = -X^{-T}$ in this scalar product. (This gives another proof that $\nabla\det (X) = cof(X)$.)
Of course if $X$ is symmetric positive definite then $-X^{-1}$ is also a valid expression. Moreover, one has in this case, for $X,Y$ positive definite, $(-X^{-1}+Y^{-1},X-Y)\ge 0$.

A: Warning!
The answers given so far work only if $X \in \mathbb{R}^{n\times n}$ is not symmetric and has $n^2$ independent variables! If $X$ is symmetric, then it has only $n(n+1)/2$ independent variables and the correct formula is
$$\frac{\partial \log\det X^{-1}}{\partial X} = -\frac{\partial \log\det X}{\partial X} = -(2X^{-1}-\text{diag}(y_{11}, \dots, y_{nn})),$$
where $y_{ii}$ is the $i$ the entry on the diagonal of $X^{-1}$. This question explains why this is the case.


text:
Q: how to solve path fill color Here is my code,
<svg height="210" width="400">
  <path stroke="#C4C24A" fill="red" d="M50 50 L100 50 L100 100 L150 100" />
</svg>

in this code i have used fill and stroke while run this the fill and stroke both's are applied. here i have used MoveTo LineTo LineTo...
another one ,
<svg height="210" width="400">
  <path stroke="#C4C24A" fill="red" d="M50 50 L100 50
  M100 50 L100 100
  M100 100 L150 100" />
</svg>

in this code i have used MoveTo LineTo MoveTo LineTo.. Same output displayed here but fill color was not applied..
why? and in first example i need to show the output without applying fill color what can i do without changing path and fill?

A: This example might clarify it:

<svg height="210" width="400">
  <path stroke="#C4C24A" fill="red" d="
    M50 50
    L100 50
    L100 100
    L150 100
    M250 50
    L300 50
    L300 100
    L350 100" />
</svg>

Path will create a polygon if you have more than two points. With two points you make a line. Each time you lift your pen by using M, you start from scratch.
So in your first example, you are making a four-point polygon. In your second example, you are making three disconnected lines. You can fill a four-point polygon, but a line is a bit too thin to fill.


text:
Q: Only return results from first table with two joins I have 3 tables. I need to get lastname, firstname, and employee number from the first table and name from another table.
In order for me to get the name on table s there needs to be a match between the slsrep columns on table s and table sw.
The issues is that I only want to return the rows from the first table (p). There is only 700 records in the first table but it is pulling 900.
Basically, I just want to look at each row in the table p and match the name from table s.
This is what I currently have:
SELECT p.LastName,
       p.FirstName,
       p.EmpNo,
       s.Name
FROM   PDDA..PhoneDirectory p
       LEFT OUTER JOIN nxtsql..swsmsn sw
            ON  p.EmpNo = sw.EmpNo
       JOIN NxtSQL..SMSN s
            ON  sw.slsrep = s.slsrep
WHERE  sw.statustype = 1
ORDER BY
       p.LastName

A: There are lots of ways to do this.   One is to use a sub-select to get s.Name:
SELECT p.LastName, p.FirstName, p.EmpNo, (
  SELECT TOP 1 s.Name
  FROM NxtSQL..SMSN s
  INNER JOIN nxtsql..swsmsn sw
    ON sw.slsrep = s.slsrep
  WHERE p.EmpNo = sw.EmpNo
  AND sw.statustype = 1
) AS Name
FROM PDDA..PhoneDirectory p
ORDER By p.LastName


text:
Q: EC2ResponseError: 401 Unauthorized AWS was not able to validate the provided access for an ec2 instance I have two ec2 instances A and B both in same region, security group etc.
I use boto to perform connection.
After updating boto from version 2.34.0 to version 2.35.0 I cannot connect to host from instance A, but able to connect from instance B.

AuthFailureAWS was not able to validate the provided access credentials

I have found out that possible reason of such issue is that boto Switch elb/ec2 over to signature version 4
How does that possible that I am able to connect from machine B, but couldn't connect from machine A ?( python code responsible for connection same on both instances)
What could cause such strange situation ? Thanks

A: The SigV4 authentication method places a greater demand on keeping the clock on the requesting device in sync with the clock on the server.  It's possible that the clock on the instance that is no longer working has drifted past the 5 minute limit but is still within the 15 minute limit required by the previous SigV2 signing algorithm.
Try sync'ing the clock on both instances.


text:
Q: Getting react-widgets' elements to align in row-wise flexbox I'm having trouble integrating react-widgets (Dropdownlist and Multiselect) with my styling in the same way as the input-fields I've used before.
It should look like this:

With the white rectangles beeing react-widgets Dropdownlists respectively Multiselect.
Here's a codepen-example, with the second blue block containing react-widget's markup: http://codepen.io/peletiah/pen/ORLaGr
This is the relevant (simplified) markup:

.route {
  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
}

.sequence {
  display: flex;
  height: 90px;
  line-height: 90px;
}

.action {
  align-self: center;
  line-height: normal
}

            <input value="set">

            <input value="data goes here">

set

          <input>

The markup inside the action-div in the second "sequence" is produced by react-widget, so I have a no influence and can't easily replace them with spans.
The widgets are supposed to be aligned next to each other like the inputs in the first sequence, but they are stacked on top of each other.
Is it possible to fix this with css?
In the codepen-example above I've included the react-widgets less-code in the upper part of the css-section of the codepend, at then end of it is my custom css.

A: There where two issues with the original code-sample.
Vertical alignment of the "action"-container inside the "sequence"-container was achieved by setting "line-height".
The line-height is also responsible for the 90px-high "rw-multiselect-wrapper"-div, which it inherits from the "sequence"-class.
Flexbox allows self-alignment of children with the "align-self"-property.
Adding an "align-self" to the class and wrapping each react-widget-div's in their own "action"-div fixes the alignment issue and the height-issue.

.route {
  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
}

.sequence {
  display: flex;
}

.action {
  align-self: center;
}

            <input value="set">

            <input value="data goes here">

    2

bridge

          test
          <input>

Codepen-sample: http://codepen.io/peletiah/pen/ozjNpW


text:
Q: Ошибка: Illegal string offset php массив есть массив
 Array
    (
        [44] => Array
            (
                [id] => 44
                [title] => Категория 1
                [link] => #
                [parent_id] => 0
                [children] => Array
                    (
                        [53] => Array
                            (
                                [id] => 53
                                [title] => Категория 1_1
                                [link] => #
                                [parent_id] => 44
                            )

                        [57] => Array
                            (
                                [id] => 57
                                [title] => Категория 45
                                [link] => #
                                [parent_id] => 44
                            )

                    )

            )

        [49] => Array
            (
                [id] => 49
                [title] => Категория 2_2
                [link] => #
                [parent_id] => 0
                [children] => Array
                    (
                        [54] => Array
                            (
                                [id] => 54
                                [title] => Категория 2_2
                                [link] => #
                                [parent_id] => 49
                            )

                    )

            )

        [51] => Array
            (
                [id] => 51
                [title] => Категория 3
                [link] => #
                [parent_id] => 0
            )

        [52] => Array
            (
                [id] => 52
                [title] => Категория 4
                [link] => #
                [parent_id] => 0
            )

        [55] => Array
            (
                [id] => 55
                [title] => Категория 44
                [link] => #
                [parent_id] => 0
            )

    )

Хочу получить в таком виде:
Категория 1
  Категория 1_1
  Категория 45
Категория 2_2
  Категория 2_2
Категория 3
Категория 4
Категория 44

Мой код :
foreach ($testing as $test_value) {
            echo $test_value['title'] . "
";
            foreach ($test_value as $value) {
                echo $value['title'] . "
";
            }
        }

Подскажите пожалуйста, что делаю не так

A: Надеюсь из моего кода Вы поймете где у Вас ошибка
<?php

foreach ($testing as $test_value) {
     echo "[-] ".$test_value['title'] . "
\n";
     if ( isset( $test_value['children'] ) && is_array( $test_value['children'] ) && count($test_value['children']) > 0) {
         foreach ($test_value['children'] as $value) {
             echo " |- ".$value['title'] . "
\n";
         }
     }
}

Результат
[-] Категория 1

 |- Категория 1_1

 |- Категория 45

[-] Категория 2_2

 |- Категория 2_2

[-] Категория 3

[-] Категория 4

[-] Категория 44


text:
Q: Validation of Azure AD token signature is invalid. The Token's Signature resulted invalid when verified using the Algorithm: SHA256withRSA I have a problem regarding the validation of an azure active directory token. I receive the token using my application_id and the username and password of a user. I'll then validate it but it results in an invalid signature. The code fragment for the validation is as follows:
    // Request access token from AAD
    IAuthenticationResult result = getAccessToken(userName, password);
    String auth = result.accessToken();
    DecodedJWT jwt = JWT.decode(auth);
    JwkProvider provider = null;
    Jwk jwk = null;
    Algorithm algo = null;
    try {
        provider = new UrlJwkProvider(new URL("https://login.microsoftonline.com/common/discovery/keys"));
        jwk = provider.get(jwt.getKeyId());
        System.out.println(jwk.getPublicKey());
        algo = Algorithm.RSA256((RSAPublicKey) jwk.getPublicKey(), null);
        algo.verify(jwt);
    }  catch (SignatureVerificationException e) {

        System.out.println(e.getMessage());

    } catch (JwkException e) {
        e.printStackTrace();
    }

I retrieve the token information with this method
private static IAuthenticationResult getAccessToken(String userName, String password)
        throws MalformedURLException, InterruptedException, ExecutionException {

    PublicClientApplication pca = PublicClientApplication.builder(
            APP_ID).
            authority(AUTHORITY).build();

    String scopes = "User.Read";
    UserNamePasswordParameters parameters = UserNamePasswordParameters.builder(
            Collections.singleton(scopes),
            userName,
            password.toCharArray()).build();
    IAuthenticationResult result = pca.acquireToken(parameters).get();
    return result;
}

The program always end up catching the SignatureVerificationException. I tried validating the token manually with the jwt.io, where I paste the certificate that I get when i compare the kid claim with the one on https://login.microsoftonline.com/common/discovery/keys but I also get Invalid Signature as a result. Is there something wrong with my token because the validating processes both say the signature is invalid in jwt.io and in my java program or is there another way to validate Azure AD tokens?
EDIT: The solution was changing the scope from "User.Read" to "[client_id]/.default".

A: Because you are getting the token of the custom api, not the token of the ms graph api. So you need to set the scope to: {api app client_id}/.default


text:
Q: Expected 'trust-anchor' error message when install Bind DNS Server on Centos 5.9 I'm about installing DNS Server on VPS with Centos 5.9 operating system, I have followed step by step from this website https://www.digitalocean.com/community/articles/how-to-install-the-bind-dns-server-on-centos-6
when i try to restart the service with:
    service named restart

there is following error:
Stopping named: [ OK ]
Starting named:
Error in named configuration:

/etc/named.conf:23: unknown option 'dnssec-validation'
/etc/named.conf:24: expected 'trust-anchor' near ';'

any solution to solve this problem? Thank you very much.

A: finally i remove these lines:
dnssec-validation yes;
dnssec-lookaside auto;

and replace it with:
dnssec-lookaside . trust-anchor dlv.isc.org.;


text:
Q: what is RMSE in the results object in R package caret? Why result 1 is different from result 2 ? Intuitively I would think that truc$results$RMSE is the root mean square error of forecasts but I guess it is not.
library(caret)
x <- data.frame(x = rnorm(15))
y <- x$x + rnorm(15)
myTimeControl <- trainControl(method = "timeslice",initialWindow = 10, horizon = 1, fixedWindow = FALSE, savePredictions=TRUE)
truc <- train(x,y,method = "lm",metric= "RMSE",trControl =myTimeControl,preProc = c("center", "scale"))
result1 <- sqrt(mean((truc$pred$pred-truc$pred$obs)^2))
result2 <- truc$results$RMSE
result1
result2

A: If you invert mean and sqrt, you get the same result... Something's weird with caret's formula... Actually, you made an interesting observation...
result1 <- mean(sqrt((truc$pred$pred-truc$pred$obs)^2))


text:
Q: How to grab onto a ledge without climbing up In Batman Arkham Origins (and AC incidentally), if I try to grapple onto a ledge from below (in order to silent-kill a guard), about half the time I'll hang from the ledge and the other half of the time I'll end up automatically climbing up, and therefore exposing myself to the guards.
Is there a way to grapple onto a ledge without climbing all the way up (i.e. hang from the ledge), so I can perform a ledge takedown?

A: In Arkham City at least, this is accomplished by holding RB (or the F key if you're using keyboard) instead of tapping it.


text:
Q: Npgsql C# - pass parameters as array of composite type into stored procedure Maybe this topic is duplicated from this Array of composite type as stored procedure input passed by C# Npgsql. But that is old one from 2017 and some APIs, properties are deprecated.
Currently, I am trying to pass an array of composite types to the stored procedures. I do map a globally composite type. But there an exception was thrown Can't write CLR type Web.API.Models.UdtSpParameter[] with handler type MappedCompositeHandler`1
I try to google that seems to not find any result to resolve that. The following below that what I create, mapping, calling command stored procedure.
Postgresql
/* Create composite type */
CREATE TYPE udt_sp_parameter AS (
    field VARCHAR(50),
    value VARCHAR
);

/* Create stored procedure */
CREATE OR REPLACE PROCEDURE stored_example(
    parameters udt_sp_parameter[])
LANGUAGE 'plpgsql'

AS $BODY$
DECLARE
    _refCursor CURSOR FOR SELECT field, value FROM UNNEST(parameters::udt_sp_parameter[]);

    _record udt_sp_parameter;
BEGIN
    OPEN _refCursor;

    LOOP
        FETCH _refCursor INTO _record;
        IF NOT FOUND THEN
            EXIT;
        END IF;

        RAISE NOTICE 'Field: %', _record.field;
        RAISE NOTICE 'Value: %', _record.value IS NULL;
    END LOOP;

    CLOSE _refCursor;
END;
$BODY$;

And I try to call the stored by plpgsql language and work well.
DO
$$
DECLARE
parameters udtt_input_param[] := ARRAY[
     ROW('YED','Yeti')
    ,ROW('INTELLIGENT','NOOB')
    ,ROW('ZXC',NULL)
    ,ROW('CXX','1')];

BEGIN

CALL stored_example(parameters);
END
$$
LANGUAGE plpgsql

C# Npgsql (nuget Npgsql 4.1.4)
// mapping global type on Startup.cs
NpgsqlConnection.GlobalTypeMapper.MapComposite<UdtSpParameter>("udt_sp_parameter");

// class model UdtSpParameter
public class UdtSpParameter
{
    [PgName("field")]
    public string Field { get; set; }
    [PgName("value")]
    public string Value { get; set; }

    public UdtSpParameter() { }
}

// call stored procedure at data access layer for example StudentDAL.cs
public IEnumerable<T> CallStoredResultSet<T>(UdtSpParameter[] inputParameters ) where T : class
{
    var conn = _GetOpenConnection();
    var tran = _BeginTransaction(conn);

    NpgsqlCommand command = new NpgsqlCommand("stored_example", conn);
    command.CommandType = CommandType.StoredProcedure;
    var cmdParam = command.CreateParameter();
    cmdParam.ParameterName = "parameters";
    cmdParam.DbType = DbType.Object;
    cmdParam.Value = inputParameters;
    cmdParam.DataTypeName = "udt_sp_parameter";

    command.Parameters.Add(cmdParam);

    // throw exception here
    // Can't write CLR type Web.API.Models.UdtSpParameter[] with handler type MappedCompositeHandler`1
    NpgsqlDataReader dr = command.ExecuteReader();

    var result = new List<T>();

    while (dr.Read())
    {
        Console.WriteLine(dr[0].ToString(), dr[1].ToString());
    }

    _CommitTransaction(tran);
    _CloseConnection(conn);

    return result;
}

Please find some stuff if I do anything wrong and point me to fix that. Thanks in advance.

A: You have this error because you have specified the type name for the parameter which is the composite type and not an array of composites. Therefore, you should specify udt_sp_parameter[] as the value of DataTypeName instead of udt_sp_parameter:
var cmdParam = command.CreateParameter();
cmdParam.ParameterName = "parameters";
cmdParam.Value = inputParameters;
cmdParam.DataTypeName = "udt_sp_parameter[]";

Since your type is registered and the driver already knows its PostgreSQL name, there is no need to specify it during the parameter setup. Feel free to remove the last line from the code above:
var cmdParam = command.CreateParameter();
cmdParam.ParameterName = "parameters";
cmdParam.Value = inputParameters;

The driver is smart enough to detect types automatically in most cases, but when there is an ambiguity then it should be specified. For example, you have a string which should be passed as JSON, or a CLR type should be serialized to JSON. In other cases just rely on the driver internals and allow him do his work.

A: The official documentation of Npgsql says:

The only way to call a stored procedure is to write your own CALL
my_proc(...) command, without setting CommandBehavior.StoredProcedure.

In your particular case you should modify your code like this:
NpgsqlCommand command = new NpgsqlCommand("call stored_example(:parameters)", conn);
// comment this line command.CommandType = CommandType.StoredProcedure;

Hope it helps bro.


text:
Q: What is 'service' method in HttpServlet class? Below is a simple servlet written for learning.
package com.example.tutorial;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletExample extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        out.println("Hello Java!");
    }

}

When a browser hits this URI: http://localhost:8081/ServletsJSPExample/servletexample,
By analyzing the request header of http packet, it shows GET request sent from the browser. But, In my servlet, I do not have GET request to process.
So,
When does service method gets invoked?
Why does service method receives this GET request?

A: HttpServlet implements Servlet whose service method javadoc states

Called by the servlet container to allow the servlet to respond to a
  request.

This is the entry point of all Servlet handling. The Servlet container instantiates your Servlet class and invokes this method on the generated instance if it determines that your Servlet should handle a request.
HttpServlet is an abstract class which implements this method by delegating to the appropriate doGet, doPost, doXyz methods, depending on the HTTP method used in the request.
@Override
public void service(ServletRequest req, ServletResponse res)
    throws ServletException, IOException
{
    HttpServletRequest  request;
    HttpServletResponse response;

    if (!(req instanceof HttpServletRequest &&
            res instanceof HttpServletResponse)) {
        throw new ServletException("non-HTTP request or response");
    }

    request = (HttpServletRequest) req;
    response = (HttpServletResponse) res;

    service(request, response);
}
[...]
protected void service(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException
{
    String method = req.getMethod();

    if (method.equals(METHOD_GET)) {
        long lastModified = getLastModified(req);
        if (lastModified == -1) {
            // servlet doesn't support if-modified-since, no reason
            // to go through further expensive logic
            doGet(req, resp);
        } else {
            long ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
            if (ifModifiedSince < lastModified) {
                // If the servlet mod time is later, call doGet()
                // Round down to the nearest second for a proper compare
                // A ifModifiedSince of -1 will always be less
                maybeSetLastModified(resp, lastModified);
                doGet(req, resp);
            } else {
                resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            }
        }

    } else if (method.equals(METHOD_HEAD)) {
        long lastModified = getLastModified(req);
        maybeSetLastModified(resp, lastModified);
        doHead(req, resp);

    } else if (method.equals(METHOD_POST)) {
        doPost(req, resp);

    } else if (method.equals(METHOD_PUT)) {
        doPut(req, resp);

    } else if (method.equals(METHOD_DELETE)) {
        doDelete(req, resp);

    } else if (method.equals(METHOD_OPTIONS)) {
        doOptions(req,resp);

    } else if (method.equals(METHOD_TRACE)) {
        doTrace(req,resp);

    } else {
        //
        // Note that this means NO servlet supports whatever
        // method was requested, anywhere on this server.
        //

        String errMsg = lStrings.getString("http.method_not_implemented");
        Object[] errArgs = new Object[1];
        errArgs[0] = method;
        errMsg = MessageFormat.format(errMsg, errArgs);

        resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg);
    }
}

If you override the service method from HttpServlet, you lose that behavior and revert back to a single handling of all Servlet requests.


text:
Q: Memory error after running pyBrain NFQ learner for a few minutes O.
Using reinforcement learning from pyBrain we are trying to solve a game.
We use NFQ and an ActionValueNetwork as controller.
We have our self-made task and are using the experiment setup from pyBrain to train.
Our agent is reset after every episode.
The way we see an episode is one run on a level.
Each episode we call experiment.doInteractions() until the level returns either failed or finished.
After that we do agent.learn() and agent.reset()
At first we thought this error was because of a memory overflow due to running one episode too long. We had a move maximum of 10.000 inserted when we first encountered the error. I lowered it to 50 now which makes the program run for more episodes but still gives the error.
This makes us believe that it is not the amount of moves that is the problem but a cumulative history being saved somewhere and overgrowing its allowed memory size.
We believed agent.reset() would clear all history from memory, is this not so?
Can we stop the history from being saved somewhere?
Or does anyone have other suggestions?
edit:
This is the exception trace.
Running level: Single box block. Try: 125
Traceback (most recent call last):
  File "wrapperSokoban.py", line 168, in <module>
    wrapperSokoban().run_Qlearning()
  File "wrapperSokoban.py", line 154, in run_Qlearning
    self.run_Qlearning_level()
  File "wrapperSokoban.py", line 122, in run_Qlearning_level
    self.experiment.doInteractions()
  File "/usr/local/lib/python2.7/dist-packages/PyBrain-0.3.1-py2.7.egg/pybrain/rl/experiments/experiment.py", line 18, in doInteractions
    self._oneInteraction()
  File "/usr/local/lib/python2.7/dist-packages/PyBrain-0.3.1-py2.7.egg/pybrain/rl/experiments/experiment.py", line 29, in _oneInteraction
    self.agent.giveReward(reward)
  File "/usr/local/lib/python2.7/dist-packages/PyBrain-0.3.1-py2.7.egg/pybrain/rl/agents/logging.py", line 62, in giveReward
    self.history.addSample(self.lastobs, self.lastaction, self.lastreward)
  File "/usr/local/lib/python2.7/dist-packages/PyBrain-0.3.1-py2.7.egg/pybrain/datasets/reinforcement.py", line 40, in addSample
    self.appendLinked(state, action, reward)
  File "/usr/local/lib/python2.7/dist-packages/PyBrain-0.3.1-py2.7.egg/pybrain/datasets/dataset.py", line 216, in appendLinked
    self._appendUnlinked(l, args[i])
  File "/usr/local/lib/python2.7/dist-packages/PyBrain-0.3.1-py2.7.egg/pybrain/datasets/dataset.py", line 196, in _appendUnlinked
    self._resize(label)
  File "/usr/local/lib/python2.7/dist-packages/PyBrain-0.3.1-py2.7.egg/pybrain/datasets/dataset.py", line 181, in _resize
    self.data[l] = self._resizeArray(self.data[l])
  File "/usr/local/lib/python2.7/dist-packages/PyBrain-0.3.1-py2.7.egg/pybrain/datasets/dataset.py", line 188, in _resizeArray
    return resize(a, shape)
  File "/usr/lib/python2.7/dist-packages/numpy/core/fromnumeric.py", line 864, in resize
    a = concatenate( (a,)*n_copies)
MemoryError


text:
Q: How do I calculate shipping in Simplecart based on total quantity? My client requires shipping rates based on quantity of items in the order.
1-10 books - $4
11-24 - $5.50
25-49 - $7
50-99- $8.50
100-199 - $11
200-299 - $16
300-399 - $23
400-499 - $30
I've been trying to tweak the JavaScript a week now. Anybody know Simplecart well enough to send me in the right direction?

A: You should not have to change the core files.
See http://simplecartjs.org/documentation/shipping
simpleCart.shipping(function(){
    if( simpleCart.quantity() <= 10 ){
         return 4;
    }
    else if( simpleCart.quantity() < 25 ){
         return 5.5;
    }
    else if( simpleCart.quantity() < 50 ){
         return 7.5;
    }
    else if( simpleCart.quantity() < 100 ){
         return 8.5;
    }
    else if( simpleCart.quantity() < 200 ){
         return 11;
    }
    else if( simpleCart.quantity() < 300 ){
         return 16;
    }
    else if( simpleCart.quantity() < 400 ){
         return 23;
    }
    else if( simpleCart.quantity() < 500 ){
         return 30;
    }
    else {
         return 30; // amount for > 500
    }
});

A: simpleCart({
  shippingCustom: function () {
    if (simpleCart.quantity() > 50) {
      return 0;
    } else if (simpleCart.quantity() > 20) {
      return 10;
    } else {
      return 20;
    }
  }
});


text:
Q: Error: unable to instantiate activity in android I am following a tutorial to creating a sliding navigation with a drawer navigation.
Android Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.aa.slide"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="7"
        android:targetSdkVersion="22" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.aa.slide.MainActivity"
            android:label="@string/app_name"
            android:theme="@style/Theme.MyCompatTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Below is my MainActivity.java
package com.aa.slide;

import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

// Adopted from: https://developer.android.com/training/implementing-navigation/nav-drawer.html
public class MainActivity extends ActionBarActivity {

    private String[] mPlanetTitles;
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private CharSequence mTitle;
    private ActionBarDrawerToggle mDrawerToggle;

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

        mTitle = "test";

        mPlanetTitles = new String[]{"one", "two", "three"};
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);

        // Set the adapter for the list view
        mDrawerList.setAdapter(new ArrayAdapter<String>(this,
                R.layout.drawer_list_item, mPlanetTitles));
        // Set the list's click listener
        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

        mDrawerToggle = new ActionBarDrawerToggle(
                this,                  /* host Activity */
                mDrawerLayout,         /* DrawerLayout object */
                R.drawable.ic_drawer,  /* nav drawer icon to replace 'Up' caret */
                R.string.drawer_open,  /* "open drawer" description */
                R.string.drawer_close  /* "close drawer" description */
        ) {

            /** Called when a drawer has settled in a completely closed state. */
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(mTitle);
            }

            /** Called when a drawer has settled in a completely open state. */
            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(mTitle);
            }
        };

        // Set the drawer toggle as the DrawerListener
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Pass the event to ActionBarDrawerToggle, if it returns
        // true, then it has handled the app icon touch event
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        // Handle your other action bar items...

        return super.onOptionsItemSelected(item);
    }

    /**
     * Swaps fragments in the main content view
     */
    private void selectItem(int position) {
        Toast.makeText(this, R.string.app_name, Toast.LENGTH_SHORT).show();

        // Highlight the selected item, update the title, and close the drawer
        mDrawerList.setItemChecked(position, true);
        setTitle(mPlanetTitles[position]);
        mDrawerLayout.closeDrawer(mDrawerList);
    }

    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getSupportActionBar().setTitle(mTitle);
    }

    private class DrawerItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView parent, View view, int position, long id) {
            selectItem(position);
        }
    }

}

Upon Executing the above codes, I keep recieving this error in my log
08-14 13:18:18.632: W/dalvikvm(12483): Unable to resolve superclass of Lcom/aa/slide/MainActivity; (11)
08-14 13:18:18.632: W/dalvikvm(12483): Link of class 'Lcom/aa/slide/MainActivity;' failed
08-14 13:18:18.632: D/AndroidRuntime(12483): Shutting down VM
08-14 13:18:18.632: W/dalvikvm(12483): threadid=1: thread exiting with uncaught exception (group=0x4113c2a0)
08-14 13:18:18.637: E/AndroidRuntime(12483): FATAL EXCEPTION: main
08-14 13:18:18.637: E/AndroidRuntime(12483): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.aa.slide/com.aa.slide.MainActivity}: java.lang.ClassNotFoundException: com.aa.slide.MainActivity
08-14 13:18:18.637: E/AndroidRuntime(12483):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2034)
08-14 13:18:18.637: E/AndroidRuntime(12483):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
08-14 13:18:18.637: E/AndroidRuntime(12483):    at android.app.ActivityThread.access$700(ActivityThread.java:140)
08-14 13:18:18.637: E/AndroidRuntime(12483):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)
08-14 13:18:18.637: E/AndroidRuntime(12483):    at android.os.Handler.dispatchMessage(Handler.java:99)
08-14 13:18:18.637: E/AndroidRuntime(12483):    at android.os.Looper.loop(Looper.java:137)
08-14 13:18:18.637: E/AndroidRuntime(12483):    at android.app.ActivityThread.main(ActivityThread.java:4921)
08-14 13:18:18.637: E/AndroidRuntime(12483):    at java.lang.reflect.Method.invokeNative(Native Method)
08-14 13:18:18.637: E/AndroidRuntime(12483):    at java.lang.reflect.Method.invoke(Method.java:511)
08-14 13:18:18.637: E/AndroidRuntime(12483):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
08-14 13:18:18.637: E/AndroidRuntime(12483):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
08-14 13:18:18.637: E/AndroidRuntime(12483):    at dalvik.system.NativeStart.main(Native Method)
08-14 13:18:18.637: E/AndroidRuntime(12483): Caused by: java.lang.ClassNotFoundException: com.aa.slide.MainActivity
08-14 13:18:18.637: E/AndroidRuntime(12483):    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:61)
08-14 13:18:18.637: E/AndroidRuntime(12483):    at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
08-14 13:18:18.637: E/AndroidRuntime(12483):    at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
08-14 13:18:18.637: E/AndroidRuntime(12483):    at android.app.Instrumentation.newActivity(Instrumentation.java:1068)
08-14 13:18:18.637: E/AndroidRuntime(12483):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2025)
08-14 13:18:18.637: E/AndroidRuntime(12483):    ... 11 more

UPDATE
this is my build.gradle
 apply plugin: 'android'

dependencies {

    compile fileTree(dir: 'libs', include: '*.jar')
    compile 'com.Android.support:appcompat-v7:21.0.+'
}

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"

    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
        }

        // Move the tests to tests/java, tests/res, etc...
        instrumentTest.setRoot('tests')

        // Move the build types to build-types/<type>
        // For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ...
        // This moves them out of them default location under src/<type>/... which would
        // conflict with src/ being used by the main source set.
        // Adding new build types or product flavors should be accompanied
        // by a similar customization.
        debug.setRoot('build-types/debug')
        release.setRoot('build-types/release')
    }
}

Please how can i solve this problem of unable to instantiate activity? Thanks

A: What exceptions throws

java.lang.ClassNotFoundException: com.aa.slide.MainActivity

ClassNotFoundException occurs when class loader could not find the required class in class path . So , basically you should check your class path and add the class in the classpath.
Rebuild and Clean up your Project.Please check This SO Answer.
For your information,Since the version 22.1.0, the class ActionBarActivity is deprecated. You should use AppCompatActivity or Actvity . I hope it helps you .

A: Be sure that this is in your gradle file:
dependencies {
    compile 'com.android.support:appcompat-v7:21.0.0'
}

The problem is that the dalvikVM can't find import android.support.v7.app.ActionBarActivity; which is the superclass of your MainActivity
You can see this in:
08-14 13:18:18.632: W/dalvikvm(12483): Unable to resolve superclass of Lcom/aa/slide/MainActivity; (11)

A: Try this in Manifest file:
 **android:name=".MainActivity"**

 <activity
        android:name="com.aa.slide.MainActivity"
        android:label="@string/app_name"
        android:theme="@style/Theme.MyCompatTheme">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>


text:
Q: Android connection to MySQL - Php or Servlet? This is not a codefix question but please help me where possible.
I am developing an application which needs to store information in a database. This information needs to be stored off-device for security reasons (patient data).
I have explored using PHP as a bridge to the external MySQL database hosted locally via WAMP, however I have recently been informed of servlets and also of SQLite.
As I am learning these technologies under a limited time frame I need to know which to invest my time into to get the job done as easily as possible. I have no experience with any query language but I did get a simple login screen to work on Android using PHP and MySQL on WAMP using HTTP post/fetch within android.
Also, is it possible to store the information in SQLite within android and write that data to a server, which can then load the SQLite database again on re-launch?
Many thanks for your time!

A: From our expericence these kind of services need to work offline if possible. Both 3g and especially wifi has been unreliable in several occasions.
You do good if you save the data locally in e.g. sqlite database but be warned the data can get wiped on OS update or software update.
Also try to write your changes/additions in batches and servr updater can send all the batches that are not yet on the server. this way it's more reliable if you miss updates.
These kind of interfaces to another systems take a lot of time in testing. Consider getting a new timeframe in advance.

A: You will find more about Android connection to MySQL here


text:
Q: Calculating area between circle and line - where have I gone wrong here I think the initial set up is wrong below I should just integrate over the area as a multiple integral here. correct? the 1step below seems wrong.
Problem is asking for the area inside a region of a circle of radius 2 (centered on origin) and with x> 0 and y > 1. Here's my attempt at a solution
$A = \int_0^\sqrt3 \sqrt{4-x^2}dx $
since when x varies from $\sqrt3$ to 0 as y varies from 1 to the circles edge. So then I tried a substitution
$x= 2\sin\theta\qquad$
 $ dx = 2\cos\theta d\theta$
$A = \int_0^{\frac{\pi}{3}} \sqrt{4-(2sin\theta)^2}dx$
$A = 2\int_0^{\frac{\pi}{3}}  \cos\theta dx $
$A = 2\int_0^{\frac{\pi}{3}}  \cos\theta dx  = 4\int_0^{\frac{\pi}{3}}  \cos^2\theta d\theta = 4\int_0^{\frac{\pi}{3}} \frac{1}{2}\left( 1 +  \cos2\theta\right) d\theta$
Here I substituted for $2\theta = v$ so $dv = 2d\theta$; and the limits change by a factor of two on the second integral so it should be
$ A= \frac{\theta}{2}|^\frac{\pi}{3}_0 + \sin{v} |^\frac{2\pi}{3}_{0} = \frac{2\pi + 3\sqrt3}{6}  $
whereas the textbook gives the solution as = $\frac{4\pi -3\sqrt3}{6}$
I know the book answers is right since the total area of the quadrant is only pi but I'm not sure where exactly I'm screwing this up any tips appreciated!

A: If we use formula for the area of circular segment
$$2A = \frac{R^2}{2} \left(\theta - \sin\theta \right)$$
with $R=2$, $\theta = \frac{2\pi}3$ and $\sin\theta=\sin\frac{2\pi}3=\sin\frac\pi3=\frac{\sqrt3}2$, we get
$$2A=2\left(\frac{2\pi}3-\frac{\sqrt3}2\right)\\
A=\frac{2\pi}3-\frac{\sqrt3}2$$
which is the same result as in the book.

You need $A = \int_0^\sqrt3 (\sqrt{4-x^2} -1) \,dx = I-\sqrt 3$, where $I$ denotes the integral you have computed.
In general $\int_a^b (g(x)-f(x)) \,dx$ is area between two functions $f$ and $g$.
You also missed factor 2 in the last step in $2\int_0^{\pi/3} 1\, d\theta$, see Rahul Narain's comment.


text:
Q: Scala define type from multiple generic traits How can I fix this code :
trait A[A,B]{
  def f(a:A):B
}
trait B[A,B]{
  def g(a:A):B
}

type C = A[String,Int] with B[String,Double]

//works fine
new A[String,Int] with B[String,Double] {
  def f(a:String):Int = 1
  def g(a:String):Double = 2.0
}

//error
new C {
  def f(a:String):Int = 1
  def g(a:String):Double = 2.0
}

The exception i got is  :
Error:(41, 6) class type required but A$A42.this.A[String,Int] with A$A42.this.B[String,Double] found
new C {
    ^

Any Idea how to solve that and what is the reason for that ?

A: My guess why it doesn't work (and probably shouldn't): type C = ... defines something which is not a class type, I wonder what it is. But when you pass it to new it expects new class_type with trait_type ..., so you are trying to replace only one thing, namely class_type with C. If you define C without with it will work.
You can also write:
type C1 = A[String,Int]
type C2 = B[String,Double]
new C1 with C2 {
  def f(a:String):Int = 1
  def g(a:String):Double = 2.0
}


text:
Q: PHP to MySQL won't show all colums My Codes :
<?php
 error_reporting(0);
      $page = 'Home';
     include('inc/overall-head.php')
?>

    Home || <?php include('inc/tag.php') ?>

    <?php
    include ('config.inc.php');
$con = mysql_query("SELECT * FROM cms_news ORDER BY id DESC LIMIT 100");
$count = mysql_num_rows($con);
echo $count;
while($row=mysql_fetch_array($con)) {

    echo "
";

    <img src='img/avatar/<?php echo $row['Author']; ?>.png'/>

    <?php echo $row['Author']; ?>

<?php  echo $row['Title'];?>

    <?php echo $row['Content'] ; ?>

    <?php }
echo "
";

?>

<?php
include('inc/sidebar.php');
include('inc/footer.php');

}

?>

So it only shows one column..
i.e.
It only shows one post??
Anyone can help??
NOTE If you think I'm dumb, maybe. I don't know much, and I use so many php, if I didn't seperate them, it would turn to be an error.
*P.S Mark Baker asked me if I could add it until the end. Here you go.

A: I think the problem is that you start a new
 for each row, but you never close it with
. You should just have a single
 that you start before the loop, and each row of the query results becomes a row in the table:
echo "
";
while ($row = mysql_fetch_array($con)) { ?>

        <img src='img/avatar/<?php echo $row['Author']; ?>.png'/>

            <?php echo $row['Author']; ?>

<?php  echo $row['Title'];?>

            <?php echo $row['Content'] ; ?>

<?php }
echo "
";

A: Have you tried
$con = mysql_query("SELECT * FROM cms_news ORDER BY id DESC LIMIT 100");
// Hier you should insert it:
$count = mysql_num_rows($con);
echo $count;

There you can proof if there are more rows.

A: Try a foreach row:
$row = mysql_fetch_array($result);
foreach($row as $r) {
…
}

BTW:  is deprecated.


text:
Q: Recalculate values in MySQL tables I have a web application that stores points in a table, and total points in the user table as below:
User Table
user_id | total_points

Points Table
id | date | user_id | points

Every time a user earns a point, the following steps occur:
1. Enter points value to points table
2. Calculate SUM of the points for that user
3. Update the user table with the new SUM of points (total_points)

The values in the user table might get out of sync with the sum in the points table, and I want to be able to recalculate the SUM of all points for every user once in a while (eg. once a month). I could write a PHP script that could loop through each user in the user table and find the sum for that user and update the total_points, but that would be a lot of SQL queries.
Is there a better(efficient) way of doing what I am trying to do?
Thanks...

A: A more efficient way to do this would be the following:
User Table
user_id

Points Table
id | date | user_id | points

Total Points View
user_id | total_points

A view is effectively a select statement disguised as a table. The select statement would be: SELECT "user_id", SUM("points") AS "total_points" FROM "Points Table" GROUP BY "user_id". To create a view, execute CREATE VIEW "Total Points View" AS <SELECT STATEMENT> where SELECT STATEMENT is the previous select statement.
Once the view has been created, you can treat it as you would any regular table.
P.S.: I don't know that the quotes are necessary unless your table names actually contain spaces, but it's been a while since I worked with MySQL, so I don't remember it's idiosyncrasies.

A: You have to user Triggers for this, to make the users total points in sync with the user_points table. Something like:
Create Trigger UpdateUserTotalPoints AFTER INSERT ON points
FOR EACH ROW Begin
    UPDATE users u
    INNER JOIN
    (
       SELECT user_id, SUM(points) totalPoints
       FROM points
      GROUP BY user_id
    ) p ON u.user_id = p.user_id
   SET u.total_points = p.totalPoints;
END;

SQL Fiddle Demo
Note that: As noted by @FireLizzard, if these records in the second table, are frequently updated or delted, you have to have other AFTER UPDATE and AFTER DELETE triggers as well, to keep the two tables in sync. And in this case the solution that @FireLizzard will be better in this case.

A: If you want it once a month, you can't deal with just MySQL. You have too « logic » code here, and put too logic in database is not the correct way to go. The trigger of Karan Punamiya could be nice, but it will update the user_table on every insert in points table, and it's not what you seem to want.
For the fact you want to be able to remove points, just add bsarv new negated rows in points, don't remove any row (it will break the history trace).
If you really want it periodically, you can run a cron script that does that, or even call your PHP script ;)