Q:

How to give and remove authority of an object between multiple clients (Or how to let the client controller push a rigidbody)

I'm doing a cooperation FPS game in which players can push big rigidbody cubes with their rigidbody characters (the one from the standard assets).
The problem is that the player hosting the game has authority on these cubes positions and so when the client tries to push them, he really struggles and the result is 100% disappointing.
So i'm searching a way to pass authority from the server to client and vice versa when the cube is touched by a player.
I'm using Unity 2018.2
Have a nice day.

A:

And so here's the script I used to solve this problem. However, if both client and host are sending commands through the object, you'll have a problem when the client has authority. I'll try to solve this later.
public class CubeAuthority : NetworkBehaviour {

private void OnCollisionEnter(Collision collision)
{

    if (collision.transform.tag == "Player" && isServer)
    {
        CmdAssignNetworkAuthority(GetComponent<NetworkIdentity>(), collision.transform.GetComponent<NetworkIdentity>());
    }
}

[Command]
public void CmdAssignNetworkAuthority(NetworkIdentity cubeId, NetworkIdentity clientId)
{
    //If -> cube has a owner && owner isn't the actual owner
    if (cubeId.clientAuthorityOwner != null && cubeId.clientAuthorityOwner != clientId.connectionToClient)
    {
        // Remove authority
        cubeId.RemoveClientAuthority(cubeId.clientAuthorityOwner);
    }

    //If -> cube has no owner
    if (cubeId.clientAuthorityOwner == null)
    {
        // Add client as owner
        cubeId.AssignClientAuthority(clientId.connectionToClient);
    }
}
}


Q:

sed write a line in a certain way

I have this text file that have lines made in a certain format just like this next line
bla bla name1=WORD1 bla    bla name2=WORD2 bla bla name3=WORD2

I want to extract WORD1 WORD2 WORD3 without all the bla bla and printing them with semicolon
WORD1;WORD2;WORD3

can this be done using only sed ?

A:

If WORD* always occur in this manner, you can use these two patterns [^=]*= and [^ ]* to match before and the word respectively. ^ at the beginning of a group inverts the matching. Something like this works in GNU sed:
sed -r 's/[^=]*=([^ ]*)[^=]*=([^ ]*)[^=]*=(.*)/\1;\2;\3/' infile


Q:

Laravel request validation with custom tenant connection on-the-fly

I'm creating an SaaS application with multiple databases and the connection to the database is set on-the-fly according to the user logged in. You can see my problem and solution here back when I was trying to figure out how to do it.
My problem now is using the $request->validate function with both unique and exists functions.
The documentation says that we can set a Custom Database Connection, by doing something like:
'email' => 'unique:connection.clients,email'

But this forces me to create my connections within the config\database.php file and that's something I don't want to do.
Currently, if I do:
$request->validate(['email' => 'required|unique:clients,email']);

I got an error saying:

Base table or view not found: 1146 Table
  'mydb_admin.clients'

Which is correct, since my Admin database does not have the table clients. So how can I, with the system I have in place, use the $request->validate function with my child databases?

A:

You can do it like this since you are already setting the tenant connection in your middleware:
$request->validate([
    'email' => 'required|unique:tenant.clients'
]);


Q:

arduino(microusb) and windows phone 8/8.1

I would like to have serial communication through usb port  with arduino in  windows phone 8/8.1 ,i would like to know if it is possible ..
Have seen sample which works with Bluetooth  Link

A:

No, you would need a USB serial driver and that's not something you're likely to find on a consumer phone. You may have some luck using a Microsoft Windows Embedded 8.1 Handheld for Mobile Rugged Industrial, Commercial, Automotive, and POS Mobile Enterprise Applications.[1] But you'll want to verify support with the manufacturer.
[1] Named by committee


Q:

Get Entity Table Name - EF7

As the question states, anyone know how to get the entity table name in entity framework 7?
I have the code to do this in entity framework 6.1 (from another site, cant find link), but none of the interfaces/objects seem to be referenced in entity framework 7.
Code for EF6.1
public string GetTableName(Type type)
{
    var metadata = ((IObjectContextAdapter)this).ObjectContext.MetadataWorkspace;
    var objectItemCollection = ((ObjectItemCollection)metadata.GetItemCollection(DataSpace.OSpace));
    var entityType = metadata.GetItems<EntityType>(DataSpace.OSpace).Single(e => objectItemCollection.GetClrType(e) == type);
    var entitySet = metadata.GetItems(DataSpace.CSpace).Where(x => x.BuiltInTypeKind == BuiltInTypeKind.EntityType).Cast<EntityType>().Single(x => x.Name == entityType.Name);
    var entitySetMappings = metadata.GetItems<EntityContainerMapping>(DataSpace.CSSpace).Single().EntitySetMappings.ToList();

    EntitySet table = null;

    var mapping = entitySetMappings.SingleOrDefault(x => x.EntitySet.Name == entitySet.Name);
    if (mapping != null)
    {
        table = mapping.EntityTypeMappings.Single().Fragments.Single().StoreEntitySet;
    }
    else
    {
        mapping = entitySetMappings.SingleOrDefault(x => x.EntityTypeMappings.Where(y => y.EntityType != null).Any(y => y.EntityType.Name == entitySet.Name));

        if (mapping != null)
        {
            table = mapping.EntityTypeMappings.Where(x => x.EntityType != null).Single(x => x.EntityType.Name == entityType.Name).Fragments.Single().StoreEntitySet;
        }
        else
        {
            var entitySetMapping = entitySetMappings.Single(x => x.EntityTypeMappings.Any(y => y.IsOfEntityTypes.Any(z => z.Name == entitySet.Name)));
            table = entitySetMapping.EntityTypeMappings.First(x => x.IsOfEntityTypes.Any(y => y.Name == entitySet.Name)).Fragments.Single().StoreEntitySet;
        }
    }

    return (string)table.MetadataProperties["Table"].Value ?? table.Name;
}

A:

The only thing you need to do now to achieve the same is this:
public string GetTableName(Type type)
{
   return this.Model.GetEntityType(type).SqlServer().TableName;
}

PS: I'm assuming this method is declared in your DbContext class, otherwise change the this keyword for your DbContext instance.
Update
GetEntityType was renamed to FindEntityType. You can find more info in this link
return this.Model.FindEntityType(type).SqlServer().TableName;


Q:

Why are no reviews being printed out? Am I using the correct HTML elements?

I'm trying to print out the paragraph portion of reviews from yelp for a specific restaurant. I am not sure if I am implementing the BeautifulSoup functions correctly.
I am providing the code below.
I have seen similar implementation of the soup.find_all work. I figured that it was an issue of what I put in the attrs. I figured that it would be best to find all the div elements that had the same class name and contained the reviews.
for i in range (0,500,20):
    url = 'https://www.yelp.com/biz/m%C3%A9m%C3%A9-mediterranean-new-york-4?start={}'.format(i)
    response = requests.get(url, headers=headers, verify=False).text
    soup = BeautifulSoup(response, "lxml")
    for s in soup.find_all('div', attrs={'span class': 'lemon--span__373c0__3997G'}):
      re = s.find('p', attrs={'lang': 'en'})
      print(re.text)

Now when I run this code it does not print out any error. All it says is: "Process finished with exit code 0"
This leads me to believe that I am not using the right elements correctly or have messed up logic in the for loop.

A:

The html looks like a lot of it is dynamic e.g. the class names etc will change over time. I would grab from the script tag the review info and parse with a json library
import requests,json
from bs4 import BeautifulSoup as bs

r = requests.get('https://www.yelp.com/biz/m%C3%A9m%C3%A9-mediterranean-new-york-4')
soup = bs(r.content, 'lxml')
data = json.loads(soup.select_one('[type="application/ld+json"]').text.strip())
print(data)

If you want to do away with bs4 you could just regex out the required string.
import requests,json, re

r = requests.get('https://www.yelp.com/biz/m%C3%A9m%C3%A9-mediterranean-new-york-4')
p = re.compile(r'({"aggregateRating.+?(?=<))', re.DOTALL)
data = json.loads(p.findall(r.text)[0].strip())


Q:

Storing salt+password hash in DB and protecting against password attack

