问:
How to use TStartMenuTreeFolderView
I am getting blank tree view for my Start menu folder browser form, I created using TStartMenuFolderTreeView.

I the problem that I do not call the TStartMenuFolderTreeView.SetPaths?

Here is the Inno Setup code:

[Code]

var
  Form2: TSetupForm;
  GFLabel1: TLabel;
  GFButton1, GFButton2: TButton;
  gEdit: TEdit;
  GroupTreeView: TStartMenuFolderTreeView;

procedure Button1Click (Sender: TObject);
begin
  Form2.Close
  WizardForm.Enabled:=True;
  WizardForm.GroupEdit.Text:=gEdit.Text;
end;

procedure Button2Click (Sender: TObject);
begin
  Form2.Close
  WizardForm.Enabled:=True;
end;

procedure EditOnChange(Sender:Tobject);
begin
  gEdit.Text:=AddBackSlash(GroupTreeView.Directory) + '{#GroupName}';
end;

procedure Close (Sender:Tobject; var Action: TCloseAction);
begin
  Form2.close
  WizardForm.Enabled:=True;
end;

procedure GroupButtonClick(Sender:Tobject);
begin
  Form2:=CreateCustomForm;
  with Form2 do
  begin
    Width:=470;
    Height:=296;
    Position:=poScreenCenter;
    CenterInsideControl(WizardForm, False);
    Caption:='Browse For Folder';
    OnClose:=@Close;
  end;

  GFLabel1:=TLabel.Create(Form2);
  with GFLabel1 do
  begin
    Parent:=Form2;
    SetBounds(5,5,100,10)
    Caption:='Select a folder in list below, Then click OK.';
  end;

  GFButton1:=TButton.Create(Form2);
  with GFButton1 do
  begin
    Parent:=Form2;
    SetBounds(285,22,80,25)
    Caption:='OK';
    OnClick:=@Button1Click;
  end;

  GFButton2:=TButton.Create(Form2);
  with GFButton2 do
  begin
    Parent:=Form2;
    SetBounds(370,22,80,25)
    Caption:='Cancel';
    OnClick:=@Button2Click;
  end;

  gEdit:=TEdit.Create(Form2);
  with gEdit do
  begin
    Parent:=Form2;
    SetBounds(5,25,275,15)
    Text:=WizardForm.GroupEdit.Text;
    OnChange:=@EditOnChange;
  end;

  GroupTreeView:=TStartMenuFolderTreeView.Create(Form2);
  with GroupTreeView do
  begin
    Parent:=Form2;
    SetBounds(5,53,445,205)
    OnChange:=@EditOnChange;
  end;

  GroupTreeView.ChangeDirectory(AddBackslash(WizardForm.GroupEdit.Text), true);
  gEdit.Text:=AddBackslash(GroupTreeView.Directory);
  Form2.Show;
  WizardForm.Enabled:=false;
end;

procedure InitializeWizard();
begin
  with WizardForm.GroupBrowseButton do
  begin
    OnClick:=@GroupButtonClick;
  end;
end;
```

答:
Yes, you have to call TStartMenuFolderTreeView.SetPaths:

GroupTreeView.SetPaths(
  ExpandConstant('{userprograms}'),
  ExpandConstant('{commonprograms}'),
  ExpandConstant('{userstartup}'),
  ExpandConstant('{commonstartup}'));
```

<hr>

<p>On top of that, your implementation of the form execution is completely wrong.</p>

<p>You have to use <code>TForm.ShowModal</code> for modal dialogs, not <code>TForm.Show</code>. Then, you won't have to do all that main form disabling/enabling (what does not work anyway, your code crashes for me every time I close the dialog).</p>

<p>You also do not need the <code>TButton.OnClick</code>. Use <code>TButton.ModalResult</code> to get the buttons close the dialog automatically. Additionally, for "OK" button, set the <code>TButton.Default</code>, for "Cancel" button, set the <code>TButton.Cancel</code>. This makes <kbd>Enter</kbd> and <kbd>Esc</kbd> keys working.</p>

<pre class="lang-pascal prettyprint-override"><code>with GFButton1 do
begin
  { ... }
  Default := True;
  ModalResult := mrOK;
end;

with GFButton2 do
begin
  { ... }
  Cancel := True;
  ModalResult := mrCancel;
end;

{ ... }

if Form2.ShowModal = mrOK then
begin
  WizardForm.GroupEdit.Text := gEdit.Text;
end;
</code>```

And remove the Button1Click, Button2Click and Close.

More observations:

No need for all those global variables. They all can be local to the GroupButtonClick.

Assigning the EditOnChange to the gEdit.OnChange is nonsense. It will prevent you from editing the folder path manually.

Do not use fixed sizes and offsets. Always use ScaleX and ScaleY functions.

E.g. Width := ScaleX(470);

Otherwise your dialog will be small on high-DPI displays.

See Inno Setup Placing image/control on custom page.

Note that in general, use of the Start menu groups is discouraged in recent version of Windows. There should be a single icon per application only.

Title: How to use TStartMenuTreeFolderView

Body:
Yes, you have to call TStartMenuFolderTreeView.SetPaths:

GroupTreeView.SetPaths(
  ExpandConstant('{userprograms}'),
  ExpandConstant('{commonprograms}'),
  ExpandConstant('{userstartup}'),
  ExpandConstant('{commonstartup}'));

On top of that, your implementation of the form execution is completely wrong.

You have to use TForm.ShowModal for modal dialogs, not TForm.Show. Then, you won't have to do all that main form disabling/enabling (what does not work anyway, your code crashes for me every time I close the dialog).

You also do not need the TButton.OnClick. Use TButton.ModalResult to get the buttons close the dialog automatically. Additionally, for "OK" button, set the TButton.Default, for "Cancel" button, set the TButton.Cancel. This makes Enter and Esc keys working.

with GFButton1 do
begin
  { ... }
  Default := True;
  ModalResult := mrOK;
end;

with GFButton2 do
begin
  { ... }
  Cancel := True;
  ModalResult := mrCancel;
end;

{ ... }

if Form2.ShowModal = mrOK then
begin
  WizardForm.GroupEdit.Text := gEdit.Text;
end;

And remove the Button1Click, Button2Click and Close.

More observations:

No need for all those global variables. They all can be local to the GroupButtonClick.

Assigning the EditOnChange to the gEdit.OnChange is nonsense. It will prevent you from editing the folder path manually.

Do not use fixed sizes and offsets. Always use ScaleX and ScaleY functions.

E.g. Width := ScaleX(470);

Otherwise your dialog will be small on high-DPI displays.

See Inno Setup Placing image/control on custom page.

Note that in general, use of the Start menu groups is discouraged in recent version of Windows. There should be a single icon per application only.


来源: stackexchange

问:
SQL SELECT various names by various id's
I have this 3 tables:

main table:

```<code>  ID | OtherStuff1 | OtherStuff2 | IdProvince | IdTown
-----+-------------+-------------+------------+--------
   1 |   Stuff1    |   Stuff2    |      1     |   1
</code>```

province table:

```<code>ID | ProvinceName
---+--------------
 1 |  ProvName1
</code>```

town table:

```<code>ID |   TownName
---+--------------
 1 |   TwName1
</code>```

Obviously the main table has foreign relationships with the province table and the town table.

The result I want is this one:

```<code>ID | OtherStuff1 | OtherStuff2 | IdProvince |   IdTown
---+-------------+-------------+------------+------------
 1 |   Stuff1    |   Stuff2    | ProvName1  |   TwName1
</code>```

I want to show the main table but with the names instead of the ID's.

I looked up other questions and I tried this one:

```<code>    SELECT *
        FROM main AS a
        INNER JOIN province AS b
        INNER JOIN town AS c
        WHERE a.IdProvince = b.ProvinceName
        AND a.IdTown = c.TownName

    AND Id=1; # this is added by me because I want to filter by id on the
              # main table, I don't want all the rows, just one filtered by ID.
</code>```

And this other one:

```<code> SELECT *
       FROM main AS a,
       INNER JOIN province AS b ON a.IdProvince = b.ProvinceName
       INNER JOIN town AS c ON a.IdTown = c.TownName
       WHERE Id=1;
</code>```

Also I would like that the query could be easy to use in the way that If I have the same problem, but instead of the main table and 2 tables, I have main table and 4 tables I could also use it just adding more "INNER JOINS" for example?

I'm trying to do this but I couldn't get it right, I get this Sql wrong every time and I don't find the correct way to do this, any ideas?

I'm using PDO and I show this on a web page.

"AND Id=1" --> this will be used like this --> "AND Id=:filterID".

I hope I explained myself right!

If you have any doubts just ask, I'll answer as fast as I can!

Thanks in advance!

---------------------------------------------------------------EDIT--------------------------------------------------------------

I already tryed the 3 answers I got and it doesn't work, I don't know why, I will add images to back up so you see.

This one works with no errors but I get no info back

```<code>SELECT a.Id, OtherStuff1, OtherStuff2, IdProvince, IdTown
 FROM main AS a
 INNER JOIN province AS b
 INNER JOIN town AS c
   WHERE a.IdProvince = b.ProvinceName
   AND a.IdTown = c.TownName
AND a.Id=1
</code>```

This is the result

This one the same and no info back, but anyways I get extra columns from the other tables that I don't need there.

```<code>SELECT *
 FROM main AS a ,province AS b , town AS c
  WHERE a.IdProvince = b.ProvinceName
  AND a.IdTown = c.TownName
AND a.Id=1
</code>```

This is the second result

I also tryed this one but I can't get it to work always shows me an error

```<code>SELECT *
   FROM
      (main AS a
      INNER JOIN province AS b ON a.IdProvince = b.ProvinceName) AS d
      INNER JOIN town AS c ON d.IdTown = c.TownName
   WHERE
      Id=1
</code>```

I can't post more than 2 photos because I don't have enough reputation but I paste the error here:

```<code>MySQL said: Documentation
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'd
      INNER JOIN town AS c ON d.IdTown = c.TownName
   WHERE
      Id=1 LI' at line 4
</code>```

And in case you ask or doubt, I did put the info in the tables, 1 row each so there is something in, but for some reason it doesn't gives me back that info.

-------------------------------------------------------LAST EDIT-------------------------------------------------------------

The 3 codes worked for me after trying them with a few edits, here are the 3 codes so people who might read this find this helpful.

```<code>ID | ProvinceName
---+--------------
 1 |  ProvName1
</code>```0

```<code>ID | ProvinceName
---+--------------
 1 |  ProvName1
</code>```1

```<code>ID | ProvinceName
---+--------------
 1 |  ProvName1
</code>```2

Thanks a lot to the people who have helped me!

答:
this is work for me ,

Please feild name first ,if its not proper then first fix it then execute ,

```<code>SELECT *
FROM main AS a ,province AS b , town AS c
WHERE a.IdProvince = b.id
AND a.IdTown = c.id
AND a.Id=1;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have this 3 tables:

main table:

  ID | OtherStuff1 | OtherStuff2 | IdProvince | IdTown
-----+-------------+-------------+------------+--------
   1 |   Stuff1    |   Stuff2    |      1     |   1

province table:

ID | ProvinceName
---+--------------
 1 |  ProvName1

town table:

ID |   TownName
---+--------------
 1 |   TwName1

Obviously the main table has foreign relationships with the province table and the town table.

The result I want is this one:

ID | OtherStuff1 | OtherStuff2 | IdProvince |   IdTown
---+-------------+-------------+------------+------------
 1 |   Stuff1    |   Stuff2    | ProvName1  |   TwName1

I want to show the main table but with the names instead of the ID's.

