To complete the proof that $\operatorname{PSL}(2,\Bbb F_5)\cong A_5$

Question: Elementary isomorphism between $\operatorname{PSL}(2,5)$ and $A_5$ I want to fill in the details of user David Speyer's algebraic proof that  $\operatorname{PSL}(2,\Bbb F_5)\cong A_5$. I haven't actually been formally introduced to the concept of a projective linear group or a projective space (I'm reading Dummit & Foote's Abstract Algebra, I'm sure it won't talk anything deep about them), but I've learnt about linear fractional transformations and cross-ratios. I hope that helps:
Of course, I won't assume that $\operatorname{PSL}(2,\Bbb F_5)$ is simple. So we let $\operatorname{PGL}(2,\Bbb F_5)$ acts naturally on $\Bbb P^1(\Bbb F_5)$ (I don't exactly know how it actually works, but I've learnt about complex Möbius transformations, so I'm sure it is $\Bbb F_5\cup\{\infty\}$):$$\operatorname{PGL}(2,\Bbb F_5)\times\Bbb P^1(\Bbb F_5)\rightarrow \Bbb P^1(\Bbb F_5)$$$$(f,x)\mapsto f(x)$$where $f:x\mapsto\frac{ax+b}{cx+d}$ can be identified with the coset with representative $\begin{pmatrix}a&b\\c&d\end{pmatrix}$ as in $\operatorname{PGL}(2,\Bbb F_5):=\operatorname{GL}(2,\Bbb F_5)/Z(\operatorname{GL}(2,\Bbb F_5))$
As a permutation on $6$ elements of $\Bbb P^1(\Bbb F_5)$, I checked for involutions in $S_6$. $15$ of them are products of three disjoint transpositions. They have no fixed point:$$\{(0\infty)(12)(34),(0\infty)(13)(24),(0\infty)(14)(23),(1\infty)(23)(04),(1\infty)(24)(03),(1\infty)(34)(02),(2\infty)(13)(04),(2\infty)(14)(03),(2\infty)(34)(01),(3\infty)(12)(04),(3\infty)(14)(02),(3\infty)(24)(01),(4\infty)(12)(03),(4\infty)(13)(02),(4\infty)(23)(01)\}$$
Now since a linear fractional transformation is completely decided by its action on $3$ points, I can write them in the form $x\mapsto\frac{ax+b}{cx+d}$ using cross-ratios because it is invariant under these transformations: for example $(0\infty)(12)(34):0\mapsto\infty,\infty\mapsto0,1\mapsto2$ so $[x,0;\infty,1]=[f(x),\infty;0,2]$, so the map is $x\mapsto\frac{2}{x}$. The $15$ involutions corresponds to (in consistent order with the permutations above):$$\{\begin{pmatrix}0&2\\1&0\end{pmatrix},\begin{pmatrix}0&3\\1&0\end{pmatrix},\dots,\begin{pmatrix}1&1\\1&4\end{pmatrix},\begin{pmatrix}1&2\\1&4\end{pmatrix},\dots,\dots,\begin{pmatrix}2&4\\1&3\end{pmatrix},\begin{pmatrix}2&3\\1&3\end{pmatrix},\begin{pmatrix}3&3\\1&2\end{pmatrix},\begin{pmatrix}3&4\\1&2\end{pmatrix},\dots,\dots,\begin{pmatrix}4&2\\1&1\end{pmatrix},\begin{pmatrix}4&1\\1&1\end{pmatrix}\}$$ where the $\dots$ are involutions $(0\infty)(14)(23),(1\infty)(34)(02),(2\infty)(13)(04),(3\infty)(24)(01),(4\infty)(12)(03)$ which I omitted since I tried to write them explicitly as linear fractional maps by investigating cross-ratios and then realised they induced different permutations: e.g. $(0\infty)(14)(23):0\mapsto\infty,\infty\mapsto0,1\mapsto4$, so I had $x\mapsto\frac{4}{x}$, but then it would in turn fixes $2$ and $3$, which is absurd.

Questions:
-The answer given by David Speyer suggested an action of $\operatorname{PGL}(2,\Bbb F_5)$ by conjugation on the $5$ involutions with fixed points, and then it gives us $\operatorname{PGL}(2,\Bbb F_5)\cong S_5$. I don't get it. I've checked above that there are indeed $5$ such involutions. Why is this action faithful?
-Let's assume I already know $\operatorname{PGL}(2,\Bbb F_5)\cong S_5$. Can I view $\operatorname{PSL}(2, \Bbb F_5)$ as a subgroup of $\operatorname{PGL}(2,\Bbb F_5)$ by saying that they are sets of linear fractional transformations? By doing so, I immediately concludes that $\operatorname{PSL}(2, \Bbb F_5)\cong A_5$ since $A_5$ is the unique subgroup of index $2$ in $S_5$.
Comment: @JyrkiLahtonen Hmm... that comment repeats what David Speyer explained and reflects what I've just done in my attempt. It does not help at all.
Comment: Ok. Sorry. ${}{}$
Comment: I have a new observation: suppose $\tau\in PGL(2,\Bbb F_5)$ stabilizes, i.e. centralizes, the $5$ involutions outside $PGL(2,\Bbb F_5)$. Suppose $\tau$ fixes an element of $\Bbb P^1(\Bbb F_5)$, then it fixes the whole projective line. $\tau=id$. What if $\tau$ does not fix anything? I'm trying to arrive at a contradiction...
Answer: You need to show that any element of $PGL(2,\Bbb F_5)$ commuting with each
of  the
five involutions you list (that are outside $PGL(2,\Bbb F_5)$) is the identity. Then the conjugation action on these five permutations is faithful.
Then $PSL(2,\Bbb F_5)$ is a subgroup of $PGL(2,\Bbb F_5)$, and as
$S_5$ has the unique index $2$ subgroup $A_5$, then it must be isomorphic to
$A_5$.
Comment: So... 'any element of $PGL(2,\Bbb F_5)$ commuting with each of the $5$ involutions... is the identity' is what I don't understand. I can only see that $\operatorname{Stab}_{PGL(2,\Bbb F_5)}\sigma$ where $\sigma$ is one of the $5$ involutions there, has order at most $48$. Why do these stabilizers intersect trivially?
Answer: I think I have it now. Let $\operatorname{PGL}(2,\Bbb F_5)$ acts on $$\{(0\infty)(14)(23),(1\infty)(34)(02),(2\infty)(13)(04),(3\infty)(24)(01),(4\infty)(12)(03)\}$$ by conjugation:$$(\tau,\sigma)\mapsto\tau\sigma\tau^{-1}$$
Suppose $\tau$ stabilizes all of the $5$ involutions. Then$$(\tau(0)\tau(\infty))(\tau(1)\tau(4))(\tau(2)\tau(3))=(0\infty)(14)(23)$$$$(\tau(1)\tau(\infty))(\tau(3)\tau(4))(\tau(0)\tau(2))=(1\infty)(34)(02)$$$$(\tau(2)\tau(\infty))(\tau(1)\tau(3))(\tau(0)\tau(4))=(2\infty)(13)(04)$$
Suppose $\tau$ fixes $0$. By the first equality, $\tau$ fixes $\infty$. By the second equality, $\tau$ fixes both $1$ and $2$. By the third equality, $\tau$ fixes both $3$ and $4$. i.e. $\tau$ fixes everything. $\tau=id$. By symmetry, we claim that if $\tau$ fixes a point on $\Bbb P^1(\Bbb F_5)$, it fixes everything.
So we suppose that $\tau$ does not fix anything. By symmetry, we may assume that $\tau(0)=\infty$. Then $\tau(\infty)=0$ by the first equality. Then $\tau(2)=1$ by the secdond equality and $\tau(2)=4$ by the third equality. Contradiction.
Thus we must have $\tau=id$. i.e. the action is faithful.
Comment: What permutations are the generators of the action of $A_5$ on six points?


Jump to the last postion when open Google Sheet

Question: my intention it is to get a simply feature which jump to the last cell in GoogleSheet from where I have closed the file. I have written this script:

function onEdit(e) {
  var ss = e.source
  var sheet = ss.getActiveSheet();
  var cell = ss.getActiveCell();
  var row = cell.getRow();
  var column = cell.getColumn();
  var sheet_name = sheet.getSheetName();
  var scriptProperties = PropertiesService.getScriptProperties();

  scriptProperties.setProperty('row',row);
  scriptProperties.setProperty('column',column);
  scriptProperties.setProperty('sheet name',sheet_name);
}

function onOpen(e) {
  var properties = PropertiesService.getScriptProperties();

  var ss = e.source;
  var sheet_name = properties.getProperty('sheet name');
  var sheet = ss.getSheetByName(sheet_name);
  var row = properties.getProperty('row');
  var column = properties.getProperty('column');
  var cell = sheet.getRange(row,column);

  ss.setActiveSheet(sheet);
  ss.setActiveRange(cell);
}

The Script write the values into the Property filed but when I open the file nothing happend.
For a better demonstation you can find my script here: https://docs.google.com/spreadsheets/d/1cAsWRNl9f5jxjvgDh17l4C43bhxJdulWyaNXmLwuab0/edit?usp=sharing
Does anyone know where my bug is?
Thanks
Answer: Issue and workaround:
In your script, you put and get the values using PropertiesService. In this case, the values of number type are put as the string type. I think that this is the reason of your issue.
When the Spreadsheet is opened, row and column are retrieved from PropertiesService. In this case, row and column are the string values. By this, an error occurs at var cell = sheet.getRange(row,column); in the function of onOpen. Because row and column are not the number values.
I think that when you turn off the V8 runtime at the script editor, var cell = sheet.getRange(row,column); works. (From the script of your shared Spreadsheet, I thought that you use the script with V8.) But when the V8 runtime is used, an error occurs. I think that this might be the specification of V8.
So in order to avoid this issue, how about the following modification?
Modified script:
From:
var cell = sheet.getRange(row,column);

To:
var cell = sheet.getRange(Number(row), Number(column));

Or
Turn off the V8 runtime at the script editor.
Reference:

getRange(row, column)

row, Integer, The row index of the cell to return; row indexing starts with 1.
column, Integer, The column index of the cell to return; column indexing starts with 1.
Comment: Hello, thanks for your perfect answer. It works fine:
Way 1: I switch off the Version V8
Way 2: I changed the commandline
Comment: @J. Doe Thank you for replying. I'm glad your issue was resolved.


Image file types indexed by Google: is TIFF part of it or not?

Question: The image file types indexed by Google are defined:

On the Google Webmaster / Search Console Help where the TIFF format is not present (latest update 2015):

Google can index the following image types:
<code>BMP
GIF
JPEG
PNG
WebP
SVG
</code>

But on the Google Search Appliance Documentation the TIFF format is present (latest update 2013):

