Q:

Is there a "perfect" game?

Is there a historic example of a chess game that has, to date, resisted all computerized attempts to find a better sequence of moves? In other words, a "perfect" game?
CLARIFICATION
I should have made it clearer that I'm not looking for a perfect (without the quotes) game. That probably will never exist.
But is there a game that no computer has ever been able to improve as of this date?

A:

In my opinion, it's almost impossible to say that a game is perfect if you include the opening.  If you take the first few moves as a given (for example 1. e4 e5), then it is possible to say that a series of moves is perfect.
One example of a so-called perfect game is the Immortal Draw.  Carl Hamppe and Philipp Meitner played to a draw in 1872, and in the next century, no improvements have been found for the game.  It has stood up to all sorts of computer analysis and GM analysis.
Obviously the argument can be made that there is a "flaw" in the first 3 moves - maybe 1. e4 is not best, or 3. Na4 was an error, but if we ignore those 3 moves, every move starting with move 4 has held up as arguably the best move.  For instance, 7. Qe1 is often given as an option for white, but black can once again sac his queen for a perpetual check.
While there are certainly other lines that draw, the game line is the most beautiful IMHO.
[FEN ""]
[Event "Vienna 1872"]
[White "Carl Hamppe"]
[Black "Philipp Meitner"]
[Site "Vienna"]
[Result "1/2-1/2"]
[PlyCount "36"]

1. e4 e5 2. Nc3 Bc5 3. Na4 Bxf2+ 4. Kxf2 Qh4+ 5. Ke3 Qf4+ 6. Kd3 d5 7. Kc3 (7.
Qe1 Nf6 8. g3 Qg4 9. Bh3 dxe4+ 10. Kc3 Nd5+ 11. Kb3 Nc6 $1 12. Bxg4 Na5+ $11)
7... Qxe4 8. Kb3 Na6 9. a3 Qxa4+ 10. Kxa4 Nc5+ 11. Kb4 a5+ 12. Kxc5 Ne7 13.
Bb5+ Kd8 14. Bc6 (14. Nf3 $4 b6#) 14... b6+ 15. Kb5 Nxc6 16. Kxc6 (16. Ka4 Nd4
17. Qf1 Bd7+ 18. Qb5 Bxb5#) 16... Bb7+ 17. Kb5 (17. Kxb7 Kd7 18. Qg4+ Kd6 19.
Qe6+ fxe6 20. Nf3 Rhb8#) 17... Ba6+ 18. Kc6 Bb7+ 1/2-1/2

A:

To know that a game is "perfect", you have to solve the entire chess game space.
What you're really asking is whether grandmasters have played a game where a computer would have played the same moves (for both sides)? Assumptions about computer and the analysis time for the computer need to be made. I think it's possible to find such a game, but as you let the computer think longer and longer the number of results will dwindle to 0. If you limit it to only one side, you might find more games.

A:

IF we assume that chess is a theoretical draw, then any move that doesn't lose is "perfect" in the theoretical sense.
I think there have been many perfect games. Take game 2 of Anand-Carlsen:
[FEN ""]
[Event "Anand-Carlsen World Championship"]
[Site "Chennai IND"]
[Date "2013.11.10"]
[EventDate "2013.11.07"]
[Round "2"]
[Result "1/2-1/2"]
[White "Viswanathan Anand"]
[Black "Magnus Carlsen"]
[ECO "B18"]
[WhiteElo "2775"]
[BlackElo "2870"]
[PlyCount "50"]

1.e4 c6 2.d4 d5 3.Nc3 dxe4 4.Nxe4 Bf5 5.Ng3 Bg6 6.h4 h6 7.Nf3
e6 8.Ne5 Bh7 9.Bd3 Bxd3 10.Qxd3 Nd7 11.f4 Bb4+ 12.c3 Be7
13.Bd2 Ngf6 14.O-O-O O-O 15.Ne4 Nxe4 16.Qxe4 Nxe5 17.fxe5 Qd5
18.Qxd5 cxd5 19.h5 b5 20.Rh3 a5 21.Rf1 Rac8 22.Rg3 Kh7 23.Rgf3
Kg8 24.Rg3 Kh7 25.Rgf3 Kg8 1/2-1/2

I cannot believe that either player had a lost position at any moment, so no mistakes were made in the theoretical sense, so that was a perfect game.
It's similar to playing a drawn tablebase endgame position against an engine that uses the tablebase. It's usually incredibly easy to draw, because the engine doesn't care about making life hard for you. E.g., in a drawn R + pawn v R position, it will often just give away the pawn. That's not worse than other drawing moves, according to the tablebase. It's flawless chess.


Q:

Generating hex file using gcc

I have a small C function and I want to make a hex file for it.
Running
gcc -c in.c

makes an object file But I need hex file for this standalone function.
I need to put this on a separate location, so that I can simply JMP to this location from my main code. But I want this to be in hex format.
I cant do a -
gcc -c in.c -o in.hex

This is not working..
Please help me out..

A:

By using objcopy we can make hex file
gcc -c example.c

objcopy --change-address 0xE0000 -O ihex example.o example.hex

it will generate example.hex file
use Bless Hex Editor to see the .hex file clearly

A:

First you need to use the linker ld to create a raw binary binary file. Then use objcopy to create the hex file.


Q:

Ordering rows when they are not numeric

using df below, I made a table with frequencies for each unit according to each combination of group/year.
After obtaining absolute and relative frequencies, I have pasted the values into just one column Frequency
Is there a way that I can after changing the table to have the units on the rows, have them ordered in descending order based on n of the Total group in 2016? I want my final output to not have rows with n and prop, only Frequency
df <- data.frame(cbind(sample(c('Controle','Tratado'),
                              10, replace = T),
                       sample(c(2012,2016), 10, T),
                       c('A','B','A','B','C','D','D','A','F','A')))

colnames(df) <- c('Group', 'Year', 'Unit')

table <- df %>%
  group_by(Year, Group) %>%
  count(Unit) %>%
  mutate(prop = prop.table(n)) %>%
  bind_rows(df %>%
              mutate(Group ="Total") %>%
              group_by(Year, Group) %>%
              count(Unit)) %>%
  mutate(prop = prop.table(n))

is.num <- sapply(table, is.numeric)
table[is.num] <- lapply(table[is.num], round, 4)
table <- table %>%
  mutate(Frequency = paste0(n,' (', 100*prop,'%)'))

table <- table %>%
  gather(type, measurement, -Year, -Group, -Unit) %>%
  unite(year_group, Year:Group, sep = ":") %>%
  spread(year_group, measurement)

Here is what I am expecting to generate:
 Unit      type 2012:Total 2012:Tratado 2016:Controle 2016:Total 2016:Tratado
1    A Frequency 2 (66.67%)   2 (66.67%)             - 2 (28.57%)     2 (100%)
2    D Frequency          -            -       2 (40%) 2 (28.57%)            -
3    B Frequency 1 (33.33%)   1 (33.33%)       1 (20%)  1 (14.29%)           -
4    C Frequency          -            -       1 (20%)  1 (14.29%)           -
5    F Frequency          -            -       1 (20%)  1 (14.29%)            -

Notice that the results are ordered according to column 2016:Total

A:

Just found out a way myself, probably not the best one.
After running the code on the question, I have done the following:
table <- subset.data.frame(table, type == 'Frequency')

table <- table %>%
  mutate(value = substr(Total_2016, 1, nchar(Total_2016) - 7 )) %>%
  mutate(value = as.numeric(value)) %>%
  arrange(desc(value))


Q:

List the files in the directory using gwt-filesystems

I tried to list the files in my local directory as well as to read a file. But was not able to do it. Can any one give me sample code to get the list of files in a directory using gwt-filesystem.

A:

It depends from where you are reading. You can't obviously read from the client due to security issues (any HTML wouldn't let you do that). However, you could obviously read the list of files in a folder from the server side.


Q:

Is it possible to call methods from one controller on another in Codeigniter?

If I am in a "signin" controller can I execute the method get_user_info() which resides in the "user" controller? If so, what would be the syntax for that?

A:

I'm not saying this can't be done, however it really shouldn't be done.
Something like this is exactly what a library is meant for.
Create a library which handles functions such as get_user_info() and then load and call that library within whichever controllers need access to it.
You can still have a controller named user and a library named user as well (though that could get confusing).
Check out CI's guide for info on how to create a library.
*Edit*
As people have mentioned models could also serve the purpose of making functions usable in multiple places.
Personally I like to keep only business logic within models (the CRUD operations) and any logical operations which must be done in multiple places I create a library for.


Q:

Atmega8 necessary circuit for standalone working

I am developing a project to monitor solar voltage and battery voltage by displaying them on an LCD. I programmed an Atmega8 with an arduino. When I attached the LCD with the board it worked pretty well. So I detached it from board and made a breadboard circuit as described on this page.
It didn't work this time. I checked all the connections many times but could not get to any point. Kindly guide me how to make a standalone atmega8 circuit to display something on an LCD.

A:

Start slowly. There are some pitfalls when migrating to your own design (and yes, there's another forum for that). If you're using an external crystal oscillator, make sure that you've programmed the Atmel chip to use it by programming the appropriate fuse bits. After that, look to see if you can toggle a single output of the device. Ideally with a single LED connected, so you can see if the output port is changing state.
Some LCD controllers can require relatively precise timings, so if you have a logic analyser you can examine the waveforms. Otherwise, check your clock timing by turning on and off an LED every ten seconds (or so) and use a stopwatch to count ten or twenty of the LED flashes. You can see what your clock speed is working out to be, and verify that it's the right clock, etc.


Q:

Will Ubuntu 18.04 LTS still support Upstart or do we have to change to systemd?

Title pretty much says it all, I'm aware that since Ubuntu 15.04 systemd is the default service management tool, but can we still use Upstart with 18.04 if we'd like?
If we can still use Upstart with Ubuntu 18.04, has Canonical announced a specific release where Upstart won't work any longer, or are we on our own to try and use Upstart with current/future Ubuntu versions until it doesn't work in a particular case?
Will Ubuntu 18.04 ship with Upstart in addition to systemd, or do we have to install Upstart separately?
Before somebody marks this as a duplicate, I realize this post:
Upstart or Systemd
states that Upstart was used through 14.10 and that now systemd is the default, but my question is can we still use Upstart with 18.04 even if it's not the default.

A:

Since Ubuntu 17.10 Ubuntu has dropped support for the Upstart init daemon in the default Ubuntu repositories. The latest version at http://upstart.ubuntu.com/, Upstart 1.13.2, was released on September 4, 2014.


Q:

How do I make spicy mayonnaise like Japanese restaurants use for sushi?

I've tried mixing mayonnaise and hot sauce together and it didn't taste right at all. Any Suggestions?

A:

Japanese spicy mayo is made with Kewpie mayo and Shichimi tōgarashi. You really just mix them to taste.

A:

You can also use regular mayo and sriricha hot sauce.  Ain't authentic, but it's a lot easier to come by, for the most part.


Q:

Strategies for reading in CSV files in pieces?

I have a moderate-sized file (4GB CSV) on a computer that doesn't have sufficient RAM to read it in (8GB on 64-bit Windows).  In the past I would just have loaded it up on a cluster node and read it in, but my new cluster seems to arbitrarily limit processes to 4GB of RAM (despite the hardware having 16GB per machine),  so I need a short-term fix.
Is there a way to read in part of a CSV file into R to fit available memory limitations?  That way I could read in a third of the file at a time, subset it down to the rows and columns I need, and then read in the next third?
Thanks to commenters for pointing out that I can potentially read in the whole file using some big memory tricks:
Quickly reading very large tables as dataframes in R
I can think of some other workarounds (e.g. open in a good text editor, lop off 2/3 of the observations, then load in R), but I'd rather avoid them if possible.
So reading it in pieces still seems like the best way to go for now.

A:

After reviewing this thread I noticed a conspicuous solution to this problem was not mentioned.  Use connections!
1) Open a connection to your file
con = file("file.csv", "r")