I looked up other questions and I tried this one:

    SELECT *
        FROM main AS a
        INNER JOIN province AS b
        INNER JOIN town AS c
        WHERE a.IdProvince = b.ProvinceName
        AND a.IdTown = c.TownName

    AND Id=1; # this is added by me because I want to filter by id on the
              # main table, I don't want all the rows, just one filtered by ID.

And this other one:

 SELECT *
       FROM main AS a,
       INNER JOIN province AS b ON a.IdProvince = b.ProvinceName
       INNER JOIN town AS c ON a.IdTown = c.TownName
       WHERE Id=1;

Also I would like that the query could be easy to use in the way that If I have the same problem, but instead of the main table and 2 tables, I have main table and 4 tables I could also use it just adding more "INNER JOINS" for example?

I'm trying to do this but I couldn't get it right, I get this Sql wrong every time and I don't find the correct way to do this, any ideas?

I'm using PDO and I show this on a web page.

"AND Id=1" --> this will be used like this --> "AND Id=:filterID".

I hope I explained myself right!

If you have any doubts just ask, I'll answer as fast as I can!

Thanks in advance!

---------------------------------------------------------------EDIT--------------------------------------------------------------

I already tryed the 3 answers I got and it doesn't work, I don't know why, I will add images to back up so you see.

This one works with no errors but I get no info back

SELECT a.Id, OtherStuff1, OtherStuff2, IdProvince, IdTown
 FROM main AS a
 INNER JOIN province AS b
 INNER JOIN town AS c
   WHERE a.IdProvince = b.ProvinceName
   AND a.IdTown = c.TownName
AND a.Id=1

This is the result

This one the same and no info back, but anyways I get extra columns from the other tables that I don't need there.

SELECT *
 FROM main AS a ,province AS b , town AS c
  WHERE a.IdProvince = b.ProvinceName
  AND a.IdTown = c.TownName
AND a.Id=1

This is the second result

I also tryed this one but I can't get it to work always shows me an error

SELECT *
   FROM
      (main AS a
      INNER JOIN province AS b ON a.IdProvince = b.ProvinceName) AS d
      INNER JOIN town AS c ON d.IdTown = c.TownName
   WHERE
      Id=1

I can't post more than 2 photos because I don't have enough reputation but I paste the error here:

MySQL said: Documentation
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'd
      INNER JOIN town AS c ON d.IdTown = c.TownName
   WHERE
      Id=1 LI' at line 4

And in case you ask or doubt, I did put the info in the tables, 1 row each so there is something in, but for some reason it doesn't gives me back that info.

-------------------------------------------------------LAST EDIT-------------------------------------------------------------

The 3 codes worked for me after trying them with a few edits, here are the 3 codes so people who might read this find this helpful.

SELECT a.Id, OtherStuff1, OtherStuff2, ProvinceName, TownName
    FROM main AS a
    INNER JOIN province AS b ON a.IdProvince = b.Id
    INNER JOIN town AS c ON a.IdTown = c.Id
    WHERE a.Id=1;

SELECT a.Id, OtherStuff1, OtherStuff2, ProvinceName, TownName
    FROM main AS a
    INNER JOIN (province AS b, town AS c)
    ON (a.IdProvince = b.Id AND a.IdTown = c.Id)
    WHERE a.Id=1;

SELECT a.Id, OtherStuff1, OtherStuff2, ProvinceName, TownName
    FROM main AS a ,province AS b , town AS c
    WHERE a.IdProvince = b.Id
    AND a.IdTown = c.Id
    AND a.Id=1;

Thanks a lot to the people who have helped me!

Body:
this is work for me ,

Please feild name first ,if its not proper then first fix it then execute ,

SELECT *
FROM main AS a ,province AS b , town AS c
WHERE a.IdProvince = b.id
AND a.IdTown = c.id
AND a.Id=1;


问:
Itext5, highlight one word in a phrase
I am designing my pdf with a table, so pdf cells recieve a phrase and not a paragraph.

I have this phrase:

```<code>Phrase subject = new Phrase( "Subject: " + NEWLINE + investigation.Title);
</code>```

and I want the word "subject" will be highlighted with a diffrent font, how do I change the font for a single word in a phrase

I would like to do it somehing like that:

```<code>Chunk chunk = new Chunk("Conclusions", titleFont);
Chapter chapter = new Chapter(new Paragraph(chunk), 1);
chapter.NumberDepth = (0);
chapter.Add(new Paragraph(investigation.InvestigationResult, textFont));
doc.Add(chapter);
</code>```

but in a phrase

答: Split your text and create a chunk for each part (or at least a chunk for the part that varies). You can set the font for each chunk individually and then add all chunks to a phrase.</p>

Title: Itext5, highlight one word in a phrase

Body:
I am designing my pdf with a table, so pdf cells recieve a phrase and not a paragraph.

I have this phrase:

Phrase subject = new Phrase( "Subject: " + NEWLINE + investigation.Title);

and I want the word "subject" will be highlighted with a diffrent font, how do I change the font for a single word in a phrase

I would like to do it somehing like that:

Chunk chunk = new Chunk("Conclusions", titleFont);
Chapter chapter = new Chapter(new Paragraph(chunk), 1);
chapter.NumberDepth = (0);
chapter.Add(new Paragraph(investigation.InvestigationResult, textFont));
doc.Add(chapter);

but in a phrase


问:
Matplotlib Scatter plot change color based on value on list
I'm quite new to matplotlib and i would like to know how we can change color of points on a scatter plot based on the value in a list.

In fact, I have a 2-D array that I want to plot and a list with the same number of rows containing, for each point, the color we want to use.

```<code>#Example
data = np.array([4.29488806,-5.34487081],
[3.63116248,-2.48616998],
[-0.56023222,-5.89586997],
[-0.51538502,-2.62569576],
[-4.08561754,-4.2870525 ],
[-0.80869722,10.12529582])
colors = ['red','red','red','blue','red','blue']
ax1.plot(data[:,0],data[:,1],'o',picker=True)
</code>```

How to set the color parameter to fit my list of colors ?

Body:
I'm quite new to matplotlib and i would like to know how we can change color of points on a scatter plot based on the value in a list.

In fact, I have a 2-D array that I want to plot and a list with the same number of rows containing, for each point, the color we want to use.

#Example
data = np.array([4.29488806,-5.34487081],
[3.63116248,-2.48616998],
[-0.56023222,-5.89586997],
[-0.51538502,-2.62569576],
[-4.08561754,-4.2870525 ],
[-0.80869722,10.12529582])
colors = ['red','red','red','blue','red','blue']
ax1.plot(data[:,0],data[:,1],'o',picker=True)

How to set the color parameter to fit my list of colors ?

Body:
You have to set argument c of plt.scatter with a list of desired colors:

import matplotlib.pylab as plt
import numpy as np

data = np.array([[4.29488806,-5.34487081],
[3.63116248,-2.48616998],
[-0.56023222,-5.89586997],
[-0.51538502,-2.62569576],
[-4.08561754,-4.2870525 ],
[-0.80869722,10.12529582]])

colors = ['red','red','red','blue','red','blue']
plt.scatter(data[:,0],data[:,1],marker='o',c = colors)
plt.show()


问:
.sh script doesn't return variable correctly
I have created a file called alias.sh in which I have put this code:

```<code>#!/bin/bash

OUTPUT="$(alias | awk -F'[ =]' '{print $2}')"
echo "${OUTPUT}"
</code>```

Whenever I run the command alias | awk -F'[ =]' '{print $2}' in a terminal, it correctly returns a list of set aliases in my preferred format.

However, when I execute the script like $ ./alias.sh, it simply returns an empty line.

The script works if I replace the alias | awk -F'[ =]' '{print $2}' command with the ls command. It even preserves line breaks.

Can anybody help me understand why the script does not return the expected result?

答:
The actual reason for the error is because alias is not expanded when the shell is not interactive,

From the man bash page,

[..] Aliases are not expanded when the shell is not interactive, unless the expand_aliases shell option is set using shopt [..]

add the line below to the top of the script for force the expansion manually.

```<code>shopt -s expand_aliases
</code>```

and then source the script and not execute it,

```<code>#!/bin/bash

shopt -s expand_aliases

output=$(alias | awk -F'[ =]' '{print $2}')
echo "$output"
</code>```

and now source the script as

```<code>. ./myScript.sh
</code>```

Body:
I have created a file called alias.sh in which I have put this code:

#!/bin/bash

OUTPUT="$(alias | awk -F'[ =]' '{print $2}')"
echo "${OUTPUT}"

Whenever I run the command alias | awk -F'[ =]' '{print $2}' in a terminal, it correctly returns a list of set aliases in my preferred format.

However, when I execute the script like $ ./alias.sh, it simply returns an empty line.

The script works if I replace the alias | awk -F'[ =]' '{print $2}' command with the ls command. It even preserves line breaks.

Can anybody help me understand why the script does not return the expected result?

Body:
The actual reason for the error is because alias is not expanded when the shell is not interactive,

From the man bash page,

[..] Aliases are not expanded when the shell is not interactive, unless the expand_aliases shell option is set using shopt [..]

add the line below to the top of the script for force the expansion manually.

shopt -s expand_aliases

and then source the script and not execute it,

#!/bin/bash

shopt -s expand_aliases

output=$(alias | awk -F'[ =]' '{print $2}')
echo "$output"

and now source the script as

. ./myScript.sh


问:
Odoo V8 Got error unhashable type : 'list'
ive got error like this :

```<code>    Traceback (most recent call last):
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\http.py", line 544, in _handle_exception
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\http.py", line 581, in dispatch
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\http.py", line 317, in _call_function
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\service\model.py", line 118, in wrapper
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\http.py", line 314, in checked_call
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\http.py", line 810, in __call__
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\http.py", line 410, in response_wrap
  File "C:\Program Files (x86)\Odoo 8.0\server\openerp\addons\web\controllers\main.py", line 944, in call_kw
  File "C:\Program Files (x86)\Odoo 8.0\server\openerp\addons\web\controllers\main.py", line 936, in _call_kw
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\api.py", line 268, in wrapper
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\api.py", line 399, in old_api
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\models.py", line 5989, in onchange
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\models.py", line 5887, in _onchange_eval
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\models.py", line 5395, in _convert_to_cache
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\models.py", line 5396, in <dictcomp>
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\fields.py", line 1661, in convert_to_cache
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\tools\misc.py", line 1288, in add
  File "collections.pyc", line 63, in __setitem__
TypeError: unhashable type: 'list'
</code>```

ive checked it using pdb, but i got no error in my code, but got in this part :

```<code>File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\models.py", line 5887, in _onchange_eval

    TypeError: unhashable type: 'list'
</code>```

and here is my code, my goal is to override onchange_employee_id function from hr.payslip model, and want to update the one2many field lines values by using (1,ID, {values}) :