TIFF Group 5 & 6 - tiff - Versions through 6
TIFF CCITT Group 3 & 4 -tiff - Versions through 6
Can someone confirm that TIFF is part or not part of the supported image file types that Google can index or not? Or give me a hint how I could verify this in a simple, fast and efficient way?
For now my reference is the first link with the Search Console Help (which was updated in 2015), but the second link (from 2013) has given me doubts... Or am I mixing two different things?
Thanks in advance for your help!
Comment: The person that down voted this question should have let a message to explain why. I have researched this question on Google and have found two responses on official google documents, which are contradictory. I am asking SEO experts to clarify. It is unfair to down vote without giving a valid reason. If you down vote, this means you have found the question through a research and something has awoken your interest and now you are deceived because you did not got the answer you wanted. But there is no reason to down vote because you are frustrated.
Answer: After clarifying directly on Google Search Console, the latest document from 2015 is the one that is right. So this question is closed for me.


Change Drupal interface language back to English

Question: I made the mistake to translate the Drupal interface in my local language. But since the language is set into the database, I can't delete this language using the Drupal UI. And I'm not sure which file(s) to delete in the database.
Does anyone know a (faultlessly) way to translate the Drupal interface back to English?
Answer: You can change the language back to English by adding this to the url of any page:
<code>&language=en
</code>
EDIT:
To have a seperate admin and front end language I'd suggest looking at the Admin Language module - http://drupal.org/project/admin_language
SECOND EDIT:
To do this via role have a look at this page - http://deglos.com/blog/2010/06/12/overriding-language-drupal-backend
They are doing what you want with a custom module. You could throw in the user role code there using the global $user.
Comment: Oh I see. Sorry. You just want the site in one language and the UI in the other? I've edited my answer...
Comment: That's something I don't want... The language was English by default and I want to delete my new language so English will be the default Drupal UI language.
Comment: Oh ok. Can't you just go to admin/settings/language and click the delete button?
Comment: Yes, but won't this action delete the whole site set in that language?
Comment: Ok, great module! But I can't get my users (a separate role) use this module (despite setting the permissions!). Only the admin users gets a translation.
Comment: So you have a user role that can access the admin theme(?) that isn't "admin" that you also want the translation to work for?
Comment: Yes. I have a role which has access to the admin theme, but isn't the admin and I do want them to be able to see the UI in English.
Comment: Ok have edited again. It's not my code and I've not tested it but it looks like it will work for you with minimal editing.
Comment: Hm, I'm not sure what they mean... I can't really figure it out. They use the same function twice... And where do I place the `global $user`?
Comment: Ok, I found the option to use the admin language on the menu in the admin language module! Thanks!
Comment: I know this is a long time later, but I just had to do exactly this. I didn't want to retain the translations and then tell Drupal to ignore them, I wanted to remove them altogether.

I started by disabling the regular updates of the interface translations, and then removed the folder containing the .po files for the different interface translations. Then, I emptied the locales_target table in the database. Since it was now empty, the site not longer shows the interface translations for different languages.


Given $u=(-2,5,3)$, how to find unit vectors$u,w$ s.t $|u+v|$ is maximal and $|u-w|$ is minimal and another similar part

Question: I was stumbled with a basic calculus question by a friend.
The question first asks to find unit vectors $v,w$ s.t $|u+v|$ is
maximal and $|u-w|$ is minimal where $u=(-2,5,3)$.
Then the question asks to find unit vectors $v,w$ s.t $u\cdot v$
is maximal and $|u\cdot w|$ is minimal.
It's easy to write out the equations in all parts, for example for
the first part: denote $v=(x,y,z)$ then we wish to find the maximum
$$(z+3)^{2}+(y+5)^{2}+(x-2)^{2}$$ under $$x^{2}+y^{2}+z^{2}=1$$
and similarly for the second part with the minimum. But this doesn't
seem like the right way to go at this, since I only know to solve
such a question with Lagrange multipliers, and they didn't study this
(yet).
Can anyone please help point me out in the right direction ?
Answer: The right direction is to consider vectors $v$ and $w$ which are collinear with $u$.
For the second part of the question, observe that $u\cdot v=|u||v|\cos\left(\angle(u,v)\right)$. In your case, the absolute values of $u$ and $v$ are fixed, so the values of $u\cdot v$ and $|u\cdot w|$ depend only on the angle between these two vectors.
Comment: Can you please add more details ? what does "collinear" mean ?
Comment: From geometric considerations it is clear that the vectors $v$/$w$ that maximise/minimise the numbers $|u+v|$, $|u-w|$ are pointing in the same direction as $u$. Two vectors are collinear if one is a scalar multiple of the other.
Comment: Thanks for the details! Does this mean that both answers are the same and are the normalized $u$ ?
Comment: Indeed, that is correct.
Comment: Thanks! Does this answer also apply to the second part of the question ?
Answer: Given $u=(-2,5,3)$ consider the following function $f_\pm(v)=<u\pm v,u\pm v>$ which is the inner product of $u\pm v$ with itself. The critical point of $f_\pm$ coincide with the critical point of $|u\pm v|$ (why?).
Now $f_\pm(v)=<u\pm v,u\pm v>=<u,u>\pm 2<u,v>+<v,v>=|u|^2+|v|^2\pm 2<u,v>$, since $u=(-2,3,5)$ and $|v|=1$ we have that $f_\pm(v)=39\pm 2<u,v>$. Since $u$ is a fixed vector and $v$ is allowed to move on a circle , $f_\pm (v)$ will be the biggest when $u$ and $v$ are multiple of each other (observe that $f_\pm(v)=39\pm\sqrt{38}\cos\theta$ where $\theta$ is the angle between $u$ and $v$, so in order for $f_\pm(v)$ to be biggest $\cos\theta$ has to be biggest, that is $\theta=0$ or $\theta=\pi$) that is when $v=\dfrac{u}{|u|}$ or $v=-\dfrac{u}{|u|}$.
This the reason why the previous suggestion
P.S. for each function you will have to check which of the two possible answers is the solution.


Suppose that $E_1,E_2,...E_n$ are compact sets, Prove that their union is also compact.

Question: Professors Road Map to Glory.

Explain why if $\{a_n\}_{n}^{\infty}$ is a sequence of numbers, and $$ a_n \in E_1\cup E_2,...\cup E_n$$ for all $n\in \mathbb{N}$,
then their is a subsequence $\{a_{n(k)}\}_{k}^{\infty}$ completely contained in one of the compact sets $E_k$ for some $k \in \{1,2,...n\}$
Explain why, for the subsequence $\{a_{n(k)}\}_{k}^{\infty}$ contained completely in one compact set $E_k$, there is a convergent subsequence of the subsequence with a limit contained in $E_k$.

these are current defenitions that I have for compactness, looking at the RTG, I more than likely will use #2
A set $E$ is compact iff

Every open cover of E permits a finite subcover.
Every sequence of values in E contains a convergent subsequence whose limit is in E.
E is closed and bounded.

My intuition:
If $\{a_n\}_{n}^{\infty}$ is a sequence in a union of compact sets.
I am super hazy in the part that reads, "then their is a subsequence $\{a_{n(k)}\}_{k}^{\infty}$ completely contained in one of the compact sets $E_k$ for some $k \in \{1,2,...n\}$"
however given then there is a subsequence $\{a_{n(k)}\}_{k}^{\infty}$ completely contained in one of the compact sets $E_k$ for some $k \in \{1,2,...n\} $ the subsequence of the subsequence is convergent to a point in $E_k$ thus by the second definition of compactness, the union of the sets are compact.
Answer: The first one is pigeonhole principle. If there are only finitely many terms in each $E_i$ then there's only finitely many terms in their union, contradiction.
The second one is your definition you've provided.
Comment: Great! now I see the connection.
Answer: Suppose $A_1,A_2,...$ cover $E_1 \cup E_2 \cup ... \cup E_n$.
Since this sequence of sets covers $E_1$, we take a finite subcover.
Since this sequence of sets also covers $E_2$, we take another finite subcover.
In total, we have $N$ finite subcovers, which unioned together still makes a finite subcover. Therefore, $E_1 \cup E_2 \cup ... \cup E_n$ is also compact.


JFileChooser can select any folder apart from the current one?

Question: I am using JFileChooser to allow the user to select a folder. They must be able to view the files in each folder for context. The problem is that I can't select the folder I am when the dialog pops up. (i.e. I click "open" and nothing happens). However, if I switch to another directory and then back to the first one, then I can select it.
public static String selectFolder()
{
    final JFileChooser chooser = new JFileChooser() {
            public void approveSelection() {
                if (getSelectedFile().isFile()) {
                    return;
                } else
                    super.approveSelection();
            }
    };

    chooser.setCurrentDirectory(new java.io.File("."));
    chooser.setDialogTitle("Select Folder");
    chooser.setFileSelectionMode( JFileChooser.FILES_AND_DIRECTORIES );

    chooser.setAcceptAllFileFilterUsed(false);

    chooser.showOpenDialog(null);

    File x = chooser.getSelectedFile();

    if( x != null )
        return x.toString();

    return null;
}

Comment: not really a solution, but IMO, it is more user friendly to start at some drive and not a folder
Comment: Hi there. We don't use [solved] title hacks here - using the acceptance system is fine on its own, as you have done already. Thanks!
Answer: public static String selectFolder() {
    final JFileChooser chooser = new JFileChooser() {
        public void approveSelection() {
            if (getSelectedFile().isFile()) {
                return;
            } else
                super.approveSelection();
        }
    };

    chooser.setCurrentDirectory(new java.io.File("."));
    chooser.setDialogTitle("Select Folder");
    chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

    chooser.setAcceptAllFileFilterUsed(true);

    chooser.setSelectedFile(new java.io.File("."));
    chooser.showOpenDialog(null);
    File x = chooser.getSelectedFile();

    if (x != null)
        return x.toString();

    return null;
}

you only have to add the line:
chooser.setSelectedFile(new java.io.File("."));

for the sake of being user-friendly, set it to the same as the CurrentDirectory, so that the user sees which directory will be selected when he clicks the button
Comment: That does it. Thanks.
Answer: As per JFileChooser you have to choose a file or folder on the dialog then only it will allow you to click open/save.
Comment: So how do you choose the directory which the dialog points to when it is first opened? Switch to a different directory and then switch back to the first one?


How to return value that is in a relation of specific index. If value came from input

Question: Let's say that input fag is informasjonsvitenskap in list(FagKode), if that is true i want it to print the values in karak that has the code INFO, like INFO100,INFO132 and INFO233. And if input fag is økonomi i want it to print the values in karak the has the code ECON. i also have a function, def legg_til(). thats will allow me to add an element in the list 'emner'. then the question will be. How to make it find the value that is in relation to input fag and print the specific value. :/
print('\nVelkommen til karakterprogrammet Infinitux\n')
print('----------------------------')

print('1: Emneliste','2: Legg til emne','3: Sett karakter','4: Karaktersnitt','5: Avslutt',sep='\n')
print('----------------------------')

emner = ['INFO100','INFO132','INFO233']
FagKode = [['informasjonsvitenskap','INFO'],['økonomi','ECON']]
karak = [['INFO100','C'],['INFO132','B'],['INFO233','C'],['ECON218','A']]

def start():
    global meny
    global fag
    meny = int(input('Tast inn ønsket valg (press 0 for meny): '))

    if meny == 1:
      valg_fag = input('Press Enter for å velge fag/emner (Skriv "alle" for å vise alle fag/emner)\n: ')

    if meny == 1 and valg_fag == 'alle':
      for i in karak:
        print(*i)

    elif meny == 1 and valg_fag == '':
      fag = input('- Fag: ')
      emnenivå = int(input('- Nivå: '))
      try:
        if fag in FagKode[0] and emnenivå in range(1,1000):
          ???????
          ???????
        else:
          print('Du har gjort noe feil!')
      except ValueError:
          print('NEI')