Please help me with my understanding. Also I am not talking about SSL or DH key exchange.
As the salt is stored in DB and is a secret to the attacker to just protect the user original password (Rainbow tables), in case attacker gets their hand on the actual DB itself. Then how will how you protect against brute/dictionary based attacks. Once again, logging the wrong requests and denying IP of many bad request is known, I am talking about cryptography here. As the password is same for user1, attacker got it from other websites, how does salt protects here. I guess not, then what are the best solutions available to stop such attacks. Assume data is really important like credit card numbers + CVV(I know don't store CVV, but that is not the question).
EDIT: By the way, I came up with some stupid idea, and it looks like a known method for stopping dictionary attacks. Read more this question: High cost encryption but less cost decryption
May be we can discuss some other methods here, to protect against brute/dictionary/social engineering password attack

A:

It's a little unclear to me what your actual question is, but if it is "How does a salt help protect me against brute force attacks?" the answer is that technically it does not. There is nothing about a salt that makes brute force attacks more difficult, salts instead make it difficult to brute force multiple accounts simultaneously. Essentially salts artificially inflate search space required to do a brute force attack, making it computationally difficult to pre-calculate every possible password and then check them against the entire database. Salts can be stored in the clear, so long as they are unique to each password.
If you want to make brute forcing passwords more difficult, what you want is an adaptive hashing scheme. These schemes allow you to dictate how long hashing should take. Because an honest client should only have to authenticate on the order of tens of times, but an attacker will need to do it on the order of millions or billions of times, slower hashes make the task near impossible for the attacker while introducing little overhead in the system.
What this all boils down to is that you should use bcrypt if you are hashing passwords. It is designed to incorporate a salt and is an adaptive hashing system. For more info, see this article on security.stackexchange.com


Q:

Add supplementary information to error message

I have tried to write a method that takes an error and returns it the same but with an exclamation mark added to the end of the message but there was a problem with the fact that the errors in java are immutable and because of limitations of generics its impossible to create new instance of error
by using new T(e, message) :
public static <T extends Throwable> T withExclamationMark(T error) {
    return new T(error.getMessage() + "!", error);
}

Is there any simple solution which doesnt require reflection etc?

A:

You can do it with a BiFunction:
public static <T extends Throwable> T withExclamationMark(
        T error,
        BiFunction<String, T, T> factory) {

    return factory.apply(error.getMessage() + "!", error);
}

Then, you can use this method as follows:
RuntimeException original = new RuntimeException("Message");

RuntimeException decorated = withExclamationMark(original, RuntimeException::new);

System.out.println(decorated.getMessage()); // Message!


Q:

How to use lebesgue dominated convergence theorem to find the limit of an integral

I have to use lebesgue dominated convergence theorem to prove that
$$
 \lim_{n\rightarrow\infty}\int_0^\infty \left[1+ \frac{\ln(x + n^2)}{n^{1/2}}\sin(x^2) + \cos\left(\frac{1}{n+x}\right)\right]  e^{-x/5} \, d\lambda\ = 5
$$
Do I have to find the function $g$ which bounds all $f_n$? [since it already says to prove using the dominated convergence theorem]
What I have done so far is:
$$\lim_{n\rightarrow\infty}\int_0^\infty \left[1+ \frac{\ln(x + n^2)}{n^{1/2}}\sin(x^2) + \cos\left(\frac{1}{n+x}\right)\right]  e^{-x/5} \, d\lambda $$
$$ = \int_0^\infty \lim_{n\rightarrow\infty}\left[1+ \frac{\ln(x + n^2)}{n^{1/2}}\sin(x^2) + \cos\left(\frac{1}{n+x}\right)\right]  e^{-x/5} \, d\lambda$$
Then,
$$\frac{\ln(x+n^2)}{n^{1/2}}=\frac{\ln\left(n^2\left(1+\frac{x}{n^2}\right)\right)}{n^{1/2}} = \frac{2\ln n +\ln\left(1+\frac{x}{n^2}\right)}{n^{1/2}}$$
I used the maclaurin expansion of $\ln(1+X)$ to prove that $\lim_{n\rightarrow\infty}\frac{\ln(1+\frac{x}{n^2})}{n^{1/2}}=0$
I compared $\lim_{n\rightarrow\infty}\frac{\ln{n}}{n^{1/2}}$ to
$\lim_{x\rightarrow\infty}\frac{\ln{x}}{x^{1/2}}$ and used l'Hopital's rule to prove that the limit is zero since I found such an example on youtube.
I don't know whether it is good. Also, when I use maclaurin's expansion of $\cos(X)$ and take $\lim_{n\rightarrow\infty}\cos(\frac{1}{n+x})$, I get it to be $1$.
Then I get $10$ as final answer.

A:

Your evaluation of the integral assuming the DCT applies is correct  (I also arrive at $10$ instead of $5$) so all you have left to do is find a function $g$ such that $f_n(x) \leq g(x)$ for all $n\in \mathbb{N}, x\in (0,\infty)$ and $\int^{\infty}_0 g(x) dx < \infty.$
Since $e^{-x/5}$ decreases quite rapidly, even a relatively weak bound on $$h_n(x) = 1+ \dfrac{\log(x + n^2)}{n^{1/2}}\sin(x^2) + \cos\left(\dfrac{1}{n+x}\right)$$
should be sufficient to ensure the required conditions. The middle term can be estimated $$\dfrac{2\log n + \log(1+ x/n^2)}{\sqrt{n}}< 3+x$$
since $\dfrac{2\log n}{\sqrt{n}} < 3$ for all $n\in \mathbb{N}$ and $\dfrac{\log(1+x/n^2)}{\sqrt{n}}< \dfrac{x/n^2}{\sqrt{n}}< x.$ Thus we can see that $h_n(x)< 5+x$ so $g(x) = (5+x)e^{-x/5}$ is a suitable dominating function.


Q:

Linking to boost::python using Visual C++ Express 10

I've built Python (3.2.1) and boost::python (1_47_0) under Windows with Visual C++ Express 2010.  While boost::filesystem works fine, boost::python doesn't (these both require linking to libraries as well as the header).  I'm getting the error:
2>LINK : fatal error LNK1104: cannot open file 'boost_python-vc100-mt-gd-1_47.lib'

This seems clear enough, but in the stage/lib folder I can see a "libboost_python_vc100-mt-gd-1_47.lib" - i.e. the correct filename, but prefixed with "lib".  Somehow the autolinking is working for the filesystem stuff, but not for Python.  If I copy the boost::python lib and remove the "lib" prefix it all links fine.
Is this a known Boost issue, or is something else wrong?  I can rename the files, but it would be nice to remove this step.

A:

You must define BOOST_PYTHON_STATIC_LIB, if you want to use libboost_* libs


Q:

The primes $p$ of the form $p = -(4a^3 + 27b^2)$

The current question is motivated by this question.
It is known that the number of imaginary quadratic fields of class number 3 is finite.
Assuming the answer to this question is affirmative, I came up with the following question.
Let $f(X) = X^3 + aX + b$ be an irreducible polynomial in $\mathbb{Z}[X]$.
Let $p = -(4a^3 + 27b^2)$ be the discriminant of $f(X)$.
We consider the following conditions.
(1) $p = -(4a^3 + 27b^2)$ is a prime number.
(2) The class number of $\mathbb{Q}(\sqrt{p})$ is 3.
(3) $f(X) \equiv (X - s)^2(X - t)$ (mod $p$), where $s$ and $t$ are distinct rational integers mod $p$.
Question
Are there infinitely many primes $p$ satisfying (1), (2), (3)?
If this is too difficult, is there any such $p$?
I hope that someone would search for such primes using a computer.

A:

For (229, -4,-1) the polynomial factors as $(x-200)^2(x-58)$
For (1373, -8,-5) the polynomial factors as $(x-860)(x-943)^2$
For (2713, -13,-15) the polynomial factors as $(x-520)^2(x-1673)$


Q:

Forcing Question about a sequence of functions from $\aleph_{0}$ into $2 = \{0, 1\}$

I'm trying to go through Timothy Chow's A Beginner's Guide to Forcing (arxiv pdf).
My particular question is about the first paragraph of Section $5$ (on p. $7$ of the above pdf).
First, my vague understanding of the broad idea of what's being done here, which anyone should feel to point out flaws in as well: we are crossing $\aleph_{2}$ with $\aleph_{0}$ and taking a function into $2 = \{0, 1\}$ (this is basically taking the power set of something, where $0$ means "exclude from subset" and $1$ means "include in subset"). More precisely, we are working with something that "looks like" $\aleph_{2}, \aleph_{0}$ in our countable standard transitive model $M$, but we note that $\aleph_{0}$ is absolute (in the sense given at the end of the previous section) so that really it's just the former that might be a bit different, hence we denote it as $\aleph_{2}^M$. The reason we have chosen $\aleph_{2}$ rather than $\aleph_{1}$ is we are hoping to "skip" over the latter and match up the powerset of $\aleph_{0}$ such that it is at least the size of $\aleph_2$; then we will have constructed a model satisfying 'not $CH$.'
The details, though, elude me. In particular, I am confused starting with: "We may interpret $F$ as a sequence of functions from $\aleph_0$ into $2$. Because $M$ is countable and transitive, so is $\aleph_{2}^M$; thus we can easily arrange for these functions to be pairwise distinct. Now, if $F$ is already in $M$, then $M$ satisfies 'not $ CH$'!"
Questions: I would be grateful if anyone could explain precisely what is meant by interpreting $F$ in the manner described above, what it means for $\aleph_{2}^M$ (a cardinal number) to be transitive (since the paper has defined it for a model), how we know the functions can be arranged to be pairwise distinct, and exactly why $F$ "shows us that the powerset of $\aleph_0$ in $M$ must be at least $\aleph_2$ in $M$."
Any additional assistance clarifying how forcing works would, of course, be welcomed as well.

A:

Because $M$ is transitive, every element of $M$ is a subset of $M$. In particular, $\aleph_2^M$ is a subset of $M$. Since $M$ is countable, so is $\aleph_2^M$. Thus, in $V$ we may index $\aleph_2^M$ as $\{x_n:n\in\omega\}$. For each $n\in\omega$ define
$$F_n:\aleph_0\to\{0,1\}:k\mapsto F(x_n,k)\;;$$
if you know $F$, you know the functions $F_n$ for $n\in\omega$, and conversely, you can reconstruct $F$ from the functions $F_n$. $\langle F_n:n\in\omega\rangle$ is the sequence of functions that Chow has in mind when he says that we can think of $F$ as a sequence of functions from $\aleph_0$ to $2$.
Since there are uncountably many functions from $\aleph_0$ to $2$, we can certainly pick a sequence $\langle F_n:n\in\omega\rangle$ of distinct functions from $\aleph_0$ to $2$ and piece them together to form the function $$F:\aleph_2^M\times\aleph_0\to 2:\langle x_n,k\rangle\mapsto F_n(k)\;.$$ This function $F$ may or may not be in $M$. If it is, then from $M$’s point of view it provides an enumeration of $\aleph_2$ distinct functions from $\aleph_0$ to $2$, even though from our (or $V$’s) point of view $\aleph_2^M$ is only countable. That is, from $M$’s point of view there are actually $\aleph_2$ functions $F_n$, because the $x_n$’s are the elements of $\aleph_2^M$, the ordinal that $M$ ‘thinks’ is $\aleph_2$. In other words, if we let $f_{x_n}=F_n$ for each $n\in\omega$, then
$$\{F_n:n\in\omega\}=\{f_{x_n}:n\in\omega\}=\{f_\xi:\xi\in\aleph_2^M\}\;,$$
where $f_\xi:\aleph_0\to 2:k\mapsto F(\xi,k)$ for each $\xi\in\aleph_2^M$. Since the $f_\xi$ for $\xi\in\aleph_2^M$ are all distinct, $\{f_\xi:\xi\in\aleph_2^M\}$ is from $M$’s point of view a family of $\aleph_2$ distinct functions from $\aleph_0$ to $2$.
The rest of the paper deals with what we do if $F\notin M$, i.e., how we add such an $F$ to $M$ without changing the rest of $M$ too much.

A:

First note that cardinal numbers are just ordinals numbers of a particular kind.  (Von Neumann) ordinals are transitive sets (since every ordinal is the set of all strictly smaller ordinals).  I actually dislike using cardinal number notations (e.g., $\aleph_\alpha$) when cardinalities are not important, and will use ordinal notations below instead.  Just remember that $\omega_\alpha = \aleph_\alpha$ as sets; the former is used generally to emphasize that it is an ordinal, and the latter that it is a cardinal.)
A function $F : \omega_2 \times \omega \to 2$ can be viewed as a ($\omega_2$-)sequence of functions $f_\alpha : \omega \to 2$ by defining $f_\alpha ( n ) = F ( \alpha , n )$ for all $\alpha < \omega_2$ and all $n < \omega$.  Working inside a countable transitive model $M$ of ZFC we have $M$'s version of $\omega_2$, denoted $\omega_2^M$, as well as $M$'s version of $\omega$, which happens to be $\omega$.  So consider some function $F : \omega_2^M \times \omega \to 2$.  This function does not itself have to be in $M$.  In the same way as above, we get an ($\omega_2^M$-)sequence of functions $f_\alpha : \omega \to 2$.
For these functions to be distinct the following must hold:

Given distinct $\alpha , \beta < \omega_2^M$ there is an $n \in \omega$ such that $f_\alpha ( n ) \neq f_\beta ( n )$.

