Using mod_rewrite as a stand-in for VirtualHosts to host two domains on one GoDaddy hosting account

Question: I'm trying to do something like VirtualHosts using mod_rewrite on a GoDaddy hosted site. I have a single hosting account and two domains, a.com and b.com. I want requests for b.com/document.html to be served from ~/html/b_site/document.html (where ~/html/ is the DocumentRoot, serving as root for a.com). I found a reference to this use case in the mod_rewrite documentation suggesting that it is possible, but I've been unsuccessful. Here's the contents of ~/html/.htaccess:
RewriteEngine on
Options FollowSymLinks

RewriteCond %{HTTP_HOST} b\.com$
RewriteBase /
RewriteRule ^(.*)$ b_site$1

The result, when I point my browser at b.com: the location bar changes to b.com/b_site/ and the server responds with 500. The following RewriteRule works without any issues:
RewriteRule ^(.*)$ b_site/index.html

...which remains the only way I've been able to get anything but a 500 or warnings about redirect loops. The RewriteBase line seems to make no difference.
To find out what was being matched, I wrote a simple PHP script which would accept a query parameter and print it, and I used this RewriteRule:
RewriteRule ^(.*)$ b_site/index.php?q=$1

The output shows that in this case the RewriteRule matched "b_site/index.php". The RewriteBase documentation does imply that something like that should be happening, but again, the RewriteBase seems to make no difference in the result. Answers posed to similar questions all seem to boil down to the same mechanism that I'm trying.
Any thoughts?
Answer: Your .htaccess context, as well as the RewriteBase, are both setting the context for the RewriteRule to /; this means your substitution would take a request for http://b.com/dir_a/page.html and serve it from http://b.com/b_sitedir_a/page.html - probably not gonna work.
From the documentation:

When using the rewrite engine in .htaccess files the per-directory prefix (which always is the same for a specific directory) is automatically removed for the RewriteRule pattern matching and automatically added after any relative (not starting with a slash or protocol name) substitution encounters the end of a rule set.

Try this:
RewriteCond %{HTTP_HOST} ^b\.com$ [NC]
RewriteRule ^(.*)$ b_site/$1

Comment: Shane, thanks for responding. Adding the slash as you suggest, I still get a 500, but the browser location at least is not rewritten from b.com to b.com/b_site. I guess that indicates mod_rewrite was not finding the b_site$1 directory and was treating it as a URI.
Answer: Solved. And no thanks to GoDaddy for making you pay for access to error logs!
This all started to make sense when I saw someone else's logs. It's now clear to me how the recursion is happening and why things are getting rewritten a second time (and infinitely recursing, causing the 500). There's a great solution to the recursion problem here (via serverfault user Dave Drager's answer to a similar question).
I simplified a little and arrived at this solution:
RewriteEngine on
Options FollowSymLinks
RewriteCond %{ENV:REDIRECT_X} =""
RewriteCond %{HTTP_HOST} b.com$ [NC]
RewriteRule ^(.*)$ b_site/$1 [E=X:1,L]


'Placeholder' text in an HTML or Blazor input control - Can it be 'lighter'?

Question: I notice that on most sites (including Stack Overflow) that it is thankfully very clear to my eye when an input is merely displaying 'placeholder' text as opposed to the text I might type into the input.
And yet (unless I'm missing something) in my Blazor apps, the default 'placeholder' text seems to appear almost dark enough that it can easily be mistaken for actual input text.
I understand that I could compose 'placeholder' strings that are unlikely to ever be mistaken for actual input text, but I thought I'd ask this anyway; just in case there's an answer out there:
Is there a way to make 'placeholder' text look more like...well... 'placeholder' text?  For example, I'm doubtful, but is there a way for CSS just to address 'placeholder' font styling?
Comment: If you turn off CSS in any site you will see your browser's default style. There is nothing specific about Blazor or any other platform that would cause the rendered HTML to have a fundamentally different default style. If you inspect an empty input with placeholder text you can see what style is being applied in your browser's dev tools and then change it to get an idea of what CSS you want to apply to lighten the placeholder text.
Answer: Yes, it is possible to style the placeholders using CSS.
Let's take a look at an example!

input[type="text"]::placeholder{
  font-size:10px;
  opacity:0.7;
}

input[type="text"]#name::placeholder{
  opacity:1;
  font-weight:700;
  color:red;
}
<input type="text" placeholder="Hello">

<input id="name" type="text" placeholder="Enter your name">

You can target a specific input field using id as shown in the code.


Press TAB and then ENTER key in Selenium WebDriver with Ruby

Question: I am doing automated testing using Selenium WebDriver with Ruby. I need to click a button. I cannot get the button element by id or css or xpath as the button is transparent. I would like to use Tab and Enter key to press the button.
I can use Tab key to get the button as below:
@element.send_keys :tab
@element --> any javascript element visible in the browser

But how do I use the Enter key on the button?
Basically I need to achieve press Tab key and then press Enter key to click the button.
I am using Selenium WebDriver @driver = Selenium::WebDriver.for :firefox
Answer: In Ruby user1316's code looks like
driver.action.send_keys(elementVisible, :tab).send_keys(elementVisible, :return).perform

Answer: Keeping in mind the excerpt :

I can use tab key to get the button as
@element.send_keys :tab
@element --> any javascript element visible in
  the browser
but how do i use the enter key on the button??

In order to use the enter key on the button, you could try one of the solution provided using Ruby here. This  basically talks about sending the :return value and not the :enter value i.e  @element.send_keys :return and some additional information.
UPDATED:
I could provide some code in Java which tries to implement the problem conceptually using the info provided here. You could try to translate for the corresponding Ruby Selenium API.
The Code:

Actions builder = new Actions(driver);
builder.sendKeys( elementVisible, Keys.TAB).sendKeys(Keys.RETURN);
Action submitTheTransperentButton = builder.build();
submitTheTransperentButton.perform();
Comment: it doesnot help.  My case is that i cannot get the button element. But i still need to click the button. Is there any other better way to achieve this? thank you
Answer: use Selenium::WebDriver::Keys::KEYS[:tab]
ref: https://www.rubydoc.info/gems/selenium-webdriver/Selenium/WebDriver/Keys
Answer: send ENTER in ruby:
@browser.action.send_keys("\n").perform

Comment: I think this doesn't work for me, like if I try going to google and typing asdf, then doing ENTER manually it works. Whereas if I use irb and programmatically start google and programmatically enter in asdf or manually type asdf. Then programmatically send ENTER, it doesn't work, whereas a manual enter does


Label Ruby One letter

Question: I am trying to figure this out. I am working on a ruby code where in I want to label each array item where in users can just type 1 letter such as l for lego and so on and it will accept that and validates/check that on the code inside the array.
MY_CHOICES = %w(lego violin xray)

l = "lego"
v = "violin"
x = "xray"

print "Choose one: #{MY_CHOICES.join(', ')} "
choice = gets.chomp

if MY_CHOICES.include?(choice)
  break
else
  puts "That is not included there."
end

Any idea how to do it? Sorry newbie here.
Answer: MY_CHOICES = {
  'l' => 'lego',
  'v' => 'violin',
  'x' => 'xray'
}

print "Choose one: #{MY_CHOICES.values.join(', ')} "
choice = gets.chomp

if MY_CHOICES[choice]
  puts "#{MY_CHOICES[choice]} chosen"
else
  puts "That is not included there."
end

Comment: Can  you explain further?
Comment: How does that .zip works? and how does it works on the puts.
Comment: https://ruby-doc.org/core-2.3.0/Array.html#method-i-zip or use the simplified version by @spickermann

Label Ruby One letter


Do you really use your reverse domain for package naming in java?

Question: For a long time ago, I have thought that, in java, reversing the domain you own for package naming is silly and awkward.
Which do you use for package naming in your projects?
Comment: See http://programmers.stackexchange.com/q/21943/24257
Comment: This convention suggests people not to develop packages until they have a domain name.
Answer: Once you understand why the convention exists, it shouldn't feel silly or awkward in the least.
This scheme does two important things:

All of your code is contained in packages that no one else will collide with. You own your domain name, so it's isolated. If we didn't have this convention, many companies would have a "utilities" package, containing classes like "StringUtil", "MessageUtil" etc. These would quickly collide if you tried to use anyone else's code.

The "reverse" nature of it makes class-directory layout very narrow at the top level. If you expand a jar, you'll see "com", "org", "net", etc dirs, then under each of those the organization/company name.

(added in 2021) This is even more important nowadays when this type of package naming is used for third-party libraries which are pulled in transitively during builds and could easily conflict if the names were not unique. If everyone adheres to the same convention, there will be no accidental collisions.
(added in 2021) The same naming convention can be used for application ids on an app store to ensure uniqueness as well.
We usually don't expand jars, but in early java development, this was important because people used expanded dir structures for applets.
However, this is nice now as source code dir structures have a very "top-down" feel. You go from the most general (com, org, net...) to less general (company name) to more specific (project/product/lib name).
Comment: I like this approach so much that it has often left me wondering why domain names are the order they are.  The paths on a host go from general->specific, but subdomain.domain.tld goes specific->general.  Inconsistency... must refactor...
Comment: Since programming came first before internet (www explosion), rather internet URL addressing scheme should have been known to be using reverse package/namespace naming scheme instead. Incidentally, it just the vice versa :P.
Answer: I actually think the reverse domain name package naming is one of the more brilliant conventions in Java.
Answer: If it's just an internal project, and the code is unlikely to ever be reused, then I'd usually go with short, descriptive names.
However, if the code is to be used externally or reused in another project, then I tend to go with the reversed domain scheme.  It makes sure there won't be any package name clashes.
Answer: I find it pretty silly myself.  The com. part really adds nothing but 4 extra characters.  Also, I think using the company name in the assembly / project name is also wrong.  I've worked at too many places that merged with another company or simply renamed itself.
Comment: To make the name unique, I see that there no need to make that way. "com.mycompany.myapp" is kinda weirdo for me, useless.
It might be "mycompany.com.myapp". It would resolve the uniqueness purpose also avoiding the weirdness.
+1 for thinking out of that shaped box.
Comment: The com part makes sure the package name is unique.  Different companies may own the .com, .net, .org etc. domains.
Comment: Plus country codes -- au.com.blahblah...
Answer: I think that this depends greatly on what sort of software is being written. For example, I develop internal systems for a small company, so I choose:
[company].[project].[sub].xyz(.abc)

Where sub is usually one of client, common and server. If I was working in a (commercial) software company, I'd be a lot more reluctant to use the project bit because it's likely that what the app was called when the project started and what it is called when it finished are two completely separate things! Here's to:
oak.lang.Object