def legg_til():
    global meny
    global fag
    if meny == 2:
      add = input('Nytt emne:  ')
      emner.append(add.upper())

def karakter(): # Sletter/Setter ny karakter
    global meny
    if meny == 3:
      valg_emne = input('Emne: ')
      slett = input('Karakter (<enter> for å slette): '+karak==valg_emne)

    if meny == 3 and valg_emne in emner and slett == '':
      for i in range(len(karak)):
        if karak[i][0] == valg_emne:
          del karak[i][1]
        start()

    if meny == 3 and valg_emne in emner:
      pass

    if meny == 3 and valg_emne in emner and slett == 'HEI':
      for i in range(len(karak)):
        if karak[i][0] == valg_emne:
          print(karak[i][1])

def snitt():
  pass

def programslutt():
  global meny
  if meny == 5:
    print('Takk for nå, velkommen igjen!')
  else:
    ('Feil verdi')

start()
legg_til()
karakter()
programslutt()

Thanks for opinions in advance :)
Comment: Why do you have the values in Lists. Why don't you use the dictionary to hold key value pairs. For the variables **FagKode** and **karak**
Comment: i have not gone throug dictionaries yet, i will do that after this assignment. i know that it would be better if i used dictionaries.
Comment: The list  i want to return values from was written wrong, the list i want the return values from is karak, not emner
Comment: There are much more efficient ways of checking if a number falls within a range... you should explain what is the exact problem you're trying to solve
Comment: What is `karak==` for? in the switch case below line:
 `if fag in FagKode[0] and emnenivå in range(1,1000):`
Comment: Let's say that input fag is informasjonsvitenskap in list(FagKode), if that is true i want it to print the values in karak that has the code INFO, like INFO100,INFO132 and INFO233. And if input fag is økonomi i want it to print the values in karak the has the code ECON. i also have a function, def legg_til(). thats will allow me to add an element in the list 'emner'. then the question will be. How to make it find the value that is in relation to input fag and return me the specific value. :/
Answer: Try this.
Make the variables FagKode and karak as dictionaries.
and try to get the values as follows.
return karak.get(FagKode.get(input(fag)))

or this for list.
for i, j in FagKode:
    if i==input(fag):
        for k, l in karak:
            if k==j:
                return l
return "Not Found"

Comment: Sukumar Rdjf, i would prefer dictionaries but i have to use list this time because this is an assignment in school. :/
Comment: Now does it only give me the value i give to input.
Comment: Why don't you just post the ldata and logic where you are trying to check the elements. There is too data which is irrelevant to the logic in the question.
Comment: What do you mean ? i dident understand that
Comment: Sukumar Rdjf.
Let's say that input fag is informasjonsvitenskap in list(FagKode), if that is true i want it to print the values in karak that has the code INFO, like INFO100,INFO132 and INFO233. And if input fag is økonomi i want it to print the values in karak the has the code ECON. i also have a function, def legg_til(). thats will allow me to add an element in the list 'emner'. then the question will be. How to make it find the value that is in relation to input fag and return me the specific value. :/


I'm trying to use a button to go to another scene, but its giving error, javaFX

Question: I'm trying to make a button work, but when I click it, it gives an error
Here's the error
Exception in thread "JavaFX Application Thread" java.lang.IllegalArgumentException: argument type mismatch
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at com.sun.javafx.reflect.Trampoline.invoke(MethodUtil.java:76)
    at jdk.internal.reflect.GeneratedMethodAccessor2.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at javafx.base/com.sun.javafx.reflect.MethodUtil.invoke(MethodUtil.java:273)
    at javafx.fxml/com.sun.javafx.fxml.MethodHelper.invoke(MethodHelper.java:83)
    at javafx.fxml/javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1782)
    at javafx.fxml/javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1670)
    at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.base/javafx.event.Event.fireEvent(Event.java:198)
    at javafx.graphics/javafx.scene.Scene$ClickGenerator.postProcess(Scene.java:3564)
    at javafx.graphics/javafx.scene.Scene$ClickGenerator.access$8200(Scene.java:3492)
    at javafx.graphics/javafx.scene.Scene$MouseHandler.process(Scene.java:3860)
    at javafx.graphics/javafx.scene.Scene$MouseHandler.access$1200(Scene.java:3579)
    at javafx.graphics/javafx.scene.Scene.processMouseEvent(Scene.java:1849)
    at javafx.graphics/javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2588)
    at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:397)
    at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$2(GlassViewEventHandler.java:434)
    at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:390)
    at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:433)
    at javafx.graphics/com.sun.glass.ui.View.handleMouseEvent(View.java:556)
    at javafx.graphics/com.sun.glass.ui.View.notifyMouse(View.java:942)
    at javafx.graphics/com.sun.glass.ui.mac.MacView.notifyMouse(MacView.java:127)

Here's the controller I'm using
package HMS;

import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

import java.io.IOException;

public class Controller {

    @FXML
    private PasswordField tf_pfield;

    @FXML
    private Button btn_login;

    @FXML
    private TextField tf_uname;

    @FXML
    private Button Doc_adPan;

    @FXML
    private Button Lab_adPan;

    @FXML
    private Button Pharma_adPan;

    @FXML
    private Button Finance_adPan;

    @FXML
    private Button Settings_adPan;

    @FXML
    private Button Staff_adPan;

    @FXML
    private Button Logout_adPan;

    @FXML
    private Button Wards_adPan;