As $\omega_2^M$ is countable we can find an injection $h : \{ ( \alpha , \beta ) : \alpha < \beta < \omega_2^M \} \to \omega$ and ensure that whenever $\alpha < \beta < \omega_2^M$ that $f_\alpha ( h ( \alpha , \beta ) ) \neq f_\beta ( h ( \alpha , \beta ) )$.  (For instance, we can first assign $f_\alpha ( h ( \alpha , \beta ) ) = 0$ and $f_\beta ( h ( \alpha , \beta ) ) = 1$ for all $\alpha < \beta < \omega_2^M$, and afterwards fill in any undefined values by $0$.)
Now, if $F \in M$, then as $M$ is a model of ZFC it will follow that $f_\alpha \in M$ for all $\alpha < \omega_2^M$, and so $\{ f_\alpha : \alpha < \omega_2^M \} \subseteq ( {^{\omega}} 2 )^{M}$ (i.e., $M$'s version of the set of all functions $\omega \to 2$).  Thus, it must be that $M \models | {^{\omega}}2 | = | \mathcal{P} ( \omega ) | \geq | \omega_2^M | = \aleph_2$, and so $M$ cannot satisfy the Continuum Hypothesis.
However, if $F \notin M$, then we would like to "add" $F$ to $M$ and create a new countable transitive model $M^*$ of ZFC.  As above it will follow that $M^* \models | \mathcal{P}^{M^*} ( \omega ) | \geq | \omega_2^M |$.  All that's left to do is ensure that $M^* \models | \omega_2^M | > \aleph_1$ and then $M^*$ will satisfy the negation of CH.
(This part of the paper appears to be introductory and does not go into details.  Precisely how all of this is accomplished should be explained in further sections in the paper.  I'm just noting the "plausibility" of this approach.)


Q:

Drawing things on a Canvas

How would I draw something on a Canvas in C# for Windows Phone?
Okay, let me be a little more clear.
Say the user taps his finger down at 386,43 on the canvas. (the canvas is 768 by 480)
I would like my application to be able to respond by placing a red dot at 386,43 on the canvas.
I have no prior experience with Canvas whatsoever.
If this is too complex to be answered in one question (which it probably is), please give me links to other websites with Canvas and Drawing articles.

A:

There are various ways of doing this. Depending on the nature of the red dot, you could make it a UserControl. For a basic circle, you can simply handle your canvas' ManipulationStarted event.
private void myCanvas_ManipulationStarted(object sender, ManipulationStartedEventArgs e)
{

            Ellipse el = new Ellipse();
            el.Width = 10;
            el.Height = 10;
            el.Fill = new SolidColorBrush(Colors.Red);
            Canvas.SetLeft(el, e.ManipulationOrigin.X);
            Canvas.SetTop(el, e.ManipulationOrigin.Y);
            myCanvas.Children.Add(el);
}

A:

I think you need to approach the problem differently.  (I'm not including code on purpose, because of that).
Forms and controls in an Windows applications (including Phone) can be refreshed for several reasons, at any time.  If you draw on a canvas in response to a touch action, you have an updated canvas until the next refresh.  If a refresh occurs the canvas repaints itself, you end up with a blank canvas.
I have no idea what your end goal is, but you likely want to either keep track of what the user has done and store that state somewhere and show it in a canvas on the repaint of the canvas.  This could be done with storing all the actions and "replaying" them on the canvas, or simply storing the view of the canvas as a bitmap and reload the canvas with that bitmap when refreshed.  But, in the later case I think using a canvas isn't the right solution.


Q:

Using C++20 chrono, how to compute various facts about a date

https://www.timeanddate.com/date/weekday.html computes various facts about a day of the year, for example:

Given an arbitrary date, how can these numbers be computed with the C++20 chrono specification?

A:

This is remarkably easy with the C++20 chrono specification.  Below I show a function which inputs an arbitrary date, and prints this information to cout.  Though at the time of this writing, the C++20 chrono specification isn't yet shipping, it is approximated by a free, open-source library.  So you can experiment with it today, and even include it in shipping applications as long as you adopt C++11 or later.
This answer will take the form of a function:
void info(std::chrono::sys_days sd);

sys_days is a day-precision time_point in the system_clock family.  That means it is simply a count of days since 1970-01-01 00:00:00 UTC.  The type alias sys_days is new with C++20, but the underlying type has been available since C++11 (time_point<system_clock, duration<int, ratio<86400>>>).  If you use the open-source C++20 preview library, sys_days is in namespace date.
The code below assumes function-local:
using namespace std;
using namespace std::chrono;

to reduce verbosity.  If you are experimenting with the open-source C++20 preview library, also assume:
using namespace date;

Heading
To output the first two lines is simple:
cout << format("{:%d %B %Y is a %A}\n", sd)
     << "\nAdditional facts\n";

Just take the date sd and use format with the familiar strftime/put_time flags to print out the date and text.  The open-source C++20 preview library hasn't yet integrated the fmt library, and so uses the slightly altered format string "%d %B %Y is a %A\n".
This will output (for example):
26 December 2019 is a Thursday

Additional facts

Common intermediate results computed once
This section of the function is written last, because one doesn't yet know what computations will be needed multiple times.  But once you know, here is how to compute them:
year_month_day ymd = sd;
auto y = ymd.year();
auto m = ymd.month();
weekday wd{sd};
sys_days NewYears = y/1/1;
sys_days LastDayOfYear = y/12/31;

We will need the year and month fields of sd, and the weekday (day of the week).  It is efficient to compute them once and for all in this manner.  We will also need (multiple times) the first and last days of the current year.  It is hard to tell at this point, but it is efficient to store these values as type sys_days as their subsequent use is only with day-oriented arithmetic which sys_days is very efficient at (sub-nanosecond speeds).
Fact 1:  day number of year, and number of days left in year
auto dn = sd - NewYears + days{1};
auto dl = LastDayOfYear - sd;
cout << "* It is day number " << dn/days{1} << " of the year, "
     << dl/days{1} << " days left.\n";

This prints out the day number of the year, with January 1 being day 1, and then also prints out the number of days remaining in the year, not including sd.  The computation to do this is trivial.  Dividing each result by days{1} is a way to extract the number of days in dn and dl into an integral type for formatting purposes.
Fact 2: Number of this weekday and total number of weekdays in year
sys_days first_wd = y/1/wd[1];
sys_days last_wd = y/12/wd[last];
auto total_wd = (last_wd - first_wd)/weeks{1} + 1;
auto n_wd = (sd - first_wd)/weeks{1} + 1;
cout << format("* It is {:%A} number ", wd) << n_wd << " out of "
     << total_wd << format(" in {:%Y}.\n}", y);

wd is the day of the week (Monday thru Sunday) computed at the top of this article.  To perform this computation we first need the dates of the first and last wd's in the year y.  y/1/wd[1] is the first wd in January, and y/12/wd[last] is the last wd in December.
The total number of wds in the year is just the number of weeks between these two dates (plus 1).  The sub-expression last_wd - first_wd is the number of days between the two dates.  Dividing this result by 1 week results in an integral type holding the number of weeks between the two dates.
The week number is done the same way as the total number of weeks except one starts with the current day instead of the last wd of the year: sd - first_wd.
Fact 3: Number of this weekday and total number of weekdays in month
first_wd = y/m/wd[1];
last_wd = y/m/wd[last];
total_wd = (last_wd - first_wd)/weeks{1} + 1;
n_wd = (sd - first_wd)/weeks{1} + 1;
cout << format("* It is {:%A} number }", wd) << n_wd << " out of "
     << total_wd << format(" in {:%B %Y}.\n", y/m);

This works just like Fact 2, except we start with the first and last wds of the year-month pair y/m instead of the entire year.
Fact 4: Number of days in year
auto total_days = LastDayOfYear - NewYears + days{1};
cout << format("* Year {:%Y} has ", y) << total_days/days{1} << " days.\n";

The code pretty much speaks for itself.
Fact 5 Number of days in month
total_days = sys_days{y/m/last} - sys_days{y/m/1} + days{1};
cout << format("* {:%B %Y} has ", y/m) << total_days/days{1} << " days.\n";

The expression y/m/last is the last day of the year-month pair y/m, and of course y/m/1 is the first day of the month.  Both are converted to sys_days so that they can be subtracted to get the number of days between them.  Add 1 for the 1-based count.
Use
info can be used like this:
info(December/26/2019);

or like this:
info(floor<days>(system_clock::now()));

Here is example output:
26 December 2019 is a Thursday

Additional facts
* It is day number 360 of the year, 5 days left.
* It is Thursday number 52 out of 52 in 2019.
* It is Thursday number 4 out of 4 in December 2019.
* Year 2019 has 365 days.
* December 2019 has 31 days.

Edit
For those who are not fond of the "conventional syntax", there is a complete "constructor syntax" that can be used instead.
For example:
sys_days NewYears = y/1/1;
sys_days first_wd = y/1/wd[1];
sys_days last_wd = y/12/wd[last];

can be replaced by:
sys_days NewYears = year_month_day{y, month{1}, day{1}};
sys_days first_wd = year_month_weekday{y, month{1}, weekday_indexed{wd, 1}};
sys_days last_wd = year_month_weekday_last{y, month{12}, weekday_last{wd}};


Q:

How to remove url /contact/index in contact page in Magento 2

When we entering contact form in footer from any page it redirect only - /contact/index/ Any options such that we can submit form in footer section not redirect /contact/index

After submit form it show -

I add contact form in footer section using this link - Magento2 contact form in CMS page, how to submit form without redirection and contact details not show in above footer section .Please reply me

A:

I assume that you want to redirect back to the page, where the customer was before sending the contact request.
To do so, you need to create a simple module. Please follow the steps below to accomplish this.
Step 1: Create the registration.php file app/code/Stack/ContactRedirect folder and paste the following content in it:
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Stack_ContactRedirect',
    __DIR__
);

Step 2: Create the module.xml file under app/code/Stack/ContactRedirect/etc folder with the following content:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Stack_ContactRedirect" setup_version="0.0.1"/>
</config>

Step 3: Define 2 plugins under app/code/Stack/ContactRedirect/etc/frontend/di.xml file:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Contact\Controller\Index\Post">
        <plugin name="contactus_before_submit" type="Stack\ContactRedirect\Plugin\BeforePost"/>
    </type>
    <type name="Magento\Contact\Controller\Index\Post">
        <plugin name="contactus_submit" type="Stack\ContactRedirect\Plugin\AfterPost"/>
    </type>
</config>

Step 4: Create before plugin class under app/code/Stack/ContactRedirect/Plugin/BeforePost.php with the following content:
<?php
namespace Stack\ContactRedirect\Plugin;

class BeforePost {
    protected $_redirect;
    protected $_coreSession;

    public function __construct(
    \Magento\Framework\App\Response\RedirectInterface $redirect, \Magento\Framework\Session\SessionManagerInterface $coreSession
    ) {
        $this->_redirect = $redirect;
        $this->_coreSession = $coreSession;
    }

    public function beforeExecute(\Magento\Contact\Controller\Index\Post $subject) {
        $this->_coreSession->start();
        $this->_coreSession->setRerererUrl($this->_redirect->getRefererUrl());
        return;
    }
}

Step 5: Create after plugin class under app/code/Stack/ContactRedirect/Plugin/AfterPost.php with the following content:
<?php
namespace Stack\ContactRedirect\Plugin;

class AfterPost {
    protected $_coreSession;

    public function __construct(
    \Magento\Framework\Session\SessionManagerInterface $coreSession
    ) {
        $this->_coreSession = $coreSession;
    }

    public function afterExecute(\Magento\Contact\Controller\Index\Post $subject, $result) {
        $this->_coreSession->start();
        return $result->setPath($this->_coreSession->getRerererUrl());
    }
}

Step 6: Your module is complete now. Run setup upgrade and then flush Magento's cache to see this module in action.
Note: There was a need to create before plugin also because in after plugin, there is no way to get the referral URL.


Q:

How can I troubleshoot this JSON method in DataTables gem?

I'm trying to implement the Railscast 340 that demos how to use DataTables, which looks like an awesome gem for my project.
My model is different, of course; but the datatables class the Mr Bates builds (very quickly), in order to do server-side processing, is rather complicated to follow. I got the source code, and basically attempted to follow along. My view comes up with zero records (but there are > 10,000 records), but does not break.
However, here is what the error message output from the rails server says just before it stops:
NameError (undefined local variable or method `genotypes' for #<GenotypesDatatable:0xa9e852c>):
  app/datatables/genotypes_datatable.rb:12:in `as_json'
  app/controllers/genotypes_controller.rb:8:in `block (2 levels) in index'
  app/controllers/genotypes_controller.rb:6:in `index'

Just before this, there appears to be this JSON error, which starts:
Started GET "/genotypes.json?sEcho=1&iColumns=8&sColumns=&iDisplayStart=0&iDisplayLength=10&mDataProp_0=...

The relevant part of the genotypes controller looks like this:
  def index
     respond_to do |format|
      format.html
      format.json { render json: GenotypesDatatable.new(view_context) }
    end
  end

And my genotypes model looks like:
class Genotype < ActiveRecord::Base
  attr_accessible :allele1, :allele2, :run_date
  belongs_to :gmarkers
  belongs_to :gsamples

end

My datatables class is given below. This is from Mr Bates code, modified (most likely incorrectly) to replace his Products model with my Genotypes model:
class GenotypesDatatable
  delegate :params, :h, :link_to, to: :@view

  def initialize(view)
    @view = view
  end

  def as_json(options = {})
    {
      sEcho: params[:sEcho].to_i,
      iTotalRecords: Genotype.count,
      iTotalDisplayRecords: genotypes.total_entries,
      aaData: data
    }
  end

private

  def data
    genotypes.map do |genotype|
      [
        link_to(genotype.name, genotype),
        h(genotype.category),
        h(genotype.released_on.strftime("%B %e, %Y")),
        genotype.run_date
      ]
    end
  end

  def Genotypes
    @Genotypes ||= fetch_Genotypes
  end

  def fetch_genotypes
    genotypes = Genotype.order("#{sort_column} #{sort_direction}")
    genotypes = genotypes.page(page).per_page(per_page)
    if params[:sSearch].present?
      genotypes = genotypes.where("name like :search or category like :search", search: "%#{params[:sSearch]}%")
    end
    genotypes
  end

  def page
    params[:iDisplayStart].to_i/per_page + 1
  end

  def per_page
    params[:iDisplayLength].to_i > 0 ? params[:iDisplayLength].to_i : 10
  end

  def sort_column
    columns = %w[gmarker gsample allele1 allele2 run_date]
    columns[params[:iSortCol_0].to_i]
  end

  def sort_direction
    params[:sSortDir_0] == "desc" ? "desc" : "asc"
  end
end

Any hints on how to troubleshoot (or fix!) this error much appreciated! (Getting this working for my project would be awesome!)
TIA,
rixter

A:

I'm not sure if this is it, but your class has a Genotype method with capital G, it should be all lowercase.


Q:

Java Business Rule to apply to setter to limit String length and insert space if limit exceeded

I have this setter method:
        public void setCgp_name(String cgp_name) {
        this.cgp_name = cgp_name;
    }

Basically when the user inserts a long string such as ARG,AUS,BEL,BRA,DNK,FRA,ITA,GBR,USA without any spaces between the commas this info is placed into a table and it will break the boundaries of the table. I am trying to apply a business rule to this setter so that if the user enters something like this : ARG,AUS,BEL,BRA,DNK,FRA,ITA,GBR,USA a space will be added in somewhere to prevent the formatting issue in the table. The word wrapping works when spaces are present but not with long strings.

A:

    public void setCgp_name(String cgp_name) {

        cgp_name = cgp_name.replaceAll(",[ ]*", ", ");

        this.cgp_name = cgp_name;
    }


Q:

why is this the answer to this riddle?

Entombed alive yet I survived
To glimpse once again at the sun
But legs to ground are shackled down
Curtailing all efforts to run
In body lies a dozen knives
My crown's sure to split and to smell
A robber's spear flew by my ear
Be thankful this ended so well
I read this riddle online, the answer to it is:

 a rose

but i can't understand why this is the answer, can anyone explain?

A:

Entombed alive yet I survived

 When you plant a rose seed in the ground, it’s “entombed alive” but it survives to become a rose

To glimpse once again at the sun

 When it grows up, a rose gets its energy from the sun

But legs to ground are shackled down

 Roses are rooted in the ground

Curtailing all efforts to run

 And can’t move/run

In body lies a dozen knives

 This references the thorns

My crown's sure to split and to smell

 This references the flower, which people like to smell

A robber's spear flew by my ear

 Potentially scissors, cutting the rose, or the spear of a bee’s sting ‘robbing’ the rose of its pollen?

Be thankful this ended so well


Q:

How do I display different records every time the user refreshes a page or enters another page?

$publicacoesIDrow2 = DBRead('publicacao', "LIMIT 4");

    <?php foreach ($publicacoesIDrow2 as $IDr2): ?>

            <a href="index.php?post=<?php echo $IDr2['title']?>"><img src="<?php echo $IDr2['capa']?>" alt="<?php echo $IDr2['alt']?>" class="card-img-top">

            <a href="index.php?post=<?php echo $IDr2['title']?>" class="card-title cardTitleLink">
<?php echo $IDr2['title']?>

<?php echo $IDr2['text']?>

    <?php endforeach; ?>

As you can see i putted a LIMIT 4. I want it to display a different record every time the user refreshes a page or enters another page. How can i do it?

A:

Try using
ORDER BY rand() LIMIT 4

instead of
LIMIT 4


Q:

Are `InputStream` and `Reader` essentially the same, and are `OutputStream` and `Writer` essentially the same?

In Java, InputStream and OutputStream deal with  byte[], and Reader and Writer with char[].

Do their input or output byte[] and char[] essentially have the same values?  (That is my impression, because a char and a byte in IO have the same value)
In other words, are InputStream and Reader essentially the same, and  are OutputStream and Writer essentially the same?

A:

They're not essentially the same, but they do the same sorts of things for different kinds of data.
InputStream and OutputStream work in bytes. You'd use them when dealing with non-textual information (such as an image).
Reader and Writer work in characters. You'd use them when dealing with textual information.
So "yes" and "no". :-) InputStream and Reader are both for reading information (a stream of bytes or a stream of characters, respectively), and OutputStream and Writer are both for writing information (a stream of bytes or a stream of characters, respectively). Which you use depends on what kind of data you're dealing with. The streams are byte-oriented. The readers/writers are character-oriented.
There are bridging classes between the two kinds of data:

InputStreamReader reads from an InputStream and converts bytes to characters using a CharSet (one provided explicitly or by name).
OutputStreamWriter does the converse: Converts characters to bytes (again via a CharSet) and writes the bytes to an OutputStream.

...but most Reader/Writer subclasses read from/write to sources/destinations that are already character-based, and so don't deal with bytes at all. For instance, StringReader reads characters from a string. Since the source (the string) is already character-based, the Reader doesn't ever deal with bytes, just characters.


Q:

Play 1.2.5 and Jedis

Simple question but how do I use Jedis with the play framework?
In the dependencies file I added
require:
...
- jedis -> jedis 2.1.0

Then I run play deps its not downloading the dependency.
I'm sure it is something simple but what am I doing wrong here.
Using Play Framework 1.2.5

A:

Sorry simple mistake in path to central maven repository.
should have been:
- redis.clients -> jedis 2.1.0


Q:

how to use yaml-cpp to modify a map node (delete key's value)

Taking this yaml node for example:
- flow:
    - do:
        ? command:
            - command1: command
            - command2: command
            - command3: command
          name: nameblock
          descr: descrblock
        : block_1

For the value "block_1", the key is a map node. How can I use yaml-cpp to delete the most inner value "block_1", so that the whole node becomes:
- flow:
    - do:
          command:
            - command1: command
            - command2: command
            - command3: command
          name: nameblock
          descr: descrblock

Any suggestion? Appreciated!

A:

You basically have to reassign the whole containing node, rather than delete anything. For example:
YAML::Node root = YAML::LoadFile("test.yaml");

// this is now the value of the "do" node
// explanation of each value:
// root[0]  - zeroth entry in the top-level sequence
// ["flow"] - value for the key "flow"
// [0]      - zeroth entry in the resulting sequence
// ["do"]   - value for the key "do"
YAML::Node node = root[0]["flow"][0]["do"];

// we're assuming there's only one entry in the map
// if you want a particular one, you can hunt for it
assert(node.size() == 1);

// this is the key of the first key/value pair
YAML::Node key = node.begin()->first;

// update the whole key/value pair to be just the key
node = key;


Q:

Property returns undefined

  private dataFromBackend: IprofileData;
  ngOnInit() {
    this.profileService.getEntities().subscribe(result => {
      this.dataFromBackend = result;
    });
    console.log(this.dataFromBackend);
  }

result returns all the data that I need but this.dataFromBackend returns undefined. I have also changed IprofileData to any but it still returns undefined. Why?

A:

console.log(this.dataFromBackend) shows up as undefined because it is getting executed before what's inside of the subscribe block. The subscribe is asynchronous and runs at a later point in time.
If you want to log it out to the console, you have to do what Tamas Szoke did in his first answer.
In the async/await way you have to convert the observable into a promise like so:
async ngOnInit() {
 this.dataFromBackend = await this.profileService.getEntities().pipe(take(1)).toPromise();
 console.log(this.dataFromBackend);
}

Keep in mind that converting it to a promise reacts once and completes. If you want to always react to emissions, you have to go the subscribe route.


Q:

Twitter Bootstrap and jQuery Validation Plugin - position or error text

I've created a form using the Twitter Bootstrap framework and have integrated the jQuery Validation Plugin. I have one form with a series of yes/no questions with radio buttons that I validate to ensure each question is not empty - this is working well.
One of the forms has some hidden table rows that appear if the user answers yes to a question. I can't seem to control the position of the error text ("this field is required") on these pages and the error text is not coloured red as per my CSS.
Here's the html:
<form class="form-horizontal" action="#" method="post" id="additional">
  <input type="hidden" name="recid" value="1">

      Question 1
      please answer yes or no to this question

      <input type="radio" name="AE_W4" id="AE_W4Yes" value="Yes" required>Yes

      <input type="radio" name="AE_W4" id="AE_W4No" value="No" required>No

      Please enter the description here

      <textarea name="AE_Details_W4" id="AE_Details_W4" rows="3" required></textarea>

          <button type="submit" class="btn btn-primary">Continue</button>
          <button type="reset" class="btn">Reset</button>

  </form>

and here's the script:
$().ready(function() {
    // validate the form when it is submitted
    $("#additional").validate();
        errorClass: "validateError";

    if($("#AE_W4Yes:checked").length != 0){
                // yes is checked... show the dependent fields
                    $("#adverseEventDetails").show();
                }else{
                    // hide it and blank the fields, just in case they have something in them
                    $("#adverseEventDetails").hide();
                    $("#AE_Details_W4").val("");
                }

    $("#AE_W4Yes").click(function () {
        $("#adverseEventDetails").show();
    });

    $("#AE_W4No").click(function () {
        $("#adverseEventDetails").hide();
        $("#AE_Details_W4").val("");
    });

});

I've setup a jsFiddle here that demonstrates this.

A:

Your code:
// validate the form when it is submitted
$("#additional").validate();
    errorClass: "validateError";

You have a serious syntax error in your code above.
There is nothing wrong with $("#additional").validate();, it simply initializes the plugin.
However, errorClass: "validateError"; cannot be floating around in your JavaScript all by itself like that.  If you want to employ the errorClass option, you must use it as per documentation, and list it inside .validate() along with any other rules and/or options...
// .validate() initializes the plugin
$("#additional").validate({
    // the rules and/or options for Validate() get listed here,
    // and they are separated by commas, not semicolons.
    errorClass: "validateError"
});


Q:

Why can't I find « booste » in the Collins Dictionary ?

I was reading news titled « Facebook booste son moteur de recherche pour mieux concurrencer Google » but couldn't find the word « booste » in Collins Dictionary. Why is this?

A:

Collins Dictionaries Online doesn't have it (it has booster, the English substantive; la fusée de lancement). It's a fashionable loanword from the English language but it is poorly compatible with French in terms of spelling and phonetics. Alternate word choices from the BDL :

gonfler, augmenter, stimuler, encourager, accroître, développer,
  renforcer, relancer, animer, hausser, dynamiser, doper (langue
  familière), donner du tonus, donner (ou redonner) de l’élan, donner un
  coup de fouet, donner un coup de pouce, remonter le moral, faire du
  battage, promouvoir, valoriser, faire la promotion, faire monter.

And from the Académie française:

Stimuler, régénérer, relancer, augmenter, accélérer, développer, faire
  croître.


Q:

Why does Linked questions allow anyone to see some details of a deleted post without checking their privileges?

Take for example the question (on Drupal.SE) about "How to process the results of a VBO enabled view via Rules?". It is deleted and in its Linked block (to the right, above its "Related" block) it shows 2 other questions. Users on that site with less than 10k reputation, or without a diamond, or not the author of the question (who happens to be me) only see a friendly "Page Not Found" message, which is all good.
However, by manually changing the URL to the Linked questions view of the question, any user can see it. Even with less than 10k reputation, even totally anonymous visitors. This is showing at least:

the title of the deleted question.
the title of the questions linked to the deleted question.

Why does Linked questions allow anyone to see some details of the deleted post without checking their privileges? That does not seem to be the case for  these variations for that same question:

The timeline page.
The revisions page.

Note: for deleted questions with 0 linked questions (such as this example), a similar Linked questions URL also reveals the title of the deleted question.

A:

I don't really see any issue with this. It doesn't really reveal any new information. If a < 10k user visits, e.g.:
https://drupal.stackexchange.com/questions/212520

You'll already see the title as the URL will be replaced with:
https://drupal.stackexchange.com/questions/212520/how-to-process-the-results-of-a-vbo-enabled-view-via-rules

Also, there's nothing you can really do with this information. There's no real consequences.
As for the linked questions, that doesn't seem to be an issue. They're just questions. If they themselves aren't deleted there's no reason to hide them.


Q:

Solve for t in overdamped 2nd order DE with non-integer constants

How would I rearrange an equation like this where there are 4 unique constants that are non-integers in front of the exponent and in front of e so as to solve for t?
$$x(t) = Ae^{Bt} + Ce^{Dt}$$
If A and C were equal this would be possible, but all four are unique and non-integers. Is it even possible?
I am trying to determine at what time $t$,  $x(t)$ will equal some value. Naturally there is a range for which this equation will have a solution but I can't seem to get anywhere with my algebra.
Thanks!

A:

As Paul commented, taking into account all the conditions described, only numeric methods will give the solution.
Where I see a potential problem is that you could have zero, one or two solutions.
Consider
$$x(t) = Ae^{Bt} + Ce^{Dt}$$
$$x'(t)= ABe^{Bt} + CDe^{Dt}$$
$$x''(t)= AB^2e^{Bt} + CD^2e^{Dt}$$
The first derivative would potentially cancel for
$$t_*=-\frac{\log \left(-\frac{A B}{C D}\right)}{B-D}$$ which does not exist in the real domain if $ABCD >0$. This is the "nice" case and Newton method will work like a charm if you consider for the zero of the better conditioned function
$$f(t)=\log(Ae^{Bt} + Ce^{Dt})-\log(x)\tag 1$$ which will almost look like a straight line.
For example, consider the case $A=234$, $B=0.345$, $C=567$, $D=0.123$, $x=123456$. Plot the original function and its transform to see how different is the problem.
Being lazy, let us start iterating with $t_0=0$; Newton method will generate the following iterates
$$\left(
\begin{array}{cc}
 n & t_n \\
 0 & 0 \\
 1 & 26.81753360 \\
 2 & 18.11584802 \\
 3 & 18.04389549 \\
 4 & 18.04388025
\end{array}
\right)$$
But, if $ABCD <0$ this would be a different story.


Q:

Opening a new activity using both spinners and a button

I basically have a spinner displaying an three items. I want it so that if Click on one of these three items and then click a button it will open up a new activity.
 String[] count;
Spinner s;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button view = (Button) findViewById(R.id.button);
    s = (Spinner)findViewById(R.id.spinner);
    count = getResources().getStringArray(R.array.country_array);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,count);
    s.setAdapter(adapter);
    view.setEnabled(false); // initially disable the button
    s.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position,
                                   long id) {
            view.setEnabled(true); // enable when user selects any item
        }
        // Listen to button click
        view.setOnClickListener( new OnClickListener() {

            @Override
            public void onClick(View v) {
                //start activity
                startActivity();
            }
        }
    });
    public void startActivity() {
        Intent intent = new Intent(YourCurrentActivity.this, NewActivity.class);
        startActivity(intent);
    }