Answer: I do this for all my projects, I've even taken it across to my .NET applications for namespaces.
Comment: This is a crime :) Standard MS namespace does not start with com.* or org.*, it is CompanyName.Utils.* or CompanyName.UI.Extensions.*. A company name perfectly separates code and packages without com.* prefix.
Comment: @Artru That's why Java developers are thinking Microsoft people are silly who don't use com and org to achieve uniqueness. But the need of the uniqueness of a single company with 2 tld is dubious.
Answer: It is very useful and copied by others (e.g. XML Schema).
It is useful in the 'large' (given the WWW) but perhaps more so across departments (i.e. in the small).  It may seem bloated for smaller projects but it acts like insurance: it's there when you need it later.
Answer: Yes, I use the reverse domain for the the start of the package, followed by the other administrative information (projects, departments, etc). The use of the domain minimizes the chance of collisions between vendors/companies/FOSS projects. My "data" package will not collide with another company's data package thanks to the domain.
I have also used the convention of dropping the tld for internal work or classes that are not meant for outside use (maybe undocumented support libraries, etc). This usually makes it clear to other developers that different rules or policies may apply to a block of code.
Using the reverse domain is a lot less chaotic than arbitrary namespaces that don't follow any rules or established pattern.
Answer: Yes, I've even devised a scheme to create namespaces in JavaScript using the reverse domain naming convention, it makes finding specific assets and what they are responsible for much easier, and it helps to prevent name collisions.


Fibonacci identity $F_{n+1}^2 - (F_{n+1}F_n) - F_n^2 = (-1)^n$

Question: I am trying to prove
Let $F_n$ be the $n$th Fibonacci number. Then $F_{n+1}^2 - F_{n+1}F_n - F_n^2 = (-1)^n$
I am not sure where to start with this.
Comment: Have you tried writing this out for some small cases (e.g. $n = 1, 2, 3, 4, 5$)?
Comment: You meant start with a base case?
Comment: Yes, it can eventually work into that. But if you have no idea where to start, why not try proving it for some small values of $n$ that you can work with by hand?
Comment: So I get what a base case is. E.g pick a starting value. But I cannot visualize how to input even just one in the above sequence.
Answer: Observe the truthfulness of the statement for $n=0$: $$1^2 +1\cdot0 -0^2 =1=(-1)^0.$$
We can then show it by induction for all $n$. That is, being true for $k+1$ is implied by the assumption that it's true for $k$:
$$ \begin{align} (F_{k+2})^2 - F_{k+2}F_{k+1} - F_{k+1}^2 &= (F_{k+1} + F_{k})^2 -F_{k+1}(F_{k+1} + F_k)  -(F_{k+1})^2 \\ &= -(F_{k+1})^2 + F_{k+1} F_k + (F_k)^2 \\ &= -(-1)^k = (-1)^{k+1}. \end{align} $$
Comment: @user1787331: Is there something I should clarify?


How to append an entered Social Security number to xxx-xx-1111?

Question: I am learning Java and am working on a program for a class. I've completed the bulk of the program so not much help is needed.
How can I convert a SSN (entered by scanner) from, 111-11-1111 to xxx-xx-1111?
I also need to validate that the format of the numbers entered is correct. There is a main class and an Astronaut class where I have getters and setters for the SSN. I already have a toString override method to format it the way I want when I run the program.
@Override
public String toString() {
    super.toString();
    System.out.println("SSN: " + ssn);
    return "";
}

Comment: What do you expect `super.toString()` to achieve?
Comment: Anyway easiest way to replacing single characters with other characters would be converting string to char[], modifying that char[], and creating `new String(modifiedCharArray)`. You could also use substring method to get only part which you are interested in and concatenate it with mask.
Comment: Aside from main question: `toString()` shouldn't be responsible for *printing* anything, but generating String representation of an object *which* then can be used as client want, for instance it can be printed. Using that logic your `super.toString()` would be redundant because it would return some value which you are ignoring. If your superclass really generates values which you want to also print along with your Astronaut then you probably wanted something like `String parentStr = super.toString(); ...; return parentStr+other+elements;`
Comment: I forgot to mention that the Astronaut is an extension of another class
Answer: You can do something like this:
@Override
public String toString() {
    return "SSN: XXX-XX-" + ssn.substring(7);
}

Answer: In order to validate that the number of digits entered is correct, you can use a regex expression. For example: ssn.matches("(\\d-)?\\d{3}-\\d{2}-\\d{4}")


Android UI pattern for saving partial record information into the database