2) Read in chunks of code with read.csv
read.csv(con, nrows="CHUNK SIZE",...)

Side note: defining colClasses will greatly speed things up.  Make sure to define unwanted columns as NULL.
3) Do what ever you need to do
4) Repeat.
5) Close the connection
close(con)

The advantage of this approach is connections.  If you omit this step, it will likely slow things down a bit.  By opening a connection manually, you essentially open the data set and do not close it until you call the close function.  This means that as you loop through the data set you will never lose your place.  Imagine that you have a data set with 1e7 rows.  Also imagine that you want to load a chunk of 1e5 rows at a time.  Since we open the connection we get the first 1e5 rows by running read.csv(con, nrow=1e5,...), then to get the second chunk we run read.csv(con, nrow=1e5,...) as well, and so on....
If we did not use the connections we would get the first chunk the same way, read.csv("file.csv", nrow=1e5,...), however for the next chunk we would need to read.csv("file.csv", skip = 1e5, nrow=2e5,...). Clearly this is inefficient.  We are have to find the 1e5+1 row all over again, despite the fact that we just read in the 1e5 row.
Finally, data.table::fread is great.  But you can not pass it connections.  So this approach does not work.
I hope this helps someone.
UPDATE
People keep upvoting this post so I thought I would add one more brief thought.  The new readr::read_csv, like read.csv, can be passed connections.  However, it is advertised as being roughly 10x faster.

A:

You could read it into a database using RSQLite, say, and then use an sql statement to get a portion.
If you need only a single portion then read.csv.sql in the sqldf package will read the data into an sqlite database.  First, it creates the database for you and the data does not go through R so limitations of R won't apply (which is primarily RAM in this scenario). Second, after loading the data into the database , sqldf reads the output of a specified sql statement into R and finally destroys the database.  Depending on how fast it works with your data you might be able to just repeat the whole process for each portion if you have several.
Only one line of code accomplishes all three steps, so it's a no-brainer to just try it.
DF <- read.csv.sql("myfile.csv", sql=..., ...other args...)

See ?read.csv.sql and ?sqldf  and also the sqldf home page.


Q:

Possible to create JavaFX Application object?

Would it be possible to make an Application object from javaFX?
public class Constructor
{
    public Constructor()
    {
        Application a = new Application()
        {
            @Override
            public void start(Stage window) throws Exception
            {

            }
        };
        a.launch();
    }
}

It currently gives me this when I try to run it:

Exception in thread "main" java.lang.RuntimeException: Error: class net.whiteautumn.lightcast.Constructor is not a subclass of javafx.application.Application

This, I presume, is caused by the class Constructor not extending Application.
Any way of getting around this or is that the only way to ever launch JavaFX applications?
EDIT:
I know how to start a javaFX application. What I want to to make an application and have it in an object. Is this possible or no?

A:

Application.launch() is a static method, therefore a.launch() is equivalent to Application.launch(). This means that it will try to launch an application of the class that calls it, which is Constructor class.
The correct way to do it is:
private static class MyApp extends Application
{
    @Override
    public void start(Stage window) throws Exception
    {

    }
};

Application.launch(MyApp.class, null);


Q:

Compute $ \lim\limits_{n \to \infty}\frac{\sqrt{3n^2+n-1}}{n+\sqrt{n^2-1}}$

Compute $$ \lim\limits_{n \to \infty}\frac{\sqrt{3n^2+n-1}}{n+\sqrt{n^2-1}}$$

I did the following:
$$ \lim\limits_{n \to \infty}\frac{\sqrt{\frac{3n^2}{n^2}+\frac{n}{n^2}-\frac{1}{n^2}}}{\frac{n}{n^2}+\sqrt{\frac{n^2}{n^2}-\frac{1}{n^2}}} = \frac{\sqrt{3}}{\sqrt{1}}=\sqrt3$$
However, the correct answer is different. Why am I wrong?
Thank you for your help.

A:

By dividing the numerator and the denominator by $n$, you should have
$$\frac{\sqrt{\frac{3n^2}{n^2}+\frac{n}{n^2}-\frac{1}{n^2}}}{\frac{n}{n}+\sqrt{\frac{n^2}{n^2}-\frac{1}{n^2}}}=\frac{\sqrt{3+\frac{1}{n}-\frac{1}{n^2}}}{1+\sqrt{1-\frac{1}{n^2}}}.$$
Instead at your denominator we have $\frac{n}{n^2}+\sqrt{\frac{n^2}{n^2}-\frac{1}{n^2}}$.
Then what is the final limit?

A:

Discarding the low order terms (which become negligible when $n$ grows), the expression has the same limit as
$$\frac{\sqrt3 n}{n+n}.$$


Q:

Output power of the Raspberry Pi Transmitter

I have figured out how use the Raspberry Pi to transmit FM Radio, but I also know that this is illegal.
All transmitters over 500mW required a licence.
What is the output power of the Raspberry Pi (in mW)?
It uses one of his GPIO pins to generate the Radio waves (More specific: The clock generator can generate square waves and now I am using this to 'send' in radio frequencies using some script downloaded on the internet)

A:

If we approximate that the dirty square wave coming from the GPIO pin, is a sinewave, and at the same time assume the antenna is directly driven. Well, then as @joan said. The GPIO maximum current draw is 16 mA. So the formula can be approximated to be:
Pavg = Vrms * Imax = (Vpp/Sqrt[2]) * Imax = 3.3 * 0.707 * 0.016 = 0.037 W = 37 mW
But at the end of the day, how much transmitted power you really get on the air (TPO) depends on your antenna and how well the impedance is matched etc. So the fact that this works at all is rather amazing...but then again, almost anything can act like an antenna. Just horribly inefficient, as you can see below.
Here's a picture from a video on the power spectrum from the Pi Wire.