A:

view.setEnabled(false); // initially disable the button
s.setOnItemSelectedListener(new OnItemSelectedListener() {

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position,
            long id) {
         view.setEnabled(true); // enable when user selects any item
    }

See how to listen to Button click: Android: how to handle button click
// Listen to button click
view.setOnClickListener( new OnClickListener() {

            @Override
            public void onClick(View v) {
                //start activity
                startActivity();
            }
        });

public void startActivity() {
    Intent intent = new Intent(YourCurrentActivity.this, NewActivity.class);
    startActivity(intent);
}


Q:

ListView does not refresh when string array model changes

My ListView doesnt show new entries in my model when they are added.
When a dialog opens I copy a QStringList from a C++ item into a Qml property.
The user then modifies the array using provided controls (add, modify, remove).
Sadly the ListView doesnt update when I modify the property. The property is modified correctly (as seen by debugging output).
How can I make the ListView updating automatically using data binding?
import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    property var things

    Component.onCompleted: things = [] // normally retrieved from C++ QStringList

    ColumnLayout {
        anchors.fill: parent

        RowLayout {
            Layout.fillWidth: true

            TextField {
                Layout.fillWidth: true
                id: theTextField
            }

            Button {
                Layout.fillWidth: true
                text: qsTr("Append")
                onPressed: {
                    things.push(theTextField.text)
                    console.log(things)
                }
            }

            Button {
                Layout.fillWidth: true
                text: qsTr("Remove")
                onPressed: {
                    var index = things.indexOf(theTextField.text)
                    if(index == -1)
                        console.warn('Not found!')
                    else
                        things.splice(index, 1)
                    console.log(things)
                }
            }

            Button {
                Layout.fillWidth: true
                text: qsTr("Clear");
                onPressed: {
                    things = [];
                    console.log(things)
                }
            }
        }

        ListView {
            id: listView

            Layout.fillWidth: true
            Layout.fillHeight: true
            model: things
            delegate: Label {
                text: modelData
            }
        }
    }
}