Question: I am designing a simple expenses app which keeps track of expenses I do per month. The expenses have a name, amount as well as a category. One can add/delete categories at will. I am storing the categories and expenses in a database.
Right now, the way I am exposing the add categories functionality is by keeping an editText and a button called "Add category" on the "Add Expenses" activity.
So, for a user scenario like when the user does not input anything about the expenses, but just adds the category, I want it to be saved in the database.
The category save can be done immediately in the database by using a AsyncTask to call the database helper to insert a value into the table.
In the mean-time I am confused as to should I put a progressDialog so as to tell the user that I am saving something or let him populate information in the other fields.
What exactly is the UI-pattern or commonly followed strategies while saving partial information of the record into the database. Also, should I just navigate to a different activity, if adding the category into the database produces an error?
Also, a side question, should I put the "Add categories" button in a different Activity than the Add Expenses one?
Comment: i wouldnt think that adding a category would need to be in an asynctask.  its should be so quick as to be imperceptible to the user.  Id just add it on the main thread and alert the user immediately if it fails.  The overhead of displaying a progress, then dismissing etc would actually make the app seem slower.
Answer: From http://developer.android.com/guide/practices/design/responsiveness.html:
Potentially long running operations such as... database operations... should be done in a child thread (or in the case of databases operations, via an asynchronous request). However, this does not mean that your main thread should block while waiting for the child thread to complete...
As the original situation of this post was described, a progress dialog is probably not necessary.  Perhaps there could be some small visual marker on screen next to the record being saved, indicating it's save state (which might be one of "new", "saving", "saved", "problem/error").  In the case of an error while saving, if it's probably important to the user that the record be saved, then I'd definitely make it very obvious to the user that there was a problem, and provide them with steps to remedy the situation.
Also, note that during at least one recent Google I/O 2011 session (for which videos are available at http://www.youtube.com/googledevelopers), the Android user interface engineers, including the guy that authored the official Twitter app, recommended that blocking UI, such as with progress dialogs, be limited, as their overuse can make for a suboptimal user experience, making the app feel unresponsive and slow to use.


On an identity that appears in Apéry's proof of the irrationality of $\zeta(3)$

Question: In proving the irrationality of $\displaystyle \zeta(3)=\sum_{n\geq1}\frac{1}{n^3}$, Apéry introduced the accelerated series
$$
\zeta(3)=\frac{5}{2} \sum_{k=1}^{\infty}{\frac{ (-1)^{k-1}} {\binom {2k}{k}k^{3}}}.
$$
A crucial ingredient of his proof of the above identity is the well-known equality
$$
\sum_{k=1}^{n-1} \frac{(-1)^{k-1}(k-1)!^2}{(n^2-1^2)\ldots(n^2-k^2)}=\frac{1}{n^2}-\frac{2(-1)^{n-1}}{n^2 \binom{2n}{n}}.
$$
(note that an excellent overview of his proof can be found in Van der Poorten's "A Proof that Euler Missed...".)

I was trying to verify the above equality numerically, in Wolfram Mathematica. However, when asking to evaluate the LHS, Mathematica surprisingly gave:
1/n^2

This is obviously false, as quick numerical verification reveals.
This was the simple Mathematica instruction I ran:
Clear[n]
N[Sum[((-1)^(k - 1) ((k - 1)!)^2)/(Product[(n^2 - j^2), {j, 1, k}]), {k, 1, n - 1}]]

Note that Wolfram Alpha gives the same incorrect evaluation for the same expression, as can be seen here.

So what am I doing wrong? Clearly, the instruction itself is correct (click the Alpha link to see this). So is the Wolfram engine making an elementary mistake, or am I doing so?
Comment: I tried the same thing using Mathematica 11.0 and got the same result. Very interesting, that means that we cannot trust Mathematica :)
Comment: This seems to be a bug. I do not see anything wrong with what you are doing. What version of mathematica are you using?
Comment: 11.1. Thank you for your comments!
Comment: Update: possible bug confirmed, check Mathematica.SE post here: https://mathematica.stackexchange.com/questions/236149/cannot-reproduce-well-known-summation-result
Answer: You already seem to have indication from Mathematica SE site that this might be a bug, here is I think an interesting observation (too long for a comment).
I reproduced the same issue in another CAS system - Maple 2020. Specifically
simplify(sum((-1)^(k-1)*(k-1)!^2/product(n^2-i^2,i=1..k),k=1..n-1))
gives the result $\frac{1}{n^2}$, which is of course incorrect for positive integer $n$. However it seems the tool somehow makes a sense of the input for non-integral $n$ and keeps going with that...
If we look at what is the intermediate result (before passing it to simplify), it is an expression in terms of gamma function, specifically:
$$
\frac{(1-n)(1+n)\Gamma(1-n)\Gamma(1+n)}{n^2\Gamma(2-n)\Gamma(2+n)}\tag{*}.
$$
However for integer $n \geq 1$ it is not hard to see that this expression is not even defined (specifically $\Gamma(1-n)$ and $\Gamma(2-n)$ are not defined because gamma function is not defined for negative integers). So somehow Maple simplified the sum to a result that is more generic, but is not defined for integral values, which paradoxically are the only ones for which the original sum was defined....
Then of course the final simplifcation is done in general without any assumption on $n$, and so for all $n$ for which the $(*)$ is defined, it simplifies to $\frac{1}{n^2}$.
One way around this is to add additional assumptions, in this case we want $n$ to be integer, and indeed if we add assume(n,integer) before the command, we get...
Error, (in SumTools:-DefiniteSum:-ClosedForm) summand is singular in the interval of summation
Well it is not what we hoped for, but at least it is giving us an error instead of incorrect result (clearly it is now aware of the limitations of methods in the given domain).
I can only assume it is a similar case in Mathematica...
Comment: The term "makes sense" makes little sense to me in this context...
Comment: That is an excellent comment, thank you. When I have the time I will try to restrict $n$ to a positive Integer in Mathematica and see what happens
Comment: Update: even using Mathematica's `Assuming[Element[n, Integers], ...]`, I still get the same incorrect result.
Comment: @Klangen I see, I wonder if it just fails to apply the assumption, or if it still sees a case where it makes sense to simplify the expression...


introducing the 3 main concepts of harmony : chord, tonality, mode

Question: Where is the best example of a 7-8 pages course defining all together the basic concepts of harmony, that would be useful when teaching harmony to an adult who is interested in classical music, jazz/blues, improvisation :

chord
tonality
mode

In my opinion it is a waste of time to teach harmony with only 2 of these 3 concepts, often forgetting the mode concept. But, of course the difficulty is to introduce these 3 concepts without completely loosing your student(s).
Note that when you search for 'chord tonality mode' on google you'll find nothing.
Comment: Of the several books on western harmony that I've read or worked on for classes, I've never seen it broken down into "chord, tonality, and mode". I'm not actually sure what the word "tonality" means in this context. This seems to me to be a good, brief intro to western harmony that concisely presents the big picture concepts: http://music.tutsplus.com/articles/the-basic-functions-of-harmony--audio-2172
Comment: Hi, I'm french so I'm not sure what are the correct words. Please re-formulate my question if you want to.
Comment: [] chord : C,E,G,Bb

[] tonality : we are in GMaj so that C,E,G,Bb is the fourth degree

[]  mode :  because it is the fourth degree of GMaj, the mode is C,D,E,F#,G,A,Bb.

 of course there many possible combinations of chord/tonality/mode and often it is ambiguous so that we are not even sure of the current state of chord/tonality/mode... it is clear now ?
Comment: And @Noel Walters the tutorial you referred to, as is often the case, doesn't introduce the mode concept.
Comment: @Todd Wilcox : did you understand my question ? are the words I used at least correct ? you said you didn't understand the term 'tonality'.... I'm french, I never spoke about music in english.
Comment: I'm not sure what the correct words are either. Did you read the article that I provided a link to? Maybe that will help you with the English words that are commonly used in music theory.
Comment: as I said before, it doesn't say anything about modes (or scales). and my question was about tonality : so the term key be better ? it is the one which is used in your link. and I see sometimes scale used instead of mode : wikipedia speaking about the lydian mode or the lydian music scale. and I absolutely need chord + keys + modes to explain for example https://en.wikipedia.org/wiki/Altered_chord#Jazz
Comment: so let's say I rename my question : introducing the 3 main concepts of harmony : chord, key, mode. will you understand it more (in opposition to chord, tonality, mode) ?
Answer: I have always found learning (and thus teaching) is better achieved when new concepts are introduced incrementally. I would suggest, in the first instance, teaching the basics of triads as based on a major scale. Then triads based on a minor scale (for simplicity, probably best to choose the relative minor of the previously-studied major!). I would hope any enthusiastic student would be happy till this point. Now point out that, given the selection of notes we have been using, these two scales are just two of the possible scales available to us: now introduce the others, one by one, and build triads upon them.
I think there's a tendency in formal music education to concentrate on major and minor scales and more or less ignore modes, and for that reason when a student comes upon them they tend to think of them as difficult or even scary. I agree with your thinking: introducing them fairly early on, and emphasising that the major and minor scales are just modes like any other, is a very good idea.
A couple of good explanations of modes can be found at:-
http://www.traditionalmusic.co.uk/sfo/musicinfo/rodsmodeguide.htm
http://www.music-theory-for-musicians.com/music-modes-1.html
Comment: I would think to an algorithm for 'constructing modes', instead of a list which makes the student think he will have to memorize all the mode names. that mostly :

- we alternate seconds major and minor, major being allowed to be repeated, while minor are not.

- with the exception of the 'blues modes' which comprise 2 consecutive minor seconds, and the minor harmonic modes which comprise an augmented second (minor third) as many of the oriental modes.

- that this way you obtain every 7-notes modes, and also the 8-notes diminished modes, and the 6-notes whole tone scales.
Comment: that there are the normal modes (let's say every classical and jazz modes) : which repeat at the octave, but that there also exist many indian and arabic modes which don't.


How to create a includes folder inside sites/all/module/custom/

Question: I want to create a folder name include in-side sites/all/custom/contrib/  and  inside this want to write some .inc files like date.inc, string.inc in each file a class is created which holds function.
Now I want to use this functions in each module under sites/all/custom/contrib. I have 10 custom module so this .inc functions are available to each custom module.
What is the directory structure I have to follow and how can I achieve this?
Comment: create one custom module with all your functions, and enable it after you enable this module you can use those functions on other custom modules.
Answer: In one of your custom modules, just create a directory includes and place your .inc files inside it.
To use the .inc files in your .module file, you can use module_load_include.


ORDER BY id DESC LIMIT 100 returns first rows instead of last

Question: Using latest versions of Postgres, Node and node pg.
Trying to figure out why ORDER BY col DESC LIMIT 100 always returns the first rows regardless of order.
Here's the table:
CREATE TABLE transactions (
    id BIGSERIAL NOT NULL,
    timestamp timestamp with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL,
    user_id INT NOT NULL,
    to_id INT NOT NULL,
    amount NUMERIC(10, 2) DEFAULT 0 NOT NULL,
    comment VARCHAR(100) DEFAULT '' NOT NULL,
    rate INT DEFAULT 0 NOT NULL,
    PRIMARY KEY (id)
);

CREATE INDEX index_transactions_id ON transactions(id);
CREATE INDEX index_transactions_user_id ON transactions(user_id);
CREATE INDEX index_transactions_timestamp ON transactions(timestamp);

Here's the query:
SELECT * FROM transactions ORDER BY $1 DESC LIMIT 100;

Where $1 is id and passed via params.
Rows in transactions are sometimes deleted, so there are empty ranges.
The returned rows from this query are always the first 100. Tried NULLS FIRST/LAST and the result is the same.
What's happening?
Answer:
Where $1 is id and passed via params.

SQL does not allow to parametrize object names like column names. In most cases you get a syntax error right away if you try this kind of nonsense. Unfortunately, the ORDER BY clause does not necessarily expect a column name, but allows expressions including a constant (typed) value (which can be parameterized).
If you pass 'id' to this prepared query, this is what happens:
SELECT * FROM transactions ORDER BY 'id'::text DESC LIMIT 100;

ORDER BY <constant value> is just noise and has no effect on the result.
Turn on the server logs to check what the database actually receives. To parameterize column names like you seem to have in mind, you need dynamic SQL, i.e. first concatenate the query string and then execute it.
Comment: I did check the logs, but yes you are right. I came back to report that the problem had been fixed by taking out the order by param and putting it in the query string before it runs. Thank you. Might be obvious nonsense to some, but seemed actually beneficial at the time to have it parametrized to prevent any issues.


How to align two inputs horizontally

Question: I am currently a very beginner in css and html. I am trying to make a login page, but i just can't align my two inputs. I want to have the labels "Username :" and "Password :" on the left of my text inputs, and that shift the inputs.
I have something that looks like this:

I want my two inputs to be aligned and not shifted like you can see on the image.
I tried to align my inputs with text-align, align-items, flex, or grid on CSS, but nothing did it. I managed to get them aligned if i put a "display: block;" in my CSS code, but it places the label on top of the input instead of on its left, which is what i want.
I guess i just don't understand how it works, and i hope someone can help me on deepening my understand of alignment on CSS.

div.Loging {
  background: url("https://via.placeholder.com/800") no-repeat center center;
  background-size: cover;
  height: 800px;
  text-align: center;
}

div.Username-Password input {
  padding: 5px;
  margin-bottom: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
}
<link href='./index-style.css' rel='stylesheet'>

  <title>Site Guillaume Test</title>

Login :

      <form>
        Username :
        <input type="text" name="pseudo" id="pseudo" placeholder="Enter Username" required>

        Password :
        <input type="password" name="password" id="password" placeholder="Enter Password" required>
      </form>

Comment: I've linked a few duplicates above. They'll help resolve the problem I mentioned on the solution below, which isn't ideal. Note that colon characters go against the text they apply to, such as `Log in: `. Don't put spaces before them. That's incorrect from a language style perspective and it also results in weird wrapping in some cases. (I'd actually eliminate all three of your colons; they're not needed.) Also note that "Login" is a noun. Your form caption should really be "Log in" (the verb form). Happy coding.
Comment: Thank you very much ! I will look into the solution you linked, happy coding !
Answer: Using the code you provided - changing as little as possible - is this what you were looking for?
StackBlitz for reference and editing

div.Loging {
  background: url("./images/index-background.jpg") no-repeat center center;
  background-size: cover;
  height: 800px;
  text-align: center;
}

.Username-Password input {
  padding: 5px;
  margin-bottom: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.Username-Password {
  display: flex;
  justify-content: center;
}

.input-group {
  display: flex;
  justify-content: space-between;
  align-items: baseline;
}

form {
  width: 50%;
}

Login :

      <form>

          Username :
          <input type="text" name="pseudo" id="pseudo" placeholder="Enter Username" required>

          Password :
          <input type="password" name="password" id="password" placeholder="Enter Password" required>

      </form>

Comment: This fails if the labels are of differing lengths. It's not a good strategy to individually pad elements. It's fragile.

How to align two inputs horizontally


Implement badge notification on my app

Question: I am new to iphone Notification. In my app, I am displaying RSS Feed contents and whenever changes happening in server side of RSS Feeds, then I want to show the notification on top of application icon with number badge and also this number should be based on number of feeds changed ( This is changes may be a Addition/Deletion/updates of RSS Feeds). Now, I trying to learn notification with some online resources, but I am not able to follow that.Please guide me? is there any sample due to achieve this?
Thanks in Advance!
Answer: Have you read the Apple developer guide to the topic?
There is a server backend component to remote push notifications that you'll need to develop/host too. You can outsource the infrastructure to companies like Urban Airship or iLime to do that part for you. Urban Airship have a sample project available that uses them.

Implement badge notification on my app


How to avoid SQL Injection in SQL query with Like % Operator. only php mysql

Question: How to avoid SQL Injection in SQL query with Like Operator for only PHP and Mysql?
 can this be done using string functions?
or can anybody tell me what should I  do to prevent attacks of like % operator?
Comment: Actually my question was, how to prevent the user from using like%... he can perform sql injection using the  like % clause, how to prevent this attack..
Comment: Use the LIKE "%SEARCH%" bar at the top.
Comment: personally I use a framework like CodeIgniter, its less boilerplate + security stuff to worry about, I wouldn't dream of doing php from ground up ever again.  Just a suggestion.
Answer: You can escape the string using mysql_real_escape_string and add the % wildcards afterwards.
Comment: you can even escape the whole string including `%` – they do not have a special meaning for escaping
Comment: True. Didn't think of that. Oh well.. It's one (or two) less characters in the string to escape. Could save you a nanosecond per year. ;)
Comment: minus the time to concatenate the strings :p but yeah, it really does not matter
Comment: You will need to concatinate anyway, because the search string is user input. :) And you could include the wildcards in your query already, which will actually save a concatination. ;)
Answer: When you run the query use mysql_real_escape_string() as follows:
mysql_query("SELECT field FROM table WHERE field2 LIKE '%".mysql_real_escape_string($yourVar)."%'");

Answer: There are few things you could do to make it secure.
First of you have to figure out what type of data you will be searching: number, string etc.
I would suggest using PHP's PDO library, preparing the query and binding the value according to the data type you should receive.
Below an example where the received data is supposed to be string. Notice the PARAM_STR.
...

$value = "apple";

$sth = $dbh->prepare('SELECT name FROM fruit WHERE type LIKE :something');
$sth->bindParam(':something', '%'.$something.'%', PDO::PARAM_STR);
$sth->execute();

...


Como atribuir um valor tratado na função para o meu vetor?

Question: #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define TAM_Min 1
#define TAM_Max 500

/*
Sintese
Objetivo: Classificar animais de um zoologico segundo seu peso
Entrada: Numeros de animais do zoologico, e para cada animal o numero de identificacao e o peso em gramas
Saída: Identificacao, peso do animal mais pesado, a identificacao e o peso do animal mais leve, e a quantidade
de animais de peso menor que o peso medio de todos os animais

*/

int le_valida_codigo_animal(int cod[], char titulo[]);
int le_valida_inteiro(int ValorMin, int ValorMax, char texto[]);

int main() {
    int i, num_animais, cod_animal[TAM_Max];
    float peso_animal[TAM_Max];

    //validar numero de animais
    printf("#--- Cadastro de animais ---#");
    num_animais =le_valida_inteiro(TAM_Min, TAM_Max, "\nDigite o numero de animais do zoologico:");

    for(i=1;i<=num_animais;i++){

        cod_animal[i] = le_valida_codigo_animal(cod_animal[i], "Digite o codigo de identificacao dos animais:");

        printf("Digite o peso (em gramas) do animal:");
        scanf("%d", &peso_animal[i]);
        system("cls");
    }

    return 0;
}