```<code>import openerp
from openerp.osv import fields, osv
from openerp import api, fields, models, _, SUPERUSER_ID
from datetime import datetime
import time

class hr_payslip(models.Model):
    _inherit = 'hr.payslip'

    #@api.model
    #@api.multi
    def onchange_employee_id(self, cr, uid, ids, date_from, date_to, employee_id=False, contract_id=False, context=None):
        import pdb;pdb.set_trace()
        res = super(hr_payslip, self).onchange_employee_id(cr, uid, ids, date_from, date_to, employee_id=employee_id, contract_id=contract_id, context=context)
        #res = super(hr_payslip, self).onchange_employee_id(cr, uid, ids, date_from, date_to, employee_id, contract_id, context)
        for pay in self.browse(cr, uid, ids):
            empy = self.pool.get('overtime_details').search(cr, uid, [
                                ('start_date','>=',datetime.strptime(pay.date_from, "%Y-%m-%d").strftime("%Y-%m-%d %H:%M:%S")),
                                ('end_date','<=',datetime.strptime(pay.date_to, "%Y-%m-%d").strftime("%Y-%m-%d %H:%M:%S")),
                                ('employee_id.name','=',pay.employee_id.name),
                                ('overtime_id.state', '=', 'done')], context=context)
            if pay.id:
                #chk_struct = self.pool.get('hr.payroll.structure').search(cr, uid, [('name', '=', pay.struct_id.name)], context=context)
                #chk_contract = self.pool.get('hr.contract').search(cr, uid, [('name', '=', pay.contract_id.name)], context=context)
                if empy:
                    #if chk_struct:
                        #if chk_contract:
                    chk_ovt = self.pool.get('overtime_details').browse(cr, uid, empy, context=context)
                    if chk_ovt:
                        counter = 0
                        hrs = 0
                        vals = []
                        for ovt in chk_ovt:
                            if ovt.id:
                                counter = counter + 1
                                hrs = hrs + ovt.ttalmtp
                    vals.append([1,[pay.worked_days_line_ids],{'number_of_days':counter,
                    'number_of_hours':hrs, 'contract_id':pay.contract_id}])
                    return {'value' : {'worked_days_line_ids' : vals }}
                                #self.create(cr, uid, val2)
                else :
                    val = 0

            return res
</code>```

what should i do to fix the error

thanks before :)

答:
The problem is here:

```<code>return {'value' : {'worked_days_line_ids' : vals }}
</code>```

You try to insert a list into a dictionary, however, this is impossible as lists are unhashable. You can solve it by converting the list to a tuple:

```<code>return {'value' : {'worked_days_line_ids' : tuple(vals)}}
</code>```

Body:
ive got error like this :

    Traceback (most recent call last):
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\http.py", line 544, in _handle_exception
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\http.py", line 581, in dispatch
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\http.py", line 317, in _call_function
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\service\model.py", line 118, in wrapper
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\http.py", line 314, in checked_call
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\http.py", line 810, in __call__
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\http.py", line 410, in response_wrap
  File "C:\Program Files (x86)\Odoo 8.0\server\openerp\addons\web\controllers\main.py", line 944, in call_kw
  File "C:\Program Files (x86)\Odoo 8.0\server\openerp\addons\web\controllers\main.py", line 936, in _call_kw
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\api.py", line 268, in wrapper
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\api.py", line 399, in old_api
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\models.py", line 5989, in onchange
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\models.py", line 5887, in _onchange_eval
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\models.py", line 5395, in _convert_to_cache
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\models.py", line 5396, in <dictcomp>
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\fields.py", line 1661, in convert_to_cache
  File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\tools\misc.py", line 1288, in add
  File "collections.pyc", line 63, in __setitem__
TypeError: unhashable type: 'list'

ive checked it using pdb, but i got no error in my code, but got in this part :

File "C:\Program Files (x86)\Odoo 8.0\server\.\openerp\models.py", line 5887, in _onchange_eval

    TypeError: unhashable type: 'list'

and here is my code, my goal is to override onchange_employee_id function from hr.payslip model, and want to update the one2many field lines values by using (1,ID, {values}) :

import openerp
from openerp.osv import fields, osv
from openerp import api, fields, models, _, SUPERUSER_ID
from datetime import datetime
import time

class hr_payslip(models.Model):
    _inherit = 'hr.payslip'

    #@api.model
    #@api.multi
    def onchange_employee_id(self, cr, uid, ids, date_from, date_to, employee_id=False, contract_id=False, context=None):
        import pdb;pdb.set_trace()
        res = super(hr_payslip, self).onchange_employee_id(cr, uid, ids, date_from, date_to, employee_id=employee_id, contract_id=contract_id, context=context)
        #res = super(hr_payslip, self).onchange_employee_id(cr, uid, ids, date_from, date_to, employee_id, contract_id, context)
        for pay in self.browse(cr, uid, ids):
            empy = self.pool.get('overtime_details').search(cr, uid, [
                                ('start_date','>=',datetime.strptime(pay.date_from, "%Y-%m-%d").strftime("%Y-%m-%d %H:%M:%S")),
                                ('end_date','<=',datetime.strptime(pay.date_to, "%Y-%m-%d").strftime("%Y-%m-%d %H:%M:%S")),
                                ('employee_id.name','=',pay.employee_id.name),
                                ('overtime_id.state', '=', 'done')], context=context)
            if pay.id:
                #chk_struct = self.pool.get('hr.payroll.structure').search(cr, uid, [('name', '=', pay.struct_id.name)], context=context)
                #chk_contract = self.pool.get('hr.contract').search(cr, uid, [('name', '=', pay.contract_id.name)], context=context)
                if empy:
                    #if chk_struct:
                        #if chk_contract:
                    chk_ovt = self.pool.get('overtime_details').browse(cr, uid, empy, context=context)
                    if chk_ovt:
                        counter = 0
                        hrs = 0
                        vals = []
                        for ovt in chk_ovt:
                            if ovt.id:
                                counter = counter + 1
                                hrs = hrs + ovt.ttalmtp
                    vals.append([1,[pay.worked_days_line_ids],{'number_of_days':counter,
                    'number_of_hours':hrs, 'contract_id':pay.contract_id}])
                    return {'value' : {'worked_days_line_ids' : vals }}
                                #self.create(cr, uid, val2)
                else :
                    val = 0

            return res

what should i do to fix the error

thanks before :)

Body:
The problem is here:

return {'value' : {'worked_days_line_ids' : vals }}

You try to insert a list into a dictionary, however, this is impossible as lists are unhashable. You can solve it by converting the list to a tuple:

return {'value' : {'worked_days_line_ids' : tuple(vals)}}


问:
Grouping row by specified column from array
I have this array

```<code>   Array
(
    [0] => stdClass Object
        (
            [TransactionNo] => OPM-EC-K-LFMCD2-21.4
            [StokOpnameTransNo] => OPM-EC-K-LFMCD2-21
            [ItemCode] => BBG150400005
            [ItemName] => BIG BAG
            [OriginalPrice] => 289900.00
            [Price] => 289900.00
            [QtyBegining] => 0
            [QtyIn] => 4
            [QtySales] => 0
            [QtyMutasi] => 0
            [QtyStock] => 4
            [QtyOpname] => 0
            [QtyAdjust] => -4
            [TotalAdjust] => -1159600.00
            [rak] =>
            [line] =>
            [TransDate] => 2017-03-31 10:46:00.000
            [CustomerCode] => K-LFMCD2
            [CreatedBy] => 1208496.
            [Remark] => re
            [Remark2] => re
            [SOTerakhir] =>
            [TglSoTerakhir] =>
        )

    [1] => stdClass Object
        (
            [TransactionNo] => OPM-EC-K-LFMCD2-21.5
            [StokOpnameTransNo] => OPM-EC-K-LFMCD2-21
            [ItemCode] => BBG150500063
            [ItemName] => BIG BAG
            [OriginalPrice] => 479900.00
            [Price] => 479900.00
            [QtyBegining] => 0
            [QtyIn] => 0
            [QtySales] => 0
            [QtyMutasi] => 0
            [QtyStock] => 0
            [QtyOpname] => 1
            [QtyAdjust] => 0
            [TotalAdjust] => .00
            [rak] => SS
            [line] => SS
            [TransDate] => 2017-03-31 10:46:00.000
            [CustomerCode] => K-LFMCD2
            [CreatedBy] => 1208496.
            [Remark] => re
            [Remark2] => re
            [SOTerakhir] =>
            [TglSoTerakhir] =>
        )

    [2] => stdClass Object
        (
            [TransactionNo] => OPM-EC-K-LFMCD2-21.5
            [StokOpnameTransNo] => OPM-EC-K-LFMCD2-21
            [ItemCode] => BBG150500063
            [ItemName] => BIG BAG
            [OriginalPrice] => 479900.00
            [Price] => 479900.00
            [QtyBegining] => 0
            [QtyIn] => 1
            [QtySales] => 0
            [QtyMutasi] => 0
            [QtyStock] => 1
            [QtyOpname] => 0
            [QtyAdjust] => 0
            [TotalAdjust] => .00
            [rak] =>
            [line] =>
            [TransDate] => 2017-03-31 10:46:00.000
            [CustomerCode] => K-LFMCD2
            [CreatedBy] => 1208496.
            [Remark] => re
            [Remark2] => re
            [SOTerakhir] =>
            [TglSoTerakhir] =>
        )

    [3] => stdClass Object
        (
            [TransactionNo] => OPM-EC-K-LFMCD2-21.6
            [StokOpnameTransNo] => OPM-EC-K-LFMCD2-21
            [ItemCode] => BBG150500081
            [ItemName] => BIG BAG
            [OriginalPrice] => 229900.00
            [Price] => 229900.00
            [QtyBegining] => 0
            [QtyIn] => 0
            [QtySales] => 0
            [QtyMutasi] => 0
            [QtyStock] => 0
            [QtyOpname] => 1
            [QtyAdjust] => 0
            [TotalAdjust] => .00
            [rak] => SS
            [line] => SS
            [TransDate] => 2017-03-31 10:46:00.000
            [CustomerCode] => K-LFMCD2
            [CreatedBy] => 1208496.
            [Remark] => re
            [Remark2] => re
            [SOTerakhir] =>
            [TglSoTerakhir] =>
        )

)
</code>```

My array(s) comming from the query result . Then i'm trying to put it to HTML Table so i try this way.

```<code><table class="table ">
                    <thead>
                        <tr>
                            <th>No</th>
                            <th>ItemCode</th>
                            <th>ItemName</th>
                            <th>TransNo</th>
                            <th>Original Price</th>
                            <th>Price</th>
                             <th>QtyBeginning</th>
                            <th>QtyIn</th>
                            <th>QtySales</th>
                            <th>QtyMutasi</th>
                            <th>QtyStock</th>
                            <th>QtyOpname</th>
                            <th>QtyAdjust</th>
                            <th>TotalAdjust</th>
                            <th>Rak</th>
                            <th>Line</th>
                        </tr>
                    </thead>
                    <tbody> <?php $x=0; foreach ($datadetail as $data) { $x++;?>
                                 <tr>
                                    <td><?=$x;?></td>
                                    <td><?=$data->ItemCode;?></td>
                                    <td><?=$data->ItemName;?></td>
                                    <td><?=$data->StokOpnameTransNo;?></td>
                                    <td><?=$data->OriginalPrice;?></td>
                                    <td><?=$data->Price;?></td>
                                    <td><?=$data->QtyBegining;?></td>
                                    <td><?=$data->QtyIn;?></td>
                                    <td><?=$data->QtySales;?></td>
                                    <td><?=$data->QtyMutasi;?></td>
                                    <td><?=$data->QtyStock;?></td>
                                    <td><?=$data->QtyOpname;?></td>
                                    <td><?=$data->QtyAdjust;?></td>
                                    <td><?=currency($data->TotalAdjust);?></td>
                                    <td><?=$data->rak;?></td>
                                    <td><?=$data->line;?></td>
                                </tr>
                            <?php } ?>

                    </tbody>

            </table>
</code>```

the result is just a simple table like this. There is no problem when showing my table . But, I want to change the result(in HTML) to something like this

it just like grouping by ItemCode. SO after every itemcode I want to sum QtyBeginning,QtyIn,QtyOut etc.

答:
Sample Data: Thanks to @sintakonte for Test data