Here you see how it is radiating all over the place, all the way up into GHz. Thus the actual energy transmitted to the exact frequency you want, is extremely small. (Which is why you don't need to listen that much to all those trolls preaching about the FCC rules.)


Q:

How to open new tab by write some text?

I was looking for some information about how to open link by writing exact word, in my case it will be "film". I want to open new link by writing on  website in input elemtent word - "film".
Can you give me some hints?
Thank you,
Megi

A:

You can use the onInput or also use onkeyup Event to open a new tab with window.open
<!DOCTYPE html>
<html>
<body>

Enter keyword: <input id="keywordinput" type="text" value="notfilm" oninput="checkForFilm()">

<script>
function checkForFilm()
{
    if(document.getElementById('keywordinput').value == 'film')
    {
      var win = window.open('http://stackoverflow.com/', '_blank');
      if (win)
      {
          win.focus();
      }
      else
      {
          alert('Please allow popups for this website');
      }
    }
}
</script>

</body>
</html>


Q:

Longest element of Weyl Group for $G_2$

Let $\mathfrak{g}$ be a semisimple Lie Algebra, $\mathfrak{t}$ a Cartan Subalgebra, $\Phi$ the  corresponding set of roots, $\Delta \subset \Phi$ a root basis and $W$ the Weyl Group with respect to $\Delta$
I am having trouble finding the longest element of the Weyl Group $w_0$ as a product of the simple reflections $w_\alpha \in W$ in the case of $G_2$.
Here are my thoughts:
Taking $\Delta = \{\alpha, \beta\}$ where in the drawing of $G_2$ (that takes the shape of the star of david), the upper-left corner is $\beta$ and the point to the right of $0$ is $\alpha$.
Then this indeed qualifies as a root basis, and using the fact that for $G_2%$ we have $W \cong D_{12}$ (a quoted result from earlier in my course), then:
Letting $w_\alpha = s \in D_{12}$, we see that $w_\beta = r^2s$ where $r$ is a clockwise rotation by $\frac{\pi}{3}$.
Further, we may note that $w_0$ must send $\Delta$ to $-\Delta$ and so $w_0 = w_\alpha w_{3\alpha + 2\beta}$
But, continuing to identify $W$ with $D_{12}$, we find that $w_{3\alpha+2\beta} = r^3s$ which cannot be generated by $s, r^2s$ which seems to imply that $W$ is not generated by the simple reflections.
Clearly something has gone wrong here, and I am really struggling to find what that might be.

A:

While Travis' answer gives a nice hands-on calculation, I like to point out two answers to related questions which put things in perspective:
Anton Geraschenko's answer here states, among other things, that the longest element in most simple types (actually, all except $A_{n \ge 2}, D_{2n+1}$ and $E_6$) is just $-id$. So this is also the case here, $w_0$ must be multiplication with $-1$ (which, since we are in two dimensions, is the same as rotating by $\pi$).
Allen Knutson's answer here on MathOverflow gives a nice general method to express $w_0$  as product of simple reflections. In the case of type $G_2$, we can choose $w=w_\alpha, b=w_\beta$, and the Coxeter number for type $G_2$ is $h=6$, so the general formula there gives $w_0 =(w_\alpha w_\beta)^{h/2} = (w_\alpha w_\beta)^{3}$. Switching the roles of $w$ and $b$, which is allowed, gives alternatively $w_0=(w_\beta w_\alpha)^{3}$, as in the other answer.


Q:

Terminal: Adding logic to 'find' directories containing either [criteria A] or [criteria B]

I have inherited a vast media archive without a unifying organizational scheme. Its contents date back at least 10 years. I have been asked to find a needle in this hay stack, and I have some guesses as to that needle's name. But I don't know its name for certain. I want to use a single find command in the Terminal to search for alternate names. And I want to include a second set: possible file extensions. In pseudocode, here's what I mean: find [in a given directory] [files and folders whose name matches (*guess1* OR *guess2*) AND whose name matches (*.extension1 OR *.extension2)]. How should I express this in the Terminal?

A:

You can do this using ls and grep with regular expressions
ls | grep -E "(guess1|guess2)(\.extension1|\.extension2)"

Or if you need to recursively look into folders:
ls -R | grep -E "(guess1|guess2)(\.extension1|\.extension2)"


Q:

Array operation; Fortran equivalent of (:)

I am converting from Fortran to C++ . In Fortran on a 2D array ie A(1000,3) i can do the following:
A(1,:)=(x0,y0,z0)

I have searched online and haven't found anything close to that for C++ so I can vectorize some operations. Any help would be appreciated.

A:

The C++ language does not include a built-in matrix type, but includes all the tools you need to build one. Fortunately, that does not mean you need to go and build one all by yourself. Indeed, that would be a bit like reinventing the wheel.
I suggest you rely on one of the existing C++ open source matrix/vector packages, rather than defining ad hoc types manually. One possibility consists of using the Armadillo library.
Armadillo Wikipedia article
Armadillo online documentation
What you want to do can be done like this:
A.row(0) = rowvec{x0, y0, z0};
Example of self-contained source code below:
#include  <armadillo>
#include  <iostream>

using  arma::Mat;
using  arma::vec;
using  arma::rowvec;
using  arma::colvec;

int main(int argc, const char* argv[])
{
    Mat<double>     A = Mat<double>(1000, 3, arma::fill::zeros);

    std::cout << "Shape of matrix A: " <<
                 A.n_rows << "x" << A.n_cols << std::endl;

    double  x0 = 1.5;
    double  y0 = 2.5;
    double  z0 = 3.5;

    A.row(0) = rowvec{x0, y0, z0};  // HERE

    std::cout << "  A(0,0)=" << A(0,0) << "  A(0,1)=" << A(0,1)
              << "  A(0,2)=" << A(0,2)  << std::endl;

    std::cout << "  A(1,0)=" << A(1,0) << "  A(1,1)=" << A(1,1)
              << "  A(1,2)=" << A(1,2)  << std::endl;

    return 0;
}

The specialized libraries go much further than this. For example, you can write a matrix product just like P=A*B, and the library will gracefully call the appropriate highly optimized BLAS/LAPACK backend routines for you. You can remain blissfully ignorant of the sad facts that the backend is Fortran-based and thus insists on numbering array elements from 1 not 0, and also insists on storing 2-dimensional arrays in contiguous columns, unlike C/C++ which prefers contiguous rows.
Of course it will take some time to learn about one the existing libraries, but it is unfortunately possible that writing/debugging your own type system will take even more time.
Alternatively, if you insist on designing/using your own C++ linear algebra package, you could do worse than getting a copy of this book:
 "The C++ Programming Language, 4th edition"
by Bjarne Stroustrup, ISBN 978-0321-563842.
As you probably know, the C++ initial design effort, and a good chunk of the subsequent language evolution was led by this author. The 4th edition of his book includes a chapter 29 (taking only 30  pages) whose title is: "A matrix design". Chapter 29 makes extensive use of "advanced" features of C++11 such as template types and operator overloading.
Regarding elementary C++ types:
Using an array of std::arrays assume that you know the size of your matrix at compile time. This is a restriction that was fortunately removed from modern versions of Fortran.
Using a vector of vector would allocate the memory space of the matrix as N separate areas, and that would be both less time-efficient and incompatible with BLAS/LAPACK backend libraries.


Q:

How to get typed values of the combobox from keylistener

How to get the typed values of the editable combobox in keypressed event? Please help me out. Please find my code:
comboInstrument.getEditor().getEditorComponent().addKeyListener(new KeyListener() {

    public void keyReleased(KeyEvent e) {
        System.out.println(comboInstrument.getSelectedItem().toString());
    }

    public void keyTyped(KeyEvent e) {
        // TODO Auto-generated method stub
    }

    public void keyPressed(KeyEvent e) {
        // TODO Auto-generated method stub
    }

});

A:

I can able to get the typed key values through the following code. getSelectedItem is retrieving only the previous value selected and not the newly typed one. Thanks for ur responses friends.
comboInstrument.getEditor().getItem().toString();


Q:

Tension in strings which accelerate 3 masses

This is a seemingly simple undergraduate problem that I cannot understand with my background (I have studied pure mathematics. now laugh freely).
Suppose three masses $M_1>M_2>M_3 $  lie in rest on a frictionless plane. THe masses are tied with a single rope in a row, like $M_3--M_2--M_1--$.
 The rope is pulled at its free end by a force $F$. What is the acceleration of every mass? What are the tension of the pieces of rope between $M_1$ and $M_2$, and $M_2$ and $M_3$?
So I know that $F=(M_1+M_2+M_3)a$ where $a=a_1+a_2+a_3$ is the acceleration of the system.
For the mass $M_1$, the forces are... $F$ and $T1$, right? So for $M_1$, the acceleration $a_1$ satisfies $M_1 a_1=F-T_1$.
Is this right?
How do I formulate the equation for $M_2,M_3$?
And what good is the equation $a=a_1+a_2+a_3$? Or perhaps I can use this as $F/(\sum M_i)$?

A:

First of all, in this kind of problems is essential to specify what our mechanical system is, so we can distinguish between external and internal forces. This way we can apply Newton's laws without confusion.
Let me consider the three masses plus the rope as our system, so an external agent is applying a force $F$ upon it, producing two tensions (internal forces): $T_{32}$ between $M_3$ and $M_2$ and $T_{21}$ between $M_2$ and $M_1$, according to your drawing. The total mass of the system is indeed the sum of the three of them, assuming the rope is massless. Applying Newton's Second Law about some horizontal axis give us:
\begin{equation}
F = (M_1+M_2+M_3)a_{s} ,
\end{equation}
where $a_{s}$ is the system's acceleration. Here is something important to clarify about your reasoning: the system's acceleration is not the sum of the individual accelerations. In fact, after $F$ is transmitted through the rope, the objects acquire the same acceleration despite the different masses. An intuitive way to think about this is to suppose the accelerations are $\textbf{not}$ equal. In this scenario the rope would bend, so tension would not act anymore and the objects would crash, and this of course doesn't happen.
Getting back to the problem, the accelerations are:
\begin{equation}
a_s=a_1=a_2=a_3=\frac{F}{M_1+M_2+M_3}.
\end{equation}
Now we can apply Newton's Second Law to every mass individually, but instead of doing Free Body diagrams and stuff, let's do it in an intuitive way; developing intuition in Physics is much more valuable. If we remove $M_3$ from the system that you drew, we note that the rope would have another free end, but this one would fall to the ground, and
applying the force $F$ at the other end would not disturb this end at all in that sense, physically meaning that tension is zero in that chunk of rope. This way, $T_{32}$ is only dependent upon $M_3$, and we get the equation:
\begin{align}
T_{32}&=M_3 a_s \\
      &=\frac{M_3}{M_1+M_2+M_3}F.
\end{align}
Applying the same reasoning for $T_{21}$, we note that removing $M_3$ and $M_2$ from the system will make this chunk of rope hit the ground, and $F$ won't tense it. This way, $T_{21}$ only depends upon the masses $M_3$ and $M_2$, so we obtain:
\begin{align}
T_{21}&=(M_3+M_2)a_s \\
      &=\frac{M_3+M_2}{M_1+M_2+M_3}F.
\end{align}
Note: Of course you can also analyze the forces acting upon every individual mass and solve for the tensions. This way, the equation $M_1 a_1 = F-T_1$ that you point out is correct.


Q:

Why did Captain Phasma play such a small part in The Force Awakens?

Prior to The Force Awakens' release, Captain Phasma was really hyped, and many of the creators seemed to really like the character.

I can only say that Gwendoline Christie is my favorite. She just killed it. You think, "Well, what? It’s wearing a costume." But it’s a lot to wear and to have a performance when you’re wearing that requires a different kind of skill set and an additional talent, and she’s got it. It’s an incredible thing to work with her. I am glad that a character has been designed that is visually as stunning as that is, because she deserves it and the fans do to. When I first saw that design my mind was blown because it looked so undeniable. -J.J. Abrams
She's an important character, a baddie in the best sense of the word. -Kathleen Kennedy

Despite this, the she plays only a minor part in the film. She actually has more lines in a Disney XD LEGO short than in The Force Awakens.
If the creators liked Phasma so much, why was she given such a small role?

A:

JJ Abrams left a lot on the cutting room floor. One of them was an extra scene with Phasma

There was actually a fun thing with Captain Phasma ordering all of the ships into the air, but they didn’t realize that Han and Finn had just thrown her down a garbage chute.

Remember, this movie had to balance the original trilogy and the new story. So it's not necessarily that she didn't get a lot of screen time, it's more likely that she had little to do in this movie (Princess Leia, a much more central character, had several scenes cut). Something tells me she'll appear more in the next few movies (she's been very hyped for an otherwise tertiary character).


Q:

Why are there more vertical takeoff than horizontal for spacecrafts?

Vertical takeoff requires disposable rockets (would it a satellite rocket), which is a money loss, and also a lot of fuel, because initial velocity is zero. Also vertical takeoff seems risky, involves huge pieces of equipments, launch pads, to diminish risk.
Horizontal takeoff are done with a reusable aircraft, like a modified 747. Initial velocity not being zero, there are much less risk, and the fuel spent in a 747 is much less expensive than a disposable rocket.
So, Why are there more vertical takeoff than horizontal for spacecrafts?

A:

A 747 - can get you to around 35,000 feet. Still very much within the atmosphere.
So what do you do then? Launching a rocket from that point still requires an awful lot of kit, so while you have reduced your propellant requirements a little, the 747 still has to carry a launch platform, so you're not really getting anything out of this.
New technologies, such as that used by Virgin Galactic is managing to make this work, hopefully, with a hybrid model that does fly up to around 50,000 feet before launching the spacecraft section, but this is very new.

So the simple answer is - it used to require vertical rocket launches, and all the associated paraphernalia, but modern technology is moving towards fully reusable methods such as this.

A:

A 747 moves at approximately 1,000 km/h, a satellite in orbit travels at 28,000 km/h. So, after your rocket is released from the 747 it still needs enough fuel to accelerate a further 27,000km/h. That requires a lot more fuel than the 747 is capable of carrying. Remember that the shuttle lift-off weight is about 2,000 tons - far more than the 747 can carry.
In addition, you need to get above the atmosphere. Going 28,000 km/h at 10,000 m will burn up any spacecraft, so you need to get up very high before you start going at extreme speeds.
It is possible to reach orbit after horizontal take-off, but we're not there yet

A:

Any system that has enough ISP to get itself out of the atmosphere has enough ISP to not need wings for lift. Thus, vertical takeoff. See this related question for a discussion of why the ISP of jet engines is so much lower than for rocket engines.
Note also that just a few weeks ago NusSTAR was launched from a Pegasus rocket on a modified 747. This is a relatively lightweight cargo and thus was fit for what the 747 could carry.


Q:

Doubts on some words in a Deng Lijun song

I just listened to the song 无奈 by Deng Lijun, and there are three points where what I hear doesn't match the lyrics I have:

At the end of the sentence at 1:30-1:37, my lyrics have 痴情 | chïqíng, but I hear either qiqi or qiqing;
The 仍藏心底 | réng cáng xïn dî at 2:59-3:01 sounds to me like ying can xin di;
The 选择 | xuânzé in the sentence at 3:14-3:18 and 3:27-3:31 sounds like suanjia to me, and given that shortly before we have a 选择 which actually sounds like xuanze I am fairly certain it must be another word.

Is that all just me mishearing or am I on to something?
Also, another video of the song has 00:41-00:47 captioned as 看着你一脸惘然 眼眶是泪滴, my lyrics have 看着你一脸茫然 眼眶是泪滴, and I'm not sure if I hear mangran or mengran. Can you confirm my lyrics have it right? Is 一脸茫然 a chengyu?

A:

Here are my conclusions:

The 痴情 is supposed to be 戚戚 | qi1qi1, as suggested here;
The 仍藏心底 is supposed to be 隐藏心底 | yin3cang2 xin1 di3, as suggested here;
The 选择 at the end is supposed to be 三角 | san1jiao4, as suggested here;
The 惘然 is supposed to be 茫然; I only draw this conclusion because it seems to me "blank" fits the context better than "suddenly", since "your face is blank and there is tears in your eyes" is what would result from 茫然, whereas with 猛然 you would have "on the whole face" (一脸) and "the eyes" (眼眶), two contradictory complements of place.

The three "here"s above all link to the same link provided in Jason Swift's comment.


Q:

Using eclipse with Java and C

I mostly use Java for programming and I used Eclipse as an (IDE). Now, I would like to  add CDT to use c to program network sockets. I followed the steps here
i.e., first I downloaded Xcode, then added the plug in  "C/C++ Development Tools"
I don't know how to create a c project, when I clicked on  File > New > Project, there is no option to choose c/c++ project.
I also, tried the suggested solution, but the problem still occurs
I'm using mac OS X Yosemite.
Is there something I'm missing?
Thanks

A:

The problem was solved when I reinstall CDT with all relative packages, i.e. I installed everything that starts with C/C++.


Q:

Error trying to push a build to a first gen iPod running os 3.1.3 using SDK 4

I just upgraded to iPhone SDK 4, I was building to the iPod running OS 3.1.3 fine untill i ugraded the SDK. When I try to build now I get the following error:
Can't run 'AppName' - was built for 'armv7', but device requires 'armv6' or compatible architecture.
In the project settings I have set the Architectures to Standard (armv7 armv6), and set the Base SDK to iPhone Device 4.0. I also set the iPhone OS Deployment Target to iPhone OS 3.1.3.
Any ideas what might be going wrong on me?

A:

Fixed it. I changed the project settings but also had to change the active target settings.
This is done in Project -> Edit Active Target "appName". I just had to switch the Architecture from optimised to standard.


Q:

Font Changing to Inherited Font on Screensize Change

I'm attempting to make a simple site mobile responsive using "@media only screen", but one of my titles is reverting to an inherited font rather than continuing to use the CSS defined font.
//HTML
<head>
<meta name="viewport" content="width=device-width; initial-scale=1.0;">
<link rel="stylesheet" href="squirrelcss.css"  type="text/css">
<link href="https://fonts.googleapis.com/css?
family=Open+Sans:400,400i,700|Pacifico" rel="stylesheet">
</head>

<body>
<h4> Short Title </h4>
</body>

//CSS
[class*="h4"]{
font-size: 5vw;
}

@media only screen and (min-width: 800px){
h4{
font-family: 'Pacifico', cursive;
font-size: 2vw;
color:#474644;
margin-left: auto;
margin-right: auto;
margin-top: 0;
margin-bottom: 0;}}

On Inspect mode in Google Chrome, it indicates that upon a smaller screen size, h4 is inheriting it's font from it's container element, col-8.
.col-8{
font-family:'Open Sans', sans-serif;
}

Every other element on the site is correctly changing when the screen size is lowered below the defined 800px, including other text, and I've repeatedly cleared my cache throughout the process to no avail. !important seems to have no effect either.
What can I do to cause the h4 element to keep displaying the 'Pacifico' font instead of the inherited font?

A:

What can I do to cause the h4 element to keep displaying the 'Pacifico' font instead of the inherited font?
Just set font-family: 'Pacifico', cursive; to your h4 element outside of the @media statement. This way no matter the size of your page, Pacifico (as long as it has loaded) will be the font.
//HTML
  <head>
    <meta name="viewport" content="width=device-width; initial-scale=1.0;">
    <link rel="stylesheet" href="squirrelcss.css"  type="text/css">
    <link href="https://fonts.googleapis.com/css?
    family=Open+Sans:400,400i,700|Pacifico" rel="stylesheet">
    </head>

    <body>
    <div class="col-8">
    <h4> Short Title </h4>
    </div>
    </body>

//CSS
 h4{
    font-family: 'Pacifico', cursive;
    }

    .col-8{
    font-family:'Open Sans', sans-serif;
    }

    @media only screen and (min-width: 800px){
    h4{
    font-size: 2vw;
    color:#474644;
    margin-left: auto;
    margin-right: auto;
    margin-top: 0;
    margin-bottom: 0;}}


Q:

Trigger an exe once My device is connected via USB

Once my embedded device is connected to USB port of my PC, it should trigger an exe as an event. How can I achieve this??
Should I create a service to keep monitoring the USB connector bus or is there any default API's available in Windows to achieve this??
thanks.

A:

A simple exe which is started on connect is not possible. But you can write a service or user mode application which listens for device arrival events. WM_DEVICECHANGE is sent to all (registered) applications with a device interface guid which represents which device is plugged in. You can then use this id with the setupapi to see if its your device.
On receiving that event, you can then start your executable.


Q:

Is there anything like Ring of Arming in 5e?

I can't seem to find anything like 3.5e's Ring of Arming (equips/unequips items as a standard action on activation), which is quite useful.
Is there a similar item in 5e or am I doomed to get caught without my heavy armor one of these days?

A:

It doesn't have to be in a book
I think you're missing the spirit of magic items in 5th edition.  (or even 3rd, or pathfinder).  Just because it's not written down in a book, doesn't mean it doesn't or can't exist.  If you are interested in such an item, it's up to you and your GM to devise a way to acquire such an item.
What is different in 5th from previous versions is the idea that you can just amass gold and there will be one of these items magically available for purchase at the local magic shop.  5th edition tries to keep magical items a bit less frequent, and more wondrous and cool when you do find one.  The chance that you could just purchase anything outside of spell scrolls or healing potions is reduced significantly.


Q:

Unable to draw Spline on secondary Y Axis (getting data from CSV file) using highchart

I am new to Highcharts and trying to draw a graph by reading a CSV File. when i extract and try to display i see that the values of the Y Axis are dots on one line (Vertical) instead of a horizontal Line.
Please tell me how to convert it to secondary X-Axis.
My Entire Code:
data.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
         <title>Performance Dashboard</title>

            TIERS PERFORMANCE DASHBOARD

Home Page

CPU Utilization

and timeData.csv
Time,users,AverageSec,Volume
8:00,2325,0.627,28821
7:55,1529,0.609,19124
7:50,1095,0.544,15825
7:45,865,0.584,12852
7:40,709,0.573,10263
7:35,554,0.605,8149
7:30,427,0.641,5821

Please need help and its greatly appreciated!!!
Thanks a lot in advance.

A:

Is this what you want? Fiddle: http://jsfiddle.net/Yrygy/84/
I have created three axis, each for one column in your data, where first column is category - time. First create series, otherwise you will create series for each line (you already doing this). After series are created push items from a line to specifc series, and in laste step, before creating chart - push series to options.
var data = 'Time,users,AverageSec,Volume\n8:00,2325,0.627,28821\n7:55,1529,0.609,19124\n7:50,1095,0.544,15825';
// Split the lines
var lines = data.split('\n');
var series = {
    data: []
};
var series1 = {
    yAxis: 1,
    data: [],
    type: 'spline'
};
var series2 = {
    yAxis: 2,
    data: []
};
$.each(lines, function (lineNo, line) {
    var items = line.split(',');

    // header line contains names
    if (lineNo == 0) {
        series1.name = items[1];
        series.name = items[2];
        series2.name = items[3];
        /*$.each(items, function (itemNo, item) {
            if (itemNo > 0)
                series.name = item;
        });*/
    }

    // the rest of the lines contain data with their name in the first position
    else {
        $.each(items, function (itemNo, item) {
            // first item on line - category/time
            if (itemNo == 0) {
                options.xAxis.categories.push(item);
            } else if (itemNo == 1) {
                series1.data.push(parseFloat(item));
            } else if(itemNo == 2){
                series.data.push(parseFloat(item));
            } else if(itemNo == 3){
                series2.data.push(parseFloat(item));
            }
        });

    }
});

    options.series.push(series);
    options.series.push(series1);
    options.series.push(series2);
var chart = new Highcharts.Chart(options);


Q:

Stacks like display:block, but retains width of text inside - is this possible?

I'm trying to create a navigation list where all the list items stack on top of one another, as per display:block, but where their width is influenced by the width of the text within them, as per display:inline.
It seems like I can only choose one or the other - I've tried setting the li and li a to various combinations of block/inline/inline-block and it's not working. Either my list items are all the same width, or they're sitting next to each other instead of on top of one another.
Here's what I'm trying to achieve and can't:
http://i39.tinypic.com/280t5s0.png
Is this possible to do? I feel like it really should be but am completely stumped and searching hasn't turned up much.
Any help would be much appreciated!
Thanks and best wishes,
Emma

A:

HTML

Item 1

Long Item 2

Longer Item 3

Item 4

Item 5

CSS
li {
    border: 1px solid black;
    display: inline-block;
    float: right;
    clear: right;
}

See it live


Q:

Aggregating R^2s in R

I am an R newbie.  This is my first question.  I have a dataset containing 1) all US zip codes, 2) unique count of sales transactions, and 3) the sum of sales transactions.  Is there a way to obtain the coefficient of determination (R^2) for every zip code using Count of Sales and Sum of Sales Transactions as my x and y variables, respectively?  Specifically, I am looking to create a table with R^2s for every US zip code using the two variables mentioned.