int le_valida_inteiro(int ValorMin, int ValorMax, char texto[]){
    int num_animais=0;
    do{

        printf(texto);
        scanf("%d", &num_animais);

        if(num_animais<ValorMin||num_animais >ValorMax){
            printf("\nValor invalido.\nDigite um numero ate 500!");
        }

    }while(num_animais<ValorMin||num_animais >ValorMax);
    return num_animais;
}

int le_valida_codigo_animal(int cod[], char titulo[]){

    char cod_an[0];

    do{
        printf(titulo);
        scanf("%d", &cod);
        if(cod == '\0'){
            printf("O codigo deve nao pode ser vazio!");
        }

    }while(cod == '\0');
}

Error recebido

C:\Users\lain\Desktop\c.c In function 'main':
  32    43  C:\Users\lain\Desktop\c.c   [Warning] passing argument 1 of
  'le_valida_codigo_animal' makes pointer from integer without a cast
  18    5   C:\Users\lain\Desktop\c.c   [Note] expected 'int *' but argument is
  of type 'int' C:\Users\lain\Desktop\c.c   In function
  'le_valida_codigo_animal': C:\Program
  Files\Dev-Cpp\MinGW64\x86_64-w64-mingw32\bin\ld.exe   reopening
  C:\Users\lain\Desktop\c.exe: Permission denied
Comment: Faltou colocar qual é o erro ou problema que você está enfrentando.
Comment: Dentro do for, aquele vetor recebendo o valor validado pela função. Veja o erro: C:\Users\lain\Desktop\c.c In function 'main':
32 43 C:\Users\lain\Desktop\c.c [Warning] passing argument 1 of 'le_valida_codigo_animal' makes pointer from integer without a cast
18 5 C:\Users\lain\Desktop\c.c [Note] expected 'int *' but argument is of type 'int'
C:\Users\lain\Desktop\c.c In function 'le_valida_codigo_animal':
C:\Program Files\Dev-Cpp\MinGW64\x86_64-w64-mingw32\bin\ld.exe reopening C:\Users\lain\Desktop\c.exe: Permission denied
Comment: Desculpa aí falta de jeito para explicar. É a primeira vez que faço uma pergunta aqui no stack.
Answer: Vou dar uma melhorada no seu código:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define TAM_MIN 1
#define TAM_MAX 500

/*
Síntese
Objetivo: Classificar animais de um zoológico segundo seu peso.
Entrada: Números de animais do zoológico, e para cada animal,
         o número de identificação e o peso em gramas.
Saída: A identificação e peso do animal mais pesado, a identificação
       e o peso do animal mais leve, e a quantidade de animais de
       peso menor que o peso médio de todos os animais.
*/

int le_valida_codigo_animal(char *titulo);
int le_valida_inteiro(int valor_min, int valor_max, char *texto);

int main() {
    int cod_animal[TAM_MAX];
    float peso_animal[TAM_MAX];

    printf("#--- Cadastro de animais ---#");
    int num_animais = le_valida_inteiro(TAM_MIN, TAM_MAX, "\nDigite o número de animais do zoológico:");

    for (int i = 1; i <= num_animais; i++) {

        cod_animal[i] = le_valida_codigo_animal("Digite o codigo de identificacao dos animais:");

        printf("Digite o peso (em gramas) do animal:");
        scanf("%f", &peso_animal[i]);
        system("cls");
    }

    return 0;
}

int le_valida_inteiro(int valor_min, int valor_max, char *texto) {
    int num_animais = 0;

    while (1) {
        printf("%s", texto);
        scanf("%d", &num_animais);

        if (num_animais >= valor_min && num_animais <= valor_max) {
            return num_animais;
        }
        printf("\nValor invalido.\nDigite um número entre %d e %d!", valor_min, valor_max);
    }
}

int le_valida_codigo_animal(char *titulo) {
    while (1) {
        int cod = 0;
        printf("%s", titulo);
        scanf("%d", cod);
        if (cod != 0) return cod;
        printf("O codigo deve nao pode ser vazio!");
    }
}

O principal problema é que a sua função le_valida_codigo_animal estava definida de forma errada. int cod[] como parâmetro é equivalente a int *cod. Quando você usa então scanf("%d", &cod);, ocorre que cod já é um ponteiro (ou seja, um endereço de memória), e portanto o correto seria scanf("%d", cod);. Ao usar &cod, você dá o endereço de um ponteiro, ou seja, um ponteiro para ponteiro, e isso não vai ser o que você quer.
Entretanto, ocorre que você quer retornar o código em le_valida_codigo_animal, então nem há motivo para recebê-lo como parâmetro.
Quanto a printf(texto);, o melhor é usar printf("%s", texto); porque assim você garante que o texto será reproduzido mesmo se ele conter coisas que poderiam ser confundidas com formatadores de string. Por exemplo, imagine um cenário que o texto fosse "Concluido 50% ou mais". Nesse cenário, usar o printf(texto); daria pau porque esse "%" seria confundido como parte da string de formatação. A solução portanto é usar printf("%s", texto);.
Comment: Poxa, mano! Valeu mesmo por suas explicações. Vou terminar de escrever e código e caso surja alguma dúvida eu apareço por aqui. Eu já tava pensando em fazer outra coisa da vida... hahah
Comment: @LucasCorreia Se essa resposta resolveu o seu problema e não restou nenhuma dúvida, marque-a como correta/aceita ao clicar no "✅" que está ao lado dela, o que também marca a sua pergunta como resolvida. Se ainda te resta alguma dúvida ou gostaria de maiores esclarecimentos, fique a vontade para comentar. :)
Comment: O único problema é que você usou ponteiros. O meu professor proibiu o uso deles antes de nós vermos o assunto em sala de aula. De qualquer maneira, a sua ajuda me deu ânimo para estudar.
Comment: @LucasCorreia Então use como `char []`, ou seja, com a notação de array. Na verdade, em C, ponteiros e arrays dão quase sempre na mesma coisa (há pouquíssimos lugares onde há alguma diferença).
Comment: Ok. Vou fazer o que me sugeriu e marcar a resposta como correta ali. Valeu! Volto assim que tiver novas dúvidas.


ValueError while parsing a tuple?

Question: My script is-
import subprocess
z = subprocess.check_output(['python3', 'test1.py'],universal_newlines=True)
mas = z
mas = dict(mas)
e = mas.get('email')
print(e)

I get an error-
ValueError: dictionary update sequence element #0 has length 1; 2 is required

But when I run-
mas = {'email': 'firstname.lastname@example.com'}
mas = dict(mas)
e = mas.get('email')
print(e)

I get the desired output i.e firstname.lastname@example.com.
Also, the output of test1.py is {'email': 'firstname.lastname@example.com'}
Comment: `check_output` returns a string.
Comment: Is there any reason why you *run* ``test1.py``, instead of just importing it?
Comment: @bereal So how can I get the exact output?
Comment: @MisterMiyagi No, not really.
Answer: check_output() returns the process output as a string. If you know that it represents a Python dictionary, you can parse it using ast.literal_eval():
import ast
import subprocess

z = subprocess.check_output(['python3', 'test1.py'], universal_newlines=True)
mas = ast.literal_eval(z)

That said, I'd rather import the python file as a module and use the functions in it directly.

ValueError while parsing a tuple?


Trying to write a simple Blackjack, but there are errors I don't understand

Question: I have a problem with a code of mine. It gives random errors and I don't know why.. I'm a newbie to C++ so please bear with me >.>
Here is the code that's problematic:
while (!IsGameOver) {
    struct decktype deck = DeckInit();
    struct card card = PickACard(deck);
    PrintHand(TextCard(card));
}

The parameter for 'PrintHand' causes compilation errors no matter what I do. Here are both the functions.
char *TextCard(struct card &card) {
    char str[22];
    sprintf(str,"%s of %s (%d)",card_num[card.number],card_type[card.color],card.value);
    return str;
}

struct card PrintHand(char &cardtext) {
    struct card card;
    return card;
}

PrintHand isn't done yet, but I don't know how to make it work.. Basically what I want to do is feed a string from TextCard to be used in PrintHand. Could you please help? Much appreciated.
EDIT:
The structure 'card' at the moment looks like this.
struct card {
    int color;
    int number;
    int value;
    char *hand;
    int totalvalue;
};

And the errors are along the lines of "can't convert something to something". Sorry I couldn't be more specific :/
Comment: When asking a question about errors you receive, it's usually helpful to include the exact errors you get.
Comment: Show us structure _card_
Answer: PrintHand expect a reference to char, but you (i.e., TextCard) provide a pointer to char.
Comment: E.g., declare PrintHand as `struct card PrintHand(char *cardtext)`. However, it depends want you want, if you need a pointer or reference. I can not see that from code of `PrintHand`.
Answer: There are several errors.
struct card PrintHand(char &cardtext) {
    struct card card;
    return card;
}

Doesn't use the cardtext, but the real error is the value passed to it from TextCard is char*, so this should be struct card PrintHand(char *cardtext)
Then:
char *TextCard(struct card &card) {
    char str[22];
    sprintf(str,"%s of %s (%d)",card_num[card.number],card_type[card.color],card.value);
    return str;
}

This returns, str, i.e. the address of str[0] which is on the stack, and disappers after TextCard returns, so nothing shoud use that return value. Either new some storage for the char array in the function return it, and have the caller cleanup, or pass in a char array from the caller.
Answer: You cannot create a local variable and return it from function. Use malloc or new instead.
char str[22];

char * str = (char *) malloc(22* sizeof(char)); OR
String str = "sometext" + "othertext";

I don't know, what you are trying to do here:
struct card PrintHand(char &cardtext) {
    struct card card;
    return card;
}

If you want just print text, do this:
void PrintHand(char * cardtext) { // * instead of &
   printf("%s", cardtext);
}


How to show if $a$$\leq$$b_1$, for every $b_1>b$, then $a$$\leq$$b$ where a,b$\epsilon$R?

Question: Not positive on the proper approach to this problem.
My first thought:
$a $ $\leq$ $b_1$ means either $a=b_1$ or $a<b_1$.
Should it broken up into cases?

Second attempt:
Assume, to the contrary, $a > b$, then let $b_1$= $(a+b)/2$. It follows that, $a > b_1 > b$, which is a contradiction.
Thus, $a\leq b$. $ \Box$$ $
Comment: I think you meant to assume that these $a,b,c$ are real numbers.
Comment: Yes I did, thank you @hardmath
Comment: Let c = b + epsilon , epsilon > 0, then let epsilon go to zero.
Answer: What would happen if, to the contrary, $a>b$?
Comment: @19059: Glad to help!
Answer: I think there's a mistake in the question.  Play with each case
a = c and a
Note- my suggestion is not proof by contradiction which assumes the conclusion false, then derives a contradiction => the assumption is invalid.
Answer: If $a>b$, then let $c:=\frac{a+b}{2}$, and you have $a> c >b$, which is a contradiction.
Therefore $a \leq b$.
Comment: Thanks so much @marcoflores, that makes sense.
Answer: Let $a$ be a real number. If there is a real $b$ such that $a \leq c$ for every real $c > b$ and $a > b$, then there is a real $c$ such that $b < c < a;$ a contradiction.
Answer: Ok, you changed the letters on us, which creates confusion with existing answers.  The question I'm answering is

