text:
Q: Algebra story problem about boat ride along river and in still water
On a sunny summer day, you are taking the scenic boat  ride  from  Stein  am  Rhein,  Switzerland,  to Schaffhausen, down the Rhein River. This nonstop trip takes 40 minutes, but the return trip to Stein, upstream, will take a full hour. Back in Stein, you decide to stay on the boat and continue on to Constance, Germany,
  now traveling on the still waters of Lake Constance. How long will this nonstop trip from Stein to Constance take? You may assume that the boat is traveling at a
  constant speed relative to the water throughout and that the Rhein River flows at a constant speed between Stein and Schaffhausen. The traveling distance from Stein to
  Schaffhausen is the same as from Stein to Constance.

I'm not sure how to set up this problem, any help would be great!

A: There are three legs of the journey: (1) Stein to Schaffhausen, (2) Schaffhausen to Stein, and (3) Stein to Constance.
Let
$$\newcommand{\sft}[1]{\mathsf{\text{#1}}}
\begin{align}
s&=\sft{speed of boat in still water (in meters/minute)}\\\\\\
r&=\sft{speed of river (in meters/minute)}\\\\\\
d&=\sft{distance from Stein to Schaffhausen (in meters)}\\
&=\sft{distance from Schaffhausen to Stein (in meters)}\\
&=\sft{distance from Stein to Constance (in meters)}\\\\\\
t&=\sft{time it takes to travel from Stein to Constance (in minutes)}
\end{align}$$
For each leg of the journey, we have that
$$\sft{distance}=\sft{speed}\times\sft{time}$$
When the boat is traveling downstream, the river speeds up the boat, and likewise when the boat is traveling upstrem, the river slows down the boat. In still water the boat just has speed $s$.
For leg (1),
$$d=(s+r)\times (40\sft{ min})$$
For leg (2),
$$d=(s-r)\times (60\sft{ min})$$
For leg (3),
$$d=s\times t.$$
Use the first two equations to solve for $s$ in terms of $d$, then plug into the third equation to find $t$.


text:
Q: How to customize container width I would like to customize the width of the class container in bootstrap.
The width I would like to obtain is 670px.
I customized the bootstrap.css file (http://getbootstrap.com/customize/) in order to obtain my own version.
The code below shows how container has been customized.
From 749px the width does not change as expected.
Do you know how to fix it?
@media (min-width: 768px) {
.container {
width: 670px;
background: green;
}
 }

@media (min-width: 992px) {
.container {
 width: 670px;
}
}
@media (min-width: 1200px) {
.container {
 width: 670px;
}
 }

A: Add '!important' after the value, like this code:
     @media (min-width: 768px) {
    .container {
    width: 670px!important;
    background: green;
    }
     }
@media (min-width: 992px) {
.container {
 width: 670px!important;
}
}
@media (min-width: 1200px) {
.container {
 width: 670px!important;
}
 }

redpajama_set_name: RedPajamaStackExchange


text:
Q: When should I use IEnumerator for looping in c#? I was wondering if there are any times where it's advantageous to use an IEnumerator over a foreach loop for iterating through a collection? For example, is there any time where it would be better to use either of the following code samples over the other?
IEnumerator<MyClass> classesEnum = myClasses.GetEnumerator();
while(classesEnum.MoveNext())
    Console.WriteLine(classesEnum.Current);

instead of
foreach (var class in myClasses)
    Console.WriteLine(class);

A: I used it sometimes when the first iteration do something different from others.
For example, if you want to print members to console and separate results by line, you can write.
using (IEnumerator<MyClass> classesEnum = myClasses.GetEnumerator()) {
    if (classEnum.MoveNext())
        Console.WriteLine(classesEnum.Current);
    while (classesEnum.MoveNext()) {
        Console.WriteLine("-----------------");
        Console.WriteLine(classesEnum.Current);
    }
}

Then the result is
myClass 1
-----------------
myClass 2
-----------------
myClass 3

And another situation is when I iterate 2 enumerators together.
using (IEnumerator<MyClass> classesEnum = myClasses.GetEnumerator()) {
    using (IEnumerator<MyClass> classesEnum2 = myClasses2.GetEnumerator()) {
        while (classesEnum.MoveNext() && classEnum2.MoveNext())
            Console.WriteLine("{0}, {1}", classesEnum.Current, classesEnum2.Current);
    }
}

result
myClass 1, myClass A
myClass 2, myClass B
myClass 3, myClass C

Using enumerator allows you to do more flexible on your iteration. But in most case, you can use foreach

A: First, note that one big difference in your example (between foreach and GetEnumerator) is that foreach guarantees to call Dispose() on the iterator if the iterator is IDisposable. This is important for many iterators (which might be consuming an external data feed, for example).
Actually, there are cases where foreach isn't as helpful as we'd like.
First, there is the "first item" case discussed here (foreach  / detecting first iteration).
But more; if you try writing the missing Zip method for stitching two enumerable sequences together (or the SequenceEqual method), you find that you can' use foreach on both sequences, since that would perform a cross-join. You need to use the iterator directly for one of them:
static IEnumerable<T> Zip<T>(this IEnumerable<T> left,
    IEnumerable<T> right)
{
    using (var iter = right.GetEnumerator())
    {
        // consume everything in the first sequence
        foreach (var item in left)
        {
            yield return item;

            // and add an item from the second sequnce each time (if we can)
            if (iter.MoveNext())
            {
                yield return iter.Current;
            }
        }
        // any remaining items in the second sequence
        while (iter.MoveNext())
        {
            yield return iter.Current;
        }
    }
}

static bool SequenceEqual<T>(this IEnumerable<T> left,
    IEnumerable<T> right)
{
    var comparer = EqualityComparer<T>.Default;

    using (var iter = right.GetEnumerator())
    {
        foreach (var item in left)
        {
            if (!iter.MoveNext()) return false; // first is longer
            if (!comparer.Equals(item, iter.Current))
                return false; // item different
        }
        if (iter.MoveNext()) return false; // second is longer
    }
    return true; // same length, all equal
}

A: According to the C# language spec:

A foreach statement of the form

foreach (V v in x) embedded-statement

is then expanded to:

{
    E e = ((C)(x)).GetEnumerator();
    try {
            V v;
            while (e.MoveNext()) {
                    v = (V)(T)e.Current;
                    embedded-statement
            }
    }
    finally {
            ... // Dispose e
    }
}

The essense of your two examples are the same, but there are some important differences, most notably the try/finally.

A: In C#, foreach is doing exactly the same thing as the IEnumerator code that you posted above. The foreach construct is provided to make it easier for the programmer. I believe that the IL generated in both cases is the same/similar.


text:
Q: Solving the wave equation in 3 dimensions
I've been set the question above, and I'm having some problems on where to start. I haven't come across PDE's in more that two dimensions before so I'm quite confused.
I started by trying to use d'Alembert's formula for this given v however first of all I thought that d'Alemberts formula only worked in two dimensions furthermore, say we could apply d'Alembert in $\mathbb{R}^3$ then determining u from our definition of it and v(x,t;s) = $\frac{1}{2c}\int^{x+t}_{x-t}$f(y,s)dy seems unfindable. I also tried determining u$_{tt}$ and u$_{xx}$ immediately however I couldn't find a viable way to do so with what I had been told in the question.
I won't be marked on this question however I would still prefer to not be given the answer to it. These equations I've been told will be relevant in my finals hence I would rather someone explain where to start on this question and I will try to complete the rest myself.


text:
Q: Variance of constant function and dirac delta I have seen claims saying constant function has 'null variance' (i.e., $0$). I find this conflicting with the fact that dirac delta also has variance of $0$ (since it is the extreme case of a
very concentrated Gaussian), since they are more of 2 species at the opposite ends of a spectrum. I'm thinking maybe the problem lies in the definition of the variance of a function and and distribution, but not very sure.

A: I think you are confusing a constant random variable with a constant probability density function.

*

*If $X = x_0$, then it means that the random variable $X$ can take one single value named $x_0$, hence $X\sim\mathcal{Delta}(x_0)$ and its PDF is given by $f_X(x) = \delta(x-x_0)$, which implies a null variance. In fact, it's the way to describe a deterministic (i.e. non-random) variable in the probabilistic language.

*The opposite end of spectrum, as you said, corresponds to the case where all events are of equal probability, hence a constant probability density function $f_X(x) = c$; thus, the considered random variable has to be uniformly distributed, i.e. $X\sim\mathcal{Unif}([0,c])$ for instance, and it has a non-zero variance.


text:
Q: writing a class that iterates over a hash of hashes I'm having trouble writing a class to iterate over a hash of hashes or nested hash, here is an example of the hash I have.
 hash = {a => {:number => 1, :color => "blue", :language => english} b => {:number => 2, :color => "red", :language => english}

I want to write class methods that will return the number of each parent

A: All you need is a method, not a class.  Here are a couple of approaches you could use.
def numbers(h)
  Hash[h.map { |k,v| [k, v[:number]] }]
end

h = { :a => {:number => 1, :color => "blue", :language => "english" },
      :b => {:number => 2, :color => "red",  :language => "english" } }

numbers(h)
  #=> {:a=>1, :b=>2}

or with Ruby 2.1:
def numbers(h)
  h.map { |k,v| [k, v[:number]] }.to_h
end

Another way that returns the same hash:
def numbers(h)
  h.each_with_object({}) { |(k,v),g| g[k] = v[:number] }
end


text:
Q: Cats on a cliff puzzle On a cliff of length 110m at a height 240m, 10 cats are positioned facing either the left or right direction arbitrarily. The length of the cliff is large compared to the size of each cat. Initially, all cats start running
in the direction they are facing at a speed 12m/sec. Whenever any cat collides with another cat, both the cats instantly reverse their respective directions and continue running. When a cat reaches the ends of
the cliff, it falls down.on average, how much time does it take for all 10 cats to fall off the cliff?

A: Hint: observe that it would take exactly as long if the cats passed by each other without changing directions.

A: When placing the cats randomly on the cliff, the randomness balances out to as if you had placed them all in the exact center. Regardless of which direction they face, all of the cats would fall of in $\dfrac{110m}{14m/s} \approx 7.857... $ seconds. I also don't really know what the height of the cliff has to do with the rest of the problem.


text:
Q: When running git svn fetch --all, what does the --all option do? I've been researching how to use Git with an SVN repo, and there are many references that use the following command:
git svn fetch --all

However, I haven't found any reference that definitely tells me what --all does differently to git svn fetch, and I haven't noticed any difference when running git svn fetch with or without the --all option.  Is there any difference?
I am using Git 1.9.5.

A: The --all flag is mentioned but doesn't appear to be documented in the git-svn man page. However, running
git log --grep="\-\-all" -- git-svn.perl

in a clone of the Git project's repo lists only two commits, the older of which describes --all:

By default, fetch will fetch everything from its default
[svn-remote]; if fetch [--all|-a] is specified, then it will
fetch from all svn remotes.

The most recent of those two commits indicates that the short version (-a) was later dropped, and that --fetch-all was introduced as a synonym of --all:

Note that the '-a' switch (short for --fetch-all/--all) has been
removed as it conflicts with the non-svn 'git fetch'

(Further inspection reveals that those two commits their way into release v1.5.1.1, way before the version of Git you're using: v1.9.5.)


text:
Q: DataFrame object Statmodels I'm trying to create a linear regression with statsmodels. I've looked at a few articles and I think I'm almost there. I'd rather not have to type in each rows values as I'll have thousands of values (https://datatofish.com/statsmodels-linear-regression/) this article says to do that. I'm trying to pull from a csv file and use that instead. Here's my code but I'm getting the following error: df = DataFrame(DataFrame.columns) Type Error: 'DataFrame' object is not callable.
Here's the entire code. Basically want to run this regression and get a summary similar to what I'd get in R or Excel for all variables. I've input 2 for testing but I'll have about 20 variables.
import pandas as pd
import statsmodels.api as sm

# Import the data
DataFrame = pd.read_csv("NBA.csv")

df = DataFrame(DataFrame.columns)

X = df[['A_OFFRTG','H_OFFRTG']]
Y = df['Margin']

X = sm.add_constant(X) # adding a constant

model = sm.OLS(Y, X).fit()
predictions = model.predict(X)

print_model = model.summary()
print(print_model)

A: So to be honest I am myself not sure what exactly are you doing with that line.
You can just change two lines and it should work all fine. Try this code:
import pandas as pd
import statsmodels.api as sm

# Import the data
df = pd.read_csv("NBA.csv")

X = df[['A_OFFRTG','H_OFFRTG']]
Y = df['Margin']

X = sm.add_constant(X) # adding a constant

model = sm.OLS(Y, X).fit()
predictions = model.predict(X)

print_model = model.summary()
print(print_model)

I hope this works for you Ben.


text:
Q: Most appropriate way to construct overlapping dummies What would be the most appropriate way to construct dummies with theoretical overlap?
I'm doing a meta-regression of studies looking at the effect of certain interventions on X. Some studies use only women, some only men, and some a mixed population. I want to control for the fact that there can be a difference.
Is there anything inappropriate about the following construction?
Effect size     Men     Women    Mixed
0.35            1       0        0
0.47            0       0        1
0.22            1       0        0
0.98            0       1        0

The categories are mutually exclusive in coding, although not in theory (mixed has some men, some women), making analysis messy. However, I think it is important to control for study characteristics. I have a variety of considerations and reservations when I look at this, but would love additional input.

A: You could probably do something like the following:
 Effect size     Men     Women    Men*Women

    0.35            1       0        0

    0.47            1       1        1

    0.22            1       0        0

    0.98            0       1        0

where Men*Women is an interaction term.


text:
Q: Проблема с MySQL C# Почему появляется исключение при изменении пароля, но пароль в базе данных меняется.
Код:
private void button1_Click(object sender, EventArgs e)
{
    string connect = "server=localhost;username=root;database=users;password=;";
    MySqlConnection connection = new MySqlConnection(connect);
    connection.Open();
    string zapros = "SELECT email FROM users.data WHERE email='" + textBox1.Text + "'";
    string updatepassword = "UPDATE `users`.`data` SET `password`='1122334455' WHERE `email`='" + textBox1.Text + "';";
    MySqlCommand command = new MySqlCommand(zapros, connection);
    MySqlCommand command1 = new MySqlCommand(updatepassword, connection);
    try
    {
        string resul = command.ExecuteScalar().ToString();
        string updpass = command1.ExecuteScalar().ToString();

    }
    catch (Exception ex)
    {
        MessageBox.Show("Такого нет!");
    }
}

resul отвечает за проверку пользователя в базе данных.
updpass отвечает за смену пароля, если пользователь присутствует.

A: Ошибка возникает из-за того, что вы пытаетесь получить результат и выполнить update-запрос с помощью ExecuteScalar, но при этом запрос на обновление данных не возвращает ничего. Для вставки, удаления и обновления данных исползуйте методв ExecuteNonQuery:
command1.ExecuteNonQuery()

В случае ошибки выполнения запроса будет выброшено соответствующее исключение класса MySqlException (или, возможно, его наследника).
В данном же случае, вы отсутствующий результат пытаетесь привести к строке, используя toString, и получаете исключение, в виду отсутствия самого результата. А поскольку отлавливаете вы самый верхний класс исключений Exception и не выводите сообщение об ошибке, возникают сложности с отладкой кода.
В дополнение отмечу, что подстановка параметров напрямую в запрос - плохая практика. Используете параметры для передачи значений в запрос.
string updatepassword = "UPDATE `users`.`data` SET `password`='1122334455' WHERE `email`= @email;";
MySqlCommand command1 = new MySqlCommand(updatepassword, connection);
command1.Parameters.AddWithValue("@email", textBox1.Text);
try {
     command1.ExecuteNonQuery();
}
catch(MySqlException ex){
    // ошибка работы с БД
}
catch(Exception ex){
    //прочие возможные ошибки
}

зы: когда вы говорите, что выбрасывается исключение, но при этом пароль меняется, это означает единственное - что ошибка возникает уже после выполнения запроса. А после запроса у вас имеется только вызов .toString, где наиболее вероятно, что результат запроса null


text:
Q: Best Visualization Platform For Sharing With External Users I'm interested in creating some dashboards for clients. They will contain some sensitive data, so I plan on putting them behind an authentication wall (ASP.net, most likely). The dashboard will allow for filtering and sorting, but no data entry or deletion. Each dashboard will be fed by an Excel file.
My company suggested using Microsoft Power BI, but BI for web doesn't allow for private/confidential data, and any other method of sharing would require the client to have a Power BI license.
I also considered Tableau but ran into similar issues.
So broadly speaking, what's the best platform for creating web-based visualizations that can be embedded into a page?
Thanks

A: Power BI gives you - Azure AD authentication ,
                   - row level security to data
So Power BI will be better option


text:
Q: permanent ldap authenticated session I am trying to build a simple web based directory navigation/administration application.
Application requirements:

*

*An Active Directory (or another directory service) domain user access
this web application and log in with the same domain user/password
credentials.

*Then the user can navigate the directory tree, create/edit entries,
edit an entry's attribute, etc..

I'm using perl Net::LDAP for the ldap operations, as in:
#!/usr/bin/perl -wT

use Net::LDAP;
use CGI qw(:standard);
use CGI::Carp qw(warningsToBrowser fatalsToBrowser);

my $ssl = 1;
my $srv = '192.168.56.110';
my $uri = $ssl ? 'ldaps://' : 'ldap://';

my $c = Net::LDAP->new($uri . $srv) or
    die "Unable to connect to server: $@\n";

# !!! This is a temporary workaround !!!
my $binddn = "cn=Administrator,cn=users,dc=example,dc=com";
my $passwd = "password";

my $mesg = $c->bind($binddn, password => $passwd);
die 'Unable to bind: ' . $mesg->error . "\n" if $mesg->code;

# DN to be deleted
my $dn = param('DN');

$mesg = $c->delete($dn);
die 'Error in delete: '. $mesg->error() ."\n" if $mesg->code();

$c->unbind;

I can call this cgi script with a HTML form, as in:
<form action="/cgi-bin/del.cgi" method="post">

Peter Parker
<input type="radio" name="DN"
    value="cn=peter parker,cn=users,dc=example,dc=com">

Clark Kent
<input type="radio" name="DN"
    value="cn=clark kent,cn=users,dc=example,dc=com">

<input type="submit" value="Delete User">
</form>

The problem with this code is that the ldap operations are using administrative credentials, not the credentials of the user running the web application. I'm using this workaround because I can't ask the user for his/her credentials every time.. and I don't know how to keep a user permanently authenticated.
My web application authenticate the user via ldap, asking he's credentials and issuing a bind request to the directory service, as in:
...
# read user supplied credentials
my $user_id = param('user_id');
my $password = param('password');

# now find the DN of user_id in directory
my $ssl = 1;
my $srv = '192.168.56.110';
my $uri = $ssl ? 'ldaps://' : 'ldap://';

my $c = Net::LDAP->new($uri . $srv) or
    die "Unable to connect to server: $@";

# admin credentials are needed here to find the user DN
my $rootdn = "cn=Administrator,cn=users,dc=example,dc=com";
my $rootpw = "secret";

my $mesg = $c->bind($rootdn, password => $rootpw);
die "Unable to bind: ". $mesg->error if $mesg->code;

$mesg = $c->search(
    base    => 'dc=example,dc=com',
    scope   => 'sub',
    filter  => "(&(objectClass=user)(sAMAccountName=$user_id))",
    attrs   => ['sAMAccountName'],
);
die "Bad search: ". $mesg->error() if $mesg->code();

my ($entry) = $mesg->entries;
die "User not found: $user_id\n" unless $entry;

my $dn = $entry->dn;

# User DN found.. now check the credentials
$mesg = $c->bind($dn, password => $password);
die "Unable to bind: ". $mesg->error if $mesg->code;

$c->unbind();

# credentials validated!
print header, start_html('Welcome!'), h1('Hello, YOU!'), end_html;

After that, a cookie is sent to the user browser initiating a web session.
I could keep the user credentials in a database and then pass it to del.cgi (and other similar script) any time I needed.. but I don't think it's good security practice.
What can I do to keep a permanent ldap authenticated session as long as the web session is active?

A: There is no session. When an LDAP client connects to the directory server, the connection is unauthenticated. The bind request, should it be successful, establishes the authorization state of the connection. The connection remains in that authorization state until the next bind request, client disconnect, or server disconnect. Depending on the local setup, it may be possible to keep the connection open indefinitely with keep-alives or something similar. or the client can transmit another bind request periodically. Modern, professional-quality directory servers support disconnecting idle clients, or disconnecting clients after a certain period of time has passed, or after a set number of LDAP operations have been transmitted. Note that network administrators may disallow permanent connections for reasons of their own.

*

*LDAP clients should check for response controls after the LDAP requests. Failure to check for response controls will result in the client missing important information from the server.

*LDAP clients must be aware that the server can send an unsolicited notification in the form of an extended result. Failure to be handle the unsolicited notification can result in a badly behaved LDAP client. Most notifications are disconnect notifications, meaning the server is disconnecting the client for whatever reason.

Please see "LDAP: programming Practices" for more information.
Out of curiosity, why code such a thing? Apache Directory Studio is an excellent LDAP client.


text:
Q: Cors error when accessing EBAY User Consent API I am attempting to follow this EBAY User Consent API article https://developer.ebay.com/api-docs/static/oauth-consent-request.html
but I am getting a CORS error "blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource."
I've read numerous Cors posts here this one being a good one: XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header but none of these solutions seem to work.
a pointer in the right direction would be great.
        $(document).on('click','.ebay_access', async function(event) {

            let scopes = encodeURIComponent("https://api.ebay.com/oauth/api_scope https://api.ebay.com/oauth/api_scope/sell.marketing.readonly https://api.ebay.com/oauth/api_scope/sell.marketing https://api.ebay.com/oauth/api_scope/sell.inventory.readonly https://api.ebay.com/oauth/api_scope/sell.inventory https://api.ebay.com/oauth/api_scope/sell.account.readonly https://api.ebay.com/oauth/api_scope/sell.account https://api.ebay.com/oauth/api_scope/sell.fulfillment.readonly https://api.ebay.com/oauth/api_scope/sell.fulfillment https://api.ebay.com/oauth/api_scope/sell.analytics.readonly https://api.ebay.com/oauth/api_scope/sell.finances https://api.ebay.com/oauth/api_scope/sell.payment.dispute https://api.ebay.com/oauth/api_scope/commerce.identity.readonly https://api.ebay.com/oauth/api_scope/commerce.notification.subscription https://api.ebay.com/oauth/api_scope/commerce.notification.subscription.readonly");
            let clientId = "{{env('EBAY_APIKEY')}}";
            let clientSecret = "{{env('EBAY_API_CERT_NAME')}}";
            let oAuthCredentials64 = btoa(clientId + ":" + clientSecret);
            let endpoint = 'https://api.ebay.com/identity/v1/oauth2/token';

            try{
                let response = await fetch(endpoint,
                    {
                        method: "POST",
                        headers:
                            {
                                "Content-Type": "application/x-www-form-urlencoded",
                                "Authorization": `Basic ${oAuthCredentials64}`
                            },
                        body:
                            "grant_type=client_credentials&scope=" + scopes
                    }

                );
                let responseJson = await response.json();
                console.log("CLIENT ACCESS TOKEN", responseJson);

            } catch(err){
                console.log("error: ", err);
            };

        }); //end function

A: There are multiple issues here.

*

*In general, if the URL - domain on your browser is not same as the ajax call browser is making then you get this error.

*Seems that you have copied the code which was meant for server side execution. You should NEVER expose your credentials to client side. Anyone can use your steal your credentials.

*The github link you provided as reference is for server side nodejs application which is running as an app and not under browser.

A: The request you are making seems to be an authentication request, or "consent request", as eBay call it. This must be made to the authorization endpoint (probably https://api.ebay.com/identity/v1/oauth2/authorize). But you make it to the token endpoint (https://api.ebay.com/identity/v1/oauth2/token), as if it were a token request. But the token request is only the second step ("Exchanging the authorization code for a User access token").
Moreover, neither the authentication request nor the token request are CORS requests:

*

*The authentication request must happen in a visible browsing context, as explained  here. The user can only consent if they see what is going on.

*The token request is not made by the browser, because this would expose the secret (as pointed out in Jags's answer). It must be made by your server.

In other words: No CORS should be involved at all. The eBay API article explains this correctly.


text:
Q: How to get the via url (or site name) on a wordpress network's home page? Hy everyone!
I listed the all network posts on my multisite to my network-home's homepage with "WDS Multisite Aggregate" plugin. This works fine, but now I want to get the author/publisher subsite's domains above each posts, similar to: by Author_name, just in this case so: via subsite_url.
So now, if Author1 publishing on his own site, example [subsite1.network.com] a new post, this post immediately appears on the homepage of [network.com], and appear above of the post content the Author's username, thus: by Author1.
Besides this, the all "shared" post's link-title control to the publisher site, so example, when on the homepage of [network.com] a new post appears, this post title shows to [subsite.network.com/current-post-idx] when I use this the_title( sprintf( '
', esc_url( get_permalink() ) ), '
' ); and if I open [network.com/current-post-idx], this redirect to [subsite.network.com/current-post-idx].
So, get_permalink() shows to the original post where the author publishing that.
Now I would like that similar to this appear above of the post content the Author's site, where can he publishing the current post, thus: via [subsite1.network.com].
So, if get_permalink() = [subsite1.network.com/current-post-idx], in this same case how can I get simply [subsite1.network.com]?
... get_home_url() and get_site_url() obviously shows to [network.com] because that particular homepage it belongs this.
Sorry, this is my first question here, ago this I find everything on the subject on the internet, but about this I did't find anything anywhere.

A: Instead of get_site_url(), use get_home_url(). This will return the URL of the site you're in.
You can also get the URL of a different site in your Multisite network by passing that site's blog_id (ie, $url = get_home_url( 2 );).
(I suspect that get_site_url() is a holdover from the early days of Multisite; when Multisite was originally moved into WordPress, you created a site of blogs. The terminology has evolved, so that we now think of a network of sites, but some of the functions still reflect the old terms.)

A: The ultimate answer here, if you have a subdomain based multisite
(This works in every case with subdomain based multisite, if your canonical URLs are okay -> so your permalinks shows to the parent posts...).
Only replace the yournetworkdomain.com to your network domain:
$posturl = esc_url( get_permalink() );
$find = array( 'http://', 'https://' );
$replace = '';
$purepostaddress = str_replace( $find, $replace, $posturl );
$afterdomain = explode('yournetworkdomain.com', $purepostaddress);
$currentpostslug = $afterdomain[1];
$find = array( '' . $currentpostslug . '' );
$replace = '';
$parentblogaddress = str_replace( $find, $replace, $purepostaddress );

$blogid = get_blog_id_from_url('' . $parentblogaddress . '');
$blog_details = get_blog_details($blogid);

And so get the parent blog's link:
echo ''.$blog_details->blogname.'';


text: Q: Faster way to display scientific data than a picture box in VB.net I am using VB.net (VS2019) to display data coming in from a instrument (mass spectrometer). I am trying to stream, process and display 2048 data points in 100ms intervals. Drawing 2000 odd lines in a picturebox is by far the biggest bottle neck. What would be the alternative?


text:
Q: What browser versions are supported in v7 of adapter.js for webRTC? We are thinking about using adapter.js (https://github.com/webrtcHacks/adapter) as an adapter for webRTC.
Based on the comment in commits for v7 (https://github.com/webrtcHacks/adapter/releases) 'removed lots of cruft from Chrome and Firefox shims. If you need support for browsers which are older than two years stick with the old version'.
So what versions are currently supported?
There is no info in the documentation anywhere and it looks like those commits removed quite a lot of checks for browser versions (there is no diff version for commits =( )

A: https://github.com/webrtcHacks/adapter/issues/881 gives you a better indication about what cruft was removed.
Basically adapter makes no promises beyond what is testable on CI, if you want support for older versions... test yourself (slimjetbrower.com provides old chrome versions for download)


text:
Q: Error in onSubmit, feedback not rendering I have some logic in onSubmit of the button (which is in Form), which may fail, so I would like to show a message using error(myMessage). But it doesn't work, and it seems that it is normal:
Feedback panel added but does not show all messages
Is there any possibility to render feedback panels with errors reported in onSubmit?
There is no ajax used on the page. I am using wicket 1.5.6
EDIT:
MyPage.java
public class MyPage extends WebPage {

    private static final Logger logger = Logger.getLogger(MyPage.class);
    private static final long serialVersionUID = -8874964120018036584L;

    public MyPage(PageParameters parameters) {
        super(parameters);
        logger.debug("Creating new login page");

        add(new MyLoginForm("loginForm"));
    }
}

MyLoginForm.java
public class MyLoginForm extends StatelessForm<Void> {

    private static final Logger logger = Logger.getLogger(MyLoginForm.class);
    private static final long serialVersionUID = -8694389090804630170L;
    private MyUser user = new MyUser();

    public MyLoginForm(String id) {
        super(id);
        setOutputMarkupId(true);
        logger.debug("Creating new stateless login form");

        add(new RequiredTextField<String>("login", new PropertyModel<String>(user, "login")));
        add(new PasswordTextField("password", new PropertyModel<String>(user, "password")));
        add(new Button("submit"));
        add(new FeedbackPanel("feedback"));
    }

    @Override
    public void onSubmit() {
        info("test info");
    }
}

MyPage.html

    <form wicket:id="loginForm">
        <fieldset>
            <legend><wicket:message key="form.login.legend"/></legend>
            <input type="text" wicket:id="login" />
            <input type="password" wicket:id="password" />
            <input type="submit" wicket:id="submit" />

        </fieldset>
    </form>

catalina.out
16 May 2012 15:24:20:860 WARN  [http-8080-2] [WebSession:135] Component-targetted feedback message was left unrendered. This could be because you are missing a FeedbackPanel on the page.  Message: [FeedbackMessage message = "test info", reporter = loginForm, level = INFO]

The same happens when I try to overwrite the onSubmit method in Button instead of the one in MyLoginForm...

A: You need to add a FeedbackPanel to your Page. Feedback messages 'bubble' up in the component hierarchie. The easiest way is to have one feedbackpanel on your page.
But, you can also display errors close to the FormComponent that reports the error. See this pdf for inspiration  or for a possible implementation.
Edit: I just build a very simple test, using the wicket quickstart. Changed the HomePage as below and it worked (I saw all error / info messages)
html:
<form wicket:id="form">

            <input wicket:id="submit" type="button" value="submit">

</form>

Java:
Form<Void> form = new Form<Void>("form") {
        @Override
        protected void onSubmit() {
            super.onSubmit();
            error("test error from form");
            error("test info from form");
        }
    };
    add(form);
    form.add(new FeedbackPanel("feedback"));
    form.add(new SubmitLink("submit") {
        @Override
        public void onSubmit() {
            super.onSubmit();
            error("an error occurred in button submit");
            info("test info from the button");
        }
    });

Edit 2: It turns out, that a StatelessForm is used (I overlooked that detail). Switching back to  (normal) Form, the messages should be displayed correctly.

A: I have checked twice, Wicket 1.5.6 FeedbackPanel (and SignInForm where I have problem) works worse than 1.5.4
I have no idea, what is backgroud of this behaviour.
EDIT: version 1.5.5 work good.
EDIT2: https://issues.apache.org/jira/browse/WICKET-4536

A: I found another way for anyone else who stumbles into this issue..
I have a base class that I inherit from and then I have the feedback messages print out as part of the base class.. I too ran into this issue, and just had a method inside my base class return an instance of itself (return this),  and then I just access the info method through this method... so, getMethod().info("some message").. and it worked for me. My feedbackPanel is also set in the base class..
So I'd imagine you can do the same thing.. Just get access to an instance of the page you want to stamp the feedback message to.


text:
Q: Can't install anything on Ubuntu I am trying to install ros-opencv3 and ros-rosserial-arduino. But when I run the command sudo apt-get install ros-kinetic-rosserial-arduino, I am getting this error:
E: dpkg was interrupted, you must manually run 'sudo dpkg --configure -a' to correct the problem.

As soon as i run this command, it just stops in the middle with an error as follows:
Downloading kernel sources...
Reading package lists...
Picking 'linux-signed-hwe' as source package instead of 'linux-image-4.15.0-46-generic'
Need to get 12,3 kB of source archives.
Get:1 http://de.archive.ubuntu.com/ubuntu xenial-updates/main linux-signed-hwe 4.15.0-48.51~16.04.1 (dsc) [1.829 B]
Get:2 http://de.archive.ubuntu.com/ubuntu xenial-updates/main linux-signed-hwe 4.15.0-48.51~16.04.1 (tar) [10,4 kB]
gpgv: Signature made Fr 05 Apr 2019 13:57:42 CEST using RSA key ID 70E1162B
gpgv: Can't check signature: public key not found
dpkg-source: warning: failed to verify signature on ./linux-signed-hwe_4.15.0-48.51~16.04.1.dsc
dpkg-source: info: extracting linux-signed-hwe in linux-signed-hwe-4.15.0
dpkg-source: info: unpacking linux-signed-hwe_4.15.0-48.51~16.04.1.tar.xz
WFetched 12,3 kB in 0s (34,0 kB/s)
: Can't drop privileges for downloading as file 'linux-signed-hwe_4.15.0-48.51~16.04.1.dsc' couldn't be accessed by user '_apt'. - pkgAcquire::Run (13: Permission denied)
grep: drivers/media/usb/uvc/uvc_driver.c: No such file or directory
INFO: No Intel RealSense(TM) cameras are currently supported.
Patching uvcvideo sources...
can't find file to patch at input line 5
Perhaps you used the wrong -p or --strip option?

What is this issue and how can I resolve it?


text:
Q: Spring Boot REST - error while updating My problem is about that i can't update my entities. Everything else is working well but when i want update by patch/put spring boot is telling me there is no way to do that.
My user class
    package com.serwis.model;

    import com.fasterxml.jackson.annotation.JsonIgnore;
    import org.hibernate.validator.constraints.Length;
    import javax.persistence.*;
    import javax.validation.constraints.NotNull;
    import java.util.Set;

    @Entity
    @Table(name="User")
    public class User {

        @OneToMany(mappedBy="user", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
        private Set<Post> posts;

        @OneToMany(mappedBy="user", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
        private Set<Photo> photos;

        @OneToMany(mappedBy="user", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
        private Set<BlockedUser> blockedUsers;

        @OneToMany(mappedBy="user", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
        private Set<ObservedUser> observedUsers;

        @Id
        @GeneratedValue(strategy= GenerationType.AUTO)
        @Column(name="id")
        private Long id;

        @NotNull
        @Length(max = 11, min = 3)
        @Column(name="login")
        private String login;

        @JsonIgnore
        @NotNull
        @Length(max = 20, min = 4)
        @Column(name="password")
        private String password;

        @NotNull
        @Length(max = 25, min = 5)
        @Column(name="email")
        private String email;

        @Column(name="avatar")
        private byte[] avatar;

        public User(){}

        public User(String login, String password, String email) {
            this.login = login;
            this.password = password;
            this.email = email;
        }

        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", login='" + login + '\'' +
                    ", password='" + password + '\'' +
                    ", email='" + email + '\'' +
                    '}';
        }

        public Long getId() {
            return id;
        }

        public Set<BlockedUser> getBlockedUsers() {
            return blockedUsers;
        }

        public void setBlockedUsers(Set<BlockedUser> blockedUsers) {
            this.blockedUsers = blockedUsers;
        }

        public Set<ObservedUser> getObservedUsers() {
            return observedUsers;
        }

        public void setObservedUsers(Set<ObservedUser> observedUsers) {
            this.observedUsers = observedUsers;
        }

        public String getLogin() {
            return login;
        }

        public void setLogin(String login) {
            this.login = login;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        public String getEmail() {
            return email;
        }

        public void setEmail(String email) {
            this.email = email;
        }

        public byte[] getAvatar() {
            return avatar;
        }

        public void setAvatar(byte[] avatar) {
            this.avatar = avatar;
        }

public Set<Post> getPosts() {
        return posts;
    }

    public void setPosts(Set<Post> posts) {
        this.posts = posts;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Set<Photo> getPhotos() {
        return photos;
    }

    public void setPhotos(Set<Photo> photos) {
        this.photos = photos;
    }
}

My userController class
package com.serwis.controller;

import com.serwis.model.User;
import com.serwis.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@RequestMapping("/user")
@Controller
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @RequestMapping(value = "create", method = RequestMethod.POST)
    @ResponseBody
    @ResponseStatus(HttpStatus.CREATED)
    public User create(String email, String login, String password) {
        User user = new User(login, password, email);
        return userRepository.save(user);
    }

    @RequestMapping("/findall")
    @ResponseBody
    @ResponseStatus(HttpStatus.FOUND)
    public Iterable<User> findAll() {
        return userRepository.findAll();
    }

    @RequestMapping(value = "delete", method = RequestMethod.DELETE) //delete?id=4
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public String delete(Long id) {
        userRepository.delete(id);
        return "Succesful deleted";
    }

    @RequestMapping(value = "update", method = RequestMethod.PATCH)
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public User update(@ModelAttribute User user) {
        return userRepository.save(user);
    }
}

My UserRepository
package com.serwis.repository;

import com.serwis.model.User;
import org.springframework.data.repository.CrudRepository;
import org.springframework.transaction.annotation.Transactional;

@Transactional
public interface UserRepository extends CrudRepository<User, Long>{
}

Error from postman when i'm trying patch/put with id=1 and login=loginn
{
  "timestamp": 1471783909628,
  "status": 500,
  "error": "Internal Server Error",
  "exception": "javax.validation.ConstraintViolationException",
  "message": "Validation failed for classes [com.serwis.model.User] during persist time for groups [javax.validation.groups.Default, ]\nList of constraint violations:[\n\tConstraintViolationImpl{interpolatedMessage='may not be null', propertyPath=password, rootBeanClass=class com.serwis.model.User, messageTemplate='{javax.validation.constraints.NotNull.message}'}\n\tConstraintViolationImpl{interpolatedMessage='may not be null', propertyPath=email, rootBeanClass=class com.serwis.model.User, messageTemplate='{javax.validation.constraints.NotNull.message}'}\n\tConstraintViolationImpl{interpolatedMessage='may not be null', propertyPath=login, rootBeanClass=class com.serwis.model.User, messageTemplate='{javax.validation.constraints.NotNull.message}'}\n]",
  "path": "/user/update/"
}

Error from console:
List of constraint violations:[
    ConstraintViolationImpl{interpolatedMessage='may not be null', propertyPath=password, rootBeanClass=class com.serwis.model.User, messageTemplate='{javax.validation.constraints.NotNull.message}'}
    ConstraintViolationImpl{interpolatedMessage='may not be null', propertyPath=email, rootBeanClass=class com.serwis.model.User, messageTemplate='{javax.validation.constraints.NotNull.message}'}
    ConstraintViolationImpl{interpolatedMessage='may not be null', propertyPath=login, rootBeanClass=class com.serwis.model.User, messageTemplate='{javax.validation.constraints.NotNull.message}'}
]] with root cause

javax.validation.ConstraintViolationException: Validation failed for classes [com.serwis.model.User] during persist time for groups [javax.validation.groups.Default, ]
List of constraint violations:[
    ConstraintViolationImpl{interpolatedMessage='may not be null', propertyPath=password, rootBeanClass=class com.serwis.model.User, messageTemplate='{javax.validation.constraints.NotNull.message}'}
    ConstraintViolationImpl{interpolatedMessage='may not be null', propertyPath=email, rootBeanClass=class com.serwis.model.User, messageTemplate='{javax.validation.constraints.NotNull.message}'}
    ConstraintViolationImpl{interpolatedMessage='may not be null', propertyPath=login, rootBeanClass=class com.serwis.model.User, messageTemplate='{javax.validation.constraints.NotNull.message}'}
]
    at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.validate(BeanValidationEventListener.java:160) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.onPreInsert(BeanValidationEventListener.java:95) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.action.internal.EntityIdentityInsertAction.preInsert(EntityIdentityInsertAction.java:214) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:92) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:492) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:197) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:181) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:216) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:334) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:289) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:195) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:126) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.jpa.event.internal.core.JpaPersistEventListener.saveWithGeneratedId(JpaPersistEventListener.java:84) ~[hibernate-entitymanager-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:206) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:149) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:75) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:811) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:784) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:789) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1181) ~[hibernate-entitymanager-4.3.11.Final.jar:4.3.11.Final]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_92]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_92]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_92]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_92]
    at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:344) ~[spring-orm-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at com.sun.proxy.$Proxy76.persist(Unknown Source) ~[na:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_92]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_92]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_92]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_92]
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:294) ~[spring-orm-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at com.sun.proxy.$Proxy76.persist(Unknown Source) ~[na:na]
    at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:439) ~[spring-data-jpa-1.9.4.RELEASE.jar:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_92]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_92]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_92]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_92]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:483) ~[spring-data-commons-1.11.4.RELEASE.jar:na]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:468) ~[spring-data-commons-1.11.4.RELEASE.jar:na]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:440) ~[spring-data-commons-1.11.4.RELEASE.jar:na]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61) ~[spring-data-commons-1.11.4.RELEASE.jar:na]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) ~[spring-tx-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281) ~[spring-tx-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) ~[spring-tx-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136) ~[spring-tx-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:131) ~[spring-data-jpa-1.9.4.RELEASE.jar:na]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) ~[spring-aop-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208) ~[spring-aop-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at com.sun.proxy.$Proxy85.save(Unknown Source) ~[na:na]
    at com.serwis.controller.UserController.update(UserController.java:45) ~[main/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_92]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_92]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_92]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_92]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110) ~[spring-webmvc-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:832) ~[spring-webmvc-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:743) ~[spring-webmvc-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:961) ~[spring-webmvc-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:895) ~[spring-webmvc-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967) ~[spring-webmvc-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:840) ~[spring-webmvc-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) ~[tomcat-embed-core-8.0.36.jar:8.0.36]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292) ~[tomcat-embed-core-8.0.36.jar:8.0.36]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) ~[tomcat-embed-core-8.0.36.jar:8.0.36]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.0.36.jar:8.0.36]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) ~[tomcat-embed-core-8.0.36.jar:8.0.36]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) ~[tomcat-embed-core-8.0.36.jar:8.0.36]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) ~[tomcat-embed-core-8.0.36.jar:8.0.36]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) ~[tomcat-embed-core-8.0.36.jar:8.0.36]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:87) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) ~[tomcat-embed-core-8.0.36.jar:8.0.36]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) ~[tomcat-embed-core-8.0.36.jar:8.0.36]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) ~[tomcat-embed-core-8.0.36.jar:8.0.36]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) ~[tomcat-embed-core-8.0.36.jar:8.0.36]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:121) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) ~[tomcat-embed-core-8.0.36.jar:8.0.36]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) ~[tomcat-embed-core-8.0.36.jar:8.0.36]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212) ~[tomcat-embed-core-8.0.36.jar:8.0.36]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106) [tomcat-embed-core-8.0.36.jar:8.0.36]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) [tomcat-embed-core-8.0.36.jar:8.0.36]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141) [tomcat-embed-core-8.0.36.jar:8.0.36]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) [tomcat-embed-core-8.0.36.jar:8.0.36]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88) [tomcat-embed-core-8.0.36.jar:8.0.36]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528) [tomcat-embed-core-8.0.36.jar:8.0.36]
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1099) [tomcat-embed-core-8.0.36.jar:8.0.36]
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:670) [tomcat-embed-core-8.0.36.jar:8.0.36]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520) [tomcat-embed-core-8.0.36.jar:8.0.36]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476) [tomcat-embed-core-8.0.36.jar:8.0.36]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_92]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_92]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.0.36.jar:8.0.36]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_92]