    @FXML
    private void handlebuttonclicks(javafx.event.ActionEvent mouseEvent)
    {
        if(mouseEvent.getSource() == Doc_adPan)
        {

        }
        else if(mouseEvent.getSource() == Lab_adPan)
        {

        }
        else if(mouseEvent.getSource() == Logout_adPan)
        {
            loadStage("Login.fxml");
        }
        else if(mouseEvent.getSource() == Staff_adPan)
        {

        }
        else if(mouseEvent.getSource() == Settings_adPan)
        {

        }
        else if(mouseEvent.getSource() == Pharma_adPan)
        {

        }
        else if(mouseEvent.getSource() == Finance_adPan)
        {

        }
        else if(mouseEvent.getSource() == Wards_adPan)
        {

        }
    }
    private void loadStage(String fxml)
    {
        try {
            Parent root = FXMLLoader.load(getClass().getResource(fxml));
            Stage stage = new Stage();
            stage.setScene(new Scene(root));
            stage.hide();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Here's the FXML file where the button exists.
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.ButtonBar?>
<?import javafx.scene.image.Image?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.Pane?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.text.Font?>
<?import javafx.scene.text.Text?>

<VBox prefHeight="742.0" prefWidth="845.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="HMS.Controller">
   <children>
      <AnchorPane onMouseClicked="#handlebuttonclicks" style="-fx-background-color: white;" VBox.vgrow="ALWAYS">
         <children>
            <Button fx:id="Doc_adPan" layoutX="344.0" layoutY="159.0" mnemonicParsing="false" onAction="#handlebuttonclicks" onMouseClicked="#handlebuttonclicks" opacity="0.0" prefHeight="123.0" prefWidth="62.0" stylesheets="@Styles.css" text="Button" />
            <Button fx:id="Lab_adPan" layoutX="532.0" layoutY="175.0" mnemonicParsing="false" onAction="#handlebuttonclicks" onMouseClicked="#handlebuttonclicks" opacity="0.0" prefHeight="123.0" prefWidth="62.0" text="Button" />
            <Button fx:id="Pharma_adPan" layoutX="724.0" layoutY="163.0" mnemonicParsing="false" onAction="#handlebuttonclicks" onMouseClicked="#handlebuttonclicks" opacity="0.0" prefHeight="123.0" prefWidth="62.0" text="Button" />
            <Button fx:id="Finance_adPan" layoutX="344.0" layoutY="332.0" mnemonicParsing="false" onAction="#handlebuttonclicks" onMouseClicked="#handlebuttonclicks" opacity="0.0" prefHeight="123.0" prefWidth="62.0" text="Button" />
            <Button fx:id="Settings_adPan" layoutX="528.0" layoutY="332.0" mnemonicParsing="false" onAction="#handlebuttonclicks" onMouseClicked="#handlebuttonclicks" opacity="0.0" prefHeight="123.0" prefWidth="62.0" text="Button" />
            <Button fx:id="Staff_adPan" layoutX="722.0" layoutY="329.0" mnemonicParsing="false" onAction="#handlebuttonclicks" onMouseClicked="#handlebuttonclicks" opacity="0.0" prefHeight="123.0" prefWidth="62.0" text="Button" />
            <Button fx:id="Logout_adPan" layoutX="756.0" layoutY="18.0" mnemonicParsing="false" onAction="#handlebuttonclicks" onMouseClicked="#handlebuttonclicks" opacity="0.0" prefHeight="89.0" prefWidth="62.0" text="Button" />
            <Button fx:id="Wards_adPan" layoutX="334.0" layoutY="502.0" mnemonicParsing="false" onAction="#handlebuttonclicks" onMouseClicked="#handlebuttonclicks" opacity="0.0" prefHeight="123.0" prefWidth="62.0" text="Button" />
            <Pane layoutY="-1.0" prefHeight="743.0" prefWidth="249.0" style="-fx-background-color: #DFF6F0 #DFF6F0;">
               <children>
                  <Text layoutX="91.0" layoutY="140.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Welcome!">

                  </Text>
                  <Text layoutX="112.0" layoutY="157.0" strokeType="OUTSIDE" strokeWidth="0.0" text="USER" />
                  <Text fill="#1273ba" layoutX="57.0" layoutY="482.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Sharif Surgical Hospital">

                  </Text>
                  <ImageView fitHeight="110.0" fitWidth="125.0" layoutX="62.0" layoutY="310.0">
                     <image>
                        <Image url="@../sss/mainLogo.png" />
                     </image>
                  </ImageView>
               </children>
            </Pane>
            <ButtonBar layoutX="174.0" layoutY="92.0" prefHeight="80.0" prefWidth="89.0" />
            <Text layoutX="441.0" layoutY="81.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Admin Panel" textAlignment="CENTER" wrappingWidth="220.0">

            </Text>
            <Text layoutX="767.0" layoutY="95.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Logout" wrappingWidth="53.66004199452357">

               </Text>
            <ImageView fitHeight="75.0" fitWidth="75.0" layoutX="334.0" layoutY="163.0">
               <image>
                  <Image url="@../sss/doctor.png" />
               </image>
            </ImageView>
            <ImageView fitHeight="75.0" fitWidth="75.0" layoutX="524.0" layoutY="163.0">
               <image>
                  <Image url="@../sss/Lab.png" />
               </image>
            </ImageView>
            <ImageView fitHeight="75.0" fitWidth="75.0" layoutX="717.0" layoutY="161.0">
               <image>
                  <Image url="@../sss/Pharmacy.png" />
               </image>
            </ImageView>
            <ImageView fitHeight="75.0" fitWidth="72.0" layoutX="336.0" layoutY="332.0">
               <image>
                  <Image url="@../sss/Finance.png" />
               </image>
            </ImageView>
            <ImageView fitHeight="75.0" fitWidth="75.0" layoutX="522.0" layoutY="329.0">
               <image>
                  <Image url="@../sss/settings.png" />
               </image>
            </ImageView>
            <ImageView fitHeight="75.0" fitWidth="75.0" layoutX="715.0" layoutY="332.0">
               <image>
                  <Image url="@../sss/Staff.png" />
               </image>
            </ImageView>
            <ImageView fitHeight="75.0" fitWidth="75.0" layoutX="334.0" layoutY="502.0">
               <image>
                  <Image url="@../sss/Wards.png" />
               </image>
            </ImageView>
            <ImageView fx:id="Logout_adPan1" fitHeight="40.0" fitWidth="40.0" layoutX="771.0" layoutY="25.0">
               <image>
                  <Image url="@../sss/logout.png" />
               </image>
            </ImageView>
            <Text layoutX="346.0" layoutY="278.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Doctor">

            </Text>
            <Text layoutX="548.0" layoutY="278.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Lab" wrappingWidth="30.958903300616043">

            </Text>
            <Text layoutX="727.0" layoutY="278.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Doctor">

            </Text>
            <Text layoutX="346.0" layoutY="437.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Finance">

            </Text>
            <Text layoutX="528.0" layoutY="437.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Settings">

            </Text>
            <Text layoutX="727.0" layoutY="437.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Staff">

            </Text>
            <Text layoutX="347.0" layoutY="611.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Wards">

            </Text>
         </children>
      </AnchorPane>
   </children>
</VBox>

Here's the FXML file to which I'm trying to go to using the button
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.PasswordField?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.image.Image?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.text.Text?>

<AnchorPane maxWidth="-1.0" prefHeight="400.0" prefWidth="370.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="HMS.Controller">
   <children>
      <Text fill="#1273ba" fontSmoothingType="LCD" layoutX="67.0" layoutY="286.0" strokeType="OUTSIDE" strokeWidth="0.0" style="-fx-font-size: 20; -fx-font-family: Times New Roman;" text="Sharif Surgical Hospital" />
      <Text layoutX="430.0" layoutY="89.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Welcome to login page!" />
      <ImageView fitHeight="150.0" fitWidth="200.0" layoutX="79.0" layoutY="85.0" pickOnBounds="true" preserveRatio="true">
         <image>
            <Image url="@../sss/mainLogo.png" />
         </image>
      </ImageView>
      <AnchorPane layoutX="331.0" prefHeight="400.0" prefWidth="325.0" style="-fx-background-color: #1273ba;">
         <children>
            <PasswordField fx:id="tf_pfield" layoutX="122.0" layoutY="233.0" prefHeight="27.0" prefWidth="152.0" promptText="Enter Password" style="-fx-background-color: white;" />
            <Button fx:id="btn_login" layoutX="160.0" layoutY="290.0" mnemonicParsing="false" text="Login" textFill="#1273ba" />
            <Text fill="WHITE" layoutX="31.0" layoutY="208.0" strokeType="OUTSIDE" strokeWidth="0.0" style="-fx-font-size: 16;" text="Username" />
            <Text fill="WHITE" layoutX="32.0" layoutY="251.0" strokeType="OUTSIDE" strokeWidth="0.0" style="-fx-font-size: 16;" text="Password" />
            <Text fill="WHITE" layoutX="138.0" layoutY="154.0" strokeType="OUTSIDE" strokeWidth="0.0" style="-fx-font-size: 20;" text="Login" />
            <TextField fx:id="tf_uname" layoutX="122.0" layoutY="192.0" prefWidth="152.0" promptText="Enter Username" style="-fx-background-color: white;" />
         </children>
      </AnchorPane>
   </children>
</AnchorPane>

Here's the main
package HMS;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("AdminDashboard.fxml"));
        primaryStage.setTitle("Login");
        primaryStage.setScene(new Scene(root));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

I'm trying to use the logout button(Logout_adPan). I've added all references and this was built using scene builder. I don't know what am I doing wrong
Comment: unrelated: java naming conventions, please!
Comment: you have same controller for both dashboard and login - that's bound to break sooner or later because the one doesn't know about the fields injected by the other (not entirely certain if that's the cause here, though). Also: why _hiding_ the login stage after loading? Anyway, what we need is a [mcve] demonstrating the problem (mind the __M__ , nothing unrelated)
Comment: and now at the end, seeing the error: you use the same method reference for both mouse handler on parent and action handler on button - they have different signatures, so loading them will blow at one of them :) Which probably is what the answer tries to explain.
Answer: you are trying to compare two objects using the symbol == while you have to do it using the method equals() which will return true if they are equal, otherwise it will return false.
Don't forget to cast mouseEvent.getSource() to Button
try this:
 if(((Button)mouseEvent.getSource()).equals(Doc_adPan))
{

}
else if(((Button)mouseEvent.getSource()).equals(Lab_adPan))
{

}
else if(((Button)mouseEvent.getSource()).equals(Logout_adPan))
{
    loadStage("Login.fxml");
}
else if(((Button)mouseEvent.getSource()).equals(Staff_adPan))
{

}
else if(((Button)mouseEvent.getSource()).equals(Settings_adPan))
{

}
else if(((Button)mouseEvent.getSource()).equals(Pharma_adPan))
{

}
else if(((Button)mouseEvent.getSource()).equals(Finance_adPan))
{

}
else if(((Button)mouseEvent.getSource()).equals(Wards_adPan))
{

}

and Use only onAction="#handlebuttonclicks", not onMouseClicked.
and remove onMouseClicked="#handlebuttonclicks"  from AnchorPane
Comment: btw, `==` vs. equals doesn't matter here, same result. But well spotted error :) At OP: as already commented to your question - time for a [mcve] .. though I think the _not working_ is a _seemingly_ not working due to hiding the loaded stage :)
Comment: because they are the same instance - that's what default equals is implemented anyway
Comment: Thank you very much, removing onMouseClicked worked. The next mistake as @kelopetra was saying that I used stage.hide().
Comment: you have to do it for all the code, I edited my answer, copy and paste it
Comment: @Saad and Use only `onAction="#handlebuttonclicks"`, not `onMouseClicked`
Comment: @Saad and remove `onMouseClicked="#handlebuttonclicks"`  from `AnchorPane`, you have Actions only on Buttons ..
Comment: After removing the onMouseClicked, the error is gone but the button is not working anymore
Comment: and as  @kleopatra already commented, you have to use one controller for each fxml page
Comment: @kleopatra why it doesn't matter here?
Comment: @Saad why do you make `stage.hide();` ? I think this is your problem, you want to show a new page which you are hiding it


How to use and pass value to Alias Column of aggregate Function of Date

Question: I am using this query to get year from adventureworksLT2008:
"select DATEPART(YYYY,SellStartDate) as Year from SalesLT.Product group by DATEPART(YYYY,SellStartDate)"

Now I want to just pass year like 1998 and get all the record of 1998
"select DATEPART(YYYY,SellStartDate) as 'Years' from SalesLT.Product where Years = '1998'"

but I'm getting this error

Invalid Column Years. SellStartDate datatype is datetime.
Answer: Years is not defined when the WHERE is executed. Have a look at the execution order of a query.
Use it like this:
SELECT DATEPART(YYYY, SellStartDate) AS Years
FROM SalesLT.Product
WHERE DATEPART(YYYY, SellStartDate) = 1998

Btw the DATEPART function returns int.
Comment: It works but giving duplicate. But when i try this querySELECT DATEPART(YYYY, SellStartDate) AS Years
FROM SalesLT.Product
WHERE DATEPART(YYYY, SellStartDate) = 1998 and DATEPART(YYYY, SellStartDate)=2002 . It is not showing record between 1998 to 2002
Answer: You can use HAVING clause with GROUP BY statements for getting unique values:
Select DATEPART(YYYY,SellStartDate) as Year from SalesLT.Product GROUP BY DATEPART(YYYY,SellStartDate)
HAVING DATEPART(YYYY,SellStartDate) = 1998

Without a GROUP BY Clause, use comparison operators with full qualifier column names:
Select DATEPART(YYYY,SellStartDate) as 'Years' from SalesLT.Product where DATEPART(YYYY,SellStartDate) = 1998

You can avoid duplicates just by using DISTINCT
Select DISTINCT DATEPART(YYYY,SellStartDate) as 'Years' from SalesLT.Product where DATEPART(YYYY,SellStartDate) > 1998


Let $f$ be continuous on $X$ and $(x_n)$ be a Cauchy sequence on $X$. Show that $(f(x_n))$ doesnt have to be a Cauchy sequence...

Question: Let $f$ be continuous on $X$ and $(x_n)$ be a Cauchy sequence on $X$. Show that $(f(x_n))$ doesnt have to be a Cauchy sequence. And show that $(f(x_n))$ always has to be a Cauchy sequence when $f$ is uniformly continuous.
My attempt:
We take the Cauchy sequence $(x_n)=\frac{1}{n}$ and choose $f:\mathbb{R}^+\longrightarrow\mathbb{R}:x\mapsto\frac{1}{x}$ which is a continuous function on given domain.
Since $x_n \longrightarrow0\,\,\Longrightarrow (f(x_n))\longrightarrow+\infty$
So eventhough $(x_n)$ is a Cauchy sequence, $(f(x_n))$ on the continuous $f$ isnt!
$\exists f\in C^0(\mathbb{R}^+)$ where the requirement does not hold!
Now we show that from the fact that $f$ is uniformly continuous we can always conclude:
Is $(x_n)$ a Cauchy sequence $\Longrightarrow$ $(f(x_n))$ is a Cauchy sequence
A function $f$ is uniformly continuous on $X$ when the Heine-Cantor theorem holds:
$\forall \epsilon>0 \,\,\, \exists \delta>0 \,\,\,\forall x,y\in X:x\in \mathcal{U}_{\delta}(y)\Longrightarrow f(x)\in \mathcal{U}_{\epsilon}(f(y))$
So for a $N\in \mathbb{N}$ we know that for all $n>N:x_n\in \mathcal{U}_{\delta}(\xi)$
Where $\xi$ is the point $(x_n)$ is converging to.
Following the Heine-Cantor theorem we know that if $n>N:x_n\in \mathcal{U}_{\delta}(\xi) \Longrightarrow f(x_n)\in \mathcal{U}_{\epsilon}(f(\xi))$
So when $(x_n)$ is a Cauchy sequence, $(f(x_n))$ has to be one aswell!
Would be great if someone could check my reasoning and give me advice for improving :)
Comment: I'm convince by the first part. But not by the second one. Can you restate the definition of a Cauchy sequence? Also, I don't know why you mention Heine-Cantor theorem. Heine-Cantor theorem gives conditions implying that a map is uniform continuous. But here we're already supposing that it is uniform continuous.
Comment: The second part follows from definition of uniform continuity and definition of a Cauchy sequence. I  don't understand why you  are quoting a theorem for this.
Comment: I thought that the cauchy sequence definition gives us, that a infinit amount of values lie in every epsilon region of our point of convergence. so there is this $\xi$ for which every $x_n$ with $N>n$ lies in any epsilon region around $\xi$. For any epsilon we might choose. And from the Heine Cantor theorem it follows that since the function is uniformly continuous our $(f(x_n))$ also has to lie in the close region of $f(\xi)$..
Comment: Cauchy sequence does not need to converge.
Comment: Ohh.. could you give me an example for that case? :) so I can ponder with that?
Comment: @CoffeeArabica What is your Heine Cantor theorem statement?
Comment: @CoffeeArabica Cauchy sequence $(\frac{1}{n})$ is not convergent in $(0, 1)$.
Answer: Consider $A = \{1, 1/2, 1/3, · · ·\}$ and $f(1/n) = \begin{cases}1, &if ~~n ~is~ odd\\−1,& if~~
n~ is ~even\end{cases}$.
Then $f$ is continuous but not uniformly continuous. The sequence $(x_n)= \frac{1}{n}$ in $A$ is Cauchy but the
sequence $f(x_n) = (1, −1, 1, −1, · · ·)$ is not Cauchy.
So the Uniformely continuous is necessary condition for the statement you want to prove.
Now
If $f$ is uniformly continuous on $A$, then given $ε > 0$ there is $δ > 0$ such that if $x, y\in A$ and $|x−y| < δ$,
then $|f(x) − f(y)| < ε$. Let $(x_n)$ be a Cauchy sequence in $A$. Then for given $δ > 0$ there is $M$ such that if $p, q > M$,
then $|x_p − x_q| < δ$, and thus $|f(x_p) − f(x_q)| < ε$, implying that $(f(x_n))$ is a Cauchy sequence.
Comment: Sorry if i miss the point.. but wasnt i stating (especially) the second part in my post?
Comment: @Coffee Arabic: Sorry,I don't see really your comment. I simply proved it by the definition of uniform continuity. I don't get that comment.