How to show if a≤b1, for every b1>b, then a≤b where a,bϵR?

Let a=b1,  then by the hypothesis    a > b.
but this contradicts the desired conclusion a≤b
Notice I assumed nothing except for a specific case allowed in the original statement.  So as given the theorem is false.  (A single counterexample can prove an entire theorem false)
Is there something I missed?
Comment: Andres, that's not helpful- what did I miss?
Comment: "Is there something I missed?" Yes.
Comment: A quantifier, "for every".
Comment: Ok.  I see it now.
Comment: It should be the same regardless if I use b1 or c, they are just symbols. I just wanted to let it match my text. @nickalh


iPhone equivalent to Android's services

Question: I'm going to port my app from Android to iPhone.
My Android version uses 2 services, one for updating from server (http requests) and store in local DB and another for monitoring some things (alarms).
How could I implement a similiar functionality in iPhone?. Do I need to start 2 threads from main and thats all? or does it have a similar functionality?.
And in the same question. Can I make http calls from my sync thread (or whatever) while my app is not in the user focus?
Answer: Second point;
Till your application is alive (whether it is active or running in background) you can make http calls through both main or sub threads. You need to set whether your application will keep running in background mode.
http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/BackgroundExecution/BackgroundExecution.html
Comment: I'm still confussing about how to make my thread to still run in background to update from server. Some code example?
Answer: I'm not very familiar with Android development, but I think I may be able to help.
As far as running HTTP Requests, you can obviously do that. I recommend the third party library ASIHTTPRequest for that. This library is very flexible and can help simplify the requests.
For local storage, you have a few options. You can use Core Data (which is the closest thing to a database, short of SQLite) or NSUserDefaults, depending on what you want to store. You can also use NSKeyedArchiver to write objects to disk as files.
As far as making HTTPRequests in the background, this is limited by certain factors. See this document for more information. Basically, your app can request up to ten minutes of background time, after which it must stop.
Comment: Thanks, but about background processing Apple is not clear. It seems that you CANN'T work while on background. Some code example?

iPhone equivalent to Android's services


C++ Constructor problems // Inherited class

Question: Initial problem solved. (which was a redefinition error)
Furthermore, I don't know how to create a Student constructor which delivers the following:
This is how I want my program / constructors to work:
//main.cpp
Student s1(4015885);
s1.print();
Student s2("Test", "Student", 22, 5051022);
s2.print();

The output should be as follows:
Standart
Name
18
4015885

Test
Student
22
5051022

s1 works, but s2 doesn't work, because I don't have a fitting constructor
This is my Person.h
#pragma once
#include <iostream>
#include <string>
using namespace std;

class Person {

public:
    Person(string name = "Standard", string surname =  "Name", int age**strong text** = 18);

    //GET
    //SET
    void print();

protected:
    string name, surname;
    int age;
};

Person.cpp
#include <iostream>
#include <string>
#include "Person.h"
using namespace std;

Person::Person(string n, string s, int a) : name(n), surname(s), age(a)
{
    cout << "Person constructor" << endl;
}
void Person::print() {
    cout << name << endl << surname << endl << age << endl << endl;
}

Student.h
#pragma once
//#ifndef PERSON_H
//#define PERSON_H
#include "Person.h"

class Student : public Person {
public:

    Student(int matrikel_nummer);

    int get_matriculation_number();

    void set_matriculation_number(int matriculation_number) {
        this->matriculation_number = matriculation_number;
    }

    void print();

private:
    int matriculation_number;

};
//#endif

Student.cpp
#include <iostream>
#include <string>
#include "Student.h"
using namespace std;

Student::Student(int matrikel_nummer) : Person(name, surname, age)

{
    cout << "Student constructor" << endl;
    this->matriculation_number = matriculation_number;
}

void Student::print() {
    cout << name << endl
            << surname << endl
            << age << endl
            << matriculation_number << endl << endl;
}

Comment: Not related to your initial question but calling the base creator like:

`Person(name, surname, age)`

means trouble (if it even compiles). You are accessing protected members of the base class which are not fully initialized at the time.
Answer: In Student.h you have
Student(int matriculation_number) : Person(name, surname, age){};

Which declares and defines a constructor for Student.  Then in Student.cpp you have
Student::Student(int matrikel_nummer) : Person(vorname, nachname, alter)

{
    cout << "Student constructor" << endl;
    this->matrikel_nummer = matrikel_nummer;
}

Which redefines the same constructor.
You either need to get rid of the constructor definition in the class
Student(int matriculation_number) : Person(name, surname, age){};
//becomes
Student(int matriculation_number);

or get rid of the constructor in the cpp file.
Also name, surname, age, vorname, nachname, alter do not appear anywhere in the code you have provided.  This will not compile unless they declared somewhere else.
EDIT:
From the comments it looks like your Student constructor should be
Student(string n, string s, int a, int mn) : Person(n, s, a), matriculation_number(mn) {}

And you can put that in the header and you do not need a constructor definition in the cpp file.
Comment: vorname, nachname and alter are name, surname and age respectively. I was translating it all from german into english and forgot these. It should recognize name, surname and age though, since i'm including "Person.h", shouldn't it?
I now removed the brckets {} from the consctructor in my Student.h, but now I get an unexpected token error. It looks like this:
    Student(int matriculation_number) : Person(name, surname, age);
Comment: @TonicGin I edited the answer to show how you would declare the constructor in the header file.  As far as the variables names you are not able to use them as the are class member variables.  You are going to have to have `Student` take in the strings that you will need to create the person object.
Comment: I've done that now. The initial error is gone now. Thanks so far! How do I create a Student constructor which creates a Student object as follows?
Student s1(name, surname, age, matriculation_number);
Comment: @TonicGin I have added that to the answer.
Comment: @TonicGin No problem.  If this or any other answer here helps you, you might want to consider accepting it.  I am not asking you to accept this one I am just pointing it out.
Comment: I've done that. I was looking to up your reputation but I didn't notice the check.
Answer: Your error is here:
Student(int matriculation_number) : Person(name, surname, age){};

Remove the {} and the base ctor call:
Student(int matriculation_number);

Answer: You already defined the constructor body of student:
Student(int matriculation_number) : Person(name, surname, age){};

That is already a complete implementation of the constructor body, you should write this in the header:
Student(int matriculation_number);


Splitting string by square brackets

Question: I have a string that comes out like this: 1.[Aagaard,Lindsay][SeniorPolicyAdvisor][TREASURYBOARDSECRETARIAT][DEPUTYPREMIERANDPRESIDENTOFTHETREASURYBOARD,Toronto][416-327-0948][firstname.lastname@example.com]2.[Aalto,Margaret][ProbationOfficer][CHILDRENANDYOUTHSERVICES][THUNDERBAY,ThunderBay][807-475-1310][email@example.com]
I want to split it into an arraylist like this:
1.
Aagaard,Lindsay
SeniorPolicyAdvisor
etc.
Any suggestions?
Comment: Have a read of the String and Strings JavaDoc, see if that helps you out
Comment: Are the 1. 2. supposed to be captured as well?
Answer: I read the JavaDoc and used Pattern and Matcher like so:
Pattern p = Pattern.compile("\\[(.*?)\\]");
Matcher m = p.matcher(tableContent);

while(m.find()) {
  System.out.println(m.group(1));
}

Answer: First delete the first and the last brackets and then split by '][':
String arr = "[Aalto,Margaret][ProbationOfficer][CHILDRENANDYOUTHSERVICES]";
String[] items = arr.substring(1, arr.length() - 1).split("][");

Answer: Simply this:
String[] list = str.split("\\[");

for(int i = 0 ; i < list.length ; i++) {
    list[i] = list[i].replace("\\]", "");
}

Comment: @kknaguib then escape it: `str.split("\\[")`.
Comment: Why not split on `\]?\[`?
Comment: it throws an exception at at the split: java.util.regex.PatternSyntaxException: Unclosed character class near index 0 @Maljam
Comment: @Maljam `[` and `]` are used to construct regexs, which is used for `split`.

Splitting string by square brackets


Docker Jenkins fails to load plugins

Question: I ran docker run jenkins and Jenkins starts correctly but almost all plugins failed to install.
In the log I got errors like this one:
SEVERE: Failed to install Folders
java.io.IOException: Failed to dynamically deploy this plugin
Caused by: java.io.IOException: Failed to install cloudbees-folder plugin
Caused by: java.io.IOException: Folders Plugin v6.11.1 failed to load.
 - You must update Jenkins from v2.60.3 to v2.138.4 or later to run this plugin.

Answer: My bad, I was using the wrong image - it should be docker pull jenkins/jenkins instead of docker pull jenkins. I found the answer in https://github.com/jenkinsci/docker/issues/787 and https://jenkins.io/blog/2018/12/10/the-official-Docker-image/#official-jenkins-image-to-use-from-docker-hub.
Comment: Thanks you..!  The only solution that works well

Docker Jenkins fails to load plugins


Get all submissions from specific webform

Question: I am trying to load webform submissions by a particular webform sign_up.
Using Query webform submissions, this does get me all the IDs associated and I can load the data using
$query = \Drupal::entityQuery('webform_submission')
  ->condition('webform_id', 'sign_up');
$result = $query->execute(); // Gives me IDs associated with the "sign_up" webform.

$storage = \Drupal::entityTypeManager()->getStorage('webform_submission');
$submissions = $storage->loadMultiple($result);
$submission_data = array();
foreach ($submissions as $submission) {
  $submission_data[] = $submission->getData();
}
// $submission_data now contains all the submissions from "sign_up" webform.

Is this the correct way of getting the submissions? I would think Webform comes with some sort of API to query the submission results.
I also tried: https://www.drupal.org/project/webform/issues/2902682 but ended up with an empty array.
Comment: I'd probably do the load in the batch operation then one by one or in chunks just to be safe and don't load like 1000s of submissions at once prematurely.
Answer: The Webform module stores submission data using a custom Entity-Attribute-Value model. Your example code is the easiest and fastest way to get all the submission data. The only limitation would be the number of submissions vs PHP's memory limit. You will run out of memory if you are loading 1000's submissions
Comment: If I need to alter and save the data in that foreach loop, do I keep calling `$submission->save()` or is there like a saveMultiple I can call after the loop?
Comment: Content and config entities don't support save multiple. If you are running out of memory you might need to use Drupal's Batch API.  If you are comfortable with SQL you could manually transform and bulk insert the data using custom code.
Comment: Nope, I wasn't running out of memory just thinking ahead. I was going to do batches if I do end up running out of memory. Thanks again!
Answer: My example shows one less line to loading the WebformSubmission entity, also uses $webform->hasSubmissions() to check if there are submissions before forging ahead:
// Set the webform.
$webform = Webform::load('sign_up');
if ($webform->hasSubmissions()) {
  $query = \Drupal::entityQuery('webform_submission')
    ->condition('webform_id', 'sign_up');
  $result = $query->execute();
  $submission_data = [];
  foreach ($result as $item) {
    $submission = \Drupal\webform\Entity\WebformSubmission::load($item);
    // Do something with the WebformSubmission item
    $submission_data[] = $submission->getData();
  }
}