A:

The reason for that is, that there is no thingsChanged-signal when using a function to modify the things. The reference stored in things will stay the same, no matter what you do.
For the data models such as ListModel this is the same, but there exist special signals many of which are used to indicate to any view, that it should update it's content.
If you desperately need to use arrays, you need to call thingsChanged() manually, whenever you changed something to the arrays content. But as this indicates only that the whole array has changed, one of the major strengths of a View are void - the ability to change only what has been changed.
When a View reacts to a thingsChanged-signal, it will destroy all current delegates and then recreate them again, no matter whether anything will be different.
If you use a ListModel or QAbstractItemModel-descendent, the View can insert single instances of new delegates, remove or alter them.


Q:

How to pass a char pointer by address to be accepted to char**?

I have a struct, known as Shader, which holds the following information:
struct Shader {
    enum ValueType{ VT_Attribute, VT_Uniform, VT_Varying };
    GLuint Memory;
    GLenum Type;
    char* Source;
    char* Name;
    std::map< Shader::ValueType, float* > Values;
};

Yet, if I do something like:
glShaderSource( shaderMem, 1, &shader.Source, NULL );
I get the following error:
error: invalid conversion from 'char* const*' to 'const char**'
Why is this happening?

A:

It happens because shader is const at that point. Assuming glShaderSource won't attempt to write the contents of its 3rd argument, then you can const_cast the const away:
glShaderSource( shaderMem, 1, const_cast< char** >( &shader.Source ), NULL );


Q:

How to pass a 2d array from JavaScript to script tag in ejs?

I am trying to pass a 2d array of false values from an index.js file of my project to a script section of an ejs file.
index.js
app.get('/nextpage',(req,res)=>{
    var arr = function I have to make a 2d array ;)
    res.render('pages/nextpage.ejs',{
        arr: arr
    });
});