How can we discover the machine name of $conf keys?

Question: This is part of an interview questions and I am not sure. How can we discover the machine name of $conf keys from standard administrative settings forms by inspecting the DOM? (Assume it is in drupal 7)
Answer: By literally looking at the DOM.
For a random example, take the aggregate CSS checkbox on the Performance page:

 <input type="checkbox" id="edit-preprocess-css" name="preprocess_css" value="1" class="form-checkbox">
 Aggregate and compress CSS files.

You'll find the machine name for the variable in the name attribute of the associated <input> element. In this case, preprocess_css.


Internalization for client components in NEXTjs

Question: I'm working on project where I need to translate content in 4 different languages. I have watched lots of tutorials and tried several solutions but everytime I'm getting stacked to the same problem.
Inside my app I have a lot of "use client" components that I need to translate, but dictionary that I use for translation works only as a server-only component.
Exanple of dictionary.ts:
<code>import 'server-only'
import type { Locale } from '@/i18n.config'

const dictionaries = {
  en: () => import('@/dictionaries/en.json').then(module => module.default),
  de: () => import('@/dictionaries/de.json').then(module => module.default)
}

export const getDictionary = async (locale: Locale) => dictionaries[locale]()
</code>
When I run my app I get an error:
You're importing a component that needs server-only. That only works in a Server Component but one of its parents is marked with "use client", so it's a Client Component.
In all of the tutorials that I watched, people were showing simple examples without any hooks, so they didn't get this type of error.
Answer: The best way to do this is to create a provider component in your base formatter near the top of your view hierarchy. This provider loads and caches the server language dictionaries at startup and is shared with the client environment. A detailed solution is here:
https://github.com/vercel/next.js/discussions/57405
Comment: Please do not reference external sources


Systems of Equations - calculate avg $x$ & $y$ given $x$ & $y$ are normally distributed

Question: Given a number of equations (say, 30), and assuming x & y are normally distributed, how would I go about determining the average value of x & y?
$10x_{1} + 60y_{1} = 5900$
$20x_{2} + 80y_{2} = 7400$
$...$
$30x_{30} + 140y_{30} = 16100$
What I'm after is the average value of x & y. I'm assuming that getting the exact average value of x & y is impossible, so how would I go about getting pretty close (or figuring out what sort of range x & y are in)?
(note: programmer running into this problem; my math skills are up to 3rd semester calc about a decade ago in college)
Comment: This question is unclear to me. Maybe you can edit it and give a better explanation. What do you mean by $x=55$ when your asking for the weighted average of $x$ and $y$. The weighted average of $x$ and $y$ should be something like $\frac{ax+by}{a+b}$.
Comment: Updated the question.  Hope that clarifies what I'm after.  Thanks!
Comment: Are x and y *jointly* normally distributed?
Comment: They both have a different mean
Answer: If align to $\dfrac 1{30}$ all coefficients at x in equations and then take sum getting equations, we can estimate linear relation between averages of x and y. So we provide average x with the definition verasity and good approaching for average of y.
Comment: Sorry, you sort of lost me.  Can you explain a little more in-depth?  Do you mean to say to take the average of the coeffients and use that as one of the equations in a system of equations?  e.g. if we use the 3 above, $20x+(240/3)y = 9800$ and then use that equation against the first, second, third?
Comment: When we align coefficients at $x$ to $\dfrac1N$ and then sum them, we get $\dfrac1{N}\sum x$ (we have $N=30$ equations)
Answer: Your question is not clear. Some suggestions
Let $z_i = a_i x_i+ b_i y_i - c_i$ where $x_i,y_i$ are normally distributed and the coefficients are known. Let $\mu_x=E(x_i)$, $\mu_y=E(y_i)$, $\sigma^2_x=Var(x_i)$, $\sigma^2_y=Var(y_i)$,
$\sigma_{xy}=Cov(x_i,y_i)$.
Then $z_i$ is normal with $\mu_{z_i}=a_i \mu_x+b_i \mu_x - c_i$ and $\sigma^2_{z_i}=a_i^2 \sigma^2_x +b_i^2 \sigma^2_y+2a_i b_i \sigma_{xy}$
Then the log-likelihood of the data ($z_i=0$) is
$$L= - \sum \frac{\mu_i^2}{2\sigma_i^2}- \frac{1}{2}\sum \log(\sigma_i^2) $$
You could try to maximize this (as function of the parameters), but it looks quite cumbersome.
Another semi-heuristic recipe, given that minimizing squared errors with linear models goes typically hand in hand with gaussian models:

Normalize each linear equation, dividing by $\sqrt{a_i^2+b_i^2}$, so that the normalized coefficients verify $a_i^2+b_i^2=1$
The squared distance of a point $(X,Y)$ to the line $a_i x + b_i y - c_i=0$ is now given by $(a_i X + b_i Y - c_i)^2$. Hence, if we want to minimize the total squared distance, we'd like to "solve" the equation

$$A X =C$$
where $A$ is a $30 \times 2$ matrix ($a_i$ as first columne, $b_i$ as second column), $X=(x,y)^t$ is a $2 \times 1$ matrix, $C$ is a  $30 \times 1$ matrix ($c_i$ as a column). Of course, this system of 30 equations with 2 variables has (in general) no  exact solution, but it can be "solved" in a least-squared sense via the pseudoinverse matrix. Typically we'd compute:
$$X = (A^t A)^{-1}A^t C$$


I get an exception when re-installing a module

Question: I have re-installed modules before, but I can't get it this time. These are the steps I take:

Uninstall the modules (by deselecting them on the module list and clicking submit changes)
Remove the Module Files from the module folder
Check the database for any potential left over tables (specifically sms_feed)
Check the system table for any left over rows dealing with my modules
Delete anything related to my modules in the database
Clear the cache
Reinstall the modules

I always get the following error:

DatabaseSchemaObjectExistsException: Table sms_feed already exists. in DatabaseSchema->createTable() (line 657 of C:\xampp\htdocs\amaware\includes\database\schema.inc).

Do you have any idea?
Comment: The devel module provides a page (devel/reinstall) to comfortably reinstall modules. It might be worth giving that a try as it always works for me when I get errors like you're getting
Answer: What you have done in the first step is disabling the module, not uninstalling it. To uninstall it, you need to click on the "Uninstall" tab, select that module, and then click on the "Uninstall" button.
The exception raised from DatabaseSchema::createTable() is because it contains the following code.
  if ($this->tableExists($name)) {
    throw new DatabaseSchemaObjectExistsException(t('Table %name already exists.', array('%name' => $name)));
  }

The code in DatabaseSchema::tableExists() is then the following one.
  $condition = $this->buildTableNameCondition($table);
  $condition->compile($this->connection, $this);
  return (bool) $this->connection->query("SELECT 1 FROM information_schema.tables WHERE " . (string) $condition, $condition->arguments())->fetchField();

You could also manually remove the database table, but if the information about that table is still contained in information_schema.tables, DatabaseSchema::createTable() will raise an exception.
Answer: The step you are missing I believe (and what is likely causing the "table still exists error") is after your step 1 (and before step 2) you should visit admin/modules/uninstall (on D7) admin/build/modules/uninstall (on D6). Check the module you previously disabled and click uninstall.  This should remove all associated tables and will allow you to avoid your steps 3, 4 & 5.
Comment: Thank you! I do things once and I get upset when I don't get it perfect the second time... thanks!


Changing block position in Bartik theme

Question: I am using bartik theme to develop a website.I need the User menu and search block to be beside the logo and main menu block to be below the logo.
But all the menu and search blocks appear below the logo.How can I move the user menu and search block to right top corner of the page.
Thank you in advance.
Answer: you can change a position of menu and search block from structure > block link and assign it to * custom made region *, also use custom css can fix your problem.
also you can Demonstrate  the all region of theme from admin/structure/block/demo/bartik
hope this will help you

Changing block position in Bartik theme


Would it be considered rude to audition for a solo that's not in my part?