so the submission loading line:
$submission = \Drupal\webform\Entity\WebformSubmission::load($item);

replaces:
$storage = \Drupal::entityTypeManager()->getStorage('webform_submission');
$submissions = $storage->loadMultiple($result);

But which is actually better/more efficient, not sure.
Comment: Uh, I think loadMultiple indeed is much more efficient than loading every submission one by one. See https://drupal.stackexchange.com/q/283604/15055. But in a correctly setup **batch process** the single load would be fine. But then it's actually the batch process that would make it better/more efficient, not necessarily the loading method.
Comment: I dont think this answer contains unnecessary complexity at all and does exactly what is being asked. Voted up.
Comment: I'm sorry, but I think this answer contains too much information then actually needed for the actual answer of the original question, making it ambiguous. Therefor downvoting this answer.
Comment: @Ambidex thanks for giving a reason for downvoting, I am not going to remove my answer however as so often the code examples here on SE are not working code. Yes I know there is hook_update specific stuff there, but perhaps you are not a programmer, the question was a coding question?
Comment: I'm a coder, though your example includes too much complexity for what's originally being asked. Especially the batch looping adds quite a heavy level of complexity. Novices will probably have quite the challenge to extract the code that is only needed to fetch webform submissions from your example.


How to join different columns of same table?

Question: Suppose I have one table with two column, Country and City.
Country
USA
Canada
UK

City
NY
London

I want to join/merge both column records and expect the output like this -
USA
Canada
UK
NY
London

So, what will be the SQL query to merge different columns records of same table?
Answer: SELECT Country FROM TABLE
UNION
SELECT City FROM Table

should do it.
Comment: You should probably structure the data in a different way possibly?
Comment: I am searching for any quick way. Because if I need to merge 10 columns then i have to write 10 Unions! Is there any other way?
Comment: No. Except changing database model
Comment: Lol.. It was a SQL quiz question.
Answer: Responding to the comment "I am searching for any quick way. Because if I need to merge 10 columns then i have to write 10 Unions! Is there any other way?":
You can use an unpivot, which means you just need to add the column names into a list. Only thing is to watch for data types though. eg:
--CTE for example only
;WITH CTE_Locations as (
    select Country = convert(varchar(50),'USA'), City = convert(varchar(50),'NY')
    union select Country = 'Canada', City = 'Vancouver'
    union select Country = 'UK', City = 'Manchester'
)
--Select a list of values from all columns
select distinct
    Place
from
    CTE_Locations l
    unpivot (Place for PlaceType in ([Country],[City])) u


Separar valores repetidos em uma lista

Question: Tenho uma lista assim:
[1,1,1,2,2,1,5,3,4,3,4]

Como gerar uma nova lista apenas com um valor de cada:
[1,2,3,4,5]

A primeira lista é um List<int> a segunda pode vir em qualquer tipo de lista.
Answer: Por definição matemática, um conjunto é uma estrutura em que cada elemento aparece uma única vez. No C#, um conjunto é representado por HashSet<T>.
Gerando um HashSet<int> da sua lista, você terá os elementos sem repetição:
var conjunto = new HashSet<int>(lista);

Veja uma demonstração aqui.
Comment: Eu não conhecia esse comando, porém, ao ler mais sobre ele no SOEn, não vi vantagens sobre o `LINQ`. http://stackoverflow.com/questions/1247442/when-should-i-use-the-hashsett-type e http://stackoverflow.com/questions/150750/hashset-vs-list-performance
Comment: @ismael É só uma forma alternativa de resolver o problema.
Answer: Utilize o Distinct para remover os items duplicados, gerando um novo objeto.
List<int> novaListaDeInteiros = listaDeInteirosVelha.Distinct().ToList();

Isto irá retornar uma sequência List<int> preenchida sem repetir os dados.
Comment: Não precisa do `Select`, é repetição desnecessária.
Comment: Obrigado pela dica, resposta editada.
Comment: Agora tem meu voto =)
Answer: Utilize o Distinct para retornar os distintos elementos da sua lista.
using System.Linq;

List<int> lista = new List<int> { 1, 1, 1, 2, 2, 1, 5, 3, 4, 3, 4 } ;
lista.Distinct();

Answer: A função Distinct do Linq elimina dados duplicados de uma lista no .Net Framework:
var lista = new List<int> {1,1,1,2,2,1,5,3,4,3,4};
var listaSemDuplicidade = lista.Distinct();

Um exemplo funcional pode ser visto aqui.

Separar valores repetidos em uma lista


What happens to emails if Distribution Group doesn't have any members on Exchange 2010

Question: We had a distribution group on Exchange 2010 which didn't had any members for long time (nobody noticed). What happens to the emails that come to such group? There was no return messages or anything.
Answer: Unfortunately all those emails have gone into the black hole. Exchange has done it's job, it looked up recipients but nothing exist, therefore discards the email. You would need an archive/compliance setup to retrieve those emails.
Also note: You would not receive any NDRs either, the process did completed as expected.
Comment: As I expected but wanted to confirm. Thanks
Answer: They go nowhere unfortunately. We've set up a PowerShell script that runs daily and will email us if it finds empty distribution groups.
Just put this in a .ps1 file and schedule it to run at whatever interval you prefer.
<code>$FromAddress = "email@example.com"
$ToAddress = "email@example.com"
$MessageSubject = "Empty distribution groups"
$SendingServer = "exchserver.example.com"

$groups = Get-DistributionGroup
$emptygroups = ($groups | ? { !(Get-DistributionGroupMember $_) })

