Q:

Cannot install PIL due to a UnicodeDecodeError

When I tried to install Pillow using pip-3.3, I got an error instead, see the traceback below.
  File "/home/samsun/workspace/python/chat_environment/lib/python3.3/site-packages/pip/req.py", line 297, in egg_info_data
    data = fp.read()
  File "/home/samsun/workspace/python/chat_environment/lib/python3.3/encodings/ascii.py", line 26, in decode
    return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 14439: ordinal not in range(128)

I think the traceback is telling me some characters in the file are Unicode, but Python is using ASCII to read the file.
I want to change python3.3 filesystemencoding to resolve this error; is there a way to change the default filesystemencoding?

A:

I just ran into this issue as well. I'm not sure if it's a pip problem or a Pillow problem, but the "culprit" appears to be the name of one of the Pillow authors, which contains non-ascii characters (Håkan Karlsson). Apparently, an EGG info file is constructed from the CHANGES.rst file in Pillow, and pip tries to parse that in ascii, failing that. Changing the authors name seems like a bad idea, so pip should handle that better.
And indeed, pip install --upgrade pip worked for me (upgrading from pip 1.4 to 1.5). It seems this change fixed that.


Q:

sudo: /etc/sudoers is owned by uid 501, should be 0

To run programs as sudo without password, I edited /etc/sudoers with wrong content.
Then I re-edited it with Mac's default text editor(course sudo cannot be used when /etc/sudoers is wrong).
I tried to run sudo agin, and get this error:
sudo: /etc/sudoers is owned by uid 501, should be 0
sudo: no valid sudoers sources found, quitting

What should I do? I cannot remember the root password (maybe I haven't ever set root password before).

A:

You can boot into single user mode by pressing Cmd-S on startup (see OS X: How to start up in single-user or verbose mode for details) which should give you a root shell. Then run
mount -uw /
chown root:wheel /etc/sudoers
chmod 440 /etc/sudoers
reboot

to fix the problem and restart.

A:

Yosemite and earlier OSX keeps info on what permissions system files (i.e. files the OS installs) should be. Apple's doc
To restore this use Disk Utility.app.
Select the boot volume (by default called Macintosh HD) on the left hand side.
Click the Verify or Repair Disk Permissions - the latter will reapply the stored permissions.
To edit sudoers in the future I would use visudo which checks that the edit is valid
re the root password you probably have not set it before - the idea of sudo is that you never need to use it and Apple disables root login by default

A:

For macOS Mojave, here is what worked for me:

Start up in recovery mode (Cmd+R during boot up)
Disk Utilities > Select Macintosh HD, and Mount
Close Disk Utilities
Utilities > Terminal
Type: chown root:wheel "/Volumes/Macintosh HD/etc/sudoers"
Reboot

You may also need to change the ownership of ts, back in the Terminal:
sudo su
sudo chown -R root:wheel /var/db/sudo/ts/


Q:

I'm trying to reduce this code

My php knowledge is not of the strongest part. I'm trying to reduce this code, but really do not know how. maybe have any advice for how to do it?
if (isset($this->data['upload_main_bg_pattern_image']) && $this->data['upload_main_bg_pattern_image'] != "" && file_exists(DIR_IMAGE . $this->data['upload_main_bg_pattern_image'])) {
    $this->data['image_pattern_preview'] = $this->model_tool_image->resize($this->data['upload_main_bg_pattern_image'], 100, 100);
} else {
    $this->data['image_pattern_preview'] = $this->model_tool_image->resize('no_image.jpg', 100, 100);
}

if (isset($this->data['upload_main_full_bg_image']) && $this->data['upload_main_full_bg_image'] != "" && file_exists(DIR_IMAGE . $this->data['upload_main_full_bg_image'])) {
    $this->data['image_main_full_bg_preview'] = $this->model_tool_image->resize($this->data['upload_main_full_bg_image'], 100, 100);
} else {
    $this->data['image_main_full_bg_preview'] = $this->model_tool_image->resize('no_image.jpg', 100, 100);
}

if (isset($this->data['upload_header_bg_pattern_image']) && $this->data['upload_header_bg_pattern_image'] != "" && file_exists(DIR_IMAGE . $this->data['upload_header_bg_pattern_image'])) {
    $this->data['image_header_pattern_preview'] = $this->model_tool_image->resize($this->data['upload_header_bg_pattern_image'], 100, 100);
} else {
    $this->data['image_header_pattern_preview'] = $this->model_tool_image->resize('no_image.jpg', 100, 100);
}

if (isset($this->data['upload_header_full_bg_image']) && $this->data['upload_header_full_bg_image'] != "" && file_exists(DIR_IMAGE . $this->data['upload_header_full_bg_image'])) {
    $this->data['image_header_full_bg_preview'] = $this->model_tool_image->resize($this->data['upload_header_full_bg_image'], 100, 100);
} else {
    $this->data['image_header_full_bg_preview'] = $this->model_tool_image->resize('no_image.jpg', 100, 100);
}

A:

Instead of doing
isset($this->data['upload_main_bg_pattern_image']) && $this->data['upload_main_bg_pattern_image'] != ""

You should do!empty($this->data['upload_main_bg_pattern_image'])
And so on for each of your statement


Q:

Possible shorter solution to this problem?

How many pairs of diagonals of a regular decagon are parallel?

The answer is $45$, and is computed via: $$5\binom{4}{2} + 5 \binom{3}{2}$$
which comes as a result of fixing one vertex and choosing $2$ of the $4$ possible parallel diagonals with that vertex fixed, and then fixing a side and choose $2$ of the $3$ possible parallell diagonals with that side fixed.

However, the answer $45$ is also just $\binom{10}{2}$. Is this just a coincidence or is there another, shorter, way to approach this problem?

A:

In a decagon, there are $10\choose2$ ways to pick pairs of vertices that are 1 side apart. Connecting these pairs gives pairs of parallel diagonals. But for each pair, only 5 of the other 9 pairs don't share a share a vertex or result in a diagonal that is just a side of the decagon, so there are $\frac59{10\choose2}$ ways here.
Now we check pairs of vertices where the vertices are 2 sides apart. There are still $10\choose2$ ways to do this where only $\frac39$ don't share vertices, don't give us sides of the decagon, and don't intersect with each other. By intersect, I mean that if you draw a segment that conjoins one pair's points and another for the other pair, then the two don't intersect. Allowing for this would make us double count some pairs of diagonals. So there are $\frac39{10\choose2}$ ways here.
We do the same for pairs of vertices that are 3 sides apart and find that there are $\frac19{10\choose2}$ possibilities
There are none for pairs of vertices that are further apart.
Adding these all up
$$\left(\frac59+\frac39+\frac19\right){10\choose2}={10\choose2}$$
Generalize this to an even n-gon, we have
$$\left(\frac1{n-1}\sum_{i=2}^{n/2-1}n-2i-1\right)\times{n\choose2}$$


Q:

Need Help on LINQ-Query

I have 3 Tables:
Table User (UserID, Username)
Table Admin (AdminID, Username)
Table PM (PMID, SenderID, Sendertype, RecipientID, RecipientType)

Now I will, in 1 Query:

Get all Information from PM
if SenderType == 'A' join SenderID to Admin-Table, get Username
if SenderType == 'U' join SenderID to User-Table, get Username
if RecipientType == 'A' join RecipientID to Admin-Table, get Username
if RecipientType == 'U' join RecipientID to User-Table, Get Username

someone have an Idea how to solve in 1 query?

A:

Why not just have a single user table that instead has a user type of either User or Admin, you could save yourself a lot of trouble... LINQ queries translate directly to SQL, so I'm not sure if you can do an indeterminate join like that in just one query.
Alternatively, if you don't want to modify the tables you could also create a view that does basically the same thing.
Or, write a stored procedure.
If you really want to use LINQ, you'll probably have to do more than one query. You could union the two User/Admin tables with a third field to differentiate, and then join to your PM table using that dataset instead.


Q:

how correlation will help me to find features of my model in machine learning?

I read articles that tells correlation is used to find features in ML. But I want to know how it's exactly working.

A:

I think it's fair to say that if you're interested in practical aspects, then the question should be on either the data science or stats SE.
However, the question does have a mathematical answer. In fact, correlation is not used to find features, exactly. Rather, it is used to select, weed out, or rank features, usually.
Suppose you have a dataset $X$, so $x_i=\text{row}_i(X)$ is a point and $f_j=\text{col}_j(X)$ is a feature, with label vector $Y$.
Two common measures of correlation are the Pearson correlation:
$$
\rho(a,b) = \frac{\mathbb{E}[(a-\mu_a)(b-\mu_b)]}{\sigma_a\sigma_b}
$$ where $\mu$ and $\sigma$ are the mean and standard deviation,
and the mutual information, which is essentially a measure of non-linear correlation:
$$ \mathfrak{I}(U,V) = \int_{V} \int_{U}
P(u,v)\log\left(
\frac{P(u,v)}{P(u)P(v)}
\right)du\,dv
$$
Denote $C$ as a correlation function (e.g. $C\in\{\rho,\mathfrak{I}\}$).
One use of correlation is straight-forward: determine how much "information" a given feature contains regarding the labels. Obviously, a feature with lots of information about (or high absolute correlation to) the labels is useful.
In other words, a feature with high $ C(f_k,Y) $ is more likely to be useful.
Another use is to remove redundancy. Having multiple features that share the same information content is essentially useless, and adds only bias and noise to the data. Hence we want low $ C(f_i,f_j)\,\forall\; i\ne j $.
Thus, we are looking for something similar to:
$$
F^* = \arg\max_{\phantom{\large TY|}\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!F\in S_f}
\sum_{f\in F} C(f,Y) - \sum_{f_1\in F}\sum_{f_2\in F} C(f_1,f_2)
$$
for $S_f$ being the set of possible combinations of features and $F$ being a particular subset of features.
Actually, these facts are the basis for the "Minimum Redundancy Maximum Relevance" feature selection algorithm.


Q:

Show that every continuous functions on closed interval is the uniform limit of a sequence of polynomial

If $0\notin [a,b]$ show that every continuous function $f$ on [a,b] is the uniform limit of a sequence of polynomials $q_n$ where $q_n = x^n p_n{(x)}$  for some polynomials $p_n$.
Attempt so far:
I have to show that $|f - q_n| < \epsilon$  it would not be that hard to show just by using stone-weierstrass theorem but what confused me is $q_n = x^n p_n (x)$.
I appreciate all the helps!

A:

For each $n$, the function $f_n(t)=f(t)t^{-n}$ is continuous. Hence you can approximate it uniformly by a polynomial, $p_n$ given any $\varepsilon >0$. You must approximate it appropriately so that $t^np_n$ converges to $f$ uniformly, i.e. you want that $\lVert t^np_n-f\rVert_\infty\to 0$.
Spoiler

Suppose first that $a>0$, and suppose we've taken $\varepsilon_n >0$ and $p_n$ for which $$\sup\limits_{t\in [a,b]}|t^{-n}f(t)-p_n(t)|\leqslant \varepsilon_n$$
Now we have $$\begin{align}\sup\limits_{t\in [a,b]}| f(t)-t^np_n(t)|&=\sup\limits_{t\in [a,b]}|t^n||t^{-n} f(t)-p_n(t)|\\&\leqslant b^n\varepsilon_n\end{align}$$
So it suffices we arrange it so that $b^n\varepsilon_n\to 0$, for example we may take $\varepsilon_n\leqslant 1/(2b)^n$. For $[a,b]$ to the left of $0$ we must look at $a$ instead of $b$.


Q:

Counter examples to inscribed squares conjecture

Can the counter examples found by me qualify as a counter proof for the "inscribed squares problem" (the Toeplitz' conjecture) ?
I ask this here because the problem stands as unsolved for 100 years, and the counterexamples below appear too simple. It is hard to believe that I am the first to find them. So, is there something I missed out?
Here are the curves:
Solution http://automaton.opa.ro/wp-content/uploads/2013/09/solution_4_s30.png
Solution http://automaton.opa.ro/wp-content/uploads/2013/09/solution_1_s30.png
Solution http://automaton.opa.ro/wp-content/uploads/2013/09/solution_3_s30.png

A:

So no, it's not a counterexample


Q:

Getting a specific joint position in C++ and kinect

How do I get the position data of a specific joint (i.e. hip joint) from Kinect using C++? I spent hours reading docs and source code but I can't figure out how to specify the joint I would like to get the data from.

A:

Take a look at the following source which explains how to lookup the right joint in the Skeleton Stream.
For example, to get the hip joint, you would use the NUI_SKELETON_POSITION_HIP_CENTER index.


Q:

joomla admin template not loading, how do i change it manually?

Hi joomla's defaut admin template "system" is not loading css stylesheets, so i wonder if there is a way to change the admin template from phpmyadmin.
Want to use the other template kephri

A:

For Changing template from phpmyadmin
==> find table #_template_styles.
==> set "home"="0" for current back-end template.
==> set "home"="1" for the template you want to make default for back-end.
Just care about client id, it is always 1 for back-end templates.


Q:

z-index in mobile not working

Is there a specific way of formatting z-index for mobile? Does it even work?
www.backwards.ca/resume
This is what I'm working on.. In mobile, the body (.info-win) is supposed to scroll up UNDER the header(.name-win), but it's not working
This is the code:
body{
background:#EEE;
margin-top:0;
margin-left:0;
}

.container{
position:relative;
top:0;
left:0;
width:100%;
height:100%;
padding-left:0;
background:#EEE;
}

.name-win{
position:fixed;
top:0;
left:0;
height:25%;
width:100%;
z-index:10000px;
padding-left:5%;
background:#EEE;
-moz-box-shadow:-2px 0px 2px 3px rgba(200, 200, 200, 0.8);
-webkit-box-shadow:-2px 0px 2px 3px rgba(200, 200, 200, 0.8);
-o-box-shadow:-2px 0px 2px 3px rgba(200, 200, 200, 0.8);
box-shadow:-2px 0px 2px 3px rgba(200, 200, 200, 0.8);
}

.scroll{
background:none;
}

.info-win{
position:relative;
margin-top:25%;
background:#FFFFFF;
height:100%;
width:100%;
z-index:-1000px;
min-height:500px;
overflow:hidden;
padding-bottom:20px;
}

.name-win h1{
font-family: 'Archivo Narrow', sans-serif;
font-weight:700;
max-width:200px;
}

#pic{
float:left;
}

#pic img{
width:60%;
border:6px solid #fff;
}