```<code>    $arrTestData = [];

    $obj = new stdClass();
    $obj->TransactionNo = "OPM-EC-K-LFMCD2-21.4";
    $obj->StokOpnameTransNo = "OPM-EC-K-LFMCD2-21";
    $obj->ItemCode = "BBG150400005";
    $obj->ItemName = "BIG BAG";
    $obj->OriginalPrice = "289900.00";
    $obj->Price = "289900.00";
    $obj->QtyBegining = "0";
    $obj->QtyIn = "4";
    $obj->QtySales = "0";
    $obj->QtyMutasi = "0";
    $obj->QtyStock = "4";
    $obj->QtyOpname = "2";
    $obj->QtyAdjust = "-4";
    $obj->TotalAdjust = "-1159600.00";
    $obj->rak = "";
    $obj->line = "";
    $obj->TransDate = "2017-03-31 10:46:00.000";
    $obj->CustomerCode = "K-LFMCD2";
    $obj->CreatedBy = "1208496.";
    $obj->Remark = "re";
    $obj->Remark2 = "re";
    $obj->SOTerakhir = "";
    $obj->TglSoTerakhir = "";
    $arrTestData[] = $obj;

    $obj = new stdClass();
    $obj->TransactionNo = "OPM-EC-K-LFMCD2-21.4";
    $obj->StokOpnameTransNo = "OPM-EC-K-LFMCD2-21";
    $obj->ItemCode = "BBG150400005";
    $obj->ItemName = "BIG BAG";
    $obj->OriginalPrice = "289900.00";
    $obj->Price = "289900.00";
    $obj->QtyBegining = "0";
    $obj->QtyIn = "2";
    $obj->QtySales = "0";
    $obj->QtyMutasi = "0";
    $obj->QtyStock = "4";
    $obj->QtyOpname = "4";
    $obj->QtyAdjust = "-4";
    $obj->TotalAdjust = "-1159600.00";
    $obj->rak = "";
    $obj->line = "";
    $obj->TransDate = "2017-03-31 10:46:00.000";
    $obj->CustomerCode = "K-LFMCD2";
    $obj->CreatedBy = "1208496.";
    $obj->Remark = "re";
    $obj->Remark2 = "re";
    $obj->SOTerakhir = "";
    $obj->TglSoTerakhir = "";
    $arrTestData[] = $obj;

    $obj = new stdClass();

    $obj->TransactionNo = "OPM-EC-K-LFMCD2-21.5";
    $obj->StokOpnameTransNo = "OPM-EC-K-LFMCD2-21";
    $obj->ItemCode = "BBG150500063";
    $obj->ItemName = "BIG BAG";
    $obj->OriginalPrice = "479900.00";
    $obj->Price = "479900.00";
    $obj->QtyBegining = "0";
    $obj->QtyIn = "0";
    $obj->QtySales = "0";
    $obj->QtyMutasi = "0";
    $obj->QtyStock = "0";
    $obj->QtyOpname = "1";
    $obj->QtyAdjust = "0";
    $obj->TotalAdjust = ".00";
    $obj->rak = "SS";
    $obj->line = "SS";
    $obj->TransDate = "2017-03-31 10:46:00.000";
    $obj->CustomerCode = "K-LFMCD2";
    $obj->CreatedBy = "1208496.";
    $obj->Remark = "re";
    $obj->Remark2 = "re";
    $obj->SOTerakhir = "";
    $obj->TglSoTerakhir = "";
    $arrTestData[] = $obj;

    $obj = new stdClass();

    $obj->TransactionNo = "OPM-EC-K-LFMCD2-21.5";
    $obj->StokOpnameTransNo = "OPM-EC-K-LFMCD2-21";
    $obj->ItemCode = "BBG150500063";
    $obj->ItemName = "BIG BAG";
    $obj->OriginalPrice = "479900.00";
    $obj->Price = "479900.00";
    $obj->QtyBegining = "0";
    $obj->QtyIn = "1";
    $obj->QtySales = "0";
    $obj->QtyMutasi = "0";
    $obj->QtyStock = "1";
    $obj->QtyOpname = "0";
    $obj->QtyAdjust = "0";
    $obj->TotalAdjust = ".00";
    $obj->rak = "";
    $obj->line = "";
    $obj->TransDate = "2017-03-31 10:46:00.000";
    $obj->CustomerCode = "K-LFMCD2";
    $obj->CreatedBy = "1208496.";
    $obj->Remark = "re";
    $obj->Remark2 = "re";
    $obj->SOTerakhir = "";
    $obj->TglSoTerakhir = "";
    $arrTestData[] = $obj;

    $obj = new stdClass();

    $obj->TransactionNo = "OPM-EC-K-LFMCD2-21.6";
    $obj->StokOpnameTransNo = "OPM-EC-K-LFMCD2-21";
    $obj->ItemCode = "BBG150500081";
    $obj->ItemName = "BIG BAG";
    $obj->OriginalPrice = "229900.00";
    $obj->Price = "229900.00";
    $obj->QtyBegining = "0";
    $obj->QtyIn = "0";
    $obj->QtySales = "0";
    $obj->QtyMutasi = "0";
    $obj->QtyStock = "0";
    $obj->QtyOpname = "1";
    $obj->QtyAdjust = "0";
    $obj->TotalAdjust = ".00";
    $obj->rak = "SS";
    $obj->line = "SS";
    $obj->TransDate = "2017-03-31 10:46:00.000";
    $obj->CustomerCode = "K-LFMCD2";
    $obj->CreatedBy = "1208496.";
    $obj->Remark = "re";
    $obj->Remark2 = "re";
    $obj->SOTerakhir = "";
    $obj->TglSoTerakhir = "";
    $arrTestData[] = $obj;
</code>```

Now, create another array whose key is itemcode, or I can say filter data group by itemcode

```<code>    $newArr = array();
    foreach($arrTestData as $data){
        $newArr[$data->ItemCode][] = $data;
    }
</code>```

Now, display the result data:

```<code>    echo '<table border="2">
                <tr>
                    <td>item code</td>
                    <td>item name</td>
                    <td>QtyBegining</td>
                    <td>QtyIn</td>
                    <td>QtySales</td>
                    <td>QtyMutasi</td>
                    <td>QtyStock</td>
                    <td>QtyOpname</td>
                    <td>QtyAdjust</td>
                    <td>TotalAdjust</td>
                </tr>';  //add others columns as required
    foreach ($newArr as $key => $item){
        $QtyBegining = $QtyIn = $QtySales = $QtyMutasi = $QtyStock = $QtyOpname = $QtyAdjust = $TotalAdjust = 0; // to store sum of each field itemcode wise
        for($i=0; $i<count($item); $i++){
            echo '<tr>'
                    . '<td>'.$item[$i]->ItemCode.'</td>'
                    . '<td>'.$item[$i]->ItemName.'</td>'
                    . '<td>'.$item[$i]->QtyBegining.'</td>'
                    . '<td>'.$item[$i]->QtyIn.'</td>'
                    . '<td>'.$item[$i]->QtySales.'</td>'
                    . '<td>'.$item[$i]->QtyMutasi.'</td>'
                    . '<td>'.$item[$i]->QtyStock.'</td>'
                    . '<td>'.$item[$i]->QtyOpname.'</td>'
                    . '<td>'.$item[$i]->QtyAdjust.'</td>'
                    . '<td>'.$item[$i]->TotalAdjust.'</td>'
                    . '</tr>';
            $QtyBegining += $item[$i]->QtyBegining;
            $QtyIn += $item[$i]->QtyIn;
            $QtySales += $item[$i]->QtySales;
            $QtyMutasi += $item[$i]->QtyMutasi;
            $QtyStock += $item[$i]->QtyStock;
            $QtyOpname += $item[$i]->QtyOpname;
            $QtyAdjust += $item[$i]->QtyAdjust;
            $TotalAdjust += $item[$i]->TotalAdjust;
        } // end for loop
        //now display the sum of each field, note: add empty td as many required
        echo '<tr>'
            . '<td> </td>'
                    . '<td> </td>'
                    . '<td>'.$QtyBegining.'</td>'
                    . '<td>'.$QtyIn.'</td>'
                    . '<td>'.$QtySales.'</td>'
                    . '<td>'.$QtyMutasi.'</td>'
                    . '<td>'.$QtyStock.'</td>'
                    . '<td>'.$QtyOpname.'</td>'
                    . '<td>'.$QtyAdjust.'</td>'
                    . '<td>'.$TotalAdjust.'</td>'
                    . '</tr>';
    }  //end foreach loop
    echo '</table>';
</code>```

Hope this may help you.

Body:
I have this array

   Array
(
    [0] => stdClass Object
        (
            [TransactionNo] => OPM-EC-K-LFMCD2-21.4
            [StokOpnameTransNo] => OPM-EC-K-LFMCD2-21
            [ItemCode] => BBG150400005
            [ItemName] => BIG BAG
            [OriginalPrice] => 289900.00
            [Price] => 289900.00
            [QtyBegining] => 0
            [QtyIn] => 4
            [QtySales] => 0
            [QtyMutasi] => 0
            [QtyStock] => 4
            [QtyOpname] => 0
            [QtyAdjust] => -4
            [TotalAdjust] => -1159600.00
            [rak] =>
            [line] =>
            [TransDate] => 2017-03-31 10:46:00.000
            [CustomerCode] => K-LFMCD2
            [CreatedBy] => 1208496.
            [Remark] => re
            [Remark2] => re
            [SOTerakhir] =>
            [TglSoTerakhir] =>
        )

    [1] => stdClass Object
        (
            [TransactionNo] => OPM-EC-K-LFMCD2-21.5
            [StokOpnameTransNo] => OPM-EC-K-LFMCD2-21
            [ItemCode] => BBG150500063
            [ItemName] => BIG BAG
            [OriginalPrice] => 479900.00
            [Price] => 479900.00
            [QtyBegining] => 0
            [QtyIn] => 0
            [QtySales] => 0
            [QtyMutasi] => 0
            [QtyStock] => 0
            [QtyOpname] => 1
            [QtyAdjust] => 0
            [TotalAdjust] => .00
            [rak] => SS
            [line] => SS
            [TransDate] => 2017-03-31 10:46:00.000
            [CustomerCode] => K-LFMCD2
            [CreatedBy] => 1208496.
            [Remark] => re
            [Remark2] => re
            [SOTerakhir] =>
            [TglSoTerakhir] =>
        )

    [2] => stdClass Object
        (
            [TransactionNo] => OPM-EC-K-LFMCD2-21.5
            [StokOpnameTransNo] => OPM-EC-K-LFMCD2-21
            [ItemCode] => BBG150500063
            [ItemName] => BIG BAG
            [OriginalPrice] => 479900.00
            [Price] => 479900.00
            [QtyBegining] => 0
            [QtyIn] => 1
            [QtySales] => 0
            [QtyMutasi] => 0
            [QtyStock] => 1
            [QtyOpname] => 0
            [QtyAdjust] => 0
            [TotalAdjust] => .00
            [rak] =>
            [line] =>
            [TransDate] => 2017-03-31 10:46:00.000
            [CustomerCode] => K-LFMCD2
            [CreatedBy] => 1208496.
            [Remark] => re
            [Remark2] => re
            [SOTerakhir] =>
            [TglSoTerakhir] =>
        )

    [3] => stdClass Object
        (
            [TransactionNo] => OPM-EC-K-LFMCD2-21.6
            [StokOpnameTransNo] => OPM-EC-K-LFMCD2-21
            [ItemCode] => BBG150500081
            [ItemName] => BIG BAG
            [OriginalPrice] => 229900.00
            [Price] => 229900.00
            [QtyBegining] => 0
            [QtyIn] => 0
            [QtySales] => 0
            [QtyMutasi] => 0
            [QtyStock] => 0
            [QtyOpname] => 1
            [QtyAdjust] => 0
            [TotalAdjust] => .00
            [rak] => SS
            [line] => SS
            [TransDate] => 2017-03-31 10:46:00.000
            [CustomerCode] => K-LFMCD2
            [CreatedBy] => 1208496.
            [Remark] => re
            [Remark2] => re
            [SOTerakhir] =>
            [TglSoTerakhir] =>
        )

)

