How to select filed position by votes MySQL?

Question: I've got a database table called servers with three columns 'id', 'name', and 'votes'.
How can I select the position of column id 5 by votes?
Example, I want to check which position server 3 is in by votes in my competition?
Answer: If I've interpreted your question correctly, you are asking how to find the rank of the row with id 5 in a list of servers sorted by votes. There is a complex solution, which requires sorting, but the easier solution which can be done in O(log(n)) space and O(n) time is to simply measure the number of votes for id = 5
select votes from servers where id = 5;

and then walk through the database and add one for every server encountered that has smaller number of votes. Alternatively, you can do something like:
select count(*) from servers where votes <= %votes

It is excessive to sort this (O(nlog(n) time) when you can simple iterate through the entire list once and gather all the information you need.
Answer: Use LIMIT:
SELECT id, name, votes FROM servers ORDER BY votes DESC LIMIT 2,1;

LIMIT a, b means "give me b rows, starting at row a", and a is zero-based.

OK, I misunderstood. Now. Suppose your server has 27 votes.
SELECT COUNT(*) FROM servers WHERE votes < 27;

Your server's rank will be 1 plus the result; ties are possible (i.e. ranks will be like 1, 2, 3, 3, 3, 6, 7, 7, 9 etc.).
Comment: and how can i print the number?
Comment: Which number? I thought you want the 3rd place.
Comment: Oh, I misunderstood, you want to know the rank of the server with ID 3?
Comment: yes i want to get the rank if the server with id 3 according to votes
Comment: I see. You can do what Whoopska says, or retrieve the ordered query result and loop through until you found id 3. It depends on whether you just want the rank of one server, or if you want the ranks of all servers.
Comment: i want the rank of only one server, can u give me an example code?
Comment: SELECT COUNT(*) as num FROM servers WHERE votes < {$r['votes']} ORDER BY votes DESC

am i right?
Comment: @Yoni: `COUNT` is an aggregate, so you only get one single result, there's no such thing as an ordering on that. Do go an try it at the mysql command line interface, you'll see.


Nullity and Rank without a clear matrix

Question: For a fixed non-zero vector b =$\left(
\begin{array}{c}
    b_1 \\
    b_2 \\
    b_3\\
  \end{array}
\right)$
, the mapping $\;T : \mathbb R^{3}\ \to\ \mathbb R^{3}\\;$
is defined by
$T$(x) = x $\times$ b,
where $\times$ denotes the cross product.
i) Show that T is linear.
ii) Find nullity(T). Give a reason.
iii) Find rank(T). Give a reason.
iv) If b =$\left(
\begin{array}{c}
    1 \\
    0 \\
    3\\
  \end{array}
\right)$
, find the matrix $A$ such that T(x) = $A$x.
So far, i) is shown with a zero vector and iv) matrix A is found, with matrix $A$ =$\left(
\begin{array}{c}
    3 & 0 & 0\\
    -3 &0 & 1\\
    0 & -1 & 0\\
  \end{array}
\right)$
Well, not sure if iv) is right but thats what I got.
The problem is about ii) and iii), if either of them is found, then the other one will be found as well, I have got no idea how to find the nullity without a clear matrix...

Thank you.
Answer: The nullity is the dimension of the kernel of $T$. Because $x \times b = 0$ whenever $x = \lambda b$ for an $\lambda \in \mathbb R$ the kernel of $T$ is the set $ker T = \{ \lambda b: \lambda \in \mathbb R\}$. This vector space is one dimensional and thus $\operatorname{nullity}(T)=1$.
Answer: Linearity results from the properties of the cross-product:

$(u+u')\times v=u\times v+u'\times v$
$(\lambda u)\times v=\lambda(u\times v)$
$u\times (v+v')=u\times v+u\times v'$
$u\times (\lambda v)=\lambda(u\times v)$
$v\times u=-u\times v$
which can be summarised as  being antisymmetric bilinear.

The image of $T $ is the plane orthogonal to $\mathbf b$. It certainly is contained in that plane. Conversely, let $\mathbf u$ be a vector that is orthogonal to $\mathbf b$. Then, by the double cross product formula:
$$\mathbf b\times(\mathbf b\times \mathbf u)=\mathbf b(\mathbf b\cdot \mathbf u)-\mathbf u(\mathbf b\cdot \mathbf b)=-\mathbf u(\mathbf b\cdot \mathbf b),$$
so that $$\mathbf u=T\Bigl(\frac{\mathbf b\times \mathbf u}{\mathbf b\cdot\mathbf b}\Bigr).$$
Hence $\operatorname{rank}(T)=2$.

The matrix $A$ must be antisymmetric. The coordinates of $\mathbf x\times \mathbf b$ are given by the minors of the matrix:$$\begin{bmatrix}x_1&b_1\\x_2&b_2\\x_3&b_3 \end{bmatrix}$$
We find $x\mathbf=\begin{bmatrix}b_3x_2-b_2x_3\\b_1x_3-b_3x_1\\b_2x_1-b_1x_2\end{bmatrix} $, whence the matrix of $T$:
$$\begin{bmatrix}0&b_3&-b_2\\-b_3&0&b_1\\b_2&-b_1&0\end{bmatrix}=\begin{bmatrix}0&3&0\\ -3&0&1\\ 0&-1&0\end{bmatrix}$$

Nullity and Rank without a clear matrix


Get node bundle (content type) from EntityInterface

Question: trying to find if node is bundle article (node bundle = content type) before executing the rest of the statements in the following example
I can test if the entity is node but I can't figure out how to test if content type is article
<?php

use \Drupal\Core\Entity\EntityInterface;

function MODULE_NAME_entity_presave(EntityInterface $entity){

    //if content type is article
    if ($entity->getEntityType()->id() == 'node') {
        //do wonderful stuff ...
    }
}

Answer: I did manage to find it after all $entity->bundle() it was pretty easy ...
 if ($entity->getEntityType()->id() == 'node' && $entity->bundle() == 'article') {


Riesz Lemma from Hahn Banach Theorem

Question: A note by Jacob Manaker provides a proof of the Riesz lemma via Hahn Banach. I am unable to follow a key construction in this proof. I note the proof down below for reproducibility, along with a screenshot:

For $X$ a normed vector space, $Y$ a closed proper subspace and $\epsilon \in [0, 1]$, there exists $x \in X$ of unit norm such that for all $y \in Y$, $|x - y| \geq 1 - \epsilon$.
Proof:
Fix any point $z \not in Y$ such that $d(z, Y) \geq 0$. Note that $d(\cdot, Y)$ is:

a sublinear function on $X$ that
vanishes on $Y$ and
equals "projection onto $\mathbb Rz \simeq \mathbb R$ on $Y + \mathbb Rz$.

By Hahn-Banach, the linear portion of $d(\cdot, Y)$ extends to a linear functional on all of $X$ that is also dominated by $d(\cdot, Y)$. Thus $Y$ is contained in the kernel of some nonzero functional $f$.
WLOG, we may rescale $f$ to have unit norm, and take some "approximate normer" $x \in X$ such that $|f(x)| \geq 1 - \epsilon$. But now, for any $y \in Y$,
$$
(1 - \epsilon) - 0 = |f(x) - f(y)| \leq |f| |x - y| = |x - y|
$$
My Question

What is this notion of "approximate normer"? Does it just mean to pick some element $x_0 \in X$ such that $|f(x_0)| \geq 1 - \epsilon$? Why does such an element $x_0$ exist?
Even given such an element, how does one find the estimate that $|f(x) - f(y)| \leq |f| |x - y|$? I guess this follows immediate from the definition of $|f| \equiv \sup_{x \in X} |f(x)|/|x|$?
Where did we use the fact that $f$ was constructed from a linear functional that acts as a projector on the subspace $\mathbb Rz$? If we don't need this fact, then why state it? I'm guessing all we need is $d(\cdot, Y)$ is non-trivial.
Does the last inequality $|f||x - y| = |x - y|$ hold because we normalized the linear functional such that $|f| = 1$?
Comment: You mean Riesz?
Answer:
"Approximate normer" of functional $f$ is element $x$ with unit norm s.t. $|f(x)| \approx \|f\|$. Such element exists by definition of norm: $\|f\| = \sup\limits_{x: \|x\| = 1} |f(x)|$.

Indeed, from definition of $\sup$: $$\forall \epsilon > 0 \exists y: \|y\| = 1 \wedge (|f(y)| > \sup\limits_{x: \|x\| = 1} |f(x)| - \epsilon)$$
$$\forall y: \|y\| = 1 \rightarrow |f(y)| \leq \sup\limits_{x: \|x\| = 1} |f(x)|$$
From the first part, substituting $\sup\limits_{x: \|x\| = 1} |f(x)| = 1$, we get $\exists y: \|y\| = 1 \wedge (|f(y)| > 1 - \epsilon)$ - such $y$ is "approximate normer".

Yes, it is from definition and linearity: $|f(x) - f(y)| = |f(x - y)| \leq \|f\| \cdot \|x - y\|$.
We need $d(\cdot, Y)$ to be not just non-trivial, but also to dominate some non-trivial linear functional.
Yes.
Comment: Yes, Hahn-Banach is about linear functional extension. We need some linear functional to apply it. We used that $|f(x)| \approx \|f\|$ when we wrote $|f(x)| \geq 1 - \epsilon$.
Comment: Added a bit more details about it. On infinite dimensional space we don't necessary have $x$ s.t. $|f(x)| = \|f\|$. For example, consider functional $f(x) = \sum_n x_n \cdot (1 - 1/n)$ on $l_1$.
Comment: Where do we need it to dominate some non-trivial linear functional? Ah, you mean, to apply hahn banach, we need both a nontrivial linear functional $g$ and a seminorm $p$ such that $g \leq p$ for the subspace $Y+ \mathbb R z \subseteq X$?
Comment: For (1), where did we use the fact that $|f(x)| \simeq ||f||$?
Comment: I am sorry, could you elaborate on why this "approximate normer" exists? I do not yet see how it follows from the above estimate. Why could I not have had that every element $x$ with unit norm has norm *equal* to that of $f$?

Riesz Lemma from Hahn Banach Theorem


Pandas Check for key values in rows prior to running pd.crosstab and add known key values if absent

Question: Afternoon All,
I run a script to create a crosstab style report from which calculations are added to the output, this assumes all fields used in the calculations are present. This assumption is incorrect, especially early in the month where a number of Results are not yet present for each Client. I would like to add some validation prior to the run.
There are no issues if and only if the following values are ALL present for field Result for each Client
Covered
Customer Reject
Customer Timeout
Dealer Reject
Dealer Timeout
Done
No RFQ
Tied Covered
Tied Done
Tied Traded Away
Traded Away

The case where all values are present and the desired output is displayed:
df = {'Client': ['A', 'A', 'A',
                 'B', 'B', 'B', 'B','B','B','B','B',
                 'C',
                 'D','D','D','D','D','D','D','D','D','D','D'],
'Result': ['Covered', 'Customer Reject', 'Customer Timeout',
           'Dealer Reject','Dealer Timeout','Done','Tied Covered','Tied Done','Tied Traded Away','Traded Away','No RFQ',
           'No RFQ',
           'Covered','Customer Reject','Customer Timeout','Dealer Reject','Dealer Timeout','Done','Tied Covered','Tied Done','Tied Traded Away','Traded Away','No RFQ']}
df = pd.DataFrame.from_dict(df)
print(df)

   Client            Result
0       A           Covered
1       A   Customer Reject
2       A  Customer Timeout
3       B     Dealer Reject
4       B    Dealer Timeout
5       B              Done
6       B      Tied Covered
7       B         Tied Done
8       B  Tied Traded Away
9       B       Traded Away
10      B            No RFQ
11      C            No RFQ
12      D           Covered
13      D   Customer Reject
14      D  Customer Timeout
15      D     Dealer Reject
16      D    Dealer Timeout
17      D              Done
18      D      Tied Covered
19      D         Tied Done
20      D  Tied Traded Away
21      D       Traded Away
22      D            No RFQ

df = pd.crosstab(df.Client,df.Result,margins=True, margins_name='Total_Result_Per_Client').drop('Total_Result_Per_Client')
# Percentage_Priced_Back_Count = (Total - Dealer Reject - Dealer_Timeout) / (Total - Customer Reject)
df['Percentage_Priced_Back_Count'] = ( df['Total_Result_Per_Client'] - df['Dealer Reject'] - df['Dealer Timeout'] ) / ( df['Total_Result_Per_Client'] - df['Customer Reject'] )
# Hit_Rate_Count = (Total – (Covered + Tied Covered) – Customer Reject – Dealer Reject – Dealer Timeout – (Traded Away + Tied Traded Away)) / (Total – Dealer Reject – Dealer Timeout)
df['Hit_Rate_Count'] = ( df['Total_Result_Per_Client'] - df['Covered'] - df['Tied Covered'] - df['Customer Reject'] - df['Dealer Reject'] - df['Dealer Timeout'] - df['Traded Away'] - df['Tied Traded Away']) / \
                       ( df['Total_Result_Per_Client'] - df['Dealer Reject'] - df['Dealer Timeout'] )
df = df.stack().reset_index(name='value')

df2 = pd.DataFrame([[''] * len(df.columns), df.columns], columns=df.columns)
df1= (df.groupby('Client', group_keys=False)
        .apply(lambda d: d.append(df2))
        .iloc[:-2]
        .reset_index(drop=True))
print (df1)

Sample output:
15  Client                        Result     value
16       B                       Covered         0
17       B               Customer Reject         0
18       B              Customer Timeout         0
19       B                 Dealer Reject         1
20       B                Dealer Timeout         1
21       B                          Done         1
22       B                        No RFQ         1
23       B                  Tied Covered         1
24       B                     Tied Done         1
25       B              Tied Traded Away         1
26       B                   Traded Away         1
27       B       Total_Result_Per_Client         8
28       B  Percentage_Priced_Back_Count      0.75
29       B                Hit_Rate_Count       0.5

The case where a value in Result (used in the calculation) for a Client is not present, an error is raised. In the example below Traded Away is removed for Client B and D. The error is raised in the pd.crosstab call:
df = {'Client': ['A', 'A', 'A',
                 'B', 'B', 'B', 'B','B','B','B',
                 'C',
                 'D','D','D','D','D','D','D','D','D','D'],
'Result': ['Covered', 'Customer Reject', 'Customer Timeout',
           'Dealer Reject','Dealer Timeout','Done','Tied Covered','Tied Done','Tied Traded Away','No RFQ',
           'No RFQ',
           'Covered','Customer Reject','Customer Timeout','Dealer Reject','Dealer Timeout','Done','Tied Covered','Tied Done','Tied Traded Away','No RFQ']}
df = pd.DataFrame.from_dict(df)
print(df)

df = pd.crosstab(df.Client,df.Result,margins=True, margins_name='Total_Result_Per_Client').drop('Total_Result_Per_Client')

KeyError: 'Traded Away'

i.e. if the known Result values are not present for any Client add it (with a zero values) before the function call so all calculations can be completed.
Answer: I suggest use DataFrame.reindex for add all missing values from list and fill them by 0:
vals = ['Covered',
'Customer Reject',
'Customer Timeout',
'Dealer Reject',
'Dealer Timeout',
'Done',
'No RFQ',
'Tied Covered',
'Tied Done',
'Tied Traded Away',
'Traded Away']

df = (pd.crosstab(df.Client,
                 df.Result,
                 margins=True,
                 margins_name='Total_Result_Per_Client')
        .drop('Total_Result_Per_Client')
        .reindex(vals + ['Total_Result_Per_Client'], axis=1, fill_value=0))

print(df)

Result  Covered  Customer Reject  Customer Timeout  Dealer Reject  \
Client
A             1                1                 1              0
B             0                0                 0              1
C             0                0                 0              0
D             1                1                 1              1

Result  Dealer Timeout  Done  No RFQ  Tied Covered  Tied Done  \
Client
A                    0     0       0             0          0
B                    1     1       1             1          1
C                    0     0       1             0          0
D                    1     1       1             1          1

Result  Tied Traded Away  Traded Away  Total_Result_Per_Client
Client
A                      0            0                        3
B                      1            0                        7
C                      0            0                        1
D                      1            0                       10

Comment: Hi @jezrael, getting KeyError: 'Total_Result_Per_Client'. Looks like the total column is not being writtent to the crosstab. Checking further
Comment: Looks like .reindex(vals, axis=1, fill_value=0) adds Total_Result_Per_Client as a row value whereas previously it was a column, hence the error. Is therer a way to make it a column as it's used in the claculations?
Comment: @PeterLucas - Changed `.reindex` with add `Total_Result_Per_Client` value.
Comment: Perfect, than @jezrael


Actionbar styled overflow menu items

Question: I need to make fully custom overflow menu items (different background colors as minimum as showed on picture).

Is it possible?
Comment: It's [possible to change the color of *all* overflow menu items](https://groups.google.com/forum/?fromgroups#!topic/actionbarsherlock/5lHOKNlXn_4), but I don't believe it's possible to set them individually.
Comment: But I need different styles for each item. I know one way to do it - PopupWindow with own layout. But it's not so elegant like popup menu in action bar.
Comment: You can achieve this setting the adapter of you action list.In adapter you can set different background colors.
Comment: @MohammadImran Please give me a little more details!
Comment: i have answered your question.If you need more help,i'll provide you.
Comment: @user2069363 respond to my answer,if you got you answer.
Answer: Last day i have to implement Action Bar Sherlock.And my case was same as yours. I have implement Adapter for my navigation List.Let say:
<code>public class MyNavigationAdapter extends BaseAdapter {
    Context mContext = null;
    String[] mTitles;
    LayoutInflater mLayOutInflater = null;

    public MyNavigationAdapter(Context context, String[] titles) {
        this.mContext = context;
        this.mTitles = titles;
        mLayOutInflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return mTitles.length;
    }

    @Override
    public Object getItem(int arg0) {
        return null;
    }

    @Override
    public long getItemId(int arg0) {
        return 0;
    }

    @Override
    public View getView(int position, View view, ViewGroup parent) {
        if (view == null)
            view = mLayOutInflater.inflate(R.layout.my_list_custom_row, parent,false);
        TextView rowName = (TextView) view.findViewById(R.id.title);
        rowName.setText(mTitles[position]);
        rowName.setBackground(your desire drawle);// yo

u can also set color etc.
//OR

if(position%2==0)
        rowName.setBackgroundColor(Color.RED);
        else
            rowName.setBackgroundColor(Color.BLUE);
        return view;
    }

}
</code>
After this,you have to write these line of code in your Activity onCreate methos.
<code>  ActionBar actionBar = getActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
actionBar.setListNavigationCallbacks(mNavigationAdapterObj, mNavigationListner);
</code>
for more information .Consult here.
Comment: Good solution! But I prefer this one: http://stackoverflow.com/a/14123377/2069363 Because it allows me to create spinner with overflow menu icon on the same place like original overflow menu.
Comment: yes,you can also add icon ,if you want. I can update my answer for icons if you want.
Comment: that is same solution,basic theme is same. Accept my answer.
Answer: You can set a custom view for each MenuItem.
<code>@Override
public boolean onCreateOptionsMenu(Menu menu) {
    menu.add("test").setActionView(R.layout.custom_action_menu_item);
    return super.onCreateOptionsMenu(menu);
}
</code>
http://developer.android.com/reference/android/view/MenuItem.html#setActionView%28int%29
Comment: It works when MenuItem showed in action bar. But doesn't work when menu item inside overflow menu.
Answer: This one https://stackoverflow.com/a/14123377/2069363 works for me!

You can create such behavior using Spinner (or IcsSpinner for ActionBarSherlock) in action layout of a menu item. Though you have to use a little trick - hide the currently selected item.

Actionbar styled overflow menu items


Assign src as the txt file content by JavaScript

Question: I have a file, name: 1.txt
In that .txt file I have a URL in the first line: https://example.com/logo.png
In this HTML code:

I want to assign the URL of that file as src by JavaScript. How can I do that? Any good idea?
I tried the following JavaScript code (But, it doesn't work):

const response = await fetch('1.txt');
const data = await response.text();
console.log(data);
$("#summer").attr('src', console.log(data));

Thanks in advance!
Answer: The return value of console.log() is always undefined
If you want to use the value of data as your attribute, then use the value of data and not of console.log(data)!
Comment: const response = await fetch('1.txt');
const data = await response.text();
console.log(data);
$("#summer").attr('src', data); this is also not working.
Comment: @MasudRana — Then something else must be wrong. Do some basic debugging. Look at the value of `data`. Make sure it is exactly what you want (and doesn't have anything like extra whitespace in it). Check that the attribute is updating in the DOM. Check the Network tab to see what URL is requested for the img.
Comment: The content of 1.txt is not assigned as javascript variable.


Creating a Mobile Programming Language

Question: I'm thinking about creating a small language that is very easy to type on a mobile phone (J2ME),
What is the more appropriate language to implement in order to run it inside a mobile phone (j2me always)? Appropriate meaning, small/easy syntax, easy to type in a mobile phone.
Is it lisp? Some sort of Basic/Python/Ruby (I think not...)? Or another new (can you propose a new syntax?)?
Answer: I am the author of just such a language: Hecl, at http://www.hecl.org .  In order to make quite applications easier, I also created a site where you can build simple apps through a web interface: http://www.heclbuilder.com .  I also wrote an article discussing the implementation of the language:
http://www.welton.it/articles/hecl_implementation
Other languages that are worth looking at include Lua, and Javascript, both of which have mobile implementations.
Answer: If you include editor support (nesting structures, indented display, balancing, ...) then some form of LISP would be relatively straightforward to implement and use. I've seen screenshots (but can't find them now) of a LISP-based language for live interactive-performance programming. It used indented, shaded rectangular areas on the screen (instead of parentheses) to show nesting of structure.
Answer: I would think the design of the editor would be the biggest consideration, not the language. For instance, supporting some kind of "intellisense"-like autocompletion would be vital for saving thumbstrokes. Some kind of language sensitivity in the editor would help a lot too. For instance, when a C user types "for" the autocomplete should show an option for filling out the syntax of a loop:
<code>   for (;;) {
   }
</code>
Answer: You might want to look into Hecl: http://www.hecl.org/
Answer: I'm not sure what's easy to type on a mobile phone, but the language I know with the most computing power per character is APL.  As a source of syntactic or design ideas, you might prefer its modern successor, the J programming language.
Comment: I actually don't think that's a very good idea. APL has all kinds of characters that aren't even in ASCII, and has often been used with special keyboards. J gets around the problem by using diagraphs (extra characters), but that defeats your whole reason for using APL here.
Comment: (not a bad enough idea to vote down though. At least you're thinking along the right lines...)
Answer: On a mobile phone, you should also consider languages like Scratch (smalltalk), because the non-typing interface would be easy to use.
Also on the smartphones with drag&drop capability, it would be something good.
On the other hand, the IDE would be a lot heavier on CPU & other resources.
Answer: Forth is usually considered a legitimate contender for these kinds of requirements. And it's about as terse as can be imagined. Extensible, small and malleable. Built-in small screen editor, too.
Comment: of course, its integration with the phone's API may be, uh, limited ... but it's an easy language to implement, and fairly fun to use (I'm currently writing an interpreter in Java)
Comment: Quartus Forth has full integration with the entire Palm SDK and even allows you to compile standalone apps, on the device! http://www.quartus.net/products/forth/
Answer: If you want super-compact, try nano-False  http://www.aldweb.com/pages/winikoff/#false
It isn't very usable, although more so than the deliberately painful Brainfuck and Whitepace. Think of it as Forth with the easy syntax made more concise ;-)
I found Quartus Forth reasonably easy to use, provided you can think in stacks, and with more Intellisense support for the API it would have been much more productive. For prototyping little algorithms on the Palm I preferred Plua or Lispme. The LispMe environment is worth studying anyway because it provided good use of lists for finding keywords and so eased GUI programming
The big decision you have to make is whether you expect users to just use a phone numeric keypad or be able to type in reasonable approximations to a full keyboard. One of the huge benefits of the Palm was the high-quality full-size folding keyboards which I sadly miss (and hope someone makes an iPhone accessory to connect). If you don't have a full keyboard, make use of selectors for verbs so they can use picking actions rather than having to type in words. Consider the amount of code typed in traditional code for the framework classes and methods compared to the user code.
Answer: When I go about dreaming about a language, I think about what features are important to me at the time I'm dreaming. Only once you figure out what features are important to you can you come up with the best answer to what syntax. For example, if you want named parameters, it greatly influences your design choice about how method calls look (a la Objective-C or Python).
Designing a language can be a really fun task. I encourage you to step back and ask yourself "Do I really like how this is done in X?" (substituting some language name). If that's something you've always loved, steal it. If not, look elsewhere. Create your ultimate mashup of what you love, and leave out what you hate!
Answer: Lisp would be difficult to type because of all the ()s, although joel.neely's answer demonstrates one way of working around that problem.
So if you want to use an existing language you might want to look at which ones use least unusual characters.
Then there's the screen size issue.  The more verbose the language the less code you're going to be able to fit onto the screen at once.  What kind of devices are you aiming at?  Smartphones with big screens (a limited audience) or 240x240 pixel feature phones?
Bear in mind that the interpreter/VM for your language will have to fit into a small amount of memory and performance may not be very good.
Answer: Brainfuck has only 8 characters -- very easy to type in on a mobile phone.
Of course, understanding and doing stuff with it... not so easy. But it satisfies the requirement....
Answer: Basic is very easy.
I would stay away from lisp. Unless you want to give your mobile users a headache on top of the headache they have from radio waves.

Creating a Mobile Programming Language


Number of random effects is not correct in lmer model

Question: I am getting this error.
Error: number of observations (=30) <= number of random effects (=30) for term (1 + year | ID0); the random-effects parameters and the residual variance (or scale parameter) are probably unidentifiable

I can't see anything wrong. The number of random effects should be 15, not 30. My grouping parameter is ID0, which is nominal, and there are twice as many observations as there are unique ID0's.
Here is some data that I'm using. I've subsetted just 30 rows of it for an example, but the original data has 1,088 obs. I'm trying to estimate random slopes and intercepts.
w1 <- structure(list(ID0 = c("007a275b3b24f4866a0d026503af0f3470f57bfc",
"007a275b3b24f4866a0d026503af0f3470f57bfc", "0225c47f9da2575d71468f753699a02b972de8ba",
"0225c47f9da2575d71468f753699a02b972de8ba", "02dc8096dff62e94c39ec3b0df26cd7dd2ed07aa",
"02dc8096dff62e94c39ec3b0df26cd7dd2ed07aa", "03099c4feb5d232d9c60e2bdd04434cde1741073",
"03099c4feb5d232d9c60e2bdd04434cde1741073", "03d255805fe183e1c3b1218fe08d7bba8ffc4d87",
"03d255805fe183e1c3b1218fe08d7bba8ffc4d87", "042746d2cd8a74b6e2bfa6a5645ae90c920cf3e1",
"042746d2cd8a74b6e2bfa6a5645ae90c920cf3e1", "046538c636e5ed4097ede61b9f6693b376c61119",
"046538c636e5ed4097ede61b9f6693b376c61119", "0489a242d084104452045fece4038cd45fba6d7a",
"0489a242d084104452045fece4038cd45fba6d7a", "06500c806172e86f835e5c21a052269dd222e30c",
"06500c806172e86f835e5c21a052269dd222e30c", "06917c5835230a589bbd5cbb40909cc45afd5c40",
"06917c5835230a589bbd5cbb40909cc45afd5c40", "06a9c55568e3f2d2d4bcef4534e5672ccc1323db",
"06a9c55568e3f2d2d4bcef4534e5672ccc1323db", "06ccbadee52b11e853eaab602f71c073a950cc85",
"06ccbadee52b11e853eaab602f71c073a950cc85", "06faa13b62f5f68089d595548638ca1b81d21b49",
"06faa13b62f5f68089d595548638ca1b81d21b49", "081d7c912e71b04e894dc21761db9ed531a99d11",
"081d7c912e71b04e894dc21761db9ed531a99d11", "08f23961db566bb51f8fa0ae37159a8d97320157",
"08f23961db566bb51f8fa0ae37159a8d97320157"), year = c(0, 1, 0,
1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1,
0, 1, 0, 1, 0, 1), SatisAvg = c(6, 5, 4, 4, 6.3333333333, 6,
5.3333333333, 5.6666666667, 6.3333333333, 6.3333333333, 6.3333333333,
7, 6, 6.3333333333, 6.6666666667, 3.6666666667, 6, 6, 6, 6, 6,
4.3333333333, 5.6666666667, 2.6666666667, 5.3333333333, 5, 6,
4.3333333333, 6.6666666667, 7)), .Names = c("ID0", "year", "SatisAvg"
), row.names = c(NA, -30L), class = "data.frame")

Comment: `(1 + year | ID0)` specify a random intercept and a random slope, both grouped by `ID0`. 15 unique IDs times (intercept + slope) gives 30 random effects. You don't have sufficient observations to support the model.
Comment: @Roland: Put that sentence in a post so we can upvote it properly. It answers the OP's question.
Comment: @Roland: Feel *the rep* move towards you!
Comment: *ding* That's a light bulb turning on and a sudden recall of all my coursework. Thanks.
Comment: Are you referring to any on-line course you can recommend?
Comment: @usεr11852 OK, done.
Answer: (1 + year | ID0) specify a random intercept and a random slope, both grouped by ID0, and additionally their correlation. See the cheat sheet for an explanation of the syntax.
15 unique IDs times (intercept + slope + correlation) gives 45 random effects. You don't have sufficient observations to support the model.
Comment: how many observations would you need to support this model? Trying to wrap my head around the data needed to estimate X number of random effects.
Comment: @Brigadeiro I suspect your question reflects a lack of understanding of mixed-effects models. In your experimental design you need to decide two numbers: the number of subjects and the number of measurements per subject. 15 subjects is sufficient in many cases. For OPs model you'd want at least 3 to 5 observations of each subject. Ultimately, a power analysis is necessary.
Comment: I am always looking to improve on what I know. I understand power, but this seems like it is less of a power issue and more of a model identification problem to me. My question is essentially how to determine how many random effects is too many? What goes into this? Thanks.
Comment: @Brigadeiro You are expressing this in a wrong way. You have never too many random effects. The random effects result from the experimental design. You can only have data that is insufficient to estimate the model and sometimes random effects can be negligible. And even if you have insufficient data to estimate the model, you can sometimes fix that by switching to a Bayesian model with informative priors. If data is sufficient to support a mixed-effects model does not only depend on the number of fixed and random effects but also on effect sizes (including correlations between effects).


Executar aplicação PHP (Zend Framework) no servidor

Question: já deixo claro que não sou programador PHP e sim Java, mas tenho que subir uma aplicação da minha empresa em uma instância na AWS (Amazon Web Services).
Bem, estou com dificuldade, até porque é a primeira vez que trabalho com projetos
PHP. Tenho uma maquina rodando Apache2 MySQL e o PHP5.5 (espero que satisfaça o deploy). Pelo que me parece a aplicação foi desenvolvida cm o Zend Framework.
Realizei a copia da aplicação para o caminho relativo no servidor /var/www/html
Agora não sei qual o próximo passo. Como realizo o "start" na aplicação.
Para ajudar aqui está o projeto no qual o apache esta servindo
http://trust.joocebox.com
EDIÇÃO
Bem pessoal depois de uma longa conversa com o Édipo (que foi de grande valia), infelizmente não conseguimos rodar a aplicação.
Mas não desisti! Criai uma nova instancia instalando o LAMP server assim como fiz o Download do Zend e copiei o conteudo da pasta library (do framework) para dentro da library do meu projeto, mas o mesmo apresenta erro 404! Alguém sabe o que posso estar tentando fazer para sanar o problema?
Abaixo segue o log:
[Wed Apr 15 17:39:59.956167 2015] [:error] [pid 7336] [client
188.8.131.52:13725] script '/opt/lampp/htdocs/trustbox/index.php' not found or unable to stat cat: /opt/lampp/var/mysql/ip-172-30-0-15.pid: Permission denied cat: /opt/lampp/var/mysql/ip-172-30-0-15.pid: Permission denied

Comment: Sabe se é Zend 1 ou Zend 2?
Comment: Oi Édipo. Infelizmente não sei te informar nesse exato momento. Mas provavelmente o 2
Comment: Essa aplicação é Zend 1
Comment: você fez aquele esquema de colocar a public como a "html" ?
Answer: Depois de uma longa conversa, conseguimos subir a aplicação com esses passos.

Instalar o PHP 5.5, pois o servidor estava utilizando PHP 5.3 e o projeto usava sintaxes do PHP 5.4
Instalar o driver do mysql para o PDO
Habilitar o mod_rewrite
Copiar a aplicação para o servidor
Copiar o Zend Framework 1 para a pasta library do projeto.
Configurar o diretório public do projeto como a raiz do apache ao invés do /var/www/html.
Importar a base de dados
Configurar o banco de dados no arquivo application/configs/application.ini

Não foi fácil, a cada passo surgia um erro diferente, na verdade os passos nem foram feitos nessa ordem, coloquei uma ordem ideal aqui no stack.
Caso sua aplicação gere arquivos, como passo 9 sugiro:

Configurar permissão de escrita nas pastas em que arquivos são gerados.

Isso é muito comum para aplicações que tem upload de arquivos, por exemplo as imagens de um CMS.
O que nos ajudou a conseguir chegar nisso foi olhar os arquivos de log, um pouco da minha experiência para identificar possíveis causas de erros, habilitar os display erros nas configurações do application.ini.
Erros e Soluções

Desconfiei da necessidade do item 1 pois tivemos um log indicando erro numa sintaxe que começava com [, olhando o arquivo vi a sintaxe de short array, vimos também a aplicação usando short tags para imprimir <?=, e elas são habilitadas no PHP 5.4 por padrão.
Desconfiei da necessidade do item 2 pois estavamos recebendo null em um foreach, para confirmar, executamos um script para testar a conexão com o banco de dados.
Desconfiei da necessidade do item 3 pois ao digitar qualquer rota da aplicação na url, recebia uma mensagem de arquivo não encontrado. O comportamento correto era direcionar para o index.php.
Desconfiei da necessidade do item 5 pois estávamos tendo uma tela em branco e nos logs não estava encontrando a classe Zend\Application.
Desconfiei da necessidade do item 6 pois estávamos tendo erros de rota, alem de ser necessário em produção.

Referencias:

http://framework.zend.com/downloads/latest#ZF1
http://framework.zend.com/manual/1.12/en/zend.application.quick-start.html
https://stackoverflow.com/questions/13375061/installing-pdo-driver-on-mysql-linux-server
https://askubuntu.com/questions/14763/where-are-the-apache-and-php-log-files
http://jaydson.org/habilitar-mod_rewrite-no-apache/
http://php.net/manual/pt_BR/pdo.connections.php
Comment: Por favor evitem longas discussões nos comentários; a conversa de vocês foi [movida para o chat](http://chat.stackexchange.com/rooms/54280/discussion-on-answer-by-edipo-costa-reboucas-executar-aplicacao-php-zend-framew)


Product rule question about Alphabet

Question: I am trying to understand the product rule and I have a simple example it says,
<code> If I have a license plate with two English letters how many different plates
 can be made?
</code>
The answer is 26^2
Now another question is in the same format but it asks how many plates can be made with upper and lower case letters. Would this still be counted as 26^2? Or would this be 52^2? Or are they all different sets, making it 78^2? I looked through lecture slides and they were no help. Thanks again.
Comment: That is not a permutation. You should google "Variation with repetition"
Answer: To think about the problem intuitively, imagine just choosing one letter out of the set of upper and lower case letters. You have $26$ lower case letters and $26$ upper case letters, giving you $26+26=52$ characters in total. Therefore there are $52$ potential choices for the first character.
Choosing for the second letter is exactly the same, and so you can choose any of the $52$ characters; combining these is a simple matter of multiplication (because for each of the $52$ choices for the first character there are $52$ choices for the second character). Therefore we have:
$$52\times52=52^{2}=2704\text{ combinations}$$
Comment: Thanks, my instructor for summer is teaching his first class and he doesn't stretch his time out well, leaving him to rush over 50 slides in 15 minutes!
Comment: @HermesTrismegistus No problem, glad to help! If this answered your question could you click on the tick next to the answer to mark the question as answered, so it no longer shows up in the unanswered section? Thanks!

Product rule question about Alphabet


$ \partial U$ is uncountable.

Question: Let $U\subset\mathbb{R}^n$ ($n\ge 2$) be a domain (bounded). How to prove that $\partial U$ is uncountable?
Domain: connected open set
$\partial U:$ boundary of $U$
Any hint would be appreciated.
Comment: It's false. Look at the the plane minus the origin.
Comment: What do you consider a "domain"? Just a subset of $\mathbb R^n$? Does it have to be open?
Comment: @zhw The OP is only allowing bounded sets as "domains", so the punctured plane is not allowed.
Comment: @JimBelk The post is edited after that comment.
Answer: take a point in the set x. Take rays emanating from it. Map a point, p, on the unit circle to the last point in the boundary on the ray from x through p.
This injective.
So the cardinality of the boundary is at least as big as that of the unit circle.
Comment: domain usually means open
Comment: Note that this only works as long as $U$ is open. For a closed counter-example, take any one-point set.

$ \partial U$ is uncountable.


iOS 7 universal background UIViewController

Question: I am trying to set up a UIViewController in my app which always remains in the background of all other UIViewControllers. What I want it to do is display a repetitive animation continuously in the background, unaffected my transitions and navigations in the UIViewControllers in the foreground. Can anybody suggest a good method to do this?
Comment: Hi, check my answer, I had this test laying around, just uploaded to github, with animation of a cat! haha .)
Answer: You could create your own UINavigationController and add your animation view to its background in the viewDidLoad method
self.view insertSubview:myAnimatedView atIndex:0

And make sure that your other viewcontollers are transparent.
See also https://stackoverflow.com/a/13096911/443270
Comment: Thanks. I will try this out and let you know how it goes! :)
Answer: Make a view controller that will have your background view and animation as your root view controller. Then make the view controller that you want to control the rest of your app (we'll call it your navigation controller). Add the view of your navigation controller as a subview of your background view controller.
edit:
You can't do this with tab bar controllers as they must be the root view controller.
Answer: start with a subclassed UINavigationController with your animation on ViewDidLoad
push the viewcontrolelrs on this subclassed NavController
example from my github page
https://github.com/mako34/backgroundNavController


How can I insert java file inside of code in Java

Question: I wanted to know if there was a way to import the code of dynamic changing code into the main coding. Something like this:
Main:
int x;
(insert input.java)

Contents of input.java:
x = 2;

Can I import the code inside input.java to the main code?
Comment: If you mean something like c's include directive, absolutely not.  Much of Java's design is built around not having to do stuff like that.
Comment: What do you mean by "dynamic changing code"?  i.e. What is the use-case here?
Comment: Do you mean at compile time or at run time? If you want to include one source file from another at compile time, the answer, as jjm said, is a definite 'no' - the java language does not support this. If you're trying to include code at run time, in theory there are ways to do it, but nothing straight-forward, and this almost certainly is not a good idea. What is it that you are trying to accomplish?
Answer: Java does not have include directives at source compilation time.
Neither does it have an eval for evaluating new Java source code at runtime.
The only real way to get new Java code into a running Java VM is via classloading.
However, since the advent of javax.script (Java 6), a sufficiently supported runtime (e.g. the Nashorn Javascript implementation from Java 8) could import and eval some scripting code that called back into a Java API. This is a huge subject & too big to address in depth here.
Comment: Just a thought: Maybe some compiling tool has this feature. For example, some time ago [someone posted a question](http://stackoverflow.com/questions/27748415/is-there-something-like-ifdef-for-methods-in-java#comment43908043_27748415) about how to remove method declarations conditionally like C does with `#ifdef`. I knew that with java you can't do it; what I **didn't know** was that with Ant you can. You can specify some "special" comments that ant has to look for _before_ compiling, and then how it should behave when those comments are found. Maybe there is a way to do `include`s with Ant?
Comment: Sure, if there's some kind of pre-compilation process to generate code, then that would work, but it would then mean that everyone else would have to follow your build process, and your IDE wouldn't work properly with those files, etc. One possibility might be to have an initial preprocess step that generates source from a non-Java format (BNF grammar or what have you) & then use normal Java from then on. But then that's not really an #include like OP wanted.
Answer: Java has no equivalent of eval, or any other construct that is capable of evaluating code at runtime.  It is perfectly capable of parsing external data, such as XML, and taking action on what it finds.  It can also start and capture output from external processes, which could very well be dynamically generated code.  The details of this process vary depending on your OS.


Is having 150+ user fields too heavy?

Question: Our user entities have about 5 fields for the public profile, and 5 fields with settings that determine the content of 60 other fields we need for our implementation (I've thought of making this 60 "computed fields"). The last ones can be overridden by the user, so we need another 60 to store the user entered values (without loosing the defaults) and 30 fields to act as a flag that indicates if the default or custom version is used (30 flags are enough because the 60 fields go in pairs, they are 30 pairs).
Let's say that we attach the 150+ fields to user entities: Wouldn't that be too heavy, especially when viewing the user profile page (where all the other fields are not necessary)?
Should we define a custom field that would integrate a pair of the default values, a pair of the custom values, and the flag, so we would only need 30 of those within a user object? Apart from having to define the custom field, we lose the computed field module, I think.
Should we offload user entities by creating a content type to attach the total 60 + 60 +30 fields, and link the user with the content type using the Relation module?
Comment: See http://drupal.org/node/1262480. I would almost consider this cross posting.
Comment: Thanks for answering over there Tim.  I posted in both places with different things in mind.  Here I'm giving all details and asking for a broad solution while there I was trying to squash the specific doubt with filed collection.  Of course I'm talking about the same problem in both posts, sorry for that.
Answer: thats right, consider creating a new entity and relate it through a user reference field, for these types of references, the "references module" is better than the "relations module".
Comment: Thanks Firdous.  Can you tell me why references module is better for these types of references ?  Maybe as it doesn't need to create an entity for the relationship (as relation module does) it is more lightweight ... I'd like to konw, as I have the idea to always blindly use relation module.
Comment: For the record, yes, I was wrong going blindly after relation for all "relating" needs. When there's no need for fields in the relation or the relation is quite simple (1-1 or 1-n), references is a better chance, specially in terms of overheads. Relation module is planning to add a simple, more references-like field so that the module could be the solution for all cases, see http://www.drupal.org/node/1246614#comment-4856364 and the module that hosts that issue if you need a simple reference to other entity than user or node
Comment: if you want to create 1-n relationship then maybe relations is the choice for you, but as the case stated above where you want to extend the user table by adding more fields, then the user reference field in your entity would do your work simply.

Is having 150+ user fields too heavy?


Pesquisa de valor exato ou aproximado em vetor desordenado em C

Question: Estou tentando escrever um algoritmo em C que lê um valor inteiro N e um vetor de 10 posições. Que busque o valor dentro do vetor, se existir informar a posição, porém se não existir, encontrar o valor mais próximo existente. Estou tendo dificuldades em terminar o código, principalmente na parte de encontrar o valor mais próximo e não sei onde estou errando:
<code>#include <stdio.h>

int main(){

    int i, n, vetor[10], posicao, diferenca, menorDiferenca, prox;

    printf("N: ");
    scanf("%i", &n);
    printf("Vetor: ");

    for (i = 0; i < 10; i++){
    menorDiferenca = abs(n - vetor[0]);

        scanf("%i", &vetor[i]);
            if (vetor[i] == n){
                posicao = i;
                printf("\nposicao: %i", posicao);
                break;
            }
            else{
                diferenca = abs(n - vetor[i]);
                if (diferenca <= menorDiferenca){
                    prox = vetor[i];
                }
            }

    }

printf("\nvalor prox: %i", prox);
return 0;
}
</code>
Comment: Teste o menorDiferenca = abs(n - vetor[0]); antes do for, creio ser isto.
Comment: https://ideone.com/fPvT6D
Answer: Bom, sou um pouco iniciante em C, mas construi a base de um algoritmo de acordo com o problema que você pede.
<code>#include <stdio.h>
#include<conio.h>

const int TAMANHO = 10;
void main(){
    //Declarando vetor
    int vet[TAMANHO];
    //Declarando Variaveis
    int i, n, k, posicao, maior = 0, menor = 0, maiorNumero = 0;

    //loop pra ler os numeros do array
    for(i=0; i<TAMANHO; i++){
        printf("Insira um numero:");
        scanf("%d", &vet[i]);
    }

    //Quebra linhas
    printf("\n");

    //ler N
    printf("N: ");
    scanf("%d", &n); //N é o numero que o usuario saber se ha no array

    //loop para saber o maior numero do array
    for(i=0; i<TAMANHO;i++){
        if(maiorNumero < vet[i]){
            maiorNumero = vet[i];
        }
    }

    //loop quando o numero esta dentro do array
    for(i = 0; i < 10; i++){
        if(n == vet[i]){
            printf("O numero %d esta no vetor na posicao %d", n);
        }
    }

     // Variáveis para armazenar os números mais próximos
    int numeroProximoMaior = -1;
    int numeroProximoMenor = -1;

    // Loop para encontrar os números mais próximos
    for (k = 1; k <= maiorNumero; k++) {
        for (i = 0; i < TAMANHO; i++) {
            //pega o valor n e soma k.
            maior = n + k;
            //pega o valor n e subtrai k.
            menor = n - k;

            if (maior == vet[i]) {
                numeroProximoMaior = maior;
            } else if (menor == vet[i]) {
                numeroProximoMenor = menor;
            }
        }
        // Se ambos os números próximos forem encontrados, pare o loop
        if (numeroProximoMaior != -1 && numeroProximoMenor != -1) {
            break;
        }
    }

    // Verificando se foram encontrados números próximos e imprimindo os resultados
    if (numeroProximoMaior != -1) {
        printf("O numero mais proximo maior que %d no vetor e: %d.\n", n, numeroProximoMaior);
    }
    if (numeroProximoMenor != -1) {
        printf("O numero mais proximo menor que %d no vetor e: %d.\n", n, numeroProximoMenor);
    }

    getch();
}
</code>
Na última parte do código, a openIa me ajudou a terminar.
Comment: [Conteúdo gerado por ChatGPT não é permitido na rede](https://pt.meta.stackoverflow.com/q/8842/137387)
Comment: Qual a parte de **Conteúdo gerado por ChatGPT não é permitido na rede** você não entendeu?
Comment: Isso mostra como o ChatGPT ainda está longe do ideal, pelo menos como gerador de código. Dá pra fazer de forma muito mais simples: https://ideone.com/fPvT6D - Independente disso, o código está errado (mais um motivo pra não confiar no ChatGPT, tem que conferir tudo que ele responde). Teste, por exemplo, com os números `2, 5, 6, 7, 9, 10, 11, 23, 3, 15` e busque pelo número `18`. Seu código vai imprimir tanto o 23 quanto o 15 (sendo que somente o 15 deveria ser mostrado).
Comment: Assim como expliquei no final da linha, as ultimas 2 linhas foram geradas pela openIA. O resto foi produzido e pensado por mim.
Comment: Entendi, obrigado pela reflexão.


A combination problem about same sum subsets

Question: Suppose $k$ is such that, given any $k$ distinct integers in $\{1,2,\dots,100\}$, there are two distinct subsets with the same sum. What is the minimum possible value of $k$?
I have $8≤ k_{min} ≤10$. For the lower bound, note  $\{1,2,4,8,16,32,64\}$ has size $7$ and no distinct subsets with the same sum. And if you have a subset of size $10$, then there are $1024$ distinct subsets (all lying in $\{0,1,2,\dots,1000\}$, so two distinct subsets must have the same sum.
Comment: https://oeis.org/A276661
Answer: The 8-subset $\{54, 76, 87, 93, 96, 98, 99, 100\}$ from an answer to this question shows that $k \ge 9$.


SQL: How to return all NULLs when no record found?

Question: I have a simple SELECT...
SELECT  TETmeetingID,
        DateID,
        WeekNo,
        TETID,
        TradeStaffID,
        EngStaffID,
        MathsStaffID,
        IoTStaffID,
        Others,
        TradeStaffPresent,
        EngStaffPresent,
        MathsStaffPresent,
        IoTStaffPresent,
        CurricTrade,
        CurricEnglish,
        CurricMaths,
        CurricIoT,
        CurricAlign,
        Notes,
        WeeksToGo,
        TotalWeeks,
        CreatedDate,
        CreatedBy,
        Complete,
        CompletedDate,
        CompletedBy
FROM tblTETMeeting
WHERE TETmeetingID = @SomeParameter

Works of course when the WHERE clause returns true.
But if it does not, I want to at least see ONE record with NULLs in every column.
How can I do this please? And I chose the above example to show the possible number of columns I could be using, so if there's a more generic query that can "determine" the columns and not have to hard-code them into the answer, that would be preferred.
Thanks
UPDATE
I've tried WITH TIES, but that also did not return a single record. Maybe I was doing it wrong. I've also tried the UNION NULL, NULL, etc trick, but that is messy when the number of columns could be undefined 'n'. The only way I can do this properly, but I am still forced to provide the correct number of NULLs is with a CTE type query.
WITH CTE (    SELECT  TETmeetingID,
            DateID,
            WeekNo,
            TETID,
            TradeStaffID,
            EngStaffID,
            MathsStaffID,
            IoTStaffID,
            Others,
            TradeStaffPresent,
            EngStaffPresent,
            MathsStaffPresent,
            IoTStaffPresent,
            CurricTrade,
            CurricEnglish,
            CurricMaths,
            CurricIoT,
            CurricAlign,
            Notes,
            WeeksToGo,
            TotalWeeks,
            CreatedDate,
            CreatedBy,
            Complete,
            CompletedDate,
            CompletedBy
    FROM tblTETMeeting
    WHERE TETmeetingID = @SomeParameter) AS tbl1

select * from CTE WHERE cte.TETmeetingID IS NOT NULL UNION SELECT NULL,NULL,NULL, etc

Comment: @sstan the last part of whizzle's link can be adapted to work for any number of columns. e.g. `select top 1 * from (myquery union all select null,null,null...) t order by case when TETmeetingID IS NULL THEN 1 ELSE 0 END` but yes it doesn't directly answer the question here.
Comment: http://stackoverflow.com/questions/8098795/return-a-value-if-no-record-is-found
Comment: Actually, the accepted answer in @whizzle's link is really only useful if you are returning a single ***field***, which is not the case here.
Comment: This sort of thing is best handled at the application layer, not in the query.
Comment: Other than the fact that I don't think this should be done in SQL, the easiest way to do it (IMO) is with an IF/ELSE statement. e.g. `if exists (select 1 from tblTETMeeting WHERE TETmeetingID = @SomeParameter) THEN myQuery ELSE SELECT NULL, NULL...`. Alternatively, the answers in whizzle's link work if there's only one row expected.
Comment: @sstan Thanks Stan, that's the problem. Yes one column is easy, but where I have multiple columns? And what if I am forced to use SELECT * because the underlying data source comes from a legacy system? Thanks
Answer: This does what you want:
SELECT C.*
FROM
(SELECT 1 As DummyColumn) As DummyTable
LEFT OUTER JOIN
tblTETMeeting C
ON TETmeetingID = @SomeParameter

Comment: The table called `DummyTable` is just one record with one column. So now you have one record _no matter what_. Then you optionally join it to your 'real' record which may or may not exist. By optionally I mean use an `OUTER JOIN`. The 1 doesn't mean anything. You could use `(SELECT 'Mastodon' As MyFavouriteBand) As MyFavouriteStuff` and it would still work. But a warning: `SELECT *` is bad practice for many reasons - don't get into the habit of using it.
Comment: Perfect! Yes that worked. But how?! How does a single SELECT 1 do this?
Answer: This should do.
The idea is to add a flag column and an extra row with NULL in all columns except the flag column.  In this example, ConditionTrue is the flag column. 1 as true and 0 as false.  This means that if the predicate in WHERE is true, the result will be all the rows returned with ConditionTrue of 1 plus a row of null with ConditioinTrue of 0.  On the other hand, if nothing was returned, it'll be just the the row of null with ConditionTrue of 0.  By putting the result into a temp table, you can then filter out unwanted rows and columns.
If the predicate is true, then there will always be 2 or more rows.  So you can check @@ROWCOUNT to your advantage.  1 means no hit, bigger means hit.
Lastly, I don't want to type all 26 columns again, so I dropped the ConditionTrue column and used SELECT * as a shortcut.  If you don't mind the flag column, leave it be, or you can move the ALTER statement before the IF block and filter out differently, like TETmeetingID IS NOT NULL.
IF OBJECT_ID('Tempdb..#tblTETMeeting','U') IS NOT NULL
    DROP TABLE Tempdb..#tblTETMeeting;

DECLARE @COUNTS INT;

SELECT  TETmeetingID,
        DateID,
        WeekNo,
        TETID,
        TradeStaffID,
        EngStaffID,
        MathsStaffID,
        IoTStaffID,
        Others,
        TradeStaffPresent,
        EngStaffPresent,
        MathsStaffPresent,
        IoTStaffPresent,
        CurricTrade,
        CurricEnglish,
        CurricMaths,
        CurricIoT,
        CurricAlign,
        Notes,
        WeeksToGo,
        TotalWeeks,
        CreatedDate,
        CreatedBy,
        Complete,
        CompletedDate,
        CompletedBy,
        1 AS ConditionTrue
INTO #tblTETMeeting
FROM tblTETMeeting
WHERE TETmeetingID = @SomeParameter
UNION ALL SELECT NULL, NULL, NULL, NULL, NULL, NULL,NULL, NULL,NULL, NULL, NULL, NULL, NULL, NULL,NULL, NULL,NULL, NULL, NULL, NULL, NULL, NULL,NULL, NULL,NULL,NULL, 0;

SET @COUNTS = @@ROWCOUNT;

IF @COUNTS > 1

    SELECT * FROM #tblTETMeeting WHERE ConditionTrue = 1;
ELSE
    BEGIN
        ALTER TABLE #tblTETMeeting
            DROP COLUMN ConditionTrue;
        SELECT * FROM #tblTETMeeting;
    END;

Comment: Thank you for that long answer, but I'd prefer the other answer where it's all in one single SQL command.
Answer: Remember UNION is the counterpart of logical OR:
SELECT TETmeetingID
  FROM tblTETMeeting
 WHERE TETmeetingID = @SomeParameter
UNION
SELECT NULL AS TETmeetingID  -- don't make me write them all out!
  FROM tblTETMeeting
 WHERE TETmeetingID <> @SomeParameter

Speaking of logic, remember in SQL a search condition (WHERE clause) can evaluate true, false and unknown due to SQL's confusing (and inconsistently applied) three-value logic. So if TETmeetingID or @SomeParameter can ever be null then you may need to add some code to handle this.


store inputs into list of string in python

Question: Is there any other optimized and simple way to store inputs into a list of string.
Input
bcdef
abcdefg
bcde
bcdef

output
['bcdef', 'abcdefg', 'bcde', 'bcdef']

below is the code I tried to code
l = []
for i in range(4):
    l.append(input())
print(l)

Comment: The code you posted works fine for me. What's the problem?
Comment: yeah I know that's fine I am figuring is there any other best way to do tath
Comment: If you want to iterate over stdin, maybe you want [`fileinput`](https://docs.python.org/3/library/fileinput.html)?
Answer: You could also write this as a list comprehension, like this:
l = [input() for i in range(4)]
print(l)

Answer: You can try the following:
import sys
l = sys.stdin.read().split()

You will need to run Ctrl+D once you have entered you input.
Comment: actually I am solving the problem in hackerank i don't is this works
Comment: @savershkumar, just try it and let me know
Answer: This works:
l = [input(), input(), input(), input()]

Comment: this will work as long as he has to enter 4 strings.
Comment: The provided answer was flagged for review as a Low Quality Post. This provided answer may be correct, but **it could benefit from an explanation**. Code only answers are not considered "good" answers. Here are some guidelines for [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer). From [review](https://stackoverflow.com/review).


Why is it recommended to work in Linux with a non-root user?

Question:
Possible Duplicate:
What's wrong with always being root?

The very first rule I've been taught about Linux is never to use root as your main user and I was wondering why
Comment: Why voting the question down? Isn't it the place to ask what you don't know?
Answer: Because root is the superuser. As root you can do anything, as such it is easy for you or someone to kill your system.
A quick search could have saved this
Answer: Because if you type the wrong thing in as root, it can have disasterous consequences:
<code>rm -rf .. /    # ONOES!  A SPACE!
</code>
Answer: Because if you make a small mistake as a non-root user, there won't be any extremely fatal outcomes like:

deleted /
move of binaries
deletion of special folders

Whilst you can make the mistakes with sudo, often you will think twice before issuing a command as you need  to enter your password.
Answer: The downfall of Windows security has always been users logging in with Administrator privileges. UNIX equivalents have always had better security because it does not allow root to log in as a normal user. If you need to do something, you run that with escalated privileges (sudo or su) and then you go back to a normal user.


A question about quadratic form of normal variables

Question: Assume $X\sim N_{n}(u,\sigma ^{2}I_{n})$,$A$ and $B$ are $n×n$ symmetric matrix,moreover,$X'AX$ and $X'BX$ are independent,then how to prove $AB=0$
Any hint will be appreciated
Comment: Let $\phi(u,v)=E\exp(tX'AX + uX'BX)$ be the mgf of the two independent quadratic forms.  Then $\phi(u,v)=\phi(u,0)\phi(0,v)$, which (among other things) implies $\det(I+tA+uB)=\det(I+tA)\det(1+uB)$ and so on.
Answer: I think I have a proof, which I will sketch here.  This problem is very similar to another one posed by OP but  possibly easier.  We know that $\int_{\mathbb R^n} \exp(-\|x\|^2/2) \,dx$ is $(2\pi)^{n/2}$ so we know that $\int_{\mathbb R^n} \exp(-x^tQx/2)\,dx = (2\pi)^{n/2}/\sqrt{\det Q}$, at least for matrices $Q$ close to the identity matrix, and hence the moment generating function $\phi(t,u)$ of the random vector $(-x^tAx/2, -x^tBx/2)$, is given by  $$\phi(t,u)=E\exp(-t x^t A x/2 -u x^t B x/2) = \det(I+tA +uB)^{-1/2},$$ at least for sufficiently small $t$ and $u$.  If $x^tAx$ and $x^tBx$ are independent, then $\phi(t,u)=\phi(t,0)\phi(0,u)$.
This implies that $\partial^2/\partial t \partial u \log \phi(t,u)=0$
which leads to the equation $$\operatorname{tr} \left( (I+tA+uB)^{-1} A (I+tA+uB)^{-1} B\right) = 0$$ for all $(t,u)$ in some neighborhood of $(0,0)$. This in turn leads to the following identity in  $\mathbb R[[t,u]]$:
$$ S=\sum_{k,l\ge0} (-1)^{k+l}\operatorname{tr}\left( (tA+uB)^k A (tA+uB)^l B\right) = 0.$$  Easy consequences are: $\operatorname{tr}(AB^k) = \operatorname{tr}(BA^k) = 0$ for all $k\ge 1$ and (taking the  coefficient of $tu$ in $S$):$ \operatorname{tr}(ABAB+BAAB+AABB+BAAB+AABB+ABAB)=0$ from which (by making free use of the identity $\operatorname{tr}(PQ-QP)=0$) yields $$4\operatorname{tr}(AABB)+2\operatorname{tr}(ABAB)=0.\tag{*}$$
Now observe that $\operatorname{tr}(AB-BA)(AB-BA)^t \ge 0$ and $\operatorname{tr}(AB+BA)(AB+BA)^t \ge 0$, from which we learn $$\operatorname{tr}(AABB)\ge\operatorname{tr}(ABAB)$$ and $$\operatorname{tr}(AABB)\ge-\operatorname{tr}(ABAB),$$ so $|\operatorname{tr}(ABAB)|\le \operatorname{tr}(AABB).$  This, together with $(*)$, implies $\operatorname{tr}(AABB)=0$ which implies $AB=0.$


Nginx add_header for a 50* page

Question: I'm currently trying to get nginx to add a header to the response when it is sending some kind of 50* error. I already have an add_header directive on the http block, and that gets respected for all requests except it seems errors. I also tried the following in one of my vhosts:
location /mediocregopheristhecoolest {
    add_header X-Test "blahblahblah";
    return 502;
}

Going to that page gives me a 502, but no header. Is this simply something nginx doesn't do, or am I doing it wrong?
Comment: Could you post the output of $ curl -I //mediocregopheristhecoolest
Answer: Since Nginx 1.7.5 you can use always to add a header irrespective of the response code:
add_header X-Test "blahblahblah" always;

Comment: Frustratingly, the version in Debian's repos is currently outdated (1.6.x), but nginx [maintains their own repository](http://nginx.org/en/linux_packages.html) with the latest stable build (1.8.x right now).
Comment: If you want to upgrade an already working debian system, debian backports is safer... https://packages.debian.org/jessie-backports/httpd/nginx The upstream package use different package organisation (may cause some downtime instead of the smooth nginx upgrade mechanism). And its postrm script removes the logs. And a couple of other small differences...
Comment: This doesn't work for me. If I make nginx reply with 502 because all the upstream servers are unavailable due to fails, it doesn't send the header. I even tried setting on the http block
Comment: nevermind, it seems somehow wget was not displaying the header with -S, but with curl i could see it wtf
Answer: The documentation states that add_header "Adds the specified field to a response header provided that the response code equals 200, 204, 206, 301, 302, 303, 304, or 307. A value can contain variables."  So it doesn't work with a 502.
I forgot to add that you can use the third party headers more module to add headers to other codes.  You'll probably have to recompile to add it, though.
Comment: See comment of marat: the new nginx version supports setting the header irrespective of response code

Nginx add_header for a 50* page


Opening an Excel spread sheet in .NET on a x64 system

Question: I can't open an Excel spread sheet with .NET on an x64 server using the following connection string
"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + filePath + "; Extended Properties=Excel 8.0;"
I get The 'Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine.
I installed the 2007 Office System Driver: Data Connectivity Components and tried with Microsoft.ACE.OLEDB.12.0 and this connection string
"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + filePath + "; Extended Properties=Excel 8.0;"
and got "The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine."
I searched Google with the only response being it's a 64 bit problem, anyone have an Idea how to fix this?
Answer: You can use the Open XML SDK to open an Excel 2007 file and read or change the contents.
http://www.microsoft.com/downloads/details.aspx?FamilyID=c6e744e5-36e9-45f5-8d8c-331df206e0d0&DisplayLang=en
This does not use the Excel program but opens it as an xml document. Thus you get around the 64bit problem.
It may however require major changes to your program.
Answer: You can only do this from the 32 bit version of the framework.  if its an ASP.net app you can change the server to run this under the 32 bit framework.  If it's a native app you'd have to recompile (although that's probably best asked on stackoverflow)
Answer: you cant, the drivers arent there. Only workaround I have found is if you can, save it as a csv and read it that way.
Answer: All Office drivers are 32-bit only, so you can't use Office files from x64 applications; the problem is most commonly experienced when ASP.NET applications on x64 systems try to open Acess databases.
You need to force you application to run in x86 mode; is it a Windows application or a ASP.NET one? In ASP.NET, you can do it as stated here.
Answer: I haven't tried it, but apparently the /passive installation switch might be a workaround with 64bit Ace.


MySQL CPU High Usage

Question: I got a problem with CPU usage on my VPS, mysqld use 100% CPU and my site go down, i have a small package, 512MB Ram, wich 300 is free, and my site has 1000-1500 unique visitors, and 50.000 views / week.
my.cnf
<code>[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
user=mysql
query_cache_size=8M
read_rnd_buffer_size=256K
tmp_table_size=16M
max_heap_table_size=16M
thread_cache_size=4
sort_buffer_size=2M
[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
</code>
My question is, if i upgrade RAM it's possible that CPU usage go back to normal?
Comment: Check your `slow_query` log and see if there's anything you can optimize. Aside from that, you're going to have to post some more detailed CPU/memory/IO statistics than just '100% CPU'. ie: unless a significant portion of your time is spent in `IOwait` you're not going to regain any CPU cycles by adding more RAM.
Comment: you could try increasing your query_cache_size to reduce the number of  times a result has to be generated: http://dev.mysql.com/doc/refman/5.0/en/query-cache-configuration.html. This would incur an increase in memory usage as the cache is stored in memory.
Comment: How big is your database? How smart are your queries?
Comment: My database has 1GB, and 1 milion rows on a table.
Answer: Solved, was one query in footer wich selected from a table with ~1 milion rows, the problem was that query was also counting rows every pageload.

MySQL CPU High Usage


Algebraic inequality proof

Question: Let $\{p_i\}_{i=1...n}$ be a set of real numbers with $p_i \in [0,1] \; \forall i$, and $\sum_{i=1}^n p_i = 1$. I assume that there is one element in this set that is strictly larger than all the others, and wlog I call it $p_1$. I am attempting to prove or disprove the following proposition:
For all $\alpha > 1$, $p_1^{\alpha-1} > \sum_{i=1}^n p_i^{\alpha} $.
Any help appreciated.
Comment: What did you attempt prior to posting this?  Please add your answer to this question in your post; otherwise  it comes across as a problem statement problem with not context, no effort, etc.
Answer: Note that
$$p_i^{\alpha}=p_i^{\alpha-1}p_i\leq p_1^{\alpha-1}p_i$$
for all $i$, with the equality being strict for $i>1$. Therefore if $n>1$ then
$$ \sum_{i=1}^np_i^{\alpha}<p_1^{\alpha-1}\sum_{i=1}^np_i=p_1^{\alpha-1}$$
since $\sum_ip_i=1$.

Algebraic inequality proof


Virtual keyboard using ASCII codes

Question: I created a virtual keyboard with the following sample code.

<form name="virtual">
<input type="text" name="text"/>
<input type="button" onclick="vkb('a')" value="a" style="border:none;"/>
</form>

This code is unable to accept a ', and \ symbols. Then I modified my code in below way

    <form name="virtual">
    <input type="text" name="text"/>
    <input type="button" onclick="vkb('a')" value="a" style="border:none;"/>
    <input type="button" onclick="vkb1()" value="'" style="border:none;"/>
    </form>

Now finally I have issue with only \ I am unable to add this stroke using my Virtual Keyboard. Can anybody help me how to add \ to textbox? Else anybody please provide me with the syntax to add \ using asci values.
Answer: Too long, didn't read :-)
Try this:

<form name="virtual">
    <input type="text" name="text"/>
    <input type="button" onclick="vkb(this)" value="a" style="border:none;"/>
    <input type="button" onclick="vkb(this)" value="\" style="border:none;"/>
    <input type="button" onclick="vkb(this)" value="'" style="border:none;"/>
    <input type="button" onclick="vkb(this)" value='"' style="border:none;"/>
</form>

The advantage is that you don't have to write twice the letter of the key :-)
Your problem is that some characters sometimes need escaping (like the \ in javascript for example, it's used to do things like \n that means new line, so to have a \ you need to escape it with a second backslash, like \\)
Try running it for example here http://jsfiddle.net/T9Ptd/1/ or http://jsbin.com/uhakaq/3/edit
Answer: I don't know that you have included enough detail to answer your question.  Keep in mind, though, that the '\' character is used as an escape character in javascript.  That means you sometimes need to double it up, and sometimes even more depending on how many levels of interpretation you are passing through:
Try '\\' to get a slash into the code, or '\\\\' to get two slashes, which would pass one slash another layer down.

Virtual keyboard using ASCII codes


How to train a neural network *not* to give a certain output?

Question: I have a neural network with a softmax layer as final layer. The loss function I use is the categorical crossentropy loss. I want to classify an input to belong to exactly one of N classes. But for some of the inputs, I don't know which class they belong to, but only which class(es) they do not belong to.
What is the best way to implement this as a training example?
The approach I used is best explained by an example:
Suppose we want to separate 4 classes and are given a training example that we know does not belong to classes 2 and 3, then I would supply the following vector as target vector:
[0.5, 0, 0, 0.5]
If instead we knew that the training example does not belong to class 1, then I would supply the following vector as target vector:
[0, 1/3, 1/3, 1/3]
Is this the correct approach? Is my choice of activation function in the final layer correct?
Answer: Usually when doing multi-class classification, we encode the classes using one-hot encoding. For example, in four-class classification, belonging to third class would be encoded as [0, 0, 1, 0]. In your case, you seem to have missing information in the data, since you know only something like "it's not class one, or two", i.e. [0, 0, ?, ?].
Simple solution could be to redefine the problem, and treat it as a multi-label classification problem, where for each training example you would code as 0's the classes that are not positive, while positive, or unknown classes are coded as 1's.
[0, 0, ?, ?] -> [0, 0, 1, 1]
[1, 0, 0, 0] -> [1, 0, 0, 0]
[?, ?, 0, ?] -> [1, 1, 0, 1]

This would make your algorithm learn to classify the possible positives, so you could choose among them to make proper classification.
Notice, that this makes it a noisy labels problem. You have data, but imprecise. Imagine that you had three, very similar, examples, and you would know that the first is "not class one", second is "not class one, or four", while third is "not class three, or four". From this, you could deduce that the examples are certainly not from class four, and probably not from class one, or two, so they likely come from class two. This is how, given enough data, your algorithm could learn the correct answer given noisy labels.
If you additionally have a subset of good data, where all the examples have proper labels, than you could use this data to learn a standard multi-class classifier. Next, you could combine both results, so that first classifier is used to filter the likely classes, and second to make the classification. For example, if the first classifier returns the probabilities of being non-negative $(p_1, p_2, p_3, p_4)$, and the second one probabilities of belonging to the class $(q_1, q_2, q_3, q_4)$, than you could combine those to make classification by taking
$$
\operatorname{arg\max}_i\; (p_1 q_1,\, p_2 q_2,\, p_3 q_3,\, p_4 q_4)
$$
Comment: @Sycorax it sounded simpler for me like this, but you're right, it isn't. Fixed.
Comment: I appreciate that we can, arbitrarily, relabel the positives as 0 and the negatives as 1, or vice-versa, but I'm not grasping what the purpose is of using the coding 1s are *not positive* and the rest as 0s. It seems to fly in the face of convention without a payoff -- or at least, not one that I can perceive. Can you elaborate?
Answer: To answer the question about your approach of providing target distributions: yes, that is a correct approach, and softmax is the right final layer for this approach.
Comment: Can you elaborate? Why is this the correct approach?


Query sql para buscar e uma string igual porém maior que a que está armazenada na tabela

Question: Eu tenho uma tabela que guarda urls de telas do meu sistema, eu queria realizar uma query que me retornasse uma url que vem parametrizada da seguinte forma /avaliacoes-cozinha-segura/avalia-cozinha/2 para essa url que está armazenada assim /avaliacoes-cozinha-segura/avalia-cozinha/, tentei usar o like mais não deu muito certo:
SELECT * FROM fogasdigital.TelaPerfil where url like ('%/avaliacoes-cozinha-segura/avalia-cozinha/2%');

porque aparentemente o like só funcionaria se a url fosse menor que a que está armazenada, mais infelizmente não tenho como trazer ela reduzida do backend, também tentei usar o in mas também não obtive sucesso. O que está impatando é esse 2 que vem do sistema.
Comment: A URL está gravada como /avaliacoes-cozinha-segura/avalia-cozinha/ e você precisa retornar ela como /avaliacoes-cozinha-segura/avalia-cozinha/2? O dois nessa história, não está presente no banco de dados, você só precisa para o retorno?
Comment: A url `/avaliacoes-cozinha-segura/avalia-cozinha/` é a que está no banco e a url `/avaliacoes-cozinha-segura/avalia-cozinha/2` é o parametro de busca `SELECT * FROM fogasdigital.TelaPerfil where url like ('%/avaliacoes-cozinha-segura/avalia-cozinha/2%');`
Answer: Você tem algums formas de normalizar sua string para comparacação.
A primeira seria no próprio SQL usando uma especie de LastIndexOf no T-SQL:
REVERSE(SUBSTRING(REVERSE('/avaliacoes-cozinha-segura/avalia-cozinha/2'),CHARINDEX('/',REVERSE('/avaliacoes-cozinha-segura/avalia-cozinha/2')),len('/avaliacoes-cozinha-segura/avalia-cozinha/2')))

A segunda seria em sua aplicação ou TSQL também, removendo o último char com o substring:
SUBSTRING('/avaliacoes-cozinha-segura/avalia-cozinha/2', 1, LEN('/avaliacoes-cozinha-segura/avalia-cozinha/2') - 1)

Mas creio que provavelmente você perderá performance comparando strings em seu sistema, talvez seria legal você repensar seu código.


Third party getting access to industrial machine on network

Question: I need to allow an outside company to get access to an industrial machine that is on the internal network of our company.
The network setup is a Cisco router that is owned and controlled by our IP (it has ports 443 and 1723 open) and inside we have an SBS 2011 and Win Server 2008 R2. The SBS is the Domain Controller, file server and most everything else, the 2008 R2 server is just used for Navision.
What I would like is for the external party to have access to that industrial machine (lets say internal IP 192.168.1.20) and nothing else.
What would be a good way to go about doing this?
Using Remote Desktop? VPN? If VPN then which ones, I do not fully trust PPTP, getting our ISP to open up ports for other VPN's shouldn't be that big of a deal. Any other options?
Comment: The Cisco router you mentioned seems to be operating a VPN already.
Comment: Well, I do believe (this is a network set up by another person, I am new to this network) that the port 1723 is forwarded to the SBS.
Comment: What about an IPSec VPN tunnel between remote company and yours ? This is usually what i do when i have to deal with such issue in my companie...Opening RDP through Internet (even if filtered by source IP) would be a bad idea IMHO
Comment: Sounds good, can the VPN somehow restrict the user to only one computer or do I need to create an AD account for him and use that to point him to the right computer?
Comment: Your VPN IPSec Gateway should handle this for you if it has an embedded Firewall (as mine). If not, route the VPN Network through Firewall.
Answer: As you're using SBS 2011, you could allow the remote company to use the Remote Web Access website - this will allow them to make an RDP connection to the internal computer via a web page.
In order to do this, you will need to set them up as a user in the SBS Console, give them access to RWA, and remote rights to that particular computer.
I'm assuming that your SBS server has been fully configured properly, and has the RWA running properly. You already have port 443 open, so I'm assuming it is set up.
More info about RWA here


Create a menu with a list of all groups

Question: I have installed the Organic Group module and I created some groups. How can I make a menu which contains a list with all the groups?
Thanks!
Answer: I am not clear what is your requirement. If you want to create a single menu page and want to show list of group name , you can do this using views. Create a view page and list your content and select menu type as normal nemu item.
OR
If you want to create list of menu items according to group name, in that case you should try to create custom menu using hook_menu.
check here https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu/7

Create a menu with a list of all groups


Mapear um campo do tipo CHAR no banco de dados para um campo do tipo bool no C#, com FluentNHibernate?

Question: No banco de dados tenho um campo ATIVO do tipo CHAR(1), onde 'T' = true e 'F' = false.
Hoje, em minha aplicação estou contornando este problema com uma "gambiarra", onde mapiei meu atributo Ativo, como string e criei outro atributo bool IsAtivo que faz algo similar a isso:
public bool IsAtivo
{
    get { return Ativo == "T"; }
    set { Ativo = value ? "T" : "F"; }
}

Nem precisam comentar que é horroroso que eu já to sabendo, até por isso quero melhorar, quando implementei isso não tive tempo para procurar forma melhorar.

Então gostaria de saber se conhecem alguma forma de mapear isso para o nhibernate, através do mapeamento pelo fluent-nhibernate?
// Acredito que alguma configuração aqui pode resolver meu problema
Map(t => t.Ativo, "ATIVO")

Answer: No NHibernate existe um UserType abstrato e específico para este caso, chamado CharBooleanType, que permite que você mapeie um tipo char como bool. Crie uma class que herda deste tipo e sobreescreva as propriedades TrueString e FlaseString:
public class ActiveBoolType : CharBooleanType
{
   public ActiveBoolType()
         : base(new AnsiStringFixedLengthSqlType(1)) { }

   protected override string TrueString
   {
       get { return "T"; }
   }

   protected override string FalseString
   {
       get { return "F"; }
   }

   public override string Name
   {
       get { return "inverted_bool"; }
   }
}

Depois basta mapea-lo da como um tipo customizado apontando para este tipo.
FluentNhibernate:
Map(x => x.IsAtivo).Column("ATIVO").CustomType<ActiveBoolType>();

HBM.XML
<property name="IsAtivo"
          column="ATIVO"
          type="MyAssembly.MyNamespace.ActiveBoolType, MyAssembly" />

Neste link fala um pouco sobre a criação de UserTypes.
Comment: +1 Interessante. Implementação do **[`NHibernate.Type.CharBooleanType`](https://gitorious.org/nhibernate/mainline/source/42f6aa2dcc5a8ced53d1e7e9746f014dce5482d8:nhibernate/src/NHibernate/Type/CharBooleanType.cs).**
Comment: Obrigado pela referência Miguel. :)
Comment: @FelipeOriani, muito obrigado, pela ajuda, muito interessante essa forma. Funcionou perfeitamente aqui.
Comment: Seria possível também utilizar o EnumCharType da mesma forma?
No base de dados legada tenho um campo que é char(1) "F" ou "J". Pessoa Física ou Jurídica, e eu gostaria de mapear para um boleano.


Bootstrap5 how to adjust the tooltip position when I use the arrtitube text-truncate?

Question: I have a table in the html and I don't want to display the long text in the cell. Therefore I use the css attritube 'text-truncate' to truancate it. Besides, I think I can use the bootstrap tooltip to show the long text, some code snippet is like this:

                {{ literature.article_title | default:"None" }}

It works well except the tooltip display at another cell, like this:

The tooltip should appear around the title cell instead of another cell. I think the cause for this problem is the tooltip doesn't know i have trunact the title text and still show in the middle of the whole title text.
So is there any method to solve this problem?
Answer: Swap elements: place span inside a tag and add d-inline-block class to a tag, so that span stretches inside a tag, and has truncated text, and triggers tooltip, and clicking on it will trigger modal set in now parent a tag.
You seem to want to toggle both modal and tooltip, so they should both work.
Try this (for some reason, tooltips won't work here so I've used JS to initiate them, but it should work without it, and toggle both tooltip and modal):

var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
var tooltipList = tooltipTriggerList.map(function(tooltipTriggerEl) {
  return new bootstrap.Tooltip(tooltipTriggerEl)
})

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap demo</title>

Hello, world!

      PMID
      Title
      Abstract

      8781

                <a
                  data-bs-custom-class="custom-tooltip"
                  data-bs-toggle="tooltip"
                  data-bs-placement="bottom"
                  data-bs-title="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
                  class="d-inline-block "
                  >

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

      sdfsd

Modal title

        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>

        ...

        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

    <link href="https://firstname.lastname@example.com/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">

Bootstrap5 how to adjust the tooltip position when I use the arrtitube text-truncate？


Como armazeno vários valores em cada "option" de um "select"?

Question: Eu tenho uma option e dois inputs para alimentar de acordo com o resultado do select.
No select é escolhido o usuário e nos dois inputs são inseridos o endereço e o email do usuário selecionado.
Eu gostaria de saber se é possível ter 2 values possíveis para alimentar os inputs.
Meu código atual é esse, o select já funciona, mas não sei como inserir o segundo valor:

        Paciente

            <select class="form-control get-placa chzn-select" type="text"  name="patient_id">
                <option value="">select</option>
                <option value="rua um">Maria</option>
                <option value="avenida dois">Jose</option>
            </select>

        <?php echo get_phrase('endereço');?>

            <input  readonly="true" type="text" class="form-control nome" name="nome">

        <?php echo get_phrase('email');?>

            <input  readonly="true" type="text" class="form-control email" name="email">

</script>
Answer: Armazenando dados arbitrários em uma tag
Usando data-attributes podemos colocar dados arbitrários em praticamente qualquer tag HTML. No nosso caso, podemos por vários valores no option desta maneira:
<option
   value="Rua Um"
   data-id="101"
   data-email="firstname.lastname@example.com"
   data-tiposanguineo="O+"
>José</option>

O value é do select, mas queremos os dados do option
Você atualmente pega o value com .val. Este valor não vem do option, pois o this se refere ao select que mudou e, consequentemente o .val vem do value atualizado pela seleção do usuário. Ocorre que nós precisamos recuperar os data-attributes que ficam lá no option e não diretamente no select.
Só que quando a opção selecionada muda, não é só o value que sofre uma alteração. O option correspondente ganha o atributo :selected, então podemos nos referir a ele desta forma:
var option = $(this).find("option:selected");

Agora que já aprendemos a localizar o option selecionado, basta recuperar os data-attributes que nos interessam. Com jQuery 1.4.3 ou maior, basta usar o .data():
var email = option.data('email'); // recuperamos o data-email
var id    = option.data('id');    // e o data-id ...
// ... e quantos outros .data() necessitarmos

E se precisarmos do conteúdo textual da tag option?
Não é o seu caso, mas em algumas situações, queremos também o texto dentro da tag option. Usando a mesma lógica do find acima, podemos obter este com o text, evitando um data-attribute redundante:
var option = $(this).find("option:selected");
var nome = option.text();

Demonstração:
Juntando as etapas anteriores, vamos a uma breve demonstração.
Note que simplifiquei o código para nos atermos aos pontos que realmente importam. Entendendo o funcionamento, fica fácil adaptar ao seu layout original.
Usando JS puro:

Paciente

<select type="text" id="meuselect">
   <option value="">select</option>
   <option value="Rua Um"   data-id="101" data-email="firstname.lastname@example.com">José</option>
   <option value="Rua Dois" data-id="122" data-email="firstname.lastname@example.com">Maria</option>
   <option value="Rua Três" data-id="134" data-email="email@example.com">Le Zuul</option>
</select>

id

<input id="id" readonly="true" type="text" name="id">

endereco

<input id="endereco" readonly="true" type="text" name="endereco">

email

<input id="email" readonly="true" type="text" name="email">

Ainda, há uma maneira mais específica de pegar data-attributes (a do exemplo acima é para atributos em geral), como exemplificado pelo colega Diogo nos comments, usando o membro dataset (verifique a tabela de compatibilidade). Segue link:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset
Modo de usar:

 ...
 console.log(elemento.dataset.girafa); // sem o prefixo data-

Usando jQuery, como na pergunta:

Paciente

<select type="text" id="meuselect">
   <option value="">select</option>
   <option value="Rua Um"   data-id="101" data-email="email@example.com">José</option>
   <option value="Rua Dois" data-id="122" data-email="email@example.com">Maria</option>
   <option value="Rua Três" data-id="134" data-email="email@example.com">Le Zuul</option>
</select>

id

<input id="id" readonly="true" type="text" name="id">

endereco

<input id="endereco" readonly="true" type="text" name="endereco">

email

<input id="email" readonly="true" type="text" name="email">

Nota:
Não precisa disso para funcionar, mas o ideal é que os seletores dos campos não sejam ambíguos. Para o demo acima, trocamos as classes por IDs, ficando assim:
$('#email').val(email);

E nos inputs, acrescentamos o ID correspondente:
<input id="email" ...

Comment: Muito obrigada! Era exatamente isso que não sabia como fazer. Valeu!!
Comment: É possível acessar atributos customizáveis sem ser por jQuery, só com JavaScript puro (document.getElem...)?
Comment: @Diogo depois de obter o elemento, faça `elemento.getAttribute('data-nomedoatributo');` - e se quiser usar com CSS puro também dá em alguns casos: https://pt.stackoverflow.com/a/163527/70
Comment: @Diogo atualizei a resposta com uma versão sem jquery
Comment: @Bacco muito obrigado. Depois de ter feito essa pergunta eu até que fucei um pouco aqui e consegui obter esses values através dessa forma (vou seguir um de seus exemplos): `elem.options[elem.selectedIndex].dataset.email`. Assim também deu certinho. Será que são similares ou pode haver alguma diferença (entre essa forma que descrevi e a da sua resposta)?
Comment: @Diogo vai muito da compatibilidade esperada, sempre bom ver no https://caniuse.com - eu geralmente, para fins de Stack Overflow procuro fazer mais didático (onde não compromete o resultado) até pra ser reaproveitado de outras formas (por exemplo, se não fosse usado data-attributes, mas fosse pegar alguma outra característica). - Na MDN já tem a tabela de compatibilidaade do dataset também, segue link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset  - Complementei a resposta com sua sugestão.


Remove title from hook_entity_view

Question: I need to remove title from rendered custom entity.
unset($entity->title) is not good because i still need to use its value in this rendered entity to use in markup.
css display:none is not good idea on my point of view as well.
Comment: "I need to remove title from rendered custom entity." ... "because i still need to use its value in this rendered entity" - you're contradicting yourself in a couple of sentences. Can you clarify the question.
Comment: for e.g. i need $entity->title to use in l() with some other url. Looks like it is not possible to do it in hook_entity_view and should be done in somevere else.
Comment: Where rendered title is generated firstly, in what function?
Comment: It was easy. I made it in my custom entity.tpl.php.
Answer: hook_entity_view(), and hook_entity_view_alter() are not the hooks you should use to avoid an entity title is rendered, as the entity title is not generally passed to the $build parameter passed to those hooks.
This is the content of the $build parameter for three different entity Drupal defines.

Node

Comment

Taxonomy term

Furthermore, the purpose of hook_entity_view() is adding content to $entity->content, not altering $entity. The description given in the documentation page for the hook is the following:

The module may add elements to $entity->content prior to rendering. The structure of $entity->content is a renderable array as expected by drupal_render().

To avoid the title is rendered for an entity, you should use a preprocess function for the template file used by the entity, and unset a variable used from the template file for the title. For example, for a node, a module could use the following code.
function mymodule_preprocess_node(&$variables) {
  $variables['title'] = '';
}

Similar code would work for comments, but in that case the function would be mymodule_preprocess_comment().
For taxonomy terms, there isn't a title but there is the term name, which is printed from the template file using the following code.
<?php if (!$page): ?>

<a href="<?php print $term_url; ?>"><?php print $term_name; ?>

<?php endif; ?>

Setting $term_url, and $term_name to an empty string would cause the following HTML output to be printed.

Comment: Thx for a lot of details, i solved my problem by coping default entity.tpl.php and commented out 'title'.
Answer: By the comments it looks like you took care of this, but I was going to suggest using the hide() function in a template file and then print out that title variable where ever you needed it in the markup of the tpl.
Comment: Thx a lot, i did not know about this function.

Remove title from hook_entity_view


Does anybody have any good material on TacPlus?

Question: Does anybody know, either good websites or books which can help us setup a Tacacs+ (tacplus) server?
Any help would be appreciated.   Thanks
AB
Answer: You can read book from Cisco Press "Routing TCP/IP Volume II" by Jeff Doyle. It has one chapter on router management, including configuring tacacs+ authentication on cisco IOS and configuring the tacacs+ server.
Tacplus installation is very easy, and you can configure the server via tacplus.conf by instruction on that book.
Comment: Thanks for this, I got a copy of the book and will have a look at in detail.  I also found this material on the net url: http://www.stben.net/tacacs/users_guide.html