.res_cont{
width:100%;
}

.contact h3{
margin-bottom:0px;
font-family: 'Archivo Narrow', sans-serif;
font-weight:700;
}

.contact p{
margin-top:0px;
font-family: 'Archivo Narrow', sans-serif;
font-weight:300;
}

.label{
height:33px;
width:420px;
padding-left:10px;
margin-bottom:10px;
}

.label h2{
font-family: 'Archivo Narrow', sans-serif;
color:#fff;
text-shadow:1px 1px #555;
}

.res_cont p{
font-family: 'Archivo Narrow', sans-serif;
color:#555;
margin-left:25px;
}

.res_cont span{
font-style:italic;
color:#999;
}

#objective_label{
background-color:#4F8AFF;
}

#rs_label{
background-color:#CC0000;
}

#about_label{
background-color:#00CC66;
}

#education_label{
background-color:#FF6633;
}

#links_label{
background:#E4B434
}

#links_ul li{
font-family: 'Archivo Narrow', sans-serif;
color:#666;
}

A:

z-index is supposed to be a numerical value like in z-index: 2; You're using the unit px with them. Remove it.


Q:

Alias' aren't runnable/executable from a shell script? Mac OS X Sierra 13.x

So this screenshot basically explains it
https://gyazo.com/1a9d621efa28c7994c3a2afbe0411a2b
I've got some alias' set up for opening a new tab within terminal, and doing other stuff, even an alias for running the debug shell script, but the debug.sh script simply uses an alias, newtab, to try and open a new tab, which works when just typing newtab, but it doesn't work, any neither do any other alias', from within a .sh or any other executable files, how do I fix this?
One thing I noticed was that I'm putting all my export's and alias' into /etc/bashrc and not ~/.bash_profile or the other ones, and I hardly see /etc/bashrc mentioned anywhere
am I doing it right?

A:

Alias expansion is done only from the interactive shell, but not within scripts so debug is expanded to newtab, but newtab is not itself expanded, since it is called from a script.
If you use exported functions instead of aliases, it will work:-
debug() { $scripts/debug.sh; }; export -f debug
...
newtab() { $scripts/newtab.osx.sh; }; export -f newtab

Exporting is necessary, because scripts run in sub-shells, although for the particular instance you cite it is only newtab that needs to be a function.
Functions can be used instead of aliases everywhere, but can do a lot more, such as adding an extra parameter to the end of the run string, a very simple requirement that aliases cannot do. In fact, they can do anything scripts can, but unlike scripts they run in the current shell, so they can change the environment and the current directory, for which a script needs . or source command to achieve.


Q:

React frontend and REST API, CSRF

Using React on the frontend with a RESTful API as backend and authorisation by JWT, how do we handle sessions? For example after login, I get a JWT token from REST. If I save it to localStorage I am vulnerable to XSS, if I save it to cookies, same problems except I set cookies to HttpOnly, but React can't read HttpOnly Cookies (I need to read cookie to take JWT from it, and use this JWT with REST requests), also I didn't mention CSRF problem. If you're using REST as backend, you can't use CSRF Tokens.
As a result, React with REST seems like a bad solution and I need to rethink my architecture. Is it possible to offer your users a secure React application that handles all business logic on the REST API side without fear of losing their data?
Update:
As far as I understood, it is possible to do this:

React makes AJAX call to REST API
React gets JWT token from REST
React writes HttpOnly cookie
Because React can't read HttpOnly cookies, we use it as-is in all our REST calls where we need authentication
REST calls check XMLHttpRequest header, which is some kind of CSRF protection
REST side checks for cookie, reads JWT from it and does stuff

I lack theoretical knowledge here, but the logic looks pretty secure, but I still need an answer to my questions and approve of this "workflow".

A:

React makes AJAX call to REST API

assured, lots of restful resource client lib available

React gets JWT token from REST

assured, this is what JWT should do

React writes httponly cookie

I don't think so, It should not work, but session is not such a important thing, it'll soon get out of date, and recheck password on key operations, even the hackers got it in a very short time, you can bind session token together with IP when user login and check it in your backend apis. If you want it most secured, just keep token in memory, and redo login when open new page or page refreshes

Because react can't read httponly cookie, we use it as-is in our all REST call where we need authentication

assured, check user and permissions through login token, like csrf you can put your login token into your request header, and check it in your backend apis.
Bind login token to your own restful lib will save you a lot codes

REST on calls checks XMLHttpRequest header, what is some kind of CSRF protection
  REST side check for cookie, read JWT from it and do stuff

assured, as most people do.
Also, bind csrf token to your own restful lib will save you a lot codes
use user token in header https://www.npmjs.com/package/express-jwt-token
Authorization JWT < jwt token >
use csrf token in header https://github.com/expressjs/csurf
req.headers['csrf-token'] - the CSRF-Token HTTP request header.
restful client https://github.com/cujojs/rest
react with jwt https://github.com/joshgeller/react-redux-jwt-auth-example

A:

Your server can set the JWT cookie directly as a response to the login request.
The server responds to POST /login with Set-Cookie: JWT=xxxxxx. That cookie is http only and therefore not vulnerable to XSS, and will be automatically included on all fetch requests from the client (as long as you use withCredentials: true).
CSRF is mitigated as you mentioned, see OWASP for details.


Q:

jQuery / Javascript - Is it possible to get the next call in the chain

I've seen the .filter() and .end() calls in a chain which leads me to believe that this is possible. So I've made my own function that can be added to the chain rawr()
$('#object').fadeIn().rawr().delay(1000).fadeOut();

I want rawr() to see what is coming up next and depending on what it is, allow execution to continue or to end the chain and move to the next line of code. How is this done?

A:

You can't get the next jQuery function in the chain of called functions directly without parsing the JavaScript source itself.
Given your comment:

I was thinking of not having this only deal with animations.

You'll want to use the queue method to store a function in the fx queue. When the custom function is executed, the fx queue will have queued all the animations in the jQuery chain.
Within your custom function you'd be able to access the fx queue and check what's been queued. You'd also be able to call clearQueue to remove any of the queued functions before dequeuing the fx queue.
It's necessary to dequeue the custom queued function as the fx queue wont continue for any other queued functions until the currently executing function has indicated that it's finished.
That all being said, it sounds like you should break your chain and conditionally execute methods, rather than trying to chain animations that are simply cleared later.


Q:

python: plotting numbers as a custom range

I'm not sure how to actually word it, but basically want i want to do is make 3 sets of number to be equivalent to the range of 0 to 10 so i that i can call it later.
for example, if i have the numbers 2, 4, and 9, i want it so that 2 represents 0, 4 as 5, and 9 as 10. that way say if i write a command that says like "call for a number that represents 2.5", then it gives me like 3. for more examples:
0=2, 2.5=3, 5=4, 7.5=6.5, 10=9
And i want it so that after i have set these numbers, i can just call from within this custom range of 2-9 by just saying which part of the scale i want (like I want the value that represents 1.25). Is there a way to do something like this in Python...?
PS: i'm sorry if a question like this already exists, I just don't know what this sort of thing is called.
EDIT: Just so you understand more of what i want to do, i'm trying to set this thing up as a script in Maya (3d program), and I would have a set of curves. Right now I have a script written to smooth out jagged curves by taking averages of 3 points and replacing that average to the middle number. But what I want to do is rather than taking just an average, is to be able to have an input of a value from 0-10 so it controls how much the curve smooths out. so if i have a curve where i have say 2 6 and 4 on Y, instead of making the middle number 3.667 (the average of the three values), I would want it to be at like 4 or 3.25, or anything other than the average. Essentially I want just a 0-10 system that controls how much this number decreases. I hope this makes sense.......

A:

For any three points, you can define a quadratic curve that fits them.
So for example, modifying code from this VB helper page, you get
def fit(p1, p2, p3):
    """Return the quadratic function that fits the three points p1, p2, p3,
    each defined as a tuple of (x,y) coordinates"""
    a = ((p2[1]-p1[1])*(p1[0]-p3[0]) + (p3[1]-p1[1])*(p2[0]-p1[0])) / \
        ((p1[0]-p3[0])*(p2[0]**2-p1[0]**2) + (p2[0]-p1[0])*(p3[0]**2-p1[0]**2))
    b = ((p2[1]-p1[1]) - a*(p2[0]**2 - p1[0]**2)) / (p2[0]-p1[0])
    c = p1[1] - a*p1[0]**2 - b*p1[0]
    return lambda x: a*x**2 + b*x + c

will give you a function that you can use (in Python 3) as follows:
>>> f = fit((0,2), (5,4), (10,9))
>>> f(2)
2.44
>>> f(100)
612.0
>>> f(4)
3.36
>>> f(5)
4.0
>>> f(9)
7.760000000000001

In Python 2, you need to call it with floats explicitly:
>>> f = fit((0.0,2.0), (5.0,4.0), (10.0,9.0))


Q:

ZF2 - Assuming other user's identity

Before I dive into reinventing the wheel, I'd first like to check if ZF2 supports, either out-of-the-box or with a 3rd party library, this particular use case where admins log in as other user, or assume their identity.
If not, as I'm not familiar with ZF2 internal design, how would I go into implementing this, with the only constraint being that the system is already built, so I can't change components (controllers, auth services, etc) into supporting it.
My first thought would be to make a mechanism to switch the logged user information stored in the session storage, with the one whose identity I want to assume. Then, write to the session, under a different namespace, the original user information (admin) so that it can be reverted.
Going by this approach, I am expecting components like Zend\Authentication\AuthenticationService return the user whose identity I'm assuming. So, in every call I make to $this->identity()->getId() (identity being a controller plugin for AuthenticationService, that returns the User) in other controllers, the business logic will work normally.
Having said this, the questions would be:

Is there a solution already for this?
Is my approach correct in assuming that by overwriting the session storage I can assume other user ID and expect ZF2 components to work accordingly, or is there any considerations regarding ZF2 internal design/infrastructure I haven't taken in consideration that I should?
Maybe there's a better way to do this?

A:

I think you would need to create your own AuthenticationAdaptor.
class AdminUserLoginAsUser implements \Zend\Authentication\Adapter\AdapterInterface
{

    /**
     * @var User
     */
    private $userToLoginAs;

    /**
     * @var AdminUser
     */
    private $adminUser;

    public function __construct(User $userToLoginAs, AdminUser $adminUser)
    {

        $this->userToLoginAs = $userToLoginAs;
        $this->adminUser = $adminUser;
    }

    /**
     * Performs an authentication attempt
     *
     * @return \Zend\Authentication\Result
     * @throws \Zend\Authentication\Adapter\Exception\ExceptionInterface If authentication cannot be performed
     */
    public function authenticate()
    {
        return new \Zend\Authentication\Result(
            Result::SUCCESS, $this->user, [
                'You have assumed control of user.',
            ]
        );
    }
}

The above class will allow you to login as another user when used with Zend's AuthenticationService class.
You will need some way of using Zend's AuthenticationService class and I would recommend using an AuthManager that wraps around the AuthenticationService.
/**
 * The AuthManager service is responsible for user's login/logout and simple access
 * filtering. The access filtering feature checks whether the current visitor
 * is allowed to see the given page or not.
 */
class AuthManager
{
    /**
     * Authentication service.
     * @var \Zend\Authentication\AuthenticationService
     */
    private $authService;

    /**
     * Session manager.
     * @var Zend\Session\SessionManager
     */
    private $sessionManager;

    /**
     * Contents of the 'access_filter' config key.
     * @var array
     */
    private $config;

    /**
     * Constructs the service.
     */
    public function __construct($authService, $sessionManager, $config)
    {
        $this->authService = $authService;
        $this->sessionManager = $sessionManager;
        $this->config = $config;
    }

    /**
     * Performs a login attempt. If $rememberMe argument is true, it forces the session
     * to last for one month (otherwise the session expires on one hour).
     */
    public function login($email, $password, $rememberMe)
    {
        // Check if user has already logged in. If so, do not allow to log in
        // twice.
        if ($this->authService->getIdentity()!=null) {
            throw new \Exception('Already logged in');
        }

        // Authenticate with login/password.
        $authAdapter = $this->authService->getAdapter();
        $authAdapter->setEmail($email);
        $authAdapter->setPassword($password);
        $result = $this->authService->authenticate();

        // If user wants to "remember him", we will make session to expire in
        // one month. By default session expires in 1 hour (as specified in our
        // config/global.php file).
        if ($result->getCode()==Result::SUCCESS && $rememberMe) {
            // Session cookie will expire in 1 month (30 days).
            $this->sessionManager->rememberMe(60*60*24*30);
        }

        return $result;
    }

    public function loginAsUser($user)
    {
        // Check if user has already logged in. If so, do not allow to log in
        // twice.
        if ($this->authService->getIdentity() !== null) {
            throw new \Exception('Not logged in.');
        }

        // First need to logout of current user
        $this->authService->clearIdentity();

        $authAdapter = $this->authService->setAdapter(new AdminUserLoginAsUser($user, $this->authService->getIdentity()));
        return $this->authService->authenticate();

    }

    /**
     * Performs user logout.
     */
    public function logout()
    {
        // Allow to log out only when user is logged in.
        if ($this->authService->getIdentity()==null) {
            throw new \Exception('The user is not logged in');
        }

        // Remove identity from session.
        $this->authService->clearIdentity();
    }

}

To see how to plug it all together I would recommend looking at the following resources:

https://olegkrivtsov.github.io/using-zend-framework-3-book/html/en/User_Management__Authentication_and_Access_Filtering.html
https://github.com/olegkrivtsov/using-zf3-book-samples/tree/master/userdemo/module/User

The resources are for zf3 but I think the authenticating of users and managing authentication is very similar to zf2.


Q:

Circle exercise Java?

This is not a homework,this is an exercise in a Java book I am learning by myself.
Build a class with the name circle which represents a circle in the coordinate plane.The fields of the class should be radius length,dy coordinates of the center.The methods of the class should be :
getArea() : Finds the area of the circle
getPerimeter() : Finds the perimeter of the circle
moveCircle() : Changes the coordinates of the center of the circle
modifyRadius() : Modifies the radius of the circle
private int x, y;

public Circle() {
   x = 0;
   y = 0;
   radius = 1;
}

public Circle(int x, int y, double radius) {
   this.x = x;
   this.y = y;
   this.radius = radius;
}

public double getArea() {
   return radius * radius * Math.PI;
}

public double getPerimeter() {
   return 2 * radius * Math.PI;
}

Now how do I continue this? for moveCircle and ModifyRadius?

A:

There should be a variable called radius in your class.
private int radius;

to move circle, you should pass your new location of the center to the object. Then it will set the new position.
public void moveCircle(int newX, int newY) {
  this.x = newX;
  this.y = newY;
}

To modify the radius you also can use the same method.
public void ModifyRadius (double newRadius) {
  this.radius = newRadius;
}

Another way is to create setters for the variables.
public void setX (int x) {
  this.x = x;
}

public void setY (int y) {
  this.y = y;
}

public void moveCircle (int x, int y) {
  setX(x);
  setY(y);
}

public void setRadius (double radius) {
  this.radius = radius;
}


Q:

How to avoid defensive if conditions in python?

I am writing a code which tries to dig deep into the input object and find out a value lying inside that object. Here is a sample code:
def GetThatValue(inObj):
    if inObj:
       level1 = inObj.GetBelowObject()
       if level1:
           level2 = level1.GetBelowObject()
           if level2:
               level3 = level2.GetBelowObject()
               if level3:
                  return level3.GetBelowObject()
    return None

There are many situations where I end up with these "slanted if conditions".
How can I avoid this? This looks dirty and also it is kind of defensive programming.

A:

Using for loop:
def GetThatValue(inObj):
    for i in range(4):
        if not inObj:
            break # OR return None
        inObj = inObj.GetBelowObject()
    return inObj

UPDATE
To avoid deeply nested if statements. Check the exceptional case, and return earlier.
For example, following nested ifs:
if a:
    if b:
        return c
return d

can be transformed to flattened ifs:
if not a:
    return d
if not b:
    return d
return c

A:

try:
    return monkey.TypeWriter().Manufacturer().Shareholders().EthnicDistribution()
except AttributeError:
    return None

Try to get the thing. If it doesn't work, you know one of the levels was missing. This works particularly nicely if those GetBelowObject calls aren't actually all the same method.


Q:

probems using ssh from cron

I am attempting to automate a script that executes commands on remote machines via ssh. I have public key authentication setup between the machines using ssh-agent. The script runs fine when executed from the command prompt. I suspect my problem is that cron isn't starting the ssh-agent due to it's minimalist environment. Here is the output when I add the -v flag to ssh:
debug1: Authentications that can continue: publickey,gssapi-with-mic,password
debug1: Next authentication method: gssapi-with-mic
debug1: Authentications that can continue: publickey,gssapi-with-mic,password
debug1: Authentications that can continue: publickey,gssapi-with-mic,password
debug1: Next authentication method: publickey
debug1: Offering public key: /home/<user>/.ssh/id_rsa
debug1: Server accepts key: pkalg ssh-rsa blen 149
debug1: PEM_read_PrivateKey failed
debug1: read PEM private key done: type <unknown>
debug1: Trying private key: /home/<user>/.ssh/id_dsa
debug1: Next authentication method: password
debug1: Authentications that can continue: publickey,gssapi-with-mic,password
Permission denied, please try again.
debug1: Authentications that can continue: publickey,gssapi-with-mic,password
Permission denied, please try again.
debug1: Authentications that can continue: publickey,gssapi-with-mic,password
debug1: No more authentication methods to try.
Permission denied (publickey,gssapi-with-mic,password).

How can I make this work? Thanks!

A:

I ended up starting ssh-agent in the script before making the ssh call with the following code. Works like a charm.
PATH=$PATH:$HOME/bin
SSH_ENV="$HOME/.ssh/environment"

function start_agent {
     echo "Initialising new SSH agent..."
     /usr/bin/ssh-agent | sed 's/^echo/#echo/' > "${SSH_ENV}"
     echo succeeded
     chmod 600 "${SSH_ENV}"
     . "${SSH_ENV}" > /dev/null
     /usr/bin/ssh-add;
}

# Source SSH settings, if applicable

if [ -f "${SSH_ENV}" ]; then
     . "${SSH_ENV}" > /dev/null
     #ps ${SSH_AGENT_PID} doesn't work under cywgin
     ps -ef | grep ${SSH_AGENT_PID} | grep ssh-agent$ > /dev/null || {
         start_agent;
     }
else
     start_agent;
fi

export PATH
unset USERNAME


Q:

Javascript Pass parameter to function inside variable

I'm trying to assign a click handler to a JQuery object, defined in a variable :
some.object.array[8].action = function(data){console.log(data);}
anotherobject = {..}