Save, find, delete everything works. My idea was that i can just find user, edit him and save but there must be better idea.

A: It sounds like the login, password, and email fields are null when you get to the userRepository.save() call. Could you show the actual HTTP request you're sending from Postman?
Just curious, did you consider using spring-data-rest and having it automagically create the REST interface? You wouldn't need to write your own controller then.


text:
Q: Access Redis connection pool using Spring Data Redis I want to monitor and periodically log information about the Redis Connection Pool usage.
I use Redis through spring-data-redis RedisTemplate object.
Is there any way to access pool?

A: I was able to access internal pool using reflection API.
  private GenericObjectPool<Jedis> jedisPool() {
    try {
      Field pool = JedisConnectionFactory.class.getDeclaredField("pool");
      pool.setAccessible(true);
      Pool<Jedis> jedisPool = (Pool<Jedis>) pool.get(jedisConnectionFactory());
      Field internalPool = Pool.class.getDeclaredField("internalPool");
      internalPool.setAccessible(true);
      return (GenericObjectPool<Jedis>) internalPool.get(jedisPool);
    } catch (NoSuchFieldException | IllegalAccessException e) {
      e.printStackTrace();
    }
  }


text:
Q: Curves of genus 0 There are two properties of (projective, geometrically integral, and regular) curves of genus 0:

If the curve has a $k$-point, then it is isomorphic to $\mathbb{P}_k^1$

where, if $P$ is a $k$-point, the line bundle $\mathscr{L}(P)$ defines a closed embedding into $\mathbb{P}_k^1$.

All genus 0 curves can be described as conics in $\mathbb{P}_k^2$

where the degree 2 line bundle $\omega_C^{\vee}$ defines a closed embedding into $\mathbb{P}_k^2$. This is mentioned, for example, in Vakil's notes section 19.3. But $\mathbb{P}_k^1$ is not a conic in $\mathbb{P}_k^2$. What's going on here? Can you actually embed $\mathbb{P}_k^1$ as a conic in $\mathbb{P}_k^2$?

A:
Can you actually embed $\mathbb{P}_k^1$ as a conic in $\mathbb{P}_k^2$?

Yes. Combining the two facts, any conic in $\mathbb{P}^2$ with a rational point is isomorphic to $\mathbb{P}^1$ (this is a nice exercise to prove directly; you don't need to know anything about line bundles, even). For an explicit example, you can consider the Veronese embedding
$$\mathbb{P}^1 \ni (A : B) \mapsto (A^2 : AB : B^2) \in \mathbb{P}^2$$
whose image is the conic cut out by the homogeneous equation $XZ - Y^2 = 0$. This is a special case of the rational normal curve.


text:
Q: Find Probability that when a fair coin is flipped indefinitely a run of five heads occurs before run of two tails Find Probability that when a fair coin is flipped indefinitely a run of five heads occurs before run of two tails.
Here i assumed exactly $5$ consecutive heads appear before we get exactly $2$ consecutive tails.
For example the possibilities are
$1.$ $HHHHHTT $
$2.$ $THTHHHHHTT$
and so on
Now i assumed the string $HHHHH=X$ and $TT=Y$
we need probability that $X$ comes before $Y$
Can i have any clue?

A: Let $H_5$ be the event we first encounter a run of five consecutive heads, and the complement $T_2$ be the event that we first encounter a run of two consecutive tails.
We flip a coin, the first.  Either we obtain a head or a tail.  Let $H$ be the event that the latest coin tossed was a head, and $T$ be that the latest coin tossed was a tail.
$$\mathsf P(H_5) = \tfrac 12\mathsf P(H_5\mid H)+ \tfrac 12\mathsf P(H_5\mid T)$$

*

*Case 1: We have a head and next either we obtain 4 more consecituve heads (then have $H_5$), or we obtain a tail before that (then are at case 2).
$$\mathsf P(H_5\mid H) = \tfrac 1{16}+\tfrac {15}{16}\mathsf P(H_5\mid T)$$

*Case 2: We have a tail and next either we obtain another tail (then have $T_2$), or obtain a head (then are at case 1).
$$\mathsf P(H_5\mid T) = 0+ \tfrac 12\mathsf P(H_5\mid H)$$
Solve the simultaneous equations.$${z=\tfrac 12(x+y)\\ x=\tfrac 1{16}+\tfrac {15}{16} y\\ y=\tfrac 12 x}$$


text:
Q: Dell Inspiron 15 5558 touchpad not working in Ubuntu I am using a Dell Inspiron 15 5558 on Ubuntu dual-booted with Windows 8.1, however I am having issues with the touchpad. It works correctly in Windows but not in Ubuntu. If I connect a mouse the pointer works but the touchpad doesn't. Is there any command that will enable my touchpad to work?
System's informations:

     xinput ==>

    ⎡ Virtual core pointer                      id=2    [master pointer  (3)]
⎜   ↳ Virtual core XTEST pointer                id=4    [slave  pointer  (2)]
⎜   ↳ Logitech Dell Wireless Mouse WM123        id=11   [slave  pointer  (2)]
⎜   ↳ Logitech Dell Wireless Mouse WM123        id=12   [slave  pointer  (2)]
⎜   ↳ DLLC6AE:00 06CB:75BF                      id=14   [slave  pointer  (2)]
⎜   ↳ SynPS/2 Synaptics TouchPad                id=16   [slave  pointer  (2)]
⎣ Virtual core keyboard                     id=3    [master keyboard (2)]
    ↳ Virtual core XTEST keyboard               id=5    [slave  keyboard (3)]
    ↳ Power Button                              id=6    [slave  keyboard (3)]
    ↳ Video Bus                                 id=7    [slave  keyboard (3)]
    ↳ Video Bus                                 id=8    [slave  keyboard (3)]
    ↳ Power Button                              id=9    [slave  keyboard (3)]
    ↳ Sleep Button                              id=10   [slave  keyboard (3)]
    ↳ Integrated_Webcam_HD                      id=13   [slave  keyboard (3)]
    ↳ AT Translated Set 2 keyboard              id=15   [slave  keyboard (3)]
    ↳ Dell WMI hotkeys                          id=17   [slave  keyboard (3)]


text:
Q: Software as a Service, Content Delivery Networks and how it all fits together I'm sure I am running the risk of being told off for being off topic or too vague with this question but after a great deal of research I really don't know where else to start other than the knowledgeable folks on SO.
Here is the general gist of what I want to do:
I have some web software I want to make available to my clients the easiest way possible. From what I have read and understand SaaS is the best option for this. I want to enable customers to sign up, and then copy and paste a segment of code into their site and that is the set up complete. Take this piece of code for example:
setTimeout(function(){var a=document.createElement("script");
var b=document.getElementsByTagName("script")[0];
a.src=document.location.protocol+"myscript.js?"+Math.floor(new Date().getTime()/3600000);
a.async=true;a.type="text/javascript";b.parentNode.insertBefore(a,b)}, 1);

This is code from another site. But from what I understand it asychronously creates script tags and calls an external javascript file from a CDN and appends this to the users web page?
So, if I am right the user will now have a pointer to a javascript file hosted on a CDN. In this file I want to dynamically generate HTML content specific to the user and then append it to the webpage they are viewing. Say this HTML is a form which submits to a database on the CDN via AJAX.
So this is what I want to do. But it is all new to me. I am not even sure if it possible, and whether SaaS using a CDN is the right approach? If anyone could point me to some tutorials or articles about how to set something like this up it would be great. I have done a great deal of research but am finding it to a bit of a minefield of information. It is difficult to know where to start.
Sorry for such a vague question. I will edit and refine as I receive answers to try and clarify things and hopefully help out some other people.
Thanks for your time.

A: Perhaps look at Google Tag Manager, as a way to inject tags into your content.


text:
Q: Existe alguma outra razão para se comprimir JavaScript no código fonte além do de ficar com tamanho reduzido? A maioria das bibliotecas vem com o código comprimido da seguinte forma
<script>(function(){function c(b){window.setTimeout(function(){var a=document.createElement("script");a.src=b;document.getElementById("xjsd").appendChild(a)},0)}google.dljp=function(b,a){google.xjsu=b;c(a)};google.dlj=c;}).call(this);(function(){window.google.xjsrm=[];})();if(google.y)google.y.first=[];if(!google.xjs){window._=window._||{};window._DumpException=window._._DumpException=function(e){throw e};if(google.timers&&google.timers.load.t){google.timers.load.t.xjsls=new Date().getTime();}google.dljp('/xjs/_/js/k\x3dxjs.ntp.en_US.FA_vN017Rto.O/m\x3dsx,jsa,ntp,d,csi/am\x3dBGg/rt\x3dj/d\x3d1/t\x3dzcms/rs\x3dACT90oH9nFbyjTsBefBncZNhBHui7Tkmvw','/xjs/_/js/k\x3dxjs.ntp.en_US.FA_vN017Rto.O/m\x3dsx,jsa,ntp,d,csi/am\x3dBGg/rt\x3dj/d\x3d1/t\x3dzcms/rs\x3dACT90oH9nFbyjTsBefBncZNhBHui7Tkmvw');google.xjs=1;}
 ..........

Em uma linha enorme.
Quais as razões? O ganho na compressão é considerável? Esses códigos são feitos à mão por algum extraterrestre :)