A:

You can do this with the purrr package.
Here is an example with mtcars:
library(purrr)

mtcars %>%
  split(.$cyl) %>%
  map(~ lm(mpg ~ wt, data = .x)) %>%
  map(summary) %>%
  map_dbl("r.squared") %>%
  data.frame(cyl = names(.), r2 = ., row.names = NULL)

         r2 cyl
1 0.5086326   4
2 0.4645102   6
3 0.4229655   8

And here is the flow for your problem, everything in "quotes" needs to be changed in your variables or dataframe, except for the "r.squared".
df <- "your dataframe" %>%
  split(.$"zipcode") %>%
  map(~ lm("sum of sales" ~ "count of sales", data = .x)) %>%
  map(summary) %>%
  map_dbl("r.squared") %>%
  data.frame(zipcode = names(.), r2 = ., row.names = NULL)


Q:

Костровый или костровой?

Знаю, что в походах человек, отвечающий за разведение и поддержание костра, называется "костровой". А вот как быть, если речь идет, например, о чайнике? Чайник будет тоже костровой или все-таки костровый?
Спасибо

A:

Слову "костер" соответствуют два относительных прилагательных: кострОвый и менее употребительное слово "костёрный".
Соответственно, чайник кострОвый.
В то же время существует существительное мужского рода "костровОй" - тот, кто поддерживает костёр. Назначить костровым.