My array(s) comming from the query result . Then i'm trying to put it to HTML Table so i try this way.

                            No
                            ItemCode
                            ItemName
                            TransNo
                            Original Price
                            Price
                             QtyBeginning
                            QtyIn
                            QtySales
                            QtyMutasi
                            QtyStock
                            QtyOpname
                            QtyAdjust
                            TotalAdjust
                            Rak
                            Line

 <?php $x=0; foreach ($datadetail as $data) { $x++;?>

                                    <?=$x;?>
                                    <?=$data->ItemCode;?>
                                    <?=$data->ItemName;?>
                                    <?=$data->StokOpnameTransNo;?>
                                    <?=$data->OriginalPrice;?>
                                    <?=$data->Price;?>
                                    <?=$data->QtyBegining;?>
                                    <?=$data->QtyIn;?>
                                    <?=$data->QtySales;?>
                                    <?=$data->QtyMutasi;?>
                                    <?=$data->QtyStock;?>
                                    <?=$data->QtyOpname;?>
                                    <?=$data->QtyAdjust;?>
                                    <?=currency($data->TotalAdjust);?>
                                    <?=$data->rak;?>
                                    <?=$data->line;?>

                            <?php } ?>

the result is just a simple table like this. There is no problem when showing my table . But, I want to change the result(in HTML) to something like this

it just like grouping by ItemCode. SO after every itemcode I want to sum QtyBeginning,QtyIn,QtyOut etc.

Body:
Sample Data: Thanks to @sintakonte for Test data

    $arrTestData = [];

    $obj = new stdClass();
    $obj->TransactionNo = "OPM-EC-K-LFMCD2-21.4";
    $obj->StokOpnameTransNo = "OPM-EC-K-LFMCD2-21";
    $obj->ItemCode = "BBG150400005";
    $obj->ItemName = "BIG BAG";
    $obj->OriginalPrice = "289900.00";
    $obj->Price = "289900.00";
    $obj->QtyBegining = "0";
    $obj->QtyIn = "4";
    $obj->QtySales = "0";
    $obj->QtyMutasi = "0";
    $obj->QtyStock = "4";
    $obj->QtyOpname = "2";
    $obj->QtyAdjust = "-4";
    $obj->TotalAdjust = "-1159600.00";
    $obj->rak = "";
    $obj->line = "";
    $obj->TransDate = "2017-03-31 10:46:00.000";
    $obj->CustomerCode = "K-LFMCD2";
    $obj->CreatedBy = "1208496.";
    $obj->Remark = "re";
    $obj->Remark2 = "re";
    $obj->SOTerakhir = "";
    $obj->TglSoTerakhir = "";
    $arrTestData[] = $obj;

    $obj = new stdClass();
    $obj->TransactionNo = "OPM-EC-K-LFMCD2-21.4";
    $obj->StokOpnameTransNo = "OPM-EC-K-LFMCD2-21";
    $obj->ItemCode = "BBG150400005";
    $obj->ItemName = "BIG BAG";
    $obj->OriginalPrice = "289900.00";
    $obj->Price = "289900.00";
    $obj->QtyBegining = "0";
    $obj->QtyIn = "2";
    $obj->QtySales = "0";
    $obj->QtyMutasi = "0";
    $obj->QtyStock = "4";
    $obj->QtyOpname = "4";
    $obj->QtyAdjust = "-4";
    $obj->TotalAdjust = "-1159600.00";
    $obj->rak = "";
    $obj->line = "";
    $obj->TransDate = "2017-03-31 10:46:00.000";
    $obj->CustomerCode = "K-LFMCD2";
    $obj->CreatedBy = "1208496.";
    $obj->Remark = "re";
    $obj->Remark2 = "re";
    $obj->SOTerakhir = "";
    $obj->TglSoTerakhir = "";
    $arrTestData[] = $obj;

    $obj = new stdClass();

    $obj->TransactionNo = "OPM-EC-K-LFMCD2-21.5";
    $obj->StokOpnameTransNo = "OPM-EC-K-LFMCD2-21";
    $obj->ItemCode = "BBG150500063";
    $obj->ItemName = "BIG BAG";
    $obj->OriginalPrice = "479900.00";
    $obj->Price = "479900.00";
    $obj->QtyBegining = "0";
    $obj->QtyIn = "0";
    $obj->QtySales = "0";
    $obj->QtyMutasi = "0";
    $obj->QtyStock = "0";
    $obj->QtyOpname = "1";
    $obj->QtyAdjust = "0";
    $obj->TotalAdjust = ".00";
    $obj->rak = "SS";
    $obj->line = "SS";
    $obj->TransDate = "2017-03-31 10:46:00.000";
    $obj->CustomerCode = "K-LFMCD2";
    $obj->CreatedBy = "1208496.";
    $obj->Remark = "re";
    $obj->Remark2 = "re";
    $obj->SOTerakhir = "";
    $obj->TglSoTerakhir = "";
    $arrTestData[] = $obj;

    $obj = new stdClass();

    $obj->TransactionNo = "OPM-EC-K-LFMCD2-21.5";
    $obj->StokOpnameTransNo = "OPM-EC-K-LFMCD2-21";
    $obj->ItemCode = "BBG150500063";
    $obj->ItemName = "BIG BAG";
    $obj->OriginalPrice = "479900.00";
    $obj->Price = "479900.00";
    $obj->QtyBegining = "0";
    $obj->QtyIn = "1";
    $obj->QtySales = "0";
    $obj->QtyMutasi = "0";
    $obj->QtyStock = "1";
    $obj->QtyOpname = "0";
    $obj->QtyAdjust = "0";
    $obj->TotalAdjust = ".00";
    $obj->rak = "";
    $obj->line = "";
    $obj->TransDate = "2017-03-31 10:46:00.000";
    $obj->CustomerCode = "K-LFMCD2";
    $obj->CreatedBy = "1208496.";
    $obj->Remark = "re";
    $obj->Remark2 = "re";
    $obj->SOTerakhir = "";
    $obj->TglSoTerakhir = "";
    $arrTestData[] = $obj;

    $obj = new stdClass();

    $obj->TransactionNo = "OPM-EC-K-LFMCD2-21.6";
    $obj->StokOpnameTransNo = "OPM-EC-K-LFMCD2-21";
    $obj->ItemCode = "BBG150500081";
    $obj->ItemName = "BIG BAG";
    $obj->OriginalPrice = "229900.00";
    $obj->Price = "229900.00";
    $obj->QtyBegining = "0";
    $obj->QtyIn = "0";
    $obj->QtySales = "0";
    $obj->QtyMutasi = "0";
    $obj->QtyStock = "0";
    $obj->QtyOpname = "1";
    $obj->QtyAdjust = "0";
    $obj->TotalAdjust = ".00";
    $obj->rak = "SS";
    $obj->line = "SS";
    $obj->TransDate = "2017-03-31 10:46:00.000";
    $obj->CustomerCode = "K-LFMCD2";
    $obj->CreatedBy = "1208496.";
    $obj->Remark = "re";
    $obj->Remark2 = "re";
    $obj->SOTerakhir = "";
    $obj->TglSoTerakhir = "";
    $arrTestData[] = $obj;

Now, create another array whose key is itemcode, or I can say filter data group by itemcode

    $newArr = array();
    foreach($arrTestData as $data){
        $newArr[$data->ItemCode][] = $data;
    }

Now, display the result data:

    echo '<table border="2">
                <tr>
                    <td>item code</td>
                    <td>item name</td>
                    <td>QtyBegining</td>
                    <td>QtyIn</td>
                    <td>QtySales</td>
                    <td>QtyMutasi</td>
                    <td>QtyStock</td>
                    <td>QtyOpname</td>
                    <td>QtyAdjust</td>
                    <td>TotalAdjust</td>
                </tr>';  //add others columns as required
    foreach ($newArr as $key => $item){
        $QtyBegining = $QtyIn = $QtySales = $QtyMutasi = $QtyStock = $QtyOpname = $QtyAdjust = $TotalAdjust = 0; // to store sum of each field itemcode wise
        for($i=0; $i<count($item); $i++){
            echo '<tr>'
                    . '<td>'.$item[$i]->ItemCode.'</td>'
                    . '<td>'.$item[$i]->ItemName.'</td>'
                    . '<td>'.$item[$i]->QtyBegining.'</td>'
                    . '<td>'.$item[$i]->QtyIn.'</td>'
                    . '<td>'.$item[$i]->QtySales.'</td>'
                    . '<td>'.$item[$i]->QtyMutasi.'</td>'
                    . '<td>'.$item[$i]->QtyStock.'</td>'
                    . '<td>'.$item[$i]->QtyOpname.'</td>'
                    . '<td>'.$item[$i]->QtyAdjust.'</td>'
                    . '<td>'.$item[$i]->TotalAdjust.'</td>'
                    . '</tr>';
            $QtyBegining += $item[$i]->QtyBegining;
            $QtyIn += $item[$i]->QtyIn;
            $QtySales += $item[$i]->QtySales;
            $QtyMutasi += $item[$i]->QtyMutasi;
            $QtyStock += $item[$i]->QtyStock;
            $QtyOpname += $item[$i]->QtyOpname;
            $QtyAdjust += $item[$i]->QtyAdjust;
            $TotalAdjust += $item[$i]->TotalAdjust;
        } // end for loop
        //now display the sum of each field, note: add empty td as many required
        echo '<tr>'
            . '<td>&nbsp;</td>'
                    . '<td>&nbsp;</td>'
                    . '<td>'.$QtyBegining.'</td>'
                    . '<td>'.$QtyIn.'</td>'
                    . '<td>'.$QtySales.'</td>'
                    . '<td>'.$QtyMutasi.'</td>'
                    . '<td>'.$QtyStock.'</td>'
                    . '<td>'.$QtyOpname.'</td>'
                    . '<td>'.$QtyAdjust.'</td>'
                    . '<td>'.$TotalAdjust.'</td>'
                    . '</tr>';
    }  //end foreach loop
    echo '</table>';

Hope this may help you.


问:
How change size of imageView(SubView) in Cell in CollectionView
I have a problem with image in cell. More precisely image in assets are bigger than cell. How i can transform image to smaller size? </p>