if ($emptygroups.count -gt 0) {
    $MessageBody = "The following Exchange distribution groups have no members:`r`n`r`n"
    $MessageBody += ($emptygroups | Select-Object DisplayName | Out-String)

    $SMTPMessage = New-Object System.Net.Mail.MailMessage $FromAddress, $ToAddress, $MessageSubject, $MessageBody

    $SMTPClient = New-Object System.Net.Mail.SMTPClient $SendingServer
    $SMTPClient.Send($SMTPMessage)
}
</code>
Answer: Here's an update on possible code.  A more efficient query since it only returns a list of empty groups.  A bit obtuse since one is led to think Get-DistributionGroup doesn't know about members (thus the need for the Get-DistributionGroupMember cmdlet).
<code>$emptygroups = Get-DistributionGroup -Filter {members -eq $null}
</code>
I've confirmed that works on Exchange 2010, SP2, RU5v2.
Answer: Thanks!  For me the nothing was happening with the above script - not sure if it's a different Powershell version or such like (Exchange 2010, Server 2008 R2) but there was nothing in the "count" attribute.
I had to replace:
<code>if ($emptygroups.count -gt 0) {
</code>
With:
<code>$emptygroupcount = echo $emptygroups | measure
if ($emptygroupcount.Count -gt 0) {
</code>
If anyone is wondering how to do a schedule of this, since the "basic" Powershell doesn't recognise the Exchange commands, I created a wrapper batch file as per http://social.technet.microsoft.com/Forums/exchange/en-US/0cad57bf-1113-4622-aac3-c3278fa97d72/how-to-schedule-a-powershell-script-through-schedule-tasks?forum=exchange2010


Using eigenvectors and eigenvalues to a find power of a transformation

Question: Let $T:R^2 \to R^2$ be a linear operator with eigenvectors $(1,-1)$ and $(1,1)$, and eigenvalues $1/2$ and $2$, respectively. How do I evaluate $T^{10}(v)$, given $v = (5,1)$?
I tried to write the transformation matrix, but I think I am missing some detail related to the basis...
Answer: We can write the eigenvalue decomposition $T = VDV^{-1}$. Now if we calculate $TT$ we get: $$T^2 = TT = VDV^{-1}VDV^{-1} = VD\underset{=I}{\underbrace{\left(V^{-1}V\right)}}DV = VDDV^{-1} = VD^2V^{-1}$$ If we keep going in the same way you will see that $T^k = VD^kV^{-1}$. So you will get away with calculating the diagonal matrix $D$ raised to 10, which is a much faster thing to do than to do 10 full matrix multiplications.
If this seems confusing at start, try and think of it as multiplying with $V^{-1}$ does the "translate to eigenbasis" part which the answer by Paul explains well and multiplying with $V$ does the "translate back to original basis" part.
Answer: Note that $$\tag{1}v=(5,1)=2(1,-1)+3(1,1).$$
Since $(1,−1)$ and $(1,1)$ are eigenvectors of $T$ with eigenvalues $1/2$ and $2$ respectively, we have
$$\tag{2}T(1,-1)=\frac{1}{2}(1,-1)\mbox{ and }T(1,1)=2(1,1).$$
By $(1)$ and $(2)$, we have
$$T(v)=2T(1,-1)+3T(1,1)=2(\frac{1}{2})(1,-1)+3(2)(1,1)=\cdots$$
where we have used the fact that $T$ is linear.
Similarly, we have
$$T^{10}(v)=2T^{10}(1,-1)+3T^{10}(1,1)=2(\frac{1}{2})^{10}(1,-1)+3(2)^{10}(1,1)=\cdots.$$
I think you can finish from this point.


Change ssh username and password

Question: I use CentOs 5.4 Operating System.
Suppose my web server is 'xyz.com' and document root is '/var/www/html/'.
How can i change ssh username and password of my web server?
Comment: What does Apache httpd have to do with the question?
Comment: why does the domain or documentroot come into it ? Are you serving pages from home directories ?
Answer: You can change the login credentials for your user with usermod -l $NEW_LOGIN $USERNAME (for changing the user name) and passwd $USERNAME (for changing the password). You'll need superuser privileges to perform these actions.
Answer: Your question is not so clear!
Anyway, you can change the Linux user password using the passwd command after you login using the username you want to change its password.
$ passwd

You can change any user password using:
$ sudo passwd <username>

Usernames are not usually changed! You can create new users!

Change ssh username and password


How to update an old spreadsheets with a new one, adding only new elements and changing color of subtracted elements?

Question: I have a problem similar to this: Imagine I have a Google Sheet (eg, with students info) which I get downloading from a school site (imagine the school system is very bad, so it's more useful to use a sheet with my Google Scripts). But I have to weekly update this sheet downloading a new sheet from school site. To not lose my previous notes, I want to write a script that makes the update process, this way:
 - If the most recent sheet has a new row which isn't in the previous sheet (a new student row), it add this row to the new sheet;
 - If the old sheet has a row which isn't in the new sheet, it change the color of that row and adds a note "Transferred student" or something like that.
I get this sample code, but I'm wonder if there isn't a better way to do this. This is my code:
function updateSheet(){
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sourceSpreadsheetID = ss.getId();
    var oldSpreadsheet = SpreadsheetApp.openById(sourceSpreadsheetID);
    var oldWorksheet = oldSpreadsheet.getSheetByName("students");
    var oldData = oldWorksheet.getDataRange().getValues();
    var newSpreadsheetUrl = Browser.inputBox("New sheet", "Put the new sheet link here:", Browser.Buttons.OK_CANCEL);
    Logger.log("newSpreadsheetUrl = " + newSpreadsheetUrl);
    var newSpreadsheetID = newSpreadsheetUrl.split('d/')[1].split('/')[0];
    var newSpreadsheet = SpreadsheetApp.openById(newSpreadsheetID);
    var newWorksheet = newSpreadsheet.getSheetByName("students");
    var newData = newWorksheet.getDataRange().getValues();
  // Iterates through the new sheet rows
    for(i=1; i<newData.length; i++){
    var alreadyInOldSheet = false;
    var remainsInNewSheet = false;
      Logger.log("newData[i][0] = " + newData[i][0]);
    // Iterates through the old sheet rows
        for(j=1; j<oldData.length; j++){
            // compares the firs cell (student name)
            Logger.log("oldData[j][0] = " + oldData[j][0]);
            Logger.log("newData[i][0] == oldData[j][0] = " + (newData[i][0] == oldData[j][0]) );
            if (newData[i][0] == oldData[j][0]) {
                alreadyInOldSheet = true;
                break; // This student is already in the old sheet, so, jump to the next row
            }
        // After iterates through all old sheet rows, the student name isn't found, so we add it
        }
          Logger.log("Last condition 'alreadyInOldSheet =' " + alreadyInOldSheet);
          Logger.log("newData =' " + newData);
          if (alreadyInOldSheet == false) {
             oldWorksheet.appendRow(newData[i]);
         }
  }
  absentInNewSheet(oldData, newData, oldWorksheet);
}

function absentInNewSheet(oldData, newData, workSheet) {
   for(i=1; i<newData.length; i++){
    var alreadyInOldSheet = false;
    Logger.log("newData[i][0] = " + newData[i][0]);
    // Iterates through the old sheet rows
        for(j=1; j<oldData.length; j++){
            // compares the firs cell (student name)
            Logger.log("oldData[j][0] = " + oldData[j][0]);
            Logger.log("newData[i][0] == oldData[j][0] = " + (newData[i][0] == oldData[j][0]) );
            if (newData[i][0] == oldData[j][0]) {
                alreadyInOldSheet = true;
                break; // This student is already in the old sheet, so, jump to the next row
            }
        // After iterates through all old sheet rows, the student name isn't found, so we add it
        }

Comment: Wanst this posted on another question?
Comment: Hi, @ZigMandel, I've had delete this question (considering it bad written) and I find a solution (very similar to this code, that I'll post here). But in other question I receive a comment saying that one guy has an answer to it. So I said to him I'd post again the question (though, of course, I'd prefer to undelete my previous question, but I think there's no way to do this undelete). In the future, I'll avoid delete questions so quickly. Any suggestion?
Answer: Example Code
function updateSheet()
{
  var ss = SpreadsheetApp.getActiveSpreadsheet();

  var masterSheet = ss.getSheetByName("Master");
  var masterRange = masterSheet.getDataRange();
  var masterData = masterRange.getValues();
  masterData.shift();
  var masterBackgrounds = masterRange.getBackgrounds();
  var masterNotes = masterRange.getNotes();
  var masterLength = masterNotes.length;

  var updateData = ss.getSheetByName("Update").getDataRange().getValues();
  updateData.shift();

  for (var i = 0; i < (masterLength - 1); i++)
  {
    masterData[i].unshift(i + 1);
  }
  masterData.sort(function(a,b) {return (a[1] > b[1]) ? 1 : ((a[1]  b[0]) ? 1 : ((a[0]  updateData[0][0]))
    {
      addedData.push(updateData.splice(0, 1)[0]);
    }
    else if (!updateData.length || (masterData.length && masterData[0][1] < updateData[0][0]))
    {
      for (var k = 0; k < masterBackgrounds[0].length; k++)
      {
        masterBackgrounds[masterData[0][0]][k] = "#dcdcdc";
      }
      masterNotes[masterData[0][0]][0] = "This student was transfered from this school";
      masterData.shift();
    }
    else
    {
      masterData.shift();
      updateData.shift();
    }
  }

  var extraRows = masterLength + addedData.length - masterSheet.getMaxRows();
  if (extraRows > 0) masterSheet.insertRowsAfter(masterLength, extraRows);

  if (addedData.length > 0) masterSheet.getRange(masterLength + 1, 1, addedData.length, addedData[0].length).setValues(addedData);
  masterRange.setBackgrounds(masterBackgrounds).setNotes(masterNotes);
}

Test spreadsheet (feel free to try out - hopefully you can adjust this to your specific spreadsheets)
Thanks for re-posting; I just happened to be helped with a similar problem I posted when the Google Apps Script forum was over at GPF (I can't find that thread at all, but credit to +ScampMichael for helping me out; I have fine-tuned the script a bit since).
In general, the algorithm is to sort both the master and update arrays, and work through each array simultaneously, comparing the first element of each and performing some action then, including shift()-ing that element off each array when you're done with it. Before sorting the master array, in your case you would need to also append an index column so you know which cells to apply the note/background to - which with this method you do in one batch set for each, which should also improve performance.
Anyway, I'm not suggesting there aren't even more efficient algorithms, but when I had thousands of rows in my situation, it took about 8 seconds, while the "multiple looping" method would often time out. I hope it helps.
Answer: This is my actual code to perform this task. Maybe it isn't the more efficient solution (any suggestions?) but it is working for this problem.
function updateSheet(){
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sourceSpreadsheetID = ss.getId();
    var oldSpreadsheet = SpreadsheetApp.openById(sourceSpreadsheetID);
    var oldWorksheet = oldSpreadsheet.getSheetByName("students");
    var oldData = oldWorksheet.getDataRange().getValues();
    var newSpreadsheetUrl = Browser.inputBox("New sheet", "Put the new sheet link here:", Browser.Buttons.OK_CANCEL);
  //  Logger.log("newSpreadsheetUrl = " + newSpreadsheetUrl);
    var newSpreadsheetID = newSpreadsheetUrl.split('d/')[1].split('/')[0];
    var newSpreadsheet = SpreadsheetApp.openById(newSpreadsheetID);
    var newWorksheet = newSpreadsheet.getSheetByName("students");
    var newData = newWorksheet.getDataRange().getValues();
  // Iterates through the new sheet rows
    for(i=1; i<newData.length; i++){
    var alreadyInOldSheet = false;
    var remainsInNewSheet = false;
//      Logger.log("newData[i][0] = " + newData[i][0]);
    // Iterates through the old sheet rows
        for(j=1; j<oldData.length; j++){
            // compares the firs cell (student name)
        //    Logger.log("oldData[j][0] = " + oldData[j][0]);
         //   Logger.log("newData[i][0] == oldData[j][0] = " + (newData[i][0] == oldData[j][0]) );
            if (newData[i][0] == oldData[j][0]) {
                alreadyInOldSheet = true;
                break; // This student is already in the old sheet, so, jump to the next row
            }
        // After iterates through all old sheet rows, the student name isn't found, so we add it
        }
      //    Logger.log("Last condition 'alreadyInOldSheet =' " + alreadyInOldSheet);
      //    Logger.log("newData =' " + newData);
          if (alreadyInOldSheet == false) {
             oldWorksheet.appendRow(newData[i]);
         }
  }
  absentInNewSheet(oldWorksheet.getDataRange().getValues(), newData, oldWorksheet);
}

function absentInNewSheet(oldData, newData, workSheet) {
   for(i=1; i<oldData.length; i++){
    var remainsInNewSheet = false;
    Logger.log("oldData[i][0] = " + oldData[i][0]);
    // Iterates through the old sheet rows
     Logger.log("oldData.length = " + oldData.length);
        for(j=1; j<newData.length; j++){
            // compares the firs cell (student name)
            Logger.log("newData[j][0] = " + newData[j][0]);
            Logger.log("first condition oldData[i][0] == newData[j][0] = " + (oldData[i][0] == newData[j][0]) );
            if (oldData[i][0] == newData[j][0]) {
                remainsInNewSheet = true;
                Logger.log("break");
                break; // This student is already in the old sheet, so, jump to the next row
            }
        // After iterates through all old sheet rows, the student name isn't found, so we add it
        }
          Logger.log("Last condition 'remainsInNewSheet =' " + remainsInNewSheet);
          Logger.log(" ");
          //Logger.log("newData =' " + newData);
          if (remainsInNewSheet == false) {
             var lastColumn = workSheet.getLastColumn();
             var firstColumn = workSheet.getLastColumn();
             var currentRow = workSheet.getRange(i+1, 1, 1, lastColumn);
             currentRow.setBackgroundRGB(220, 220, 220).setNote("This student was transfered from this school");
         }
    }
}


Show comment author e-mail in comment.html.twig

Question: Anonymous users can leave their e-mail when posting a comment but how can I display this e-mail as a plain text value in the comment.html.twig?
Comment: If you have a fresh Drupal 8 standard install, go to: 'People > Permissions' and Allow anonymous users to 'Post comments' and 'Skip comment approval'. Then go to: 'Structure > Content Types > Article > Manage Fields'  and edit the 'Comments' field. Go to 'Anonymous commenting' and select 'Anonymous posters may leave their contact information'. Click 'Save settings'. Now when you go post a comment as an anonymous user you can leave your e-mail.
Comment: By default, anonymous comments have no such "e-mail" field. Was this field added by you?
Comment: If yes and you used the e-mail field type, then simply go to the comments manage display and for Format select plain text.
Comment: You can enable anonymous users to leave their contact information in the comments field of a content type.
Comment: Where is that option located at?
Answer:
If you have a fresh Drupal 8 standard install, go to: 'People >
  Permissions' and Allow anonymous users to 'Post comments' and 'Skip
  comment approval'. Then go to: 'Structure > Content Types > Article >
  Manage Fields' and edit the 'Comments' field. Go to 'Anonymous
  commenting' and select 'Anonymous posters may leave their contact
  information'. Click 'Save settings'. Now when you go post a comment as
  an anonymous user you can leave your e-mail.

You can print that e-mail value in plain text like this:
<code>{{ content.comment_body['#object'].getAuthorEmail() }}
</code>
Now, this will print the e-mails of logged in users as well. If you don't want that, then you will need to add a conditional to check if their User ID is 0, which means they are anonymous.
<code>{% if attributes.toArray()['data-comment-user-id'] == 0 %}

    {{ content.comment_body['#object'].getAuthorEmail() }}

{% endif %}
</code>


Eclipse-like minimap ruler on PyCharm scrollbar

Question: I'm having a small issue in PyCharm : I want to go directly to the corresponding code line when clicking on the scrollbar.
Not just going a little up or down but at the point where I click, like with the Eclipse minimap ruler.
Is it possible ?
Answer: Just found an answer : it is possible by clicking with the middle mouse button.


"Once-initialized" variables that are not initialized in construction time

Question: Is there any way in Java to create variables like final that are not initialized inside the constructor, but yet once they are initialized they can never be changed again? My problem is that I get the variable values at different time points and I'd like to create the class before or as soon as I receive the first value.
I've already thought about the obvious solution of keeping a flag for each variable, but I wanted to know if there's anything more efficient than that.
Comment: a static final variable is effectively a constant
Answer: I would probably do something along the lines of the last answer here. Always set the fields with a setter, and if the field is not the default value (i.e. null), do not allow it to be set.
Comment: That's quite a good idea. But is it safe to assume that the variables will have the expected initial value or should I initialize them first on the constructor and use this value as the default?
Comment: "Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type.  Relying on such default values, however, is generally considered bad programming style." See this [article](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html).
Comment: Yes I've already read that. And basically the reason I asked the question was that sentence underlying that it "is generally considered bad programming style".
Comment: I believe that it is bad programming style to assume that a field is set to a given value that you plan on using. For example, one should not assume an int is 0 without setting it (especially because it is unclear when reading the code). But the only reason you check the default is to make sure you have not set a value yet, so there should not be a problem.
Comment: Yes that sounds reasonable. Thanks for the help! :-)
Answer: While initializing this final variable make sure that you are initializing only in one of the following constructs, otherwise compiler throw an error.

Initializer expression
public class FinalVariable {
    // in the instance initializer expression, or while declaration itself
    // final   = ;
    final int finalInstanceField = 5;
}
Instance initializer block
public class FinalVariable {
    final int finalInstanceField;
{
    // Initialization in instance initializer block
    finalInstanceField = 5;
}

Constructor block
public class FinalVariable {
final int finalInstanceField ;

public FinalVariable() {
    // constructor
    finalInstanceField = 7;
}

}

Static final variables can be initialized in two ways.
1.Initializer expression
public class FinalVariable {
    // in the instance initializer expression, or while declaration itself
    // final <type> <variable_name> = <initializer expression>;
    static final int finalStaticField = 25;

}

Static initializer block
public class FinalVariable {
static final int finalStaticField;

static {
    finalStaticField = 7;
}

}


How to secure XenApp traffic over the internet?

Question: I am planning to host a client's legacy Line of Business application using a hosted Windows Virtual Server running Citrix XenApp. How do I secure the traffic as it will all pass over the internet? Ideally I would like clients to be able to connect without having to open a VPN connection first. I know Microsoft have the Remote Desktop Gateway but I don't know the Citrix equivalent. Do I need the Citrix Secure Gateway or does XenApp come with some functionality to do this already?
Answer: External access to Citrix XenApp (or XenDesktop, for that matter), is usually secured using  Citrix "Access Gateway", a feature in Citrix NetScaler.
If you only need the Access Gateway, and not the rest of the NetScaler featureset, you can license NetScaler Gateway VPX (virtual appliance) for $1,000 (retail) per instance.
Comment: Am I right in saying that NetScaler Gateway has to be either a physical appliance or run on top of a hypervisor such as VMWare or Hyper-V?
Comment: _NetScaler Gateway_ "is a virtual appliance running on XenServer or VMware ESX/ESXi". The functionality you're looking for is also present in the "full" NetScaler product line, which are phsyical appliances. These are typically used for rather large installations. Check their specs and rated (or licensed) concurrent connections against your need.
Comment: Hmmm, as I suspected. Citrix XenApp isn't really lending itself to a cheaply hosted cloud solution. I was hoping to rent a Windows Virtual Server from someone like FastHosts for a reasonable price and host it all in the cloud. I would probably need a dedicated server for NetScaler Gateway though. I think with MS Remote Desktop the Gateway comes free and the RDS licenses cover it as well. Thanks anyway.


Can I add a menu link with a parameter?

Question: I would like to add a menu link using the "Link"-Field with Autocomplete, but I would like to add a parameter afterwards.
Pretty much like this:

...which is not working.
Is that possible? Thanks!
Answer: I didn't find a direct answer, but I used the module "Menu Link Attributes" to add a class and used JS to add the parameter:
<code>$('#menu ul li a.parameter').each(function() {
    $(this).attr("href", $(this).attr("href") + "?p=parameter");
});
</code>
Maybe that's helpful.

Can I add a menu link with a parameter?


Drawing Pie3D Graph in R

Question: I was plotting a data.frame in R in a pie graph. Here is the code
library(plotrix)
piepercent<- round(100*cause_wise$suicides/sum(cause_wise$suicides), 1)
png(file = "plots/cause suicide.png")
pie3D(cause_wise$suicides,labels = piepercent,explode = 0.1,
  main = "Suicide by Gender(in percentages)")
#legend("topright", cause, cex = 0.8, fill = rainbow(length(cause)))
dev.off()

The data.frame which I am trying to plot here has 38 values, I want to leave out those values which do not contribute significantly to the piepercent into one big area say less than 2%. Is there a way I can do this?
Here is how the graph looks like:
Comment: Yes you can aggregate categories using a minimum threshold. Probably there are already answers relating to that. But more importantly are you sure this is the kind of graph you want? 3d pies (and pies in general) are widely discouraged due to poor visual interpretation of the data. Would a bar chart suit better?
Comment: Thank you for letting me know about the best practices! Will use bar graphs in my result!
Answer: Aggregate the ones less than threshold into one category, then plot:
library(plotrix)
library(dplyr)

# dummy data
cause_wise <- data.frame(suicides = c(2, 3, 1, 50, 1, 50, 45))

# sum values where percentage is less than 2%
plotDat <- cause_wise %>%
  mutate(grp = ifelse(suicides/sum(suicides) < 0.02, "tooSmall", row_number())) %>%
  group_by(grp) %>%
  summarise(suicides = sum(suicides)) %>%
  select(-grp) %>%
  ungroup()

# set label and color(grey for <2%)
piepercent <- round(100 * plotDat$suicides/sum(plotDat$suicides), 1)
piecol <- c(rainbow(length(piepercent) - 1 ), "grey")

# why oh why 3D pie chart...
pie3D(plotDat$suicides,
      labels = piepercent,
      explode = 0.1,
      col = piecol,
      main = "Suicide by Gender (in percentages)")

Drawing Pie3D Graph in R


iText - Como Usar "For Each" em VB.NET

Question: Estou tentando usar o "For Each" para gerar vários PDF's, como uma Mala Direta do Word. Minha ideia é selecionar vários nomes da ListBox e gerar os PDFs com os itens selecionados.
Meu código está assim:
Dim listarNomes As String = ListBox1.GetItemText(ListBox1.SelectedItem)

        Dim data As String() = {listarNomes}

        For i As Integer = 0 To data.Length - 1
            doc.NewPage()
            doc.Add(gif)
            doc.Add(New Paragraph(" "))
            doc.Add(New Paragraph(data(i), fonte1))

        Next

Mesmo quando eu seleciono vários nomes do ListBox, só gera uma página com apenas um nome.
Minha ListBox usa Itens de Associação de Dados.
Answer: Faça um For Each dentro de ListBox.SelectedItems:
For Each listaItem In ListBox1.SelectedItems
    Dim listarNomes As String = ListBox1.GetItemText(listaItem)

    Dim data As String() = {listarNomes}

    For i As Integer = 0 To data.Length - 1
        doc.NewPage()
        doc.Add(gif)
        doc.Add(New Paragraph(" "))
        doc.Add(New Paragraph(data(i), fonte1))
    Next
Next

Desta forma, irá percorrer por todos os itens selecionados na sua ListBox, uma vez que esteja habilitado para selecionar vários itens.

iText - Como Usar "For Each" em VB.NET


Determine the order of the rate of convergence for these values

Question:
Consider the recurrence relation $x_n=2(x_{n-1}+x_{n-2})$ and the general solution $z_n=\alpha(1+\sqrt{3})^n+\beta(1-\sqrt{3})^n$.
For which values of $\alpha,\beta\in\mathbb{R}$ does the general solution converge? Determine the order of the rate of convergence for these values.

I've found $z_n$ to be convergent for $\alpha=0$ and $\beta\in (-\infty,\infty)$.
But how do I go about determining the the order of the rate of convergence?
Answer: When there is convergence,
$$z_n=\beta(1-\sqrt3)^n$$ is simply a geometric progression of common ratio $1-\sqrt3$ and the convergence is linear.
Comment: Thank you. Would the following be a correct answer?
When there is convergence:
$$z_n=\beta(1-\sqrt{3})^n.$$
We see that
$$c=\frac{|z_{n+1}|}{|z_n|}=\frac{|\beta(1-\sqrt{3})^{n+1}|}{|\beta(1-\sqrt{3})^n|}\to\sqrt{3}-1\quad\text{ for }n\to\infty.$$
Since $c<1$, the rate of convergence is linear.
Comment: @user405381 You forgot the absolute value.
Comment: Where did I forget it?
Comment: @user405381: oops, no, sorry.


How to flat array in zustand

Question: I have a brands list array, every brand object has a brand name & products
So the first time, I pushed the new brand object to the brands list, and that's work well,
Now if I want to push a new brand to the brands list and keep the previous brand data it does not work as expected.
and it looks like this

the expected should be like this

I'm trying to use flat() but not work here
minimal reproduction here
Code
import create from 'zustand';
import {persist} from 'zustand/middleware';
import {zustandStorage} from '../utils/Storage';

export const useFavoritesStore = create(
  persist(
    set => ({
      brandsFavoritesList: [],
      updateFavList: brandData => {
        set(state => ({
          brandsFavoritesList:
            // check if there are any brands on the list before
            state.brandsFavoritesList.length > 0
              ? state.brandsFavoritesList.map(brand =>
                  // if the brand exists before pushing new products
                  brand.tenant === brandData?.tenant
                    ? {
                        ...brand,
                        products: [...brand.products, ...brandData.products],
                      }
                    : // if the brand does not exist before push the new brand data to the brandsFavoritesList
    // Issue here...
                      [...state.brandsFavoritesList, brandData].flat(),
                )
              : [...state.brandsFavoritesList, {...brandData}],
        }));
      },
    }),
    {
      name: 'favorites-local',
      getStorage: () => zustandStorage,
    },
  ),
);

Answer: It looks like you want something like
function updateBrandsFavoritesList(brandsFavoritesList, brandData) {
  const brandIndex = brandsFavoritesList.findIndex((brand) => brand.tenant === brandData.tenant);
  if (brandIndex < 0) {
    // This is a new brand, append it to the list.
    return [...brandsFavoritesList, brandData];
  }
  // This is an existing brand, update it.
  const existingBrand = brandsFavoritesList[brandIndex];
  const updatedBrand = {
    ...existingBrand,
    products: [...existingBrand.products, ...brandData.products],
  };
  return brandsFavoritesList.map((brand, index) => (index === brandIndex ? updatedBrand : brand));
}

const updateFavList = (brandData) => {
  if (!brandData) return;
  set(({brandsFavoritesList}) => ({
    brandsFavoritesList: updateBrandsFavoritesList(brandsFavoritesList, brandData),
  }));
}

– no need for flat.
The complex logic of finding and updating a brand has been moved to a separate free function which should be easier to e.g. test in isolation too.
(Even better still would be to use TypeScript so errors would be more obvious...)
Comment: @OliverD Sure, fixed.
Comment: Hey @AKX first of all thank u, but not work.
as I see here
`brandsFavoritesList.map(existingBrand =>...)`
 I need to push the new brand to fav List if it does not exist before but in ur answer u push the `existingBrand` so it will not push any new brand
Comment: Right, just a sec...
Comment: @OliverD See revised answer :)
Comment: Thank you @AKX, but there is a small issue I fixed in the first condition,
`brandData` it's an `object` so we can't spread it.
so it should be like this  `return [...brandsFavoritesList, brandData];`, Can u please update it so I can accept your answer with the fixed?

How to flat array in zustand