now inside some loop, I need to assign this function to the click handler:
and want to pass the whole 'anotherobject' object
for (var i = 0; i < foo.length; i++) {
    $('<div/>').click(some.object.array[i].action);
}

But how can I pass the parameter?
If I encapsulate it inside some anonymous function, I'm losing my scope...:
for (var i = 0; i < foo.length; i++) {
    $('<div/>').click(function() {
        some.object.array[i].action(anotherobject)
    });
}

because i has changed...
How are we supposed to do this?

A:

There are just too many ways to do this:
for (var i = 0; i < foo.length; i++) {
    (function(i) {
        $('<div/>').click(function() {
            some.object.array[i].action(anotherobject);
        });
    })(i);
}

Or
for (var i = 0; i < foo.length; i++) {
    $('<div/>').data("i", i).click(function() {
            var i = $(this).data("i");
            some.object.array[i].action(anotherobject);
        });
    });
}

Or
function getClickHandler(callback, parameter) {
    return function() { callback(parameter); };
};
for (var i = 0; i < foo.length; i++) {
    $('<div/>').click(getClickHandler(some.object.array[i].action, anotherobject));
}


Q:

Mobile Chat functionality using Push Notifications, when should something be pushed?

(The following question is for mobile platforms in general (iPhone, Android, Blackberry))
We are integrating chat functionality into our existing application. I designed the system with a .Net web service and Sql Database to keep track of chat messages. Everything's working fine so far, when the chat window is open.
I need a way to notify the user of a new message when he/she is not currently viewing the chat screen (meaning either the app is not in the foreground or they are in another section of the app (not the chat screen).
Obviously, push notifications would be perfect here, but I'm not sure when I should be sending pushes.
How would the client sending the message know whether or not the other guy is viewing the chat screen? Should I just be sending pushed with every single message and have the receiving device decide whether or not it needs to pop up a window or display something in a nofication bar?
It seems like overkill to be pushing every single time a message is sent. How is this normally done?
Any ideas at all would be greatly appreciated.
Thanks.

A:

First and foremost, keep in mind that your server will act as the broker for all messages passed between different chat clients. Here's how this could work:

User A initiates a message for user B
Message gets sent to the server.
Server determines that this message is for user B.
Server initiates a push notification and delivers the message to user B.

Now why would you need to push every single chat message? Because the only other way for your users to get notified would be to poll your server for new messages. Constant polling (at whatever rate you determine) is extremely bad in the mobile realm due to limited resources (battery, networking, etc.)
In a push notification scenario, it is up to your application to handle the logic of whether the user is notified on receiving a new message. What this means is that when user B receives a new message from user A, it's up to you to decide if you wish to notify B (i.e.  bring your app to the foreground) or not. In either scenario, you want to use push notifications instead of polling.
On a similar note, user B does not necessarily have to know that user A's application (your app) is in the background which is why you will need to handle that logic (within your app) appropriately.


Q:

how to display my own custome message in the top of admin page

want to display my own custom message and link in the top of localhost/admin/module/field before the select fields to change page. I tried with link_display that for displaying each instance obj itself, and i don't want that.

A:

You need to override the change_list.html template for your app, see the documentation.
Money quote for your problem:

For example, if we wanted to add a tool to the change list view for
  all the models in an app named my_app, we would copy
  contrib/admin/templates/admin/change_list.html to the
  templates/admin/my_app/ directory of our project, and make any
  necessary changes.


Q:

Why am I getting null reference error for spinner here?

I am programming in android studio and here is my code snippet :
public class settingsView extends Fragment {

    public settingsView() {
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        final Spinner citySpinner = (Spinner) getActivity().findViewById(R.id.citySpinner);

        FirebaseDatabase.getInstance().getReference("/movies/karnataka").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                ArrayList<String> cityList = new ArrayList<>();

                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    cityList.add(snapshot.getKey());
                }

                Log.d("firebasedata", cityList.toString());

                ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getApplicationContext(), android.R.layout.simple_spinner_item, cityList );
                adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
                citySpinner.setAdapter(adapter);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
            }
        });

        return inflater.inflate(R.layout.settingsview, container, false);
    }
}

I am getting
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Spinner.setAdapter(android.widget.SpinnerAdapter) on a null object reference exception

at line :
citySpinner.setAdapter(adapter)

A:

You need to first inflate the xml file which has the view for your fragment in oncreateview.
Then use that view to do the findviewbyid:
view = inflater.inflate(R.layout.fragment_xml, container, false);
final Spinner citySpinner = (Spinner) view.findViewById(R.id.citySpinner);


Q:

Should I create an index for non key columns?

I have a table in a PostGreSql database defined as following:
CREATE TABLE public."MATCH"(
    "ITEM_A_ID" bigint DEFAULT 0,
    "ITEM_B_ID" bigint DEFAULT 0,
    "OWNER_A_ID" bigint DEFAULT 0,
    "OWNER_B_ID" bigint DEFAULT 0,
    "OTHER_DATA" varchar(100) NOT NULL DEFAULT ''
    CONSTRAINT "MATCH_PK" PRIMARY KEY ("ITEM_A_ID","ITEM_B_ID")
);

It will contain a lot of rows. There will be a lot of queries like the following performed on this table:
SELECT * FROM "MATCH" WHERE "OWNER_A_ID" = owner_a_id;
SELECT * FROM "MATCH" WHERE "OWNER_B_ID" = owner_b_id;

I was thinking about creating indexes on OWNER_A_ID and OWNER_B_ID, since these columns are not keys. Is this a good idea, and if yes, how should I create these? Should I create one index with both columns? Should I create two indexes? Should I include other columns?

A:

Please be more specific: "It will contain a lot of rows". How many? Millions, thousands or billions. "Is it a good idea?" It depends.
If your queries are like the ones you mention, you should create two b-tree indexes, one for each field. Instructions are here: http://www.postgresql.org/docs/9.1/static/sql-createindex.html
You should only create one index for both fields, ONLY IF all your queries are like:
SELECT * FROM "MATCH" WHERE "OWNER_A_ID" = owner_a_id AND "OWNER_B_ID"=owner_b_id;

This index will also work for queries like:
SELECT * FROM "MATCH" WHERE "OWNER_A_ID" = owner_a_id;

but NOT for
SELECT * FROM "MATCH" WHERE "OWNER_B_ID" = owner_b_id;

A:

The selection of enough indexes is often difficult. In your case it should be useful to create two indexes.
You should only create one index with both columns if your query always include the first column as a condition:
SELECT * FROM "MATCH" WHERE "OWNER_A_ID" = owner_a_id [AND "OWNER_B_ID" = owner_b_id]

The whole B-Tree is built upon the order of columns in the index! You can't fully use a multi-column index on a, b on the following queries:
SELECT * FROM "MATCH" WHERE "OWNER_A_ID" = owner_a_id OR "OWNER_B_ID" = owner_b_id
SELECT * FROM "MATCH" WHERE "OWNER_A_ID" = "OWNER_B_ID"