<p>`   var photos = ["IMG_3814","IMG_3803"]</p>

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return photos.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellID", for: indexPath)
    let img = photos[indexPath.row]
    let imageView: UIImageView = UIImageView(image: UIImage(named: img))

    cell.contentView.addSubview(imageView)

    return cell
}`
</code>```

答:
Try using

```<code>let imageView: UIImageView = UIImageView(image: UIImage(named: img))
imageView.frame = cell.contentView.frame
imageView.contentMode = .scaleAspectFit
</code>```

it will adjust your image to imageView

Body:
I have a problem with image in cell. More precisely image in assets are bigger than cell. How i can transform image to smaller size?

`   var photos = ["IMG_3814","IMG_3803"]

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return photos.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellID", for: indexPath)
    let img = photos[indexPath.row]
    let imageView: UIImageView = UIImageView(image: UIImage(named: img))

    cell.contentView.addSubview(imageView)

    return cell
}`

Body:
Try using

let imageView: UIImageView = UIImageView(image: UIImage(named: img))
imageView.frame = cell.contentView.frame
imageView.contentMode = .scaleAspectFit

it will adjust your image to imageView


问:
How to download a file from a url with Javascript?
How to download a file from a url with Javascript?

I'm trying to get from a textfield a user enters a url as follows:

```<code>new Ext.form.TextField({
                disabled: false,
                        fieldLabel: "file",
                        value:'',
            id:"url"};
</code>```

and I need the value of this variable is the file contained in the above url I am trying as follows:

```<code>var file1 = new OpenLayers.WPS.ComplexPut({
                      identifier: "file1",
                      value: window.location.href = document.getElementById("url")
</code>```

答: is this done in a browser? If so, you could use Ajax to download plain text or XML. Save yourself a lot of trouble and learn jQuery first, and it'll be quite easy.</p>

ContentLicense: CC BY-SA 4.0

Body:
How to download a file from a url with Javascript?

I'm trying to get from a textfield a user enters a url as follows:

new Ext.form.TextField({
                disabled: false,
                        fieldLabel: "file",
                        value:'',
            id:"url"};

and I need the value of this variable is the file contained in the above url I am trying as follows:

var file1 = new OpenLayers.WPS.ComplexPut({
                      identifier: "file1",
                      value: window.location.href = document.getElementById("url")

ContentLicense: CC BY-SA 2.5


问:
GCM push notifications not working if the app is closed in some devices
I've followed Google's GCM setup guide and their example on Github to create an app that receives notifications.

When does it work:

App opened (all devices)

App in background (all devices)

App closed (all except one)

The phone that is not working:

Huawei P8 lite

Android 5.1

Google Play Services 8.3.01

This phone works fine, it can receive WhatsApp messages or any other kind even if the user kills the app.

I am afraid this could happen in many other devices I haven't test. So I want to show off some code in order to see if there are any problems.

Here my AndroidManifest.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.presentation" >

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <!-- Keeps the processor from sleeping when a message is received. -->
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <!-- This app has permission to register and receive data message. -->
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

    <permission
        android:name="com.example.presentation.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />
    <uses-permission android:name="com.example.presentation.permission.C2D_MESSAGE" />

    <application
        android:name=".AndroidApplication"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <receiver
            android:name="com.google.android.gms.gcm.GcmReceiver"
            android:exported="true"
            android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <category android:name="com.example.presentation" />
                <!-- If you want to support pre-4.4 KitKat devices. -->
                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
            </intent-filter>
        </receiver>
        <service android:name="com.example.data.gcm.RegistrationIntentService"
            android:exported="false" />
        <service
            android:name="com.example.data.gcm.MyGcmListenerService"
            android:exported="false" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            </intent-filter>
        </service>
        <service
            android:name="com.example.data.gcm.MyInstanceIDListenerService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.android.gms.iid.InstanceID"/>
            </intent-filter>
        </service>

    </application>

</manifest>
</code>```

Added this dependency in the project-level build.gradle:

```<code>buildscript {
  repositories {
    jcenter()
  }
  dependencies {
    classpath 'com.android.tools.build:gradle:1.3.0'
    classpath 'com.neenbedankt.gradle.plugins:android-apt:1.4'
    classpath 'com.google.gms:google-services:1.4.0-beta3'
  }
}
</code>```

Added this dependency in the app-level build.gradle:

```<code>compile "com.google.android.gms:play-services-gcm:8.1.0"
</code>```

And the Java classes are the same of the Github example.

Why is this device not working when the user closes the app but it works in all other devices I have tested?

答:
It's a "bug/feature" of Huawei devices.

Android - GCM - Not receiving push notifications on background

Once you kill application on xiaomi, huawei these phones unregister broadcast receivers, services of the application.

In case of notification, your GCM broadcastreceiver get unregistered on killing >app, that is likely the reason for this.

User has to add your app on a whilelist on the battery manager

https://www.forbes.com/sites/bensin/2016/07/04/push-notifications-not-coming-through-to-your-huawei-phone-heres-how-to-fix-it/#578f42bd1ccc

Tested on Huawei Gra-L09 with Android 5.0.1

EDITED:

You can warn the user and launch Protected Apps manager.

"Protected Apps" setting on Huawei phones, and how to handle it

Body:
I've followed Google's GCM setup guide and their example on Github to create an app that receives notifications.

When does it work:

App opened (all devices)

App in background (all devices)

App closed (all except one)

The phone that is not working:

Huawei P8 lite

Android 5.1

Google Play Services 8.3.01

This phone works fine, it can receive WhatsApp messages or any other kind even if the user kills the app.

I am afraid this could happen in many other devices I haven't test. So I want to show off some code in order to see if there are any problems.

Here my AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.presentation" >

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

    <permission
        android:name="com.example.presentation.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />
    <uses-permission android:name="com.example.presentation.permission.C2D_MESSAGE" />

    <application
        android:name=".AndroidApplication"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <receiver
            android:name="com.google.android.gms.gcm.GcmReceiver"
            android:exported="true"
            android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <category android:name="com.example.presentation" />

                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
            </intent-filter>
        </receiver>
        <service android:name="com.example.data.gcm.RegistrationIntentService"
            android:exported="false" />
        <service
            android:name="com.example.data.gcm.MyGcmListenerService"
            android:exported="false" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            </intent-filter>
        </service>
        <service
            android:name="com.example.data.gcm.MyInstanceIDListenerService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.android.gms.iid.InstanceID"/>
            </intent-filter>
        </service>

    </application>

</manifest>

Added this dependency in the project-level build.gradle:

buildscript {
  repositories {
    jcenter()
  }
  dependencies {
    classpath 'com.android.tools.build:gradle:1.3.0'
    classpath 'com.neenbedankt.gradle.plugins:android-apt:1.4'
    classpath 'com.google.gms:google-services:1.4.0-beta3'
  }
}

Added this dependency in the app-level build.gradle:

compile "com.google.android.gms:play-services-gcm:8.1.0"

And the Java classes are the same of the Github example.

Why is this device not working when the user closes the app but it works in all other devices I have tested?


问:
php artisan migrate:reset failed to open stream: No such file or directory
when I ran

```<code>php artisan migrate:reset
</code>```

I got

```<code>[ErrorException]
include(app/database/migrations/2014_08_06_120900_alter_xxx_table.php): failed to
open stream: No such file or directory
</code>```

But I don't have that php file, I just have another file named

```<code>2014_08_06_121048_alter_xxx_table.php
</code>```

And the migrations table in mysql has only

```<code>2014_08_06_121048_alter_xxx_table.php
</code>```

but not

```<code>2014_08_06_120900_alter_xxx_table.php
</code>```

Now I can't reset my database. What can I do about this?

答:
```<code>php artisan dump-autoload
</code>```

It do well in windows10.

Body:
when I ran

php artisan migrate:reset

I got

[ErrorException]
include(app/database/migrations/2014_08_06_120900_alter_xxx_table.php): failed to
open stream: No such file or directory

But I don't have that php file, I just have another file named

2014_08_06_121048_alter_xxx_table.php

And the migrations table in mysql has only

2014_08_06_121048_alter_xxx_table.php

but not

2014_08_06_120900_alter_xxx_table.php

Now I can't reset my database. What can I do about this?

Body:
php artisan dump-autoload

It do well in windows10.


问:
spring data Page/Pageable can't deserialization,how to use?
if use Page/Pageable in controller with rest, I got error,because they hasn't empty construct for deserialization</p>

```<code>Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of org.springframework.data.domain.Page, problem: abstract types either need to be mapped to concrete types, have custom deserializer, or be instantiated with additional type information
 at [Source: java.io.PushbackInputStream@67635da8; line: 1, column: 1]
at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148) ~[jackson-databind-2.6.4.jar:2.6.4]
at com.fasterxml.jackson.databind.DeserializationContext.instantiationException(DeserializationContext.java:892) ~[jackson-databind-2.6.4.jar:2.6.4]
at com.fasterxml.jackson.databind.deser.AbstractDeserializer.deserialize(AbstractDeserializer.java:139) ~[jackson-databind-2.6.4.jar:2.6.4]
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3736) ~[jackson-databind-2.6.4.jar:2.6.4]
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2810) ~[jackson-databind-2.6.4.jar:2.6.4]
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:221) ~[spring-web-4.2.4.RELEASE.jar:4.2.4.RELEASE]
... 30 common frames omitted
</code>```

答:
If you pass the parameters throught the HTTP Body, you need use a concrete implementation. The Daniel's solution is recommanded.

Another smart solution is using the HandlerMethodArgumentResolver

Step 1 - Creation of your argument handler similar to this

```<code>public class PageableHandler implements HandlerMethodArgumentResolver
{
    @Override
    public boolean supportsParameter(MethodParameter methodParameter)
    {
        return methodParameter.getParameterType().equals(Pageable.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception
    {
        String limit = nativeWebRequest.getParameter("limit");
        int size = toInt(limit, 100);

        String offset = nativeWebRequest.getParameter("offset");
        int page = (toInt(offset, size) / size);
        Sort sort = null;
        String sortStr = nativeWebRequest.getParameter("sort");
        String orderStr = nativeWebRequest.getParameter("order");
        if(sortStr != null && orderStr != null)
        {
            Direction direction = "asc".equalsIgnoreCase(orderStr) ? Direction.ASC : Direction.DESC;
            sort = new Sort(direction, sortStr);
        }
        return new PageRequest(page, size, sort);
    }

    private int toInt(String value, int defaultValue)
    {
        int resultValue = defaultValue;
        if(value != null)
        {
            try
            {
                resultValue = Integer.parseInt(value);
            }catch(NumberFormatException e)
            {
            }
        }
        return resultValue;
    }

}
</code>```

Step 2 - Register your handler on a Spring Configuration

```<code>@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(new PageableHandler());
        super.addArgumentResolvers(argumentResolvers);
    }
}
</code>```

Step 3 - Enjoy use on your controller

```<code>@RequestMapping(value = "/api/personne", method = RequestMethod.GET)
public List<Personne> getAllPersonnes(Pageable pageable) {
    return adminService.getAllPersonnes(pageable);
}
</code>```

Step 4 - Example of REST GET

```<code>http://localhost:8080/api/personne?offset=2&limit=25
</code>```

Body:
if use Page/Pageable in controller with rest, I got error,because they hasn't empty construct for deserialization

Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of org.springframework.data.domain.Page, problem: abstract types either need to be mapped to concrete types, have custom deserializer, or be instantiated with additional type information
 at [Source: java.io.PushbackInputStream@67635da8; line: 1, column: 1]
at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148) ~[jackson-databind-2.6.4.jar:2.6.4]
at com.fasterxml.jackson.databind.DeserializationContext.instantiationException(DeserializationContext.java:892) ~[jackson-databind-2.6.4.jar:2.6.4]
at com.fasterxml.jackson.databind.deser.AbstractDeserializer.deserialize(AbstractDeserializer.java:139) ~[jackson-databind-2.6.4.jar:2.6.4]
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3736) ~[jackson-databind-2.6.4.jar:2.6.4]
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2810) ~[jackson-databind-2.6.4.jar:2.6.4]
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:221) ~[spring-web-4.2.4.RELEASE.jar:4.2.4.RELEASE]
... 30 common frames omitted

Body:
If you pass the parameters throught the HTTP Body, you need use a concrete implementation. The Daniel's solution is recommanded.

Another smart solution is using the HandlerMethodArgumentResolver

Step 1 - Creation of your argument handler similar to this

public class PageableHandler implements HandlerMethodArgumentResolver
{
    @Override
    public boolean supportsParameter(MethodParameter methodParameter)
    {
        return methodParameter.getParameterType().equals(Pageable.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception
    {
        String limit = nativeWebRequest.getParameter("limit");
        int size = toInt(limit, 100);

        String offset = nativeWebRequest.getParameter("offset");
        int page = (toInt(offset, size) / size);
        Sort sort = null;
        String sortStr = nativeWebRequest.getParameter("sort");
        String orderStr = nativeWebRequest.getParameter("order");
        if(sortStr != null && orderStr != null)
        {
            Direction direction = "asc".equalsIgnoreCase(orderStr) ? Direction.ASC : Direction.DESC;
            sort = new Sort(direction, sortStr);
        }
        return new PageRequest(page, size, sort);
    }

    private int toInt(String value, int defaultValue)
    {
        int resultValue = defaultValue;
        if(value != null)
        {
            try
            {
                resultValue = Integer.parseInt(value);
            }catch(NumberFormatException e)
            {
            }
        }
        return resultValue;
    }

}

Step 2 - Register your handler on a Spring Configuration

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(new PageableHandler());
        super.addArgumentResolvers(argumentResolvers);
    }
}

