text:
Q: Should I be using multiple SQL queries or multiple loops in my client code? I'm building a small internal phone number extension list.
In the database I have two tables, a people table, and a numbers table. The relationship is a one-to-many respectively.
I want to display the results in a single HTML table with one person per row but if they have multiple numbers it shows those in a single column with a rowspan on the person row to compensate.
Now, to get the results from the database to work with, I can either do:
(pseudocode)

SELECT id, name
FROM people

foreach result as row {
  SELECT number
  FROM numbers
  WHERE numbers.person_id = row['id']
}

This would mean that I'm doing one query to get all users, but then if I have 100 users, I'm performing 100 additional queries to get the numbers for each user.
Instead I could do it like this:
(pseudocode)

SELECT number, person_id
FROM numbers

SELECT id, name
FROM people

foreach people as person {
  echo name
  foreach numbers as number {
    if (number.id = person.id) {
      echo number
    }
  }
}

So, essentially it is doing the exact same thing except instead I do two queries to get all the results into arrays and then loop through the arrays to format my tables.
Which method should I be using or is there a better way to do this?

A: The common way is to do a regular JOIN:
SELECT id, name, number
FROM people, numbers
WHERE people.id = numbers.person_id;

You can either add an ORDER BY to get the numbers in order, or you could create an array with a single pass over the resultset, and then loop through that array.
You can also consider a GROUP_CONCAT to concatenate all the numbers for the same person:
SELECT id, name, GROUP_CONCAT(number SEPARATOR ', ')
FROM people, numbers
WHERE people.id = numbers.person_id
GROUP BY people.id;

Since you are even asking this question: I cannot stress the fact that you should pick up an introductory book on database design. It helped me wonders to learn the theories behind relational databases.

A: You probably want to execute just one query.  Something like
select people.id, people.name, group_concat(numbers.number)
from people
inner join numbers on numbers.id = people.id
group by people.id, people.name
order by people.name

Then you can loop over the result set with simple php code.

A: It depends, and you may have to time it to find out.  Doing multiple queries is a lot of network turns if your database is on a different computer than your web server, so often this takes longer.  However, if your database server is on the same computer as your web server, this might not be an issue.
Also consider the time it will take to look up the number in the array.  As an array you are doing a linear order O(N) search.  If you can put it in a hash, the lookup will be much faster, and the two query approach may be faster, but not if you spend a lot of time looking up the answer in your array.
Using a join to get it into one query, may be fastest, as the numbers will be associated with the people, depending on your container structure you are storing the data into to be accessed in your foreach loop.

A: Use a stored procedure or function to retrive the data, don't wite the sql in your programm

A: You should do neither. You can do one query (join) over the tables:
select name, number
from people p, numbers n
where p.id = n.person_id
order by name, number;

and then just one loop:
$link = mysqli_connect(...);
$query = 'select name, number from people p, numbers n where p.id = n.person_id order by name, number';

if ($result = mysqli_query($link, $query)) {
    $person = '';
    while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
        if ($row['name'] !== $person) {
            $person = $row['name'];
            echo $person;
        }

        echo $row['number'];
    }
}


text:
Q: configure my router to translate "example.com" to a website's IP Is possible to confingure my router to translate certain domain names ex:"example.com"
to a specified website's IP ex:"173.194.32.23" ???
I have a Sitecom Modem Router N300, and there are a lot of settings, but I don't understand what I have to configure.. DNS server, DNSmasq, virtual server...??

A: This can be done on individual computers by modifying a plain text file called hosts (the file itself usually has plenty of instructions on how to do so). See http://en.wikipedia.org/wiki/Hosts_file. I really recommend this solution if you have access to all the computers on the network. Note that this will persist across all networks though, since the data is stored on the computer.
A quick look at the manual for your router shows that the exact feature you're looking for is not possible. However, I noticed a Virtual Server function that could (possibly) be used for your problem. You can forward port 80 inside your LAN to a computer that needs to act as a DNS server, it's very complicated, and I'm not even sure that's feasible.
Another solution would be to just create a subdomain on a site you own and have that correspond to the IP you want (if the IP is local, you can't do that).
If what you're looking for is just URL blocking, your router supports that (under Firewall settings).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Fix multiple columns in html table (JQuery) I am looking for a way to freeze first three columns in html table. Sample of table: http://jsfiddle.net/ee6reLug/

...

Columns Column name1, "+" and Column name2 must be fixed and scrollable from left to right.
There is a demo for single fixed left column,
how do I create an HTML table with fixed/frozen left column and scrollable body?
but I need multple columns fixed. Is it possible in html, javascript or jquery?

A: answering it late.. but useful for someone searching for a solution
I've changed your code to this --> http://jsfiddle.net/PrateekPatra26/ee6reLug/5/
Separated the tables into two, one with 3 columns and the remaining table into another. Put them into div's and gave them specific width.
the css:
.pull-left {
    float: left!important
}
.pull-right {
    float: right!important
}
th{
    height:40px;
}
td{
    height:60px;
}

div's:

       .
       .
       .

       .
       .
       .

A: Enclose the table in a div and set a margin-left say 15em. Also set overflow-x:scroll
.outer {
   overflow-x:scroll;
   margin-left:15em;
   overflow-y:visible;
}

Now for the first 3 columns have separate classes and set position:absolute and left to 0em, 5em and 10em respectively.
.headcol1 {
    position:absolute;
    width:5em;
   left:0;
   top:auto;
}

.headcol2 {
   position:absolute;
   width:5em;
   left:5em;
   top:auto;
}

.headcol3 {
   position:absolute;
   width:5em;
   left:10em;
   top:auto;
}

Demo here
PS: I have some problems setting the column heights. If someone could fix that it will be helpful.


text:
Q: Assign CSS for all tables except one In my CSS I have:
table {
Width:100%;
max-width:600px;
}

Thisobviously assigns the above CSS to every table on the site but how can I make it not assign to just on table throughout the whole site?

A: You can use the CSS :not() Selector.
Here's an example for a selector for all tables except for a table with an ID of #uniqueTableID
table:not(#uniqueTableID) {
    width:100%;
    max-width:600px;
}

Notice this have some browser compatibility issues:
Feature         Chrome  Firefox (Gecko)         Internet Explorer   Opera   Safari
Basic support   1.0     1.0 (1.7 or earlier)    9.0                 9.5     3.2

Summary
The negation CSS pseudo-class, :not(X), is a functional notation
  taking a simple selector X as an argument. It matches an element that
  is not represented by the argument. X must not contain another
  negation selector, or any pseudo-elements.

A: If you need to support older browsers, one option would be to give your special table an id (or class) and then override the default table styles from your stylesheet. For example:
#special-table {
  display:table;
  width:auto;
  max-width:none;
  ...
}


text:
Q: Defining a code section within which a different code path is executed Is it possible to define a section or scope in my code within which a different code path is executed, without using a global or passed-down state variable?
For debugging purposes, I want to be able to surround a section of faulty code with a scope or #define to temporarily switch on pre-defined debugging behavior within this section, e.g. use debug data, a more precise data type, an already validated algorithm, … This needs to work in a multi-threaded application in which multiple threads will likely execute the same shared code concurrently, but only some of them have called this code from within the defined section.
For example, here is some pseudo-code that is not working, but might illustrate what I'd like to do. A static expensive function that is called from several places concurrently:
Result Algorithms::foo()
{
#ifdef DEBUG_SECTION
    return Algorithms::algorithmPrecise(dataPrecise);
#else
    return Algorithms::algorithmOptimized(dataOptimized);
#endif
}

Three classes of which instances need to be updated frequently:
Result A::update()
{
    return Algorithms::foo();
}

Result B::update()
{
    Result result;

#define DEBUG_SECTION
        ...

        result = a.update() + 1337;

        ...
#undef DEBUG_SECTION

    return result;
}

Result C::update()
{
    return a.update();
}

As you can see, class A directly calls foo(), whereas in class B, foo() is called indirectly by calling a.update() and some other stuff. Let us assume B::update() returns a wrong result, so I want to be able to use the debug implementation of foo() only from this location. In C::update(), the optimized version should still be used.
My conceptual idea is to define a DEBUG_SECTION around the faulty code which would use the debug implementation at this location. This, however, does not work in practice, as Algorithms::foo() is compiled once with DEBUG_SECTION not being defined. In my application, Algorithms, A, B, and C are located in separate libraries.
I want that within a section defined in the code, a different code section within shared code is executed. However, outside of this section I still want execution of the original code, which at runtime will happen concurrently, so I cannot simply use a state variable. I could add a debugFlag parameter to each call within the DEBUG_SECTION that is passed down in each recursive call that is then provided to Algorithms::foo(), but this is extremely prone to errors (you must not miss any calls, but the section could be quite huge, spread over different files, …) and quite messy in a larger system. Is there any better way to do this?
I need a solution for C++11 and MSVC.

A: This might work by using a template:
template<bool pDebug>
Result Algorithms::foo()
{
    if(pDebug)
        return Algorithms::algorithmPrecise(dataPrecise);
    else
        return Algorithms::algorithmOptimized(dataOptimized);
}

On the other hand this means moving your function definition into a header (or forcing template instantiation, see these answers).
The downside is that changing the call to Algorithms::foo() from instance.foo<false> to instance.foo<true> every time you want to switch between debugging and release might require effort. If you have multiple affected calls you could use a compile time const variable to reduce the typing effort, but not knowing your code exactly I can't estimate if this is a feasible solution.
If the majority of your code uses the optimized version of the function you can also set the template parameter to default to false (template<bool pDebug = false>) to avoid changing existing code that will not call the debug-version.


text:
Q: Inaccuracy of the Difference between two $\chi^2$ Cummulative Distribution Functions I have an algorithm which needs to calculate the difference of two Gamma distributions evaluated at some large values. I cannot do this over CDFs because they give $1$ if a large value is evaluated. Then the difference of the CDFs is always $0$. Getting a difference of zero is breaking down my code at the optimzation stage. I am able to solve this problem if I use NIntegrate over the PDFs but every iteration needs alot of time and eventually the code is not running due to impracticality or in other words I must wait a day which normally should end in a few minutes at max. Here is my code:
m = 1;
ω = {10, 10, 10, 10, 10, 10, 10, 10, 10, 10};
γ = {0.1202, 0.1413, 0.1862, 0.2399, 0.3090, 1.0000, 1.5849, 1.9055, 1.9953, 2.5704};

f0[k_,y_] := PDF[ChiSquareDistribution[ω[[k]]], y]
f00[k_, z_] := Gamma[ω[[k]]/2, 0, z/2]/Gamma[ω[[k]]/2]

f1[k_,y_] := \[Piecewise]   ((2(γ[[k]]+1))^(-ω[[k]]/2) E^(-y/(2(γ[[k]]+1))) y^(-1+ω[[k]]/2))/Gamma[ω[[k]]/2]    y>0  0 True
f11[k_, z_] := Gamma[ω[[k]]/2, 0, z/(2 (γ[[k]] + 1))]/Gamma[ω[[k]]/2]

t={120,200};
p0[k_, idx_] := f00[k, t[[idx+1]]] - f00[k, t[[idx]]]
p1[k_, idx_] := f11[k, t[[idx + 1]]] - f11[k, t[[idx]]]
utmp[k_, idx_] := Log[p1[k, idx]/p0[k, idx]]
Subscript[m, 0][k_] := Sum[p0[k, idx]*utmp[k, idx], {idx, 1, m}];
Subscript[s, 0] := Sum[Sum[p0[k, idx]*(utmp[k, idx] - Subscript[m, 0][k])^2, {idx, 1, m}], {k, 1, 10}];