If you're only using equality checks you might consider a hash index. But postgresql has some disadvantages you should check first.
On other dbms you should consider adding additional columns in the index as data. This would be useful if you query these specific columns and not * because the dbms wouldn't need to feed the data from the table after using the index.
An important factor: indices fragment over the time (unless you aren't performing any insert/update/delete on the table). Please check whether your dba has some optimization operations installed.
Pleae check the documentation for additional options like FILLFACTOR or partial indexes: http://www.postgresql.org/docs/9.3/static/sql-createindex.html


Q:

Show that $L/L_s$ is purely inseparable and $L_s/ K$ is separable.

Let $L/K$ be an extension of fields, let $L_s$ be the separable closure of $K$ on $L$. Show that $L/L_s$ is purely inseparable and $L_s/ K$ is separable.
That $ L_s / K $ is separable, follows directly from the definition of $ L_s $.
Could you help me show that $L /L_s$  is purely inseparable? Thanks..

A:

Hint: Suppose some $\alpha\in L$ is separable over $L_s$.  What can you say about $\alpha$ over $K$?
A full answer is hidden below.

 Since $\alpha$ is separable over $L_s$ and $L_s$ is separable over $K$, $\alpha$ is separable over $K$.  But that implies $\alpha\in L_s$ by definition of $L_s$.  Thus any element of $L\setminus L_s$ is inseparable over $L_s$, so $L$ is purely inseparable over $L_s$.


Q:

SQL query for partitioning using two columns

I have an Oracle table called sites where there are multiple records for the same name. For Eg.:
 Owner Name          Contact Name            Owner Address  Contact Address
        A                  A                   XYZ                 SDF
        A                  D                   ABC                 JKL
        B                  E                   QWE                 YUR
        B                  F                   JKL                 SFD
        C                  C                   ZXC                 ASD
        B                  G                   BNM                 SAD

My SQL query should return
A1           XYZ
A2           ABC
A3           SDF
B1           QWE
B2           JKL
B3           BNM
C1           ZXC
C2           ASD
D            JKL
E            YUR
F            SFD
G            SAD

Could someone help me write such a query.Ideally, I wouldn't like a number suffix with single records but if  it simplifies the query I could do with that too.

A:

You can use union to create what you want:
with the_data as (
  select owner_name as name, owner_address as address
    from my_table
   union all
  select contact_name as name, contact_address as address
    from my_table
         )
select name
        || case when count(*) over ( partition by name ) = 1 then ''
                else to_char(row_number() over ( partition by name
                                                     order by address ))
           end
     , address
  from the_data

If you only want distinct address, contact combinations change the union all to union. Here it is in SQL Fiddle form.


Q:

File structure for custom modules in Drupal 7

Note: I have already posted this question on [SE's drupal] but didnt got any positive response there so i am posting same question here again.

I want to organize non-core(modules that are not bundled with core) modules in Drupal 7. This is my proposed structure:

Contributed modules - downloaded modules that are untouched
Custom modules - downloaded modules that are modified to suit the requirement
local modules - self-developed modules

I GUESS, the best approach for this is to make three folders within sites/all/modules like below:

sites/all/modules/contrib
sites/all/modules/custom
sites/all/modules/local

Now, there are two ways to install a module:

Manually
From the admin panel

While installing the new module manually, everything is fine. I can just go to the directory and place the module there. But how to install a newly downloaded module in `sites/all/modules/contrib from admin-panel. Moreover, is there any better approach for organizing non-core modules?

A:

Finally after banging head on google for hours, asking question on SO and SE's drupal and communicating with other users via comments, I cracked it...
Well, the directory structure is still debatable but satisfactory for me. But the answer to the most imp question is "DRUSH".
Refer this and this node from Drupal. Collectively, it has everything needed to answer my entire question.
I would also like to point you to this answer which has provided the first and most-imp hint to me.


Q:

What is the root logger in log4net

I don't quite understand what the main functionality for root logger as shown in following section is. What is the difference from other loggers?
<root>
  <level value="WARN" />
  <appender-ref ref="RollingLogFileAppender" />
</root>

A:

I think the log4net documentation explains this quite nicely:
Loggers are organized in hierarchies. E.g.: The logger Foo.Bar is child of the logger Foo. This way the loggers create a tree and the root logger is simply the root of that tree (in the example Foo is a child of the root logger).
This hiearchy allows for some interesting configuration applications (e.g. disable/enable logging for an entire sub system of your application).

A:

The Root Logger can hold a list of appenders and settings (typically just the log level) used when logging.
Check this link for more details about the Root Logger with Log4net.


Q:

How to retrieve a html text from rich text area into word document without html code by Bonita BPM?

I am developing a Bonita application.
I created a word document using by the connector.
It works well. however, the data from a rich text area retrieve with HTML code.
For example,
This is the format of the word document.
    «${doc.firstName}» «${doc.lastName}»,

    «${today}»
    Request conclusion
    Dear «${doc.firstName}»,
    After review by the HR, your request for «${doc.requestCategory}» has been evaluated.

     Request conclusion:

        «${doc.conclusion}»

 And the result is as follow;
Walter Bates
2019-04-02
Request conclusion
Dear Walter,
After review by the HR, your request for Request has been evaluated.
Request conclusion:
< p >< b >Hello,< /b >< / p >< p >< b > This is conclusion < /b >< /p>
** In order to show the HTML code, I put some space between the code.
How to retrieve the HTML code from the BDM?
Thanks in advance

A:

I spent time looking at the connector source code and sadly I can confirm that the Word / ODT template connector currently does not support HTML formatting of a field. I have created a new entry for this improvement (for this Enterprise Edition feature) in our internal features/improvements tracker tool.
The only alternative I might suggest is to create your own connector.


Q:

Can "although" and "however" be used together?

I know that a sentence does not contain both "although" and "but" at the same time.
Niall has also pointed out that the following sentence is wrong:

Although some of the plots are transcendental, the justice deeply rooted in people's mind, however, will surely applaud for the victory of him.

As DamkerngT. mentioned in the comment, after changing the word order of "however", the following sentence can be correct:

Although some of the plots are transcendental, the justice deeply rooted in people's mind will, however, surely applaud for the victory of him.

Is it true that I have to change it to get a correct sentence? And what is the grammar term for "however" in the second(correct) sentence?
Thanks

A:

"However" is basically intended to be introduced as a parenthetical comment.
The problem is that it it is placed in a spot where it looks ambiguously like a conjunction.
There is considerable flexibility in the language. For instance, suppose instead of "however" we introduce the a phrase like "you know" or "come to think of it", or "I suspect":

Although some of the plots are transcendental, the justice deeply rooted in people's mind, I suspect, will surely applaud for the victory of him.
Although some of the plots are transcendental, the justice deeply rooted in people's mind will, I suspect, surely applaud for the victory of him.
I suspect, although some of the plots are transcendental, the justice deeply rooted in people's mind will surely applaud for the victory of him.
Although some of the plots are transcendental, the justice deeply rooted in people's mind will surely applaud for the victory of him, I suspect.

Basically "however" is acting as a comment phrase of this type and not as a formal conjunction. It is acceptable because it reinforces the "although", or at least does not outright conflict with it semantically.  "However" can be put in all those same places as "I suspect", and just makes a comment that the second clause is in spite of the first clause.
But, as I will get to in a moment, there is a reason why we perceive a slight problem specifically with the sentence.
Basically both of these forms can mean "S2 in spite of S1":

Although S1, S2.
S1; however, S2.

so there is synergy between "although" and "however".
What is going on in the first example is that the "although" relativizes the clause. S1 is a subordinate clause of the main clause S2, creating a big clause.
Now consider this pattern:

However, although S1, S2.

In this pattern, built on the first example, S1 and S2 are still relativized, and so the "however" applies to both of them as a unit, and has a relationship in particular with S2 which is the main clause to which S1 is subordinated.
There must be some earlier clause S0 which is being contrasted by "however", that is:

S0. However, although S1, S2.

Now the meaning is something like: "in spite of or in contrast with S0, and in spite of S1, we have S2".
Anyway, since we can have an introductory "however" in front of the whole clause which isn't functioning as a conjunction with the earlier S0, it is also legitimate that we can move it around within the clause, like we can do with any other introduction such as "in my opinion", "I suspect", "surprisingly", "unfortunately". For instance, we can move it way into the middle of S2:

S0. Although S1, S2a, however, S2b.

Concrete example:

Jack gets top grades without studying hard. Although Janet studies hard, she, however, maintains only a C average. [Janet gets only C's, in spite of studying hard, which is in contrast to Jack]

And now, finally, we get to the crux of the issue. Suppose the above "however" moves into this position:

S0. Although S1; however, S2.*

Oops! There is a problem, because it now resembles the conjunctive "however" which relates S1 and S2, not S0 and S2, as in:

S1; however, S2.

Concretely:

Jack gets top grades without studying hard. Although Janet studies hard; however, she maintains only a C average.*

If we write the "however" in the conjunctive style semicolon-however-comma it really jumps out as wrong. If we just put commas, it is acceptable because we are able to understand it as the commentary "however" linking back to the first sentence:

Jack gets top grades without studying hard. Although Janet studies hard, however, she maintains only a C average.

In other words, we can use this in speech, but when we write it down, we must not use semicolon-however-comma, and for best clarity, we should probably avoid it, at least in writing, by moving the "however" elsewhere:

Jack gets top grades without studying hard. However, although Janet studies hard, she maintains only a C average.
Jack gets top grades without studying hard. Although Janet studies hard, she maintains only a C average, however.

Etc.


Q:

Android Studio "Function invocation 'Button(...) expected"

I am a novice at android studio and I am trying to make a simple calculator that takes a string and returns a value.
The issue is that when writing the code to initialize a "Button" object, it believes I am trying to call a function. It shows an error that says that:
Function invocation 'Button(...) expected

But I am not trying to call a function for button just make a Button object.
This is my main activity file:
package com.example.myfirstcalc

import android.os.Bundle;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main)

        Button calcBtn =  (Button) findViewById(R.id.calculateBtn);
    }
}

This is the activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/expressionEditText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="124dp"
        android:ems="10"
        android:hint="Enter an expression"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0" />

    <Button
        android:id="@+id/calculateBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Calculate"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/expressionEditText"
        app:layout_constraintVertical_bias="0.089" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Result"
        android:textSize="30sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/calculateBtn"
        app:layout_constraintVertical_bias="0.124" />
</androidx.constraintlayout.widget.ConstraintLayout>

A:

The problem is due to incorrect syntax. You are mixing syntax of Java and Kotlin
To write it correctly in Kotlin, change the line:
Button calcBtn =  (Button) findViewById(R.id.calculateBtn);

to:
val calcBtn =  findViewById(R.id.calculateBtn) as Button

To know basic information about Android application in Kotlin see here. To know basics syntex of Kotlin, visit here.


Q:

wondering about multiplicative (not arithmetic) sequences of primes

(Apologies in advance if the terminology is wrong).
I've been led by my research into looking at sequences of primes of the form $(p_1,p_2,\ldots,p_m)$ with each $p_i$ of the form $k_i(p_1-1)+1$, where  $k_i$ is a strictly increasing finite sequence of integers.  Additionally, the sequences I'm interested in have the property that each $k_i$ divides $k_m$.
For example $(7,13,19,37)$ has this property, with $p_1=7$ and the $k_i = \{1,2,3,6\}$.
$(7,13,19,31)$ does not meet the requirements, because the $k_i$ are $ = {1,2,3,5}$.
Sequences that meet both requirements have the property that $lcm(p_1-1,\ldots,p_m-1)=\lambda(\prod_{i=1}^m p_i)$ (Carmichael's lambda function), is $p_m-1$, the minimum possible value for $m$ primes.  Lambda in the first case is $\lambda(7.13.19.37)= 36$, but lambda in the second case is $\lambda(7.13.19.31) = 180$.
Anyone know anything about what happens to the prevalence of such sequences (beyond the fact they become less frequent) as m increases with fixed p1?  As p1 increases with fixed m?  As the maximum k increases?  Any informed speculation?  Starting points besides the Prime Number Theorem?  Grateful for any help.

A:

Given a prime $p_1$, the obvious algorithm is to use Dirichlet's theorem in arithmetic progressions to find $m-2$ primes $p_2,\ldots,p_{m-1}\equiv 1\bmod p_1-1$, then compute $\ell = \lambda(\prod_{i=1}^{m-1} p_i)$ and use Dirichlet's theorem again to find a prime $p_m\equiv 1 \bmod \ell$.
The minimal size of $\lambda(\prod_{i=1}^m p_i)$ as $p_1\to \infty$ depends on the least prime in arithmetic progression as well as the expected size of $\gcd(p_2-1,\ldots,p_{m-1}-1)$. The random model for the primes should predict those quantities reasonably well.


Q:

How to insert carriage return in regex replace

I want to insert newline character in regex replace what field.
For example:
Find With: (xyxyxy.*[\r\n]+)(yzyzyz)

Replace with: $1xyxyxy\r\nxyxyxy

also tried replace with: $1xyxyxy$r$nxyxyxy

None of them seems to be working.
Question is what is the mantra to insert carriage return and/or new line via regex replace.

A:

You can capture the newline characters and use that in replacement. By capturing the newline characters, you don't have to worry about differences in different OS representation of newline.
Find:
(xyxyxy.*(\r\n|\r|\n)+)(yzyzyz)

Replace:
$1$2$3

$2: Is the single newline character.


Q:

fetch data in dropdownlsit using linq

i am new to ASP.NET,
i am making Country, state dropdownlist.
for eg: For particular country, i will read states of that country from XML file.
i am unable to fetch states of required country in my Dropdownlist...
here is my code snippet in XMLFile.xml
 <?xml version="1.0" encoding="utf-8" ?>
<countrys>

  <country name="India">
    <state value1="Maharashtra"></state>
    <state value2="Kashmir"></state>
    <state value3="Goa"></state>
  </country>

  <country name="Sri Lanka">
    <state value1="Kanady"></state>
    <state value2="Colombo"></state>
    <state value3="Galle"></state>
  </country>

  <country name="Australia">
    <state valu1e="Sydney"></state>
    <state value2="Perth"></state>
    <state value3="Melbourne"></state>
  </country>

  <country name="South Africa">
    <state value1="Capetown"></state>
    <state value2="Johanusburg"></state>
      <state value3="Durban"></state>
  </country>

</countrys>

and code in Country.aspx.cs
 public partial class Country : System.Web.UI.Page
   {
       protected void Page_Load(object sender, EventArgs e)
       {

            if (!IsPostBack)
            {
                LoadDropdown();
            }
     }

    protected void LoadDropdown()
    {
            DataSet ds = new DataSet();
            ds.ReadXml (Server.MapPath("XMLFile.xml"));

            DropDownListCountry.DataTextField = "country_text";

            DropDownListCountry.DataSource = ds;
            DropDownListCountry.DataBind();
            DropDownListCountry.Items.Insert(0,new ListItem(" Select ","0"));
        }
     }

    protected void DropDownListCountry_SelectedIndexChanged(object sender, EventArgs e)
    {
            string  st = (DropDownListCountry.SelectedIndex).ToString();

             XDocument main = XDocument.Load(@"XMLFile.xml");

        var query = from state in doc.Descendants("countrys").Elements("country")
                    where st == state.Value
                    select state.NextNode;

        DropDownListState.DataSource = query;
        DropDownListState.DataBind();
    }
}

ERROR :  Object reference not set to an instance of an object.
Thanks In Advance !!

A:

OK here is the solution:
First few changes in the xml, the attribute 'value1' in the state element should be value for all. So the new XML is:
<?xml version="1.0" encoding="utf-8" ?>
<countrys>

  <country name="India">
    <state value="Maharashtra"></state>
    <state value="Kashmir"></state>
    <state value="Goa"></state>
  </country>

  <country name="Sri Lanka">
    <state value="Kanady"></state>
    <state value="Colombo"></state>
    <state value="Galle"></state>
  </country>

  <country name="Australia">
    <state value="Sydney"></state>
    <state value="Perth"></state>
    <state value="Melbourne"></state>
  </country>

  <country name="South Africa">
    <state value="Capetown"></state>
    <state value="Johanusburg"></state>
    <state value="Durban"></state>
  </country>

</countrys>

Now come to ASPX page: You should have two drop down lists with AutoPostBack set to true
<asp:DropDownList ID="DropDownListCountry" runat="server" AutoPostBack="true"
    onselectedindexchanged="DropDownListCountry_SelectedIndexChanged">
</asp:DropDownList>
<asp:DropDownList ID="DropDownListState" runat="server" AutoPostBack="true"
    onselectedindexchanged="DropDownListState_SelectedIndexChanged">
</asp:DropDownList>

Now in the Code behind:
Call LoadCountryDropDown to populate Country - I am using LINQ to XML here as well instead of data set
protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                LoadCountryDropDown();
            }

        }
        void LoadCountryDropDown()
        {
            XDocument doc = XDocument.Load(Server.MapPath("test.xml"));

            DropDownListCountry.DataSource = from t in doc.Descendants("countrys").Elements("country")
                                             select new
                                             {
                                                 Name = t.Attribute("name").Value
                                             };

            DropDownListCountry.DataTextField = "Name";
            DropDownListCountry.DataValueField = "Name";
            DropDownListCountry.DataBind();
            DropDownListCountry.Items.Insert(0, new ListItem(" Select ", "0"));
        }

LoadStateDropDown() method to populate State drop down on Selected index changed event of country drop down
private void LoadStateDropDown(string p)
    {
        XDocument doc = XDocument.Load(Server.MapPath("test.xml"));

        var statequery = from t in doc.Descendants("countrys").Elements("country")
                                         where t.Attribute("name").Value.Equals(p)
                                         select new
                                         {
                                             State = t.Elements("state").Attributes("value").ToList()
                                         };

        DropDownListState.DataSource = statequery.First().State;
        DropDownListState.DataTextField = "value";
        DropDownListState.DataValueField = "value";
        DropDownListState.DataBind();
        DropDownListState.Items.Insert(0, new ListItem(" Select ", "0"));
    }

In the end you have event handler for drop down list
 protected void DropDownListCountry_SelectedIndexChanged(object sender, EventArgs e)
        {

            LoadStateDropDown(DropDownListCountry.SelectedValue);
        }
  protected void DropDownListState_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

(Please rename countrys to countries in xml)


Q:

Center a nav item (or logo) responsive in the middle of a navbar

I can't seem to find an elegant and responsive way to auto position a 'logo' in the center of a navbar consider more items could be added or removed, and it would make much more sense than fixed margin numbers (as I know I could do it that way).
The design is simple (built in Gatsby):

nav {
  display: flex;
  margin: 0 auto;
  max-width: 600px;
}

a {
  margin-right: 20px;
}

.logo {
  margin: 0 auto;
}

  Item 1
  Item 2
  Item 3
  Logo
  Item 4

I'm not sure how to approach this problem without, as mentioned before, fixing margin number (i.e. 10px left 22px right) with the combination of media queries.
Anyone have any solutions?

A:

One solution might be to group your nav into 3 different sections, left, center and right. Then use flex box to position these, but give them a min and max of a 3rd of a page. Also, you will need to center your logo and right align your right column.
Probably a more robust solution is to use CSS grid. Same sort of idea where divide your page into 3 columns, but you can set your 3 columns widths to 1fr, instead of giving a min and max width of 33.333333...% - This is far more elegant solution, I think. I've provided an example of this too.

nav {
  display: flex;
  justify-content: flex-start;
}

nav>div {
  max-width: 33.3333%;
  min-width: 33.3333%;
}

.logo {
  text-align: center;
}

.right {
  text-align: right;
}

.grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
}

.grid-left {
  grid-column: 1 / 2;
  background-color: darkseagreen;
}

.grid-center {
  grid-column: 2 / 3;
  background-color: coral;
  text-align: center;
}

.grid-right {
  grid-column: 3 / 4;
  background-color: steelblue;
  text-align: right;
}

Flex example

    Item 1
    Item 2
    Item 3

    Logo

    Item 4

Grid example

    Item 1
    Item 2
    Item 3
    Item 4
    Item 5

    Logo

    Item 4


Q:

How do I get CAML for a custom content type

I am trying to get the CAML for a custom content type that I am creating. What I am really doing is creating the content type in Visual Studio 2010 via CAML and then deploying that content type to my sandbox using the new deploy features in VS 2010. At that point, I am modifying the content type using the SharePoint interface (i.e changing advanced settings, adding columns, etc) since it is easy to do via the web interface. What I would like to do, is after I have made my changed, update my CAML in Visual Studio to match my changes.
I want to do this because I am creating custom fields and content types for my project and want to create a solution with these customizations. Since there doesn't seem to be a way to do this (create custom fields and content types) as a solution using SharePoint without putting them into a list, I am using Visual Studio and CAML for this. I also want to use Visual Studio and CAML so that I can put these CAML xml files in source control so that I can version my custom fields and custom types.
I have tried using tools like http://spcamlviewer.codeplex.com/ but that doesn't seem to work with SP 2010.
Does anyone have any suggestions? I wish Visual Studio would just have an update from SP button after I have deployed my solution and made changes on the server so it would sync VS from the SP server.

A:

SharePoint Manager 2010


Q:

How to create a Raster from a pixel float array in Java?

I'm trying to take a BufferedImage, apply a Fourier transform (using jtransforms), and write the data back to the BufferedImage. But I'm stuck creating a new Raster to set the results back, am I missing something here?
BufferedImage bitmap;
float [] bitfloat = null;

bitmap = ImageIO.read(new File("filename"));
FloatDCT_2D dct = new FloatDCT_2D(bitmap.getWidth(),bitmap.getHeight());

bitfloat = bitmap.getData().getPixels(0, 0, bitmap.getWidth(), bitmap.getHeight(), bitfloat);
dct.forward(bitfloat, false);

But I'm stumped trying to finish off this line, what should I give the createRaster function? The javadocs for createRaster make little sense to me:
bitmap.setData(Raster.createRaster(`arg1`, `arg2`, `arg3`));

I'm starting to wonder if a float array is even necessary, but there aren't many examples of jtransforms out there.

A:

Don't create a new Raster. Use WritableRaster.setPixels(int,int,int,int,float[]) to write the array back to the image.
final int w = bitmap.getWidth();
final int h = bitmap.getHeight();

final WritableRaster wr = bitmap.getData();
bitfloat = wr.getPixels(0, 0, w, h, bitfloat);

// do processing here

wr.setPixels(0, 0, w, h, bitfloat);

Note also that if you're planning to display this image, you should really copy it to a screen-compatible type; ImageIO seldom returns those.


Q:

How can I synchronize the bar width between two histograms when merging with ggarrange()?

Please, find my data w below.
I have produced these two histograms, Plot A and Plot B, which I subsequently merged using ggarrange()

As you can see, the widths of the bars does not match between the two individual histograms. Its probably because of the 0 events in plot A.
How can I synchronize the width between the bars in plot A and plot B, respectively? Like this:

I used these scripts
# Plot A
io <- ggplot() +

  geom_bar(mapping = aes(x = w$WHO[w$response==1]), stat = "count", alpha=0.2, colour="#1C73C2", fill="#ECF0F9") +

  scale_y_continuous(name = "Number of progressions", breaks=yaks, sec.axis = sec_axis(~ . * 1 , name = "Progression rate per 100 person-yrs", breaks=yaks, labels=c("0","40","80","120","160","200","240","280","320","360"))) +
  scale_x_continuous(name="", breaks = c(1,2,3,4), labels =c("\nWHO-I\nn=32","\nWHO-II\nn=23","\nWHO-III\nn=16","\nUnknown\nn=5")) +
  coord_cartesian(ylim=c(0, 18)) +

  geom_point(mapping = aes(x = 1, y = 0.2677376), size=5, alpha=0.7, shape=18, colour="red") +
  geom_point(mapping = aes(x = 2, y = 3.2870709), size=5, shape=18,alpha=0.7, colour="red") +
  geom_point(mapping = aes(x = 3, y = 16.98), size=5, shape=18,alpha=0.7, colour="red") +

  annotate("text", x = c(1,2,3, 4) , y = c(0.2677376+1.3, 3.2870709+1.3, 16.98+1.3, 0.5),  label = c("5.4","65.7","339.6", "0 events"), col="red", fontface=2, cex=4)+

  theme(axis.text.y.right = element_text(color = "red", size = 11),
        axis.title.y=element_text(color="darkgrey", size=11,face="bold", margin = margin(t = 0, r = 15, b = 0, l = 0)),
        axis.text.y = element_text(color = "#1C73C2", size = 11),
        axis.title.y.right=element_text(color="darkgrey", size=11,face="bold", margin = margin(t = 0, r = 0, b = 0, l = 15)),
        axis.text.x = element_text(color = "grey20", size = 11))

And
# Plot B
yt <- ggplot()  +
  geom_bar(mapping = aes(x = w$WHO[w$Death==1]), stat = "count", alpha=0.2, colour="#1C73C2", fill="#ECF0F9")  +

  scale_y_continuous(name = "Number of deaths", breaks=yaks, sec.axis = sec_axis(~ . * 1 , name = "Mortality rate per 100 person-yrs", breaks=yaks, labels=c("0","5","10","15","20","25","30","35","40","45"))) +
  scale_x_continuous(name="", breaks = c(1,2,3,4), labels =c("\nWHO-I\nn=37","\nWHO-II\nn=29","\nWHO-III\nn=19","\nUnknown\nn=25")) +

  coord_cartesian(ylim=c(0, 18)) +

  geom_point(mapping = aes(x = 1, y = 3.329993), size=5,alpha=0.7, shape=18, colour="red") +
  geom_point(mapping = aes(x = 2, y = 12.424504), size=5,alpha=0.7, shape=18, colour="red") +
  geom_point(mapping = aes(x = 3, y = 17.23519), size=5, alpha=0.7,shape=18, colour="red") +
  geom_point(mapping = aes(x = 4, y = 4.549763), size=5, alpha=0.7, shape=18, colour="red") +

  annotate("text", x = c(1,2,3,4) , y = c(3.329993+1.3, 12.424504+1.3, 17.23519+1.3,4.549763+1.3 ),  label = c("8.3","31.1","43.1","11.4"), col="red", fontface=2, cex=4) +

  theme(axis.text.y.right = element_text(color = "red", size = 11),
        axis.title.y=element_text(color="darkgrey", size=11,face="bold", margin = margin(t = 0, r = 15, b = 0, l = 0)),
        axis.text.y = element_text(color = "#1C73C2", size = 11),
        axis.title.y.right=element_text(color="darkgrey", size=11,face="bold", margin = margin(t = 0, r = 0, b = 0, l = 15)),
        axis.text.x = element_text(color = "grey20", size = 11))

And lastly
ggarrange(io, yt,labels = c("A", "B"), ncol = 1, nrow = 2, heights = 1.2)

My data w
w <- structure(list(WHO = c(1L, 3L, 2L, 2L, 2L, 3L, 2L, 3L, 1L, 2L,
3L, 3L, 3L, 1L, 2L, 1L, 2L, 3L, 3L, 1L, 2L, 1L, 3L, 1L, 1L, 1L,
1L, 1L, 1L, 2L, 4L, 4L, 1L, 4L, 1L, 2L, 1L, 4L, 1L, 4L, 4L, 4L,
4L, 3L, 3L, 4L, 4L, 4L, 4L, 1L, 4L, 4L, 2L, 1L, 2L, 2L, 4L, 4L,
4L, 2L, 4L, 1L, 4L, 4L, 2L, 4L, 4L, 3L, 4L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 4L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 3L, 2L, 2L, 3L, 3L, 3L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 2L,
3L, 4L, 3L, 4L, 3L), response = c(0L, 1L, 0L, 0L, 0L, 1L, 1L,
1L, 0L, 0L, 0L, 1L, 1L, 0L, 1L, 0L, 1L, 1L, 1L, 0L, 1L, 0L, 1L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 0L, 0L,
0L, 0L, 0L, 0L, 1L, 0L, 0L, 1L, 0L, 1L, 1L, 0L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 0L, 1L, 0L, 0L, 0L,
0L, 0L, 0L, 1L, 0L, 1L, NA, 1L), Death = c(0L, 1L, 1L, 0L, 0L,
1L, 0L, 0L, 0L, 1L, 1L, 1L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 1L,
0L, 1L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 0L, 0L,
0L, 0L, 0L, 0L, 1L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 1L, 0L, 1L, 0L, 1L, 1L,
1L, 1L, 0L, 0L, 1L, 0L, 1L, 0L, 0L, 1L, 0L, 1L, 0L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 0L, 1L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, NA, 1L)), class = "data.frame", row.names = c(NA,
-111L))

A:

You can just create a dummy data frame to obtain a 4th column in your plot A, that you will turn fully transparent :
w2=data.frame(WHO=4,response=1,Death=NA)

and then correct the two first rows of plot A as :
io <- ggplot(data = w[w$response==1,]) +

  geom_bar(mapping = aes(x = WHO), stat = "count", alpha=0.2, colour="#1C73C2", fill="#ECF0F9") + geom_bar(data=w2,mapping = aes(x = WHO),alpha=0,stat = "count") +

  scale_y_continuous(name = "Number of progressions", breaks=yaks, sec.axis = sec_axis(~ . * 1 , name = "Progression rate per 100 person-yrs", breaks=yaks, labels=c("0","40","80","120","160","200","240","280","320","360"))) +
  scale_x_continuous(name="", breaks = c(1,2,3,4), labels =c("\nWHO-I\nn=32","\nWHO-II\nn=23","\nWHO-III\nn=16","\nUnknown\nn=5")) +
  coord_cartesian(ylim=c(0, 18)) +

  geom_point(mapping = aes(x = 1, y = 0.2677376), size=5, alpha=0.7, shape=18, colour="red") +
  geom_point(mapping = aes(x = 2, y = 3.2870709), size=5, shape=18,alpha=0.7, colour="red") +
  geom_point(mapping = aes(x = 3, y = 16.98), size=5, shape=18,alpha=0.7, colour="red") +

  annotate("text", x = c(1,2,3, 4) , y = c(0.2677376+1.3, 3.2870709+1.3, 16.98+1.3, 0.5),  label = c("5.4","65.7","339.6", "0 events"), col="red", fontface=2, cex=4)+

  theme(axis.text.y.right = element_text(color = "red", size = 11),
        axis.title.y=element_text(color="darkgrey", size=11,face="bold", margin = margin(t = 0, r = 15, b = 0, l = 0)),
        axis.text.y = element_text(color = "#1C73C2", size = 11),
        axis.title.y.right=element_text(color="darkgrey", size=11,face="bold", margin = margin(t = 0, r = 0, b = 0, l = 15)),
        axis.text.x = element_text(color = "grey20", size = 11))

finally, just use ggarrange as before :
ggarrange(io, yt,labels = c("A", "B"), ncol = 1, nrow = 2, heights = 1.2)


Q:

BroadCast Variable publish in Spark Program

In the spark - java program I need to read a config file and populate a HashMap , which I need to publish as broadcast variable so that it will be available across all the datanodes .
I need to get the value of this broadcast variable in the CustomInputFormat class which is going to run in the datanodes . How can i specify in my CustomInputFormat class to get value from the specific broadcast variable since the broadcast variable is declared in my driver program ?
I am adding some code to explain it in more :
In this scenario1 I am using it in Driver Program itself ie the variable is used in the same class : Here I  can use Broadcat.value() method
> final Broadcast<String[]> signPrefixes =
> sc.broadcast(loadCallSignTable());
>     JavaPairRDD<String, Integer> countryContactCounts = contactCounts.mapToPair(
>       new PairFunction<Tuple2<String, Integer>, String, Integer> (){
>         public Tuple2<String, Integer> call(Tuple2<String, Integer> callSignCount) {
>           String sign = callSignCount._1();
>           String country = lookupCountry(sign, signPrefixes.value());
>           return new Tuple2(country, callSignCount._2());
>         }}).reduceByKey(new SumInts());

In the scenario 2 I am going to use the Broadcast Variable inside my Custom Input Format class :
Driver Program :
> final JavaSparkContext sc=    new
> JavaSparkContext(sConf.setAppName("ParserSpark").setMaster("yarn-cluster"));
> Broadcast<int[]> broadcastVar = sc.broadcast(new int[] {1, 2, 3});
>
> JavaPairRDD<NullWritable, ArrayList<Record>> baseRDD =
> sc.newAPIHadoopFile(args[2], InputFormat.class, NullWritable.class,
> ArrayList.class, conf);

InputFormat.class
> public class InputFormat extends  FileInputFormat {
>
>   @Override   public RecordReader<NullWritable, ArrayList<Record>>
>   createRecordReader(InputSplit split,            TaskAttemptContext context)
> throws IOException,           InterruptedException{
>       //I want to get the Broadcast Variable Here -- How will I do it
>
>         RecordReader reader = new RecordReader();         reader.initialize(split, context);      return reader;  }   @Override
>   protected boolean isSplitable(JobContext context, Path file) {
>       return false;    } }

A:

I ran into this myself recently. Ended being rather simple actually (after a few hours and then a... a Ha!)
Create a new Configuration, set your vars, and pass it to a slightly different implementation of the newAPIHadoopFile function.
From the driver program (using Scala here):
val myConf = new Configuration();
    myConf.set("var1", v1)
    myConf.set("var2", v2)
    myConf.set("var3", v3)

val yourFile = sc.newAPIHadoopFile("yourFilePath", classOf[MyFileInputFormat],classOf[org.apache.hadoop.io.Text], classOf[org.apache.hadoop.io.DoubleWritable],myConf)

From your InputFormat or InputReader..or wherever you have a context (Java this time)
context.getConfiguration().get("var1");

or maybe
job.getConfiguration().get("var2");


Q:

Appending data from two different api calls inside single list

I have integrated search bar inside action bar.I want suggestion list to display data from two different api calls so i am calling two apis inside onQueryTextChange() but the issue is that first data is displayed from first api call and then the data is replaced by the data of second api call.How can i display data to from two different api calls in the suggestion list of searchview?
@Override
public boolean onQueryTextChange(String s) {

        if(s.length()>=3) {
        String mStart = "";
      int mCount = 10;

            String[] columnNames = {"_id", "name", "userImage", "location"};
            final String[] temp = new String[5];
            final MatrixCursor cursor = new MatrixCursor(columnNames);
            SearchAPI.getSearchFeed(getApplicationContext(), s, mStart, mCount, mSettingsManager.getInstance().getAccessToken(), new APIResponseListener() {
                @Override
                public void onResponse(Object response) {

                    searchResponses= (List<Video>) response;

                    for (Video searchResponse :searchResponses) {
                        temp[0] = Long.toString(id++);
                        temp[1] = searchResponse.getCaption();

                        temp[3] = searchResponse.getLocation();

                        cursor.addRow(temp);
                    }

                    mSearchView.setSuggestionsAdapter(new SearchListAdapter(HomeActivity.this, cursor));

                }

                @Override
                public void onError(VolleyError error) {

                    if (error instanceof NoConnectionError) {

                    }

                }
            });
            SearchAPI.getSearchUser(getApplicationContext(), s,mSettingsManager.getInstance().getAccessToken(), new APIResponseListener() {
                @Override
                public void onResponse(Object response)
                {

                        userResponses = (List<User>) response;

                    for (User searchResponse :userResponses) {
                        temp[0] = Long.toString(id++);
                        temp[1] = searchResponse.getUserName();

                        temp[3] = searchResponse.getEmail();

                        cursor.addRow(temp);
                    }
                    mSearchView.setSuggestionsAdapter(new SearchListAdapter(HomeActivity.this, cursor));

                }

                @Override
                public void onError(VolleyError error)
                {

                    if (error instanceof NoConnectionError) {

                    }

                }
            });
        }

    return true;
}

A:

Try,

Create a model with video and user.
Call your API's and create model objects.
Then add the model object list in to list view


Q:

rspec create() method not working

I am working on an online learning portal like bento. For a user to unlock the next lesson, they must have to review at least one submission from the other user on the assignment of any previous lessons(complete by the current user). Considering this logic, I have a rspec test where I have tested if the page is being redirected to the other user's submission or not? In order to pass the test, I have to create dummy submission. For that, I am using create() method but the redirection to submission page is failing on the test but it works fine on the website. The code responsible for redirection in submission_controller is
def review_submission
 @submission = Submission.where('lesson_id < ?', current_user.submissions.last.assignment.lesson_id.to_i)
                        .shuffle[1]
 if @submission.nil?
  redirect_to @assignment
 else
  redirect_to assignment_submission_path(assignment_id: @assignment.id, id: @submission.id)
 end
end

The code of the test is
it "redirects to submission path" do
    admin_user = create(:admin_user)
    sign_in admin_user
    user = create(:user)
    sign_in user
    assignment = create(:assignment, admin_user_id: admin_user.id)
    #I was creating dummy submissions data using rspec create method.
    submission = create(:submission, lesson_id: 1)
    post :create, params: { submission: attributes_for(:submission, user_id: user.id), assignment_id: assignment.id}

    expect(response).to redirect_to assignment_submission_path( assignment_id: assignment.id, id: Submission.last.id)
  end

Dummy data is coming from FactoryGirl
factory :submission do
  user_id 1
  assignment_id 1
  lesson_id 2
  content "this is the submission of my assignment"
  factory :invalid_submission do
    content ""
  end
end

Any suggestions are highly appreciated. Thank you in advance.

A:

It looks like @submission is nil, so it's redirecting you to the Attachments#show page instead of the Submissions#show page. You're setting it like:
@submission = Submission.where('lesson_id < ?', current_user.submissions.last.assignment.lesson_id.to_i).shuffle[1]

It's trying to find the Submission based on current_user.submissions. Your Factory is just making the submission like:
submission = create(:submission, lesson_id: 1)

That defaults the user_id to be 1, which probably isn't the ID of your signed in user (since you create the admin user above it). Try passing in the user_id to your FactoryGirl's creation of the Submission. May also want to pass in the assignment_id too actually, so the Submission will correctly belong to the Assignment.
submission = create(:submission, lesson_id: 1, user_id: user.id, assignment_id: assignment.id)

Then the Submission should be assigned to your User, and hopefully the Controller will find it and your test will pass.


Q:

Sieve of Eratosthenes

I read up on the sieve of Eratosthenes while solving a question on Project Euler. I'm sure you guys know which question im talking about.
So here's the thing. My code manages to show all the primes under 1 million correctly.
However when i try the same implementation for 2 million it's giving me a segmentation fault...
I have a certain idea of why the error is coming but don't know how to correct it...
Here's the code for primes under 1 million.
#include<stdio.h>
int main(void)
{
   int i,k=2;
   int j;
   int n=1000000;
   int prime[2000000]={};
   for(i=0;i<n;i++) // initializes the prime number array
   {
      prime[i]=i;
   }
   for(i=2;i<n;i++) // Implementation of the Sieve
   {
      if(prime[i]!=0)
      {
         for(j=2;j<n;j++)
         {
            {
               prime[j*prime[i]]=0;
               if(prime[i]*j>n)
                  break;
            }
         }
      }
   }
   for(i=0;i<n;i++) // Prints the prime numbers
      if(prime[i]!=0)
      {
         printf("%d\n"prime[i]);
      }
      return(0);
   }
}

A:

You're allocating a huge array in stack:
int prime[2000000]={};

Four bytes times two million equals eight megabytes, which is often the maximum stack size. Allocating more than that results in segmentation fault.
You should allocate the array in heap, instead:
int *prime;
prime = malloc(2000000 * sizeof(int));
if(!prime) {
    /* not enough memory */
}
/* ... use prime ... */
free(prime);


Q:

how to insert values into middle of array

So I have an array something like this [1,2,3,4,5,6,7,8,9] the max for this array is 15 values. What I want to do is insert an int if i call a numbers index. So say I call 5 which is index 4 from there everything shifts over and the new value is inserted [,1,2,3,4,0,5,6,7,8,9] How would I go about this?
I tried this but i can't seem to get it right it overrides the value.
int xxx;
        cin >> num;
        if (num >= 0 && num <= 15) {
            for (int i = num; i < MAX; i++) {
                values[i] = values[i+1];
                cout << values[i+1] << endl;
            }
            viewVal(values, position);
            cout << endl << endl;
        }

A:

The problem is that values[i] = values[i+1]; shifts a value one step to the left (index 4 now has the value of index 6), but you want to shift all values one step to the right. Thus, you have to reverse the assignment.
This creates the problem that once you have moved a value to the right, the previous value on the position to the right is lost. To prevent this, you can start from the back of the array.


Q:

Convert an object with key values to an array of objects with said key name and values

I'm getting my head stuck in a twist with this one...
I'm trying to convert my req.query I get in Express which is an object to make an array of objects so I can pass these through to SQL Server as inputs for stored procedures.
This is the data I have -
{ param1: 'testing123', param2: 'poooool', param300: 'nnnvncn' }

I want it to appear like
[{param1: 'testing123'},{param2: 'poooool'},{param300: 'nnnvncn'}]

Any idea how I would get to the desired array above?
EDIT: This is the code I went for in the end running in node.js
app.get('/:client/storedproc/:sp', function(req, resp){
    var sp = req.params.sp;
    var obj = req.query;
    var test = function(){ return Object.keys(obj).map(k => ({ [k]: obj[k] }));}
    var arr = test();
    console.log(arr)
});

A:

You can use Object.keys for this. Given the object from your first snippet o:
return Object.keys(o).map(function(k) {
    var x = {};
    x[k] = o[k];
    return x;
});

Just for fun, here's how terse it is with ES2015:
return Object.keys(o).map(k => ({ [k]: o[k] }));


Q:

Vagrant Shell Executes Successfully as User but it doesn't 'stick'

This code seems to work fine on 'vagrant up', but when I 'vagrant ssh' into the vm I have to redo everything in the "#doesn't take" block, even though I saw the successful output while the scripts were being run.
In Vagrantfile:
Vagrant.configure(2) do |config|

  config.vm.box = "ubuntu/trusty64"

  config.vm.network "forwarded_port", guest: 9000, host: 9000, auto_correct: true
  config.ssh.forward_agent = true

  config.vm.synced_folder ".", "/home/vagrant/www", create: true, group: "vagrant", owner: "vagrant"

  config.vm.provision :shell, path: "vagrant/rootScript.sh"
  config.vm.provision :shell, privileged: false, path: "vagrant/userScript.sh"
end

rootScript.sh:
sudo apt-get update
sudo apt-get install -y git
sudo apt-get install python-software-properties python g++ make

sudo apt-get update

userScript.sh:
cd www
touch test.txt    # this is successfully created in the correct folder

whoami            # 'vagrant'
echo "${PWD}"     # 'home/vagrant/www'

# # Installing nvm
wget -qO- https://raw.github.com/creationix/nvm/master/install.sh | sh

# # This enables NVM without a logout/login
export NVM_DIR="/home/vagrant/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"  # This loads nvm

# Install a node and alias
nvm install 0.10.33

# ************** doesn't take **************
nvm use 0.10.33
npm install -g npm@latest
npm install -g bower grunt-cli
npm install
bower install
# *******************************************

whoami                   # still 'vagrant'
echo "${PWD}"            # still 'home/vagrant/www'

Why do these commands need to be re-run in ssh?  And is there anything I can do to make them 'take' while running as a script?  Driving me nuts.  Thanks for the help.

UPDATE -- just discovered that the npm and bower commands DID take -- only command that does not seem to be working in the script is 'nvm use 0.10.33'

A:

nvm use only sets the node version for that shell session.
To make it work for any new shells you should instead use nvm alias default 0.10.33. This is mentioned briefly in the nvm README:

To set a default Node version to be used in any new shell, use the
  alias 'default':
nvm alias default stable

This will only work on new shells though so if you want to perform any commands at the same time you will need to use nvm use 0.10.33 as well.
In your case you probably just want to add the nvm alias default 0.10.33 command right at the end of your node configuration in userScript.sh.


Q:

How to Implement $child method in new AngularFire v0.8.0?

A user is logged in to the website and tries to create a post. Whenever a new post is created, this post gets associated with the user who created the post.
Referring to a thinkster.io Tutorial, which uses older API of AngularFire.
When using AngularFire API v0.8.0, this line of code which adds the post breaks:
user.$child('posts').$child(postId).$set(postId);

The Post Factory (post.js) with the method for creating post is:
app.factory('Post',
function ($firebase, FIREBASE_URL, User) {
  var ref = new Firebase(FIREBASE_URL + 'posts');

  var posts = $firebase(ref).$asArray();

  var Post = {
    all: posts,
                                       //Starting of create function
    create: function (post) {
      if (User.signedIn()) {
        var user = User.getCurrent();   //Gets the current logged in user
        post.owner = user.username;

        return posts.$add(post).then(function (ref) {
          var postId = ref.name();

          user.$child('posts').$child(postId).$set(postId);

          //user.$getRecord('posts').$getRecord(postId).$set(postId);

          return postId;
        });
      }
    },
                                       //End of create function

Changelog for AngularFire states that

$child() no longer exists. The data already exists in the parent object and creating additional synchronized children is not efficient and discouraged. Use data transformations, flatten your data, or drop down to the Firebase SDK and use its child() method.

I am confused as to how to change the code to work with the update in the API.
After Edit
This is the getCurrent method:
getCurrent: function(){ // retrieves current user
  return $rootScope.currentUser;
},

Which belongs to user.js Factory:
'use strict';

app.factory('User', function ($firebase, FIREBASE_URL, Auth, $rootScope) {
 var ref = new Firebase(FIREBASE_URL + 'users');

 var users = $firebase(ref);
 var usersdiv = $firebase(ref).$asArray();

 var User = {

    create: function (authUser, username) {
      users[username] = {
        md5_hash: authUser.md5_hash,
        username: username
      };
      users.$update(username, {
          md5_hash: authUser.md5_hash,
          username: username
      }).then(function (dataRef) {
          dataRef.setPriority(authUser.uid);
          setCurrentUser(username);
      });
    }, // end of create method

    findByUsername: function(username){
      if(username){
        return usersdiv.$getRecord(username);
      }
    },

    getCurrent: function(){ // retrieves current user
      return $rootScope.currentUser;
    },

    signedIn: function(){ //checks if user is signed in
      return $rootScope.currentUser !== undefined;
    }

  }; // end of User

  // so that we can pull info about user when logged in
  function setCurrentUser (username){
    $rootScope.currentUser = User.findByUsername(username);
  }

  //for logins and refreshes
  $rootScope.$on('$firebaseSimpleLogin:login', function(e, authUser){

      var queryRef = ref.startAt(authUser.uid).endAt(authUser.uid);

      var queryArray = $firebase(queryRef).$asArray();

      queryArray.$loaded().then(function() {
        setCurrentUser(queryArray.$keyAt(0));
      });
  });

  //logout
  $rootScope.$on('$firebaseSimpleLogin:logout', function(){
    delete $rootScope.currentUser;
  });
  return User;
});

A:

Correct Answer is:
'use strict';

app.factory('Post',
    function ($firebase, FIREBASE_URL, User) {
      var postsref = new Firebase(FIREBASE_URL + 'posts');
      var usersref = new Firebase(FIREBASE_URL + 'users');
      var posts = $firebase(postsref).$asArray();

      var Post = {
        all: posts,

        create: function (post) {
          if (User.signedIn()) {
            var user = User.getCurrent();
            post.owner = user.username;
            return posts.$add(post).then(function (ref) {
              var postId = ref.name();
              //a child in user forge should be made with its key as postID
              usersref.child(post.owner).child('posts').child(postId).set(postId);
              return postId;
            });
          }
        },

        find: function (postId) {
          return $firebase(postsref.child(postId)).$asObject();
        },

        delete: function (postId) {
          if (User.signedIn()) {
            var postToDel = Post.find(postId);
            postToDel.$loaded().then(function(){
                var p = posts[postToDel.$id];
                posts.$remove(postId).then(function(){
                    $firebase(usersref.child(p.owner).child('posts')).$remove(p.$id);
                });
            });
          }
        },

Thus, child can be used at Firebase SDK Level.
Example:
var ref = new Firebase(FIREBASE_URL);
var userArray = $firebase(ref.child('user')).$asArray();
var userObject = $firebase(ref.child('user')).$asObject();