based on a few stack answers from others' related posts, I tried the following implementation in my ejs file:
nextpage.ejs

    <div id = "script" arr= "<%=arr%>" >

I thought I was close. I tried to pass in a 3x3 array and this is what I got:

instead of rendering a button for each value in the 2d array, it renders a button for each character in the string. What I am looking for is the ability to display buttons for each entry of the 2d array. More specifically, how do I allow the script tag of an ejs file to have access to the same variables that the rest of the file has access to?

A:

If you pass data from backend to frontend, you have to properly serialize it, usually as JSON:
 "<%=JSON.stringify(arr)%>"
// ->
var arr = JSON.parse( document.getElementById("script").getAttribute('arr'));

But that is just ugly. Why not just directly generate the buttons with EJS?:
<% for(const sub of arr) { %>
  <% for(const el of sub) { %>
    <button> <%= el %> </button>
  <% } %>
<% } %>


Q:

Area links don't generate in asp.net-core-mvc

Following this guide I've been creating an Admin area:
https://docs.asp.net/en/latest/mvc/controllers/areas.html
I can navigate to the admin pages by directly typing in the url, however I can't get links to generate
I've tried placing the following on the Admin index.cshtml:

Admin Index

Admin Index

Admin Index

Yet the all end up being non clickable anchors (no href)
In fact, when I view source, I actually still see the "asp-action" etc tags
Admin Index

MVC doesn't seem to be processing the link helper tags?
Any idea what I've missed? Perhaps a configuration step somewhere?
Thanks

A:

Got it!
I needed to add a _ViewImports.cshtml to my Areas folder
_ViewImports.cshtml needs the following inside:
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

Odd how it wasn't mentioned in the tutorial


Q:

How do I communicate from JS to Swift

I'm creating a hybrid app and I'm trying to figure out how to pass some data from the WKWebView to the native app.
I've been trying to figure this out for days and I can't seem to find anything! There seems to be very little info online about this, and everything I do find, is the other way around (Swift to JS, not JS to Swift).
I've tried using URL variables, but the Webview has to reload for Swift to recognize that it changed. I tried using WKScriptMessageHandler, but I can't find any good documentation about it, and it seems very complicated.
There must be some easy way to accomplish this.
Any ideas?
I would be really grateful to anyone who can help me with this.

A:

It's not that complicated actually.
Firstly you have to add the script message handler into the content controller.
let contentController = WKUserContentController()
contentController.add(self, name: "derp") //name is the key you want the app to listen to.

Next up you have to assign the content controller into the configuration.
let config = WKWebViewConfiguration()
config.userContentController = contentController

then you need to assign the configuration to your web view.
let webView = WKWebView(frame: CGRect.zero, configuration: config) //set your own frame

and for the JS side.
var message = {'fruit':'apple'};
window.webkit.messageHandlers.derp.postMessage(message);

