问:
How to change flex-layout using Angular2 animations?
I made my first steps in @angular/animations with help of official tutorial. I added reqired libraries and i create my first animation. I already know what transition and state is. I can create simple animations (changing background colors and changing size of elements.

I use @angular/flex-layout library in my project to create neat page layout. And here comes the question: How can I animate increasing and decreasing width of elements my flex layout? For example:

I have 3 "columns" on my page:

In the first state their width is: 38%, 52%, 10% of container

and in the second state their width is: 50%, 25%, 25%

just like in the picture (these are the same columns in other states)

Question: How should I make a transitions to animate changing width of columns? Which methods and attributes can I use? What code should look like?

=====

@EDIT:

I publish fragment of my HTML code to present which attribute I want change (fxFlex)

app.component.html

```<code><div class="flex-container"
    fxLayout="row"
    fxLayout.xs="column"
    fxLayoutAlign="end none"
    fxLayoutAlign.xs="end none" class="container-style">

    <!-- first column -->
    <div class="flex-item" fxFlex="38%" fxShow.xs="false" class="one" [@oneState]="state"></div>

    <!-- second column -->
    <div class="flex-item" fxFlex="52%" class="two" [@twoState]="state"></div>

    <!-- third column -->
    <div class="flex-item" fxFlex class="three"></div>
</div>
</code>```

for app.component.ts

```<code>@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  animations: [
    trigger('oneState', [
      state('inactive', style({
        //I have no idea what I should use to change fxFlex attribute!
        //Style? Maybe, something else?
      })),
      state('active',   style({
        //I have no idea...
      })),
      transition('inactive => active', animate('100ms ease-in')),
      transition('active => inactive', animate('100ms ease-out'))
    ]),
    trigger('twoState', [
      state('inactive', style({
        //I have no idea what I should use to change fxFlex attribute!
        //Style? Maybe, something else?
      })),
      state('active',   style({
        //I have no idea...
      })),
      transition('inactive => active', animate('100ms ease-in')),
      transition('active => inactive', animate('100ms ease-out'))
    ]),
  ]
})
export class AppComponent {
  title = 'app works!';

  state: string = 'inactive';

  toggleMove() {
    this.state = (this.state === 'inactive' ? 'active' : 'inactive');
    console.log(this.state);
  }

}
</code>```

I know that I can change styles of div in simple way. But i don't want to change style. I would like to change a fxFlex attribute of element.

Anyone can help me? Is it possible??

答:
You don't actually need angular animations for this, you can create a <col> component, like this:

```<code>@Component({
  selector: "col",
  styles:[`
  :host{
    transition: width 300ms linear;
    display:block;
  }
  `],
  template:`<ng-content></ng-content>`
})
export class ColComponent{
  @Input()
  @HostBinding("style.width")
  fxFlex:string;
}
</code>```

and then use it in your app template like <col fxFlex="50%"></col> (note that you can use another selector like "div[flexible]" or whatever...

I created a plunker

Body:
I made my first steps in @angular/animations with help of official tutorial. I added reqired libraries and i create my first animation. I already know what transition and state is. I can create simple animations (changing background colors and changing size of elements.

I use @angular/flex-layout library in my project to create neat page layout. And here comes the question: How can I animate increasing and decreasing width of elements my flex layout? For example:

I have 3 "columns" on my page:

In the first state their width is: 38%, 52%, 10% of container

and in the second state their width is: 50%, 25%, 25%

just like in the picture (these are the same columns in other states)

Question: How should I make a transitions to animate changing width of columns? Which methods and attributes can I use? What code should look like?

=====

@EDIT:

I publish fragment of my HTML code to present which attribute I want change (fxFlex)

app.component.html

for app.component.ts

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  animations: [
    trigger('oneState', [
      state('inactive', style({
        //I have no idea what I should use to change fxFlex attribute!
        //Style? Maybe, something else?
      })),
      state('active',   style({
        //I have no idea...
      })),
      transition('inactive => active', animate('100ms ease-in')),
      transition('active => inactive', animate('100ms ease-out'))
    ]),
    trigger('twoState', [
      state('inactive', style({
        //I have no idea what I should use to change fxFlex attribute!
        //Style? Maybe, something else?
      })),
      state('active',   style({
        //I have no idea...
      })),
      transition('inactive => active', animate('100ms ease-in')),
      transition('active => inactive', animate('100ms ease-out'))
    ]),
  ]
})
export class AppComponent {
  title = 'app works!';

  state: string = 'inactive';

  toggleMove() {
    this.state = (this.state === 'inactive' ? 'active' : 'inactive');
    console.log(this.state);
  }

}

I know that I can change styles of div in simple way. But i don't want to change style. I would like to change a fxFlex attribute of element.

Anyone can help me? Is it possible??

Body:
You don't actually need angular animations for this, you can create a <col> component, like this:

@Component({
  selector: "col",
  styles:[`
  :host{
    transition: width 300ms linear;
    display:block;
  }
  `],
  template:`<ng-content></ng-content>`
})
export class ColComponent{
  @Input()
  @HostBinding("style.width")
  fxFlex:string;
}

and then use it in your app template like <col fxFlex="50%"></col> (note that you can use another selector like "div[flexible]" or whatever...

I created a plunker


来源: stackexchange

问:
Application server hosting
I'm writing a Qt/C++ application and i plan to add a network part with socket connection to a server implemented in Qt also.

If i host locally the server there is no real problem.

But if i want to share my application (client part) with some people and then be sure my server is always running, the best way would be to have a distant server.

Could you give me some clue to do it ? It's not still clear for me for steps to follow in this case.

Is it a better way for that ?

Can i find free hosting ?

Thanks a lot! :-)

答:
There are generally 3 options:

1. Local hosting

This is server running at Your physical location. You can set it clearly as You want and the server will do whatever You want. But must be turned on the whole time, when there is no other work it will just consume power. Also You must get all the hardware (server components), software for running (Operation system), network device and connection (some router, which needs to have special set-up [NAT, port-forward, ...], speed and reachability of the internet connection) and most likely also some security device/SW (firewalls or so).

This is best idea for basic developement and testing. But once the service should work for public audience, it is not really worth to run server Yourself.

2. Remote hosting (virtualized or dedicated server)

This option was the top in last 20-30 years, where all the Web developers and App developers were putting their software on some prepared server. Dedicated is physical server running at some providers' location, who are lending You the hardware (and maybe some license for OS/other SW). Virtualized machine is just 1 hardware piece (server) with multiple virtual servers on it (more clients running on same hardware).

This got generally benefits as the networking/security/hardware issues are being carried out by the hosting owner. You are just borrowing some diskspace and computer time/performance. Normally the company will provide whole server, on which You can set up several services, run multiple protocols, etc..

Ideal solution for webs and single/few (not much) instances of server application(s).

3. Cloud hosting

This is the newest technology at the moment (alive around 10-15 years [eg. AWS running since 2006, Azure since 2010]). Datacenter owners (from 2. point) get better and created some applications on the servers, which will do all the work for You (mostly automatically). In few clicks the servers are running and application can be deployed, used database engines, web pages, IOT hubs, ... quite lot of stuff. Benefits are clearly that You just have to spent minimum of time to set up things and they will run. With high uptime (eg.: 99.9995%).

Difference between dedicated & cloud: On dedicated server there can be put almost any OS which fits the needs, run just services You want, have full control. In cloud solution, You don't have so much of "physical" control and the data moreless live somewhere in Datacenters all over the world. But generally it is more scalable solution and once Your app will be used by lot of users from public sector, this is best way to go.

Common ideology:

The most common solution is that when You develop, You create local server on which You deploy, test, improve. Once stable, order a server either on cloud or as dedicated/virtual machine and deploy it there. Some developers knows that their App will run on cloud services from the very beggining so they order it and start developing against it, but in most cases there is no need for that.

ContentLicense: CC BY-SA 3.0

Title: Application server hosting


问:
Insert from one table into another with commit Intervals
I have written a procedure to insert data from one table into another table. There is a huge amount of data - a total of 106 millions rows. So I want to put a commit interval on the query.

I have found this script that normally will work and will not take time to get the job done but I don't know why I get an error on

```<code>INSERT INTO dlc_pr_activity_remise
VALUES (add all values using ga_array(i).<value in select>)
</code>```

Errors:

Error(51,1): PL/SQL: SQL Statement ignored

  Error(51,47): PL/SQL: ORA-00917: missing comma

My procedure :

```<code>create or replace
PROCEDURE ACTIVITY1 AS
BEGIN
DECLARE
commit_interval pls_integer := 250000 ;
uncommitted pls_integer := 0;
fetch_size  pls_integer := 2500 ;
cursor g1 is SELECT prr.EVT_DECLENCHEUR ,
                    prr.BQ_CDF ,
                    prr.BQ_DOM ,
                    prr.NUM_COMMERCANT ,
                    prr.TYPE_CONTRAT_COM ,
                    prr.COMMERCANT_SIRET ,
                    prr.TYPE_PRE_COMP ,
                    prr.BQ_CDF_ID_EBF ,
                    prr.BQ_DOM_ID_EBF ,
                    prr.DAT_TRAITEMENT ,
                    prr.EVT_TYPE_OPERATION ,
                    prr.DEV_MT_CRE ,
                    prr.NBR_DECI_MT_CRE ,
                    prr.REF_FICHIER_TRAITE ,
                    prr.NUM_CTC ,
                    prr.REF_FICHIER_ORIGINE ,
                    prr.ORIGINE_FLUX ,
                    prr.NUM_EST_REMISE ,
                    prr.NUM_REMISE_ORIGINE ,
                    prr.NUM_MACHINE ,
                    prr.REF_ARCHIVAGE_REM ,
                    prr.DAT_REMISE ,
                    prr.SUPPORT_REMISE ,
                    prr.DAT_REMISE_CALCULEE ,
                    prr.DAT_VALEUR_REMISE ,
                    prr.COD_APPLI ,
                    to_date(SYSDATE,'DD/MM/YYYY')
                    FROM dlc_pr_remise prr
                    WHERE NOT EXISTS
                      (SELECT *
                      FROM DLC_PR_ACTIVITY_REMISE prao
                      WHERE prao.num_est_remise = prr.num_est_remise
                      );
TYPE GL_T is table of gl%rowtype ;
gl_array GL_T;
begin
open gl ;
loop
fetch gl
bulk collect
into gl_array
limit fetch_size ;
forall i in 1 .. gl_arary.count
INSERT INTO dlc_pr_activity_remise values(add all values using ga_array(i).<value in select>)
uncommitted :+ uncommitted + sql%rowcount ;
exit when gl_arary.count < fetch_size ;
if uncommitted >= commit_interval
then
commit ;
uncommitted := 0;
end if ;
end loop ;
commit ;
close gl;
END ;
END ACTIVITY1;
</code>```

答:
```<code>cursor g1 is select acct_nbr from dwc_tmp_acct_rcvbl;
</code>```

The cursor's select above must be replaced with :

```<code>SELECT prr.EVT_DECLENCHEUR ,
prr.BQ_CDF ,
prr.BQ_DOM ,
prr.NUM_COMMERCANT ,
prr.TYPE_CONTRAT_COM ,
prr.COMMERCANT_SIRET ,
prr.TYPE_PRE_COMP ,
prr.BQ_CDF_ID_EBF ,
prr.BQ_DOM_ID_EBF ,
prr.DAT_TRAITEMENT ,
prr.EVT_TYPE_OPERATION ,
prr.DEV_MT_CRE ,
prr.NBR_DECI_MT_CRE ,
prr.REF_FICHIER_TRAITE ,
prr.NUM_CTC ,
prr.REF_FICHIER_ORIGINE ,
prr.ORIGINE_FLUX ,
prr.NUM_EST_REMISE ,
prr.NUM_REMISE_ORIGINE ,
prr.NUM_MACHINE ,
prr.REF_ARCHIVAGE_REM ,
prr.DAT_REMISE ,
prr.SUPPORT_REMISE ,
prr.DAT_REMISE_CALCULEE ,
prr.DAT_VALEUR_REMISE ,
prr.COD_APPLI ,
to_date(SYSDATE,'DD/MM/YYYY')
  FROM dlc_pr_remise prr
  WHERE NOT EXISTS
    (SELECT *
    FROM DLC_PR_ACTIVITY_REMISE prao
    WHERE prao.num_est_remise = prr.num_est_remise
    )
</code>```

Then , this line :

```<code>insert into dwc_tmp_acct_rcvbl_year_col (acct_nbr)
</code>```

must be replaced with

```<code>INSERT INTO dlc_pr_activity_remise values(add all values using ga_array(i).<value in select>)
</code>```

Hope this helps.

Body:
I have written a procedure to insert data from one table into another table. There is a huge amount of data - a total of 106 millions rows. So I want to put a commit interval on the query.

I have found this script that normally will work and will not take time to get the job done but I don't know why I get an error on

INSERT INTO dlc_pr_activity_remise
VALUES (add all values using ga_array(i).<value in select>)

Errors:

Error(51,1): PL/SQL: SQL Statement ignored

  Error(51,47): PL/SQL: ORA-00917: missing comma

My procedure :

create or replace
PROCEDURE ACTIVITY1 AS
BEGIN
DECLARE
commit_interval pls_integer := 250000 ;
uncommitted pls_integer := 0;
fetch_size  pls_integer := 2500 ;
cursor g1 is SELECT prr.EVT_DECLENCHEUR ,
                    prr.BQ_CDF ,
                    prr.BQ_DOM ,
                    prr.NUM_COMMERCANT ,
                    prr.TYPE_CONTRAT_COM ,
                    prr.COMMERCANT_SIRET ,
                    prr.TYPE_PRE_COMP ,
                    prr.BQ_CDF_ID_EBF ,
                    prr.BQ_DOM_ID_EBF ,
                    prr.DAT_TRAITEMENT ,
                    prr.EVT_TYPE_OPERATION ,
                    prr.DEV_MT_CRE ,
                    prr.NBR_DECI_MT_CRE ,
                    prr.REF_FICHIER_TRAITE ,
                    prr.NUM_CTC ,
                    prr.REF_FICHIER_ORIGINE ,
                    prr.ORIGINE_FLUX ,
                    prr.NUM_EST_REMISE ,
                    prr.NUM_REMISE_ORIGINE ,
                    prr.NUM_MACHINE ,
                    prr.REF_ARCHIVAGE_REM ,
                    prr.DAT_REMISE ,
                    prr.SUPPORT_REMISE ,
                    prr.DAT_REMISE_CALCULEE ,
                    prr.DAT_VALEUR_REMISE ,
                    prr.COD_APPLI ,
                    to_date(SYSDATE,'DD/MM/YYYY')
                    FROM dlc_pr_remise prr
                    WHERE NOT EXISTS
                      (SELECT *
                      FROM DLC_PR_ACTIVITY_REMISE prao
                      WHERE prao.num_est_remise = prr.num_est_remise
                      );
TYPE GL_T is table of gl%rowtype ;
gl_array GL_T;
begin
open gl ;
loop
fetch gl
bulk collect
into gl_array
limit fetch_size ;
forall i in 1 .. gl_arary.count
INSERT INTO dlc_pr_activity_remise values(add all values using ga_array(i).<value in select>)
uncommitted :+ uncommitted + sql%rowcount ;
exit when gl_arary.count < fetch_size ;
if uncommitted >= commit_interval
then
commit ;
uncommitted := 0;
end if ;
end loop ;
commit ;
close gl;
END ;
END ACTIVITY1;

Body:
cursor g1 is select acct_nbr from dwc_tmp_acct_rcvbl;

The cursor's select above must be replaced with :

SELECT prr.EVT_DECLENCHEUR ,
prr.BQ_CDF ,
prr.BQ_DOM ,
prr.NUM_COMMERCANT ,
prr.TYPE_CONTRAT_COM ,
prr.COMMERCANT_SIRET ,
prr.TYPE_PRE_COMP ,
prr.BQ_CDF_ID_EBF ,
prr.BQ_DOM_ID_EBF ,
prr.DAT_TRAITEMENT ,
prr.EVT_TYPE_OPERATION ,
prr.DEV_MT_CRE ,
prr.NBR_DECI_MT_CRE ,
prr.REF_FICHIER_TRAITE ,
prr.NUM_CTC ,
prr.REF_FICHIER_ORIGINE ,
prr.ORIGINE_FLUX ,
prr.NUM_EST_REMISE ,
prr.NUM_REMISE_ORIGINE ,
prr.NUM_MACHINE ,
prr.REF_ARCHIVAGE_REM ,
prr.DAT_REMISE ,
prr.SUPPORT_REMISE ,
prr.DAT_REMISE_CALCULEE ,
prr.DAT_VALEUR_REMISE ,
prr.COD_APPLI ,
to_date(SYSDATE,'DD/MM/YYYY')
  FROM dlc_pr_remise prr
  WHERE NOT EXISTS
    (SELECT *
    FROM DLC_PR_ACTIVITY_REMISE prao
    WHERE prao.num_est_remise = prr.num_est_remise
    )

Then , this line :

insert into dwc_tmp_acct_rcvbl_year_col (acct_nbr)

must be replaced with

INSERT INTO dlc_pr_activity_remise values(add all values using ga_array(i).<value in select>)

Hope this helps.


问:
Where is the wordpress folder in XAMPP?
I have installed XAMPP on my mac and recently downloaded and installed Bitnami-Wordpress. It all works fine but I just cant find the Wordpress folder. I can open wordpress in my browser with http://localhost/wordpress. So I thought there must be a wordpress folder in htdocs. But I just cant find it in htdocs or any subfolders. I want to access the themes folder. Maybe I am searching in the wrong place? I am really lost here. Any help will be appreciated!

答:
Old thread but I was looking for the location.

On macOS Wordpress install is located in:

XAMPP.app/xamppfiles/apps/wordpress

Title: Where is the wordpress folder in XAMPP?


问:
Get the last day of the month
Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month?

If the standard library doesn't support that, does the dateutil package support this?

答:
EDIT: see my other answer. It has a better implementation than this one, which I leave here just in case someone's interested in seeing how one might "roll your own" calculator.

@John Millikin gives a good answer, with the added complication of calculating the first day of the next month.

The following isn't particularly elegant, but to figure out the last day of the month that any given date lives in, you could try:

```<code>def last_day_of_month(date):
    if date.month == 12:
        return date.replace(day=31)
    return date.replace(month=date.month+1, day=1) - datetime.timedelta(days=1)

>>> last_day_of_month(datetime.date(2002, 1, 17))
datetime.date(2002, 1, 31)
>>> last_day_of_month(datetime.date(2002, 12, 9))
datetime.date(2002, 12, 31)
>>> last_day_of_month(datetime.date(2008, 2, 14))
datetime.date(2008, 2, 29)
</code>```

OwnerDisplayName: Cristian

ContentLicense: CC BY-SA 4.0

Title: Get the last day of the month

Body:
EDIT: see my other answer. It has a better implementation than this one, which I leave here just in case someone's interested in seeing how one might "roll your own" calculator.

@John Millikin gives a good answer, with the added complication of calculating the first day of the next month.

The following isn't particularly elegant, but to figure out the last day of the month that any given date lives in, you could try:

def last_day_of_month(date):
    if date.month == 12:
        return date.replace(day=31)
    return date.replace(month=date.month+1, day=1) - datetime.timedelta(days=1)

>>> last_day_of_month(datetime.date(2002, 1, 17))
datetime.date(2002, 1, 31)
>>> last_day_of_month(datetime.date(2002, 12, 9))
datetime.date(2002, 12, 31)
>>> last_day_of_month(datetime.date(2008, 2, 14))
datetime.date(2008, 2, 29)

OwnerDisplayName: Blair Conrad

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Blair Conrad


问:
Font in WPF application looks different in notepad or any other application
I have otf font called "Houschka Rounded". In notepad, word or any WinForms app it looks like this:

 - this is ok

Code:

```<code><TextBox Text="asdf www w er AAs" FontSize="16" FontFamily="Houschka Rounded" Height="23" HorizontalAlignment="Left" Margin="12,12,0,0" Name="textBox1" VerticalAlignment="Top" Width="317" />
</code>```

In WPF 4.0 it looks like this:

 - this is bad

Anyone know why it's happening?

答:
It turned out that otf font has featureas which can change the look of font. In my case I set ContextualAlternates=false.

```<code><TextBox FontFamily="Houschka Rounded" Height="23" HorizontalAlignment="Left" Margin="12,12,0,0" Name="textBox1" VerticalAlignment="Top" Width="317">
    <Run Typography.ContextualAlternates="False" >
        asdf www w er AAs
    </Run>
</TextBlock>
</code>```

For details see:
http://msdn.microsoft.com/en-us/library/ms745109.aspx

Body:
I have otf font called "Houschka Rounded". In notepad, word or any WinForms app it looks like this:

 - this is ok

Code:

<TextBox Text="asdf www w er AAs" FontSize="16" FontFamily="Houschka Rounded" Height="23" HorizontalAlignment="Left" Margin="12,12,0,0" Name="textBox1" VerticalAlignment="Top" Width="317" />

In WPF 4.0 it looks like this:

 - this is bad

Anyone know why it's happening?

Body:
It turned out that otf font has featureas which can change the look of font. In my case I set ContextualAlternates=false.

<TextBox FontFamily="Houschka Rounded" Height="23" HorizontalAlignment="Left" Margin="12,12,0,0" Name="textBox1" VerticalAlignment="Top" Width="317">
    <Run Typography.ContextualAlternates="False" >
        asdf www w er AAs
    </Run>
</TextBlock>

For details see:
http://msdn.microsoft.com/en-us/library/ms745109.aspx


问:
UIAlertController foreground is dimmed when it should not be
I have a strange issue which is affecting all of many UIAlertControllers shown throughout my app - the AlertControllers' white foreground appears dimmed, or less bright, than it should be.

The easiest way to describe it is to illustrate the desired and expected effect I obtain by placing the relevant code in a fresh 'Test' Single View application (Swift 3 - I should note that the actual app is a Single View application using Swift 2.3).

In my 'Test' app, the code below uses a deprecated AlertView to show a sample message, then builds a AlertController and shows that immediately 'after'.  There is no need to use the AlertView except to highlight the contrast in foreground 'white' - the problematic behaviour is the same if I comment out the AlertView.

Problematic behaviour:

Image 1: Test app: the AlertView is shown and the AlertController then shows behind it. Note the whiteness/brightness of the AlertView foreground.

Image 2: Test app: when the AlertView is dismissed, the AlertController is then the uppermost viewcontroller and as expected and desired, its foreground brightness is exactly the same as the AlertView's previously was

Image 3: real app: same code, also positioned in viewDidAppear - the AlertView is shown with the expected whiteness/brightness

Image 4: real app: when the AlertView is dismissed, the AlertController is then uppermost, but its foreground is nowhere near as bright / white as the AlertView's was, OR as it was in the Test app example, image 2.

As previously stated, the behaviour is the same even if I eliminate the AlertView step (which is just for contrast).

One further observation - often when I observe the behaviour, just momentarily when an affected AlertController first appears, as in for maybe 1/4 or 1/8 of a second, its foreground is the correct whiteness/brightness, but then an instant later it becomes dimmed, per the stated problem.

One other observation - some AlertControllers in the real app display properly with the correct level of brightness, but many others do not.

One last observation - I have user the 'View UI Hierarchy' in Xcode and there does not appear to be anything 'on top of' the affected AlertController.

```<code>import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func viewDidAppear(_ animated: Bool) {

    UIAlertView(title: "My AlertView Title", message: "My AlertView Message", delegate: self, cancelButtonTitle: "OK").show()

    let alertTitle = "My AlertController Title"
    let msg = "\r\r\r\r\r\r\r\rMy AlertController Msg"

    let alertController = UIAlertController(title: alertTitle, message: msg, preferredStyle: .alert)

    let cancelAction = UIAlertAction(title: "Don't show this again", style: .cancel) { (action:UIAlertAction!) in
        print("Dismiss button pressed")

    }
    alertController.addAction(cancelAction)

    let OKAction = UIAlertAction(title: "Action 1", style: .default) { (action:UIAlertAction!) in

        print("I'm action1!!")
    }

    alertController.addAction(OKAction)

    let OK2Action = UIAlertAction(title: "Action2", style: .default) { (action:UIAlertAction!) in

        print("I'm action2")
    }

    alertController.addAction(OK2Action)

    present(alertController, animated: false, completion: nil)

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
</code>```

}