Step 3 - Enjoy use on your controller

@RequestMapping(value = "/api/personne", method = RequestMethod.GET)
public List<Personne> getAllPersonnes(Pageable pageable) {
    return adminService.getAllPersonnes(pageable);
}

Step 4 - Example of REST GET

http://localhost:8080/api/personne?offset=2&limit=25


问:
How to hide or show a content of a python function on qweb report depend on condition?
im trying to re design my Odoo 9 qweb report. that inherited sale_order_report. I have created some python function that have been called on the qweb. Now i would like to hide that content of the python function depend on conditions. Please take a moment to read my code bellow and help me to point out the specifics way to solve the problem?

```<code>@api.multi
def handle_detail(self, order_line):
    dict_item = {}
    for line in order_line:
        for key in
        quantity_extra = int(line.quantity_extra)
        if quantity_extra not in dict_item.keys():
                dict_item[quantity_extra].append(line.lng)
            else:
                dict_item[quantity_extra] = [line.lng]
result = []
total = 0.0
for item in dict_item.keys():
    lst_ing = dict_item[item]
    if len(lst_ing) > 1:
        result.append(
            '( %s ) x %s' % (' + '.join([str(lng) for lng in lst_ing]),
                             str(item)))
        total += (sum(lst_ing) * item)
    else:
        result.append('%s x %s' % (str(lst_ing[0]), str(item)))
        total += (lst_ing[0] * item)
return result, total
</code>```

Thank for your time.

答:
surround the code in the template by a t-if statement like this</p>

```<code> <t t-if="condition"> <!-- if the condition is true the contenant is shown -->
       <....code that calls the method and show the value on the template />
  </t>
</code>```

Body:
im trying to re design my Odoo 9 qweb report. that inherited sale_order_report. I have created some python function that have been called on the qweb. Now i would like to hide that content of the python function depend on conditions. Please take a moment to read my code bellow and help me to point out the specifics way to solve the problem?

@api.multi
def handle_detail(self, order_line):
    dict_item = {}
    for line in order_line:
        for key in
        quantity_extra = int(line.quantity_extra)
        if quantity_extra not in dict_item.keys():
                dict_item[quantity_extra].append(line.lng)
            else:
                dict_item[quantity_extra] = [line.lng]
result = []
total = 0.0
for item in dict_item.keys():
    lst_ing = dict_item[item]
    if len(lst_ing) > 1:
        result.append(
            '( %s ) x %s' % (' + '.join([str(lng) for lng in lst_ing]),
                             str(item)))
        total += (sum(lst_ing) * item)
    else:
        result.append('%s x %s' % (str(lst_ing[0]), str(item)))
        total += (lst_ing[0] * item)
return result, total

Thank for your time.

Body:
surround the code in the template by a t-if statement like this

 <t t-if="condition"> <!-- if the condition is true the contenant is shown -->
       <....code that calls the method and show the value on the template />
  </t>


问:
Aot errors angular 2 different behaviour
I'm building my angular 2 project with angular-cli. Locally I build it with no problem for prod ng build --prod --aot. When it is build on the server however the following errors are present:

```<code>...
 [1m [31mERROR in
<frontend/src/$$_gendir/app/incidents/dialog/tabs/measurements/incident.measurements.component.ngfactory.ts>
(1080,35): Supplied parameters do not match any signature of call
target. [39m [22m

 [1m [31mERROR in
<frontend/src/$$_gendir/app/incidents/dialog/tabs/measurements/incident.measure.form.ngfactory.ts>
(1050,89): Property 'takenMeassure' does not exist on type
'IncidentAction'. [39m [22m

 [1m [31mERROR in
<frontend/src/$$_gendir/app/shared/dropdown/custom-dropdown.component.ngfactory.ts>
(94,7): Supplied parameters do not match any signature of call
target. [39m [22m
...
</code>```

Those errors are correct and should be fixed, but why is the angular compiler more restrictive on the server machine than on my local one. The versions of all libraries are fixed and every time the project is build on the server the node_modules folder is deleted and all dependencies are downloaded again. Why do I get different behaviour when all the things are the same. Any idea is of great help :)

答:
How do you build your project locally? Are using the AoT compiler or the JIT compiler locally?

The AoT compiler needs to be more strict to know how to pre-compile your code.

Body:
I'm building my angular 2 project with angular-cli. Locally I build it with no problem for prod ng build --prod --aot. When it is build on the server however the following errors are present:

...
 [1m [31mERROR in
<frontend/src/$$_gendir/app/incidents/dialog/tabs/measurements/incident.measurements.component.ngfactory.ts>
(1080,35): Supplied parameters do not match any signature of call
target. [39m [22m

 [1m [31mERROR in
<frontend/src/$$_gendir/app/incidents/dialog/tabs/measurements/incident.measure.form.ngfactory.ts>
(1050,89): Property 'takenMeassure' does not exist on type
'IncidentAction'. [39m [22m

 [1m [31mERROR in
<frontend/src/$$_gendir/app/shared/dropdown/custom-dropdown.component.ngfactory.ts>
(94,7): Supplied parameters do not match any signature of call
target. [39m [22m
...

Those errors are correct and should be fixed, but why is the angular compiler more restrictive on the server machine than on my local one. The versions of all libraries are fixed and every time the project is build on the server the node_modules folder is deleted and all dependencies are downloaded again. Why do I get different behaviour when all the things are the same. Any idea is of great help :)


问:
highchart is not displaying in django twitter bootstrap
I am having problem with displaying highchart in django. I am using twitter bootstrap.Chart is not showing in chart.html. Can anyone help me what I am doing wrong here?Please find below version of django

Django==1.8.7

django-highcharts==0.1.7

base.html:

```<code><!DOCTYPE html>
{% load staticfiles %}
<html>
<head>
  {% block title %}<title>mbr page </title>{% endblock %}
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="{% static "mbr/css/boostrap-fluid-adj.css" %}" rel="stylesheet">
  <link href="{% static "mbr/css/bootstrap.min.css" %}" rel="stylesheet" media="screen">
  <link href="{% static "mbr/css/bootstrap-responsive.css" %}" rel="stylesheet">

  <style>
  body {
    padding-top: 50px;
  }
  @media (max-width: 980px) {
    body {
      padding-top: 0;
    }
  }
</style>
</head

<body>
<div class="navbar navbar-inverse navbar-fixed-top">
   <div class="navbar-inner">
       <div class="container-fluid">
           <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
               <span class="icon-bar"></span>
               <span class="icon-bar"></span>
               <span class="icon-bar"></span>
           </button>

           <div class="nav-collapse collapse">
               <ul class="nav pull-right">
                    <li><a href="/admin/">Login</a></li>
               </ul>
               <ul class="nav navbar-nav">
                    <li class="active"><a href="/mbr/">Home</a></li>
                    <li><a href="{% url 'search_form' %}">Search s</a></li>
                    <li><a href="{% url 'results_list' %}">Results History</a></li>
                    <li><a href="{% url 'chart_test' %}">Statistics</a></li>
               </ul>
           </div>
       </div>
   </div>
</div>
<div class="container-fluid">
    <div class="row-fluid">
        <div class="span3">
             <div class="well sidebar-nav">
              <h3> Name</h3>
              <p class="active"><a href="/mbr/4/">TEST1</a></p>
              <p><a href="/mbr/3/">TEST2</a></p>
              <p><a href="/mbr/2/">TEST3</a></p>
              <p><a href="/mbr/1/">TEST4</a></p>
             </div>
        </div>
        <div class="span9">
            {% block content %}
            {% endblock %}
        </div>
    </div>
</div>

<hr>
<script src="{% static 'mbr/js/jquery-3.2.0.js' %}"></script>
<script src="{% static 'mbr/js/bootstrap.min.js' %}"></script>
</body>
</html>
</code>```

chart_test.html:

```<code>{% extends "base.html" %}
{% load staticfiles %}
{% block content %}
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<!--<script src="{% static "js/jquery.min.js" %}"></script>-->
<!--<script src="{% static "js/highcharts.js" %}"></script>-->
</head>
<body>
<script type="text/javascript">
$(function () {
$('#chart_container').highcharts({
chart: {
type: 'bar'
},
title: {
text: 'Monthly Sales'
},
xAxis: {
categories: ['Jan','Feb','Mar','Apr']
},
yAxis: {
title: {
text: 'numbers'
}
},
series: [{
name: 'John',
data: [1, 0, 4]
}, {
name: 'King',
data: [5, 7, 3]
}]
});
});
</script>
<div id="chart_container" style="height: 300px"></div>
</body>
</html>
{% endblock %}
</code>```

view:

```<code>def chart_test(request):
     return render(request,'mbr/chart_test.html')
</code>```

答:
chart_test.html extends base.html - it should not contain html/body tag anymore and you load jquery twice - once in base and once in chart_test...
try something like:</p>

```<code>{% extends "base.html" %}
{% load staticfiles %}
{% block content %}

<div id="chart_container" style="height: 300px"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script type="text/javascript">
$(function() {
$('#chart_container').highcharts({
chart: {
type: 'bar'
},
title: {
text: 'Monthly Sales'
},
xAxis: {
categories: ['Jan','Feb','Mar','Apr']
},
yAxis: {
title: {
text: 'numbers'
}
},
series: [{
name: 'John',
data: [1, 0, 4]
}, {
name: 'King',
data: [5, 7, 3]
}]
});
});
</script>
{% endblock %}
</code>```

Body:
I am having problem with displaying highchart in django. I am using twitter bootstrap.Chart is not showing in chart.html. Can anyone help me what I am doing wrong here?Please find below version of django

Django==1.8.7

django-highcharts==0.1.7

base.html:

<!DOCTYPE html>
{% load staticfiles %}

  {% block title %}<title>mbr page </title>{% endblock %}
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="{% static "mbr/css/boostrap-fluid-adj.css" %}" rel="stylesheet">
  <link href="{% static "mbr/css/bootstrap.min.css" %}" rel="stylesheet" media="screen">
  <link href="{% static "mbr/css/bootstrap-responsive.css" %}" rel="stylesheet">

</head

           <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">

           </button>

Login

Home

Search s

Results History

Statistics

 Name

TEST1

TEST2

TEST3

TEST4

            {% block content %}
            {% endblock %}

chart_test.html:

{% extends "base.html" %}
{% load staticfiles %}
{% block content %}

{% endblock %}

view:

def chart_test(request):
     return render(request,'mbr/chart_test.html')

Body:
chart_test.html extends base.html - it should not contain html/body tag anymore and you load jquery twice - once in base and once in chart_test...
try something like:

{% extends "base.html" %}
{% load staticfiles %}
{% block content %}

<div id="chart_container" style="height: 300px"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script type="text/javascript">
$(function() {
$('#chart_container').highcharts({
chart: {
type: 'bar'
},
title: {
text: 'Monthly Sales'
},
xAxis: {
categories: ['Jan','Feb','Mar','Apr']
},
yAxis: {
title: {
text: 'numbers'
}
},
series: [{
name: 'John',
data: [1, 0, 4]
}, {
name: 'King',
data: [5, 7, 3]
}]
});
});
</script>
{% endblock %}


问:
Cocos2d - Creating collidable Sprites?
Hello everyone I an very new to cocos2d, so I apologize if this is a simple question. I would like to create to sprites that collide when they hit each other.

For instance, one sprite, spriteA, is in a fixed position on the screen. And another sprite, spriteB, is moving around the screen. SpriteB will collide with spriteA. If that doesn't make sense or you don't understand it, tell me and I will elaborate further. Any help is appreciated. Thank YOU!

答:
Try using Chipmunk or Box2d physics systems. These are included with Cocos2d and work by having a physics simulation that updates with every time the graphics change on screen.

The physics simulation will tell you if two objects are overlapping, and will provide physical attributes like weight, slipperiness (friction), speed and direction, which creates reactions like bouncing, sliding, realistic loss of speed and changes of direction on impact.

If you are new to physics simulation, here's a 30 second run down:

Create "bodies" in the physics simulation that represent each graphical sprite

Bodies are usually defined more simply than their graphical counterparts, like a circle, square or simple polygon shape

In order to update the graphics on the screen accurately, first you establish a pixels to meters ratio. Meters are notional (i.e. made up) measurement that is used in the physics sim

Each time the physics simulation "ticks", you update the graphics on screen accordingly

So if a body in the physics sim moves 1 meter, you might transform the pixel sprite 32 pixels

Here's a good tute on collision detection using Box2d.
http://www.raywenderlich.com/606/how-to-use-box2d-for-just-collision-detection-with-cocos2d-iphone

enjoy

Title: Cocos2d - Creating collidable Sprites?


问:
C# How to convert specific lower-case letters to uppercase and uppercase letters to lowercase at the same time
I want to exchange all occurences of a character in a string with their case-counterpart.

For example:

"%Y %m %d | %H:%M:%S"

should become

"%Y %M %d | %H:%m:%S"

for the character 'm' or 'M'.

How can I best do this in C# ?

答:
You could use regexes... there are two possibilities here:

One using two distinct groupings and choosing which grouping was used in the replace function:

```<code>var rx1 = new Regex("(%M)|(%m)");

string original1 = "%Y %m %d | %H:%M:%S";
string modified1 = rx1.Replace(original1, x => x.Groups[1].Success ? "%m" : "%M");
</code>```

The other simply taking a look in the replace function on what is the matched text.

```<code>var rx2 = new Regex("%[Mm]");

string original2 = "%Y %m %d | %H:%M:%S";
string modified2 = rx2.Replace(original2, x => x.Value == "%M" ? "%m" : "%M");
</code>```

Just as a curiousity, I'll add two regexes that handle the escaping of a % with another %: %m is month, %%m is the string %m, %%%m is % plus the month.

```<code>var rx1 = new Regex("(?<=(?:^|[^%])(?:%%)*)(?:(%M)|(%m))");
</code>```

and

```<code>var rx2 = new Regex("(?<=(?:^|[^%])(?:%%)*)%[Mm]");
</code>```

Body:
You could use regexes... there are two possibilities here:

One using two distinct groupings and choosing which grouping was used in the replace function:

var rx1 = new Regex("(%M)|(%m)");

string original1 = "%Y %m %d | %H:%M:%S";
string modified1 = rx1.Replace(original1, x => x.Groups[1].Success ? "%m" : "%M");

The other simply taking a look in the replace function on what is the matched text.

var rx2 = new Regex("%[Mm]");

string original2 = "%Y %m %d | %H:%M:%S";
string modified2 = rx2.Replace(original2, x => x.Value == "%M" ? "%m" : "%M");

Just as a curiousity, I'll add two regexes that handle the escaping of a % with another %: %m is month, %%m is the string %m, %%%m is % plus the month.

var rx1 = new Regex("(?<=(?:^|[^%])(?:%%)*)(?:(%M)|(%m))");

and

var rx2 = new Regex("(?<=(?:^|[^%])(?:%%)*)%[Mm]");


问:
Disable add to cart if in quantity box is 0
I'm looking for solution for my problem. I have category list with add to cart button and quantity box. I need to disable add to cart when is in quantity box 0 and allow it when is 1 and more.
I need default value 0.
Now, when I click to add to cart button is added one product to the cart.

This problem is just in category list, not on product page.

My code from /app/design/frontend/theme/theme/template/catalog/product/list.phtml

```<code><?php  if ( !($product->getTypeInstance(true)->hasOptions($product)/*$_product->getData('has_options')*/ || $product->isGrouped()) ) :  ?>

                                <div class="qty-holder">
                                    <input type="text" name="qty" id="qty_<?php echo $_product->getId(); ?>" maxlength="12" value="<?php echo $product->getProductDefaultQty() * 1 ?>" title="<?php echo $this->__('Qty') ?>" class="input-text qty" />
                                    <div class="qty-changer">
                                        <a href="javascript:void(0)" class="qty_inc" style="height:34px; line-height:34px;"><i class="icon-up-dir"></i></a>
                                        <a href="javascript:void(0)" class="qty_dec" style="height:34px; line-height:34px;"><i class="icon-down-dir"></i></a>
                                    </div>
                                </div>
                            </form>
                            <?php $_productid == $_product->getId(); ?>

                            <a href="<?php if(!Mage::getStoreConfig("ajaxcart/addtocart/enablecategory", $code) && !Mage::getStoreConfig("porto_settings/category/qty_field", $code)): ?><?php echo $this->getAddToCartUrl($_product) ?><?php else: ?>javascript:void(0)<?php endif; ?>" class="addtocart" title="<?php echo $this->__('Add to Cart') ?>" <?php if(Mage::getStoreConfig("ajaxcart/addtocart/enablecategory", $code)):?>onclick="setLocationAjax(this,'<?php echo $this->getAddToCartUrl($_product) ?>','<?php echo $_product->getId(); ?>')"<?php elseif(Mage::getStoreConfig("porto_settings/category/qty_field", $code)): ?>onclick="document.getElementById('addtocart_form_<?php echo $_product->getId(); ?>').submit()"<?php endif; ?>><i class="icon-cart"></i><span> <?php echo $this->__('Add to Cart') ?></span></a>

                        <?php else : ?>
                            <a href="<?php if(Mage::getStoreConfig("ajaxcart/addtocart/enablecategory", $code)):?>javascript:showOptions('<?php echo $_product->getId()?>')<?php else: ?><?php echo $this->getAddToCartUrl($_product) ?><?php endif; ?>" class="addtocart" title="<?php echo $this->__('Add to Cart') ?>"><i class="icon-cart"></i><span> <?php echo $this->__('Add to Cart') ?></span></a>
                            <a href='<?php echo $this->getUrl('ajaxcart/index/options',array('product_id'=>$_product->getId()));?>' class='fancybox' id='fancybox<?php echo $_product->getId()?>' style='display:none'>Options</a>
                        <?php endif;?>
</code>```

Any ideas?

Thanks!

答:
Maybe something like this (javascript):

```<code>jQuery('.addtocart').each(function() {
    var $self = jQuery(this),
        oldOnClick = $self.attr('onclick'),
        $product = $self.closest('.item');

    $self.attr('data-onclick', oldOnClick).removeAttr('onclick');
    $self.off('click').on('click', function() {
        if($product.find('.input-text.qty').val() < 1)
            return false;
        else
            eval(jQuery(this).data('onclick'));
    });
});
</code>```

When user clicks on 'add to cart', check if the quantity value is >= 1.

Edit: fix some things..

Body:
I'm looking for solution for my problem. I have category list with add to cart button and quantity box. I need to disable add to cart when is in quantity box 0 and allow it when is 1 and more.
I need default value 0.
Now, when I click to add to cart button is added one product to the cart.

This problem is just in category list, not on product page.

My code from /app/design/frontend/theme/theme/template/catalog/product/list.phtml

<?php  if ( !($product->getTypeInstance(true)->hasOptions($product)/*$_product->getData('has_options')*/ || $product->isGrouped()) ) :  ?>

                                    <input type="text" name="qty" id="qty_<?php echo $_product->getId(); ?>" maxlength="12" value="<?php echo $product->getProductDefaultQty() * 1 ?>" title="<?php echo $this->__('Qty') ?>" class="input-text qty" />

                            </form>
                            <?php $_productid == $_product->getId(); ?>

                            <a href="<?php if(!Mage::getStoreConfig("ajaxcart/addtocart/enablecategory", $code) && !Mage::getStoreConfig("porto_settings/category/qty_field", $code)): ?><?php echo $this->getAddToCartUrl($_product) ?><?php else: ?>javascript:void(0)<?php endif; ?>" class="addtocart" title="<?php echo $this->__('Add to Cart') ?>" <?php if(Mage::getStoreConfig("ajaxcart/addtocart/enablecategory", $code)):?>onclick="setLocationAjax(this,'<?php echo $this->getAddToCartUrl($_product) ?>','<?php echo $_product->getId(); ?>')"<?php elseif(Mage::getStoreConfig("porto_settings/category/qty_field", $code)): ?>onclick="document.getElementById('addtocart_form_<?php echo $_product->getId(); ?>').submit()"<?php endif; ?>> <?php echo $this->__('Add to Cart') ?>

                        <?php else : ?>
                            <a href="<?php if(Mage::getStoreConfig("ajaxcart/addtocart/enablecategory", $code)):?>javascript:showOptions('<?php echo $_product->getId()?>')<?php else: ?><?php echo $this->getAddToCartUrl($_product) ?><?php endif; ?>" class="addtocart" title="<?php echo $this->__('Add to Cart') ?>"> <?php echo $this->__('Add to Cart') ?>
                            <a href='<?php echo $this->getUrl('ajaxcart/index/options',array('product_id'=>$_product->getId()));?>' class='fancybox' id='fancybox<?php echo $_product->getId()?>' style='display:none'>Options
                        <?php endif;?>

Any ideas?

Thanks!

Body:
Maybe something like this (javascript):

jQuery('.addtocart').each(function() {
    var $self = jQuery(this),
        oldOnClick = $self.attr('onclick'),
        $product = $self.closest('.item');

    $self.attr('data-onclick', oldOnClick).removeAttr('onclick');
    $self.off('click').on('click', function() {
        if($product.find('.input-text.qty').val() < 1)
            return false;
        else
            eval(jQuery(this).data('onclick'));
    });
});

When user clicks on 'add to cart', check if the quantity value is >= 1.

Edit: fix some things..


问:
Nginx: HowTo rewrite nonx-existing .php file to index.php?
Below you see the part of my server which works brilliant, but now i have to "simulate" a php file which does not exists.

```<code>location ~ \.php$
{
 fastcgi_pass php;
 include fastcgi.conf;
}

try_files $uri $uri/ /index.php?$uri&$args;
</code>```

All my urls are currently rewritten du the try_files setting to my index.php, but not if i try to access domain.tld/something.php.

How can i make those location block/s make domain.tld/something**.php** to use my try_files and send it to index.php?

Thanks in advance.

答:
Working fine for me. Hope this will work for you as well.</p>

```<code>location ~\.php$ {
    index index.php index.html;
    include fastcgi_params;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    try_files /index.php /index.php;
}
</code>```

Body:
Below you see the part of my server which works brilliant, but now i have to "simulate" a php file which does not exists.

location ~ \.php$
{
 fastcgi_pass php;
 include fastcgi.conf;
}

try_files $uri $uri/ /index.php?$uri&$args;

All my urls are currently rewritten du the try_files setting to my index.php, but not if i try to access domain.tld/something.php.

How can i make those location block/s make domain.tld/something**.php** to use my try_files and send it to index.php?

Thanks in advance.

Body:
Working fine for me. Hope this will work for you as well.

location ~\.php$ {
    index index.php index.html;
    include fastcgi_params;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    try_files /index.php /index.php;
}