A: As pessoas acham que assim ninguém irá entender o código maravilhoso que ela escreveu, oque não deixa de ser verdade, dificulta um pouco. Em geral quem faz isso por esse objetivo geralmente não escrevem códigos tão bons assim. Mas costuma funcionar porque só vai tentar copiar quem é muito ruim para entender um código ofuscado. Quem é bom não perde tempo.
Alguns até acham que assim o software dela ficará mais seguro. Se for isso, é um grande erro. Segurança não pode se valer neste tipo de artifício. Até um executável não dá segurança, imagine um código fonte, segurança de vir de técnicas corretas.
Fora isto é só reduzir o tempo de carga do script. Se bem feito dá um ganho grande.


text:
Q: How to define two new attributes in a factory which is defined inside another factory in RSpec? I have two models named Student and Teacher. Both of them have same fields like name, age etc. Except Teacher has two extra attributes qualification and college. Now for writing rspec, I decided to created factories for the same as below:

FactoryGirl.define do
  factory :student do
    type 'student'

    factory :teacher do
      type 'teacher'
      qualification BA
      college XYZ
    end
  end
end

I defined the teacher inside student because both of them have same attributes except teacher has two extra attributes. I added the attributes as above, but it gave error as:

  1) Teacher#default_value_for
     Failure/Error: it { expect(subject.qualification).to be_false}

     NoMethodError:
       undefined method `qualification' for #Student:0x0000000e8c0088'

Finished in 1.75 seconds (files took 14.48 seconds to load)
1 example, 1 failure

How to add those attributes in Teacher factory?
Thanks

A: If your Student and Teacher models are 2 different classes without inheritance, you can't do what you're trying to achieve.
According to the FactoryBot source:

You can easily create multiple factories for the same class without
  repeating common attributes by nesting factories
factory :post do
  title { "A title" }

  factory :approved_post do
    approved { true }
  end
end

You can actually write nested factories if Teacher inherits the Student class.
Example here: how to define factories with a inheritance user model

A: I resolved the above issue by removing the nesting in the factories.

FactoryGirl.define do
  factory :student do
    type 'student'
  end

 factory :teacher do
   type 'teacher'
   qualification BA
   college XYZ
 end
end

This created two different factories in the same factory. :)


text:
Q: _ViewStart stops working after creating a razor custom view engine I've created a razor custom view engine that extends RazorViewEngine. Then suddenly I'm unable to access the variables I've defined in _ViewStart.cshtml at the /Views folder, which normally work on a default project initialized by VS2010 MVC3 template.
My question is how to enable _ViewStart in a razor custom view engine?

A: Without seeing your code I can't specifically say what's going wrong, but after viewing the source the for the RazorViewEngine I think may have an idea what you are not doing.
This is what the CreateView method looks like:
    protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
    {
        var view = new RazorView(controllerContext, viewPath,
                                 layoutPath: masterPath, runViewStartPages: true, viewStartFileExtensions: FileExtensions, viewPageActivator: ViewPageActivator)
        {
            DisplayModeProvider = DisplayModeProvider
        };
        return view;
    }

You can see they are passing a value of true in for the runViewStartPages argument on the RazorView constructor.  Looking at the source of the RenderView method in the RazorView class reveals that this boolean parameter is used to create a StartPageLookupDelegate that is responsible for finding the _ViewStart file and compile it into the execution hierarchy.
WebPageRenderingBase startPage = null;
if (RunViewStartPages)
{
    startPage = StartPageLookup(webViewPage, RazorViewEngine.ViewStartFileName, ViewStartFileExtensions);
}
webViewPage.ExecutePageHierarchy(new WebPageContext(context: viewContext.HttpContext, page: null, model: null), writer, startPage);

So this means you are likely doing one of two things:

*

*Overriding the CreateView method of the RazorViewEngine and not initializing a RazorView in the manner listed above.

*Overriding the RenderView method of the RazorView without creating a StartPageLookupDelegate and passing it into the ExecutePageHierarchy method.

Hopefully this helps send you down the correct path to finding a solution!


text:
Q: The column status returned was The value violated the schema's constraint for the column I have a SQL Server table column with length as nvarchar(2000). Wanted to transfer the data to Excel file 2007  using SSIS.
What i did

Source column Data type is Nvarchar(2000) which is DT_NTEXT on SSIS.
on Excel the column Datatype is Nvarchar(255)
Below blue color circled Columns are giving me troubles.
Source MetaData

What can we do to take the whole source column data into one cell in the excel column?
The error I'm getting an error
ERROR
[Excel Destination [8]] Error: SSIS Error Code DTS_E_OLEDBERROR.  An OLE DB error has occurred. Error code: 0x00040EDA.
An OLE DB record is available.  Source: "Microsoft Access Database Engine"  Hresult: 0x80040E21  Description: "The field is too small to accept the amount of data you attempted to add. Try inserting or pasting less data.".

[Excel Destination 3] Error: There was an error with Excel Destination.Inputs[Excel Destination Input].ColumnsComment] on Excel Destination.Inputs[Excel Destination Input]. The column status returned was: "The value violated the schema's constraint for the column
[Excel Destination 3] Error: SSIS Error Code DTS_E_INDUCEDTRANSFORMFAILUREONERROR.  The "Excel Destination.Inputs[Excel Destination Input]" failed because error code 0xC0209076 occurred, and the error row disposition on "Excel Destination.Inputs[Excel Destination Input]" specifies failure on error. An error occurred on the specified object of the specified component.  There may be error messages posted before this with more information about the failure.

How can i overcome this problem.


text:
Q: Remove Last Word in SQL row if maxlength is reached? (PHP) A php script I have is extracting data from an XML file to a MySQL database.
It is set-up as followed:
$sql   = "INSERT IGNORE INTO `tablename` (columnname) VALUES ('text text text text text text $variablename text text $variablename2 text text')

$variablename and $variablename2 are both variables being extracted from the XML file, and have varying lengths.
So, I know, if I was just dealing with PHP I could use strlen or a variation of (see How to Truncate a string in PHP to the word closest to a certain number of characters? but 'columnname' in my sql database is not a variable.
And 'columnname' is what is limited to the characters.
I set this in mySQL to VARCHAR MAX=106 -- and that works --
But when re-outputting this to my web host it takes the data from the SQL database which is stopped at the maxlength cut-off mid-word.
I want it so that if it does reach the maxlength, the last word is just removed.
Could this be done, perhaps when inputting into the SQL table?
Or even perhaps in the PHP file outputting back to my web host?, such as here:
$rs->data_seek(0);
while($res = $rs->fetch_assoc()) {
   $a_topic = array(
   "columnname" => $res["columnname"]

or maybe in the $params here?
  $params = array(
    'status' => $share['columnname'],

Big thanks!

A: function cut($string, $maxLength)
{
    $revertString = strrev($string);
    $spaceRevertedPos = strpos($revertString, ' ', strlen($string)-$maxLength);
    $revertedCutString = substr($revertString, $spaceRevertedPos);

    return strrev($revertedCutString);
}

DEMO


text:
Q: Google Sheets Query Returns Abnormal Result After Changing Sheet Name I have a Google Sheet which i share with some users. They enter data at first sheet. I use their data at second, using query:
query('First Page'!A3:N;"select A, B, C, D, E, F, G, H, I, J, K, L, M, N where A = date '"&TEXT(TODAY();"yyyy-mm-dd")&"'")

This was returning todays data as expected, such as:
First Row (where i put formula): 'todays date' value value value ...

I had to delete 'First Page' because of certain problems. Then I have created an 'Entry Page' and modified my query:
query('Entry Page'!A3:I;"select A, B, C, D, E, F, G, H, I where A = date '"&TEXT(TODAY();"yyyy-mm-dd")&"'")

Now it returns:
First Row (where i put formula): previous dates (all  in one cell, seperated by space)
Second Row: 'todays date' value value value ...

Why this would happen? Why does it return irrelevant results?

A: Third parameter of query function proved essential here, by making it 0 i have solved my problem:
query('Entry Page'!A3:I;"select A, B, C, D, E, F, G, H, I where A = date '"&TEXT(TODAY();"yyyy-mm-dd")&"'";0)


text:
Q: How to calculate position for div with absolute when browser window change width I have img and div under it with position absolute. So I need that this div always start from bottom right corner of image and go to left. But div gets off from img bottom corner after resize browser window when I use this code :
div1.style.left = ((imgRect.left +
  (window.pageXOffset || document.body.scrollLeft) -
  (document.body.clientLeft || 0))
  - 532) + "px";

Note that div take correct position when refresh the page, but how to do this without refreshing?
I try to add this code:
$(window).resize(function () {
  div1.style.left = ((imgRect.left +
    (window.pageXOffset || document.body.scrollLeft) -
    (document.body.clientLeft || 0))
    - 532) + "px";
});

but still have same result. I guess it is not a correct calculation.

A: There's plenty wrong with your code, but the bit that's causing your code not to work is the div1 variable is likely inaccessible within the resize callback. Ensure div1 is available within the function and you should be good to go.


text:
Q: Android: Transparent gradient view I have searched for this question and found a lot of answers that and people claim that those answers work, and I do not doubt that. However, in my case non of these answers help. I need transparent gradient view under toolbar, so that when RecyclerViewis scrolled, it is visible under that gradient view. Is it even possible?
I tried doing this:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
    android:startColor="#e9e8e9"
    android:endColor="#30ffffff"
    android:angle="270"
    >
</gradient>

This, however, does not make any transparency. I also tried "@android:color/transparent", but still no luck.
This is how layouts are:
    <RelativeLayout
    android:id="@+id/layout_button_category">
    ....
    </RelativeLayout>
    <View android:id="@+id/shadow"
        android:layout_below="@+id/layout_button_category"
        android:layout_width="match_parent"
        android:layout_height="24dp"
        android:dither="true"
        android:background="@drawable/shadow"
        xmlns:android="http://schemas.android.com/apk/res/android" />
</android.support.design.widget.AppBarLayout>

A: You can use the Recycle view. The sample code is given below
<android.support.v7.widget.RecyclerView
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:id="@+id/recyclerView"
 android:scrollbars="vertical"
 android:scrollbarThumbVertical="@drawable/gradiant
/>

Step2. gradiant from xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient android:startColor="#000" android:endColor="#000"
    android:angle="45"/>
 <corners android:radius="6dp" />
</shape>

This will help out.


text:
Q: why templateUrl not working? why templateUrl not working in angular 2.when I used template it works .It not work ..here is my code
http://plnkr.co/edit/WI4gK2vbaj4OUX5ImJor?p=preview
import {Component,View} from 'angular2/core';

@Component({
    selector: 'my-app',
//  template: '<div (click)="onclck()">hello</div>'
})

@View({
  templateUrl: 'home/home.html'
});
export class AppComponent {

  onclck(){
    alert('--')
  }

}

A: You have a semi-colon between @View decorator and your export class AppComponent in app/script.ts. Just remove it and it works.

A: Autosave might be turn off, just try saving home.component.html,home.component.ts and app.module.ts file


text:
Q: Not able to access googleapis auth.OAuth2 for google calender api The below code is pasted from node.js quickstart of Google calender Api section.This code is not able to access auth from google API's.I copied the error below.To see full code you can access this link .Thanks for the help.
const google = require('googleapis');
const OAuth2Client = google.auth.OAuth2;

Error looks like this :

const OAuth2Client = google.auth.OAuth2;
                                   ^
      TypeError: Cannot read property 'OAuth2' of undefined

A: try it:
const {google} = require('googleapis');
const OAuth2 = google.auth.OAuth2;


text:
Q: jQuery.get callback not called in IE6 I have some Javascript code containing calls to jQuery.get().  I'm passing a callback to receive the response from the server.
In Firefox 3.5 (Windows and Linux) and IE8, the callback is called reliably.  In IE6, it's never called.
I've tried jQuery 1.3 and 1.4 -- same result.
Is there some setting in IE6 that could cause such a problem?  I've tried IE6 from a couple of different machines, same behavior.

A: Can you confirm that in IE6 the server talk is taking place and that the data is being received, if not then its not a callback issue but and XmlHttpRequest issue.
Also try setting the dataType attribute in the ajax call to whatever your fetching, so for instances if your fetching an xml document then do
$(function() {
        $.ajax({
                type: "GET",
                url: "some.xml",
                dataType: "xml", //<<<<<<<<
                success: function(xmlData)
                {
                        alert('Fetch')
                }
        });
});

As iv'e heard that it has caused some issues in the past.

A: I tried many things, without success.  Wireshark tells me that the server is sending
the requested data back to the browser.
So now I detect IE6 and redirect to a page that says "please upgrade your browser".
That's not ideal, because IE6 is still the default browser on Windows XP.  However,
our target audience is software developers, and they shouldn't be bothered too much
by having to upgrade.

A: Horse die - come down. I would recommend to stop supporting IE6. As it do Google Gmail, YouTube, Facebook and Digg. The share of IE6 is already negligible.
P.S.> Sorry for my english.


text:
Q: Using time_to_sec() in laravel eloquent How can i use time_to_sec() in laravel eloquent ?
Here is my Query in sql :
select time_to_sec('00:02:00')

Is there any way to implement this in laravel eloquent ?
I have the value in the coloumn charge as 750 which means 750 $ for one hour
If i give 00:30:00 It should convert the value to seconds and do the same in the coloumn.
And the result should be 375
It means for half hour the charge is 375
The mysql alternate is select time_to_sec("00:30:00") / 3600
I just want to know how to do this in laravel eloquent way.

A: You can use DB::select() if you'd like to run simple queries like that. DB::select() will return an array of stdClass objects containing the results of the query.
$result = DB::select("select time_to_sec('00:30:00') as seconds");
// print_r($result);
// Array
// (
//     [0] => stdClass Object
//         (
//             [seconds] => 1800
//         )
// )

$time = reset($result)->seconds;

Edit
If you're trying to incorporate this into an Eloquent query, you can use the selectRaw() method:
$time = '00:30:00';
$model = OutSideCity::selectRaw("*, ((time_to_sec('".$time."') / 3600) * charge) as calculated_charge")->first();
print_r($model->calculated_charge);

A: Most probably what you're looking for is the "raw" method. See: http://laravel.com/docs/4.2/queries#raw-expressions


text:
Q: What is causing my PayPal IPN script to fail? I am receiving the following from a PayPal IPN script. Is it evident from the following what is causing the IPN transaction to fail? If not, how can I investigate the problem further?
[01/25/2010 7:49 PM] - FAIL: IPN Validation Failed.
IPN $_POST variables from PayPal:
mc_gross=25.00
protection_eligibility=Ineligible
address_status=unconfirmed
payer_id=AEVB83JZKDRCL
tax=0.00
address_street=1 Main Terrace
payment_date=10:49:52 Jan 25, 2010 PST
payment_status=Pending
charset=windows-1252
address_zip=W12 4LQ
first_name=Test
address_country_code=GB
address_name=Test User
notify_version=2.9
custom=
payer_status=unverified
address_country=United Kingdom
address_city=Wolverhampton
quantity=1
verify_sign=A0I1KzEZadt6mIDXxQkkIQCQKPTMAGvCuZ8RKXsOCujIi.RoMxAnbZXi
payer_email=test1_1263505944_per@example.com
txn_id=38A45069EV5838100
payment_type=instant
last_name=User
address_state=West Midlands
receiver_email=martin@example.com
pending_reason=unilateral
txn_type=web_accept
item_name=Ultimate Challenge UK Ressurection  Standard Seating (25.00 GBP)
mc_currency=GBP
item_number=
residence_country=GB
test_ipn=1
handling_amount=0.00
transaction_subject=Ultimate Challenge UK Ressurection  Standard Seating (25.00 GBP)
payment_gross=
shipping=0.00

IPN response from PayPal server:
 HTTP/1.1 200 OK
Date: Mon, 25 Jan 2010 18:49:56 GMT
Server: Apache
Set-Cookie: cwrClyrK4LoCV1fydGbAxiNL6iG=_hMqg4cipUMV6RnPhXQ-05S5HEZk2hx2Yc87bjkBg5dZZLYqHTsxqiYwvU9Hjas5YeKTg9jnkbQYomER3_bjuAIW9f15003nc2FYPzIYqFuCc-Jfz1B8byXHhtrJ6OHyiPlmo0%7cGRbawzJR-iAiebJ1pZJZ3DzypAO4untXvofHa07UaqPHkeOZNQTSoCfMobgODGnxgP6jHW%7cf29zaCIP63s4TuzaT12cEiU-aih_kOHju4cqZ4KPV18bl-LTNlFzFLLGmr_DOhyXznq--m%7c1264445397; domain=.paypal.com; path=/
Set-Cookie: cookie_check=yes; expires=Thu, 23-Jan-2020 18:49:57 GMT; domain=.paypal.com; path=/
Set-Cookie: navcmd=_notify-validate; domain=.paypal.com; path=/
Set-Cookie: navlns=0; expires=Sun, 20-Jan-2030 18:49:57 GMT; domain=.paypal.com; path=/
Vary: Accept-Encoding
Keep-Alive: timeout=5, max=92
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: text/html; charset=UTF-8

7
INVALID
0

A: Anyone using the PHP Paypal IPN Integration Class by Micah Carrick and having the same problem:
The IPN variables and values have to be preceded with cmd=_notify-validate. In the paypal.class.php file it's just the opposite.
So, just replace $post_string = ''; in line 179 by
$post_string="cmd=_notify-validate";
replace
$post_string .= $field.'='.urlencode(stripslashes($value)).'&';
in line 181 by $post_string .= '&' . $field.'='.urlencode(stripslashes($value));
then delete $post_string.="cmd=_notify-validate"; in line 184 and your problem should be solved.

A: Have you tried the IPN test tool to investigate the problem?
You can use it to reproduce the form you're submitting and see if you get consistent results.
You might get better answers if you specify exactly in which context it is failing.

A: For connect to sandbox Paypal use this line :
$fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);

and not : $fp = fsockopen($url_parsed['host'],"80",$err_num,$err_str,30);
and the response IPN send the word "VERIFIED"
If you're testing Paypal IPN over SSL, you will have to use ssl://www.sandbox.paypal.com on the port 443

A: @ Dominik , that seems to fix my problems too !
I happened to be using Md Emran Hasan's PHP class.
And done tearing my hair out for about a week with this issue!
So my edit looked like this... where $postString .="cmd=_notify-validate"; // used to be after the while loop! This code was wrapped in a validateIPN function.
    $postString .= "cmd=_notify-validate"; // append ipn command

    foreach ($_POST as $field=>$value)
    {
        $this->ipnData["$field"] = $value;
        $postString .= '&' . $field .'=' . urlencode(stripslashes($value));
    }


text:
Q: How to prove unbiasedness/consistency/normality of an estimator that doesn't have a closed form? My estimator looks like this:
$$
\hat\theta(X) = \arg\max_{\theta} \frac1N \sum_{n=1}^N f(x_n|\theta)
$$
Here, $f(x_n|\theta)$ is some arbitrary function: it's not a logarithm, and the sum is not a log-likelihood.
I don't think that there's a closed form expression for $\hat\theta(X)$, so I'm using numerical optimization (gradient descent, Newton's method) to find it. However, this doesn't seem to let me calculate the expectation $\mathbb{E}\hat\theta(X)$ to prove even unbiasedness of the estimator.
How does one theoretically (without simulations) prove that such an estimator is (un)biased, (in)consistent, (non-)normal and so on?

A: On a general basis, $\hat\theta(X)$ is biased, due to the fact that it is equivariant under reparameterisation, i.e., if$$\eta=h(\theta)$$ is another parameterisation of the model, with $h$ a bijection, then $$\hat\eta(X)=h(\hat\theta(X))$$ while unbiasedness does not carry under arbitrary transforms $h$.
Note also that most parameters (or parameterisations) do not allow for the existence of an unbiased estimator, see e.g. the $\eta=1/p$ example for the Binomial model.

A: Your estimator is what's known as an M-estimator of $\rho$-type, where in this case $\rho = -f$.
If your function $f$ is differentiable, then it is known that under some (fairly strong) conditions, the M-estimator is consistent for the true maximizer of $f$, and is in fact asymptotically normal. See Chapter 7 of Boos & Stefanski's Essential Statistical Inference (2013) for a detailed treatment of M-estimation.


text:
Q: How to perform a hardware reset of a specific HID device? The aim
Perform a hardware reset of a specific USB dongle ANT, HID device, with Delphi app.

1. CM_Request_Device_Eject function attempt
I have tried to use the CM_Request_Device_Eject function and it correctly ejects my device, but on some systems does not automatically start it again.
This is the code I've used for the device eject:
str := PChar(GetDeviceID(DeviceInfoData.DevInst));
status := CM_Locate_DevNodeA(dev, str, CM_LOCATE_DEVNODE_NORMAL);
status := CM_Request_Device_EjectA(dev, nil, '', 0, 0);

Is there a way to ensure that my device will start if it does not automatically start after eject when using this function ?

2. SetupDiRestartDevices function attempt
As an alternative I've tried to use the SetupDiRestartDevices function and this one properly resets my device, but except that resets all the HID devices (such as mouse, keyboard, etc.), and this function requires administrator rights to work:
rslt1 := SetupDiRestartDevices(hDevInfo, DeviceInfoData);

How can I reset only my device with this function ?

Question
Is there a generic, recommended way to perform a hardware reset of a specific USB HID device ? Or is there a way to resolve any of the above problems ?

A: Hard reset is not something you can do just of your own...
to do a hard reset to some device, that particular device must support hard reset...
ways hard reset varies from device to device.
some devices have a button on it to do a hard reset. some requires a piece of code. most of the company releases a set of AT-command lists for there specific devices..
for example..
here is list of at commands released by the manufacturer for there specific device
this can help you in this case...
if not keep googling.


text:
Q: Rename file in PHPStorm without refactoring How do I quickly rename a file name without refactoring in PHPStorm? Even after I've just created the file, PHPStorm takes a long time to search through my files for its usage.

A: Default is Shift-F6. For not refactoring, disable the checkboxes in the popup.
I wanted to use F2 for file renaming like Windows default.
You can make a shortcut for F2. Go to:

*

*File

*Settings

*Keymap

*Search for "rename"

*Doubleclick "Refactor -> Rename"

*Click "Keyboard Shortcut"

*Press F2

*Ok

EDIT
If it does not work immediately, restart PHPStorm.

A: My technique for renaming files quickly is to single-click the file name and press Shift-F6. A dialog opens and you can immediately type the new name of the file and hit return/enter to complete the rename.
I find this technique intuitive because you don't have to move your mouse to the dialog window, type the new name, or click anything to confirm. As long as all you're doing is a rename that you know is safe, you just type it and go.
I also like this feature because you still have the option of quickly previewing the changes before they're made. And on those occasions when you are refactoring something with possible implications to the rest of your app, you can still enable "Search for references" and/or "Search in comments and strings" to get the whole enchilada. (I have those options disabled by default.)
I agree with you that right-clicking the file name, scrolling down to Refactor, selecting Rename, and then entering the new name is cumbersome, especially if the safe checks are enabled. I find that PhpStorm developers seem to understand these types of issues and usually have thought of a "faster way" to do things as well.

A: There is also an option available Right-click on file select "Show In Explorer" and then in windows explorer rename file by F2. It will not refactor or effect any other file in your project.

A: You can't do it without refactoring, though Refactor | Rename is usually very quick and you can disable options to search for references.

A: This will work for linux users.
It depends on zenity, so first check if it installed on your system,
run in console:  zenity --version
If it output something like 3.18.1.1 - then it's ok.
Create file idea-rename.sh with content below:
#!/usr/bin/env bash

FileDir="$1"
FileName="$2"

NewFileName="$(zenity --entry --title "Rename ${FileName}" --text "Please enter new name" --entry-text "${FileName}" --ok-label="Rename" 2>/dev/null)"

if [[ "${NewFileName}" != "" ]]; then
    if [[ -f "${FileDir}/${FileName}" ]]; then
        path="${FileDir}"
        name="${NewFileName}"

        if [[ "${NewFileName}" == *"/"* ]]; then
            IFS='/' read -ra newDirs <<< "$NewFileName"
            IFS='/' read -ra dirs <<< "$FileDir"

            last=$((${#newDirs[@]} - 1))
            path=""
            name="${newDirs[$last]}"
            unset 'newDirs[last]'

            if [[ "${NewFileName}" == *"./"* ]]; then
                for i in "${!newDirs[@]}"; do
                    dir="${newDirs[i]}"

                    if [[ "$dir" == ".." ]]; then
                        unset 'newDirs[i]'
                        j=$i

                        while [ $j -ge 0 ]; do
                            j=$(($j-1))

                            if [ $j -lt 0 ]; then
                                for (( k=${#dirs[@]}-1 ; k>=0 ; k-- )); do
                                    if [[ "${dirs[k]}" ]]; then
                                        echo 'dirs[k]'
                                        unset 'dirs[k]'
                                        break
                                    fi
                                done
                            elif [[ "${newDirs[j]}" ]]; then
                                echo 'newDirs[j]'
                                unset 'newDirs[j]'
                                break
                            fi
                        done

                    elif [[ "$dir" == "." ]]; then
                        unset 'newDirs[i]'
                    fi
                done
            fi

            for dir in "${dirs[@]}"; do
                if [[ "$dir" ]]; then
                    path="${path}/${dir}"

                    if [[ ! -d "$path" ]]; then
                        mkdir -m 0777 "$path"
                    fi
                fi
            done

            for dir in "${newDirs[@]}"; do
                if [[ "$dir" ]]; then
                    path="${path}/${dir}"

                    if [[ ! -d "$path" ]]; then
                        mkdir -m 0777 "$path"
                    fi
                fi
            done
        fi

        if [[ ! -f "${FileDir}/${NewFileName}" ]]; then
            mv "${FileDir}/${FileName}" "${path}/${name}"
        fi
    fi
fi

Open your Settings > Tools > External Tools, click on
and fill form as below

Name: Rename
Group: File
Program: /bin/bash
Parameters: /path/to/idea-rename.sh $FileDir$ $FileName$
Working Directory: $ProjectFileDir$
Click Ok, Apply
After that you can see new item in your file menu

When you click on rename will opens dialog

After rename in some cases phpstorm not sync files, so in path where located your file need to click in file menu "Synchronize 'path'"