Lets evaluate the code:
Subscript[s, 0]

Indeterminate

If we change
t = {20, 25};

we get
0.517914

If I change
p0[k_, idx_] := NIntegrate[f0[k, y], {y, t[[idx]], t[[idx + 1]]}]
p1[k_, idx_] := NIntegrate[f1[k, y], {y, t[[idx]], t[[idx + 1]]}]

Then for the original case
t={120,200};

we get
3.17318*10^-17

But in this case as I said before evaluating Subscript[s, 0] is taking too much time.. Is there anyway to do with without NIntegrate?
here it is

A: m = 1;
ω = {10, 10, 10, 10, 10, 10, 10, 10, 10, 10};

Convert γ to exact values to avoid forcing machine precision calculations
γ = {0.1202, 0.1413, 0.1862, 0.2399, 0.3090, 1.0000, 1.5849, 1.9055,
    1.9953, 2.5704} // Rationalize;

f0[k_, y_] := PDF[ChiSquareDistribution[ω[[k]]], y]
f00[k_, z_] := Gamma[ω[[k]]/2, 0, z/2]/Gamma[ω[[k]]/2]

f1[k_, y_] :=
   Piecewise[{{y^(-1 + ω[[k]]/2)/
             ((2*(γ[[k]] + 1))^(ω[[k]]/2)*
                E^(y/(2*(γ[[k]] + 1))))/
          Gamma[ω[[k]]/2], y > 0}}]

f11[k_, z_] :=
 Gamma[ω[[k]]/2, 0, z/(2 (γ[[k]] + 1))]/Gamma[ω[[k]]/2]

t = {120, 200};
p0[k_, idx_] := f00[k, t[[idx + 1]]] - f00[k, t[[idx]]]
p1[k_, idx_] := f11[k, t[[idx + 1]]] - f11[k, t[[idx]]]
utmp[k_, idx_] := Log[p1[k, idx]/p0[k, idx]]
Subscript[m, 0][k_] := Sum[p0[k, idx]*utmp[k, idx], {idx, 1, m}];
Subscript[s, 0] :=
  Sum[Sum[p0[k, idx]*(utmp[k, idx] - Subscript[m, 0][k])^2, {idx, 1, m}], {k,
    1, 10}];

In evaluating Subscript[s,0] use arbitrary-precision rather than machine precision
Subscript[s, 0] // N[#, 15] &

(* 3.17318496695314*10^-17 *)

EDIT : Re your comment
If you enter machine precision numbers you will get machine precision results.
Precision[104.93434075028202]

(* MachinePrecision *)

N[f00[9, 200] - f00[9, 104.93434075028202], 100]

(* 0. *)

Precision[%]

(* MachinePrecision *)