Q:

Can I set up a template in Xamarin Forms for Xaml that's repetitive?

I use the same XAML many times in my application with two minor differences which are the value of the Text and Selected that I pass in:
<ViewCell Tapped="selectValue" >
   <Grid VerticalOptions="CenterAndExpand" Padding="20,0" >
      <local:StyledLabel Text="{Binding [1].Name}" HorizontalOptions="StartAndExpand" />
      <local:StyledLabel IsVisible="{Binding [1].IsSelected}" TextColor="Gray" HorizontalOptions="End" Text="✓" />
   </Grid>
</ViewCell>

Does Xamarin forms have any template feature where I could for example shorten this to something like:
<local:SwitchViewCell Text="{Binding [1].Name}" Selected="{Binding [1].IsSelected}" />

Here's what I have so far:
<?xml version="1.0" encoding="utf-8" ?>
<ViewCell xmlns="http://xamarin.com/schemas/2014/forms"
          xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
          mlns:local="clr-namespace:Japanese;assembly=Japanese"
          x:Class="Japanese.SwitchViewCell""
          Tapped="selectValue" >
   <Grid VerticalOptions="CenterAndExpand" Padding="20,0" >
      <local:StyledLabel Text="{Binding Text, Source={x:Reference this}}" HorizontalOptions="StartAndExpand" />
      <local:StyledLabel IsVisible="{Binding IsVisible, Source={x:Reference this}}" TextColor="Gray" HorizontalOptions="End" Text="✓" />
   </Grid>
</ViewCell>

With this code behind right now:
namespace Japanese.Templates
{
    public partial class SwitchViewCell : ViewCell
    {
        public SwitchViewCell()
        {
            InitializeComponent();
        }

        public static readonly BindableProperty TextProperty = BindableProperty.Create(nameof(Text), typeof(string), typeof(SwitchViewCell));
        public static readonly BindableProperty IsVisibleProperty = BindableProperty.Create(nameof(IsVisible), typeof(bool), typeof(SwitchViewCell));

        public string Text
        {
            get
            {
                return (string)GetValue(TextProperty);
            }
            set
            {
                SetValue(TextProperty, value);
            }
        }

        public bool IsVisible
        {
            get
            {
                return (bool)GetValue(IsVisibleProperty);
            }
            set
            {
                SetValue(IsVisibleProperty, value);
            }
        }

    }
}

I'm not sure if this is 100% the way to go but when I try to implement this I get the message:
 EventHandler "selectValue" not found in type "Japanese.Templates.SwitchViewCell" (Japanese)

A:

ListView Cell:
For the ListView cell, you can define the ViewCell layout of ListView item.
Ex. PersonCell.xaml
<ViewCell xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
          x:Class="DataTemplates.PersonCell">
     <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="0.3*" />
            <ColumnDefinition Width="0.3*" />
            <ColumnDefinition Width="0.4*" />
        </Grid.ColumnDefinitions>
        <Label Text="{Binding FirstName}" />
        <Label Grid.Column="1" Text="{Binding LastName}" />
        <Label Grid.Column="2" Text="{Binding Email}" />
    </Grid>
</ViewCell>

Then you can use this into ListView's DataTemplate as:
<ListView ItemSource="{Binding PersonList}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <local:PersonCell />
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

This way ListView resuses the cell design for each item.
Reusable View:
You can also make a reusable view which can be simply included in your page.
Ex. MyCustomView.xaml:
<Grid xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Xam.Control.MyCustomView">
    <StackLayout>
        <Label Text="Hello"/>
        <Label Text="How Are You?"/>
    </StackLayout>
</Grid>

Page:
<ContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:customView="clr-namespace:Xam.Control;assembly=Xam"
x:Class="Xam.View.HomePage">

Here, notice that you have to include the namespace and assembly where your custom view resides.
And then in this page, simply add it like:
<customView:MyCustomView />


Q:

How can I see code for nib/xib files?

Is it possible for us to see the source code generated behind the out of xib/nib files (I know they are xml files)?
I heard about NIBTOOL but I believe it is no longer available or replaced by some other tool which I cannot find. Does anyone know about it?
Thank you very much for responses.

A:

Nitish edited answer is : Just right click on nib file and Open As Source Code


Q:

Is it possible to tell composer to always choose lower package version, when there are more then one matching requiremnets

I have a package which uses "satooshi/php-coveralls" package to calculate coverage on TravisCI. Coveralls composer.json requires:
"require": {
        "php": ">=5.3.3",
        "ext-json": "*",
        "ext-simplexml": "*",
        "guzzle/guzzle": "^2.8|^3.0",
        "psr/log": "^1.0",
        "symfony/config": "^2.1|^3.0",
        "symfony/console": "^2.1|^3.0",
        "symfony/stopwatch": "^2.0|^3.0",
        "symfony/yaml": "^2.0|^3.0"
    },

My package doesn't use any of those packages directly, but I am supporting PHP 5.4 which in turn requires that lower version of all them are used. Is there a way to tell composer to use guzzle/guzzle: ^2.8 rather then ^3.0, symfony/config: ^2.1 rather then ^3.0 etc. Currently when I run composer install, higher versions are installed so the build fails on PHP 5.4

A:

There is a prefer-lowest option when running composer. Here are more details
https://evertpot.com/testing-composer-prefer-lowest/


Q:

Can transient keywords mark a method?