Lastly you have to let your view controller (I'm assuming that the webView is in a view controller) conform to the WKScriptMessageHandler protocol. I've added the rest of the codes into a sample view controller as requested.
class MyViewController: UIViewController, WKScriptMessageHandler {

    override func viewDidLoad() {

        super.viewDidLoad()

        let contentController = WKUserContentController()
        contentController.add(self, name: "derp")

        let config = WKWebViewConfiguration()
        config.userContentController = contentController

        let webView = WKWebView(frame: self.view.frame, configuration: config) //you can consider using auto layout though
        self.view.addSubview(webView)

        //load your url here
    }

    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {

        //handle script messages here
        //message.name is "derp"
        //message.body is ["fruit":"apple"]
    }
}


Q:

php + oauth: is it possible to make oauth-request from the domain different from app domain

I'm having an app(site), e.g. on Facebook, domain is mydomin.com. Just wondering if there a way to make an oauth request with appid of that app from domain different from mydomin.com?
Thank you in advance!
UPD: please do not propose solutions specific to concrete oauth server.

A:

When editing your App in Facebook developers page there's a App Domains field where you can add multiple domains:

All requests coming from the added domains will be allowed to interact with the app using AppId and AppSecret.


Q:

problema com referencia de evento do click dentro de uma div

Estou tendo um problema de referência no evento de click, não sei o que está evitando a funcionalidade da função de click do jquery, eis o meu código abaixo para análise:
div = $('#container_principal_box_pesquisa');

                            contador =1;

                            for(i=0; i<data.length; i++){
                              if(i < 5){
                                 div.append('
'+data[i]+'
');
                                 id = $('#box_pesquisa_'+contador);
                                 div.find('img').width(60);
                                 div.find('img').height(60);
                                 contador++;
                              }
                            }

                              box1 = $("#box_pesquisa_1");
                              box2 = $("#box_pesquisa_2");
                              box3 = $("#box_pesquisa_3");
                              box4 = $("#box_pesquisa_4");
                              box5 = $("#box_pesquisa_5");

                              box1.click(function(){
                                alert('teste');
                              });

O evento de click das div's box1...até 5 que estão dentro do container_principal_box_pesquisa não funcionam, mesmo fazendo a referência, já quando eu referencio o evento de click da div cujo id  é o container_principal_box_pesquisa ele funciona normalmente. O que poderia ser? alguém pode me ajudar?

A:

Na medida em que for criando as divs, atribua o evento click.
$('

nova div '+contador+'
').appendTo(div)
.on('click', function() {....});

Exemplo:

var div = $('#container_principal_box_pesquisa');

contador =1;

for(i=0; i<10; i++){

if(i < 5){

$('
nova div '+contador+'
').appendTo(div).on('click', function() {

console.log($(this).attr('id'));

});

contador++;

}

}


Q:

BizTalk HL7 send pipeline error due to line breaks in empty XML elements

I am mapping to an HL7 A31 message using the BizTalk mapper.  The map has several inline XSLT scripting functoids.
When the XML is put through the HL7 send pipeline, it generates an error:

The element 'ROL_11_OfficeHomeAddress' has an invalid structure

If I look at the suspended message, I can see why this has happened.  The ROL_11 element is empty, and looks like this:
    <ROL_11_OfficeHomeAddress>
    </ROL_11_OfficeHomeAddress>

Between the opening and closing tags, there is a line break and several spaces/tabs due to indenting.  This is exactly as generated by the XSLT and I believe it is the line break that is causing the error.
I could wrap the XSLT in an <xsl:if> statement to check for a value before writing the XML.  However this problem is occurring in many places and it seems overkill to wrap every single element like this.
What I really want is for BizTalk to automatically convert the element to an empty one, like this:
<ROL_11_OfficeHomeAddress />

I believe this would solve the problem.  Is there any way I can tell it to do that?
Things I have already tried:

Using <xsl:strip-space> but that raised its own error.  I think this is because BizTalk wraps the inline XSLT in its own code and thus strip-space was specified in the wrong place.
Changing the map's grid properties to set Indent to No in the hope the whitespace would be removed.  This had no effect on the XML seen in the suspended message.
Adding the registry key for legacy whitespace handling as per this guidance.  Again, this appeared to have no effect at all.

A:

If you convert your entire map into XSLT, the below will strip out newlines and whitespace and leave you with an empty tag if there isn't anything but whitespace:
<xsl:element name="ROL_11_OfficeHomeAddress">
  <xsl:if test="normalize-space(ROL_11_OfficeHomeAddress)">
    <xsl:value-of select="normalize-space(ROL_11_OfficeHomeAddress)" />
  </xsl:if>
</xsl:element>

Edit:
Biztalk usually generates XSLT like the following in a typical 1:1 nillable element mapping
    <xsl:variable name="var:v2" select="string(ns0:ROL_11_OfficeHomeAddress/@xsi:nil) = 'true'" />
    <xsl:if test="string($var:v2)='true'">
      <ns0:ROL_11_OfficeHomeAddress>
        <xsl:attribute name="xsi:nil">
          <xsl:value-of select="'true'" />
        </xsl:attribute>
      </ns0:ROL_11_OfficeHomeAddress>
    </xsl:if>
    <xsl:if test="string($var:v2)='false'">
      <ns0:ROL_11_OfficeHomeAddress>
        <xsl:value-of select="ROL_11_OfficeHomeAddress/text()" />
      </ns0:ROL_11_OfficeHomeAddress>
    </xsl:if>

So if you did use <xsl:strip-space> it would mean that the element would map to <ROL_11_OfficeHomeAddress></ROL_11_OfficeHomeAddress> if whitespace only, unless you went through the map changing it back to <xsl:element>.
What you could try is to use a call template like the below (nodeXfrm is a node)
<xsl:template name="StripElement">
    <xsl:param name="nodeXfrm"></xsl:param>
    <xsl:variable name="nodeName">
        <xsl:value-of select="local-name($nodeXfrm)"></xsl:value-of>
    </xsl:variable>
    <xsl:element name="{$nodeName}">
        <xsl:if test="normalize-space($nodeXfrm)!=''">
            <xsl:value-of select="$nodeXfrm/text()"/>
        </xsl:if>
    </xsl:element>
</xsl:template>

And then within your map you can call the template for each element you need stripped in this way
  <xsl:call-template name="StripElement">
    <xsl:with-param name="nodeXfrm" select="ROL_11_OfficeHomeAddress"></xsl:with-param>
  </xsl:call-template>

An XSLT guru might be able to do this more elegantly


Q:

Cast object pointer to char array

unsigned char *check = NULL;
check = (dynamic_cast<unsigned char *>( ns3::NetDevice::GetChannel() ));

This is what I am trying. But the error is:
error: cannot dynamic_cast ‘ns3::NetDevice::GetChannel() const()’ (of type ‘class       ns3::Ptr<ns3::Channel>’) to type ‘unsigned char*’ (target is not pointer or reference to class)

I also tried:
reinterpret_cast

But it doesn't work at all.

A:

The return type of ns3::NetDevice::GetChannel() is some kind of custom smart pointer; without seeing the definition of that, we can only guess at how you can convert that into a raw pointer.
Perhaps it implements a conversion operator, operator T*(), although that's generally regarded as a bad idea since it makes it unintended conversions too easy to do by accident. In that case, you could do:
void * check = ns3::NetDevice::GetChannel();

Otherwise, perhaps it has a member function to convert to a raw pointer. The standard smart pointers conventionally call this get():
void * check = ns3::NetDevice::GetChannel().get();

If it doesn't offer that, and you really do want to get a raw pointer, then you could dereference it and take a pointer to the dereferenced object (assuming it supports dererencing; otherwise, it's a bit odd to call it a pointer at all):
void * check = &*ns3::NetDevice::GetChannel();

Once you have a void *, you can use static_cast to change it into unsigned char *, if that's what you want. Be careful what you do with it, since messing around with the bytes of an object can easily lead to undefined behaviour.
UPDATE: if ns3::Ptr is the template documented here, then you can get the raw pointer using:
void * check = PeekPointer(ns3::NetDevice::GetChannel());


Q:

How to make a thumbnail of a static image using sorl-thumbnail

I have a user model with an avatar field in my Django project:
class User(AbstractBaseUser):

    avatar = models.ImageField(
        null=True,
        blank=True,
        upload_to='user/avatar/',
    )

The avatar is not required, so I would like to use a default image if a user hasn't uploaded one. On the other hand I don't want to use a default parameter in order to be able to change the default avatar in the future for all users:
class User(AbstractBaseUser):

    avatar = models.ImageField(
        null=True,
        blank=True,
        default='defaults/no-avatar.png',
        upload_to='user/avatar/',
    )

So I ended up writing a get_avatar method that returns an image if the avatar exists or a path to a default static image:
@property
def get_avatar(self):
    if self.avatar:
        return self.avatar
    return '{0}defaults/no-avatar.png'.format(settings.STATIC_URL)

But in this case sorl-thumbnail doesn't generate a thumbnail for a default image
{% thumbnail user.get_avatar "46x46" crop="center" as im %}
    <img title="{{ user }}" src="{{ im.url }}" class="img-circle" />
{% endthumbnail %}

and returns the following error:
ERROR 2014-09-22 12:49:48,020 thumbnail :: Thumbnail tag failed:
Traceback (most recent call last):
  File "/Users/vera/.virtualenvs/my_app/lib/python2.7/site-packages/sorl/thumbnail/templatetags/thumbnail.py", line 45, in render
    return self._render(context)
  File "/Users/vera/.virtualenvs/my_app/lib/python2.7/site-packages/sorl/thumbnail/templatetags/thumbnail.py", line 97, in _render
    file_, geometry, **options
  File "/Users/vera/.virtualenvs/my_app/lib/python2.7/site-packages/sorl/thumbnail/base.py", line 56, in get_thumbnail
    source_image = default.engine.get_image(source)
  File "/Users/vera/.virtualenvs/my_app/lib/python2.7/site-packages/sorl/thumbnail/engines/pil_engine.py", line 12, in get_image
    buf = StringIO(source.read())
  File "/Users/vera/.virtualenvs/my_app/lib/python2.7/site-packages/sorl/thumbnail/images.py", line 121, in read
    return self.storage.open(self.name).read()
  File "/Users/vera/.virtualenvs/my_app/lib/python2.7/site-packages/django/core/files/storage.py", line 33, in open
    return self._open(name, mode)
  File "/Users/vera/.virtualenvs/my_app/lib/python2.7/site-packages/django/core/files/storage.py", line 159, in _open
    return File(open(self.path(name), mode))
  File "/Users/vera/.virtualenvs/my_app/lib/python2.7/site-packages/django/core/files/storage.py", line 260, in path
    raise SuspiciousFileOperation("Attempted access to '%s' denied." % name)

I tried to rewrite that method in order to return an image instead:
from django.core.files.images import ImageFile

@property
def get_avatar(self):
    if self.avatar:
        return self.avatar
    return ImageFile(open(os.path.join(settings.STATIC_ROOT, 'defaults/no-avatar.png'), 'r'))

but I got a similar error:
ERROR 2014-09-22 12:52:18,448 thumbnail :: Thumbnail tag failed:
Traceback (most recent call last):
  File "/Users/vera/.virtualenvs/my_app/lib/python2.7/site-packages/sorl/thumbnail/templatetags/thumbnail.py", line 45, in render
    return self._render(context)
  File "/Users/vera/.virtualenvs/my_app/lib/python2.7/site-packages/sorl/thumbnail/templatetags/thumbnail.py", line 97, in _render
    file_, geometry, **options
  File "/Users/vera/.virtualenvs/my_app/lib/python2.7/site-packages/sorl/thumbnail/base.py", line 56, in get_thumbnail
    source_image = default.engine.get_image(source)
  File "/Users/vera/.virtualenvs/my_app/lib/python2.7/site-packages/sorl/thumbnail/engines/pil_engine.py", line 12, in get_image
    buf = StringIO(source.read())
  File "/Users/vera/.virtualenvs/my_app/lib/python2.7/site-packages/sorl/thumbnail/images.py", line 121, in read
    return self.storage.open(self.name).read()
  File "/Users/vera/.virtualenvs/my_app/lib/python2.7/site-packages/django/core/files/storage.py", line 33, in open
    return self._open(name, mode)
  File "/Users/vera/.virtualenvs/my_app/lib/python2.7/site-packages/django/core/files/storage.py", line 159, in _open
    return File(open(self.path(name), mode))
  File "/Users/vera/.virtualenvs/my_app/lib/python2.7/site-packages/django/core/files/storage.py", line 260, in path
    raise SuspiciousFileOperation("Attempted access to '%s' denied." % name)
SuspiciousFileOperation: Attempted access to '/Users/vera/workspace/my-website/static/defaults/no-avatar.png' denied.

A:

sorl-thumbnail used storage functionality. Django delegates decisions about how and where to store files to a file storage system. This is the object that actually understands things like file systems, opening and reading files, etc. Django ships with a django.core.files.storage.FileSystemStorage class which implements basic local filesystem file storage. By default, Django stores files locally, using the MEDIA_ROOT and MEDIA_URL settings.
So in your case django try find image under MEDIA_ROOT, but you have saved the image under STATIC_ROOT.
How fix that
As hotfix you can try move image under MEDIA_ROOT and will change path in get_avatar method.
Or you can try write custom storage, which will work with both folders. Example custom storage.


Q:

Doing a PHP While Loop Inside A While Loop

I am trying to do a php while loop inside another php while loop but when I get to the second loop it doesn't go back to the first one and reloop again Here is the code I am using:
Database connection string is in a separate module. The first while Loop should loop twice but what I think is happening when it gets to the second database while loop that loop returns positive and it affects the first loop so I only get 1 loop from the first loop. Can someone please tell me how I could change this to avoid this problem?
These are the two loops below from a database:
while($row = $result->fetch_assoc()) {

    // Show/Hide Regions:

    error_reporting(-1);
    ini_set('display_errors', 'On');

    //Access our class.
    $db_Class = new db_Class;
    $conn = ($db_Class->db_conn());

    $sql = "SELECT id, region FROM tbl_region;";
    $result = $conn->query($sql);

          if ($result->num_rows > 0) {
        // output data of each row
        $counter = 0; //Set count to 1
        while($row = $result->fetch_assoc()) {
            $counter++; //Increment counter by 1's
            $rID = $row["id"];
            ?>
                Output Region Here!

               <?php

            //Output companies for this region.

            $sql = "SELECT
                    tbl_company.company_name,
                    tbl_company.group_number,
                    tbl_region.region
                    FROM
                    tbl_region
                    INNER JOIN tbl_company ON tbl_company.region_id = tbl_region.id
                    WHERE
                    $rID = tbl_company.region_id
                    ORDER BY
                    tbl_company.company_name ASC
                    ";
            $result = $conn->query($sql);

            if ($result->num_rows > 0) {
                // output data of each row
                while($row = $result->fetch_assoc()) {

                    echo $row["company_name"]."
";

                    }
                }
            echo "A";
            echo '
';
            }
            } ?>

A:

Change inner loop $row and $result with any other name..for example I have done $rowInner and $resultInner here.
<?php
while($row = $result->fetch_assoc()) {
    if ($result->num_rows > 0) {
        $counter = 0; //Set count to 1
        while($row = $result->fetch_assoc()) {
            $counter++; //Increment counter by 1's
            $rID = $row["id"];
            ?>
                Output Region Here!

            <?php
            $sql = "SELECT
                    tbl_company.company_name,
                    tbl_company.group_number,
                    tbl_region.region
                    FROM
                    tbl_region
                    INNER JOIN tbl_company ON tbl_company.region_id = tbl_region.id
                    WHERE
                    $rID = tbl_company.region_id
                    ORDER BY
                    tbl_company.company_name ASC
                    ";
            $resultInner = $conn->query($sql);
            if ($resultInner->num_rows > 0) {
                while($rowInner = $resultInner->fetch_assoc()) { // Change $row to $rowInner
                    echo $rowInner["company_name"]."
";

                }
            }
            echo "A";
            echo '
';
        }
    }
}
?>


Q:

mysql Select AS

i need to do the following select:
select distinct type as option from pages

but i keep getting errors.
Can you help me please?

A:

option is a MySQL reserved word.
Enclose it in back-ticks or use a different non-reserved-word alias.


Q:

Toggle link with content

I've this code :
Link1
Link2
Link3

Content link 1

Content link 2

Content link 3

I want that each link matches to its div (Link1 => Content link 1, Link2 => Content link 2, ect .....)
I wrote this Javascript
        $('div').hide();

             $(".btn").click(function () {
               $(this).next("div").slideToggle('slow');
           });

But it does not work. If someone could help me.

A:

$('div').hide();

$(".btn").click(function () {
  var index = $(this).attr("data-index");
  $("div[data-index!='"+index+"']").slideUp('slow', function(){
    $("div[data-index='"+index+"']").delay(400).slideDown();
  });

});

Link1
Link2
Link3

Content link 1

Content link 2

Content link 3

A:

You need to create a link between each content div and the button to activate it. You also need to start all content divs as hidden.

$('.btn').click(function(elm) {
  $('.content').hide();
  console.log($(this).attr('data-link'))
  var id = $(this).attr('data-link')
  $('#' + id).slideToggle('slow')
})
.content {
  display: none;
}

Link1
Link2
Link3

Content link 1

Content link 2

Content link 3


Q:

Error:Execution failed for task ':app:transformClassesWithDexForDebug'. finished with non-zero exit value 1

Error:Execution failed for task ':app:transformClassesWithDexForDebug'.

com.android.build.api.transform.TransformException: java.lang.RuntimeException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'E:\androidWare\jdk1.7\bin\java.exe'' finished with non-zero exit value 1
  My app gradle file

apply plugin: 'com.android.application'

android {
compileSdkVersion 23
buildToolsVersion "23.0.3"

defaultConfig {
    applicationId "com.wjc.wjcrun"
    minSdkVersion 17
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'),
   'proguard-rules.pro'
    }
  }
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.2.1'
}
dependencies {
compile "org.igniterealtime.smack:smack-android:4.1.0-rc1"
compile "org.igniterealtime.smack:smack-tcp:4.1.0-rc1"
 }

Here is Project Build Gradle
buildscript {
repositories {
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:2.1.3'
   }
}
  allprojects {
  repositories {
    jcenter()
  }
}
 task clean(type: Delete) {
delete rootProject.buildDir
}

A:

Use your build.gradle like this.
apply plugin: 'com.android.application'

android {
compileSdkVersion 23
buildToolsVersion "23.0.3"

defaultConfig {
    applicationId "com.wjc.wjcrun"
    minSdkVersion 17
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'),
   'proguard-rules.pro'
    }
  }
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.2.1'

compile "org.igniterealtime.smack:smack-android:4.1.0-rc1"
compile "org.igniterealtime.smack:smack-tcp:4.1.0-rc1"
 }
}


Q:

Using OVH/SYS failover IP as server's main IP

