Add field in a Gii form from another table

Question: I have a table called child (id, name, sport_id), a table called sports (id, name), a table called parent (id, name) and a table called child_parent(id, child_id, parent_id).
I created the crud with Gii and I modified the child_parent to show not the id of the child and parent but the names, also made a dropdownlist for search and for the create form. But one thing I can't do is put an extra column on the index from called 'Sport', so I can filter childs/parents by sport. How can I do this?
Comment: What model are you using on this index? `child_parent` ?
Comment: Exactly. Im using child_parent model
Comment: ActiveRecord likely won't do you much good here.  You are probably best to use yii\db\Query and yii\data\SqlDataProvider with join() between child_parent and child and handling the filtering yourself.
Answer: Junction table is not necessary, you can use a self-referencing relation.

node ( id, parent_id, sport_id, name)
sport ( id, name )

With parent_id defaulting to NULL (root). If need be, you can add a rule or conditional visibility for fields that enforces children to have the same sport_id as the parent (unless its a root).
Now you can easily enable filtering by sport.
<code>[
    'attribute' => 'sport_id',
    'filter' => Html::activeDropDownList(
        $searchModel,
        'sport_id',
        ArrayHelper::map(Sport::find()->all(),'id','name'),
        ['prompt' => '']
    ),
    'value' => function($model) {
        return $model->sport->name;
    }
],
</code>


Angular 5 - W3C markup validation

Question: I'm building Angular 5 application with Angular Universal. Currently I got a problem with W3C validation. The validator is showing errors on every attribute from Angular core.
For example, for code part like:
Toggle

I'm getting error like:

Attribute _ngcontent-c1 not allowed on element span at this point.

I read about adding before Angular attributes data- prefix, but on Angular 5 it won't work (I think).
Is there any solution to remove it on server side using Angular Universal, or is there any external tool?
Comment: Related discussion at https://stackoverflow.com/questions/18607437/should-i-care-about-w3c-validation/29023301#29023301. What we need is to get agreement on some standard syntax for custom-attribute names. Some proposals have been discussed at https://github.com/whatwg/html/issues/2271 but there's been no resolution yet. If/when the HTML spec defines some standard syntax for custom attributes, I could update the W3C HTML checker to recognize them. In the meantime, you can use the message-filtering feature (button) in the checker UI to persistently (using localstorage) filter out those errors
Comment: You should read a description. I think it won't work with Angular 5. Gr
Comment: https://www.npmjs.com/package/angular-html5
Comment: Is this W3C validation absolutely required?
Comment: Okey, thank You for answer. I hope it will be avaible soon.
Answer: Angular provide these _ngcontent-c1, _ngcontent-c2 attribute added to specific DOM elements with styles.
_ngcontent-c1 is used unique identity when rendered from server. when we do ViewEncapsulation.Emulated and it's the default behaviour of angular.
If you don't want such kind of attribute so you can add ViewEncapsulation.None or ViewEncapsulation.Native.
eg.
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  encapsulation: ViewEncapsulation.None
})

Angular 5 - W3C markup validation


Xcode: Handling "duplicate symbol" for external libraries

Question: In our project we rely on 2 printer libraries: StarIO & Epson ePOS, and during compile i hit this error:
duplicate symbol _GetOnlineStatus in:
/Users/brendan/Development/xxxx/Frameworks/StarIO.framework/StarIO(StarIOPort.o)
/Users/brendan/Development/xxxx/xxxxApp/SDKs/Epson/libepos2.a(eposprint_common_status.o)
ld: 1 duplicate symbol for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see
invocation)

Need some help with the best way to resolve this issue please.
Comment: How did you guys solve this?
Comment: I just checked and Epson released a newer version that fixes this issue. Unfortunately for me I still have another library that conflicts with the star framework. Ugh..
Answer: This situation can sometimes be challenging — since both libraries are seemingly using the same symbol and because the implementations could be different. The only reliable way to fix this is to have each library vendor use a prefix for each of their classes/symbols within their libraries.
Apart from that, since I assume you only have the compiled version of the epson library (libepos2.a) you'll either want to:

Rename the symbol(s) that clash in StarIO.framework
Combine both libraries.

Option 1:
If you decide to simply rename the symbol causing the issue do a search in StarIO.framework:
GetOnlineStatus

Then rename it everywhere (in 12 files) it shows up in that library to something slightly different:
StarIO_GetOnlineStatus

Located in the following:
StarIO.framework/Versions/A/Headers/SMPort.h
StarIO.framework/Versions/A/Headers/WBluetoothPort.h
StarIO.framework/Versions/A/Headers/BluetoothPort.h
StarIO.framework/Versions/A/Headers/starmicronics/StarIOPort.h

StarIO.framework/Versions/Current/Headers/SMPort.h
StarIO.framework/Versions/Current/Headers/WBluetoothPort.h
StarIO.framework/Versions/Current/Headers/BluetoothPort.h
StarIO.framework/Versions/Current/Headers/starmicronics/StarIOPort.h

StarIO.framework/Headers/SMPort.h
StarIO.framework/Headers/BluetoothPort.h
StarIO.framework/Headers/WBluetoothPort.h
StarIO.framework/Headers/starmicronics/StarIOPort.h

Option 2:
The other option would be to combine the two libraries into one, although that can be quite a bit more complicated and present other issues perhaps. For details on how to go about doing so please see this answer here on stackoverflow.
Comment: Thanks for your answer I'L'l. I tried option 1, though unfortunately that did not work for me. Option 2 I'm a bit reluctant to try. I've been in touch with Epson and they hopefully can create a new build with namespaced symbols.


Insert Combobox items to database column

Question: Is it possible to insert values from combobox to specific column in database?
For example if i have combobox with items: item1, item2, item3 and I want to bind them to some column: column1, what I want to manage is this: if item1 is selected, when I click on button, I want to insert value of that item in the column1, otherwise if selected item is item2 then I want value of item2 to be inserted in column1, etc...
Now I know that the question is not really well written, but I just want to know if this is possible to do.
I've been Googling for this type of problem but I couldn't find the solution. I know how to make column records to be inserted into combobox items list but don't know the way to do the opposite.
Also would like to say that I have this problem in my WPF/WCF/MVVM application, so I would like to know if this is possible (and how) to solve it that way.
Comment: Just clarifying your question, you have two controls on the form, one is combobox and other is button. You want to save the selected value in combobox to database tables's col1 field. is my understanding correct???
Comment: Yes that's right. Let me be more specific: imagine that i have combobox with persons names: George, James, Michael. And have a button insert, and some table in database that have column "Names" which is empty. If i select "Michael" in combobox list, press the button insert, than i want "Michael" to be inserted in column "Names".
Answer: ofc you can. On the button click event you can just get the selected value of the combobox and save it.
var selectedItem = ComboBoxName.SelectedItem;

But if you have binded the combobox with objects then you can cast it.
var selectedItem = ComboBoxName.SelectedItem as (objecttypehere)

Update
I missed that you used MVVM. Then in the view you can use bind the combobox with selected item.
<ComboBox ItemsSource="{Binding Items}" SelectedItem="{Binding TheSelectedItem}">
     //Itemtemplates.
</ComboBox>

In the viewModel just acces the property you binded with the selecteditem in my test case "TheSelectedItem" property.
Save it!
Answer: This solution is based on MVVM pattern .
Bind the Selected item of combo box control to some property in View model.
So your view should look like
    <ComboBox ItemsSource="{Binding SomeItems,UpdateSourceTrigger=PropertyChanged,NotifyOnSourceUpdated=True}" SelectedValue="{Binding SelectedItemBinding,UpdateSourceTrigger=PropertyChanged,NotifyOnSourceUpdated=True}" />

    <Button Command={Binding ButtonClickCommand} ..../>

so once the Button is clicked you will get the RelayCommand handle in viewmodel and you can have a logic there to Get the selected item and use the value to insert into the column. Your view model should look like ,
    public class ViewModel : //implement notify property changed and ICommand
    {
        public RelayCommand ButtonClickCommand
        {
             get new RelayCommand(EventHandlerToBeCalled);
        }

        public string SelectedItemBinding
        {
             get;
             set
             {
                  //notify property changed.
             }
        }

        //method called when button is clicked.
        private void EventHandlerToBeCalled()
        {
              //here set the SelectedItemBinding to a column.
        }
    }

Comment: What if you want to write it to (for example a database) without the use of a button? (so change the combobox value => directly write to the database) with MVVM.
Answer:
in combobox you can store values with prefix (col1_12, col2_24 etc)
on button click you should parse value: separate it on prefix and original value
so you can write value to needed column:
switch (prefix) {
case "col1" : table.column1 = value; break;
case "col2" : table.column2 = value; break;
// etc
}


Pandas-How I find the lag difference days in treatment for each patient?

Question: Please help. In my sample, each patient has multiple treatments and each treatment start the specific day. My objective here is to compute the difference in each treatment.
Also, all my patients are in a single column. Once a new patient comes, the lag difference has to be reset.
My current dataset format:
df2 = pd.DataFrame({'patient': ['one', 'one', 'one', 'two','two', 'two'],
...:                     'treatment_schedule': ['treatment1', 'treatment2', 'treatment3', 'treatment1', 'treatment2', 'treatment3'],
...:                     'date': ['11/20/2022', '11/22/2022', '11/23/2022', '11/8/2022', '11/9/2022', '11/14/2022']})

 df2

My desired dataset format:
df3 = pd.DataFrame({'patient': ['one', 'one', 'one', 'two','two', 'two'],
...:                     'treatment_schedule': ['treatment1', 'treatment2', 'treatment3', 'treatment1', 'treatment2', 'treatment3'],
...:                     'date': ['11/20/2022', '11/22/2022', '11/23/2022', '11/8/2022', '11/9/2022', '11/14/2022'],
...:                     'lag_diff_days_between_each_treatment':[0, 2, 1, 0, 1, 5]})     ##### If no prior values for patient one, then like to see either null or zero

 df3

Answer: s = (pd.to_datetime(df2['date']).groupby(df2['patient']).diff(1)
     .div(pd.Timedelta('1day')).fillna(0).astype('int'))
df3 = df2.assign(lag_diff_days_between_each_treatment=s)

df3
    patient treatment_schedule  date     lag_diff_days_between_each_treatment
0   one     treatment1          11/20/2022  0
1   one     treatment2          11/22/2022  2
2   one     treatment3          11/23/2022  1
3   two     treatment1          11/8/2022   0
4   two     treatment2          11/9/2022   1
5   two     treatment3          11/14/2022  5

Answer: Use DataFrameGroupBy.diff with convert timedeltas to days bySeries.dt.days and replace missing values to 0 by Series.fillna:
df2['date'] = pd.to_datetime(df2['date'])

df2['lag_diff_days_between_each_treatment'] = (df2.groupby('patient')['date']
                                                  .diff()
                                                  .dt.days
                                                  .fillna(0, downcast='int'))
print (df2)
  patient treatment_schedule       date  lag_diff_days_between_each_treatment
0     one         treatment1 2022-11-20                                     0
1     one         treatment2 2022-11-22                                     2
2     one         treatment3 2022-11-23                                     1
3     two         treatment1 2022-11-08                                     0
4     two         treatment2 2022-11-09                                     1
5     two         treatment3 2022-11-14                                     5

Comment: @Murali - For gours multple output by `24` and for minutes by `1440`.
Comment: Is that possible I to get the difference either in hours or in minutes?


Drush hangs when trying to bootstrap Drupal