Any help as to this puzzle gratefully received, thanks!

EDIT:

thanks to @Richard G for putting me on the right track - I still have the problem but with more clarity.

So, it you look at the two screenshots below side by side, they are both from the real app, both use the code shown above to generate the UIAlertController (I have now delete the UIAlertView line as it isn't needed), the only difference between the one on the left and one on the right is the one on the right has these 3 lines of code added:

```<code>let backView = alertController.view.subviews.last?.subviews.last
backView?.layer.cornerRadius = 10.0
backView?.backgroundColor = UIColor.whiteColor()
</code>```

side by side UIAlertControllers 1 transparent 1 not

According to Apple, "The UIAlertController class is intended to be used as-is and does not support subclassing. The view hierarchy for this class is private and must not be modified."  OK, so this is hacking into it, and it proves that somehow the alertController has acquired, prior to displaying it, a backgroundColor which was partly transparent.

By setting the backgroundColor to UIColor.whiteColor() the problem is fixed, but the solution should be unnecessary - how on earth did the problem arise in the first place?

How was the backgroundColor somehow set to have a transparency when Apple doesn't even expose that property to me to be able to set?

any answers gratefully received!

答:
After seeing an image that you have uploaded I can mention some point.

The UIAlertController is little bit transparent if you notice.

Since UIAlertController is transparent so the background will affect on appearance of alert controller.

NOTE: In case 1 & 2 background is white and case 3 & 4 background is black.

So what you can do it make background as bright as in case 1 and case 2 (from image).

**EDIT : **

TO change background color of UIAlertController you can do like...

```<code>let subView = alertController.view.subviews.first!;
var alertContentView = subView.subviews.first!;
alertContentView.backgroundColor = UIColor.darkGray;
alertContentView.layer.cornerRadius = 5;
</code>```

Body:
I have a strange issue which is affecting all of many UIAlertControllers shown throughout my app - the AlertControllers' white foreground appears dimmed, or less bright, than it should be.

The easiest way to describe it is to illustrate the desired and expected effect I obtain by placing the relevant code in a fresh 'Test' Single View application (Swift 3 - I should note that the actual app is a Single View application using Swift 2.3).

In my 'Test' app, the code below uses a deprecated AlertView to show a sample message, then builds a AlertController and shows that immediately 'after'.  There is no need to use the AlertView except to highlight the contrast in foreground 'white' - the problematic behaviour is the same if I comment out the AlertView.

Problematic behaviour:

Image 1: Test app: the AlertView is shown and the AlertController then shows behind it. Note the whiteness/brightness of the AlertView foreground.

Image 2: Test app: when the AlertView is dismissed, the AlertController is then the uppermost viewcontroller and as expected and desired, its foreground brightness is exactly the same as the AlertView's previously was

Image 3: real app: same code, also positioned in viewDidAppear - the AlertView is shown with the expected whiteness/brightness

Image 4: real app: when the AlertView is dismissed, the AlertController is then uppermost, but its foreground is nowhere near as bright / white as the AlertView's was, OR as it was in the Test app example, image 2.

As previously stated, the behaviour is the same even if I eliminate the AlertView step (which is just for contrast).

One further observation - often when I observe the behaviour, just momentarily when an affected AlertController first appears, as in for maybe 1/4 or 1/8 of a second, its foreground is the correct whiteness/brightness, but then an instant later it becomes dimmed, per the stated problem.

One other observation - some AlertControllers in the real app display properly with the correct level of brightness, but many others do not.

One last observation - I have user the 'View UI Hierarchy' in Xcode and there does not appear to be anything 'on top of' the affected AlertController.

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func viewDidAppear(_ animated: Bool) {

    UIAlertView(title: "My AlertView Title", message: "My AlertView Message", delegate: self, cancelButtonTitle: "OK").show()

    let alertTitle = "My AlertController Title"
    let msg = "\r\r\r\r\r\r\r\rMy AlertController Msg"

    let alertController = UIAlertController(title: alertTitle, message: msg, preferredStyle: .alert)

    let cancelAction = UIAlertAction(title: "Don't show this again", style: .cancel) { (action:UIAlertAction!) in
        print("Dismiss button pressed")

    }
    alertController.addAction(cancelAction)

    let OKAction = UIAlertAction(title: "Action 1", style: .default) { (action:UIAlertAction!) in

        print("I'm action1!!")
    }

    alertController.addAction(OKAction)

    let OK2Action = UIAlertAction(title: "Action2", style: .default) { (action:UIAlertAction!) in

        print("I'm action2")
    }

    alertController.addAction(OK2Action)

    present(alertController, animated: false, completion: nil)

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

Any help as to this puzzle gratefully received, thanks!

EDIT:

thanks to @Richard G for putting me on the right track - I still have the problem but with more clarity.

So, it you look at the two screenshots below side by side, they are both from the real app, both use the code shown above to generate the UIAlertController (I have now delete the UIAlertView line as it isn't needed), the only difference between the one on the left and one on the right is the one on the right has these 3 lines of code added:

let backView = alertController.view.subviews.last?.subviews.last
backView?.layer.cornerRadius = 10.0
backView?.backgroundColor = UIColor.whiteColor()

side by side UIAlertControllers 1 transparent 1 not

According to Apple, "The UIAlertController class is intended to be used as-is and does not support subclassing. The view hierarchy for this class is private and must not be modified."  OK, so this is hacking into it, and it proves that somehow the alertController has acquired, prior to displaying it, a backgroundColor which was partly transparent.

By setting the backgroundColor to UIColor.whiteColor() the problem is fixed, but the solution should be unnecessary - how on earth did the problem arise in the first place?

How was the backgroundColor somehow set to have a transparency when Apple doesn't even expose that property to me to be able to set?

any answers gratefully received!

Body:
After seeing an image that you have uploaded I can mention some point.

The UIAlertController is little bit transparent if you notice.

Since UIAlertController is transparent so the background will affect on appearance of alert controller.

NOTE: In case 1 & 2 background is white and case 3 & 4 background is black.

So what you can do it make background as bright as in case 1 and case 2 (from image).

**EDIT : **

TO change background color of UIAlertController you can do like...

let subView = alertController.view.subviews.first!;
var alertContentView = subView.subviews.first!;
alertContentView.backgroundColor = UIColor.darkGray;
alertContentView.layer.cornerRadius = 5;


问:
Django Rest Framework Update or Create if not exists
I want to use the perform an update or create in django-rest-framework, by passing or not the id field. I've got this model

```<code>class Etiqueta(models.Model):
    name_tag = models.CharField(max_length=200, blank=False, null=False)
    description_tag = models.TextField(max_length=500, blank=False, null=False)

    def __unicode__(self):
        return self.name_tag
</code>```

And in django-rest-framework I've got this serializer

```<code>from myapp.modulos.estado_1.models import Etiqueta
from rest_framework import serializers, viewsets

# Serializers define the API representation.
class TagSerializer(serializers.ModelSerializer):
    class Meta:
        model = Etiqueta
        fields = (
            'id',
            'name_tag',
            'description_tag'
        )

# ViewSets define the view behavior.
class TagViewSet(viewsets.ModelViewSet):
    queryset = Etiqueta.objects.all()
    serializer_class = TagSerializer
</code>```

Normally when I create an object, I perform a POST to the URL without the /:id, but if I've got an object with a local id, I want him to be created in the REST with the same id (remote id), django overwrite my local id and creates a new one. Does anybody know how achieve this? Also it is important to mention that I'm working with google-app-engine, google-cloud-datastore and django-dbindexer.

答: I've write a drf views mixin for updating an object by id, if no corresponding object, just create it then update.</p>

Body:
I want to use the perform an update or create in django-rest-framework, by passing or not the id field. I've got this model

class Etiqueta(models.Model):
    name_tag = models.CharField(max_length=200, blank=False, null=False)
    description_tag = models.TextField(max_length=500, blank=False, null=False)

    def __unicode__(self):
        return self.name_tag

And in django-rest-framework I've got this serializer

from myapp.modulos.estado_1.models import Etiqueta
from rest_framework import serializers, viewsets

# Serializers define the API representation.
class TagSerializer(serializers.ModelSerializer):
    class Meta:
        model = Etiqueta
        fields = (
            'id',
            'name_tag',
            'description_tag'
        )

# ViewSets define the view behavior.
class TagViewSet(viewsets.ModelViewSet):
    queryset = Etiqueta.objects.all()
    serializer_class = TagSerializer

Normally when I create an object, I perform a POST to the URL without the /:id, but if I've got an object with a local id, I want him to be created in the REST with the same id (remote id), django overwrite my local id and creates a new one. Does anybody know how achieve this? Also it is important to mention that I'm working with google-app-engine, google-cloud-datastore and django-dbindexer.


问:
Laravel - Call Crypt::decrypt() in blade template
i'm using datatables serverside to get all the data from 2 tables and display them. One of the values that i get is encrypted in the database.

Is there any way to decrypt this value within the blade template before displaying it?

I'm editing other values of the tables using

```<code>"mRender": function (data, type, full) {}
</code>```

Tried to use Illuminate\Support\Facades\Crypt::decrypt($value) but it has no result.

答:
full[5] is a javascript variable, if you pass it to Crypt::decrypt() it will not know it is a javascript variable, but a php constant, because it is inside <?php ?>.

You need to "rebuild" your data the way you want it to be displayed in datatables.

To do so, use editColumn method:

```<code>Route::get('/serverSideSymv', ['as' => 'serverSideSymv', 'uses' => function () {
    $symv = App\Symvolaia::Select('table1.*')->join('table2', 'table1.insurancecompanyid', '=', 'table2.id')->join('table3', 'table1.simvalomenos', '=', 'table3.kodikos_pelati')->select('filed1,field2,field3,......');
    return Datatables::of($symv)
    ->editColumn('your_column', function($data) {
        return Illuminate\Support\Facades\Crypt::decrypt($data->your_column);
    })
    ->make();
});
</code>```

Body:
i'm using datatables serverside to get all the data from 2 tables and display them. One of the values that i get is encrypted in the database.

Is there any way to decrypt this value within the blade template before displaying it?

I'm editing other values of the tables using

"mRender": function (data, type, full) {}

Tried to use Illuminate\Support\Facades\Crypt::decrypt($value) but it has no result.

Body:
full[5] is a javascript variable, if you pass it to Crypt::decrypt() it will not know it is a javascript variable, but a php constant, because it is inside <?php ?>.

You need to "rebuild" your data the way you want it to be displayed in datatables.

To do so, use editColumn method:

Route::get('/serverSideSymv', ['as' => 'serverSideSymv', 'uses' => function () {
    $symv = App\Symvolaia::Select('table1.*')->join('table2', 'table1.insurancecompanyid', '=', 'table2.id')->join('table3', 'table1.simvalomenos', '=', 'table3.kodikos_pelati')->select('filed1,field2,field3,......');
    return Datatables::of($symv)
    ->editColumn('your_column', function($data) {
        return Illuminate\Support\Facades\Crypt::decrypt($data->your_column);
    })
    ->make();
});


问:
Typeahead and clickable suggestion link
i have this code in search.php:

```<code><?php

    $key=$_GET['key'];
    $array = array();
    $con=mysql_connect("localhost","user","pass");
    $db=mysql_select_db("db",$con);
    $query=mysql_query("select * from users where username LIKE '%{$key}%'");
    while($row=mysql_fetch_assoc($query))
    {
      $array[] =$row['code'].$row['id'];

    }
    echo json_encode($array);
?>
</code>```

And this script in Javascript

```<code><script src="typeahead.min.js"></script>
        <script>
    $(document).ready(function(){
    $('input.typeahead').typeahead({
        name: 'typeahead',
        remote:'search.php?key=%QUERY',
        href : 'profile.php?id='

        });
});
    </script>
<script>
    $('input.typeahead').on( 'typeahead:selected', function(event, datum) {

  window.location = "profile.php?id="
});
    </script>
</code>```

I'm not very handy with js and API of typeahead, then i ask you:
There is another function to make a suggestion the url link?

The syntax is

profile.php?id=$id

I am using the window.location but I can not pass the user id in the variable array
Thanks

答:
I know this post is quite old but, I'll leave a solution that worked for me for the same exact issue.

You need to use a custom template to achive this.

```<code>$('input.typeahead').typeahead(null, {
    displayKey: 'name',
    source: restaurants.ttAdapter(),
    templates:{
      suggestion:function(data) {
        return "<a href=""profile.php?id="  + data.id + ">"+ data.name +"</a>"
      }
    }
  });
</code>```

Title: Typeahead and clickable suggestion link

Body:
i have this code in search.php:

<?php

    $key=$_GET['key'];
    $array = array();
    $con=mysql_connect("localhost","user","pass");
    $db=mysql_select_db("db",$con);
    $query=mysql_query("select * from users where username LIKE '%{$key}%'");
    while($row=mysql_fetch_assoc($query))
    {
      $array[] =$row['code'].$row['id'];

    }
    echo json_encode($array);
?>

And this script in Javascript

I'm not very handy with js and API of typeahead, then i ask you:
There is another function to make a suggestion the url link?

The syntax is

profile.php?id=$id

I am using the window.location but I can not pass the user id in the variable array
Thanks

Body:
I know this post is quite old but, I'll leave a solution that worked for me for the same exact issue.

You need to use a custom template to achive this.

$('input.typeahead').typeahead(null, {
    displayKey: 'name',
    source: restaurants.ttAdapter(),
    templates:{
      suggestion:function(data) {
        return "<a href=""profile.php?id="  + data.id + ">"+ data.name +"</a>"
      }
    }
  });


问:
How to set focus to a textbox within content control when clicked?
I have a View which contains two views within the view (these are contained within a ContainerControl).
On the other side of the View there's a Telerik GridView where the user can select a row. When a row is selected the other side of the View is dynamically changed to another View (and ViewModel). The dynamic view is a simple Grid with a lots of TextBoxes, so nothing special there.

Now when a user wants to enter values to the dynamically loaded View, he has to first click the ContentControl and then click again to a TextBox he wants to focus. This only happens when the GridView's row is in Edit Mode.

I've tried setting the ContentControl's FocusManager.IsFocusScope="False".

I've also tried settings all other controls with IsFocusable=False.

I know there must be a way to do this with WPF events, but I'm not an expert on this area.

I'm settings the dynamic View using Catel's converter like this (don't know it it's relevant):

XAML:

```<code><ContentControl Content="{Binding SelectedItemViewModel, Mode=TwoWay, Converter={catel:ViewModelToViewConverter}}" />
</code>```

ViewModel:

```<code>public MyDataModel SelectedItem
{
    get { return GetValue<MyDataModel>(SelectedItemProperty); }
    set
    {
         SetValue(SelectedItemProperty, value);
         RaisePropertyChanged(() => SelectedItemViewModel);
    }
}
public static readonly PropertyData SelectedItemProperty = RegisterProperty("SelectedItem", typeof(MyDataModel));

    public ViewModelBase SelectedItemViewModel
    {
        get
        {
            if (SelectedItem != null)
            {
                switch (SelectedItem.Type)
                {
                    case 1:
                        return new OneViewModel(SelectedItem);
                    case 2:
                        return new TwoViewModel(SelectedItem);
                }
            }

            return null;
        }
    }
</code>```

答: I resolved this by removing external view (different xaml file) reference and merging the views to one big xaml. For some reason the Telerik's gridiview "stole" the cursor from the referenced view, but when all controls are on the same xaml file everything works as expected.</p>

Body:
I have a View which contains two views within the view (these are contained within a ContainerControl).
On the other side of the View there's a Telerik GridView where the user can select a row. When a row is selected the other side of the View is dynamically changed to another View (and ViewModel). The dynamic view is a simple Grid with a lots of TextBoxes, so nothing special there.

Now when a user wants to enter values to the dynamically loaded View, he has to first click the ContentControl and then click again to a TextBox he wants to focus. This only happens when the GridView's row is in Edit Mode.

I've tried setting the ContentControl's FocusManager.IsFocusScope="False".

I've also tried settings all other controls with IsFocusable=False.

I know there must be a way to do this with WPF events, but I'm not an expert on this area.

I'm settings the dynamic View using Catel's converter like this (don't know it it's relevant):

XAML:

<ContentControl Content="{Binding SelectedItemViewModel, Mode=TwoWay, Converter={catel:ViewModelToViewConverter}}" />

ViewModel:

public MyDataModel SelectedItem
{
    get { return GetValue<MyDataModel>(SelectedItemProperty); }
    set
    {
         SetValue(SelectedItemProperty, value);
         RaisePropertyChanged(() => SelectedItemViewModel);
    }
}
public static readonly PropertyData SelectedItemProperty = RegisterProperty("SelectedItem", typeof(MyDataModel));

    public ViewModelBase SelectedItemViewModel
    {
        get
        {
            if (SelectedItem != null)
            {
                switch (SelectedItem.Type)
                {
                    case 1:
                        return new OneViewModel(SelectedItem);
                    case 2:
                        return new TwoViewModel(SelectedItem);
                }
            }

            return null;
        }
    }


问:
No 'Access-Control-Allow-Origin' header is present on the requested resource error. Request succeeds but failure is triggered
I'm encountering a bit of a strange issue when making an Ajax cross domain request. I get the following error in the console of chrome dev tools:

No 'Access-Control-Allow-Origin' header is present on the requested resource error

However, when I look at the network requests, it passes the browsers CORS preflight request because request changes from OPTIONS which it was when it was failing preflight request to GET, and the response is as I would get via postman. However, the Ajax failure message is triggered so even though in dev tools the request appears to succeed, I can't access the successful response via the JavaScript.

Additional info is that the file that is making the ajax request is just an HTML file with inline JavaScript that I open directly from the file directory. I'm thinking this might be my problem but couldn't find anything that explicitly says this so I am wanting confirmation.

Note with respect to the API: the appropriate access control headers are set

答: You have to pass some (if not all, I haven't checked) with every response, not only the response to the pre-flight OPTIONS request.


问:
zabbix monitor JMX C3P0 tokenid
the key is:

```<code>jmx["com.mchange.v2.c3p0:identityToken=2yaf3o9m1taosztt7mari|2294069,name=2yaf3o9m1taosztt7mari|2294069,type=PooledDataSource",maxPoolSize]
</code>```

but the identityToken changed when restart the tomcat.
is there a macro to define it,adapt when changed?
enter image description here

答:
You can configure c3p0's JMX key to be something that will not change.

Please see http://www.mchange.com/projects/c3p0/#jmx_configuration_and_management

The simple story is:

Be sure to set the c3p0 configuration property dataSourceName, which will become the value of a name attribute in the JMX key;

Set (in a c3p0.properties file or as a system property or in typesafe-config file) com.mchange.v2.c3p0.management.ExcludeIdentityToken=true

If you are using a c3p0.properties file, it'd be something like

```<code>c3p0.dataSourceName=myPooledDataSource
com.mchange.v2.c3p0.management.ExcludeIdentityToken=true
</code>```

Title: zabbix monitor JMX C3P0 tokenid

Body:
the key is:

jmx["com.mchange.v2.c3p0:identityToken=2yaf3o9m1taosztt7mari|2294069,name=2yaf3o9m1taosztt7mari|2294069,type=PooledDataSource",maxPoolSize]

but the identityToken changed when restart the tomcat.
is there a macro to define it,adapt when changed?
enter image description here

Body:
You can configure c3p0's JMX key to be something that will not change.

Please see http://www.mchange.com/projects/c3p0/#jmx_configuration_and_management

The simple story is:

Be sure to set the c3p0 configuration property dataSourceName, which will become the value of a name attribute in the JMX key;

Set (in a c3p0.properties file or as a system property or in typesafe-config file) com.mchange.v2.c3p0.management.ExcludeIdentityToken=true

If you are using a c3p0.properties file, it'd be something like

c3p0.dataSourceName=myPooledDataSource
com.mchange.v2.c3p0.management.ExcludeIdentityToken=true


问:
Playground, unable to set same UIImageView to more than one UIView
I've got this code

```<code>    override public func viewDidLoad() {

    let imageBlankCard = UIImage(named: "BlankCard.png")
    let imageViewBlankCard = UIImageView(image: imageBlankCard)

    rockCard.addSubview(imageViewBlankCard)
    scissorCard.addSubview(imageViewBlankCard)
    paperCard.addSubview(imageViewBlankCard)

    self.view.addSubview(rockCard)
    self.view.addSubview(scissorCard)
    self.view.addSubview(paperCard)

}
</code>```

But when I run the playground, only the latest UIView (paperCard) is displayed properly, the other cards are not shown at all as you can see in the image here: there should be two cards like the last one, in place of the arrows.
Can someone help me? Thanks everybody!

答:
According to the documentation,

Views can have only one superview. If view already has a superview and that view is not the receiver, this method removes the previous superview before making the receiver its new superview.

This explains the behaviour that you're getting.

One solution to this is to create three separate image views and add each of them as a subview.

Judging by the variable names, I think you are creating something similar to a rock paper scissors game. And you have three views that each holds an image view with the image of a blank card. And you want to add the image of a stone, paper and scissors as an overlay to the image view. If that's what you want to do, why not just make rockCard, paperCard and scissorsCard themselves UIImageViews and set the image to be BalnkCard.png?

```<code>let imageBlankCard = UIImage(named: "BlankCard.png")
rockCard.image = imageBlankCard
scissorsCard.image = imageBlankCard
paperCard.image = imageBlankCard
</code>```

Body:
I've got this code

    override public func viewDidLoad() {

    let imageBlankCard = UIImage(named: "BlankCard.png")
    let imageViewBlankCard = UIImageView(image: imageBlankCard)

    rockCard.addSubview(imageViewBlankCard)
    scissorCard.addSubview(imageViewBlankCard)
    paperCard.addSubview(imageViewBlankCard)

    self.view.addSubview(rockCard)
    self.view.addSubview(scissorCard)
    self.view.addSubview(paperCard)

}

But when I run the playground, only the latest UIView (paperCard) is displayed properly, the other cards are not shown at all as you can see in the image here: there should be two cards like the last one, in place of the arrows.
Can someone help me? Thanks everybody!

Body:
According to the documentation,

Views can have only one superview. If view already has a superview and that view is not the receiver, this method removes the previous superview before making the receiver its new superview.

This explains the behaviour that you're getting.

One solution to this is to create three separate image views and add each of them as a subview.

Judging by the variable names, I think you are creating something similar to a rock paper scissors game. And you have three views that each holds an image view with the image of a blank card. And you want to add the image of a stone, paper and scissors as an overlay to the image view. If that's what you want to do, why not just make rockCard, paperCard and scissorsCard themselves UIImageViews and set the image to be BalnkCard.png?

let imageBlankCard = UIImage(named: "BlankCard.png")
rockCard.image = imageBlankCard
scissorsCard.image = imageBlankCard
paperCard.image = imageBlankCard


问:
Copying children of a
 to another
 using jQuery
How can I copy copy content of a ul that is li's inside it to another ul.

Say we have t = $("ul#target") and s = $("ul#source").

答:
You can .clone() the children then use .appendTo() to put them on the destination
, like this:

```<code>$("#source").children().clone().appendTo("#target");
</code>```

Title: Copying children of a <ul> to another <ul> using jQuery

Body:
You can .clone() the children then use .appendTo() to put them on the destination <ul>, like this:

$("#source").children().clone().appendTo("#target");


问:
Show field_dict.items() of django-reversion in template
I am tring to use django reversion app in my project. I am little bit comfused. How to show list of changes (field_dict.items()) in template?

models.py:

```<code>@reversion.register()
class Function(models.Model):
    ***FIELDS***
</code>```

views.py:

```<code>def function_revisions(request, function_code):
    function = get_object_or_404(Function, pk=function_code)
    versions = Version.objects.get_for_object(Function)
    context = {
        'function': function,
        'versions': versions,
    }
    return render(request, 'project/function_revisions.html', context)
</code>```

function_revisions.html:

```<code>{% for version in versions %}
     <p>Version: {{ forloop.counter }}.</p>
     <p>Revision by {{ version.revision.user }}.</p>
     <p>Date of revision : {{ version.revision.date_created }}.</p>

     {% for field_name, field_value in version.field_dict.items() %} <-- ???
         <p>Field </p>{{ field_name }} had the value {{ field_value }}<p>
     {% endfor %}
{% endfor %}
</code>```

ERROR:

```<code>Traceback (most recent call last):
  File "C:\Users\Nurzhan\PycharmProjects\RMS\project\views.py", line 231, in function_revisions
    versions = Version.objects.get_for_object(Function)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\reversion\models.py", line 118, in get_for_object
    return self.get_for_object_reference(obj.__class__, obj.pk, model_db=model_db)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\reversion\models.py", line 113, in get_for_object_reference
    return self.get_for_model(model, model_db=model_db).filter(
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\reversion\models.py", line 106, in get_for_model
    content_type = _get_content_type(model, self.db)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\reversion\revisions.py", line 402, in _get_content_type
    version_options = _get_options(model)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\reversion\revisions.py", line 388, in _get_options
    _assert_registered(model)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\reversion\revisions.py", line 381, in _assert_registered
    if not is_registered(model):
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\reversion\revisions.py", line 319, in is_registered
    return _get_registration_key(model) in _registered_models
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\reversion\revisions.py", line 312, in _get_registration_key
    return (model._meta.app_label, model._meta.model_name)
AttributeError: type object 'ModelBase' has no attribute '_meta'
</code>```

答:
Drop the parens and the Django template engine will do the calling for you:

```<code>{% for field_name, field_value in version.field_dict.items %}
</code>```

This works for methods that take zero arguments.

Body:
I am tring to use django reversion app in my project. I am little bit comfused. How to show list of changes (field_dict.items()) in template?

models.py:

@reversion.register()
class Function(models.Model):
    ***FIELDS***

views.py:

def function_revisions(request, function_code):
    function = get_object_or_404(Function, pk=function_code)
    versions = Version.objects.get_for_object(Function)
    context = {
        'function': function,
        'versions': versions,
    }
    return render(request, 'project/function_revisions.html', context)

function_revisions.html:

{% for version in versions %}

Version: {{ forloop.counter }}.

Revision by {{ version.revision.user }}.

Date of revision : {{ version.revision.date_created }}.

     {% for field_name, field_value in version.field_dict.items() %} <-- ???

Field
{{ field_name }} had the value {{ field_value }}

     {% endfor %}
{% endfor %}

ERROR:

Traceback (most recent call last):
  File "C:\Users\Nurzhan\PycharmProjects\RMS\project\views.py", line 231, in function_revisions
    versions = Version.objects.get_for_object(Function)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\reversion\models.py", line 118, in get_for_object
    return self.get_for_object_reference(obj.__class__, obj.pk, model_db=model_db)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\reversion\models.py", line 113, in get_for_object_reference
    return self.get_for_model(model, model_db=model_db).filter(
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\reversion\models.py", line 106, in get_for_model
    content_type = _get_content_type(model, self.db)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\reversion\revisions.py", line 402, in _get_content_type
    version_options = _get_options(model)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\reversion\revisions.py", line 388, in _get_options
    _assert_registered(model)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\reversion\revisions.py", line 381, in _assert_registered
    if not is_registered(model):
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\reversion\revisions.py", line 319, in is_registered
    return _get_registration_key(model) in _registered_models
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\reversion\revisions.py", line 312, in _get_registration_key
    return (model._meta.app_label, model._meta.model_name)
AttributeError: type object 'ModelBase' has no attribute '_meta'

Body:
Drop the parens and the Django template engine will do the calling for you:

{% for field_name, field_value in version.field_dict.items %}

This works for methods that take zero arguments.


问:
Merge 2 SELECT statement in one result table
I have 2 different select statements, both of which generate similar tables. How can I put the result from both of them in one table?
Example:

First SELECT generates

```<code>Col1  Col2  Col3
A     X     Y
B     X     Z
</code>```

The second SELECT generates

```<code>Col1  Col2  Col3
A     Z     Z
C     X     X
</code>```

And I want the result to be

```<code>Col1  Col2  Col3
A     X     Y
B     X     Z
A     Z     Z
C     X     X
</code>```

答:
You should use UNION or UNION ALL if you want duplicate data.

Remember that column name and type must be same in two queries.

For example

```<code>SELECT
col1,
col2
FROM table1
UNION
SELECT
col1,
col2
FROM table2
</code>```

Body:
I have 2 different select statements, both of which generate similar tables. How can I put the result from both of them in one table?
Example:

First SELECT generates

Col1  Col2  Col3
A     X     Y
B     X     Z

The second SELECT generates

Col1  Col2  Col3
A     Z     Z
C     X     X

And I want the result to be

Col1  Col2  Col3
A     X     Y
B     X     Z
A     Z     Z
C     X     X

Body:
You should use UNION or UNION ALL if you want duplicate data.

Remember that column name and type must be same in two queries.

For example

SELECT
col1,
col2
FROM table1
UNION
SELECT
col1,
col2
FROM table2


问:
Sylius Product customized model : fields not showed in form
I started to learn Sylius few days ago. I need an ecommerce module within my Symfony 3 project. So I gonna extend my project with Sylius, I'll just use the Core/Components stack.

I started with the installation of the Sylius ProductBundle (cf. http://docs.sylius.org/en/latest/bundles/SyliusProductBundle/installation.html)

Seems simple but didn't work at first because Composer installed a stable version (0.19) which is not supported anymore... Anyway, I finally installed the sylius/sylius ~1.0@dev package so my composer.json looks like that :

```<code>"minimum-stability" : "dev",
"prefer-stable" : true,
"require" : {
    "php" : "^7.0",
    "sylius/sylius" : "^1.0@beta",
    "friendsofsymfony/user-bundle" : "~2.0@dev",
    "symfony/assetic-bundle" : "^2.8",
    "gedmo/doctrine-extensions" : "^2.4"
},
</code>```

=> First question : is this the right way ???

Then I created a SyliusBundle within my project to decouple the entire Sylius configuration from the rest of my project.

In SyliusBundle/app/config.yml :

```<code>imports:
    - { resource: "@SyliusProductBundle/Resources/config/app/config.yml" }

# Doctrine
stof_doctrine_extensions:
    default_locale: "%locale%"
    orm:
        default:
            tree: true
            sluggable: true
            timestampable: true
            loggable: false
            sortable: true

# Product
sylius_product:
    driver: doctrine/orm
    resources:
        product:
            classes:
                model: OfferBundle\Entity\Offer
                repository: OfferBundle\Entity\OfferRepository
                form: OfferBundle\Form\OfferType
</code>```

I followed the Sylius guideline to customize my Offer model inherited from Sylius Product model (quite simple)

in OfferBundle/Entity/Offer.php :

```<code><?php
namespace OfferBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Sylius\Component\Core\Model\Product as BaseProduct;

/**
 * @ORM\Table(name="offer")
 * @ORM\Entity(repositoryClass="OfferRepository")
 */
class Offer extends BaseProduct
{
</code>```

=> question 2 : sounds good to you ?

Then I customized the form extended my Offer form with the Sylius Product form (cf. http://docs.sylius.org/en/latest/customization/form.html)

in OfferBundle/Form/OfferType.php :

```<code><?php

namespace OfferBundle\Form;

use Symfony\Component\OptionsResolver\OptionsResolver;
use OfferBundle\Entity\Offer;
use Symfony\Component\Form\AbstractType;

class OfferType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(['data_class' => Offer::class]);
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'offer';
    }

    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        return \Sylius\Bundle\ProductBundle\Form\Type\ProductType::class;
    }
}
</code>```

In OfferBundle/Form/Extension/OfferTypeExtension.php :

```<code><?php

namespace OfferBundle\Form\Extension;

use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use AppBundle\Form\Type\WysiwygType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use OfferBundle\Form\Type\TagsType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use OfferBundle\Entity\Offer;
use MediaBundle\Form\MediaFileType;
use MediaBundle\Form\MediaVideoType;
use CompanyBundle\Entity\Company;
use Tetranz\Select2EntityBundle\Form\Type\Select2EntityType;
use Admin\CompanyBundle\Controller\CompanyController;
use Symfony\Component\Form\AbstractTypeExtension;
use OfferBundle\Form\ContactType;
use OfferBundle\Form\PriceType;
use OfferBundle\Form\OfferType;

final class OfferTypeExtension extends AbstractTypeExtension
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('advantage', WysiwygType::class)
            ->add('ecommerce')
            ->add('enabled')
            ->add('bestseller')
            ->add('company', Select2EntityType::class, [
                'multiple' => false,
                'remote_route' => 'admin_company_company_autocomplete',
                'class' => Company::class,
                'primary_key' => 'id',
                'text_property' => 'name',
                'minimum_input_length' => 0,
                'page_limit' => CompanyController::NB_PER_PAGE,
                'allow_clear' => false,
                'delay' => 250,
                'cache' => false,
                'cache_timeout' => 60000,
                'language' => 'fr',
                'placeholder' => 'form.choose',
                'required' => true,
            ])
            ->add('state', ChoiceType::class, [
                'choices' => Offer::getStates(),
                'placeholder' => 'form.choose',
            ])
...
</code>```

And the form extension is loaded by service.
in OfferBundle/Resources/config/services.yml :

```<code>offer.form.extension.type.offer:
        class: OfferBundle\Form\Extension\OfferTypeExtension
        tags:
            - { name: form.type_extension, extended_type: OfferBundle\Form\OfferType }
</code>```

Question 3 : It works BUT in see that Sylius\Bundle\CoreBundle\Form\Extension\ProductTypeExtension contains additionnal fields like $images, $variantSelectionMethod... But it doesn't appear in my form. So I suppose that a service.yml somewhere is not loaded ?

Hope somebody can help me on that !

答:
I think the problem is because you have overridden the form, and not extended it. So you only see your form fields, and not the Product form fields (as this form is not used anymore).
If you want to have the Product form with some changes, you only have to make a form extension to modify the existing Product form.

http://docs.sylius.org/en/latest/customization/form.html

Hope this helps ! :)

Body:
I started to learn Sylius few days ago. I need an ecommerce module within my Symfony 3 project. So I gonna extend my project with Sylius, I'll just use the Core/Components stack.

I started with the installation of the Sylius ProductBundle (cf. http://docs.sylius.org/en/latest/bundles/SyliusProductBundle/installation.html)

Seems simple but didn't work at first because Composer installed a stable version (0.19) which is not supported anymore... Anyway, I finally installed the sylius/sylius ~1.0@dev package so my composer.json looks like that :

"minimum-stability" : "dev",
"prefer-stable" : true,
"require" : {
    "php" : "^7.0",
    "sylius/sylius" : "^1.0@beta",
    "friendsofsymfony/user-bundle" : "~2.0@dev",
    "symfony/assetic-bundle" : "^2.8",
    "gedmo/doctrine-extensions" : "^2.4"
},

=> First question : is this the right way ???

Then I created a SyliusBundle within my project to decouple the entire Sylius configuration from the rest of my project.

In SyliusBundle/app/config.yml :

imports:
    - { resource: "@SyliusProductBundle/Resources/config/app/config.yml" }

# Doctrine
stof_doctrine_extensions:
    default_locale: "%locale%"
    orm:
        default:
            tree: true
            sluggable: true
            timestampable: true
            loggable: false
            sortable: true

# Product
sylius_product:
    driver: doctrine/orm
    resources:
        product:
            classes:
                model: OfferBundle\Entity\Offer
                repository: OfferBundle\Entity\OfferRepository
                form: OfferBundle\Form\OfferType

I followed the Sylius guideline to customize my Offer model inherited from Sylius Product model (quite simple)

in OfferBundle/Entity/Offer.php :

<?php
namespace OfferBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Sylius\Component\Core\Model\Product as BaseProduct;

/**
 * @ORM\Table(name="offer")
 * @ORM\Entity(repositoryClass="OfferRepository")
 */
class Offer extends BaseProduct
{

=> question 2 : sounds good to you ?

Then I customized the form extended my Offer form with the Sylius Product form (cf. http://docs.sylius.org/en/latest/customization/form.html)

in OfferBundle/Form/OfferType.php :

<?php

namespace OfferBundle\Form;

use Symfony\Component\OptionsResolver\OptionsResolver;
use OfferBundle\Entity\Offer;
use Symfony\Component\Form\AbstractType;

class OfferType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(['data_class' => Offer::class]);
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'offer';
    }

    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        return \Sylius\Bundle\ProductBundle\Form\Type\ProductType::class;
    }
}

In OfferBundle/Form/Extension/OfferTypeExtension.php :

<?php

namespace OfferBundle\Form\Extension;

use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use AppBundle\Form\Type\WysiwygType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use OfferBundle\Form\Type\TagsType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use OfferBundle\Entity\Offer;
use MediaBundle\Form\MediaFileType;
use MediaBundle\Form\MediaVideoType;
use CompanyBundle\Entity\Company;
use Tetranz\Select2EntityBundle\Form\Type\Select2EntityType;
use Admin\CompanyBundle\Controller\CompanyController;
use Symfony\Component\Form\AbstractTypeExtension;
use OfferBundle\Form\ContactType;
use OfferBundle\Form\PriceType;
use OfferBundle\Form\OfferType;

final class OfferTypeExtension extends AbstractTypeExtension
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('advantage', WysiwygType::class)
            ->add('ecommerce')
            ->add('enabled')
            ->add('bestseller')
            ->add('company', Select2EntityType::class, [
                'multiple' => false,
                'remote_route' => 'admin_company_company_autocomplete',
                'class' => Company::class,
                'primary_key' => 'id',
                'text_property' => 'name',
                'minimum_input_length' => 0,
                'page_limit' => CompanyController::NB_PER_PAGE,
                'allow_clear' => false,
                'delay' => 250,
                'cache' => false,
                'cache_timeout' => 60000,
                'language' => 'fr',
                'placeholder' => 'form.choose',
                'required' => true,
            ])
            ->add('state', ChoiceType::class, [
                'choices' => Offer::getStates(),
                'placeholder' => 'form.choose',
            ])
...

And the form extension is loaded by service.
in OfferBundle/Resources/config/services.yml :

offer.form.extension.type.offer:
        class: OfferBundle\Form\Extension\OfferTypeExtension
        tags:
            - { name: form.type_extension, extended_type: OfferBundle\Form\OfferType }

Question 3 : It works BUT in see that Sylius\Bundle\CoreBundle\Form\Extension\ProductTypeExtension contains additionnal fields like $images, $variantSelectionMethod... But it doesn't appear in my form. So I suppose that a service.yml somewhere is not loaded ?

Hope somebody can help me on that !


问:
Using response from one API call to do another API Call
I'm using AngularJS to build a site where one of the functions is to present Billboard(it's a music chart) listings for a specified date.
I want to present the songs in order, together with an image of the song.

First I'm calling this API:

http://billboard.modulo.site/

where I give a date and get a response of the top 10 songs for that date and data about each song.

The response from the Billboard API also includes a spotify id and I want to use that ID and call the Spotify Web API to get an image of that song, to complement the information I present about each song.

This is how it looks like in my controller:

```<code>var spotifyID = [];
$scope.spotifyImg = [];

musicService.getBillboard($scope.date).then(function(data){ //Response is top 10 songs for given date
        $scope.status = "";
        $scope.songlist = data;
        for (var i = 0; i < data.length; i++) {
            spotifyID[i] = data[i].spotify_id; //data[i].spotify_id returns the ID of the track, as given by the billboard API
        }
        $scope.getImages();
    });

$scope.getImages = function() {
    for (var i = 0; i < spotifyID.length; i++) {
        if(spotifyID[i] !== null) {
            musicService.getSpotify(spotifyID[i]).then(function(data){
                $scope.spotifyImg[i] = data.album.images[0].url; //returns the appropriate image from the Spotify Web API
        });
    }
    }
    console.log($scope.spotifyImg);
}
</code>```

And in my view it would look something like this:

```<code><div ng-repeat = "song in songlist">
    <div>{{ song.rank }}</div>
    <div>
        <img ng-src=" {{ spotifyImg[$index] }}"/>
    </div>
</div>
</code>```

However, it does not work.

When I'm checking the $scope.spotifyImg array in the console, it is of length 11 and only has one element in index 10 and that is the image of the last song(that is the 10th song).

I'm a bit confused as to why the $scope.spotifyImg array only contains one element in index 10. Also why is the array of length 11 when the spotifyID is of length 10?

Any ideas of how I could solve this?

答:
You can use IIFE

```<code>(function(i){
        musicService.getSpotify(spotifyID[i]).then(function (data) {

          $scope.spotifyImg[i] = data.album.images[0].url;
        });
 })(i)
</code>```

So,your getImages function should be like this.

```<code>$scope.getImages = function () {
for (var i = 0; i < spotifyID.length; i++) {
    if (spotifyID[i] !== null) {
        (function(i){
             musicService.getSpotify(spotifyID[i]).then(function (data) {

                $scope.spotifyImg[i] = data.album.images[0].url;
             });
        })(i)

    }
}
</code>```

}

Body:
I'm using AngularJS to build a site where one of the functions is to present Billboard(it's a music chart) listings for a specified date.
I want to present the songs in order, together with an image of the song.

First I'm calling this API:

http://billboard.modulo.site/

where I give a date and get a response of the top 10 songs for that date and data about each song.

The response from the Billboard API also includes a spotify id and I want to use that ID and call the Spotify Web API to get an image of that song, to complement the information I present about each song.

This is how it looks like in my controller:

var spotifyID = [];
$scope.spotifyImg = [];

musicService.getBillboard($scope.date).then(function(data){ //Response is top 10 songs for given date
        $scope.status = "";
        $scope.songlist = data;
        for (var i = 0; i < data.length; i++) {
            spotifyID[i] = data[i].spotify_id; //data[i].spotify_id returns the ID of the track, as given by the billboard API
        }
        $scope.getImages();
    });

$scope.getImages = function() {
    for (var i = 0; i < spotifyID.length; i++) {
        if(spotifyID[i] !== null) {
            musicService.getSpotify(spotifyID[i]).then(function(data){
                $scope.spotifyImg[i] = data.album.images[0].url; //returns the appropriate image from the Spotify Web API
        });
    }
    }
    console.log($scope.spotifyImg);
}

And in my view it would look something like this:

{{ song.rank }}

However, it does not work.

When I'm checking the $scope.spotifyImg array in the console, it is of length 11 and only has one element in index 10 and that is the image of the last song(that is the 10th song).

I'm a bit confused as to why the $scope.spotifyImg array only contains one element in index 10. Also why is the array of length 11 when the spotifyID is of length 10?

Any ideas of how I could solve this?

Body:
You can use IIFE

(function(i){
        musicService.getSpotify(spotifyID[i]).then(function (data) {

          $scope.spotifyImg[i] = data.album.images[0].url;
        });
 })(i)

So,your getImages function should be like this.

$scope.getImages = function () {
for (var i = 0; i < spotifyID.length; i++) {
    if (spotifyID[i] !== null) {
        (function(i){
             musicService.getSpotify(spotifyID[i]).then(function (data) {

                $scope.spotifyImg[i] = data.album.images[0].url;
             });
        })(i)

    }
}

}


问:
Generate CSR that is connected with 2 domains
I'm using plesk, how do I get a CSR for 2 domains at the same time? </p>

答:
If you want to generate a Certificate Signing Request (CSR) for your domains, then it depends on the type of SSL certificate that you will use. If each domain will have a separate SSL certificate, then you will need to generate one CSR for each domain.

If you are using the "Let's Encrypt" Plesk extension, then you should read the documentation on how to use it.