Good morning
my server is a dedicated from SoYouStart. I purchased 8 failover IP.
OS is Centos 7.4 + CloudLinux. The machine will run a cPanel box.
What I need is associate the cPanel and CloudLinux licenses to one of the failover IP's rather than the main server IP.
In order to check the license, both cPanel and CloudLinux check the result of
#hostname --ip-address

or
curl -L http://cpanel.net/showip.cgi

I mean that the IP resulting from above command is the IP used for the license.
My question is: how I can configure network in order that #hostname --ip-address returns one of the failover IP's?
I searched on cPanel and CL docs/forums but not found a solution.
Thank you very much.

A:

There may be OVH-specific requirements to change the primary IP address on your server, so check your customer dashboard: for one you should switch to a stock kernel from the OVH netboot kernel if you haven't all ready. You also need to change your cPanel license to the new address at your reseller, which is usually buycpanel.net.
Changing IP addresses should be a case of editing /etc/sysconfig/network-scripts/ifcfg-eth0 with your required address as IPADDR, netmask and the gateway from your address range allocation. Restart the network using systemctl restart networking or just reboot.
Set your hostname using hostname and then edit /etc/hosts to link the new primary IP to the hostname.
Change the cPanel IP address with /usr/local/cpanel/cpkeyclt and confirm that this is validating with curl -L http://cpanel.net/showip.cgi.


Q:

Adding Session / Array to SQL Database

I have the session created and it stores the data, that is working 100%;
I have a foreach loop that converts all the session data into an array of in_fields and in_values.
But the form is not submitting to the database, please assist !
    // sql fields and values
$in_fields = array();
$in_values = array();

foreach($_SESSION as $key => $value) {
    if(!empty($value)) {
        $value = sql_escape($value);
        $key = explode("#",$key);

            $in_fields[] = "`{$key[0]}`";
            $in_values[] = "'{$value}'";
    }
}

if(!empty($in_fields)) {

    $sql  = "INSERT INTO wills(";
    $sql .= implode(", ",$in_fields);
    $sql .= ") VALUES (";
    $sql .= implode(", ",$in_values);
    $sql .= ")";

if(executeSql($sql)) {
        $id = mysql_insert_id();
                executeSql($sql);
            }
        }

I have created a print_r of $in_fields and $in_values and it displays as an array.
The error i am receiving now:
Warning: trim() expects parameter 1 to be string, array given in E:\xampp\htdocs\sc\form\inc\functions.php on line 22

Database query error.
Unknown column 'step' in 'field list'
LIne 22 from Functions.php
    $value = get_magic_quotes_gpc() ? stripslashes($value) : trim($value);

A:

Database query error. Unknown column 'step' in 'field list'

do you need any further explanations?


Q:

How to understand the regular expressions while doing any validations

I found this reg expression for email validation. But it's not clear me what it's doing and difficult for me to understand what is this Regular Expression doing and how can I learn to understand it.
[a-z0-9]+([-+._][a-z0-9]+){0,2}@.*?(\.(a(?:[cdefgilmnoqrstuwxz]|ero|(?:rp|si)a)|b(?:[abdefghijmnorstvwyz]iz)|c(?:[acdfghiklmnoruvxyz]|at|o(?:m|op))|d[ejkmoz]|e(?:[ceghrstu]|du)|f[ijkmor]|g(?:[abdefghilmnpqrstuwy]|ov)|h[kmnrtu]|i(?:[delmnoqrst]|n(?:fo|t))|j(?:[emop]|obs)|k[eghimnprwyz]|l[abcikrstuvy]|m(?:[acdeghklmnopqrstuvwxyz]|il|obi|useum)|n(?:[acefgilopruz]|ame|et)|o(?:m|rg)|p(?:[aefghklmnrstwy]|ro)|qa|r[eosuw]|s[abcdeghijklmnortuvyz]|t(?:[cdfghjklmnoprtvwz]|(?:rav)?el)|u[agkmsyz]|v[aceginu]|w[fs]|y[etu]|z[amw])\b){1,2}

A:

Use https://regex101.com set it to the correct Flavor in your case ECMAScript (Javascript) and it will give you a break down of what it's doing in the Explanation box,
While I was writing this and getting the screenshot it appears @Rajesh added this as a comment as well.


Q:

Изменение копии Map

Подскажите:
HashMap<String,String>data=new HashMap<>();
data.put("Имя","Вася");
data.put("Фамилия","Иванов");
HashMap<String,String>data11=data;
data.put("Имя","Петя");
System.out.println(data11.get("Имя"));

Каким образом можно сделать, чтобы второе Map сохранило значение?

A:

Новая ссылка на тот же объект (то, что в вопросе):
HashMap<String, String> data11 = data;

var data = {};
data["Имя"] = "Вася";
data["Фамилия"] = "Иванов";
var data11 = data;
data["Имя"] = "Петя";
console.log(data11["Имя"]);

Новый объект с теми же данными (то, что Вы хотите):
HashMap<String, String> data11 = new HashMap<String, String>(data);

var data = {};
data["Имя"] = "Вася";
data["Фамилия"] = "Иванов";
var data11 = Object.assign({}, data);
data["Имя"] = "Петя";
console.log(data11["Имя"]);


Q:

how to use odata services to create model dynamically from manifest.json

I am very new to UI5, I am working on an application which requires me to create models based on the request made from the browser (client).
If I consume all the odata services beforehand & use them according to the request made, it will become too heavy unnecessarily.
is there any way, this can be done dynamically?

A:

I think your question title and the question content might be contradictory so I am placing my suggestions separately.

how to use odata services to create model dynamically from manifest.json

In your manifest.json file, locate the "sap.app" section/property and then add a datasource as follows:
"dataSources": { //used data sources -> ui5-related information stored in sap.ui5 namespace (unique inside the app)
         "modelalias": { //key is alias which is used below in e.g. sap.ui5 ...
             "uri": "/sap/opu/odata/snce/PO_S_SRV;v=2/" , //mandatory; version is part of uri, e.g. ";v=2", default is 1
             "type": "OData" , //OData (default)|ODataAnnotation|INA|XML|JSON
             "settings": { //data-source-type-specific attributes (key, value pairs)
                 "odataVersion": "2.0" , //possible values: 2.0 (default), 4.0
                 "annotations": [ "equipmentanno" ], //filled e.g. for Smart Template
                 "localUri": "model/metadata.xml" //relative url to local metadata
    "maxAge": 360 //time in seconds
    }
         }

To instantiate this model with the alias "mymodel", you can add an entry into the manifest.json under "sap.ui5" as follows:
    "models": {
...
            "mymodel": { //empty string "" is the default model
                "preload": true; //indicator that the model will be created immediately after the manifest is loaded by component factory and before the component instance is created
                "dataSource": "modelalias", //reference of dataSource under sap.app - only enhance it with more settings for UI5 if needed
                "settings": {
                }
            }
        },

Now the manifest file will instantiate "mymodel" based on your odata uri in "datasources" and then set the model onto your Component.js. So when your application starts, you can access the model in any controller using:
this.getOwnerComponent().getModel("mymodel")

If I consume all the odata services beforehand & use them according to
  the request made, it will become too heavy unnecessarily. is there any
  way, this can be done dynamically?

Your assumption is that creating a model will slow the app startup. This may not always be true since:

The model creation is very quick
Reading data is what takes time and model instantiation
ODataModels work asyncronously be default so calling .read or .write are operations that can be managed asynchronously

Special case: If you wish to pre-fetch all your data in advance (at startup) I would advise that you ensure that you utilize filters like $select, $top and $skip on your Gateway service to implement growing list like behavior.
Hope that helps you.

More information on manifest.json: Link
Growing List: Link
ODataModel Examples: Link


Q:

How to switch creation direction in recyclerView

hi, I have a some question.
I want to create recyclerview's item from left. but they are currently right.
Could you give me a little hint?
All layout setting are already 'Horizontal'
Thank you for read my question.
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:orientation="horizontal">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycle_view"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scrollbars="horizontal"
        android:layout_gravity="left"
        >

    </android.support.v7.widget.RecyclerView>

public class PostAdapter extends RecyclerView.Adapter<Bitmap_ViewHolder> {

    private ArrayList<Bitmap> items=new ArrayList<>();

    public PostAdapter(ArrayList<Bitmap> items){
        this.items=items;
    }

    //뷰홀더 객체 생성
    @Override
    public Bitmap_ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v=LayoutInflater.from(parent.getContext()).inflate(R.layout.add_imagelist,parent,false);
        return new Bitmap_ViewHolder(v);
    }

    // 데이터를 뷰홀더와 바인딩
    @Override
    public void onBindViewHolder(Bitmap_ViewHolder holder, int position) {
        Bitmap item=items.get(position);
        holder.iv.setImageBitmap(item);
    }

    // 추가
    public void add(Bitmap pd){
        items.add(pd);
        notifyDataSetChanged();
    }

    // 특정 위치 아이템 삭제
    public void removeItem(PostData pd, int index){
        items.remove(index);
        notifyItemRemoved(index);
    }

    public ArrayList<Bitmap> getAllItem(){
        return items;
    }

    //데이타 수
    @Override
    public int getItemCount() {
        return items.size();
    }
}

public class Bitmap_ViewHolder extends RecyclerView.ViewHolder {
    ImageView iv;
    public Bitmap_ViewHolder(View v){
        super(v);
        iv=(ImageView)v.findViewById(R.id.addlist_picture);
    }
}

@Override
public void onClick(View v) {
    switch (v.getId()){
        //사진 추가 눌렸을 때
        case R.id.iv_picture:
            openGallery();
            break;
        case R.id.tv_picture:
            openGallery();
            break;

private void openGallery(){
    Intent gallery=new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
    startActivityForResult(gallery, PICK_IMAGE);
}

private void init(){
    item= new ArrayList<>();
    mAdapter=new PostAdapter(item);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, true));
    mRecyclerView.setAdapter(mAdapter);
}

A:

I solved that.
I just set the.
<android.support.v7.widget.RecyclerView
                    android:id="@+id/recycle_view"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:scrollbars="horizontal"
                    >
                </android.support.v7.widget.RecyclerView>

Formerl, I set View's width and height to 'match_parent'. Therefore, each items are displayed as occupying the bigger scrren, evenif they set only 60dp.
That's my very stupid miskate.


Q:

Is it possible to turn an array into a list of parameters for a function?

I have a function that accepts n number of parameters (it's the devinus/sh function) where you can execute a command line program and obtain the results:
Example: Sh.file "-b", "--mime-type", path_to_file
But I want to have the parameters in an array so they can be varying depending on how the function is called.
Example of what I want:
data = ["-b", "--mime-type", path_to_file]

# a way of going through the array and turning it into the parameters for the Sh function

Sh.file <loop array params here>

Sh doesn't take an array for a parameter.
Any ideas?

A:

You can use apply(Sh, :file, args), where args is an array of arguments.