Question: Running Ubuntu 12.04 with the 14.04 backports for Drush (meaning we are running Drush 5.10.0)
After importing the database (with drush sqlc < dump.sql), Drupal is no longer able to be bootstrapped by Drush.
drupal-site@uat-previewweb1:/var/www/drupal/uat-preview/current$ drush st -v -d
Bootstrap to phase 0. [0.01 sec, 3.81 MB]                            [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drush() [0.01 sec, 4.04 MB] [bootstrap]
Loading drushrc "/etc/drush/drushrc.php" into "system" scope. [0.01 sec, 4.04 MB]                                                                            [bootstrap]
Cache HIT cid: 5.10.0-commandfiles-0-42f7d1cb79623ad6de6c23932c9a4e2b [0.02 sec, 4.07 MB]                                                                        [debug]
Bootstrap to phase 0. [0.06 sec, 9.04 MB]                                                                                [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_root() [0.08 sec, 9.04 MB]                                                                                [bootstrap]
Initialized Drupal 7.31 root directory at /var/www/drupal/uat-preview/releases/20140911-4 [0.09 sec, 10.69 MB]                                          [notice]
Drush bootstrap phase : _drush_bootstrap_drupal_site() [0.09 sec, 10.7 MB]                                                                                [bootstrap]
Initialized Drupal site uat-preview at sites/default [0.09 sec, 10.7 MB]                                                                                [notice]
Cache HIT cid: 5.10.0-commandfiles-2-c32acd775c18a90c5b41d0fc9accf5ab [0.09 sec, 10.71 MB]                                                                       [debug]
Drush bootstrap phase : _drush_bootstrap_drupal_configuration() [0.1 sec, 10.75 MB]                                                                          [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_database() [0.1 sec, 10.81 MB]                                                                               [bootstrap]
Successfully connected to the Drupal database. [0.1 sec, 10.81 MB]                                                                                [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_full() [0.12 sec, 11.92 MB]                                                                                [bootstrap]

The command hangs here and does not return.
Does anyone have any ideas on what could be causing this? Is it worth it to stray from debian packages and run Drush 6.4.0 here?
Answer: In this particular case, the issue was with an incorrectly configured memcache server settings, the Drupal environment in question was attempting to communicate with a memcache instance that had a firewall dropping all connections.
The fix was to configure memcache servers in the Drupal settings file. Hope this helps someone else.
Answer: Drush 5 is no longer supported, so I would recommend installing Drush 6 per the instructions in the README on the project page.  My guess is that Drush 6 will behave the same for you here, but it might be worth a try.  (If you are running Drupal 8, you must run the master branch of Drush, though.)
Regarding your specific problem above, a lot can go wrong if the versions of your modules is no longer in sync with the versions of the table schemas in your database.  If the database is OLDER than the code, you could try running drush updatedb immediately after you import the database.
If that does not help, it's hard to tell from the information available what could be causing the hang-up.  You'll have to dive in deeper and find out where in the code the bootstrap is having trouble, and isolate from there.
Comment: Yeah, there doesn't seem to be any Drush 6.x packages for Debian anywhere.  You can find Drush via Composer w/ Puppet here: https://github.com/greg-1-anderson/ogm-postfix-environment.  The Drush and Composer modules are inlined here; these are a work-in-progress that I will factor out once finished. Having a package is better for keeping things up to date, but installing from composer in this way is a reasonable alternative when the version of the code you need isn't available in a package yet.
Comment: Thanks Greg. Do you know of any debian package repositories for Drush 6.x?
Comment: I thought Anarcat was maintaining these in Debian backports, but could not find any in a casual search. Installing via composer is probably best.


When can the ref cancel or abandon a match due to severe weather?

Question: According to the Laws of the Game it is for the referee to decide whether or not a match can take place when the weather is too severe. But what defines the term "too severe"? Are there any guidelines about wind speed, snow, rain fall, etc. the referees have to follow?
Right now we have wind speeds of >120 km/h, which would in my opinion way over the limit, but what actually defines that limit? In our referee group we had a test for that, but that was just a small guidance for our local league (like can you see both goals from the middle line or can you run on the pitch or is it too deep, etc).
Comment: I'm surprised nobody's mentioned lightning. No, it's not in the Laws but the Dutch Guidelines state that you have to suspend play when lightning is near (10 sec between flash and thunder). And of course abandon when you have to suspend for more than 30 minutes. Hm, 2 weeks ago no sign of lightning at all. Match has ended and I'm walking to the club building. *FLASH* ... 0.1 second (estimate)... *BOOM* ... OK, we escaped that one.
In general the referee has to suspend / abandon the match if conditions are dangerous to the players. It must be somewhere in the rules but common sense counts also.
Answer: In the FA Laws of the Game, there are no official guidelines regarding what you've asked regarding wind speed, visibility. I too have received local league guidance on what they believe are grounds of abandonment, but nothing official in the laws of the game.
LotG only states that the referee is not liable for any loss suffered by players, club, ground etc. - this is including making decisions:

"that the condition of the field of play or its surrounds or that the weather conditions are such as to allow or not to allow a match to take place."

http://www.thefa.com/football-rules-governance/lawsandrules/laws/football-11-11/law-5---the-referee
Edit: another link may be useful to you - this also provides the same level of vagueness as for the LotG: https://www.westmorlandfa.com/~/media/CountySites/wmlfa/documents/refereeing/advice-on-the-application-of-the-laws-of-the-game.ashx
Comment: The appendix is fine and I'm glad you included it - it gives an example of advice provided to referees in a specific geographic area (i.e. England), which may help referees in other locations develop their own standard for managing weather in the absence of their own local competition rules. However, the FA is not the authoritative source on the Laws of the Game - IFAB is. National FAs may not update their copy of the Laws in a timely manner, so it's better to link to the IFAB resource, which is updated as soon as changes are made.
Comment: When referring to the Laws of the Game, [please use the IFAB source](https://sports.meta.stackexchange.com/questions/664/psa-please-stop-using-outdated-rules).
Comment: @studro The first link is directly from the FA and is a digitized version of the Laws of the Game. The second is simply an appendix that offers application advice.
Answer: I found the guidelines from Dutch FA (dated december 2014)
It says (among a lot of other rules) that a referee has to postpone play whenever the fog is so heavy that the referee is unable to see the goals from the centre spot.
Comment: You should have checked the laws.
Comment: Well, I've added my source. It's not the official laws, but at least locally this is what's being used.


Deployment errors, "There is already an object named 'PK_***' in the database. Could not create constraint."

Question: When I try to run my app, I get the following errors:
There is already an object named 'PK_***' in the database. Could not create constraint."

That's actually two errors combined for brevity. Note: the asterisks are my own; that is not the actual name of the key.
I've scoured what seems like every post on here, but I can't seem to get any further in finding a solution. The worst part? No one else in the team is experiencing these errors when they run, nor can they determine why I am. We are all using the same environment, VS 2012 Premium RC. I certainly have latest from TFS.
I am wondering if anyone else has come across an issue similar to this where the problems/errors occurred in only one person's environment? I can continue and run the app. It seems to run as expected, but I am the only one getting those errors.
Comment: Please [don't use signatures](http://stackoverflow.com/faq#signatures) in your questions.
Comment: When you run your app, is it using LocalDB or the SQL Server DB as its data source? If it is the former, that could be the cause of you being the only one to see the error.
Answer: In SQL Server constraints such as primary keys or foreign keys are objects in their own right, even though they are dependent upon the "containing" table.
That means that their names must be unique within the owning schema. So, just as executing DDL along the lines of
create table some_schema.foo
(
  id int not null
)
go

create table some_schema.foo
(
  id int not null
)
go

will raise an error when the second create table is [attempted to be] executed, executing ddl like this will likewise raise an error:
create table some_schema.foo
(
  id          int          not null ,
  description varchar(200) not null ,

  constraint PK   primary key clustered ( id          ) ,
  constraint AK01 unique nonclustered   ( description ) ,

)
go

create table some_schema.bar
(
  id          int          not null ,
  description varchar(200) not null ,

  constraint PK   primary key clustered ( id          ) ,
  constraint AK01 unique nonclustered   ( description ) ,

)
go

will likewise raise an error as the constraint that you're trying to create have duplicate names. You need to qualify them with the table name, thusly:
create table some_schema.foo
(
  id          int          not null ,
  description varchar(200) not null ,

  constraint foo_PK   primary key clustered ( id          ) ,
  constraint foo_AK01 unique nonclustered   ( description ) ,

)
go

create table some_schema.bar
(
  id          int          not null ,
  description varchar(200) not null ,

  constraint bar_PK   primary key clustered ( id          ) ,
  constraint bar_AK01 unique nonclustered   ( description ) ,

)
go

and you problem will go away.
It does seem to me that dependent objects that don't exist outside the context of an owing object should be namespaced within the owning object's scope, but that's not the way the SQL standard works.
Good luck!


How to calculate $(n^{-1})\%(p^a)$ for prime $p$?

Question: I actually needed to calculate $(a/b)\%m$ when $m$ is not prime. Here is what I have done so far.
$(a/b)\%m = (a* \text{modinv}(b))\%m$, I can calculate mod inverse only if $m$ and $b$ are co-primes.
So, $m= p_1^{k_1}  p_2^{k_2} \cdots p_n^{k_n}$.
For each prime factor, I will separately calculate $(a/b)\%(p_i^{k_i})$ and then combine all the answers using Chinese Remainder Theorem.
The problem is I am unable to calculate $(a/b)\%(p^k)$, can I please get some help on this.
Comment: Welcome to MSE! Please learn how to format math for this site (simple things like those in your question are not hard to do). See [formatting](http://math.stackexchange.com/help/notation) . You may also find the [tour](http://math.stackexchange.com/tour) useful.
Comment: There are much more computationally efficient ways, such as the Extended Euclidean Algorithm. No factorization, no CRT.
Comment: You can be more direct and use [Euler's theorem](https://en.wikipedia.org/wiki/Euler's_theorem). Or, if you like being optimal, [Carmichael's theorem](https://en.wikipedia.org/wiki/Carmichael_function).
Comment: @AndréNicolas Can you please elaborate ? I though Extended Euclidean Algorithm will work only if $b$ and $m$ are co-prime.
Comment: If $b$ and $m$ are not relatively prime, then $b$ does not have an inverse modulo $m$. However, if you want to solve $bx\equiv a\pmod{m}$, you can compute the gcd $d$ of $b$ and $m$. If $d$ does not divide $a$, there is no solution. If $d$ divides $a$, use the Euclidean Algorithm so solve $(b/d)x\equiv a/d\pmod{m/d}$. There will be a unique solution modulo $m/d$, but several modulo $m$.
Comment: Do you mean $\pmod x$ when you use $\%x$ as we do in Python?
Answer: It looks as if you are trying to solve the congruence $bx\equiv a\pmod{m}$.
If $b$ and $m$ are coprime, use the Extended Euclidean Algorithm to find a $z$ such that $bz\equiv 1\pmod{m}$. Then $az$ is a solution of $bx\equiv a\pmod{m}$, and it is unique modulo $m$.
If $b$ and $m$ are not coprime, then $b$ does not have a modular inverse modulo $m$. However, sometimes we can solve the congruence $bx\equiv a\pmod{m}$.
Let $d=\gcd(b,m)$. If $d$ does not divide $a$, then our congruence does not have a solution.  So suppose that $d$ divides $a$.
Then $b/d$ and $m/d$ are relatively prime. The congruence $(b/d)y\equiv a/d\pmod{(m/d)}$ has a unique solution modulo $m/d$, which we can obtain using the Extended Euclidean Algorithm.
However, the congruence has $d$ solutions modulo $m$, and from each of these solutions we can obtain a solution of $bx\equiv a\pmod{m}$.
Informally, if $b$ and $m$ are not relatively prime, then $a/b$ need not exist modulo $m$, and when it exists it is not uniquely defined modulo $m$.


Find a nonzero matrix, so that when it is multiplied by another nonzero matrix, the zero matrix is the result.

Question: Here's an interesting review question I have: Find a nonzero matrix, so that when it is multiplied by another nonzero matrix, the zero matrix is the result. How would you go about solving this? Thanks!
Comment: I don't understand: you want a matrix $A\neq 0$ such that for all $B\neq 0$, $AB=0$. But if you take $B=I$?
Comment: I want AB = 0 when A ≠ 0 and B ≠ 0. B can be any non-zero matrix
Answer: First, I'd look for a simple example, so I'd start with $2\times 2$ matrices, say $A$ and $B$. If I make the bottom row of $A$ all zeroes, the bottom row of $AB$ will automatically be all zeroes. If I make the second column of $B$ all zeroes, the second column of $AB$ will automatically be all zeroes. At this point I have
$$\pmatrix{a&b\\0&0}\pmatrix{c&0\\d&0}=\pmatrix{ac+bd&0\\0&0}\;,$$
and all that's needed in order to finish the job is to find $a,b,c$, and $d$ so that $ac+bd=0$, at least one of $a$ and $b$ is non-zero, and at least one of $c$ and $d$ is non-zero; this is very easy to do.
If you're comfortable thinking of matrices as linear transformations, you can look for a pair of non-zero linear transformations $S$ and $T$ such that $T\circ S$ sends everything to $0$. Here again, I'd try to keep it simple, so I'd look for linear transformations sending $R^2$ to itself. What if $S$ is the linear transformation that projects the plane to the $x$-axis, and $T$ is the one that projects the plane to the $y$-axis? Clearly, $T\circ S$ (and for that matter $S\circ T$) sends everything to the origin, so it's the zero transformation, but neither $S$ nor $T$ by itself does so. Having seen that, all I'd have to do is write down the matrices of $S$ and $T$.
Comment: @Chris: You're welcome!
Answer: You can find surprising results with matrices of nullity 2 or higher. For example, here are two matrices that multiply to zero, despite having all non-zero entries:
$\begin{bmatrix}
1 & 2 & 3 & 4 \\
5 & 6 & 7 & 8 \\
9 & 10 & 11 & 12 \\
13 & 14 & 15 & 16 \\
\end{bmatrix}
*
\begin{bmatrix}
4 & 3 & -2 & -9 \\
-5 & -5 & 1 & 14 \\
-2 & 1 & 4 & -1 \\
3 & 1 & -3 & -4 \\
\end{bmatrix}
=
\begin{bmatrix}
0 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 \\
\end{bmatrix}
$


group algebra and kernel

Question: I want to prove this lemma

Let $G$ be a group, $H$ an invariant subgroup, $k$ a field; consider the canonical map $\varphi \colon k[G] \to k[G/H]$;
  then the kernel of $\varphi$ is the ideal generated by the elements $(g − g')$, where $gH = g'H$.
Answer: On one hand for $gH = g'H$ we have $g-g' \in \ker \let\phi\varphi\phi$ as
$$ \phi(g-g') = gH -g'H = 0 $$
On the other hand, pick a set $A \subseteq G$  of representatives for the left cosets in $G/H$, suppose $\phi\bigl(\sum a_g g\bigr) = 0$, that is
$$ 0 = \phi\left(\sum a_g g\right) = \sum a_g gH = \sum_{a \in A} \sum_{g \in aH} a_ggH = \sum_a \left(\sum_{g \in aH} a_g\right)aH $$
As the $aH$ are linearly independent over $k$, we have $\sum_{g \in aH} a_g = 0$ for each $a\in A$, that is
$$ \sum a_g g = \sum_{a\in A} \sum_{g\in aH} a_g g = \sum_{a \in A} \sum_{g\in aH} a_g(g-a) \in \left< g-g' \mid gH  =g'H \right>$$
Comment: Are you assuming that $H$ has finite index in $G$?
Comment: I do not think so. All but finitely many $a_g$ are equal to $0$, and hence for all but finitely many $a$ we have $\sum_{g \in aH} a_g = 0$, so all sums above are finite sums. Did I overlook something (besides the dirty notation)?
Comment: Ahh, right. There does seem to be something missing in the second displayed equation (it has no mention of $\varphi$ it seems).
Comment: You're right, will add the $\phi$, thanks.

group algebra and kernel


How to downweigh outlier in a sum?

Question: I have a simple problem.
Assume following dataset:
resids <- c(, 9, 8, 7, 12, 14, 8, 9, 15, 4, 9, 10, 200)
n <- length(resids)
p <- 2

Using this dataset I want to estimate:
Phi.P <- sum(resids^2)/(n-p)

We see that the variable 'resids' contain an outlier with value 200. This outlier will cause the estimate of Phi.P to be too high. So I used a robust estimator based on the median:
Phi.P <- median(resids^2)*(n/(n-p))

This works OK but not extremely good. Therefore I am looking for a way do downweight the outlier in sum(resids^2). Does anybody know how to do this?
Comment: why are you dividing by n-p? are those resid, residuals of some regression function? In that case you might consider a robust regression. See rlm from the MASS package of R.
Comment: Can't really answer this question without knowing why 200 is considered an "outlier".  The code fragment suggests it is a residual, in which case it may not be an outlier but an indicator of a serious problem with a model, in which case you probably don't want to downweight it.  Especially as it is apparently a squared residual.
Comment: A simple way to lower the influence of outliers in a mean is to eliminate values above/below certain percentiles. The trimmed mean is an example of this.
Answer: One problem with the median is that it's not a smooth function, which can make optimizing things difficult. Several alternative robust estimates are available Tukey's bisquare and the huber loss function are both popular. You may also want to consider a trimmed mean.
From the syntax in your post it looks like you are using R. In R, the trimmed mean is implemented as mean(trim=). The other two I mentioned are implemented in the robust package in robust::psi.weight.
Comment: `sum( yourvector * yourweights ) / sum(yourweights)`
Comment: Thank you for the response. The purpose is to downweight the outlier already in the sum., so weights should be used in the sum. Can this be obtained using psi.weight?
Comment: robust::psi.weight(x) returns the weighted vector. The weights would be given by robust::psi.weight(x)/x
Comment: And how can these weigst be used in the sum? Since the sum command does not have weight option.
Answer: I don't understand exactly what do you want estimate. If you want approximative value of the variable 'resids' or value of sum(resids^2)/(n-p) and I don't know why you use this variable 'p'.
But if you want estimate the approximative value of 'resids', you can use the geometric mean, it works well even if your numerical vector ('resids') contains an outlier as we can see in this example below:
# Geometric mean function
fGeometric <- function(x) {
  n <- length(x)
  Moy <- prod(x)^(1/n)
  return(Moy)
}

resids <- c(1,4,3,2,5,3,1,6, 4, 990)

fGeometric(resids)

[1] 4.934179

**********************************************************
# An other values of the numerical vector for example:

resids<-c(16,9,8,7,12,14,8,9,15,4,9,10,1257)

fGeometric(resids)

[1] 13.8061

Hope it can help you...;-)

How to downweigh outlier in a sum?


ELB is as slow as its Idle Connection Timeout setting

Question: I'm trying out ELB with a minimal configuration (HTTP 80 -> 3000), and for one just one EC2 instance.
(I know that normally one would put at least two EC2 instances, but I'm just assessing ELB.)
I've noticed that under this setup (which I assume I've configured correctly - maybe I missed something), the response time will be exactly as slow as the Idle Connection Timeout setting I specified.
For example if the setting is 30 seconds, and I visit elb-XXXXXXXXX.eu-west-1.elb.amazonaws.com, my browser will have to wait 30 seconds for the page to load.
Same for 2, 5, 60 seconds.
Set to 1 second, I don't have to wait 1 whole second though - I can continuously re-request the page (i.e. keep the Refresh keyboard shortcut held) and I see no hiccups.
So leaving the setting to 1 seconds can be tempting - is it advisable though?
Can I get to use the recommended setting (60 seconds) with just one EC2 instance behind ELB without experiencing slowness?
Comment: If, for example, your application writes data to the client without using chunked transfer encoding or sending an accurate content-length header, the browser could wait until the connection is closed before concluding the content has been received.  I would suspect something like this based on what you have described so far.
Comment: Definitely not normal.  I have something like 30 different ELB deployments and have never encountered this.  It sounds as if your application is not behaving correctly, but in a way that is masked during direct connections.
Comment: Indirectly, yes, if the application is behaving in a not-quite-correct fashion in its handling of the http protocol.  It might be worth your trouble to install nginx on the instance and proxy the traffic through it to your app, as it might correct any subtle protocol issue for you, as well as potentially maintaining keepalives between itself and the ELB. That's a pretty common configuration with a bonus of having it handle any static files directly.
Comment: Now I just associated 5 additional EC2 instances with ELB, and the issue persits. So the problem doesn't seem to have to do with the actual number of instances behind ELB.
Comment: Thanks so much for the insight. What kind of problem might my application (or EC2 instance) have? It's always accessed by the same port (3000), whether it's via ELB or directly. Only slow when via ELB.
Comment: The content-length header was missing, but setting it made no difference sadly. Using chunked transfer encoding is quite more complex to setup, it's not easily available in Ruby on Rails so I don't think that can be the cause...?
Comment: One thing that I've noticed is that the EC2 server returns `Connection: close` header (keepalive is not supported in the server I want to use). Might that be the cause?
Comment: Yes, precisely I was thinking doing that setup. Thanks so much!
Answer: Apparently, an application server (Unicorn in my case) generally must not talk directly to ELB - it must do it behind a highly specialized HTTP server such as Nginx. This is particularly true for serving static files - one does not want those to be served by Ruby!
Unicorn in particular assumes 'fast clients', a guarantee that only nginx can fulfill - not ELB.
Doing so fixed my issue.


Have 2 NCAA basketball teams ever played each other 5 times in a season?

Question: Two NCAA basketball teams from the same conference could play each other 5 times in one season.  This would happen if:

They played each other in an early season tournament.  (You can see this year's Battle 4 Atlantis tournament includes Butler and Georgetown - both from the Big East conference.)
They played each other twice as part of the conference's regular season schedule.
They played each other in the conference tournament.
They played each other in a postseason tournament like the NCAA Tournament, NIT, CBI, or CIT.

Has this ever happened?  Have two college basketball teams ever played each other 5 times in one season?
Comment: Unfortunately, I can't seem to find a good data source to search this - Sports Reference only goes back to 2010 on single game box scores, and searching schedules is very messy if you want to get _all_ schools.  Not sure how easy it'll be to get the full thing.
Comment: Even a conference of 8 schools will find 14 conference games among them (which is around what most schools play - 14 to 18).  Currently there aren't any conferences smaller than that.  It's certainly possible that edge cases existed (where a conference was coming into or phasing out of existence, for example), but I don't think < 8 school conferences are normally in existence.
Comment: @Oldcat In fact, the most recent defunct conference (the Great West conference) had only five schools in the 2012-13 season, and yet teams played 2 conference games versus each other (so 8 total conference games).  See [Chicago State](http://www.sports-reference.com/cbb/schools/chicago-state/2013-schedule.html) for example.
Comment: Why do you assume that teams in a conference only play twice? A small conference might play 4 games inside the conference to avoid having to find dozens of non-conference games.
Answer: I found an article at RPIRatings.com that has a list of college basketball teams that have played each other 4 or more times in one season.  It is not a comprehensive list, but it is still pretty impressive as it has data going back as far as 1906.
The article says:

Note that many of the teams in the following list are from the present-day Big 12 and Pac-10 conferences. Several of these teams had long travels to play games, especially before 1940, and it was common then to play a visiting team twice and then return the favor with a pair of games.

Based on their list (which includes the home, road, and neutral site records) it seems that up until the early 1970s, teams in certain conferences played each other 4 times during the conference's regular season.  During that time, there were quite a few instances of 2 teams playing each other 5 or 6 times in one season, and one instance of 2 teams playing each other 7 times in one season.
But the article has a separate list of teams that have played each other at least 4 times in a season since 1975.  I presume that since 1975, no conference has had their teams play each other 4 times during the regular season.  Since 1975, there have been no teams that have played each other 5 times in one season.


Integral functional equation.

Question: $f(x)= \Big(\int _1^x g_1(t)g_2(t)dt\Big)\Big(\int _1^x g_3(t)g_4(t)dt\Big)-\Big(\int _1^x g_1(t)g_3(t)dt\Big)\Big(\int _1^x g_2(t)g_4(t)dt\Big) $ $\forall$  $x$ $\in R$
Where $g_1(x),g_2(x),g_3(x)$ and $g_4(x)$ are non constant continuous and differentiable functions and $f(x)$ is a polynomail of degree $4$ with leading coefficent $1$.
ATTEMPT: Let $f(x)=x^4+bx^3+cx^2+dx+e.$
Then by Leibntiz's rule, $f'(x)=\Big( g_1(x)g_2(x)\Big) \Big(\int _1^x g_3(t)g_4(t)dt\Big)+\Big( g_3(x)g_4(x)\Big) \Big(\int _1^x g_1(t)g_2(t)dt\Big)-\Big( g_1(x)g_3(x)\Big) \Big(\int _1^x g_2(t)g_4(t)dt\Big)-\Big( g_2(x)g_4(x)\Big) \Big(\int _1^x g_1(t)g_3(t)dt\Big)$
However where do I employ the given conditions to get the answer?
Should I consider the integrals of $g_1(x),g_2(x),g_3(x)$ and $g_4(x)$ as $G_1(x),G_2(x),G_3(x)$ and $G_4(x)$ and try equating the coefficients of$x$?
Answer: Maybe there is a better method (well, there has to be); this one is very tedious but it works:
1) Evaluate $f(1)=0$.
2) Evaluate $f'(1)=0$.
3) Evaluate $f''(1)=0$.
4) Evaluate $f'''(1)=0$.
5) Evaluate $f''''(1)=$:
$$
\frac{1}{2}f''''(1)=g_1'(1)g_2'(1)g_3(1)g_4(1)-g_1'(1)g_2(1)g_3'(1)g_4(1)-g_1(1)g_2'(1)g_3(1)g_4'(1)+g_1(1)g_2(1)g_3'(1)g_4'(1)
$$
With this in mind, and if you are certain that $f(x)$ is a fourth-degree polynomial, then we can say that
$$
f(x)=f(1)+(x-1)f'(1)+\frac{1}{2}(x-1)^2f''(1)+\frac{1}{3!}(x-1)^3f'''(1)+\frac{1}{4!}(x-1)^4 f''''(1)=
$$
$$
=\frac{1}{12}(x-1)^4 \bigg[g_1'(1)g_2'(1)g_3(1)g_4(1)-g_1'(1)g_2(1)g_3'(1)g_4(1)-g_1(1)g_2'(1)g_3(1)g_4'(1)+g_1(1)g_2(1)g_3'(1)g_4'(1)\bigg]
$$
I know this is not a very nice answer, but I believe its good enough for now, until any other one here post something better.
Comment: Thanks for the hint. But we can simply solve 4 equations in $b,c,d$ and $e$ by using the fact that $f(1),f'(1),f''(1)$and $f'''(1)=0$ to give $f(x)=(x-1)^4$
Comment: Yes, youre absolutely right (I didnt realise you were told that the leading coefficient was one, so I needed a fifth equation to solve for five unknowns)

Integral functional equation.


How to fetch a field's values from a lot of nodes?

Question: I need to create a list of all submitted values from a field named field_telephone from thousands of nodes from a specific content type.
using the node_load() function takes long time.
What is the fastest way to fetch the field's values?
Answer: You can also use field_attach_load, I believe you can pass it just 1 field you want and a set of entity ids and you can get back all the values. The below example is taken from this blog post and I take no credit for the code:
$query = new EntityFieldQuery();
 $query->entityCondition('entity_type', 'node')
   ->entityCondition('bundle', 'article')
   ->propertyCondition('status', 1)
   ->fieldCondition('field_image', 'fid', 'NULL', '!=');
 $results = $query->execute();
 $articles = $results['node'];
 $fields = field_info_instances('node', 'article');
 $field_id = $fields['field_image']['field_id'];
 field_attach_load('node', $articles, FIELD_LOAD_CURRENT, array('field_id' => $field_id));

Answer: The fastest (but not sanctioned/recommended) way would be to go directly in the database table to get the data:
// db_query() is quicker than db_select() so if you're going for performance,
// build up an SQL string
$sql = '
  SELECT f.entity_id, f.field_telephone_value
  FROM {field_revision_field_telephone} f
  WHERE f.entity_type = :entity_type
  AND f.bundle = :bundle';

// Set some args up for your query
$args = array(':entity_type' => 'node', ':bundle' => 'content_type');

// Extract the query results into an array keyed by nid
$data = db_query($sql, $args)->fetchAllKeyed();

There are many good reasons not to do this kind of thing directly (no support for translations, it will only work if the field storage engine is MySQL, etc.)
Any other method I can think of would involve a call to node_load() or node_load_multiple() at some point.
Comment: you may be interested in my answer below for a non-sql way to achieve this for a set of entity ids.


How show active call between sip to sip in asterisk?

Question: When I type "core show channels" I get a channel for the current calls through DAHDI but I want see calls between sip to sip too.
Answer: Use http://asternic.org or some other panel project already writed.
btw, core show channels show all calls, including sip. If you not see sip calls, you have set on your peer
<code>canreinvite=no
</code>


How to get Alt + C(or any other key) to work in JavaScript on Chrome for Mac and windows

Question: I have tried following code,
window.onkeypress =  function(event){

   if(event.altKey && (event.keyCode == 99 || event.keyCode == 67)){

      alert("alt + C pressed")
   }
}

How ever It doesn't work!
I tried alert(event.keyCode) per keypress and it seems when I press opt/alt key on Mac, I get a different keycode other than 99 or 67 with the combination.
Whats the correct way to achieve this ?
Comment: Got it, on Mac option plus other key combination generates different characters that's why!

opt + c prints ç on TextEdit, thats why a different keyCode.
Comment: possible duplicate of [How does one capture a Mac's command key via Javascript?](http://stackoverflow.com/questions/3902635/how-does-one-capture-a-macs-command-key-via-javascript)
Comment: I have seen and tried that example. command key is working fine. I have a problem with alt!
Answer: Try using the keydown or keyup handler. In that case 'c' = keyCode 67:
window.onkeydown = function(e) {
    e = e || event;
    if (e.altKey && e.keyCode === 67) {
        console.log("alt+c pressed!");
    }
}

jsfiddle
Comment: Doesn't work on the iMac keyboard. Option + key is generating a different character and keyCode value wont remain 67 or 99!
Comment: I wanted to launch a popup with that key combination, I think I will resort to cmd + shift + c instead!
Comment: Maybe http://stackoverflow.com/questions/3902635/how-does-one-capture-a-macs-command-key-via-javascript offers a solution?


Problema com programa em C

Question: Estou resolvendo um exercício que pede para ler um vetor de 20 posições e imprimir na tela excluindo valores repetidos, consegui resolver porem, ele esta mostrando os valores na tela varias vezes.
<code>#include <stdio.h>
#include <stdlib.h>

int main()
{
 int vet[20], x;
 for(int i = 0; i < 20; i++)
 {
     printf("Digite um numero: ");
     scanf("%d", &vet[i]);
 }
 for(int i = 1; i < 20; i++)
 {
    for(x = 0; x < 20; x++)
    {
       if(vet[i] != vet[x])
       {
          printf("\n%d", vet[x]);
       }
    }
 }

}
</code>
Answer: Uma pequena alteração em seu programa melhora esta solução:
<code>#include <stdio.h>
#include <stdlib.h>

int main() {
    int vet[20], x, repete;
    for(int i = 0; i < 20; i++) {
        printf("Digite um numero: ");
        scanf("%d", &vet[i]);
    }
    for (int i = 0; i < 20; i++) {
        repete = 0
        for(x = 0; x < 20; x++) {
            if(i != x && vet[i] == vet[x]) {
                repete++;
            }
        }
        if (repete == 0)
            printf("\n%d", vet[x]);
    }
    return 0;
}
</code>
Comment: Valeu mesmo, tava quebrando a cabeça aqui por uma coisa tão simples kkkkk

Problema com programa em C


Prove that there are no analytic function satisfying this property

Question: This kind I'm kindly asking you to help me in solving this question:

Prove that there are no analytic functions $f:\mathbb R\to \mathbb R$ such that $$f\left(\frac 1n\right)=\frac{(-1)^n}{n^2},$$ for every $n\in\mathbb N$.

Thank you very much in advance for any hint because I'm out of ideas.
Regards
Comment: Hint: Where can you infer that $f(x)=0$? What do you know about zeros of analytic functions?
Answer: In fact there is no $f$ two times differentiable in a neighborhood of $0$ such that $f(n^{-1})=\frac{(-1)^n}{n^2}$. Indeed, if $f$ is such a function, then $f(0)=0$, $f'(0)=\lim_{n\to \infty}nf(n^{-1})=\lim_{n\to\infty}\frac{(-1)^n}n=0$ and $f''(0)=\lim_{n\to\infty}n^2f(n^{—1})$ but the last limit is the limit of $(-1)^n$, which doesn't exist.
Answer: Hint $f(z)=z^2$ for all $z=\frac{1}{2m}$, and this sequence has an accumulation point.
But $f(\frac{1}{2m+1})=- (\frac{1}{2m+1})^2$.
Answer: $f(x)=x^2\cos\left(\frac{\pi}{x}\right)$ satisfies the given condition on $\mathbb{N}$, but is not analytic at $x=0$.  Its analytic continuation to $\mathbb{C}$ has an essential singularity at $0$.
Since an analytic function is continuous, the Intermediate Value Theorem says that, since $f$ changes sign between $\frac1n$ and $\frac{1}{n+1}$, there is a sequence $\{x_n:\frac{1}{n+1}< x_n<\frac1n\}$ so that $f(x_n)=0$. Since $\lim\limits_{n\to\infty}x_n=0$, the set of zeros of $f$ has $0$ as a limit point. If the set of zeros of an analytic function has a limit point in the domain of said function, the function is identically $0$ on the connected component of that domain containing that limit point.
Answer: suppose such $f$ were exist, define $g(z)= f(z)- (-1)^nz^2$ which is also holomorphic, but $g(1/n)=0\forall n$ and Uniqueness theorem says that $g(z)\equiv 0$, $f(z)=(-1)^nz^2$ but which is not unique, so no such analytic function cant exist.
Comment: What exactly is your $g$? It seems to depend on $n$...


Sympa sending problems with attachments

Question: I have set up a Sympa list serv server and everything is working fine for the most part. One issue that I am running into is sending files over ~580 KB in size (just a normal .txt file) are not going through. I am getting the following error.

Impossible to distribute your message
  for list 'list-name' because of an
  internal server error.

I have verified that my "Maximum message size (max_size)" setting in Sympa is get to 5 MB so that shouldn't be the problem. If I try sending the same .txt file after taking out a few lines, and the file size is ~530 KB, then it works just fine. Any help would be greatly appreciated.
Comment: Do you have some interesting logs in Sympa ?
Comment: Nothing that's really jumping out to why that error is occurring.
Answer: Got it fixed.
It was a problem with the database not being able to handle the packet size. I had to manually edit the /etc/my.cnf file and bump up the max_allowed_packets size and then restart mysqld.
Answer: I'd say this has something to do with php settings variables upload_max_filesize and memory_limitphp. They're normally somewhere in php.ini, depending on your OS and Webserver.
Comment: Sympa is written in Perl, not PHP. I don't know anything about upload limits in Perl, but I'd be willing to guess you're right about there being an upload size limit somewhere.
Comment: Oh, hmm, you're right, I'm confusing sympa and phplist.
Comment: It could be, but the only real "max file size limit" setting I see is the one I mentioned in the original post and it is set to 5 MB. The entire email including the .txt file attachment is less than 1 MB.

Sympa sending problems with attachments


How to install and use mongodb with node js?

Question: I am very new to MongoDB and node.
So first of all:

How can I install MongoDB using the terminal on a Mac computer
Then how can I connect MongoDB with node?
How can I create a database in MongoDB using node?
Any help is appreciated. Thank You.
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:8080/mydb";
MongoClient.connect(url, function(err, db){
if(err)
{
  console.log('error');
  throw err;
}
else
{
   console.log('success');
}
});

I tried this code but it shows an error.
This is the error I received:
Comment: have you started the mongodb service ?
Comment: You have to start mongo server in your computer and then only you will able to connect it to the client.
Comment: Default port for mongodb is 27017 so your url should be like mongodb://localhost:8080/mydb
Answer: You have to open the MongoDB server first.
Do this:

Go to the directory where mongo is installed: i.e.: <mongodb-install-directory>/bin
Start the server by : ./mongod --dbpath <mongo-data-directory>
Comment: how can I know where I installed mongoDB
Comment: Thank you I got it.


how to write a bar chart for the datas in the mysql in java

Question: i have succefully inserted data inside the mysql using xml dom parsing now i want to display the mysql data on my bar chart, so please help with the proper code.
my database has 4 columns, namely "name", "college", "grade", "nature"
so i  have inserted 4 different names and out of 4 names, 2 are sharing the same college. each one are having different grade like good bad and medium. same goes with the grade as well, like first, second, third. So now i need to write the bar chart for this. please help me out.
Comment: You have to collect the raw data i.e the numbers by using a select on the rows.Save the numbers and then draw the chart as you have numbers now.
Comment: Draw a bar chart, or write?
Comment: draw a bar charthttp://stackoverflow.com/users/1820722/joey-rohan
Comment: And that link was for?May be you can use javaFX or swing..to draw..Enough tutorials.Search google.
Comment: i searched it but there is no code which uses mysql. and i am new to this forum.
Comment: thank you for the instant reply, can you help me wit the code if you do not mind, i am not getting any idea, since i am new to java.
Answer: Here I have done an example.

Extract database values and store in the array's work[] and values[] .
Use a container as per your needs
I have used JApplet

import java.awt.*;
import javax.swing.JApplet;

public class BarChart extends JApplet
{
    private final  int n=5;
    private String work[];
    private int value[];

    @Override
    public void init()
    {

        work = new String[n];
        value = new int[n];

        work[0] ="name";
        work[1] = "college";
        work[2] = "grade";
        work[3] = "nature";
        work[4] = "extra";

        value[0] = 20;
        value[1] = 10;
        value[2] = 4;
        value[3] = 15;
        value[4] = 5;

    }

    @Override
    public void paint(Graphics g)
    {
        Font font = new Font("Arial",Font.BOLD,15);
        g.setFont(font);
        for(int i  = 0; i < n; i ++)
        {
            g.setColor(Color.BLUE);
            g.drawString(work[i], 20, i * 50 + 30);
            g.setColor(Color.RED);
            g.fillRect(70, i * 50 + 10, value[i], 40);
            g.drawString(String.valueOf(value[i]) + "%", 180, i * 50 + 35);
        }

    }
}

EDIT :
For your select stmt., I went to google and typed - select query msql java
and I got this :
+----+------------+-----------+---------------------+----------+------------+
| id | first_name | last_name | date_created        | is_admin | num_points |
+----+------------+-----------+---------------------+----------+------------+
|  2 | Fred       | Flinstone | 2010-06-23 00:00:00 |        0 |       6000 |
|  3 | Barney     | Rubble    | 2010-06-23 00:00:00 |        0 |       5000 |
+----+------------+-----------+---------------------+----------+------------+

import java.sql.*;

/**
 * A Java MySQL SELECT statement example.
 * Demonstrates the use of a SQL SELECT statement against a
 * MySQL database, called from a Java program.
 *
 * Created by Alvin Alexander, http://devdaily.com
 */
public class JavaMysqlSelectExample
{

  public static void main(String[] args)
  {
    try
    {
      // create our mysql database connection
      String myDriver = "org.gjt.mm.mysql.Driver";
      String myUrl = "jdbc:mysql://localhost/test";
      Class.forName(myDriver);
      Connection conn = DriverManager.getConnection(myUrl, "root", "");

      // our SQL SELECT query.
      // if you only need a few columns, specify them by name instead of using "*"
      String query = "SELECT * FROM users";

      // create the java statement
      Statement st = conn.createStatement();

      // execute the query, and get a java resultset
      ResultSet rs = st.executeQuery(query);

      // iterate through the java resultset
      while (rs.next())
      {
        int id = rs.getInt("id");
        String firstName = rs.getString("first_name");
        String lastName = rs.getString("last_name");
        Date dateCreated = rs.getDate("date_created");
        boolean isAdmin = rs.getBoolean("is_admin");
        int numPoints = rs.getInt("num_points");

        // print the results
        System.out.format("%s, %s, %s, %s, %s, %s\n", id, firstName, lastName, dateCreated, isAdmin, numPoints);
      }
      st.close();
    }
    catch (Exception e)
    {
      System.err.println("Got an exception! ");
      System.err.println(e.getMessage());
    }
  }
}

Comment: @RajeshAcharya You should first check that : `if(grade is second) {marks=2} ` and so on. Then put marks in `value[]` array
Comment: God! how i will know what is your dataBase, tables, values..do u know the code how to get make select stmt.?
Comment: you have been a  greatest help and i really appreciate your patience..let me check that.
Comment: now i edited my database to get more clarity, so i have only 2 column now, one is name and other one is grade. name column has "gary" "ray" "chris" and their grade is "first", "second", "first". now i want to draw the bar chart using the above database value, it should be like in the x axis name should be there  and in the y  axis grade should be mentioned.


Understanding the proof of Yoneda Embedding

Question: Definitions
Recently I was going through the proof Yoneda Embedding from Steven Roman's An Introduction to the Language of Category Theory. But before I go into the problem that I am having with the proof let me first state Roman's definition of an embedding (I do so because according to this there is "no satisfactory and generally accepted definition of embeddings that is applicable in all categories").

Let $\mathcal{C},\mathcal{D}$ be two categories and $F:\mathcal{C}\to\mathcal{D}$ be a functor. Then,
Definition 1. The restriction of $F$ to $\text{hom}_\mathcal{C}(A,B)$ as a local arrow part of $F$ and by the object part of $F$ we mean $F:\text{Obj}(\mathcal{C})\to\text{Obj}(\mathcal{D})$ where $\text{Obj}(\mathcal{C})$ and $\text{Obj}(\mathcal{D})$ denotes the set of objects of respectively $\mathcal{C}$ and $\mathcal{D}$.
Definition 2. $F$ is full if all of its local arrow parts are surjective.
Definition 3. $F$ is faithful if all of its local arrow parts are injective.
Definition 4. $F$ is fully faithful if all of its local arrow parts are bijective.
Definition 5. $F$ is an embedding of $\mathcal{C}$ in $\mathcal{D}$ if it is fully faithful and the object part of $F$ is injective.

Background
Now let me come directly to my problem. What I was going through is the following theorem (number unaltered),

Theorem 48
Let $\mathcal{C}$ be a category. The contravariant functor $y: \mathcal{C} \to \sf{Set}^\mathcal{C}$ defined by,
  $$y(A)=\text{hom}_\mathcal{C}(A,\cdot)$$and, $$y(h)=\{{h_X}^\rightarrow\}:\text{hom}_\mathcal{C}(A,\cdot)\to\text{hom}_\mathcal{C}(B,\cdot)$$for all $A\in\mathcal{C}$ and all $h\in\text{hom}_\mathcal{C}(B,A)$
  is a contravariant embedding of $\mathcal{C}$ into the functor
  category $\sf{Set}^\mathcal{C}$, called the Yoneda embedding of $\mathcal{C}$ in $\mathsf{Set}^\mathcal{C}$.

Where ${h_X}^\rightarrow:\text{hom}_\mathcal{C}(A,X)\to\text{hom}_\mathcal{C}(B,X)$ defined by, $${h_X}^\rightarrow(g)=g\circ h_X$$
In the proof he writes,

The object part of $y$ maps $A$ to $\text{hom}_\mathcal{C}(A,\cdot)$ and since $\text{hom}_\mathcal{C}(A,\cdot)$ and $\text{hom}_\mathcal{C}(B,\cdot)$ are distinct for distinct objects $A$ and $B$, the object part of $y$ is injective.
As to injectivity, if $y_{A,B}(h) = y_{A,B}(k)$ for $h,k: B \to A$, then
$$\{h_X^\to:X\in\mathcal{C}\}=\{k_X^\to:X\in\mathcal{C}\}$$
In particular, for the components associated with $X=A$, we can apply them to $1_A$ (the identity morphism from $A$ to $A$) to get
$$1_A ∘ h = 1_A ∘ k$$
and so $h = k$.

My Questions

How does it follow that $A\ne B$ implies that $\text{hom}_\mathcal{C}(A,\cdot)\ne\text{hom}_\mathcal{C}(B,\cdot)$?
If $\{h_X^\to:X\in\mathcal{C}\}=\{k_X^\to:X\in\mathcal{C}\}$ then all we can say is the following, $$1_A ∘ h_Y = 1_A ∘ k_Z$$for some $Y,Z\in\mathcal{C}$. Why can we remove the subscripts?
Comment: So much about the terminology and notation here (presumably from Roman) makes me sad...
Comment: Definitions 2 and 3 are wrong : 2 should be faithful and 3 should be full.
Comment: 1) If $A\not = B$, no $f\colon  A \to X$  equals  any $ g\colon B \to X$, because  part of the defining data of a 'function' (ok, arrow) is its domain (ok, source). 2) You're being confused by the set notation $\{ \cdot \}$, I think. Think "components" $(\cdot, \cdots, \cdot )$. A function on a product space is equal iff it's equal on each of the components.
Comment: Namely, despite the notation, for each $X$, $h_X: {\rm hom} (A, X) \to {\rm hom} (B, X)$. It makes no sense to mix different components $X$ and $Y$, as you seem to be doing. In the case of the proof, the component is $X=A$.
Comment: @ArnaudD.: Yes. You are right. Sorry for the typo.
Comment: @peterag Note that this works even if we don't explicitly include the domain as part of the data defining $f$: the domain is determined by its graph $\{\langle a, f(a)\rangle: a\in dom(f)\}$ (unlike the codomain).
Comment: @NoahSchweber - Perhaps I shouldn't have said 'function' - but I had wanted to bring the level of abstraction down. Still,  I really wanted the OP to think 'arrow,' which always comes with a specific source and specific target...
Comment: @NoahSchweber - and I always like trotting out, in this context, an old quote/quasi-joke of a category theory friend  of mine. "The Yoneda lemma is a tautology: the statement of Yoneda is 'An object is determined by the arrows from it.' The proof of Yoneda is 'in particular, it's determined by the identity.'"
Comment: @peterag: I have understood your comment [here](https://math.stackexchange.com/questions/2552256/understanding-the-proof-of-yoneda-embedding?noredirect=1#comment5269025_2552256) as follows, please let me know if I have misunderstood your comment.
Comment: If possible let us suppose that $A\ne B$ but $\text{hom}_\mathcal{C}(A,\cdot)=\text{hom}_\mathcal{C}(B,\cdot)$. Then for all $X\in \mathcal{C}$ we would have, $$\text{hom}_\mathcal{C}(A,\cdot)(X)=\text{hom}_\mathcal{C}(B,\cdot)(X)\implies \text{hom}_\mathcal{C}(A,X)=\text{hom}_\mathcal{C}(B,X)$$for all $X\in\mathcal{C}$. However this would then imply that if $f\in \text{hom}_\mathcal{C}(A,X)$ we must also have $f\in \text{hom}_\mathcal{C}(B,X)$. In other words we must have both $f:A\to X$ and $f:B\to X$. However since each arrow has an unique source, we must have $A=B$, contradiction.
Comment: However I don't understand [this comment](https://math.stackexchange.com/questions/2552256/understanding-the-proof-of-yoneda-embedding?noredirect=1#comment5269060_2552256). Can you elaborate a bit more?
Comment: See below for a response -
Answer: Yes - you understood my comment on 1. Point 2, is similar. Namely: Suppose we are given $h\colon B \to A$. Then $h$ induces, for each $X$, a  function $$h_X\colon {\rm hom} (A, X) \to {\rm hom }( B, X), $$ defined by the rule $ h_X (g) = g \circ h $. [No subscript on the right.]
[ Continuing the proof of Yoneda - although you're not asking for it: ]
Suppose we  are given 'another' morphism $k\colon B \to A$ (same source and target as $h$).
That means that we  now have, for  each $X$, two functions
 $$h_X,k_X \colon {\rm hom} (A, X) \to {\rm hom }( B, X). $$
But what  happens, if for each $X$, $h_X$ and $k_X$ coincide? That is, what happens if, for each $X$,  $$h_X = k_X?$$
Then the  previous equality holds, in particular, with $X=A$. That is,  $$h_A = k_A.$$
That means, for every $g\in {\rm hom} (A, A)$, that
$$ h_A (g) = k_A(g),$$ or equivalently $g \circ h = g \circ k$. In particular, we can take $g= 1_A$. Therefore $1_A\circ h = 1_A\circ k$, and $h = k$ - and we are done.
To summarize: if $h_X=k_X$ for every $X$, then $h_A=k_A$, so that $h_A(1_A)=k_A(1_A)$, so that $1_A\circ h = 1_A\circ k$, so that $h=k$.
[This answer was a follow-up to a comment above - but was itself too long for a comment.]
Comment: Excellent!. That's exactly what I wanted. Many thanks also for continuing the proof of Yoneda Lemma (even though I didn't ask for that).
Comment: @user170039 I haven't listened to the following in a while, but I remember enjoying Eugenia Cheng's  cat theory lectures, and you might too: https://www.youtube.com/user/TheCatsters/videos
Comment: If $h_X=k_Z$ (using your notation) for some $X,Z\in\mathcal{C}$ then in particular for $X=A$ we would have $h_A=k_Z$ for some $Z\in\mathcal{C}$ and this would imply that $$h_A(1_A)=k_Z(1_A)\implies 1_A\circ h=1_A\circ k\implies h=k$$Is there anything wrong in this alternative argument?
Comment: I mind it because it doesn't make much sense to write $h_X= k_Z$ unless $X= Z$ - two functions can, a priori, only be compared (e.g. the above equal sign) if they have the same source and target, e.g.,   it makes no sense (without something else going on) to compare a function which takes  values in (or has as source) a finite field with another function which takes values in (or has as source)  three dimensional euclidean space. (cont)
Comment: (cont ) Likewise, I would say that it is syntactically incorrect to write "$h_Z(1_A)$"  unless  $Z=A$ to begin with, because $1_A$ is in the domain only of $h_A$. Do you see what I mean?  For instance, in a 'strict type' programming language, I would expect that "$h_Z(1_A)$" would give a compilation error. It might be interesting to try that out in Haskell - if that idea/test makes sense. I might try it out, or bring it up on the haskell stack exchange... If I do, I'll let you know.
Comment: I agree with everything that you said. My point simply was to assume that $h_X=k_Z$ for some $X,Z\in\mathcal{C}$ and then prove that $X=Z$ and finally conclude that (as you have done in your answer), $h=k$. (I reposted the comment because just now I noticed that I have made a typo in the now-deleted comment which needs to be corrected.)


Extending Symfony2 Controller Resolver

Question: I am currently creating a bundle which can rename fooAction into fooAjaxAction if request is an Ajax Request.
As the answer of that question says, I have to extend the controller resolver class.
I have a ResourceNotFoundException if I change the controller_resolver.class in config.yml . but if I don't, I don't have any errors (but there is no override so this is not what I want)
My questions are : how can i register my new controller resolver and use it ? I am right ? Wrong ?
This is what I've done :
You can find my Bundle for testing in packagist and download it via :
composer require  "/prefix-bundle":"dev-dev"
activate it in AppKernel.php:
<?php
// AppKernel.php
new \PrefixBundle\PrefixBundle()

Config
# App/Config/config.yml
parameters:
    controller_resolver.class: PrefixBundle\Component\Controller\ControllerResolver

So this is my custom Controller.
<?php
namespace \PrefixBundle\Component\Controller;

use Symfony\Component\HttpKernel\ControllerControllerResolver as BaseControllerResolver;
use Symfony\Component\HttpFoundation\Request;

class ControllerResolver extends BaseControllerResolver
{

    public function getArguments(Request $request, $controller)
    {
        parent::getArguments($request, $controller);
    }
}

I am assuming that this controller is doing nothing for instance, I will add logic in the future.
Comment: My question is : how can i register my new controller resolver and use it ? - edited
Comment: What exactly is the question?
Comment: What namespace are you using for your controller resolver? I got it wrong in my original answer but I will update now.
Comment: updated code, didn't copy the namespace
Comment: Yeah just realised and went through your github. I didn't put the `return` before `parent::getArguments` so the method is doing nothing. Not sure why the controller resolver can't be found though. or is it that controller aren't being found when using this resolver?
Comment: that was that, missign return, answer if you want
Answer: The return is missing from the getArguments method (due to me missing it when I did the other answer) meaning that the controller resolver isn't actually getting any arguments to resolve.
public function getArguments(Request $request, $controller)
{
    // Should have the return..
    return parent::getArguments($request, $controller);
}

Comment: Thanks a lot ! I have spent all night at that. Have a nice day !
Comment: I really should have gotten it right the first time, to be fair.

Extending Symfony2 Controller Resolver


Xen Vif creation xl vs xm

Question: Hi everyone,
I switch my server from a xend/xm Xen install to a 4.1 xl Xen install.
Therefore Xen does not create vif network interface when I launch xl create /etc/xen/my_server.cfg but does create vif network interface with the  command xm create /etc/xen/my_server.cfg
Here are sample configuration:
nano /etc/xen/xl.conf
vifscript="vif-bridge"

nano /etc/xen/xend-config.sxp
(network-script network-bridge)
(vif-script vif-bridge)

nano /etc/default/xen
TOOLSTACK=xl

Any idea ? I'm lost :-(
Best Regards.

[EDIT] I do not undertand but after several changes it is working now,
  here we go:
nano /etc/xen/xl.conf # Use the whole path not just vifscript="vif-bridge" I think the problem was there...
vifscript="/etc/xen/scripts/vif-bridge"

Network on the HOST:
# The primary network interface
auto  xenbr0
allow-hotplug  xenbr0
iface xenbr0 inet dhcp
bridge_maxwait 5
bridge_ports eth0

# The secondary network interface
auto  xenbr1
allow-hotplug  xenbr1
iface  xenbr1 inet dhcp
bridge_maxwait 5
bridge_ports eth1

nano  /etc/xen/xend-config.sxp # No network script sets...
(dom0-min-mem 196)
(enable-dom0-ballooning yes)
(total_available_memory 0)
(dom0-cpus 0)
(vncpasswd '')

Network VM interface with IP failover XXX.XXX.XXX.XXX > IP FO  YYY.YYY.YYY.YYY > IP HOST
#The primary network interface

auto eth0 iface eth0 inet static
address XXX.XXX.XXX.XXX
netmask 255.255.255.255

post-up route add YYY.YYY.YYY.YYY/32 dev eth0
post-up route add default gw YYY.YYY.YYY.YYY

VIF HOST Created by XL vif8.0
Link encap:Ethernet  HWaddr fe:ff:ff:ff:ff:ff
inet6 addr: fe80::fcff:ffff:feff:ffff/64 Scope:Link
UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
RX packets:1336 errors:0 dropped:0 overruns:0 frame:0
TX packets:14342 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:32
RX bytes:81534 (79.6 KiB)  TX bytes:1268787 (1.2 MiB)

nano /etc/xen/my_server.cfg
vif         = [ 'ip=XXX.XXX.XXX.XXX ,mac=XX:XX:XX:XX:XX:XX,bridge=xenbr0']
And its' OK ! Regards !

If you DownVote what ever the reason please give some advice and do not downvote without any explication that's not fair !!

[EDIT2] If you were using XM be Aware that with XL you have to set vifscript="/etc/xen/scripts/vif-bridge" into /etc/xen/xl.conf
  because symlink vifscript="vif-bridge" only works with XM !!!
Comment: Was that meant to be an answer? If so, it belongs as an Answer below, not as part of your Question.
Comment: Thanks for driving me to this point. I add some infos because my question was missing some configurations informations. But I post an answer below after checking that my problem was due to symlinks support missing with XL...
Answer: Be Aware that if you were using XM that with XL you have to set full path for network script, if not script isn't executed:
So for XL use you have to set :
vifscript="/etc/xen/scripts/vif-bridge" (or another script)
into /etc/xen/xl.conf
because symlink vifscript="vif-bridge" only works with XM (on my Debian Xen install)!

Xen Vif creation xl vs xm


Is there a simple algorithm I can use for this?

Question: if I were asked to find all integers between 1 and 100 that leave remainder 3 on division by 5 and leave remainder 4 on division by 7, how would I go about this? It seems like such a simple question yet I am not sure if there is a simple algorithm that I can use? It should jump out at me but it doesn't seem to.
Comment: CRT: Chinese Remainder Theorem. http://en.wikipedia.org/wiki/Chinese_remainder_theorem. To find one of solutions ($18$), then $\pm 35, \pm 70, \pm 105, ...$, while they were in $[1,100]$.
Comment: Do you know how to do it if you have only one constraint, leaving a remainder of $r$ on division by $d$?
Answer: As suggested by oleg567 you have to solve the following
$\begin{cases}
x \equiv 3 \pmod{5}\\
x \equiv 4 \pmod{7}\\
\end{cases}$
or you can write
$\begin{cases}
x=3+5t\\
x=4+7s
\end{cases}$
Now after subtituting the value of $x$ from first equation into the second equation you will have
$3+5t=4+7s$
or you can write
$3+5t=4 \pmod{7}$
$\hspace{0.3cm}$$\implies$$\hspace{0.3cm}$$5t=1 \pmod{7}$
$\implies$
$t=5^{-1} \pmod{7}=3 \pmod{7}$
So
$t=3+7s$
Hence
$x=3+5t=3+5(3+7s)=18+35s$
Hence the all integers between$\hspace{0.1cm}$$1$ and $100$ that leave remainder $3$ on division by $5$ and leave remainder $4$ on division by $7$ are
$x=18,53,88$


return true or false after ajax post in parent function?

Question: I want to return true or false after making this ajax call:
function write_csv(data, path, file) {

    $.ajax({
        url: 'functions.php',
        type: 'POST',
        data: {
            operation: 'SAVE_CSV',
            save_path: path,
            save_file: file,
            save_string: data
        },
        success: function(result) {
            console.log('write_file(' + path + file + '); -done');

            return true; /* <-- */

        }
    });
}

Example use case of what I want:
function make_csv () {

    /*
    |
    V
    */

    if (write_csv(my_data, my_path, 'export.csv') == true) {
        go_on();
    }

    function go_on() {
        alert('YEAH!');
    }

}

I know it's async, but maybe someone has another idea.
I won't do it with if's and stuff...
Comment: possible duplicate of [How to return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call)
Answer: You can use Promises or callbacks to accomplish what you want.
function write_csv(data, path, file, callback) {

    $.ajax({
        url: 'functions.php',
        type: 'POST',
        data: {
            operation: 'SAVE_CSV',
            save_path: path,
            save_file: file,
            save_string: data
        },
        success: function(result) {
            console.log('write_file(' + path + file + '); -done');

            callback(true); /* <-- */

        }
    });
}

And:
function make_csv () {

    /*
    |
    V
    */

    function go_on() {
        alert('YEAH!');
    }

    write_csv(my_data, my_path, 'export.csv', function(result) {
        if (result == true) {
            go_on();
        }
    });
}

Answer: I am going to go off of jQuery convention and give you a "jQuery" answer since that's what you are using.
In jQuery, you have the ability to pass in a callback (a function to "call" once the actual function you are using finishes) in most jQuery methods.  jQuery's convention is to have the callback as the last parameter you pass in into a function.  In your example, your write_csv() function would look like this with an extra callback as the last parameter:
function write_csv(data, path, file, callback){
    $.ajax({
        url: 'functions.php',
        type: 'POST',
        data: {
            operation: 'SAVE_CSV',
            save_path: path,
            save_file: file,
            save_string: data
        },
        success: function(result) {
            console.log('write_file(' + path + file + '); -done');
            callback(true);
        }
        error: function(result){
            console.log('async failed');
            callback(false);
        }
    });
}

Notice the error key being passed in and the changes made to the success key in the $.ajax() function.
Now, when you want to use your async function in an if conditional statement, you can use
write_csv(my_data, my_path, 'export.csv', function(response){
    if(response === true){
        go_on()
    }
    else if(response === false){
        // do something else
    }
});


Como exibir um conteúdo html em um dataTable

Question: Possuo o campo mensagem em um Editor que depois da inclusão é mostrado em um dataTable.
<rich:editor value="#{solicitacaoImpressaoBean.solicitacao.mensagem}" toolbar="full"  style="margin-bottom: 1em">

DataTable:
<rich:dataTable id="tabelaSolicitacoes" value="#{solicitacaoImpressaoBean.peg.solicitacoes}" var="solicitacao"
            iterationStatusVar="it" rowClasses="linhaPar, linhaImpar"
            style="width: 100%;"
            >

            <rich:column style="text-align: center;">
                <f:facet name="header">Data</f:facet>
            <h:outputText value="#{solicitacao.dataEnvio}" converter="dataHoraConverter"  />
            </rich:column>

            <rich:column style="text-align: center;">
                <f:facet name="header">Siape do Cadastrador</f:facet>
            <h:outputText value="#{solicitacao.siapeCadastrador.siape}" />
            </rich:column>

            <rich:column style="text-align: center;">
                <f:facet name="header">Assunto</f:facet>
            <h:outputText value="#{solicitacao.assunto}" />
            </rich:column>

            <rich:column style="text-align: center;">
                <f:facet name="header">Mensagem</f:facet>
            <h:outputText value="#{solicitacao.mensagem}" />
            </rich:column>

O problema é que o editor insere o código da mensagem em html e depois de incluido irá mostrar o html inserido.
Ex do campo mensagem :
Teste de inclusao na Mensagem Enviar Solicitação para a peg 4415

Teste de inclusao na Mensagem Enviar Solicitação para a peg 4415
Como posso mostrar este conteúdo no dataTable da mesma forma que escrevi no Editor, ou seja sem as tags html?
Answer: O padrão do JSF é fazer o escape de tags de HTML e XML, o que precisa fazer é desabilitar isso.
Para a tag outputText basta definir o atributo escape para false:
<h:outputText escape="false" value="#{solicitacao.mensagem}" />

Comment: E como manter a formatação ? por ex <span style="font-family:arial,helvetica,sans-serif"


Hibernate not seeing a getter method

Question: For some reason Hibernate is not seeing a Getter in one of my classes, or at least that's what I think is happening. Is there something I have set wrong in my hibernate mapping file or a different XML configuration file?
The code I am showing you is generated by WaveMaker and is supposed to work. I am trying to run a simple HQL query but I always get the following error. It doesn't matter how simple the query is or on what entities I query, I always get the "Could not find a getter" error.
I am using WaveMaker 6.5 with whatever version of Hibernate and Spring it downloads during installation.
Here is the error I get:
Run query error: Error creating bean with name 'm2mex2DBDataService' defined in
resource loaded through SAX InputSource: Cannot resolve reference to bean
'm2mex2DBHibernateTemplate' while setting constructor argument; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name
'm2mex2DBHibernateTemplate' defined in resource loaded through SAX InputSource: Cannot
resolve reference to bean 'm2mex2DBSessionFactory' while setting bean property
'sessionFactory'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name
'm2mex2DBSessionFactory' defined in resource loaded through SAX InputSource: Invocation
of init method failed; nested exception is org.hibernate.PropertyNotFoundException:
Could not find a getter for bookauthors in class com.m2mex2db.data.Author

Here is the code of my Author class:
package com.m2mex2db.data;

import java.util.HashSet;
import java.util.Set;

/**
 *  m2mex2DB.Author
 *  05/08/2013 16:33:50
 *
 */
public class Author {

private Integer id;
private String firstname;
private String lastname;
private Set<com.m2mex2db.data.Bookauthor> bookauthors = new HashSet<com.m2mex2db.data.Bookauthor>();

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

public String getFirstname() {
    return firstname;
}

public void setFirstname(String firstname) {
    this.firstname = firstname;
}

public String getLastname() {
    return lastname;
}

public void setLastname(String lastname) {
    this.lastname = lastname;
}

public Set<com.m2mex2db.data.Bookauthor> getBookauthors() {
    return bookauthors;
}

public void setBookauthors(Set<com.m2mex2db.data.Bookauthor> bookauthors) {
    this.bookauthors = bookauthors;
}

}

and here is my Hibernate mapping file:
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.m2mex2db.data.Author" table="author" schema="kentoj" dynamic-insert="false" dynamic-update="false">
    <id name="id" type="integer">
        <column name="id"/>
        <generator class="assigned"/>
    </id>
    <property name="firstname" type="string">
        <column name="firstname" length="98" not-null="true"/>
    </property>
    <property name="lastname" type="string">
        <column name="lastname" length="98"/>
    </property>
    <set name="bookauthors" inverse="true" cascade="">
        <key>
            <column name="authorid" not-null="true"/>
        </key>
        <one-to-many class="com.m2mex2db.data.Bookauthor"/>
    </set>
</class>
</hibernate-mapping>

Comment: interesting, can you post the code of the Bookauthor?
Answer: http://forum.springsource.org/showthread.php?29965-PropertyNotFoundException-getter
Hibernate - PropertyNotFoundException: Could not find a getter for

Hibernate not seeing a getter method


Counting problem involving Hat Check experiment with n hats

Question: The question is a spin on the Hat Check problem. "There are n= 2k hats (an even number). Find the probability of B = { $h_{i} = i$ if $i$ is even and $h_{i} \neq i$ if $i$ is odd)." My interpretation for what the problem is asking is to find the probability that at least one "even numbered" person gets their own hat back AND at least one "odd numbered" person does not get their own hat.
An earlier part asked to find A = {$h_{i} = i$ if $i$ is even} which, as I understood, needed to be rewritten as $ A = \bigcup_{i= 1}^k A'_{2i}$ where $A'_i = \{h_i = i\}$ in order to apply the inclusion exclusion principle.
Then $S_i = \dbinom{k}{i}\dfrac{(2k-i)!}{(2k)!} $
and $P(A) = \sum_{i=1}^{k} (-1)^{n+1}\dbinom{k}{i}\dfrac{(2k-i)!}{(2k)!}$
I'm stuck on how to do something similar with the second conditional statement in the mix.
Answer: It is not clear what the problem is. We will assume it goes as follows. We have $2k$ people, named $1$ to $2k$, who check their hats. The hats get scrambled. What is the probability that all even numbered people get their own hat, and no odd-numbered person gets her own hat?
There are $(2k)!$ equally likely permutations. The "favourables" are the permutations that fix the even numbers, and fix no odd number. The number of favourables is therefore the derangement number $D_k$, also known as $!k$.
Comment: My reading of it is that there is an implicit $\forall$.
Comment: Now that you mention it, is the event A = {$h_{i} = i$ if $i$ is even} ambiguous without saying either "for all i" or "for any i"?
Comment: @Bernabe, the $h_i \ne i$ if $i$ is odd is equally ambiguous.


What is the term for a time series regression having more than one predictor?

Question: It's pretty tough to search the Web for info on something when you don't know what words are commonly used to describe it. In this case, I'm wondering what it's called when you include another predictor in a time series.
As an example, say I'm modeling a variable $X$ using AR(3):
$ X_t = \varphi_1 X_{t-1} + \varphi_2 X_{t-2} + \varphi_3 X_{t-3} + \varepsilon_t $
I want my model to include the effects of another variable—say, $Y$—so my model is now described as:
$ X_t = \varphi_1 X_{t-1} + \varphi_2 X_{t-2} + \varphi_3 X_{t-3} + \beta_1 Y_{t-1} + \beta_2 Y_{t-2} + \beta_3 Y_{t-3} + \varepsilon_t $
What would the term (or terms) be that distinguishes the former model from the latter?
Comment: I took this information and have tried to build a model in SAS; you may find the question I've asked about it relevant: "[How do I ensure PROC ARIMA is performing the correct parameterization of input variables?](http://stats.stackexchange.com/q/10604/1583)"
Answer: ARIMAX (Box-Tiao) is what it is called when you add covariates to Arima models, is is basically arima + X.
http://www.r-bloggers.com/the-arimax-model-muddle/
Also search for Panel data or TSCS: 'Time-series–cross-section (TSCS) data consist of comparable time series data observed on a variety of units'
See:
https://web.archive.org/web/20100612090957/http://as.nyu.edu/docs/IO/2576/beck.pdf
or https://stat.ethz.ch/pipermail/r-sig-mixed-models/2010q4/004530.html.
Answer: This is called a Transfer Function Model. It has also been referred to as a Dynamic Regression Model.
Comment: +1: Thank you for your answer. It was helpful to my search, but I can't mark two answers as accepted.
Answer: Searching the SAS documentation for ARIMAX (based on Patrick's answer), I found (in "The ARIMA Procedure: Input Variables and Regression with ARMA Errors") that they listed the following terms:

ARIMAX
Box-Tiao
Transfer Function Model
Dynamic Regression
Intervention Model
Interrupted Time Series Model
Regression Model with ARMA Errors

The term ARIMAX was used almost equally as much as the term Transfer Function Model. Intervention Model and Interrupted Time Series Model appear to refer to a different kind of model than the others.


How to list all taxonomy terms in a vocabulary followed by associated node titles in Views

Question: I am trying to list all of the taxonomy terms from a vocabulary in views and have the node title of all of the nodes that have that term associated with them listed under each term. For example, I have a vocabulary of State names. The various nodes have a term reference field to link the node with a state. I then want to create a view that will show the state name followed by the nodes with that state name, then the next state name etc. I can create a taxonomy view that lists all of the state names, but can't find a way to add the node titles under each state name. I am converting an existing non-Drupal site to Drupal 7.
Here is a link to the current page that I want to make happen in Drupal. It shows the states following by what would be the node titles for each state.
http://www.cbfisk.com/do/DisplayInstrumentList/filter/geographic
Thank you for any help.
Answer: Create a view in following way,
<code>1. create a new view to show taxonomy terms of type state
2. Then click relationship under advanced, and choose 'Taxonomy term: Content with term'
3. Then under 'fields' add ' Content: Title' as new field, by keeping relationship 'node'
4. Under 'format' choose HTML list (or table), and set  Taxonomy term: Name  as grouping   field
5. You can choose 'exclude from display' option for field  Taxonomy term: Name
</code>
Then you will get the output in desired format as below,
Comment: This worked perfectly and is exactly what I wanted to do. Thank you very much for your help. It's greatly appreciated.
Comment: welcome, if it is worked mark it as answer :)
Comment: Sorry, I just noticed your reply. I'm new to this and don't know how to "mark it as an answer." Can you tell me how to do that?
Comment: please checkout faq http://drupal.stackexchange.com/faq#howtoask


Lagrange's Equation on a Manifold

Question: I know that, if $L: \mathbb{R}^n \times \mathbb{R}^n \times \mathbb{R} \rightarrow \mathbb{R}$, then the Euler-Lagrange equation is:
$$ \nabla_x L - (\nabla_{\dot{x}}L)' \equiv 0$$
In trying to generalize this for a given riemannian manifold. My idea is to consider:
$$L: TM \times \mathbb{R} \rightarrow \mathbb{R}$$
And then split $TTM$ in its horizontal and vertical components $T_hTM $ and $T_vTM$ by the riemannian connection. Therefore:
$TL: TTM \times \mathbb{R} \rightarrow \mathbb{R}$
$TL: T_hTM \times T_vTM \times \mathbb{R} \rightarrow \mathbb{R}$
Now, given a path $\gamma:(0,1) \rightarrow M$ and using the canonical metric of $T_hTM$ and $T_vTM$ due to identifications with $T_xM$, I would get two differentiable sections:
$\nabla_xL: (0,1) \rightarrow \gamma ^*T_hTM$ that maps $t \mapsto (t,\nabla_1 L(\gamma(t)))$, where $\nabla_1 L(x)$ is the vector that determines the linear functional $TL |_{T_hT_xM}$
Analogously for $\nabla_{\dot{x}}L$ (with respect to $TL |_{T_vT_xM}$).
And now, the euler-lagrange would takes its normal form:
$$ \nabla_x L - (\nabla_{\dot{x}}L)' \equiv 0$$
Now, my question is: Is my idea correct? Is this the way to generalize it? I think there may be a simpler way to do so. Not only that, I'm not sure that the splitting is the right idea to consider.
Answer: The key point, I think, is that the Euler-Lagrange equations are not geometric objects.
You can see this by deriving the equations from the least action principle: for boundary conditions $p_0, p_1$ you can write down the variational problem
$$\mathop{\textrm{ext}}_{\substack{\gamma:[0,1]\to M\\ {\gamma(0)=p_0},\ \gamma(1)=p_1}} \int_0^1 L(\gamma'(t),t)\,dt$$
and notice that the variational problem requires nothing of $M$ beyond differential structure.
If you have a metric you can use it to solve the variational problem using the calculus of variations in a coordinate-free way, e.g. $\gamma$ is a solution to the variational problem if, for every vector field $\delta(t)$ along $\gamma$ with $\delta(0)=\delta(1)=0$,
$$0=\frac{d}{d\epsilon}\int_0^1 L(\exp[\gamma(t),\epsilon\delta(t)]'(t),t)\,dt\Bigg\vert_{\epsilon\to 0},$$
and you can get E-L equations in terms of Jacobi fields on $TTM$ etc.
But if you don't, you can instead work in coordinates on charts, and the Euler-Lagrange equations in local coordinates must be the familiar ones from Euclidean space.

Lagrange's Equation on a Manifold


How to use ip to visit AcquiaDevDesktop's site?

Question: I want to visit drupal site through 'Local area network'.
For example, my server ip address is 192.168.0.1, My drupal site is http://daxuebao.local:8083/
I try to use 192.168.0.1:8083/daxuebao.local, 192.168.0.1:8083/daxuebao. But can not be visited.
Comment: Try reading the site via 192.168.0.1:8083 without /daxuebao or /daxuebao.local. Verify that 192.168.0.1's firewall allows connections on port 8083.
Comment: Not work, When I open 192.168.0.1:8083, It show me a drupal site with Access denied (I never create)
Answer: Ok, i get it. I installed Acquia Dev Desktop and tried it out. This is what I think is what has happened and what the problem is:
You installed Acquia Dev Desktop and entered parameters about the default site that comes with Acquia (this is required during installation - so this must have happened). This site is what you reach when you from another computer enter 192.168.0.1
You created the daxuebao site via Acquia Dev Desktop application and entered "Sitename" as daxueabao and you did not enter a "URL Path" so the result is that "Site Path" then becomes "daxuebao.localhost:8083". This means that the Apache software in Acquia Dev Desktop will examine every request it receives and determine if it should go to (a) the default site or (b) the daxuebao site.
The problem is that the daxuebao site is local and that your client computers on the LAN does not know where "daxuebao.localhost:8083" points... the have no knowledge of what IP number that corresponds to and if you enter just 192.168.0.1 the Apache software will determine that to be a request for the default site. The only site that is not local is the default site.
There are basically 3 different ways of solving this problem (which one depends on your need):
Solution 1: add a DNS record to the local DNS if you have one (I don't think you do) or
Solution 2:  add a DNS record to the hosts file of all of your client computers (see more at www.howtogeek.com/howto/27350/beginner-geek-how-to-edit-your-hosts-file/ ) or
Solution 3: move site duxuebao to the default site so that Apache servers that codebase and data instead. Make sure you backup files and database before you do it. I can tell you exactly how to do it if you tell me what operating system you are using.

Added in response to comments:
I would do it like this:
Oh, by the way. Acquia Dev Desktop works out of the box on port 8082 and not 8083, just to be sure here, you're not working with multiple installations of Acquia Dev Desktop? If not then:
1 Backup the daxuebao site:
1.1 Open the Acquia Dev Desktop control panel
1.2 Click the Settings button
1.3 Click the Sites tab
1.4 Highlight the daxuebao site
1.5 Click Export button, select "to file"-option to download a copy to your Desktop.
1.6 Backup done (files and data)
2 Backup the default site:
Note: Do this just to be sure.
2.1 Open the Acquia Dev Desktop control panel
2.2 Click the Settings button
2.3 Click the Sites tab
2.4 Highlight the localhost site
2.5 Click Export button, select "to file"-option to download the export to somewhere.
3 Replace the default site FILES with the daxuebao site FILES:
We cannot use the Acquia Dev Desktop import feature here unfortunately because the default site is reserverd/protected. We need to do the copying manually of files (step 3) and data (step 4):
3.1 Stop servers in Acquia Dev Desktop from it's control panel
3.2 Delete all files in /Users/YOUR-COMPUTER-USER-NAME/Sites/acquia-drupal/sites/default
3.3 Copy all files in /Users/YOUR-COMPUTER-USER-NAME/Sites/acquia-drupal/sites/daxuebao.localhost to /Users/YOUR-COMPUTER-USER-NAME/Sites/acquia-drupal/sites/default
3.4 Start servers in Acquia Dev Desktop from it's control panel
3.5 File copy complete.
4 Replace the default site DATA with the daxuebao site DATA:
Both sites default site and daxuebao are now using the same database. That's not good because if you delete the daxuebao site then the data will disappear. So we need to copy the data from database daxuebao to the acquia default database.
4.1 Extract the files downloaded int step 1.5 on the desktop ( it will extract to /Users/YOUR-COMPUTER-USER-NAME/Desktop/daxuebao.localhost ). This folder contains data and files.
4.2 Go to the In the Acquia Dev Desktop controlpanel click button "Manage my database" and a browserwindows with phpMyAdmin will appear.
4.3 Select the database acquia_drupal in left part of the window. In the right part of the window all tables in the database will appear.
4.4 Go to the bottom of the page in the right part of the window and select "check all" and
4.5 delete the tables by using the dropdown to the immediate right labeled "With selected:" and select "Drop".
4.6 Confirm deletion.
4.7 Now, we're going to import the data from the daxuebao site
4.8 Click on the tab "Import" at the top of the right hand window.
4.9 Click button "Choose file".
4.10 Navigate and select the datafile daxuebao.sql thats in the /Users/YOUR-COMPUTER-USER-NAME/Desktop/daxuebao.localhost directory.
4.11 Click button "Go"
4.12 Data copy complete.
5 Change settings-file for default site to look at correct database table
5.1 Open settings.php in /Users/YOUR-COMPUTER-USER-NAME/Sites/acquia-drupal/sites/default directory
5.2 Change
    $base_url = 'http://daxuebao.localhost:8082';
to
    $base_url = 'http://localhost:8082';
5.3 Change
    $db_url = 'mysqli://email@example.com:33066/daxuebao';
to
    $db_url = 'mysqli://firstname.lastname@example.com:33066/acquia_drupal';
5.4 Change
'database' => 'daxuebao',
to
'database' => 'acquia_drupal',
5.5 Verify by going to the site from your local computer
5.6 Verify by going to 192.168.0.1:8083 from another computer within the LAN
5.7 If all looks fine then your default site in Acquia Dev Desktop is now using it's own database "acquia_drupal". You can now safeley delete the daxuebao site from your Acquia Dev Desktop controlpanel.
BR / Fredrik
Comment: thanks for your reply, This above solution about DNS seems bother. I am using MAC, I hope you tell me how to fix that problem with solution 3, thanks.
Comment: Thanks, I try your step, It works. But too bother. I already switched to MAMP, although it is pretty slow.
Comment: @Wooden Ok. Yes MAMP is pretty slow with Druapal but there are 2 "tricks"

1. add the following to the htaccess-file in your Drupal installation:

php_value memory_limit 128M

php_value upload_max_filesize 32M

php_value post_max_size 32M

php_value max_input_time 300

php_value max_execution_time 300

php_value realpath_cache_size 24M

2. Use APC cache and PHP 5.4.10.

BR / Fredrik
Comment: I am used to use PHP 5.5.3 in MAMP, Now I switch to PHP 5.4.19. Does APC can be used as a production environment?
Comment: I use PHP 5.5 in production environments with OP Cache that comes with PHP 5.5 since I experience it as faster.


Are the following graphs isomorphic?

Question:
The graphs have different cycle lengths. So can they be considered as not isomorphic?
Answer: An isomorphism would map a cycle to a cycle of the same length, so the fact that one graph has triangles ($3$-cycles) and the other one doesn't implies that the graphs are not isomorphic.

Are the following graphs isomorphic?


Using migrate, how can you set the default format to Full HTML?

Question: Using the migrate module to import content from a database. One of the fields contains full HTML but on import the text field defaults to plain text. The admin default is set to Full HTML, but even though the imports are being created by admin, it defaults to plain text.
How do you set the default to full HTML for imports? There's obviously a way around this in code but wondering if there's a patch or anyone has advice on the right approach.
Answer: In Drupal 6, when you import with the Migrate and Table Wizard modules there is a text field when mapping each field that is empty. Just type in full_html and each node when imported with have full_html entered into that row in the database.
Answer: <code>$this->addFieldMapping('body', 'body')
     ->arguments(array('format' => 'full_html'));
</code>
This works for me.
Comment: Does it work for comments as well?