Question: In my college wind ensemble, we're playing the (band version of) Danzon no. 2 by Arturo Marquez. In the band version, there's trumpet parts and flugelhorn parts, and the band director assigned me to one of the flugelhorn parts. In the piece, there's also a really big trumpet solo, and so he decided to open auditions to se who can do it best.
Would it be considered rude for me, someone assigned to a flugelhorn part, to audition for the trumpet solo? I really love the piece, I've listened to it so many times, and I feel like I could do the solo justice, but at the same time I don't want anyone who was assigned one of the trumpet parts to feel like I `stole' their solo or anything like that.
Comment: Is it this: https://www.youtube.com/watch?v=3LonUO6eL08&t=415s
Comment: If the director doesn't mind, go for it, and please leave ego out of it.  Every audition you do is good experience.  Also note that to be an asset to the ensemble, be reliable (show up, wear the "uniform" well, do not get lost, follow the director religiously, come back from breaks a little early, etc., etc., and you'll get picked to fill in for other solos when someone comes down with a stomach bug.
Answer: If it's open auditions, then it's open auditions. However, this is a question for the ensemble director. "Am I eligible to audition for the part?".
Comment: I agree with this answer.  I'd add that it also depends on how you relate with the group.  Are a "just one of the gang" or do you think you're the best and therefore deserve the part?  Do you get most of the solos, or is it rare? Etc.


Motivating a solution of $\frac{a+b}{\sqrt{2(a^3+bc)}}+\frac{b+c}{\sqrt{2(b^3+ca)}}+\frac{c+a}{\sqrt{2(c^3+ab)}}≤\frac{a^2+b^2+c^2+21}{8abc}$

Question: The following is the problem I have been working on:

Let $a,b,c>0$ and $a+b+c=3$. Prove that:
$$\frac{a+b}{\sqrt{2(a^3+bc)}}+\frac{b+c}{\sqrt{2(b^3+ca)}}+\frac{c+a}{\sqrt{2(c^3+ab)}} \le\frac{a^{2}+b^{2}+c^{2}+21}{8abc}\tag{1}$$

A solution I read just uses one inequality that isn't very intuitive and doesn't come naturally to me
Solution:

Using this inequality:
$$\frac{a+b}{\sqrt{2(a^3+bc)}} \leq\frac{a^2+7}{8abc}+\frac{2a-b-c}{24abc}+\frac{2bc-ca-ab}{8abc}\tag{2}$$
We prove $(1)$

I don't understand how inequality $(2)$ is derived to prove the inequality $(1)$. Any help with the derivation of $(2)$ would be appreciated.
Comment: Isn't there a misprint in the numerator of the LHS of $(2)?$ shouldn't it be $a+b$ instead of $a+1?$
Comment: It seems (2) is not true for $a = 1, b = 3/2, c = 1/2$?
Comment: The question seems to be in spirit of [AM-GM](https://en.wikipedia.org/wiki/AM-GM_Inequality) and somewhat [partial fractions](https://en.wikipedia.org/wiki/Partial_fraction_decomposition). Try manipulation with those.
Comment: Can you show full the ans, I can't understand it! Thanks!
Comment: Oh I fixed it!!
Comment: I took it from the another source, the owner said that it is true!
Answer: Unfortunately, this is not a full answer, but it was too long in the comments. I tried proving the inequality, but I quickly burnt out. Maybe someone could try this with an online calculator like WolframAlpha.
For this problem, it is not AM-GM or partial fractions as it seems initially, but rather, substitution is $\color{red}{key}$.
The simplicity of the problem can be easily exploited when taking advantage of $\color{red}{a+b+c=3\iff a=3-b-c\iff b=3-a-c\iff c=3-b-a}$.

 You could trial and error for a decent amount of time with substitutions, but here I will just show how your inequalities can be much reduced.

Substituting into $(2)$,
\begin{align}\frac{a+1}{\sqrt{2(a^3+bc)}} &\leq \frac{1}{8}(\frac{a^2+7}{abc})+\frac{2a-b-c}{24abc}+\frac{2bc-ca-ab}{8abc}\\&\leq \frac{a^2+7}{8abc} + \frac{\color{blue}{2a^2-12a-6(c+b)+2ab+2ac+18+b^2+c^2}+4bc-6(b+c)+8-2a}{8abc}\\&\leq \frac{a^2+\color{blue}{b^2+c^2}+4bc-6(b+c)+13-2a}{8abc}\\&\leq \frac{a^2+\color{green}{b^2+c^2+2bc-6(b+c)+9}+4-2a+2bc}{8abc}\\&\leq \frac{a^2+\color{green}{a^2}+4-2a+2bc}{8abc}\\&\leq \frac{a^2-a+bc+2}{4abc}\end{align}
With given constraints, it can proven with more substitutions that $(2)$ is true
Comment: Can you show the more detailed ans please! Thanks!!


Rodar script Ajax automaticamente

Question: Estou com um problema em um projeto de faculdade.
Gostaria de saber como faço para rodar esse script Ajax automaticamente:

Rodar script Ajax automaticamente


Estimating a proportion based on two counts

Question: I need to estimate a proportion based on independent measurements of the numerator and the denominator.  Both the numerator and denominator are measured as counts.
I know from theory that the proportion must be less than one, but in practice the numerator can be higher than the denominator because both are estimates.
To make it concrete, these are cell counts in pre-treated vs post-treated biological samples.  I can measure cells in independent before-treatment and after-treatment samples, but imperfectly, and I know the treatment leads to fewer cells.  I want to estimate what proportion of cells survive the treatment (with an appropriate interval to reflect uncertainty).
How could I go about this?  My initial thought is a Bayesian negative binomial model with a truncated prior on the treatment effect but it feels like there should be a simpler way!
Edit: An example as requested - usually the post-treatment counts are less than the pre-sample counts, eg 4 cells in 1ml of sample post-treated compare to 10 cells in 1ml pre-treated.  In one or two cases I see, say 12 or 15 cells in 1ml treated sample compared to 10 in 1ml of pre-treated sample.  (Cells do cluster so I'm not concerned that the treated numbers look high given the theory).  I am comparing around 20 treatments to each control if that's useful information!
Comment: It sounds more like you have units like "cells per mL" than you have a proportion.
Comment: Can you give a numerical example, showing the sizes of the counts and typical amounts by which numerator may exceed denominator?
Comment: added an example
Comment: @Dave true I am measuring cells/ml in two sub-samples, but the underlying estimand is a proportion, as its the proportion of cells in the post-treatment sample that survived the treatment.  so i'm trying to use these counts/rates to get at that underlying proportion.
Answer: Comment, maybe not a complete Answer:
You mention counts might be Poisson. Suppose the true rate of a sample before
treatment is $\lambda_{pre} = 13$ and the true rate after treatment is $\lambda_{post} = 10.$ Then the probability of a higher count after treatment is
about $1/4.$ (Simulation below based on 100,000 hypothetical samples.)
set.seed(2021)
pre = rpois(10^5, 13)
mean(pre)
[1] 13.00925   # near 13
post = rpois(10^5, 10)
mean(post)
[1] 9.99841    # near 10

mean(post > pre)
[1] 0.23089    # aprx P(Post > Pre)

Put another way, quantiles .05 and .95 of $\mathsf{Pois}(13)$ $[7$ and $19,$ respectively] are not a lot
different from quantiles .05 and .95 of $\mathsf{Pois}(10),$ [5 and 15]. (Both Poisson distributions put a lot of probability between 7 and 15.)
qpois(c(.05,.95), 13)
[1]  7 19
qpois(c(.05,.95), 10)
[1]  5 15

A plot of the two Poisson PDFs is shown below.

A speculative Bayesian prior distribution could be chosen to have the effect of substantially ignoring 'reverse' counts, but that would not improve the relatively poor information available
from comparing Poisson counts.
I don't yet have a sufficiently good grasp of the context of your comparisons to
make a responsible recommendation.
(a) If your goal is to show that treatment tends in the direction of decreased counts,
then a (highly-random) Poisson model might be able to detect a meaningful decrease overall.
Suppose the overall rates are $\lambda_{pre}=13, \lambda_{post}=10$ throughout a group of $n=12$ subjects and that group averages before and after treatment are compared. Then the probability is about 98% that there will be
a positive decrease from average before to average after. (Even though some individual patients may not have shown decreases.)
set.seed(520)
a.dec = replicate(10^5, mean(rpois(12,13)) - mean(rpois(12,10)))
mean(a.dec > 0)
[1] 0.98395

(b) However, if your goal is to say whether treatment has truly decreased the rate for a particular patient, I don't think your method as described is adequate.

Note: R code for first figure:
x = 0:30;  PDF = dpois(x,13)
pdf = dpois(x,10)
hdr = "PDFs of POIS(13) [blue] and POIS(10)"
plot(x-.1, PDF, type="h", xlab="x", ylim=c(0,.14), lwd=2,
     col="blue", main=hdr)
 lines(x+.2, pdf, type="h", col="brown")
 abline(h=0, col="green2")
 abline(v=0, col="green2")

Comment: Thanks.  My goal is the former, but maybe even less ambitious I'm just trying to put a reasonable bound on what the treatment effect might be.  I know it's going to be vague!  Also I didn't mention I do have some replicates so its not as hopeless as it might seem.
Comment: Good. Then in my simulation for (a), R code `quantile(a.dec, c(.025, .975))` gives an approximate 95% confidence interval $(0.33, 5.67)$ on the avg decrease. Centered at $3.0.$ // Time for grocery shopping here.
Answer: I do have some experience with this type of data, so I'd suggest a couple of things to implement BruceET's elaboration on Poisson statistics (+1).
First, don't model ratios. Model counts. Model counts as close to the raw data as possible. If you're doing things like hemacytometer counts, model the actual counts, not the transformations to counts per ml.
Second, have a separate data line for each observed count value, annotated with all of the associated values of interest. Obviously you include the treatment type; structure it as a multi-level categorical variable with "control" as the reference level. Also include in each data line anything else that might matter: date of experiment if there is substantial inter-day variability, an indicator of which observations are paired if that's the case, drug concentrations if some of your "treatments" are the same drug at different concentrations, etc. If your cell counts come from different volumes of cell suspensions, include the volume value too.
Third, start with a Poisson regression generalized linear model. That makes sure that the error estimates are properly based on Poisson statistics (variance equals mean). Include the treatment predictor and any other variables that might be of interest. If volumes of the cell suspensions differed and you are interested in differences in cell numbers, use the log of the volume as an offset in the model (fixed to have a slope of 1).
Then (with standard treatment/dummy coding) each coefficient reported for the categorical treatment variable will represent the log difference between a corresponding treatment and control, taking into account any other predictors in your model. That is precisely the log of the ratio that you wish to estimate. It won't matter if in some cases, contrary to expectation, you find more cells in treatment than in control; it will effectively average out over the replicates. (Or not, if a treatment doesn't affect cell count.)
You might find that the Poisson model doesn't work well, in that estimated means and variances are too far apart. Then there are related regression approaches, allowing for a Poisson-like model with variance at some fixed multiple of the mean to be estimated from the data (quasipoisson) or modeling directly with a negative binomial distribution instead. The data set-up and modeling principles, however, would be the same.


How do customize settings.php during installation profile

Question: I'm creating an installation profile for my current company internal project.
During the installation process, one of the custom modules crashes during init(), since it tries to use one global variable defined on settings.php (that's current default behavior of the module)
Using system_form_install_settings_form_alter() I changed the settings form, by adding one input textfield for user's input, and on submit the value is appended to settings.php, but settings.php is rewrited before profile installation starts.
There is any way to prevent cleanup of settings.php by the installation process?
Comment: Maybe it would be easier to patch the module that is crashing, and submit your change to the issue queue for that project.  Before your change is accepted, you can add a reference to your patch in the makefile for your installation profile.
Comment: Hi, thanks for your answer. It's an custom internal module (not a contrib one), but yes, I patched it and problem solved.
Comment: Is it something where using a settings.local.php file that overrides the settings.php file could also help?
Comment: This link was big help for me http://previousnext.com.au/blog/collecting-and-writing-configuration-settings-settingphp-install-profile
Answer: You may find it easier to use a settings.common.php
Often during team projects, we have local settings.php with db credentials etc.. and a settings.common.php with settings common to the install and deployment environments.
You can add settings.common.php with an include / require line in settings.php
require 'settings.common.php'; // same directory, e.g sites/default/settings.common.php

and then write to it as needed during install.
Answer: My answer depends on the server using Apache, but I assume any of the other web servers can accomplish this too.
In your virtualhost config, you can set all of the variables for your environment:
SetEnv DBUSER datbase_user
SetEnv DBPASS database_pass
SetEnv DBNAME database_name
SetEnv DBHOST localhost

And in your settings.php file:
$databases = array (
   'default' =>
   array (
     'default' =>
     array (
       'database' => $_SERVER["DBNAME"],
       'username' => $_SERVER["DBUSER"],
       'password' => $_SERVER["DBPASS"],
       'host' => $_SERVER["DBHOST"],
       'port' => '',
       'driver' => 'mysql',
       'prefix' => '',
    ),
   ),
 );

You can set any other variables this way as well.
If you are worried about the $_SERVER array getting into the wrong hands, you can unset all of the important variables at the bottom of settings.php:
unset($_SERVER["DBUSER"]);
unset($_SERVER["DBPASS"]);
unset($_SERVER["DBNAME"]);
unset($_SERVER["DBHOST"]);

This is how we do it at my office to move sites between our dev environments, staging and even production.


Acrescentando valor no picturebox

Question: eu gostaria de saber se tem algum jeito de fazer isso aqui funcionar
int chck = 0;
int fid = 0;
        while (chck < 150)
        {
            try
            {
                sqlcon.Open();
                string sql2 = "SELECT img FROM clienteimg WHERE ((clienteid = '" + cid + "') AND (id = '" + fid + "'))";
                SqlCommand cmd2 = new SqlCommand(sql2, sqlcon);
                SqlDataReader dr2 = cmd2.ExecuteReader();
                dr2.Read();
                byte[] imgLoc = (byte[])dr2[0];
                sqlcon.Close();
                MemoryStream mstream = new MemoryStream(imgLoc);
                pb1.Image = Image.FromStream(mstream);
            }
            catch (Exception)
            {
                sqlcon.Close();
                sqlcon.Open();
                string foid = "9";
                string sql3 = "SELECT img FROM ClienteImgDB WHERE id = '" + foid + "'";
                SqlCommand cmd3 = new SqlCommand(sql3, sqlcon);
                SqlDataReader dr3 = cmd3.ExecuteReader();
                dr3.Read();
                byte[] imgLoc = (byte[])dr3[0];
                sqlcon.Close();
                MemoryStream mstream = new MemoryStream(imgLoc);
                pb1.Image = Image.FromStream(mstream);
            }
            chck++;
            fid++;
        }

sendo que, ali no  pb1.Image (picturebox1 pra quem não entendeu), eu queria que o numero fosse flexivel, eu sei que o exemplo a seguir não funciona, mas espero que entendam onde quero chegar
int chck = 0;
int fid = 0;
        while (chck < 150)
        {
            try
            {
                sqlcon.Open();
                string sql2 = "SELECT img FROM clienteimg WHERE ((clienteid = '" + cid + "') AND (id = '" + fid + "'))";
                SqlCommand cmd2 = new SqlCommand(sql2, sqlcon);
                SqlDataReader dr2 = cmd2.ExecuteReader();
                dr2.Read();
                byte[] imgLoc = (byte[])dr2[0];
                sqlcon.Close();
                MemoryStream mstream = new MemoryStream(imgLoc);
                pb'"+fid+"'.Image = Image.FromStream(mstream);
            }
            catch (Exception)
            {
                sqlcon.Close();
                sqlcon.Open();
                string foid = "9";
                string sql3 = "SELECT img FROM ClienteImgDB WHERE id = '" + foid + "'";
                SqlCommand cmd3 = new SqlCommand(sql3, sqlcon);
                SqlDataReader dr3 = cmd3.ExecuteReader();
                dr3.Read();
                byte[] imgLoc = (byte[])dr3[0];
                sqlcon.Close();
                MemoryStream mstream = new MemoryStream(imgLoc);
                pb'"+fid+"'.Image = Image.FromStream(mstream);
            }
            chck++;
            fid++;
        }

pra que toda vez que rode o loop, o "pb" se acrescente em mais 1 para preencher os 150 pictureboxes que tenho
Comment: Vendo o código e mesmo você explicando, não entendi o que você quer dizer com número flexível. Qual é o erro específico que você está encontrando? Você quer criar objetos dinamicamente?
Answer: Você pode utilizar o método Find do controle ou form em que estão inseridos os picturebox:
for (int i =0; i < 5; i++)
{
    ((PictureBox)this.Controls.Find("pb" + i, true)[0]).Image = null;
}

ps. Tenha certeza que existe o controle, caso contrário receberá uma exception.

Outra opção, seria gerar os controles dentro do loop, e então geraria somente a quantidade necessária (Eu faria dessa forma).
Considerando que os PictureBox estarão dentro do panel1:
panel1.Controls.Clear();
for (int i =0; i < 5; i++)
{
    PictureBox pb = new PictureBox();
    pb.Name = "pb" + i;
    pb.Image = null;
    pb.Parent = panel1;
    pb.Show();
}

Edit:
A primeira opção, no seu código ficaria assim:
try
{
    sqlcon.Open();
    string sql2 = "SELECT img FROM clienteimg WHERE ((clienteid = '" + cid + "') AND (id = '" + fid + "'))";
    SqlCommand cmd2 = new SqlCommand(sql2, sqlcon);
    SqlDataReader dr2 = cmd2.ExecuteReader();
    dr2.Read();
    byte[] imgLoc = (byte[])dr2[0];
    sqlcon.Close();
    MemoryStream mstream = new MemoryStream(imgLoc);
    ((PictureBox)this.Controls.Find("pb" + fid , true)[0]).Image = Image.FromStream(mstream);
}
...

Lembrando que o nome do seu PictureBox deve ser "pb"+ [cada fid que você irá carregar]

A segunda opção, sim, terá que remover os PictureBox da tela, pois não servirão pra nada. A recomendação é que utilize um Panel ou FlowLayoutPanel para inserir todos os PictureBox dentro, dessa forma fica fácil organizar, limpar e inserir.
Mas, com a segunda opção, muda a lógica que você está usando, o Select seria diferente, entre outras coisas.
Comment: desculpa mas eu nunca usei isso, não entendi direito como encaixar o meu "try" dentro, estou tentando com sua segunda opção, outra coisa, os pb que tenho então devo deletar né?, pelo que entendi o código ai cria um pb toda vez, correto?
Comment: com a permissão do colega, editei a resposta explicando como entraria no seu código. Espero que ajude.
Comment: deu certo, só ficou meio lento pq tem 150, mas pode ser o meu pc, de resto ficou top, vlw ai (:

Acrescentando valor no picturebox


Por que usar StyleSheet.create?

Question: Por que usar o StyleSheet.create? Ao iniciar um novo projeto (react-native init test, o projeto vem com o style da seguinte forma.
const styles = StyleSheet.create({
  container: {

  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
  Imagem: {
    resizeMode: 'contain',
    width: 50,
    height: 50
  }
});

Porem se eu fizer da seguinte forma, o style vai funcionar da mesma forma, então qual a diferença?
const styles = {
  container: {

  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
  Imagem: {
    resizeMode: 'contain',
    width: 50,
    height: 50
  }
}

Answer: Eu acho  melhor usar  StyleSheet sempre que possível porque você terá mais performance do que apenas usar objetos comuns.
Citação retirada da documentação do React :

Criar uma folha de estilo a partir de um objeto de estilo (Stylesheet) torna possível se referir a ele por ID em vez de criar um novo objeto de estilo sempre.
Ele(Stylesheet) também permite enviar o estilo apenas uma vez. Todas as utilizações subsequentes vão encaminhar um id (não implementado ainda).

Espero que ajude!

Por que usar StyleSheet.create?


How to disable parent term options in select list?

Question: I have a view with an exposed filter of taxonomy terms. The terms are displayed as a hierarchical structure in the select list. I want to disable the parent terms in the select list. How to do it in Drupal way?
Comment: In an HTML select list, how do you disable options? I wasn't aware that you could and Drupal doesn't affect how HTML works. You'll need to come up with a way to do that in HTML before working out how to apply it to Drupal
Comment: @Neograph734 Thank you very much! The patch works like charm and it provides expected output i.e. user cannot select parent term and hence it is as good as disabled. Thank you once again.
Comment: How would you do that using standard HTML?
Comment: Sorry, I did not get your question.
Comment: @Clive is right, though I suppose you could use [optgroups](https://developer.mozilla.org/nl/docs/Web/HTML/Element/optgroup) instead
Comment: I do not know much about optgroups. Does it integrate with views module?
Comment: `The HTML  element creates a grouping of options within a  element.` So they can be used everywhere a select can be used. How to get them in views is a different question. You could try this patch: https://www.drupal.org/node/1695658
Answer: I wanted to disable the parent term in the select list (views exposed filter) so that the user is not able to select it. This is how I achieved the desired functionality -
As mentioned by @Neograph734, using <optgroup> creates a grouping of options within <select> element. I applied the patch at drupal.org/node/1695658 that @Neograph734 provided.
Then in the views filter section, I selected the desired taxonomy reference field. Selected options as shown below -

Configured the field as an exposed filter. As as result you can see it as per below -

Now the user can select only child terms and not the parent terms.


How to Map this Array of objects to get a full object by deffrient specfic code property?

Question: Hey I need to map this array of products. I want to get the full objects after search with a specific value of the code property.
For example, how do I find all objects where the code is "balance"?
"products": [{
  "code": "balance",
  "currency": "ILS",
  "percentage": 1,
  "totalWorth": 150000,
  "totalYieldPer": 0,
  "items": [{
    "name": "בנק של עומרי",
    "currency": "NIS",
    "worth": 150000,
    "portfolioPer": 1,
    "yield": 0,
    "yieldPer": 0
  }]
}, {
  "code": "debt",
  "currency": "ILS",
  "percentage": 1,
  "totalWorth": 150000,
  "totalYieldPer": 0,
  "items": [{
    "name": "משכנתא על הדירה שלי",
    "currency": "ILS",
    "worth": 150000,
    "portfolioPer": 1,
    "yield": 0,
    "yieldPer": 0
  }]
}, {
  "code": "pension",
  "currency": "ILS",
  "percentage": 1,
  "totalWorth": 150000,
  "totalYieldPer": 0,
  "items": [{
    "name": "פנסיוני",
    "currency": "ILS",
    "worth": 150000,
    "portfolioPer": 1,
    "yield": 0,
    "yieldPer": 0
  }]
}]
}

Comment: Maybe you could use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter ?
Comment: Can you be bit what's the correct expected output.
Comment: you can use, an object containing objects
Answer: As far as my understanding, this solution would suffice:

var resObj = {};
products.forEach((item) => {
  resObj[item.code] = item;
});

console.log(resObj);


Symbolic Constants: How are they stored and what are their types?

Question: C++ allows you to use the #define preprocessor directive to define symbolic constants which the compiler will replace before compilation. My question is, how do compilers typically store these internally and do they have data types?
Answer: Strictly speaking, the compiler never sees constants declared with the #define preprocessor directive. These are handled on a textual substitution basis by the preprocessor. They do not have "types" in the C++ sense, since the preprocessor does not know anything about the C++ language semantics.
The preprocessor uses a straightforward text substitution strategy to resolve macros. For example, in the following code:
#define FIVE 5

int a = FIVE;

the compiler will see only:
int a = 5;

The symbol FIVE is gone from the source the compiler sees. Your compiler will have an option to run the preprocessor only; in GCC it is -E and in MSVC it is /E or /P. Using such an option, you can run your source through the preprocessor to see how it is changed.


Robust regression: setting the limit between errors and influential observations

Question: This thread discusses an issue found in robust regression estimation: when the model fit is particularly low, although significant, the Huber estimator with a standard $k$ value of, say, 2.5, downweights most of the observations. The result is very low coefficients and, loosely speaking, under-estimation of the predicted values.
When the errors dispersion is relatively compact and the model fit low, like in this example, which robust estimator is more efficient? Does it make sense to set Huber $k$ to some arbitrary errors quantile?
These are the diagnostics from the ordinary linear regression (lm). Note how Cook's distance is not flagging any particular influential point:
Comment: What is your response variable? How is it measured?
Comment: @whuber The model is trying to predict seismic movements every 10 seconds, based on a number of real-time predictors.
Comment: Yes, but how exactly is a "seismic movement" measured and represented? On the face of it, such a movement would (in its simplest form) be a 3D vector. You have also mentioned an interesting and important factor: your data must be *time series.*  That suggests there may be strong autocorrelations among the predictors and predictand, which is something you can (and need to) exploit.
Comment: @whuber About the time series, I've tried to use lagged versions of the predictors (around 0.10 correlation for some) but they don't give me a significant prediction improvement. The seismic measure is represented by a linear scale calculated aggregating a number of factors. But in general my question is about robust regression and the Huber estimator when facing a low fit model.
Answer: Your QQ plot bears a strong resemblance to that of a t distribution with 2 degrees of freedom (plot based on 40000 observations):

A t(3) and a Cauchy with sample sizes of 40,000 don't look as much like your QQ plot as the t(2), but note I'm not saying this is evidence that your error distribution is a t(2) or is even well-approximated by one.  The point is that your distribution is very fat-tailed indeed.
With the t family, the optimal estimator of location is redescending, meaning, heuristically, that the weight applied to extreme observations goes to zero faster than the observation value goes to infinity.  This means that extreme values receive less weight than with the Huber estimator, for which absolute values greater than the parameter $k$ have weights that, in effect, go to zero as fast as the observation value goes to infinity.  In the Wikipedia page for "Robust statistics", a little over halfway down, is a graphical comparison of the influence of values on the Huber (called "Winsorizing at 1.5") and Tukey biweight (a redescending estimator.)  A little farther down is a plot of the influence function of the optimal estimator for various t distributions.
Consequently, with this data, I'd not use the Huber $\psi$-function at all, instead setting psi=biweight in your call to rlm, and accepting the fact that a lot of your observations will have little or no influence on the final estimates.  Note, as @Macro observed in the thread to the other question, that this isn't a question of identifying and downweighting outliers, this is actually trying to get somewhat close to optimal estimates given your errors really do come from a very fat-tailed distribution - no outliers required or assumed.
Answer: This looks like a case where a linear fit might not be a good idea and there are certainly outliers and leverage points.  In your first plot it looks like your estimator is tring to fit just 3 or 4 point very closely and is essentially ignoring several outliers.  But I don't think it is fitting three points and ignoring the rest.  It appears to me that it is trying to go through te center of that oval shape mass of points and coincidentally by doing that it practically runs through three or four isolated points.  The Q-Q plot shows heavytailed behavior because of the large residuals both positive and negative due to the outliers. That should not be a surprise.  What I find interesting is that the robust regression gives a negative slope to the line.  it would be helpful to see the scatter plot of X vs Y so we could imagin what the least squares estimate would be.  If there are leverage points for extreme values of x the slope could even change sign.  Maybe any linear model would not help this.  It could be that X and Y are practically uncorrelated.
Comment: Michael, the plots are for the non-robust linear regression lm() to show the residuals without downweighting.
Comment: Sorry I read too quickly.  I am a little surprised that the red line represents the least squares fit.  I would have thought that the outlier with the huge residual of 50 at a fitted value of ten would have strong enough leverage to pull the curve to a positive slope without much change on the residuals in the central mass. But maybe it is just that my mind wants to view this as a scatter plot where the slope of the line would represent the slope parameter estimate for the model. But it is not.
Comment: The abscissa is actually the fitted Ys and the residuals don't tell me what the Xs are. The slope for the X covariate is not depicted there.
Comment: @RobertKubrick Is the lower plot with the V shaped fitted Ys the result for the robust regrssion?
Comment: Nope, all the diag plots are from lm().
Comment: Oh I see the V shape comes because the y coordinate is like an absolute value.  But how do we get an idea of what the robust estimator is doing?  It is pretty clear that least squares does not do a good job on this data.
Comment: Michael the model fit is low, that's a fact, and I'm not looking for a much better improvement using robust regression. The question is about the Huber estimator $k$ value when the residuals are not overly dispersed and the fit is low.


How to force a webpage to use HTTPs?

Question: I have designed a Online shopping website. Everything works fine with http. Now I want that the profile and the payment gateway should use HTTPS instead of HTTP. I have not dealt with https before and so I am stuck here. Here is my code snippet. I want profile.php to use https. I have seen some post where it has been told to edit mod_rewrite or use some https redirect function. But how will I do that? I am using XAMPP.
    if($rws['user_email']==$UserName && $rws['user_pass']==$UserPwd){
        if($_REQUEST['remember']==1){
            setcookie('uname',$UserName,time()+24*60*60);
            setcookie('pwd',$UserPwd,time()+24*60*60);
        }

        $_SESSION['fname'] = $rws['user_fname'];
        $_SESSION['ud'] = $rws['user_id'];

        header('Location:profile.php');
       }

Comment: Duplicate of http://stackoverflow.com/questions/4398951/force-ssl-https-using-htaccess-and-mod-rewrite
Comment: Read this post [How to make a website secured with https][1]

  [1]: http://stackoverflow.com/questions/2205325/how-to-make-a-website-secured-with-https
Answer: You need to put a rewrite condition in your .htaccess
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.yourdomain.com/$1 [R,L]

Comment: I am not familiar with this. Can you please explain how to edit .htaccess?
Comment: You need to redirect every url without the https, create a .htaccess file in the root of the project and past the code.
You just need to change the url adress.

How to force a webpage to use HTTPs?


how to create folder inside /Android/media in android 11?

Question: I want to create a new folder inside internal storage. But in the new version of Android, we can't create a folder as we created before. But some apps like WhatsApp create folders inside /Android/media/. I want to know about the way how we can create folders inside this location
Comment: Your app itself cannot create folders in ../Android/media. But a folder with the packagename of your app will be created if your app calls Context:getExternalMediaDirs(). After that your app can create folders and files in that directory. It is a pitty that some moderating person which hides behind @Commynity closed your question. Maybe it was a duplicate but the provided link is not for your question.
Comment: you have to use [MediaStore API](https://developer.android.com/reference/android/provider/MediaStore) for placing files in `media` folder
Comment: yep. But I couldn't find solution there. That's why I post this question. Do you have any solution?
Comment: @blackapps thanks that made the trick. upvoted, should be more visible and accepted answer.
Comment: @blackapps can you please explain and post an answer with example code?
Comment: Your post is closed so i cannot post an answer. Edit your question and hit the moderators.
Comment: Voting for reopen so answer can be posted :)
Comment: @blackapps It really helps, appreciate your answer. Actually nobody provided proper solution of this question. Now my question is, on android 11 and above it needs write external storage permission, so which is the right permission to write to android/media/package folder ? As stated by official doc that WES permission has no effect on Android 11 and above but without this permission we can not write any image or video. Can you please give your feedback on the same.
Comment: @blackapps Sorry for misunderstanding, it is working without any permission on Android 11 and above. Not tested below 11. Thank you :)
Comment: @smeet can you please share source code here. it will be easy to understand.
Answer:
context.getExternalMediaDirs() will return you all the folders from media folder and when you call that it will create a folder with your app's package name all you have to do is identify packagename and get your folder path. This function will return you full path to your folder inside media folder. But it will not work for lollipop and less versions.

<code> public static String create_folder_in_app_package_media_dir_new2(Context context) {

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
     File[] directory = new File[0];

     directory = context.getExternalMediaDirs();

 for(int i = 0;i<directory.length;i++){

         if(directory[i].getName().contains(context.getPackageName())){
             return directory[i].getAbsolutePath();
         }

     }

 }

     return null;
}
</code>

Note : If you delete or uninstall your application from device this folder will also be removed and data inside this folder will also be removed.


Include external setup files in setup.txt TYPO3

Question: is it possible to outsource some setups into different setup files, e.g. like menus or language setups? I want my setup.txt to stay clean.
Thanks for your replies :)
Answer: For including additional setup files you can use the INCLUDE_TYPOSCRIPT - Tag. Here is an example:
<INCLUDE_TYPOSCRIPT: source="FILE:fileadmin/TypoScript/menu.txt">

For the people who keep their setup file in an extension.
<INCLUDE_TYPOSCRIPT: source="FILE:EXT:ext_name/Configuration/TypoScript/Setup/setup.txt">

Be sure, that you place the include-tag at the right position in your setup.txt
Hope that helps
Comment: Please don't  advice people to put their TypoScript files under fileadmin. This is considered a bad practise.
Comment: True that. But the question is not specific enough. Should have covered both opportunities
Comment: Thanks, the INCLUDE-Tag is exactly what i've been searching for :)
Answer: This is possible, you can include single files with
<INCLUDE_TYPOSCRIPT: source="FILE:EXT:my_ext/Configuration/TypoScript/Setup/Config.txt">

It is also possible to include directories recursively:
<INCLUDE_TYPOSCRIPT: source="DIR:EXT:my_ext/Configuration/TypoScript/Setup/" extensions="txt">

Comment: Not all Typo users are using setup files from extentions^^
Comment: Well, they should... :) Puting configuration files into fileadmin is not a good practise.
Comment: Agreed as mentioned i should've covered both opportunities
Comment: Thanks for your answer :)


Contact Form in custom Theme

Question: I need to create one request information form that goes to each page in my website. That means I need to add that form into page.tpl.php page.
Form includes just basic information like name, email, phone, message and submit button.
So, what is the best practice to implement that form in my theme? I mean what are the steps to add form in Drupal?
I am new to Drupal and trying to learn it.
Thanks in advance!
Answer: You shouldn't add a form in the page.tpl.php.
Instead define your own form in a block, and then place your block in every page (using Drupal standard block system or a contrib module such Context
To define your contact form you have two options:

Use Form API: The form API allows you to create forms and react to submit of those forms. There are plenty examples of this. You will need to write your own module (easy), define your form in it and implement the block hooks to define a block that contains your custom form (you'll need at least hook_block_info and hook_block_view).
Use Webform module: This module allows you define forms that users can submit and the submitted data can be emailed to the email addresses you want. You don't have to write code and you can theme them with your theme.

Also Drupal has a simple module with contact forms, but I think is only to contact  users.
Comment: Thanks for your prompt response. Yes, this is Drupal 7.

I have created my own module for that form and activated that in my theme. It might sound silly but I don't know where and how should I include that so that it appears into all my page.
Thanks,
Comment: You don't "enable" a module in a theme. You enable modules, and you can enable themes, but they are unrelated actions. If you have created your form you will need to add to a custom block with that form as the block content. I've updated my answer.

Contact Form in custom Theme