In a java class java.util.Locale, I find that the keyword transient marked a method.
 public final class Locale
    implements Cloneable, Serializable
{
    private static class LocaleNameGetter
        implements sun.util.LocaleServiceProviderPool.LocalizedObjectGetter
    {

        public transient String getObject(LocaleNameProvider localenameprovider, Locale locale, String s, Object aobj[])
        {
            if(!$assertionsDisabled && aobj.length != 2)
                throw new AssertionError();
            int i = ((Integer)aobj[0]).intValue();
            String s1 = (String)aobj[1];
            switch(i)
            {
            case 0: // '\0'
                return localenameprovider.getDisplayLanguage(s1, locale);

            case 1: // '\001'
                return localenameprovider.getDisplayCountry(s1, locale);

            case 2: // '\002'
                return localenameprovider.getDisplayVariant(s1, locale);
            }
            if(!$assertionsDisabled)
                throw new AssertionError();
            else
                return null;
        }

Can someone tell me why can this be?

A:

No it can't, it's only valid for fields. You seem to get your source from .class by decompiling. This is the decompiler bug, if you take a look at java.lang.reflect.Modifier src you will see that transient and varargs have the same value
public static final int TRANSIENT        = 0x00000080;
...
static final int VARARGS   = 0x00000080;

for a field 0x00000080 means transient, for a method (your case) it means varargs. This is how getObject looks like in java.util.Locale src
public String getObject(LocaleNameProvider localeNameProvider,
                        Locale locale,
                        String key,
                        Object... params) {   <-- varargs

In .class (bytecode) varargs is represented by Object[] as the last parameter + modifier bit 7 = 1 (0x80). I guess the decompiler is old and simply does not know about varargs which is since Java 1.5 so it printed it as transient.

A:

If this code has been decompiled it is most likely a result of this: Why Java methods with varargs identified as transient?
I am quoting from there:

Sort of an answer can be found in the code of javassist AccessFlag
public static final int TRANSIENT = 0x0080; public static final int
  VARARGS   = 0x0080; It appears both have the same values. And since
  transient means nothing for methods, while varargs means nothing for
  fields, it is ok for them to be the same.

A:

transient can only be applied to member variables and not to methods so there is a problem here.
Looking at the variable names in your code - things like String s and Object[] aboj - it looks like this source has been generated by decompiling the relevant .class file.
I think there is a bug in whichever decompiler you're using which is erroneously adding transisent to the method declaration.


Q:

Appropriate use of the [tag] syntax in questions

Is it appropriate to use [tag] in question text:
This is an example discussion on when to use tags in asking-questions
I personally like it as it creates a kind of "wiki" feel and can sometimes justify when a certain tag has been added to a question.  However I haven't seen many questions make use of it.
Is there a guideline for when it is or is not appropriate to use [tag]?

A:

Guideline: don't be annoying.
Generally, you'll want to make sure to link the first mention of a tag. Further mentions usually don't need it - folks can click the first one if they wish to review the tag. This keeps the page uncluttered while still providing quick access to the tag being referenced.
Of course, using tag links for things-that-are-not-tags is annoying - so don't do it.


Q:

Group By to get min transaction

Currently I have a list of transactions as below:
Front Office ID    Transaction ID    TradeDate    SettlementDate
10000              1234              2015-03-03   2015-03-04
10000              1235              2015-03-03   2015-06-17
10001              1232              2015-03-13   2015-03-18
10001              1231              2015-03-13   2015-06-17

What I need to do is find transaction ID's per Front Office ID which has the shortest number of days between trade date and settlement.
I know how to get the date difference, but I'm confused as to how to get this to work in a group by:
MIN(DATEDIFF(DD,FX.TradeDate,FX.SettleDate))

Any help or pointers in the right direction greatly received.
Thanks.

A:

Why do you need a GROUP BY if you want to "find transaction ID's per Front Office ID which has the shortest number of days between trade date and settlement"?
SELECT TOP 1 t.[Transaction ID]
FROM dbo.Transactions t
WHERE t.[Front Office ID] = @FrontOfficeID
ORDER BY DATEDIFF(DD,  t.TradeDate, t.SettleDate) ASC

If you instead want to find it for all transaction ID's you could use a CTE + ROW_NUMBER:
WITH CTE AS
(
    SELECT t.[Transaction ID],  t.[Front Office ID], t.TradeDate, t.SettleDate
           RN = ROW_NUMBER() OVER (PARTITION BY [Front Office ID]
                                   ORDER BY DATEDIFF(DD,  t.TradeDate, t.SettleDate) ASC)
    FROM dbo.Transactions t
)
SELECT [Transaction ID],  [Front Office ID], TradeDate, SettleDate
FROM CTE
WHERE RN = 1

If you want to return all transaction ID's which have the shortest timespan between TradeDate and SettleDate(in case of ties), use DENSE_RANK instead of ROW_NUMBER.


Q:

Maintaining the session even after the browser is closed

Could anyone tell how to maintain a session (in PHP) so that the session contains are preserved and are accessible even after the browser is restarted.
In general a session expires with the closing of a browser, but I want the session NOT TO BE CLOSED so that the session data's can be accessed the next time the browser is used.
Thanks

A:

There is a really good tutorial on howto save session contents to a database.
The only thing needed is to refill a new session with the saved data - there you go.


Q:

Add text/html before end of body tag

I have string(not document object) which contain html

      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

      bla bla

and some text or other html code, which I need to insert before end of body tag in first html.
In which way is better to do this?
- Convert string to html?
- Insert text or html to it
- Convert result to string

A:

Try this :-
var newHTML = "

This is New Html

";
    $("body").append(newHTML);
    console.log($("body").html());

If you need to concatenate another string in your HTML, try this :-
var firstString = "

This is a string

";
var secondString = "
This is another string
";
firstString += secondString;
console.log(firstString);

Update
 function AddHtml() {
    var firstString = "

This is a string

";
    var indexOfbody = firstString.indexOf("");
    var Firsthalf = firstString.slice(0, indexOfbody);
    var middleHalf= "

This is another string

";
    var LastHalf = firstString.slice(indexOfbody);
    var FinalString = Firsthalf + middleHalf+ LastHalf;
    console.log(FinalString);
}


Q:

Android add a subview to a row layout of a listview

I have a ListView in my application with a custom adapter that extends the BaseAdapter. In the getView() method of my custom adapter a relative layout is inflated in order to display data parsed from JSON.
In SOME cases data include an image url that i want to load in an ImageView of the row's RelativeLayout. But by default this layout doesn't include a second ImageView for this purpose.
Question: Which is the appropriate way of adding a sub-element (ImageView) in the RelativeLayout depending on the data received and after its been inflated in the getView() method of my adapter? The following image is the relative layout that is inflated:

And this is how i want it in some cases (rows of list depending on data):

I should mention that i've searched for this a lot. But can't decide for a efficient way of doing this.

A:

By default put the image view always in your list item layout and make visibility as "Gone" whenever you required you can set the image and change the visibility.
if(imageDisplay){
   //set the image and change the visibility as "Visible"
}else{
   //set the visibility as "Gone"
}


Q:

Is Draco portrayed in the canon books as good-looking?

In fan-fiction, Draco-Harry and Draco-Hermione pairings are very common. Their popularity is evidenced by the fact that this very site has specific tags for them. This is often attributed to Draco being cute.
And there's no doubt that Tom Felton, who plays Draco in the films, is good-looking. But is there any canonical information in the books or related material about Draco's appearance? Is he conventionally attractive? Or not so much, like most of the Slytherins we hear about save Zabini and Riddle?

A:

Draco isn’t described as attractive or ugly.
Draco isn’t usually described as either good or bad looking. The best indication of what Draco was supposed to look like in the books is this drawing by J.K. Rowling.

He’s mainly described as having a pale pointed face with cold grey eyes and white-blond hair, without any mention of how attractive he is.  While the books are written in the third person, they reflect Harry’s view, so it’s unclear if the word choice is colored by that. The terms “pale and pointed” may have a slightly negative association, but whether those features make him look attractive or unattractive isn’t ever stated, so it can’t be assumed from that description. His description remains consistent throughout the series. In the first book, Draco is described as having a pale, pointed face.

"In the back of the shop, a boy with a pale, pointed face was standing on a footstool while a second witch pinned up his long black robes. Madam Malkin stood Harry on a stool next to him, slipped a long robe over his head and began to pin it to the right length." - Harry Potter and the Philosopher’s Stone)

He’s mentioned as having identically cold and grey eyes as his father.

"The man who followed could only be his father. He had the same pale, pointed face and identical cold grey eyes." - Harry Potter and the Chamber of Secrets

He’s again described as having a pale and pointed face in “Chamber of Secrets”.

"And from behind the six large figures before them came a seventh, smaller boy, smirking all over his pale, pointed face. It was Draco Malfoy." - Harry Potter and the Chamber of Secrets

Further descriptions of him tend to focus on a combination of these same features.

"It was Draco Malfoy. He had pushed to the front of the crowd, his cold eyes alive, his usually bloodless face flushed, as he grinned at the sight of the hanging, immobile cat." - Harry Potter and the Chamber of Secrets

His face is also described as sneering in “Prisoner of Azkaban”, in addition to being pale and pointed.

"Draco Malfoy and Harry had been enemies ever since they had met on their very first train journey to Hogwarts. Malfoy, who had a pale, pointed, sneering face, was in Slytherin house." - Harry Potter and the Prisoner of Azkaban

Through the years as he gets older, the description of Draco stays the same.

"The Gryffindor team laughed loudly. Malfoy’s pale eyes narrowed, and he stalked away." - Harry Potter and the Goblet of Fire

It’s mentioned that his mother Narcissa would be attractive if she didn’t look so haughty, but no observations are made on Draco’s attractiveness.

"Harry and Draco Malfoy had been enemies ever since their very first journey to Hogwarts. A pale boy with a pointed face and white-blond hair, Draco greatly resembled his father. His mother was blonde, too; tall and slim, she would have been nice looking if she hadn’t been wearing a look that suggested there was a nasty smell under her nose." - Harry Potter and the Goblet of Fire

Draco is also consistently described as looking like his father.

"‘Manners, Potter, or I’ll have to give you a detention,’ drawled Malfoy, whose sleek blond hair and pointed chin were just like his father’s. ‘You see, I, unlike you, have been made a prefect, which means that I, unlike you, have the power to hand out punishments.’" - Harry Potter and the Order of the Phoenix

The same words are used to describe Draco throughout the series, from his introduction to his later years.

"A teenage boy with a pale, pointed face and white-blond hair appeared from behind the rack wearing a handsome set of dark green robes that glittered with pins around the hem and the edges of the sleeves. He strode to the mirror and examined himself; it was a few moments before he noticed Harry, Ron and Hermione reflected over his shoulder. His light grey eyes narrowed." - Harry Potter and the Half-Blood Prince

At no point is it mentioned how attractive he is - he’s simply described as having white-blond hair and a pale pointed face.

"Harry did not dare look directly at Draco, but saw him obliquely: a figure slightly taller than he was, rising from an armchair, his face a pale and pointed blur beneath white-blond hair." -  Harry Potter and the Deathly Hallows

In Deathly Hallows, Draco’s face is also described as usually languid, but that may have only be since he became a Death Eater.

"‘Of course not, of course not!’ said Lucius impatiently. He approached Harry himself, came so close that Harry could see the usually languid, pale face in sharp detail even through his swollen eyes. With his face a puffy mask, Harry felt as though he was peering out from between the bars of a cage." - Harry Potter and the Deathly Hallows

Even in the epilogue, Draco is described as having a pointed chin and a receding hairline.

"Draco Malfoy was standing there with his wife and son, a dark coat buttoned up to his throat. His hair was receding somewhat, which emphasised the pointed chin." - Harry Potter and the Deathly Hallows

Throughout the series, Draco is never canonically stated to be either attractive or unattractive.


Q:

require.js require a module with index.js

So I'm trying to set up Typescript and Chutzpah for testing purposes. Typescript is set up to output in this format:
define(['require', 'exports', './someModule'], function(require, exports, someModule) {
    //examplecode
});

Which works fine, the problem occurs when someModule is actually a directory with an index.js.
/app
  app.js
  /someModule
    index.js

require.js is unable to resolve someModule in this way and the test fails.
Is there any way to tell require.js that this is a module?

A:

RequireJS won't automatically check for the presence of index.js and load that as your module. You need to tell RequireJS that when you want to load someModule, it should load someModule/index. I'd set a map in my call to require.config:
require.config({
  [ ... ]
  map: {
    '*': {
        someModule: 'someModule/index',
    }
  },
});

You have to adjust the name you give there so that it is a path relative to your baseUrl. It's not clear from the information you give in your question what it should be.
(For the record, there's also a packages setting that you could probably tweak to do what you want but putting something packages says "this is a package", which is not what you appear to have here. So I would not use it for what you are trying to do.)


Q:

Check if any field is different from database value

After I submit a form, I need to check if any field in the database table changed. If changed I create a new record, if not, I don't do anything. I can't just update the record.
Is there a way to do it without checking every single field like the code below?
<cfquery name="getData" datasource="myDS">
  Select * From table Where ID = #form.ID#
</cfquery>
<Cfset changed = false />
<!-- Check every field -->
<cfif form.data1 neq getData.data1>
   <cfset changed = true />
</cfif>
<cfif form.data2 neq getData.data2>
   <cfset changed = true />
</cfif>
<cfif form.data3 neq getData.data3>
   <cfset changed = true />
</cfif>
...

Thanks

A:

Might depend on what database you are using but you should be able to do a query that will insert if the data does not exist.
As an example I just tested this against Oracle 12c using CF2016 Enterprise and it creates a new record if the data does not exist.
<cfquery name="Testing" datasource="Test">
    INSERT INTO TESTTABLE (DATA1, DATA2, DATA3)
    SELECT  <cfqueryparam value="#Form.Data1#" cfsqltype="CF_SQL_VARCHAR" />, <cfqueryparam value="#Form.Data2#" cfsqltype="CF_SQL_VARCHAR" />, <cfqueryparam value="#Form.Data3#" cfsqltype="CF_SQL_VARCHAR" />
    FROM dual
    WHERE NOT EXISTS
    (SELECT DATA1, DATA2, DATA3 FROM TESTTABLE WHERE DATA1 = <cfqueryparam value="#Form.Data1#" cfsqltype="CF_SQL_VARCHAR" />,
    AND DATA2 = <cfqueryparam value="#Form.Data2#" cfsqltype="CF_SQL_VARCHAR" /> AND DATA3 = <cfqueryparam value="#Form.Data3#" cfsqltype="CF_SQL_VARCHAR" />)
</cfquery>


Q:

python Matplotlib -- Multiple Chart Objects?

How can I use matplotlib to create many different chart objects and then have the ability to control each chart object separately (without affecting the other chart objects)?
Ideally, I'd like to have something of the following:
# creating the chart handler object
chartHandler = ChartHandler()
# plotting some values for chart #0
chartHandler[0].plot( range(0,100) )
# plotting some values for chart #5
chartHandler[5].plot( range(500,700) )

A:

Unless you are talking about something that I haven't dealt with in matplotlib yet, I think that what you are looking for is figure.add_subplot().  You should be able to capture the return from each figure.add_subplot() and operate on each individually from then on, kind of like this:
import matplotlib.pyplot as plt

#Create an 11x5 figure
fig = plt.figure(figsize=(11,5))

#Create subplots[0]
subplts = []
subplt = fig.add_subplot(121)
subplts.append(subplt)

#Create subplots[1:20]
for xind in range(4,8):
    for yind in range(0,5):
        subplt = fig.add_subplot(5,8,(yind*8+xind))
        subplts.append(subplt)

plt.show()

It should be noted that there are a few problems with the above script.  Mainly, the subplots overlap slightly.  This can be solved using the position keyword to add_subplot and some simple math.
In any case, you can now modify each subplot by referencing its index in subplots.  It should be pretty simple to add plots, modify ranges, etc.


Q:

Setting logging levels using a variable

I haven't quite got the hang of Python enough to figure this out on my own, so I'm asking for help.
I have various logging messages scattered throughout my python module. I would like the code calling the module to be able to set the debug level by doing:
module.DEBUG = INFO
for instance. But I'm not able to translate that into work. I've got global variable "DEBUG", and I would like it to be interpreted in the following line, rather than DEBUG acting as a literal string, which is what I think is happening:
 logging.basicConfig(format='%(levelname)s - %(message)s', level=logging.DEBUG)

How can I make that string be treated as a variable instead of a literal (if that's what is happening?)
Thanks!
--Matt

A:

If you would like the calling code control the logging level on your module, you should consider accepting the log level as a parameter in your module. Below is some sample code on how you can do that:
import logging

class MyModule(object):
"""
Sample module to demonstrate setting of loglevel on init
"""

    def __init__(self, logLevel):
        #logLevel, a string, should be one of the levels of the logging modules. Example: DEBUG, INFO, WARNING etc.

        #Translate the logLevel input string to one of the accepted values of the logging module. Change it to upper to allow calling module to use lowercase
        #If it doesn't translate default to something like DEBUG which is 10
        numeric_level = getattr(logging, logLevel.upper(), 10)

        logging.basicConfig(filename='example.log', level=numeric_level)

    def testLogger(self):
        #logging object that you defined the level in init is used here for some sample logging
        logging.debug('see this at debug level')
        logging.info('see this at info and debug')
        logging.warning('see this at warn, info and debug')

if __name__ == "__main__":
    MM= MyModule('info')
    MM.testLogger()


Q:

.Net Web Reference SSL Error

While using a Visual Studio "Web Reference" to a SOAP service on a server that requires an HTTPS connection I get the error:
"The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel."
The parent class of the client is SoapHTTPClientProtocol if that makes any difference.
I am not in the position to modify the certificate of the server. Is there a programmatic way to accept the certificate?
Googling around I found several references to the ServicePointManager class but none comprehensive enough that I understand how to make use of it.
http://support.microsoft.com/kb/915599
Has anyone else encountered this error?

A:

Try calling this before calling the service:
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);

And put this callback method in:
    private static bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
    {
        return true;
    }


Q:

Sum of multiplication of all the elements in a list in C++

The program is suppose to return the sum of multiplication of all elements in the list.
If list contains (1,2,3), it should return 6.
I saw a few related posts but I still couldn't figure it out.
I tried this:
The xList cotains (3,2)
for (std::list<unsigned>::iterator it=xList.begin(); it!=xList.end(); ++it)
{
subtotal= ((*it) * ((*it+1));

total= total + subtotal;
}

The output i get is 18, I should get 6. Any clue?

A:

Assuming that @Frank Osterfeld's comment is correct in suggesting that you want the product of the elements in the list, this will do it:
#include <iostream>
#include <list>

int main () {
    std::list<unsigned> xList;
    xList.push_back(3);
    xList.push_back(2);

    unsigned product = 1;

    for (std::list<unsigned>::iterator it=xList.begin(); it!=xList.end(); ++it) {
        product = product * (*it);
    }

    std::cout << product << std::endl;
    return 0;
}

Since it is an iterator rather than a pointer, you can't get the next value of the iterator by adding one to it. As others have shown, the original code adds one to the value of the list element, which isn't what would be wanted either.


Q:

User authentication design, are users people?

The application is written in Ruby on Rails but the problem I am facing is more a design matter than language related.
the system provides service to a number of users to maintain a registry. So it relates persons to things. As such it has a model called Person representing owners and it has a model called User representing those who manage the registry.
Now a new requirement has arisen to allow People to log in and be able to change personal details which it was not required for the original design.
The question is how to refactor the application to allow this new requirement in?
One easy solution is to create Users for each person who request login credentials and link user to person entity but that is not very DRY as some fields such as firstname, surname etc. are in both classes and in particular, that is precisely the data people will be able to change. Besides User and Person are stored in separate tables.
The other possibility I was considering is to make one to extend the other but having data in separated tables it makes it a bit messy. Additionally the logical extension would be User <- Person as an user is (generally) a person but thinking on the implementation Person <- User is quite a lot easier.
One last option could be to scrap User and move login credentials into Person leaving logon fields empty for those who won't log in and half of the fields empty for those just login in.
Can you think of a better solution?

A:

You could think about how this should ideally work if you were to write the application bottom-up, and then figure out how to make a reasonable compromise between that and your current setup. Here are some generic inputs.
As authentication is involved, you need an "Identity" that can be authenticated. This can be e.g. an email address and an associated password, with email verification.
An Identity can potentially be associated to multiple "Roles" and someone authenticated with the identity can choose which role to perform, e.g. "I am now an administrator" vs. "I am now a regular site user", and the role defines the user's current rights for the logged in identity. Or if you don't need that level of complexity, you can say that an Identity is a (single) Role.
You need some tracking between possible "Rights" and the Role the user is performing. E.g. the simplest setup could be the Identity or Role has some boolean can_edit_profile or can_modify_registry properties.
Whenever a user attempts to perform an action which requires certain Rights, it is simply a matter of looking up the corresponding rights set for the Role being performed by the user, to check whether the user is allowed to proceed.
For your application this may just involve adding a 'can_change_registry' property for your user objects, and check whether that property is True for any code accessing that part of the site.


Q:

Visualizing a huge graph like wikipedia

I have a hugh graph structure like wikipedia. I have the adjacency list for the graph as it is very sparse. Is there a open source software to visualize the graph and zoom in and out.

A:

GraphViz is a very well known OSS graphing tool. If you can print your graph in one of its supported formats you should be ready to go.


Q:

What is the complexity of computing a compatible 3-coloring of a complete graph?

Given a complete graph whose edges are colored by 3 colors, a compatible 3-coloring is a coloring of nodes such that no edge of the graph has the same color as its end-points.
The best algorithm I know is quasi-polynomial time. The problem is not known to be NP-complete. What is known about the status of this problem ?

A:

Apparently, this paper by Cygan, Pilipczuk, Pilipczuk and Wojtaszczyk (2010+) gives a faster (polynomial time) algorithm: http://arxiv.org/abs/1004.5010
It was accepted to SODA 2011.

A:

The fastest known algorithm has running time $n^{O(\log n/ \log \log n)}$ [1].
Your question is reposed as an open problem in [2, page 4].
[1]: T. Feder, P. Hell, D. Král, and J. Sgall. Two algorithms for general list matrix partitions. SODA 2005, pages 870–876.
[2]: E. D. Demaine, M. Hajiaghayi, D. Marx. Open Problems -- Parameterized complexity and approximation algorithms. Dagstuhl Seminar 09511 (2009). Available here.


Q:

how to arrange the input text/file in a line

I am designing a web page with multi line Label name & input type file. i tried very hard to arrange in same line sequence but failed to do. Is there any idea about it?
please take a look enter link description here , it looks very ugly and

A:

I am not really sure what you are looking for, but check out the jsfiddle changes I had made.  I modified both CSS classes a little bit.


Q:

Is there an advanced way to label in ArcMap so that the label will not be dropped?

Is there an advanced way to label in ArcMap so that the label will not be dropped?

A:

On the labels tab of the layer properties, click Placement Properties...
On the conflict detection tab, turn on the checkbox for "Place overlapping labels".


Q:

Why isAnnotationPresent(Id.class) is not working for the class file

I have a class file test.class. In that file there is  annotations as @Id and @Entity. But when i check for the annotation with the method field.isAnnotationPresent(Id.class), it returns false. I am getting all the fields in field variable.
Can any body tell me what mistake i did.
update:am using the following code to get the class
File file=new File("D:/test/");
URL url=file.toURL();
URL[] urls=new URL[]{url};
ClassLoader loader=new URLClassLoader(urls);
Class cls=loader.loadClass("com.net.test.Test");

A:

Have you annotated your annotation with a retention policy? If no retention policy is set the default retention policy behaviour is that the annotation is read by the compiler and also retained in the generated .class files but won't be accesible during runtime. If you need the annotation in runtime you need to annotate your annotations with:
@Retention(RetentionPolicy.RUNTIME)

A:

Your test's classloader may have a different Id than loader's.
A quick way to check:
...
Class idType = loader.loadClass("my.package.Id");
...
field.isAnnotationPresent(idType);

If that works, then you have a classloader problem -- more specifically, your loader does not use your test case's loader. To fix, use a different constructor:
ClassLoader loader = new URLClassLoader(urls, this.getClass().getClassLoader());


Q:

How should we handle "why someone does X" questions?

Note: This question was supposed to cover all "why someone does X" questions, not only the example mentioned here.

Example: Can I tell my girlfriend that I'm too lazy to meet up?
After fixing the formatting a bit, and reading twice, I feel this question should be on-topic. This question is asking about "why my girlfriend is mad at me after I do ..."
While that type of question is inherently opinion-based (we cannot possibly know what someone's thinking and why someone does something), it seems the reason is rather obvious to reasonable people, but not to OP.
This answer beautifully address the reason why his girlfriend surely will be mad at him, and I believe this is the fundamental reason why she's mad. This is a very helpful insight to future visitors who might do the same thing like OP (which I believe they will be a lot of teenagers).
I think questions that ask insight about why someone does something should be on-topic. The nature of this type of question is opinion-based, so it must be handled on a case-by-case basis. So, while it is on-topic, it may be unanswerable because too opinion-based.
Q: How the community feels about "Why someone does X" questions? How should we handle them?
Note: For this particular question, I think it is on-topic, and while opinion-based, I think this is answerable, and that answer gives an example how it should be answered.
Another example of good "Why someone does X":

Why do (half-)strangers say "I'm sure you'll love it" when they don't know my interests?
Why are people unwilling to share information about their salary?
Why do people flirt in customer service situations?

A:

I think it is probably on topic, as well, but I still agree it should have been put on hold.
As HDE 226868 explains in a comment on that question, any or all of the following pieces of context would make the question clearly answerable:

1) What are you trying to accomplish? In other words, what is your specific goal you need help with?
2) Can you give some more background on your relationship, if you think it's needed? Certain personal details (e.g. general age range) could also be useful.
3) What culture is this taking place in? Interpersonal situations are often strongly culturally-dependent.

The answer mentioned in your question is good, but it is very generic.  The only part that is specific to the question (without making guesses about the OP's intent and thoughts) is that the relationship is relatively new.
Take note of the other (non-deleted) answer.  It starts with:

Depends on the context. Did you consent to go out to before the shower? Where you the one that proposed to go out?

This is a strong flag that the question does not provide enough details.  That's why it should be put on hold, until enough details are provided.

A:

I feel some of these kinds of questions run a fine line between being on-topic and off-topic.

If the situation can be reworded as

How can I better empathise with X's feelings in Y situation.

Then that does involve an interpersonal skill, and answers can point out potential viewpoints to consider as well as techniques for gaining a better understanding of the other person's viewpoint.

Or if it's asking for a general answer, to common etiquette. Such as:

Why do people flirt in customer service situations?

Then again, it's on-topic as it's asking about culture in general, and can help somebody develop their interpersonal skills/gives context to them using those skills.

However, if the question effectively distils down to:

Please explain why this person feels/does X.

Then it is off-topic. We cannot read minds, and it would be dangerous for us to second guess a 3rd party's motives. There will never be enough information in the question to properly answer such a question, as that information would need to come from the 3rd party themself.

I feel it's important to distinguish between the examples given in the question here; which are all on-topic. Either asking about how to better understand somebody else's viewpoint, or how to understand social norms in general.
However, there are questions asked on IPS which effectively come down to "why did he do what he did" - which we simply can't answer.


Q:

Accessing calendar event data in FullCalendar

I'm trying to use FullCalendar to render the events from a Google calendar on a webpage. I want the starting date/time, description, and place. Future events in one div and past events in another.
Right now I have FullCalendar working to its basic functionality: a complete calendar on my page that displays my gcal events.
So my question is: how can I access the data and render it as text on my page? There is a block of code in the gcal.js file that looks like this
events.push({
   id: entry['gCal$uid']['value'],
   title: entry['title']['$t'],
   url: url,
   start: start,
   end: end,
   allDay: allDay,
   location: entry['gd$where'][0]['valueString'],
   description: entry['content']['$t']
  });
});

how would I go about accessing this events array?
Hope this question isn't too vague, thanks for your help.

A:

See: clientEvents
You can also use a function, like:
mycal.fullCalendar('clientEvents', function(ev) {
 // ev is Event object...
});


Q:

How can I make sure the rotation has finished or the transform is facing the target?

void FixedUpdate()
    {
        LiftProcess();
        MoveProcess();
        TiltProcess();

        if (hasRotate == true)
        {
            Vector3 targetDirection = helicopterPlatform.transform.position - transform.position;
            Vector3 newDirection = Vector3.RotateTowards(transform.forward, targetDirection, lookAtSpeed * Time.deltaTime, 0.0f);
            transform.rotation = Quaternion.LookRotation(newDirection);
        }
    }

I want ot make a check IF transform.rotation has finished and the transform is facing the newDirection then change the flag hasRotate to false. What check and how should I apply ?

A:

You can check if ( Vector3.Angle(newDirection, targetDirection) < thresholdDegrees), where you can set the threshold in degrees as tight as you like.


Q:

To find the minimum(least) number of Unique numbers in a given list after 'n' reductions

Problem Statement: To find the minimum(least) number of Unique numbers in a given list after 'n' reductions
Input:
N and an Array(or list)

Where 0 < N < len(Array)

N is the number of reductions possible  and the input for the array needs to be separated by commas(,)
Example 1:
N = 2

Array = 1, 2, 3, 3, 4, 4

Output:
To find the Least or minimum number of unique elements after deleting N number of elements in the Array
In the above example,
After deleting N = 2 number of elements from the Array
In the above example 1, 2 should be deleted from the array
         3, 3, 4, 4 will be remaining
So, 2 unique elements remaining after deleting 2 elements from the array
So, the output should be 2
Example 2:
N = 2 [ number of reductions possible]

Input Array : 1,3,4,1,2,4,2,2

Output: 3 [least number of unique elements]

Explanation :[1,1,2,2,4,4] will be the resultant array when [2,3] are removed
Supposed to be coded in Python exclusively but solutions in any language will be appreciated.

A:

Finding the minimum number of unique elements is equivalent to finding the maximum number of duplicates.
The driving idea here would be to use your reductions to take out the elements that appear the fewest number of times first. In order to do that, you'd want to count the number of occurrences of each element in the list, sort them by number of occurrences, and remove them from least to most until you run out of deletions. The only tricky part is the first part, and that's only if you have to code it in pure python (@DerekLangley's answer gives a good example of how you might do that).
If you're allowed to import other parts of the standard library, then collections.Counter makes quick work of this problem. Here's a sample implementation that doesn't account for anything that could go wrong (such as an empty list, or N being larger than len(lst) - these are things that the interviewer would expect you to mention and know how to handle, so work on that).
import collections
...
def min_uniques(N, lst):
    # use collections.Counter to get a sorted list of unique elements and their frequencies
    most_common = collections.Counter(lst).most_common()
    # returns [(most_frequent, num_occurrences), ...], so we pull from the back to get fewest occurrences.
    # We could reverse the list and pull from the front but that would be less efficient
    while N >= most_common[-1][1]:
        # remove the element with lowest count and subtract its count from N, all at once
        N -= most_common.pop()[1]
    # return the number of unique elements left, after we can no longer remove enough to decrease that count
    return len(most_common)

min_uniques(2, [1, 2, 3, 3, 4, 4])
# 2
min_uniques(2, [1, 3, 4, 1, 2, 4, 2, 2])
# 3

My comments on that code represent how I would talk through the problem with the interviewer as I was writing it. This is a four-line python function, but I'm pretty sure you could also do it in two - the interviewer might ask for how you can improve this code, and if you can put in that as an example (maybe say "I think it would use mechanism X or mechanism Y, but I'd have to look at the documentation and do some tinkering first).
I don't especially see how Dynamic Programming is relevant here, though I kind of feel like Dynamic Programming is a bit of a buzzword anyway.


Q:

mysql selection first letter of each word in a cell

I would like to return the first letter of each word in a MySQL column called 'initials'.
For example, my table may look like this:
|             project_unit              | initials |
+---------------------------------------+----------+
|      Mbita Clinic Rehabilitation      |   MCR    |
| Management Strategy for Thrips Cowpea |   MSTC   |

Any suggestions?

A:

You can use below mentioned function to achieve your requirement.
 DELIMITER $$
CREATE FUNCTION split_string(split_string varchar(255),my_delimiter varchar(1)) RETURNS varchar(10)
BEGIN
DECLARE temp_string varchar(255);
DECLARE occurance INT;
DECLARE i INT;
DECLARE temp_result varchar(10);
DECLARE final_result varchar(10);
SET temp_result = '';
SET occurance=length(split_string)-length(replace(split_string,' ',''))+1;
  IF occurance > 0 then
    set i=1;
    while i <= occurance do
        set temp_string = (select SUBSTRING_INDEX(SUBSTRING_INDEX(split_string, my_delimiter, i),my_delimiter ,-1));
        set temp_result = CONCAT(temp_result, SUBSTRING(temp_string,1,1));
      set i=i+1;
    end while;
  ELSE
        set temp_result = SUBSTRING(split_string,1,1);
  END IF;
  set occurance=0;
  SET final_result = temp_result;
  RETURN (final_result);
END $$
DELIMITER ;

You can use it like this :
SELECT Projcect_unit, split_string(Projcect_unit,' ') as initials FROM main_table;


Q:

ENDORSEMENT_POLICY_FAILURE error on on invocation of chaincode functions

On instantiating the chaincode without specifying the endorsement policy, invocation of functions in chaincode work fine and stored data can be seen on couchdb database. But on explicitly specifying endorsement policy as "AND ('mohaMSP.peer','ecMSP.peer')" during instantiation of chaincode, the invocation  of chaincode functions don't show any error, but do not update the couchdb state database. So I checked the logs on peer0.moha.nid.com and it showed the following error:
2019-01-29 09:46:00.851 UTC [valimpl] preprocessProtoBlock -> WARN cac6 Channel [nid-channel]: Block [7] Transaction index [0] TxId [bfed301afcaae5ad2ee8885c3cdbd39521827b25cabe92d6cf03f931da4ea391] marked as invalid by committer. Reason code [ENDORSEMENT_POLICY_FAILURE]

I have installed the chaincode on peer0.ec.nid.com and peer0.moha.nid.com (i.e. in both organizations) and verified the installation as well. There are three peers joined to the nid-channel - peer0.moha.nid.com, peer1.moha.nid.com, peer0.ec.nid.com as shown by peer channel list command.
here is docker-compose.yaml file to start the network
here is docker-compose-base.yaml file
here is peer-base.yaml file
I am running fabric 1.2.1 containers and have tagged them as latest.
Chaincode instantiation command:
peer chaincode instantiate -o orderer.nid.com:7050 -n car_reg -v 1 -C nid-channel -c '{"Args":[]}' -P "AND ('ecMSP.peer','mohaMSP.peer')"

A:

I was missing the --peerAddresses arguments during invocation of chaincode function. Now it's solved. Thanks to @Harshit 's comment
peer chaincode invoke -o orderer.nid.com:7050 -C nid-channel -n car_reg --peerAddresses peer0.moha.nid.com:7051 --peerAddresses peer0.ec.nid.com:7051 -c '{"Args":["createCar","1","bmw","tx","blue","me"]}'


Q:

Error in eclipse when running activity

I am starting to program for android, when I first try to run the application from eclipse IDE it worked fine, but now I am getting the following error:
emulator: ERROR: unexpected qemud char. channel close

I didn't change the configuration or the code i had, also the activity is not starting in the emulator and I can't debug.
Can someone tell me what this error means?
Thanks

A:

you may try to delete the AVD & create a new one
sometimes it keeps saving errors in a log then those errors become permanent
try to create a new emulator then test again


Q:

Subdomain and subdirectories together in one installation

I'm currently want to develop my design company website and choosing wordpress as my CMS.
How do I should install the wordpress when I want the domain structure like this:

Blog = blog.example.com
Portfolio = example.com/portfolio/...
Shop = shop.example.com = using WooCommerce

I'll be glad if someone would help, because I really have no idea to config.

A:

If you want sections in a subdomain and in subdirectories, use a multi-site installation. See Create a Network and our tag multi-site.
Then you set the the blog and the shop as separate sites, and the portfolio as a custom post type or as a regular page in the main blog.