Use either
f00[9, 200] - f00[9, 104.93434075028202`40]

(* 5.5830137827358486462429*10^-18 *)

Precision[%]

(* 22.7469 *)

Note that the complexity of the calculation results in a loss of about 17 digits of precision
or
f00[9, 200] - f00[9, SetPrecision[104.93434075028202, 40]]

(* 5.5830137827358526192441*10^-18 *)

Precision[%]

(* 22.7469 *)

EDIT 2: I cannot reproduce the results that you show in your comments. I am using version 12.0.0 on a Mac.
f11[1, SetPrecision[525/4, 40]] - f11[1, SetPrecision[225/2, 40]]

(* 4.4711124996345361867775*10^-17 *)

Precision[%]

(* 23.3494 *)

N[f11[1, 525/4] - f11[1, 225/2], 30]

(* 4.47111249963453618677749651064*10^-17 *)

Precision[%]

(* 30. *)

A: Edit:  I've changed this from an extended comment to an answer.
The title concerns estimating the difference between two $\chi^2$ distribution functions.  The text has the appearance of not directly addressing that question because of the large amount of code that doesn't explicitly mention a distribution function (at least in my opinion).
A brute force approach is to create a function that calculates the difference explicitly:
f[n_?IntegerQ, z1_?NumericQ, z2_?NumericQ, nDigits_: 50] :=
 N[CDF[ChiSquareDistribution[n], Rationalize[z2]] -
   CDF[ChiSquareDistribution[n], Rationalize[z1]], nDigits]

For an example:
f[10, 199, 200]
(* 9.9470513771808598331974744855157686475664682149287*10^-38 *)

However, this direct approach fails for more extreme values of $z_1$ and $z_2$.  Note that the difference in the CDF functions is a function of the incomplete gamma function:
PiecewiseExpand[
   CDF[ChiSquareDistribution[n], z2] - CDF[ChiSquareDistribution[n], z1],
   Assumptions -> {z1 > 0, z2 > 0}] // FunctionExpand // FullSimplify

(* (Gamma[n/2, z1/2] - Gamma[n/2, z2/2])/Gamma[n/2] *)

This is the same as using
Gamma[n/2, z1/2, z2/2]/Gamma[n/2]

So a more stable function for the difference in two $\chi^2$ distribution functions (with the same number of degrees of freedom) is
g[n_?IntegerQ, z1_?NumericQ, z2_?NumericQ, nDigits_: 50] :=
 N[Gamma[n/2, Rationalize[z1/2], Rationalize[z2/2]]/Gamma[n/2], nDigits]
g[10, 199999, 200000]

(* 9.6305672408760073406090960801307527696848945201455*10^-43412 *)


text:
Q: Docker compose volume mount ignores the data I have a docker compose file as:
    ...
    restart: always
    ports:
      - "5432:5432"
    environment:
      POSTGRES_PORT: 5432
    volumes:
      - ./tablestruct:/docker-entrypoint-initdb.d/folder1
      - ./tablestruct1:/docker-entrypoint-initdb.d/folder2

volumes:
  folder1:
  folder2:

When i run compose up, i get:
postgres_1  | /usr/local/bin/docker-entrypoint.sh: ignoring /docker-entrypoint-initdb.d/folder1
postgres_1  |
postgres_1  | /usr/local/bin/docker-entrypoint.sh: ignoring /docker-entrypoint-initdb.d/folder2

A: From dockerhub postgres image documentation:

If you would like to do additional initialization in an image derived
  from this one, add one or more *.sql, *.sql.gz, or *.sh scripts under
  /docker-entrypoint-initdb.d (creating the directory if necessary).
  After the entrypoint calls initdb to create the default postgres user
  and database, it will run any *.sql files, run any executable *.sh
  scripts, and source any non-executable *.sh scripts found in that
  directory to do further initialization before starting the service.
Warning: scripts in /docker-entrypoint-initdb.d are only run if you
  start the container with a data directory that is empty; any
  pre-existing database will be left untouched on container startup. One
  common problem is that if one of your /docker-entrypoint-initdb.d
  scripts fails (which will cause the entrypoint script to exit) and
  your orchestrator restarts the container with the already initialized
  data directory, it will not continue on with your scripts.

You should move everything to the same directory and mount it as /docker-entrypoint-initdb.d/ and not a folder inside it.
So:
volumes:
  - ./tablestruct:/docker-entrypoint-initdb.d


text:
Q: Hide/Show Div below select depending on whether an option is selected or not Basically I have a select:
<select id="SelectExample">
    <option value="no_selection"> </option>
    <option value="accessoires">Accessoires pour poubelles</option>
    <option value="chaises">Chaises</option>
    <option value="collecte">Collecte de déchets</option>
    <option value="poubelles">Poubelles</option>
</select>

Just below that is a div I want hidden if the value is no_selection

Poids (kg)<input type="text" id="poids" class="medium" disabled="disabled"/>

Prix (€)<input type="text" id="prix" class="medium" disabled="disabled"/>

Volume (l)<input type="text" id="volume" class="medium" disabled="disabled"/>

Modifier les attributs…

I've tried the previous JQuery and CSS examples I've found, but none seem to work for me, can anyone give me a good example of what to do as I'm a bit stuck, thanks.

A: Here you go.
You need to bind a change event to your select box, and on change, use :selected to retrieve the value of the selected option, and show or hide depending on that. The jQuery toggle method is great for that.
<!DOCTYPE html>

        <select id="SelectExample">
            <option value="no_selection"> </option>
            <option value="accessoires">Accessoires pour poubelles</option>
            <option value="chaises">Chaises</option>
            <option value="collecte">Collecte de déchets</option>
            <option value="poubelles">Poubelles</option>
        </select>

Poids (kg)<input type="text" id="poids" class="medium" disabled="disabled"/>

Prix (€)<input type="text" id="prix" class="medium" disabled="disabled"/>

Volume (l)<input type="text" id="volume" class="medium" disabled="disabled"/>

Modifier les attributs…

A: <select id="SelectExample" onChange="$('#OtherDiv').toggle($(this).val() != 'no_selection');">

A: Sounds like something of the following could work for you?
$("#SelectExample").change(
 function()
 {
  var that = $(this);

  if(that.val() == "no_selection"){
   $("#OtherDiv").show();
  }else{
   $("#OtherDiv").hide();
  }
 }
);

Just a simple OnChange event, then checking the value of the field - saying that, you don't even really need JQ for this..

A: change display:
<select id="SelectExample" onchange="showOther(this.value)">
    <option value="no_selection"> </option>
    <option value="accessoires">Accessoires pour poubelles</option>
    <option value="chaises">Chaises</option>
    <option value="collecte">Collecte de déchets</option>
    <option value="poubelles">Poubelles</option>
</select>

Poids (kg)<input type="text" id="poids" class="medium" disabled="disabled"/>

Prix (€)<input type="text" id="prix" class="medium" disabled="disabled"/>

Volume (l)<input type="text" id="volume" class="medium" disabled="disabled"/>

Modifier les attributs…

and create a javascript function that handles your onchange:

JSFiddle Example


text:
Q: How to learn abstract algebra rigorously on your own? I am a PhD student in chemical engineering. I use abstract algebra to large extent. Even many times I have to read many bigs proof's from mathematics like structure theorem etc and present in front of faculty members. The problem I am facing is I have done enough course on abstract algebra, but even after doing those course I feel quit weak. I can read a proof and try to write it on notebook many times and many times I convince myself with wrong proofs that means wrong interpretation of the proof, I realise these things in front of faculty member's. I want to avoid these things. I want to work in such a way that proof's becomes clear to me. I try things like writing proofs on my own at least 4-5 times etc.I want to do preparation of these proof's in rigorously mean each term should be clear. I took one-two weeks to prepare one proof.
Question : How to learn abstract algebra rigorously on your own? One more meaning of rigorous is not get confused when people ask questions. In simple how to avoid confusions to maximum extent?

A: First, I would recommend learning some formal logic and proof theory directly. In particular, you'd want a text that focuses on proving and not on semantics or metatheory. It should use something like Natural Deduction or the Fitch system, and not a Hilbert-style approach. You don't have to go very deep or spend a lot of time on this. You're looking at it as a tool, not as a field of study.
Second, you should rebuild your understanding of the field, abstract algebra in this case, from the ground up. Go back to some introductory book and read through it again. Only this time, every time you get to a proposition or a theorem, prove it yourself before looking at the proof in the book (if any is given). Prove everything. You should be able to skim past most of the text, so the "reading" shouldn't take very long, but, on the other hand, thinking up your own proof of a statement is a lot more challenging and time-consuming.
Typically, the proof you come up with will be similar to the one in the book. If it is similar, but the book's proof is simpler than yours then this is an opportunity to refine your proof writing skills. If it is similar, but the book's proof is more complicated, this often means that you've missed some detail or are making unwarranted assumptions. If it is different, this could be due to several reasons: 1) your proof could be wrong, 2) the book proof restricts itself to an "elementary" approach while you do not, 3) your proof is "right" but circular (e.g. using the fundamental theorem of finite abelian groups to prove a result that will later be used to prove the fundamental theorem of abelian groups); you're not "solving problems", you're rebuilding, 4) the book's prof is wrong, 5) your proof is just different. Differentiating case 1 from case 5 is where studying proof theory and such comes in. You need to be able to tell when your proofs are wrong or right. When you're uncertain about a proof, make it more formal. In fact, you should try to be as formal as is tolerable during this rebuilding.
You probably don't want to do this quite so slavishly as I've presented it. First, for the "heavy-duty" theorems, you may want to flesh out a proof sketch rather than formulate your own proof from scratch. Second, you should feel free to bring in your understanding from other fields and prove things your own way. Third, and related to the previous, reorganize the presentation to suit your tastes, don't just follow the book's presentation. That said, if you are not confident in the correctness of your own proofs, it can still be worthwhile to prove the statements in the book in the style/way the book expects so you can compare apples to apples. Feel free to prove the statements in multiple ways. Often seemingly different proofs are different ways of packaging the same idea and you should get used to translating between the different views.
Obviously, none of this is specific to abstract algebra. This "rebuilding" process is something you should do multiple times throughout your career. (Often it is a way to refresh your knowledge of a field that you've been away from for a while.) Later "rebuildings" will likely rely much less on books. Instead, you'll be more interested in integrating it with knowledge you've acquired in the meantime or fitting it into higher-level frameworks.


text:
Q: Using Reactive Expressions I am trying to use the user selected variable inputs after uploading any .csv file into the app, and plot a simple scatter plot.

Error: Reading objects from shinyoutput object not allowed.

I understand that I'm supposed to add in the reactive function, however I do not know where to add it. Could someone please share with me? Thank you!
library(shiny)

# Define UI for application that draws a histogram
ui <- fluidPage(

  # Application title
  titlePanel("Javier Test"),

  # Sidebar with a slider input for number of bins
  sidebarLayout(
    sidebarPanel(

      # Input: Select a file ----
      fileInput("file1", "Choose CSV File",
                multiple = FALSE,
                accept = c("text/csv",
                           "text/comma-separated-values,text/plain",
                           ".csv")),

      # Horizontal line ----
      tags$hr(),

      # Input: Checkbox if file has header ----
      checkboxInput("header", "Header", TRUE),

      # Input: Select separator ----
      radioButtons("sep", "Separator",
                   choices = c(Comma = ",",
                               Semicolon = ";",
                               Tab = "\t"),
                   selected = ","),

      # Input: Select quotes ----
      radioButtons("quote", "Quote",
                   choices = c(None = "",
                               "Double Quote" = '"',
                               "Single Quote" = "'"),
                   selected = '"'),

      # Horizontal line ----
      tags$hr(),

      # Input: Select number of rows to display ----
      radioButtons("disp", "Display",
                   choices = c(Head = "head",
                               All = "all"),
                   selected = "head"),

      #implementing dropdown column
      uiOutput("input1"), #use this instead when you are trying to upload something instead then process it
      uiOutput("input2"),

      sliderInput("bins",
                  "Number of bins:",
                  min = 1,
                  max = 50,
                  value = 30)
    ),

    # Show a plot of the generated distribution
    mainPanel(
      # Output: Data file ----
      plotOutput("distPlot"),
      plotOutput("scatterplot")
    )
  )
)

library(ggplot2)

# Define server logic required to draw a histogram
server <- function(input, output) {

  #df <- reactiveValues(x= list, y = data.frame())

  output$input1 <- renderUI({
    selectInput("variable", "Variable:",
                colnames(input$file1)) #this will select
  })

  output$input2 <- renderUI({
    selectInput("variable1", "Variable:",
                colnames(input$file1)) #this will select
  })

  # output$distPlot <- renderPlot({
  #
  #   # obtain input from user for column
  #   x    <- output$contents[, input1$variable] #selecting which column position
  #
  #   # generate bins based on input$bins from ui.R
  #   bins <- seq(min(x), max(x), length.out = input$bins + 1)
  #
  #   # draw the histogram with the specified number of bins
  #   hist(x, breaks = bins, col = 'darkgray', border = 'white')
  #
  # })

  output$scatterplot <- renderPlot({

    x <- output$contents[, input$variable]
    y <- output$contents[, input$variable1]

    #generate plot
    ggplot(output$contents, aes(x=x, y=y, colour=Species)) + geom_point() + theme_classic()

  })

}

shinyApp(ui, server)

Update
I've gotten it to work. Solution is below.
library(shiny)
library(ggplot2)

# Define UI for application that draws a histogram
ui <- fluidPage(

  # Application title
  titlePanel("Javier Test"),

  # Sidebar with a slider input for number of bins
  sidebarLayout(
    sidebarPanel(

      # Input: Select a file ----
      fileInput('file1', 'Choose CSV File',
                accept=c('text/csv',
                         'text/comma-separated-values,text/plain',
                         '.csv')),

      # Horizontal line ----
      tags$hr(),

      checkboxInput('header', 'Header', TRUE),
      radioButtons('sep', 'Separator',
                   c(Comma=',',
                     Semicolon=';',
                     Tab='\t'),
                   ','),
      radioButtons('quote', 'Quote',
                   c(None='',
                     'Double Quote'='"',
                     'Single Quote'="'"),
                   '"'),

      #implementing dropdown column
      selectInput('xcol', 'X Variable', ""),
      selectInput('ycol', 'Y Variable', "", selected = "")),

    # Show a plot of the generated distribution
    mainPanel(
      # Output: Data file ----
      plotOutput('MyPlot')
    )
  )
)

# Define server logic required to draw a histogram
server <- shinyServer(function(input, output, session) {
  # added "session" because updateSelectInput requires it

  data <- reactive({
    req(input$file1) ## ?req #  require that the input is available

    inFile <- input$file1

    # tested with a following dataset: write.csv(mtcars, "mtcars.csv")
    # and                              write.csv(iris, "iris.csv")
    df <- read.csv(inFile$datapath, header = input$header, sep = input$sep,
                   quote = input$quote)

    # Update inputs (you could create an observer with both updateSel...)
    # You can also constraint your choices. If you wanted select only numeric
    # variables you could set "choices = sapply(df, is.numeric)"
    # It depends on what do you want to do later on.

    updateSelectInput(session, inputId = 'xcol', label = 'X Variable',
                      choices = names(df), selected = names(df))
    updateSelectInput(session, inputId = 'ycol', label = 'Y Variable',
                      choices = names(df), selected = names(df)[2])

    return(df)
  })

  output$MyPlot <- renderPlot({
    x <- data()[,c(input$xcol, input$ycol)]
    plot(x)
  })
})

shinyApp(ui, server)


text:
Q: Pdf is not getting open some time after BinaryWrite I created the functionality to edit the existing PDf content(adding some text and images) and after that i am opening this pdf file for print or download and i am using this code
Pdf is not getting open some time after BinaryWrite
byte[] outBuf = outStream1.GetBuffer();
HttpContext.Current.Response.Expires = 0;
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition",  "attachment;filename="test.pdf");
HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.ContentEncoding = new System.Text.UTF8Encoding();
HttpContext.Current.Response.BinaryWrite(outBuf);
outStream.Close();
HttpContext.Current.Response.End();

It is working fine on local machine or development server and some time on server.
On server after some times it is opening blank page. And after browser cache clear or temp file clear it works
I am not getting it where is the problem may be some client browser memory problem.
But if it is browser memory issue the it should also come on local too because I am using the same browser.
Please give me some idea or solution so that I can sort our this thing.

A: The GetBuffer method only returns exactly the content of the memory stream if it was created as a readonly stream from an array of bytes to begin with. Otherwise it returns the internal buffer, which may contain unused bytes at the end.
Use the ToArray method to get exactly the content of the memory stream, and nothing more:
byte[] outBuf = outStream1.ToArray();

A: Another thing that triggers some browsers some of the time to treat your stream as PDF, is to append some dummy argument to your URL so that it ends with ".pdf". I am not sure if this is really necessary in your case since your are setting the 'content-disposition' to 'attachment'. It won't hurt though.


text:
Q: Module not found building Storybook in an Angular Nx Monorepo I am unable to build and run Storybook after adding it to an Nx Angular v11 project.  The project was recently migrated to Nx.  The project builds and serves without issue and I was able to add an e2e app without problem.
❯ npx nx build-storybook client

> nx run client:build-storybook

>  NX  ui framework: @storybook/angular

>  NX  Storybook builder starting ...

info => Cleaning outputDir: /repos/project/dist/storybook/client
info => Loading presets
info => Compiling manager..
info => Compiling preview..
info => Found custom tsconfig.json
info => Using implicit CSS loaders
info => Loading angular-cli config for angular lower than 12.2.0
info => Using angular project "client:build" for configuring Storybook
info => Using angular-cli webpack config
info => Loading custom Webpack config (full-control mode).
Starting type checking service...
(node:35617) DeprecationWarning: Default PostCSS plugins are deprecated. When switching to '@storybook/addon-postcss',
you will need to add your own plugins, such as 'postcss-flexbugs-fixes' and 'autoprefixer'.

See https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#deprecated-default-postcss-plugins for details.
(Use `node --trace-deprecation ...` to show where the warning was created)
ERR! => Failed to build the manager
ERR! Module not found: Error: Can't resolve '@storybook/addon-knobs/register' in '/repos/project'
Module not found: Error: Can't resolve '@storybook/addon-knobs/register' in '/repos/project'

To add Storybook, I ran the following:
nx g @nrwl/angular:storybook-configuration --name=client
Below are some pertinent details about the resulting configuration without modification.
I suspect it is a webpack configuration issue. Can anyone spot what my issue is?  Thx.
❯ npx nx report

>  NX  Report complete - copy this into the issue template

  Node : 14.16.1
  OS   : darwin x64
  npm  : 7.24.2

  nx : Not Found
  @nrwl/angular : 11.6.3
  @nrwl/cli : 11.6.3
  @nrwl/cypress : 11.6.3
  @nrwl/devkit : 11.6.3
  @nrwl/eslint-plugin-nx : 11.6.3
  @nrwl/express : 11.6.3
  @nrwl/jest : 11.6.3
  @nrwl/linter : 11.6.3
  @nrwl/nest : Not Found
  @nrwl/next : Not Found
  @nrwl/node : 11.6.3
  @nrwl/react : Not Found
  @nrwl/schematics : Not Found
  @nrwl/tao : 11.6.3
  @nrwl/web : Not Found
  @nrwl/workspace : 11.6.3
  @nrwl/storybook : 11.6.3
  @nrwl/gatsby : Not Found
  typescript : 4.0.8

❯ cat package.json
{
  ...
  "dependencies": {
    "@angular/animations": "11.2.14",
    "@angular/cdk": "^11.2.13",
    "@angular/common": "11.2.14",
    "@angular/compiler": "11.2.14",
    "@angular/core": "11.2.14",
    "@angular/forms": "11.2.14",
    "@angular/google-maps": "^11.2.13",
    "@angular/platform-browser": "11.2.14",
    "@angular/platform-browser-dynamic": "11.2.14",
    "@angular/platform-server": "11.2.14",
    "@angular/router": "11.2.14",
    ...
  },
  "devDependencies": {
    "@angular-builders/custom-webpack": "^11.1.1",
    "@angular-devkit/build-angular": "~0.1102.0",
    "@angular-eslint/eslint-plugin": "~1.0.0",
    "@angular-eslint/eslint-plugin-template": "~1.0.0",
    "@angular-eslint/template-parser": "~1.0.0",
    "@angular/cli": "^11.2.0",
    "@angular/compiler-cli": "^11.2.0",
    "@angular/elements": "^11.2.14",
    "@angular/language-service": "^11.2.0",
    "@babel/core": "^7.15.8",
    "@compodoc/compodoc": "^1.1.15",
    "@nrwl/angular": "11.6.3",
    "@nrwl/cli": "11.6.3",
    "@nrwl/cypress": "11.6.3",
    "@nrwl/eslint-plugin-nx": "11.6.3",
    "@nrwl/express": "11.6.3",
    "@nrwl/jest": "11.6.3",
    "@nrwl/linter": "11.6.3",
    "@nrwl/node": "11.6.3",
    "@nrwl/storybook": "^11.6.3",
    "@nrwl/tao": "11.6.3",
    "@nrwl/workspace": "11.6.3",
    "@storybook/addon-actions": "^6.3.12",
    "@storybook/addon-essentials": "^6.3.12",
    "@storybook/addon-knobs": "^6.1.11",
    "@storybook/addon-links": "^6.3.12",
    "@storybook/angular": "^6.3.12",
    ...
    "ts-node": "~9.1.1",
    "typescript": "^4.0.8",
    "webpack-bundle-analyzer": "^3.3.2"
  },
...

❯ cat .storybook/tsconfig.json
{
  "extends": "../tsconfig.base.json",
  "exclude": [
    "../**/*.spec.js",
    "../**/*.spec.ts",
    "../**/*.spec.tsx",
    "../**/*.spec.jsx"
  ],
  "include": ["../**/*"]
}

❯ cat apps/client/.storybook/tsconfig.json
{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "emitDecoratorMetadata": true
  },
  "exclude": ["../**/*.spec.ts" ],
  "include": ["../src/**/*", "*.js"]
}

❯ cat .storybook/webpack.config.js
/**
 * Export a function. Accept the base config as the only param.
 * @param {Object} options
 * @param {Required<import('webpack').Configuration>} options.config
 * @param {'DEVELOPMENT' | 'PRODUCTION'} options.mode - change the build configuration. 'PRODUCTION' is used when building the static version of storybook.
 */
module.exports = async ({ config, mode }) => {
  // Make whatever fine-grained changes you need

  // Return the altered config
  return config;
};

❯ cat apps/client/.storybook/webpack.config.js
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
const rootWebpackConfig = require('../../../.storybook/webpack.config');
/**
 * Export a function. Accept the base config as the only param.
 *
 * @param {Parameters<typeof rootWebpackConfig>[0]} options
 */
module.exports = async ({ config, mode }) => {
  config = await rootWebpackConfig({ config, mode });

  const tsPaths = new TsconfigPathsPlugin({
    configFile: './tsconfig.base.json',
  });

  config.resolve.plugins
    ? config.resolve.plugins.push(tsPaths)
    : (config.resolve.plugins = [tsPaths]);

  return config;
};

❯ cat .storybook/main.js
module.exports = {
  stories: [],
  addons: ['@storybook/addon-knobs/register'],
};

❯ cat apps/client/.storybook/main.js
const rootMain = require('../../../.storybook/main');

// Use the following syntax to add addons!
// rootMain.addons.push('');
rootMain.stories.push(
  ...['../src/app/**/*.stories.mdx', '../src/app/**/*.stories.@(js|jsx|ts|tsx)']
);

module.exports = rootMain;

A: Addon-knobs is deprecated anyway so try to remove it and install addon-controls instead
https://www.npmjs.com/package/@storybook/addon-knobs

A: The root cause of this error is that addon-knobs does not have a register module.  It has a preset module.
Changing
addons: ['@storybook/addon-knobs/register']

to
addons: ['@storybook/addon-knobs/preset']

resolves the module not found error.
However, as @marko suggests, the better solution is to migrate to addon-controls.


text:
Q: Update dynamic object (using QThread) image from C++ to QML I have a problem with my assignment.
After receiving data in real time, I can create and show 1 moving object image on a background from C++ to qml using ImageProvider (this is simple and done). However, my assignment requirements: "Click on button to generate dynamically a number of object moving independently (example 3 objects, but it should not be fixed). So I decided to create 3 threads for each item, each thread will be received data and update to image separately. However, my problem is:
In qml file, I must declare a code segment for update a image such:
Image  {
   id: id_image
   source: "image/MyImageProvider/id_image

   cache: false
   function reload(){
      source = "";
      source = "image/MyImageProvider/id_image"
}

Connections {
   target: MyObject
   onSignal_reload:{
     id_image.reload()
   }
}

How could I do the similar thing when I can not know number of object in advanced? Anyone have idea? Thanks.

A: You could put the Image Item into a Repeater.
Then subclass the QAbstractItemModel and use this as model for the Repeater.
Take a look at the example at
http://doc.qt.io/qt-5/qtquick-modelviewsdata-cppmodels.html


text:
Q: Dual of an eulerian graph I was studying graph theory in Bollobas book's and I found a result given without proof that I wasn't able to understand. Here is my problem:
"Le G be an eulerian graph, then its planar dual is a bipartite graph". Can anyone explain me why it is true.
Thanks in advance for the help.

A: The edge set of a circuit in $G$ correspond to (inclusion wise) minimal cuts in $G^*$ and vice versa.
Now we have the following theorem:
Let $G$ be a graph, $G$ is eulerian if and only if every minimal cut has even cardinality.
Proof:
$"\Longleftarrow"$
Let $v \in V(G)$ be a vertex then the cut $\delta(v)$ has even cardinality, thus $\text{deg}(v)=|\delta(v)|$ is even.
$"\Longrightarrow"$
Let $\delta(X)$ be a cut,  $X \subset V$. As $G$ is eulerian we can partition its edge set into edge-disjoint closed walks $C_1,\ldots, C_k$. But note that every of those walks intersects $\delta(X)$ in an even number of edges.
Thus $G$ is eulerian iff every minimal cut has even cardinality. Every minimal cut in $G$ has even cardinality iff every circuit in $G^*$ has even cardinality.
It follows that $G$ is eulerian iff $G^*$ is bipartite.


text:
Q: Ruby, How to create an n size array of random float from 0 to 1 I know that i can create a random float by calling rand() to generate a (psuedo-)random float between 0 and 1. But what is the best way to create an array of size n of random float between 0 and 1 without using a loop? Thanks!

A: This would do:
Array.new(n) { rand }


text:
Q: CloudFlare Invalid SSL certificate I have a Laravel 8 application.
I have no idea what I missed. I'm trying to deploy a site in my server.
I kept getting :
Invalid SSL certificate
https://mybabies.app/

server {
    listen 443;
    ssl_certificate /etc/nginx/ssl/mybabies.app.crt;
    ssl_certificate_key /etc/nginx/ssl/mybabies.app.key;

    server_name mybabies.app www.mybabies.app;

    root /home/bheng/mybabies/public;

    index index.html index.htm index.php;

    charset utf-8;

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php/php7.3-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include /etc/nginx/fastcgi_params;
    }

    client_max_body_size 500M;

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    access_log on;
    access_log /var/log/nginx/access.log;
    error_log  /var/log/nginx/error.log error;
    error_page 404 /index.php;

    # Media: images, icons, video, audio, HTC
    location ~* \.(?:jpg|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|mp3|ogg|ogv|webm|htc|woff2|woff)$ {
        expires 1M;
        access_log off;
        add_header Cache-Control "public";
    }

    # CSS and Javascript
    location ~* \.(?:css|js)$ {
        expires 1y;
        access_log off;
        add_header Cache-Control "public";
    }

    location / {
        #limit_req zone=one burst=2 nodelay;
        try_files $uri $uri/ /index.php?$query_string;
        add_header 'Access-Control-Allow-Origin' '*';
    }

}

I already create crt + pem key in CloudFlare and configure in these 2 lines :
ssl_certificate /etc/nginx/ssl/mybabies.app.crt;
ssl_certificate_key /etc/nginx/ssl/mybabies.app.key;

Edit
When I paused it

When I clicked View Certificate, I see

Updated
I created the cert from

A: To setup secure connection between Cloudflare and your server you need to generate Origin CA Certificate in page Origin Certificates, but you did this in Client Certificates instead, so that's why you are getting error.
They are completelly different things with different purpose. Read descriptions.
Client Certificates

Secure and authenticate your APIs and web
applications with client certificates. Block traffic from devices that
do not have a valid client SSL/TLS certificate with mTLS rules.

Origin Certificates

Generate a free TLS certificate signed by Cloudflare to install on
your origin server. Origin Certificates are only valid for encryption
between Cloudflare and your origin server.

After generating PEM an KEY you need to put them in .crt and .key and load in nginx config, like you did before.
listen 443;
ssl_certificate /etc/nginx/ssl/mybabies.app.crt;
ssl_certificate_key /etc/nginx/ssl/mybabies.app.key;

Now connection Full (strict) should work.
If you want to use self-signed certificate instead, but still leverage secure connection between CF and server, then use option Full instead (without strict). By using Flexible your visitor will be still using HTTPS, but there will be no SSL connection between CF and server, and server will see this as HTTP connection, so this option is not recommended.
Rad more: https://support.cloudflare.com/hc/en-us/articles/200170416-What-do-the-SSL-options-mean-


text:
Q: Windows azure disabled due to cache exeeding 128 MB alocated to msdn premium subscription I just started to learn windows azure and have I have exceeded the cache limit of 128 MB for my MSDN Premium subscriptions this month and my account have been disabled. I'm trying to figure out what services use cache by default as I looked at usage log and saw that something used about 8 MB per day. I have not done something specific just played around created one web site, two cloud services(but not deployed any packages), one service bus namespace, one sql database, one vm (but un-deployed it after some testing, disk remained on storage account).
My question is what is cause that constant usage of cache space.

A: I was also confused by this and wrote a post about Azure cache billing but in summary:
You have assigned a 128MB cache to use each month but since it displays usage as a percentage, 50% implies you have 64MB left to use but it doesn't accumulate like that. Think of 50% to mean you have half a month left to use the cache.
Because you have set up a 128MB cache you are using it - regardless of if you are actually using it. It's like compute hours in that respect.


text:
Q: Error when install the Composer LARAVEL The PHP exe file you specified did not run correctly:
C:\xampp\php\php.exe

The php.ini used by your command-line PHP is:
C:\xampp\php\php.ini

A setting in your php.ini could be causing the problem: Either the 'extension_dir' value is incorrect or the dll does not exist.
Program Output:

Warning: PHP Startup: Unable to load dynamic library
  'C:\xampp\php\ext\php_pdo_firebird.dll' - The specified module could
  not be found.  in Unknown on line 0
Warning: PHP Startup: Unable to load dynamic library
  'C:\xampp\php\ext\php_imagick.dll' - %1 is not a valid Win32
  application.  in Unknown on line 0

A: please check the php.ini file located in C:\xampp\php
and search extension=php_imagick.dll and replace with
 ;extension=php_imagick.dll


text:
Q: Jquery .find td with text in th I need set color for TD which containt 1, but only for TH which containt AAA. I have this table and I prepare this script. But script not work. Do you have some idea please ?
Thank very much
TABLE

AAA

    1
    2

    A
    B

DDD

    1
    2

    A
    B

SCRIPT
$('tr').each(function(){
var tr = $(this);
if (tr.find('th:eq(0)').text()=="AAA") {
    if(tr.find('td:eq(0)').text()=="1") tr.addClass('hidden');
}
});

CSS
.hidden{
color:red;
 }

A: Because of the way your s are mixed in with your other rows, the simplest solution involves looping through all rows, like this:
var lastHeader = '';
$('table tr').each(function() {
    var cells = $(this).find('td,th');
    if (cells.filter('th').size() > 0) { // this is a header row
        lastHeader = cells.text();
    } else if (lastHeader == 'AAA') { // it's under an AAA section
        cells.filter(':contains(1)').addClass('hidden');
    }
});

You can see an example of this here: http://jsfiddle.net/kapvr/
I took a bit of a shortcut in the above script to add the class to any cells that contain the text 1 - even if there's more content as well. If you want an exact match, you could modify it like this:
var lastHeader = '';
$('table tr').each(function() {
    var cells = $(this).find('td,th');
    if (cells.filter('th').size() > 0) { // this is a header row
        lastHeader = cells.text();
    } else if (lastHeader == 'AAA') { // it's under an AAA section
        cells.each(function() {
            if ($(this).text() == '1') $(this).addClass('hidden');
        });
    }
});

That version can be seen in action here: http://jsfiddle.net/5ybPp/

A: The body of your each loop looks at a single tr, trying to find both th and td there, but in your HTML the th and td are not in the same row. You'll need to look for the th in tr.prev() or look for the td in tr.next().

A: Personally I would change the markup to make this easier.

AAA

    1
    2

    A
    B

DDD

    1
    2

    A
    B

With this altered markup, you don't need the script at all.
How are you getting the HTML in this case?


text:
Q: SQL Converting sum of null values to 0 I have a query in SQL which sum values and add them as months to a date.
    SELECT
    FROM_UNIXTIME(S.created) as start_date,
   (FROM_UNIXTIME(S.created) + INTERVAL (C.items_left + C.items_given) MONTH)
    AS end_date,
    FROM table1 S
    LEFT JOIN table2 C ON C.id = S.id;

The problem arises when some of these values to sum are null instead of 0 and I am not able to change the source of data.
(FROM_UNIXTIME(S.created) + INTERVAL (C.items_left + C.items_given) MONTH)
AS end_date,

is generating nulls because (C.items_left + C.items_given) is null.
So, the question is, how do I execute this sum so the result is 0 instead of null?

A: use coalesce
SELECT
    FROM_UNIXTIME(S.created) as start_date,
   ( coalesce(FROM_UNIXTIME(S.created),0) + INTERVAL coalesce((coalesce(C.items_left,0) + coalesce(C.items_given,0)),0) MONTH)
    AS end_date,
    FROM table1 S
    LEFT JOIN table2 C ON C.id = S.id;

A: Use COALESCE():
(FROM_UNIXTIME(S.created) + INTERVAL (COALESCE(C.items_left, 0) + COALESCE(C.items_given, 0)) MONTH)


text:
Q: User login always display "Invalid password" error in MEAN I am trying to write a simple user login method in node.js using mongoose and mongoDB as database. Everytime I register a new user, I am able to login with those credentials for a few times, but then somehow it starts displaying the error "Invalid password". Any help would be appreciated. Below are the code snippets:
HTML file:
<form>

Email: <input type="email" ng-model="LC.logInfo.email" required>

Password: <input type="password" ng-model="LC.logInfo.password" required>

    <input type="submit" value="Login" ng-click="LC.login()" class="logreg_button">
</form>

user.js (model file)
UserSchema.methods.validPassword = function(enteredPassword){
return bcrypt.compareSync(enteredPassword, this.password)
    }

UserSchema.pre('save', function(next){
var user = this
bcrypt.genSalt(10, function(err,salt){
    if(err) console.log(err);
    bcrypt.hash(user.password, salt, function(err, hash){
        if(err) console.log(err);
        user.password = hash;
        next();
    });
});
})

users.js (server side controller file)
login: function(req,res){
    User.findOne({email: req.body.email}, function(err, user){
        if(err) {
            res.json({status: false, errors:err});
        }
        else if(user){
            if(user.validPassword(req.body.password)){
                req.session['userInfo'] = {
                id: user._id,
                first_name: user.first_name
                }
                res.json({status:true, userInfo: req.session['userInfo'] })
            } else {
                res.json({status: false, errors: 'Invalid password!'})
            }
        } else {
            res.json({status: false, errors: 'User not found!'})
        }
    })
},

A: It's not related to login service.
You generate hashed password in pre save hook. For first time this is correct but when an user need to be updated this hook corrupts the password.
You need to handle it in other ways. For example in pre save hook you would check if the user is new or not and if it's new then hash the password.


text:
Q: How to make clickable Header in React I am trying to make my Header clickable to navigate to homepage but the code below is not working, I'm sure that there should be a really easy way to do it.
const Header = () => {
  const navigate = useNavigate()

  return (

        The X app

  )
}

A: React executes navigate('/') on every render (and assigns the results to the onClick prop)
Shouldn't this be onClick={() => navigate('/')} ?


text:
Q: The following error originated from your application code, not from Cypress i tried to test this simple code
       type Url = string
       it('loads examples', () => {
      const url: Url = 'https://www.ebay.com/'
       cy.visit(url)
       cy.get('input[type="text"]').type('book')
        cy.get('#gh-btn').click();

        })

then I faced this error

how can I solve it

A: The accepted answer will cause Cypress to ignore all uncaught exceptions in the application. Generally, when these come up it means you found a bug in your app and should fix it.
Binding to the global Cypress object causes the event to stay bound for your entire test run. Usually, this isn't what you want.
If you actually need to ignore the exceptions though, you should be binding the event on the cy object so it's only persisted for the single test it's used in.
it('my test', () => {
  cy.once('uncaught:exception', () => false);

  // action that causes exception
  cy.get('body').click();
});

A: Try adding this in support/index.js:
import './commands'
Cypress.on('uncaught:exception', (err, runnable) => {
  // returning false here prevents Cypress from failing the test
  return false
})

This should avoid the uncaught:exception in the click() method.

A: I got Same Issue like this
Cypress Error
The following error originated from your application code,
not from Cypress.    >
Cannot read properties of null (reading 'textContent')
When Cypress detects uncaught errors originating from
your application it will automatically fail the current test.
This behavior is configurable, and you can choose to turn this off by
listening to the uncaught:exception event.Learn more
No Need to worry about this.
Just paste this code to your index.js file :)
import './commands'
   Cypress.on('uncaught:exception', (err, runnable) => {
   // returning false here prevents Cypress from
 // failing the test
   return false
   })

A: Actually, if you click in the Learn more link that comes with the error, you'll get everything you need.
https://docs.cypress.io/guides/references/error-messages#Uncaught-exceptions-from-your-application

Quoting others:

won't this answer ignore all errors thrown by the application?
The accepted answer will cause Cypress to ignore all uncaught exceptions

That is true.
Also, @DJSDev did not work for me when using Cypress v10.0.3.
The aforementioned link provides a working alternative:
it('is doing something very important', (done) => {
  // this event will automatically be unbound when this
  // test ends because it's attached to 'cy'
  cy.on('uncaught:exception', (err, runnable) => {
    expect(err.message).to.include('something about the error')

    // using mocha's async done callback to finish
    // this test so we prove that an uncaught exception
    // was thrown
    done()

    // return false to prevent the error from
    // failing this test
    return false
  })

  // assume this causes an error
  cy.get('button').click()
})


text:
Q: How to prevent clicking on GestureDetector child Flutter I'm having a button inside a GestureDetector. Both the GestureDetector and the IconButton have their own function. However, I just want to execute the function of GestureDetector instead of ```IconButton`` when tapping on the icon. I know some solutions for this proble, but I still wonder in the case above, is there any solution that prevent flutter from executing the IconButton's function?
Thanks

A: Tap priority child> GesuterDetector. If you have a single child as IconButton on GestureDetector only IconButton will work.
Let's say you have a column instead.

*

*you can pass null on onPressed of IconButton based on condition.

*using AbsorbPointer will prevent tap event of its child, and GestureDetector tap event will work in this case.

*IgnorePointer will totally ignore any tap event in its area.

Demo Widget

class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget();
  // final String title;

  @override
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  bool _disableIconButton = false;

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      backgroundColor: Colors.white,
      body: Container(
        child: Column(
          children: [
            GestureDetector(
              onTap: () {
                print("GestureDetector Tapped");
              },
              child: IconButton(
                onPressed: () {
                  print(" only Icon will be working here");
                },
                icon: Icon(Icons.ac_unit),
              ),
            ),
            SizedBox(
              height: 100,
            ),
            GestureDetector(
              onTap: () {
                print("GestureDetector Tapped");
              },
              child: Column(
                children: [
                  Text("Inside Column"),
                  Switch(
                    value: _disableIconButton,
                    onChanged: (v) {
                      setState(() {
                        _disableIconButton = v;
                      });
                    },
                  ),

                  ///* Colors will faded on
                  IconButton(
                    onPressed: _disableIconButton
                        ? null
                        : () {
                            print("Icon null checker tapped");
                          },
                    icon: Icon(Icons.ac_unit),
                  ),

                  ///* Colors will faded on like disable and will work on GuesterTap
                  AbsorbPointer(
                    absorbing: _disableIconButton,
                    child: IconButton(
                      onPressed: _disableIconButton
                          ? null
                          : () {
                              print("Icon AbsorbPointer tapped");
                            },
                      icon: Icon(Icons.ac_unit),
                    ),
                  ),

                  ///* it will ignore tap event
                  IgnorePointer(
                    ignoring: _disableIconButton,
                    child: IconButton(
                      onPressed: _disableIconButton
                          ? null
                          : () {
                              print("Icon IgnorePointer tapped");
                            },
                      icon: Icon(Icons.ac_unit),
                    ),
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}

A: Solution 2: Write a separate function and pass a parameter to trigger that function based on your requirement.
About this. I think he meant that you have 2 functions now that you call if user tap the icon/button:
tapIcon() {//do this and that}

tapButton() {//do this and that}

Then you create a 3rd function that has an argument on which you decide which function should be called:
callFunc(bool iconTap) {
   iconTap ? tapIcon() : tapButton();
}

And you use this on the onTap/onPressed: () {callFunc(true/false);}
Or you can use enum if you are planning to have more functions:
enum FunctionsEnum { BUTTON, ICON }

callFunc(FunctionsEnum functionsEnum) {
   if (functionsEnum == FunctionsEnum.BUTTON) tapButton();
   if (functionsEnum == FunctionsEnum.ICON) tapIcon();
}

Then pass an enum: onTap: () {callFunc(FunctionsEnum.BUTTON);}

A: Solution 1: You can just provide an empty function to IconButton onPressed method.
Solution 2: Write a separate function and pass a parameter to trigger that function based on your requirement.


text:
Q: How do you determine power flow direction in a transmission line? Below is a picture of a typical transmission line(about 200 kV). Is there a simple physics experiment which can be performed safely near the line, to determine the power flow direction. Or in other words: where is the generator and where a consumer.

A: Measuring T-line power flow from the ground without contact is tricky, especially near the tower. The tower is a solidly grounded structure and tends to sink the EM fields to ground, and the conductors are far from your position (high in the air). Better to move to mid-span where there is no tower and the conductors are closer to the ground. Also better to select a single-circuit power line (the photo above shows a double-circuit tower).
Voltage can be estimated with a capacitive voltage divider by using a horizontal-flat-plate capacitor on a grounded pole. The bottom plate connects to the grounded pole (is grounded), and the top plate floats at a voltage proportional to line voltage. Put a plastic sheet between them for insulation. The measurement will be corrupted by the unequal contribution of the 3 phases, but the closest phase will dominate. Be careful - this top plate can reach several hundred volts depending on the line voltage and distance from line to capacitor. It won't hurt you (too high impedance) but might damage a voltmeter.
Current can be estimated by detecting the magnetic field at ground level using a loop of wire. The varying mag field from the AC current flow in the line will couple to the coil and produce an EMF. If the coil is open circuit, this results in a 60 Hz voltage across the terminals. If it is closed circuit, the result is a 60 Hz current through the loop. Again, the value is corrupted by the 3 phases, but the closest phase will dominate. Us the right hand rule to orient your coil to determine the direction of current flow. Move the coil around to get the largest output.
Calibration is not really possible for an accurate measurement of power flow unless you have a real flow measurement to compare to, but if you are substantially closer to one outside phase than to the center and other outside phase, you should be able to compare voltage phase and current phase to determine power flow direction.
Recall that REAL Current Transformers have an orientation indication, telling you that if power is positive (voltage and current are in phase) then power flow is in a known direction. Your ground set will change power flow direction if you flip the coil around. But you can figure that out by starting with a line where you know the direction of real power flow (away from an operating generator).
If you plan to use an Arduino or other microcontroller to measure and calculate for you, be aware of the voltages and scale appropriately. A high impedance measurement device might see too high a voltage from the plate capacitor and be damaged. You can scale using a capacitive voltage divider before connecting to your measurement input. Start with a high voltage voltmeter connected to top and bottom plate set on highest AC range to get a feel for the output voltage. The indictive coil voltage is a crap-shoot - try putting a 100 ohm resistor across the open terminals and measure with a voltmeter.
Make sense?

A: The relevant equation is that of complex power in an AC circuit:
$$\vec{S}=\frac{\vec{V} \vec{I}^{*}}{2}=\frac{V I}{2} \angle -\phi$$
This is to say, the complex power flowing through a line is equal to the complex voltage times the conjugate of the complex current divided by two.  Those not familiar with AC circuits will have a tough time with the complex variables, but let's turn to the following definitions for illustration.  Note that I'm going to establish voltage as the reference angle.
$$S=P+jQ$$
$$\vec{I}=I \angle \phi$$
$$\vec{V}=V \angle 0^{\circ}$$
The real power is $P$ and the imaginary power is $Q$.  The interesting thing to note is that $P$ can be either negative or positive.  Before applying any of this however, you must have a reference direction.  You're looking at the line, you can look either right or left, you establish one of those directions as positive, and then $P$ will follow as either negative or positive and if positive, it flows in the direction you're looking.
Here is an illustration, although I think this differs in convention by the sign of $\phi$.

Now, here is what you need to establish the direction of power flow:

*

*A reference direction

*The angle between the voltage and current

Exactly how you measure this is certainly the difficult part.  I will defer to other answer regarding that.  But provided that you do, if $\phi \in (-\pi/2,\pi/2)$ then the power flows in the positive direction and if $\phi \in (\pi/2, 3\pi/2)$ it flows in the negative direction.

A: When power is consumed, the voltage and current rises and fall together (with some variation due to power factor).  As you consume energy from the grid the voltage generally stays the same but the current rises and falls depending on your consumption.  As you reduce your demand to zero, the current falls to zero, then when you start feeding into the grid, the current becomes negative with respect to voltage (ie. 180 degrees out of phase).  So to determine energy flow, you need to know the current in the wire and whether that current is negative or positive with respect to the voltage.
You can do this by measuring the voltage and current at the same time (instantaneous values), then multiply them together, if the answer is negative, you are feeding into the grid, if it's positive, you are using power.  How you do this is the tricky bit, a current clamp and a voltage transformer with the output calculated within a micro-controller (ie. Arduino). Could also use a current clamp and an antenna wire near the power wire with a circuit tuned to your mains frequency (measuring the emf), again results calculated via a micro-controller.  Been trying to find a better/easier way to do this without contact, but as yet haven't found an easy answer?   The measuring current via a current clamp is easy, but the voltage transformer and emf antenna for me have produced some erratic results.

A: Actually, you don't need to measure things at two different positions along the wire to determine the power flow. You can do this with measurements taken at a single position. You must measure both current and voltage. The measuring device is built so that it rotates based on the relative phase of the current and voltage; and the direction of rotation corresponds to the direction of power flow. That's what happens in the power meter connected to your house. If you couldn't measure power flow this way it would be very hard for the electric utility to charge you for power.
EDIT: The power meter in your house of course touches the wires, but standing on the ground under a transmission line you can do something similar. You can have two pickups, a coil and a straight antenna, and you could feed them into an xy-oscilloscope. Pure reactive power should show a straight diagonal trace, and real power should show a circular loop. The problem is that you won't be able to see the direction the loop is tracing...clockwise or counterclockwise. You would need to compare the direction of rotation to a known field source, e.g. a short line you've set up purposely for calibration. You've got to make sure you're consistent with the relative physical orientation of the two pickups. In effect you're measuring the Poynting vector.
If you had two guitar amplifiers, you could amplify your pickups and feed them into an ordinary household power meter, which is already set up to convert the relative phases into an actual mechanical rotation that you can see. Of course you've still got to orient your pickups consistently and calibrate the direction of rotation against a known power flow.

A: With a high-powered rifle, shoot one of the lines in two at the middle. Observe the two ends. The one that sparks the most is the line going back to the generator.
When these power lines carry DC, I believe it is impossible to easily determine the direction of current flow.
For AC lines, it's fairly easy; one times the 60Hz signal. Use two receivers separated by long enough to get 60Hz out of phase. If the speed of light is 186,000 miles per second, and the speed of wave transmission in the lines is on that order, then a 1% phase difference will need a distance of 0.05 x 186,000 miles/second x (1/60th seconds) = 31 miles.

I learned something from the comments on this question: power companies nowadays adjust the phases of their power lines by putting capacitors and inductors in the line. They do this fairly often and their effect is to modify the relative phase. So if you do measure the field at two points near the wire, make sure that there's not a power station in between your measurements. To learn more about this, try googling "power transmission"+shunt+series


text:
Q: Json Record to show <?php require_once('Connections/mycon.php'); ?>
<?php

mysql_select_db($database_mycon, $mycon);
$query_Recordset1 = 'SELECT country.name as country, country_Message.name as Message
FROM country, country_Message
WHERE country.id = country_Message.country_id';

//$Recordset1 = mysql_query($query_Recordset1) or die(mysql_error());

$query_Recordset2='select name from country';
$Recordset2=mysql_query($query_Recordset2) or die(mysql_error());
$json_output=array();

$json_countryoutput=array();
while($mainrow=mysql_fetch_assoc($Recordset2))
{
$json_countryoutput[]=array($mainrow['name']=>$mainrow['name'] );

}

mysql_free_result($Recordset2);

$Recordset2=mysql_query($query_Recordset2) or die(mysql_error());
while($mainrow=mysql_fetch_assoc($Recordset2))
{

$Recordset1 = mysql_query($query_Recordset1) or die(mysql_error());
while($row=mysql_fetch_assoc($Recordset1))
{

if(strcmp ( $mainrow['name'] , $row['country'])==0)
{
//echo $row['country'];
$json_output[]=array($mainrow['name']=>$row['Message'] );

/
/$json_output[]1=array('country'=>$row['country'],'Message'=>$row['Message'] );
}

mysql_free_result($Recordset1);

}
//$json_output=array_merge($json_output, $json_countryoutput);

echo json_encode(array('item'=>$json_output,'country'=>$json_countryoutput));

mysql_free_result($Recordset1);

Out Put:
{"item":[{"German":"Hello"},{"German":"guten Morgen"},{"German":"gute Nacht"},{"English":"Hello"},{"English":"good morning"},{"English":"good Night"},{"French":"bonjour"},{"French":"bonne nuit"},{"French":"bonjour"}],"country":[{"German":"German"},{"English":"English"},{"French":"French"}]}
i want to change basically i have different country  and each country i want to display all records:
 {"German":[{"hello"},{"gutton Morgan"}],"English":[{""},{""}],"French":[{""},{""}]  }

A: I'm not really sure if I understood what you try correctly but maybe this might help:
$recordSet = mysql_query($queryRecordSet1);
$results = array();
while ($row = mysql_fetch_assoc($recordSet)) {
  if (isset($results[$row["name"]])) {
    $results[$row["name"]][] = $row["Message"];
  } else {
    $results[$row["name"]] = array($row["Message"]);
  }
}
echo json_encode($results);

There can be some syntactical errors but I hope I was able to give you the idea. As the result set will give you something like this:
"German" "hello"
"German" "gutten tag"
When adding them to a result set check if the "German" key is already set or not. If the key exists, then you should just append to the array, if not you should create a new array and add a new element to it.


text:
Q: Convert multiple .wav to .caf I'm making an iPhone app and I have a ton of .wav files I need to convert to .caf
I can use this for each file:
afconvert -f caff -d LEI8@22050 walking.wav walking.caf

But that would take ages, so I'm trying to convert all files with:
for i in *.wav; do afconvert -f -caff -d LEI16@44100 -c 1 $i ${i%.wav}.caf; done

But I get this error:
Error: ExtAudioFileCreateWithURL failed ('typ?')

EDIT:The error will actually occur because of a typo in the for loop shown above. It should be caff not -caff. The correct code snippet would then be.
for i in *.wav; do afconvert -f caff -d LEI16@44100 -c 1 $i ${i%.wav}.caf; done

There may be other issues and the accepted answer is valid, just wanted to help out with making the question clear. /EDIT

A: Try adding echo $i; before afconvert in your script to get the name of sound file your command fails on. Then try to convert it manually, it will probably fail too.
I suspect one of your files is not an actual wav, but is in format not recognizable by afconvert.

A: This is the script i have been using, slightly modified from another source, which kindly deserves all credit:
##
## Shell script to batch convert all files in a directory to caf sound format for iPhone
## Place this shell script a directory with sound files and run it: 'sh afconvert_wavtocaf.sh'
## Any comments to 'support@ezone.com'
##

for f in *.wav; do
if  [ "$f" != "afconvert_wavtocaf.sh" ]
then
 afconvert -f caff -d ima4 $f
 echo "$f converted"
fi
done

Save this in a file named 'afconvert_wavtocaf.sh'. See if that does the trick.


text:
Q: MongoDb fetch subset instead of whole record I have a MongoDB document structure like this:
 [
   {
      "locale":"en",
      "translations":[
         {
            "name":"translation1",
            "value":"enValue"
         },
         {
            "name":"translation2",
            "value":"enValue"
         },
         {
            "name":"translation3",
            "value":"enValue"
         }
      ]
   },
   {
      "locale":"ru",
      "translations":[
         {
            "name":"translation1",
            "value":"ruValue"
         },
         {
            "name":"translation2",
            "value":"ruValue"
         },
         {
            "name":"translation3",
            "value":"ruValue"
         }
      ]
   }
]

and I need to get the translation with name translation1 for locale en. I'm trying to do it like this: db.translations.find({"locale" : "en", "translation.name": "translation1"} ) but it returning whole locale row, with all translations instead of just translation1. I'm new to MongoDB, what I'm doing wrong?

A: you can use $elemMatch for this.
db.translations.find({"locale" : "en"},
                     { translations: { $elemMatch: { name: "translation1" } } } )

Result:
{
    "_id" : ObjectId("5e845ba1005e625a6237d2e0"),
    "translations" : [
        {
            "name" : "translation1",
            "value" : "enValue"
        }
    ]
}


text:
Q: Update some of the word embeddings I'm experimenting the code in https://github.com/dennybritz/cnn-text-classification-tf and initiallize the word embeddings with Glove. Now I would like to freeze most of the word embeddings and only train a small part. The only relevant thread I can find is Update only part of the word embedding matrix in Tensorflow
However, I still have trouble understanding how to do it properly in my case. Given something like this:
optimizer = tf.train.AdamOptimizer(1e-3)
grads_and_vars = optimizer.compute_gradients(cnn.loss)
train_op = optimizer.apply_gradients(grads_and_vars)

How do I change the indices to only train part of the embeddings in this case?
Thanks!


text:
Q: UIViewController view's frame changes after present(viewController: animated: completion: ) I have a UIViewController that I set its size in ViewDidLoad like that:
//Setting view's frame
let width = UIScreen.main.bounds.size.width - 10
let height = (43 * UIScreen.main.bounds.height) / 100 //%43 of the screen
self.view.frame = CGRect(x: 5, y: 80, width: width, height: height)

It works great until I try to present another ViewController like that:
//Presenting AutoCompleteVC
self.autocompleteVC = GMSAutocompleteViewController()
self.autocompleteVC.delegate = self
self.present(self.autocompleteVC, animated: true, completion: nil)

After I dismiss this view (self.autocompleteVC.dismiss(animated: true, completion: nil)) the frame of the first ViewController's view changes to the full screen's frame.
Any idea how to fix it?
Thanks!

A: Set your frame in viewWillLayoutSubviews. The frame is already known then. Like this:
public override func viewWillLayoutSubviews() {
    super.viewWillLayoutSubviews()

   //Setting view's frame
   let width = UIScreen.main.bounds.size.width - 10
   let height = (43 * UIScreen.main.bounds.height) / 100 //%43 of the screen
   self.view.frame = CGRect(x: 5, y: 80, width: width, height: height)
}

A: I suggest that write your code in viewWillAppear but after set frame, you should write
self.view.setNeedsLayout()
I hope this will work.

A: The main view of a view controller is positioned and sized by system logic depending on landscape/portrait, splitscreen, modal display, view controller containment...
Instead you should do every content layouting in subviews (depending on main view size) and set background color of the main view to UIColor.clear.
So in your case add a subview and configure it as you wish.
Hint: You should do it with auto layout instead of manipulating the frame.


text:
Q: Implementing PIN code security model for apps I've noticed a lot of apps, even ones that handle sensitive information like finance apps, have this security model: the user first logs in with username/password and from then on just has to enter a PIN to access the app.  I was wondering how this is usually implemented.  Is it just done by storing hashed credentials into a local database and tying them to a PIN?

A: Username/password login should be the default for authentication and authorization on a remote server. You can set up your app to log in once, get an auth token from the server, and then use this auth token to log in for subsequent visits.
As an alternative, you can ask the user to log in every time.
You should use a PIN to restrict access to the entire app, including any local data. Having said that, PINs aren't particularly secure. If you want an additional level of security, consider using an OTP.


text:
Q: Generalized Regular Polygon Area Formula to Any Number of Sides I was looking for a way to check if the regular polygon area formula of $\frac{ns^2}{4} \cot \frac{π}{n}$ where s is the side length and n is the number of sides could be extended to fractional  and irrational n. Setting s to be 1, we get the constant in exact form of the area of the polygon. This also gives the area of the unit polygon as well. I am assuming the area of the entire polygon not using the even-odd rule just like the Wolfram Alpha example.
Let this area be called $A_n=\frac{n}{4}\cot\frac{π}{n}$ Testing n=$\frac{5}{2}$, we see that the interior angle is θ=$\frac{4π}{5}$. This creates the pentagram polygon with Schläfli Symbol of $\lbrace\frac{5}{2}
\rbrace$. When putting the formula into use, $A_\frac{5}{2}=\frac{5/2}{4}\cot\frac{π}{5/2}$= $\frac{\sqrt{5}}{8}\sqrt{5-2\sqrt{5}}$, but when searching in Wolfram Mathworld, the constant came out to be A(unit pentagram or area constant of pentagram)=$\frac{\sqrt{10}}{4}\sqrt{65-29\sqrt{5}}$. Similarly, the area of a pentagon can be used in the formula to give $A_5=\frac{5}{4}\cot\frac{π}{5}$= $\frac{\sqrt{5}}{4}\sqrt{5+2\sqrt{5}}$,
In addition, one interpretation of the number of sides can also be the perimeter as we are assuming the side length is $\frac{5}{2}$ meaning that each side has a length of $\frac{1}{2}$ or less which contradicts the assumption that we can only have one side.
However, if we allow the side length to be one without any scaling of the sides as a result of the n-value, the formula still has the constant incorrect. Only when solving for the area of the $36^\circ-126^\circ-18^\circ$ triangle, do we get the value. After multiplying by $10$, the number of triangles in the shape, we get the same value as in Wolfram Mathworld. This triangle is the triangle when the shape is radially divided into ten equal triangles.
My question is what the restrictions are for the formula $A=A(n,s)=\frac{ns^2}{4}\cot \frac{π}{n}$ where n is the number of sides and s is the side length. It definitely works for $n\in\Bbb Z$ an integer assuming negative values of n would correspond to negative areas. If $n=0$, the formula is undefined as well as for any values $n= \frac{1}{m}$ where $m\in\Bbb Z$ and the formula equals $0$ when n= $\frac{2}{2m+1}$ where $m\in\Bbb Z$.
My second question is if there are restrictions for this equation, what would be a general formula only in terms of $n$ and $s$ defined in the above paragraph? This means $n,s\in\Bbb R$. How about for $n,s\in\Bbb C$? How about $n$ and $s$ in the set of all matrices with complex entries $\Bbb M$?
It seems like for a regular complex polygon, the area would be in the form of A=2n*$\frac{1}{2}$bh=nbh=nc*h where 2n is the amount of dividing triangles there are in the polygon, $\frac{1}{2}$bh is the area of these triangles, and c is the circumradius being equal to the base, denoted by b, of each triangle. This premise assumes the regular complex polygon is "filled" so that the "star" outline was filled in completely without any self-intersections affecting the area definition.
Going onto seedcode and setting the stator rotor (sr) to the number of sides and leaving only one rotor to be inside the stator rotor (sr) which is named rotor 1 (r1) to be the turning number will give a shape reminiscent of the shape with Schläfli of $$\left\{ \frac{p}{q}\right\}=\left\{ \frac{sr}{r1}\right\}=\left\{ \frac{\text{number  of sides}}{\text{turning number}}\right\}$$ Be sure to set the pen radius (r) in the app to be r1. In the app, r=r1.
Thanks to @Blue for figuring out the formula for a "filled" star polygon in terms of the circumradius and Schläfli number $$\{N\}=\text{ratio}=\left\{\frac{p}{q}\right\}$$. I also appreciate them for giving insight into the other convention. Going on the star polygon link below, gives the circumradius in terms of the ratio which then can be simplified to $\frac{1}{2} \csc\frac{π}{N}$. This can be intuitively and geometrically understood by imagining the cosecant operator in the diagram in their post. However, this assumes a unit length and therefore "area constant".
Interestingly enough, substituting this value into their formula for r and multiplying by $s^2$ for s being the side length simplified down to:
$$\text{Area}\left(\text{"filled" polygon with side length }s\text{ and Schläfli symbol }\{N\}=\left\{\frac a b\right\}\right)=A(a,b,s)=A_N (s)= \frac{a s^2\csc^2 \frac{π}{N}}{4(\cot\frac{π}{a}+\tan\frac{π}{N})}$$. Testing the pentagram we get $$A_{5/2} = \frac{\sqrt{10}}{4}\sqrt{65-29\sqrt{5}}=.31027…$$ after a few steps, the same value as in Wolfram Mathworld.
Amazingly, when putting $$N=a=\frac a1 =\frac ab$$ we get $$A_N (s)=\frac {a s^2 }4 \cot \frac πa$$ which implies the cotangent formula assuming a "filled polygon" and b=1 can only have n as an integer and n not equal to 0. Even trying a pure imaginary number such as $\{N\}=\left\{\frac i2\right \} $ with side length $i$ experimentally gets:
$$A_{\frac i2} (i)=\frac 14\tanh(\pi)\coth(2\pi)\text{csch}(2\pi)=\frac{e^{2\pi}(e^{4 \pi}+1)}{2(e^{2 \pi}+1)^3(e^{2 \pi}-1)}=.00093025…$$ after a few steps. This experimental example has the hyperbolic trig functions.
New answers for complex $n,s$ are always welcomed. Please correct me and give me feedback!
Here are some links that were used in the making of these questions:
Pentegram
Generalized Overturned Polygons
Generalized Fractional Polygons
Shläfli Symbol
Star Polygon

A: First, I'll note that not everyone agrees about terminology and/or notation in this area. My biases are informed by Branko Grünbaum (my masters thesis advisor (name-drop!)), who's responsible for introducing relatively-new conventions. (See, for instance, the Regular Star Polygons section of Wikipedia's "Regular Polygon" entry.) Be that as it may ...

It's best to think of the "regular polygon" with Schläfli symbol $\{n/k\}$ as a closed polygonal path that shares vertices with a regular $n$-gon but whose edges jump to every $k$-th one. For instance, here's $\{7/3\}$, traversing the vertices of the regular $7$-gon in the order $P_{3m}$, for $m=0, 1, 2, \ldots, 6$, (with subscripts taken modulo $7$);

For $k=1$, the regular $\{n/k\}$-gon (I'll stop typing "regular") traces the boundary of the standard, convex $n$-gon. For $n$ and $k$ co-prime, it's a self-intersecting path with no discernible "interior". Non-co-primes create a path that traces over itself multiple times (eg, a $\{6/2\}$ is a hexagonal path that wraps twice around a triangle); it may-or-may not have an "interior", or a "multiply-covered interior", or whatever, but I won't dwell on that.
Assigning an "area" to such a thing may-or-may not make sense in every context. However, the Shoelace Formula for computing the area of a polygon from the coordinates of its vertices can't tell if the path is self-intersecting, so it generates "area" calculations that, while possibly non-sensical, are at least consistent with non-self-intersecting cases; this makes it as good a definition of "area" as any.
Taking vertex $P_m$ of the host $n$-gon to have coordinates $(r\cos(2\pi m/n), r\sin(2\pi m/n))$ so that $\{n/k\}$ traces a path of the vertices $P_{km}=(r\cos(2\pi km/n), r\sin(2\pi km/n))$, the Shoelace Formula ultimately yields exactly what one gets from OP's motivating Cotangent Formula, with $n/k$ substituting for the "number of sides":
$$\text{"area"} = n\cdot\frac12\cdot r^2\sin\frac{2k\pi}{n} = \frac14 ns^2\cot\frac{\pi}{n/k} = \frac14 ns^2\cot\frac{k \pi}{n} \tag{$\star$}$$
where $s:=2r\sin(\pi k/n)$ is a segment of the polygonal path (eg, $\overline{P_0 P_3}$ in the above $\{7/3\}$).
But OP isn't interested in that. :)
Rather, OP wants a formula for the area of a "complex", "filled" polygon whose outline matches that of an $\{n/k\}$-gon. While sources (I'm looking at you, MathWorld) tend to conflate such a figure with the $\{n/k\}$-gonal path itself, I'll dub the figure the hull of the $\{n/k\}$-gon, and denote it $[n/k]$. (Here, we'll assume $n$ and $k$ are co-prime.) So, for instance, below is $[7/3]$, which is a pointy, non-convex, equilateral $14$-gon with a non-self-intersecting boundary; it is not a $7$-gon. (Generally, $[n/k]$ is a $2n$-gon.)

Calculating the hull's area is straightforward. In the $[7/3]$ example, symmetry tells us that the area is $2\cdot7$-times that of $\triangle OP_0 Q$; and that area we can compute with some angle chasing and a little help from the Law of Sines. In general, writing $r$ for the circumradius, we have ...
$$\begin{align}
\text{area of}\;[n/k] &= 2n\cdot |\triangle OP_0Q| = 2n\cdot \frac12|OP_0||OQ|\sin\angle P_0OQ \\[8pt]
&= n\cdot r\cdot \frac{r\sin\frac{\pi(n-2k)}{2n}}{\sin \frac{\pi(n+2k-2)}{2n}}\cdot\sin\frac{\pi}{n} \\[8pt]
&= n r^2 \frac{\cos\frac{k\pi}{n}\sin\frac{\pi}{n}}{\cos\frac{(k-1)\pi}{n}} \\[8pt]
&= \frac{n r^2}{\cot\dfrac{\pi}{n}+\tan\dfrac{k\pi}{n}} \tag{$\star\star$}
\end{align}$$
Expressing $(\star\star)$ in terms of the $\{n/k\}$ path's segment length (eg, $|P_0P_3|$) or the $[n/k]$ hull's side length ($|P_0 Q|$) is left as an exercise to reader.

As for OP's questions about generalizing further, say to an irrational "numbers of sides" ...
Observe that the rational case (including the good ol' integer case), the vertices of the polygon lie along a circle's circumference with central angles that are rational multiples of $\pi$. If the irrational case simply substitutes irrational central angles, then any such path bounces unendingly about the circle, with vertices arbitrarily close to any any point on the circumference. In the "$\{n/k\}$ path" sense, it has infinitely many sides and thus infinite (Shoelace) "area"; in the "$[n/k]$ hull" sense, it effectively fills the circle, for an "area" of $\pi r^2$.
Then again, there may be alternative interpretations. This may be a discussion for another time (and question). I've done enough typing. :)


text:
Q: Loading file, checking for duplicates, skipping duplicates and printing them out at the end in java I am new to Java and i need to find a way to check if an incoming file has duplicate lines, skip those lines and not load them, and then at the end print out a message saying what the duplicates were.
Please help.

A: In this case, you might need to read one line and compare with another file to line by line. Normally, you can use .equal, but you need to make sure you are reading one lie and it has been excluded change line code such as ¥n or ¥r. You had better to check the value using debugger. Better to share your code if you need further help.

A: Here's something I quickly whipped up which might help you out:
import java.util.ArrayList;
import java.io.*;

public class DuplicateChecker {

    public static void main(String[] args) {
        ArrayList<String> lines = new ArrayList<>();
        try {
            BufferedReader in = new BufferedReader(new FileReader("testfile"));
            String line_read = "";
            line_read = in.readLine();
            while(line_read != null) {
                if ( lines.contains(line_read) ) {
                    System.out.println("Duplicate found: " + line_read);
                }
                lines.add(line_read);
                line_read = in.readLine();
            }
        } catch (FileNotFoundException fnf_ex) {

        } catch (IOException io_ex) {

        }
    }
}


text:
Q: How to Get Different Response Body from Server in Android with Retrofit so I have this JSON samples here, I have three kinds of response:
{"status": "00",
 "message": "Successfully Registered!"}

{"status": "02",
 "message": "Register is failed, the data is not available"}

{"status": "03",
 "message": "Register is failed, the data already exists"}

What I want to ask here is that when I want to do POST data to the server, I want that one of the JSON lines will appear instead of the regular response code such as "200" or "400".  When I try it on the postman, the body will display one of the JSON lines above, but when I try to insert data from the android application, it shows me the regular response one. How can I get the custom code prepared by the server and display it through Toast.maketext() instead of the "Actual" response.body()?
Here is the link for my POJO class:
https://pastebin.com/xKNz3GW9
and here is the link for the method I used to POST the data;
public void registrationNewUser(Regisresponse regisresponse){
        SharedPreferences preferences = getSharedPreferences("MyPref",0);
        String tokens = preferences.getString("userToken",null);
        Call<Regisresponse> call = apiService.regisUser("Bearer " + tokens,regisresponse);
        call.enqueue(new Callback<Regisresponse>() {
            @Override
            public void onResponse(Call<Regisresponse> call, retrofit2.Response<Regisresponse> response) {
                if (response.isSuccessful()){
                    try {
                        if(response.body()!=null)
                            Toast.makeText(SignupActivity.this," response message success " + response.code(),Toast.LENGTH_SHORT).show();
                        if(response.errorBody()!=null)
                            Toast.makeText(SignupActivity.this," response message error " + response.code(),Toast.LENGTH_LONG).show();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                } else {
                    Toast.makeText(SignupActivity.this, response.errorBody().toString(), Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(Call<Regisresponse> call, Throwable t) {
                Log.e("ERROR : ", t.getMessage());
//                mProgressDialog.dismiss();
            }
        });
    }

Please kindly help me to solve this, cause I also new to handling different response like this :)) Thank you


text:
Q: In C++: Is it possible to have a named enum be continued in a different file? For example:
Base class header file has:
enum FOO
{
FOO_A,
FOO_B,
FOO_C,
FOO_USERSTART
};

Then the derived class has:
enum FOO
{
FOO_USERA=FOO_USERSTART
FOO_USERB,
FOO_USERC
};

Just to be clear on my usage it is for having an event handler where the base class has events and then derived classes can add events. The derived classes event handler would check for it's events and if the event was not for it, then it would pass the event down to the base class.
class Base
{
public:
    virtual void HandleFoo(FOO event);
};

class Derived: public Base
{
public:
    void HandleFoo(FOO event);
};

void Base::HandleFoo(FOO event)
{
     switch(event)
     {
     case FOO_A:
       /* do stuff */
     break;
     case FOO_B:
       /* do stuff */
     break;
     case FOO_B:
       /* do stuff */
     break;
     }
 }

void Derived::HandleFoo(FOO event)
{
     switch(event)
     {
     case FOO_USERA:
       /* do stuff */
     break;
     case FOO_USERB:
       /* do stuff */
     break;
     case FOO_USERB:
       /* do stuff */
     break;
     default:
          /* not my event, must be for someone else */
          Base::HandleFoo(event);
     break;
     }
 }

A: Yes, as long as the enum's are both members of a class. If they weren't then they would be of the same type and the compiler would be very unhappy.

A: No. The compiler needs to be able to decide whether the enum fits in a char, short, int or long once it sees the }.
So if the base class header has
enum Foo {
  A,
  B,
  MAX = 1<<15
};

a compiler may decide the enum fits in 16 bits. It can then use that, e.g. when laying out the base class. If you were later able to add 1<<31 to the enum, the base class enum member would not be able to hold one of the enum values.

A: Yes, this works. To simplify your code a bit, I would suggest this, more common method of "extending" enums:
enum FOO // Base class's FOO
{
FOO_A,
FOO_B,
FOO_C,
FOO_BASE_MAX // Always keep this as the last value in the base class
};

enum FOO // Derived class's FOO
{
FOO_USERA=FOO_BASE_MAX+1, // Always keep this as the first value in the derived class
FOO_USERB,
FOO_USERC
};
You still need to watch out for "out of order" enums. (Example: FOO_A=15, FOO_B=11, etc.)


text:
Q: cannot implicitly convert type 'string' to 'system.collections.arraylist' in C# Here is my code :
XmlNodeList ProjectNode = DOC.GetElementsByTagName("AppBuilderProject");

foreach (XmlNode AllNodes in ProjectNode)
{
    Project.Titel = AllNodes["Titel"].InnerText; // 1st value from node

    foreach (XmlNode controlsform in Project.Forms) // arraylist Forms
    {
        Project.Forms = controlsform["forms"].InnerText;// error
    }
}

Please tell me how to resolve this problem.

A: Property  "Project.Forms" is obviously of type arraylist and property (XmlNode).InnerText is string
Try this
if(Project.Forms == null) Project.Forms = new ArrayList();
Project.Forms.Add(controlsform["forms"].InnerText);


text:
Q: UIAlertView buttons don't work I'm using an alert view to alert the user when the internet is not connected. I have two buttons in the alert view and they both don't seem to work. I already implemented the in the .h file. I used NSLog to check whether it responds when I click. It responds in the console, but does nothing when the button is pressed. Here's a snippet of my code.
- (IBAction)startButton:(id)sender
   {
     if (![self connectedToNetwork])
     {
       UIAlertView *internetAlert = [[UIAlertView alloc] initWithTitle: @"Network Error!" message: @"You are not connected to the internet" delegate: self cancelButtonTitle: @"OK" otherButtonTitles: @"Open Settings", nil];
       [internetAlert show];
     }
   }

- (void)alertView: (UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
  {
     if (buttonIndex == 0)
     {
        NSLog(@"Ok clicked");
        HomeViewController *blah = [self.storyboard instantiateViewControllerWithIdentifier:@"HomeViewController"];
       [self.view addSubview: blah.view];
     }

     else if (buttonIndex == 1)
     {
        NSLog(@"Settings clicked");
        [[UIApplication sharedApplication] openURL: [NSURL URLWithString:@"prefs:root=WIFI"]];
     }
}

I used [self.contentView addSubview: blah.view] because I do not have a navigation controllers. Any thoughts on what I'm doing wrong

A: Here you are using wrong method for UIAlertView button clicked. you have to use another method of UIAlertView.
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex

Please change to the following code and it will work.
- (IBAction)startButton:(id)sender
{
    if (![self connectedToNetwork])
    {
        UIAlertView *internetAlert = [[UIAlertView alloc] initWithTitle: @"Network Error!" message: @"You are not connected to the internet" delegate: self cancelButtonTitle: @"OK" otherButtonTitles: @"Open Settings", nil];
        [internetAlert show];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0)
    {
        NSLog(@"Ok clicked");
        HomeViewController *blah = [self.storyboard instantiateViewControllerWithIdentifier:@"HomeViewController"];
        [self.view addSubview: blah.view];
    }

    else if (buttonIndex == 1)
    {
        NSLog(@"Settings clicked");
        [[UIApplication sharedApplication] openURL: [NSURL URLWithString:@"prefs:root=WIFI"]];
    }
}

Please let me know if you still have any questions.