问:
Python Accessing Nested JSON Data
I'm trying to get the zip code for a particular city using zippopotam.us. I have the following code which works, except when I try to access the post code key which returns TypeError: expected string or buffer

```<code>r = requests.get('http://api.zippopotam.us/us/ma/belmont')
j = r.json()

data = json.loads(j)

print j['state']
print data['places']['latitude']
</code>```

Full JSON output:

```<code>{
"country abbreviation": "US",
"places": [
    {
        "place name": "Belmont",
        "longitude": "-71.4594",
        "post code": "02178",
        "latitude": "42.4464"
    },
    {
        "place name": "Belmont",
        "longitude": "-71.2044",
        "post code": "02478",
        "latitude": "42.4128"
    }
],
"country": "United States",
"place name": "Belmont",
"state": "Massachusetts",
"state abbreviation": "MA"
}
</code>```

答:
I'm using this lib to access nested dict keys

https://github.com/mewwts/addict

```<code> import requests
 from addict import Dict
 r = requests.get('http://api.zippopotam.us/us/ma/belmont')
 j = Dict(r.json())

 print j.state
 print j.places[1]['post code']  # only work with keys without '-', space, or starting with number
</code>```

Title: Python Accessing Nested JSON Data

Body:
I'm trying to get the zip code for a particular city using zippopotam.us. I have the following code which works, except when I try to access the post code key which returns TypeError: expected string or buffer

r = requests.get('http://api.zippopotam.us/us/ma/belmont')
j = r.json()

data = json.loads(j)

print j['state']
print data['places']['latitude']

Full JSON output:

{
"country abbreviation": "US",
"places": [
    {
        "place name": "Belmont",
        "longitude": "-71.4594",
        "post code": "02178",
        "latitude": "42.4464"
    },
    {
        "place name": "Belmont",
        "longitude": "-71.2044",
        "post code": "02478",
        "latitude": "42.4128"
    }
],
"country": "United States",
"place name": "Belmont",
"state": "Massachusetts",
"state abbreviation": "MA"
}

Body:
I'm using this lib to access nested dict keys

https://github.com/mewwts/addict

 import requests
 from addict import Dict
 r = requests.get('http://api.zippopotam.us/us/ma/belmont')
 j = Dict(r.json())

 print j.state
 print j.places[1]['post code']  # only work with keys without '-', space, or starting with number


来源: stackexchange

问:
Android Studio - SQL Syntax Error
Creating my first App in Android Studio. Creating a database to store values of customers.

This is the error I'm getting;

```<code>E/SQLiteLog: (1) near "Details": syntax error
E/SQLiteDatabase: Error inserting Surname=Cliff Contact Details=James@gmail.com  Address=111 First Name=James
                  android.database.sqlite.SQLiteException: near "Details": syntax error (code 1): , while compiling: INSERT INTO Customer_Table(Surname,Contact Details,Address,First Name) VALUES (?,?,?,?)
                  #################################################################
                  Error Code : 1 (SQLITE_ERROR)
                  Caused By : SQL(query) error or missing database.
                    (near "Details": syntax error (code 1): , while compiling: INSERT INTO Customer_Table(Surname,Contact Details,Address,First Name) VALUES (?,?,?,?))
                  #################################################################
                      at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                      at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1005)
                      at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:570)
                      at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                      at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:59)
                      at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
                      at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1771)
                      at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1643)
                      at com.example.user.plannerv2.DatabaseHelper.insertData(DatabaseHelper.java:43)
                      at com.example.user.plannerv2.Customer$1.onClick(Customer.java:39)
                      at android.view.View.performClick(View.java:6207)
                      at android.widget.TextView.performClick(TextView.java:11094)
                      at android.view.View$PerformClick.run(View.java:23639)
                      at android.os.Handler.handleCallback(Handler.java:751)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6688)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
</code>```

Not 100% sure where the error is coming from, Just starting to learn SQL.

This is my database.java class

```<code>    package com.example.user.plannerv2;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Created by user on 30/03/2017.
 */

public class DatabaseHelper extends SQLiteOpenHelper {
    public static final String DATABASE_NAME = "Customer.db";
    public static final String TABLE_NAME = "Customer_Table";
    public static final String COL_1 = "ID";
    public static final String COL_2 = "First Name";
    public static final String COL_3 = "Surname";
    public static final String COL_4 = "Address";
    public static final String COL_5 = "Contact Details";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, FIRST TEXT, SURNAME TEXT, ADDRESS TEXT, CONTACT TEXT);");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME);
        onCreate(db);
    }

    public boolean insertData(String first, String surname, String address, String contact) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL_2,first);
        contentValues.put(COL_3,surname);
        contentValues.put(COL_4,address);
        contentValues.put(COL_5,contact);
        long result = db.insert(TABLE_NAME,null ,contentValues);
        if(result == -1)
            return false;
        else
            return true;
    }
}
</code>```

Any help would be great :) Thanks.

答:
Your column names for COL_2 and COL_5 are invalid. You need to either remove the spaces or surround the column name with square brackets. Since the brackets are considered bad practice, I recommend you change COL_2 and COL_5 as follows:

```<code>public static final String COL_2 = "First_Name";
public static final String COL_5 = "Contact_Details";
</code>```

ContentLicense: CC BY-SA 3.0

Title: Android Studio - SQL Syntax Error

Body:
Creating my first App in Android Studio. Creating a database to store values of customers.

This is the error I'm getting;

E/SQLiteLog: (1) near "Details": syntax error
E/SQLiteDatabase: Error inserting Surname=Cliff Contact Details=James@gmail.com  Address=111 First Name=James
                  android.database.sqlite.SQLiteException: near "Details": syntax error (code 1): , while compiling: INSERT INTO Customer_Table(Surname,Contact Details,Address,First Name) VALUES (?,?,?,?)
                  #################################################################
                  Error Code : 1 (SQLITE_ERROR)
                  Caused By : SQL(query) error or missing database.
                    (near "Details": syntax error (code 1): , while compiling: INSERT INTO Customer_Table(Surname,Contact Details,Address,First Name) VALUES (?,?,?,?))
                  #################################################################
                      at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                      at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1005)
                      at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:570)
                      at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                      at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:59)
                      at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
                      at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1771)
                      at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1643)
                      at com.example.user.plannerv2.DatabaseHelper.insertData(DatabaseHelper.java:43)
                      at com.example.user.plannerv2.Customer$1.onClick(Customer.java:39)
                      at android.view.View.performClick(View.java:6207)
                      at android.widget.TextView.performClick(TextView.java:11094)
                      at android.view.View$PerformClick.run(View.java:23639)
                      at android.os.Handler.handleCallback(Handler.java:751)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6688)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)

Not 100% sure where the error is coming from, Just starting to learn SQL.

This is my database.java class

    package com.example.user.plannerv2;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Created by user on 30/03/2017.
 */

public class DatabaseHelper extends SQLiteOpenHelper {
    public static final String DATABASE_NAME = "Customer.db";
    public static final String TABLE_NAME = "Customer_Table";
    public static final String COL_1 = "ID";
    public static final String COL_2 = "First Name";
    public static final String COL_3 = "Surname";
    public static final String COL_4 = "Address";
    public static final String COL_5 = "Contact Details";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, FIRST TEXT, SURNAME TEXT, ADDRESS TEXT, CONTACT TEXT);");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME);
        onCreate(db);
    }

    public boolean insertData(String first, String surname, String address, String contact) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL_2,first);
        contentValues.put(COL_3,surname);
        contentValues.put(COL_4,address);
        contentValues.put(COL_5,contact);
        long result = db.insert(TABLE_NAME,null ,contentValues);
        if(result == -1)
            return false;
        else
            return true;
    }
}

Any help would be great :) Thanks.

Body:
Your column names for COL_2 and COL_5 are invalid. You need to either remove the spaces or surround the column name with square brackets. Since the brackets are considered bad practice, I recommend you change COL_2 and COL_5 as follows:

public static final String COL_2 = "First_Name";
public static final String COL_5 = "Contact_Details";


问:
Resetting the navigation stack for the home screen (React Navigation and React Native)
I've got a problem with the navigation of React Navigation and React Native. It is about resetting navigation and returning to the home screen.

I've build a StackNavigator inside of a DrawerNavigator, and the navigation between home screen and other screens is working. But the problem is, that the navigation stack grows and grows. I'm not sure how to remove a screen from the stack.

For example when going from the home screen to the settings screen, then to the entry screen and lastly again to the home screen, the home screen is twice in the stack. With the back button I do not get out of the app, but again to the entry screen.

When selecting the home button again a reset of the stack would be great, but I don't know how to do this. Here someone tried to help an other person with a similar problem, but the solution didn't work for me.

```<code>const Stack = StackNavigator({
  Home: {
    screen: Home
  },
  Entry: {
    screen: Entry
  },
  Settings: {
    screen: Settings
  }
})

export const Drawer = DrawerNavigator({
  Home: {
    screen: Stack
  }},
  {
    contentComponent: HamburgerMenu
  }
)
</code>```

And this is a simple example of the drawer screen

```<code>export default class HamburgerMenu extends Component {
  render () {
    return <ScrollView>
      <Icon.Button
        name={'home'}
        borderRadius={0}
        size={25}
        onPress={() => { this.props.navigation.navigate('Home')}}>
        <Text>{I18n.t('home')}</Text>
      </Icon.Button>

      <Icon.Button
        name={'settings'}
        borderRadius={0}
        size={25}
        onPress={() => { this.props.navigation.navigate('Settings')}}>
        <Text>{I18n.t('settings')}</Text>
      </Icon.Button>

      <Icon.Button
        name={'entry'}
        borderRadius={0}
        size={25}
        onPress={() => { this.props.navigation.navigate('Entry')}}>
        <Text>{I18n.t('entry')}</Text>
      </Icon.Button>
    </ScrollView>
  }
}
</code>```

I hope you can help me. This is an essential part of the navigation and a solution would be great!

答:
This is How I do it :

```<code>reset(){
    return this.props
               .navigation
               .dispatch(NavigationActions.reset(
                 {
                    index: 0,
                    actions: [
                      NavigationActions.navigate({ routeName: 'Menu'})
                    ]
                  }));
  }
</code>```

at least replace 'Menu' with 'Home'.
You may also want to adapt this.props.navigation to your implementation.

In version > 2 follow this:

```<code>import { NavigationActions, StackActions } from 'react-navigation';
        const resetAction = StackActions.reset({
                index: 0,
                actions: [NavigationActions.navigate({ routeName: 'MainActivity' })],
            });

this.props.navigation.dispatch(resetAction);
</code>```

Body:
I've got a problem with the navigation of React Navigation and React Native. It is about resetting navigation and returning to the home screen.

I've build a StackNavigator inside of a DrawerNavigator, and the navigation between home screen and other screens is working. But the problem is, that the navigation stack grows and grows. I'm not sure how to remove a screen from the stack.

For example when going from the home screen to the settings screen, then to the entry screen and lastly again to the home screen, the home screen is twice in the stack. With the back button I do not get out of the app, but again to the entry screen.

When selecting the home button again a reset of the stack would be great, but I don't know how to do this. Here someone tried to help an other person with a similar problem, but the solution didn't work for me.

const Stack = StackNavigator({
  Home: {
    screen: Home
  },
  Entry: {
    screen: Entry
  },
  Settings: {
    screen: Settings
  }
})

export const Drawer = DrawerNavigator({
  Home: {
    screen: Stack
  }},
  {
    contentComponent: HamburgerMenu
  }
)

And this is a simple example of the drawer screen

export default class HamburgerMenu extends Component {
  render () {
    return <ScrollView>
      <Icon.Button
        name={'home'}
        borderRadius={0}
        size={25}
        onPress={() => { this.props.navigation.navigate('Home')}}>
        <Text>{I18n.t('home')}</Text>
      </Icon.Button>

      <Icon.Button
        name={'settings'}
        borderRadius={0}
        size={25}
        onPress={() => { this.props.navigation.navigate('Settings')}}>
        <Text>{I18n.t('settings')}</Text>
      </Icon.Button>

      <Icon.Button
        name={'entry'}
        borderRadius={0}
        size={25}
        onPress={() => { this.props.navigation.navigate('Entry')}}>
        <Text>{I18n.t('entry')}</Text>
      </Icon.Button>
    </ScrollView>
  }
}

I hope you can help me. This is an essential part of the navigation and a solution would be great!

Body:
This is How I do it :

reset(){
    return this.props
               .navigation
               .dispatch(NavigationActions.reset(
                 {
                    index: 0,
                    actions: [
                      NavigationActions.navigate({ routeName: 'Menu'})
                    ]
                  }));
  }

at least replace 'Menu' with 'Home'.
You may also want to adapt this.props.navigation to your implementation.

In version > 2 follow this:

import { NavigationActions, StackActions } from 'react-navigation';
        const resetAction = StackActions.reset({
                index: 0,
                actions: [NavigationActions.navigate({ routeName: 'MainActivity' })],
            });

this.props.navigation.dispatch(resetAction);

ContentLicense: CC BY-SA 4.0


问:
Check if element has CSS class. If not add it
How can I convert my jQuery lines below into Javascript. I'd like to check if this element has a class. If it doesn't have the CSS class I want to add it to the element. The lines are in asterisks below.

Jquery

```<code>    var slides = document.querySelectorAll('#slides .slide');
    var currentSlide = 0;

  function goToSlide(n){

  //Remove showing from the current slide
    var thisSlide = slides[currentSlide];

    thisSlide.classList.remove("showing");

  //get position of next slide.
    currentSlide = (n+slides.length)%slides.length;

  //Add current to next slide
    var nextSlide = slides[currentSlide];

 //Check if nextSlide has showing class. If not, add it.
  **
   if (!($(nextSlide).hasClass('showing'))) {
           $(nextSlide).addClass('showing');
    }
  **

    }
</code>```

答:
You can use the classList and it's contains and add method.

```<code>if(!nextSlide.classList.contains(classname)){
      nextSlide.classList.add(classname);
}
</code>```

function addclass(){
  if(!document.getElementById('div1').classList.contains("new")){
      document.getElementById("div1").classList.add("new");
  }
  else{
      console.log("Already exist");
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.bg-r{
  width:50px;
  height:50px;
  border:1px solid #000;
}
.new{
  background-color:#f00;
}</code>```

<button onclick="addclass();">Add</button>```

Body:
How can I convert my jQuery lines below into Javascript. I'd like to check if this element has a class. If it doesn't have the CSS class I want to add it to the element. The lines are in asterisks below.

Jquery

    var slides = document.querySelectorAll('#slides .slide');
    var currentSlide = 0;

  function goToSlide(n){

  //Remove showing from the current slide
    var thisSlide = slides[currentSlide];

    thisSlide.classList.remove("showing");

  //get position of next slide.
    currentSlide = (n+slides.length)%slides.length;

  //Add current to next slide
    var nextSlide = slides[currentSlide];

 //Check if nextSlide has showing class. If not, add it.
  **
   if (!($(nextSlide).hasClass('showing'))) {
           $(nextSlide).addClass('showing');
    }
  **

    }

Body:
You can use the classList and it's contains and add method.

if(!nextSlide.classList.contains(classname)){
      nextSlide.classList.add(classname);
}

function addclass(){
  if(!document.getElementById('div1').classList.contains("new")){
      document.getElementById("div1").classList.add("new");
  }
  else{
      console.log("Already exist");
  }
}

.bg-r{
  width:50px;
  height:50px;
  border:1px solid #000;
}
.new{
  background-color:#f00;
}

<div id="div1" class="bg-r"></div>
<button onclick="addclass();">Add</button>


问:
Export/import ACL using csv
I want to export in a csv file the ACL of every subfolder starting from a root folder and then to import them of mirroring folders on another computer.

I'm using this code to export from C:\Users\user\Desktop\a :

```<code>Get-ChildItem "C:\Users\user\Desktop\a" -Recurse | ?{ $_.PsIsContainer } | %{
$Path = $_.FullName
# Exclude inherited rights from the report
(Get-Acl $Path).Access | ?{ !$_.IsInherited } | Select-Object `
    @{n='Path';e={ $Path }}, IdentityReference, AccessControlType, `
    InheritanceFlags, PropagationFlags, FileSystemRights
} | Export-CSV "C:\Users\user\Desktop\Permissions.csv"
</code>```

and this code to import ACL:

```<code>$par = Import-Csv -Path "C:\Users\user\Desktop\Permissions.csv"
foreach ( $i in $par ) {
    $path= $i.Path
    $IdentityReference= $i.IdentityReference
    $AccessControlType=$i.AccessControlType
    $InheritanceFlags= $i.InheritanceFlags
    $PropagationFlags=$i.PropagationFlags
    $FileSystemRights=$i.FileSystemRights
    echo $path $IdentityReference
    $acl = Get-Acl C:\Users\user\Desktop
    $permission = $i.IdentityReference,$i.FileSystemRights,$i.AccessControlType
    $accessRule = new-object System.Security.AccessControl.FileSystemAccessRule $permission
    $acl.SetAccessRule($accessRule)
    $acl | Set-Acl $path
}
</code>```

Permissions.csv is something like this:

```<code>#TYPE Selected.System.Security.AccessControl.FileSystemAccessRule
"Path","IdentityReference","AccessControlType","InheritanceFlags","PropagationFlags","FileSystemRights"
"C:\Users\user\Desktop\a\b","DITOADMIN\pluto","Allow","None","None","ReadAndExecute, Synchronize"
"C:\Users\user\Desktop\a\b\c","DITOADMIN\pluto","Allow","ContainerInherit, ObjectInherit","None","ReadAndExecute, Synchronize"
"C:\Users\user\Desktop\a\b\c","DITOADMIN\admin","Allow","None","None","FullControl"
"C:\Users\user\Desktop\a\b\c","DITOADMIN\pippo","Allow","ContainerInherit, ObjectInherit","None","ReadAndExecute, Synchronize"
</code>```

unfortunately, import action doesn't work since only last permission is imported (so only for pippo user and not for pluto).

anybody knows why?

答:
It's almost perfect.  Here you add the permission from the CSV to the folder, but you keep the old permission on it.  You dont "reset/copy" the ACL from one folder to the other.

So instead of getting the ACL of the receiving folder:
$acl = Get-Acl $path

Ive create a new one:
$acl = New-Object System.Security.AccessControl.DirectorySecurity

But then, i lose the Owner attribute.  So i need a way to export the owner in the CSV with the rights..

Title: Export/import ACL using csv

Body:
I want to export in a csv file the ACL of every subfolder starting from a root folder and then to import them of mirroring folders on another computer.

I'm using this code to export from C:\Users\user\Desktop\a :

Get-ChildItem "C:\Users\user\Desktop\a" -Recurse | ?{ $_.PsIsContainer } | %{
$Path = $_.FullName
# Exclude inherited rights from the report
(Get-Acl $Path).Access | ?{ !$_.IsInherited } | Select-Object `
    @{n='Path';e={ $Path }}, IdentityReference, AccessControlType, `
    InheritanceFlags, PropagationFlags, FileSystemRights
} | Export-CSV "C:\Users\user\Desktop\Permissions.csv"

and this code to import ACL:

$par = Import-Csv -Path "C:\Users\user\Desktop\Permissions.csv"
foreach ( $i in $par ) {
    $path= $i.Path
    $IdentityReference= $i.IdentityReference
    $AccessControlType=$i.AccessControlType
    $InheritanceFlags= $i.InheritanceFlags
    $PropagationFlags=$i.PropagationFlags
    $FileSystemRights=$i.FileSystemRights
    echo $path $IdentityReference
    $acl = Get-Acl C:\Users\user\Desktop
    $permission = $i.IdentityReference,$i.FileSystemRights,$i.AccessControlType
    $accessRule = new-object System.Security.AccessControl.FileSystemAccessRule $permission
    $acl.SetAccessRule($accessRule)
    $acl | Set-Acl $path
}

Permissions.csv is something like this:

#TYPE Selected.System.Security.AccessControl.FileSystemAccessRule
"Path","IdentityReference","AccessControlType","InheritanceFlags","PropagationFlags","FileSystemRights"
"C:\Users\user\Desktop\a\b","DITOADMIN\pluto","Allow","None","None","ReadAndExecute, Synchronize"
"C:\Users\user\Desktop\a\b\c","DITOADMIN\pluto","Allow","ContainerInherit, ObjectInherit","None","ReadAndExecute, Synchronize"
"C:\Users\user\Desktop\a\b\c","DITOADMIN\admin","Allow","None","None","FullControl"
"C:\Users\user\Desktop\a\b\c","DITOADMIN\pippo","Allow","ContainerInherit, ObjectInherit","None","ReadAndExecute, Synchronize"

unfortunately, import action doesn't work since only last permission is imported (so only for pippo user and not for pluto).

anybody knows why?


问:
How to price a SimpleCashFlow
I would like to use QuantLib to price a portfolio of liabilities, which are modeled to be deterministic future cash-flows. I am now modelling them as a strip of FixedRateBonds with zero coupons, which seems like a very inelegant solution.

Problem:

Question 1: Is there a way to create an 'Instrument' that is just a 'SimpleCashFlow', 'Redemption' etc. and price it on a discount curve?

Question 2: Is it possible to construct a 'CashFlows' object or Instrument from multiple SimpleCashFlow's and price it on a curve?

Many thanks in advance

Code Example:

See code below for an example of what I am trying to do.

```<code>from QuantLib import *

# set params
calc_date = Date(30, 3, 2017)
risk_free_rate = 0.01
discount_curve = YieldTermStructureHandle(
                     FlatForward(calc_date, risk_free_rate, ActualActual()))
bond_engine = DiscountingBondEngine(discount_curve)

# characteristics of the cash-flow that I am trying to NPV
paymentdate = Date(30, 3, 2018)
paymentamount = 1000

# this works: pricing a fixed rate bond with no coupons
schedule = Schedule(paymentdate-1, paymentdate, Period(Annual),  TARGET(),
Unadjusted, Unadjusted, DateGeneration.Backward, False)
fixed_rate_bond = FixedRateBond(0, paymentamount, schedule, [0.0],ActualActual())
bond_engine = DiscountingBondEngine(discount_curve)
fixed_rate_bond.setPricingEngine(bond_engine)
print(fixed_rate_bond.NPV())

# create a simple cashflow
simple_cash_flow = SimpleCashFlow(paymentamount, paymentdate)
# Q1: how to create instrument, set pricing engine and price a SimpleCashFlow?
#wrongcode:# simple_cash_flow.setPricingEngine(bond_engine)
#wrongcode:# print(simple_cash_flow.NPV())

# Q2: can I stick multiple cashflows into a single instrument, e.g.:
# how do I construct and price a CashFlows object from multiple 'SimpleCashFlow's?
simple_cash_flow2 = SimpleCashFlow(paymentamount, Date(30, 3, 2019))
#wrongcode:# cashflows_multiple = CashFlows([simple_cash_flow, simple_cash_flow2])
#wrongcode:# cashflows_multiple.setPricingEngine(bond_engine)
#wrongcode:# print(cashflows_multiple.NPV())
</code>```

答:
There are a couple of possible approaches.  If you want to use an instrument, you can use a ZeroCouponBond instead of the fixed-rate one you're currently using:

```<code>bond = ZeroCouponBond(0, TARGET(), paymentamount, paymentdate)
bond.setPricingEngine(bond_engine)
print(bond.NPV())
</code>```

Using an instrument will give you notifications and recalculation if the discount curve were to change, but might be overkill if you want a single pricing.  In that case, you might work directly with the cashflows by using the methods of the CashFlows class:

```<code>cf = SimpleCashFlow(paymentamount, paymentdate)
print(CashFlows.npv([cf], discount_curve, True))
</code>```

where the last parameter is True if you want to include any cashflow happening on today's date and False otherwise (note that this will give you a result a bit different from your calculation; that's because the payment date you used is a TARGET holiday, and the FixedRateBond constructor adjusts it to the next business day).

The above also works with several cash flows:

```<code>cfs = [SimpleCashFlow(paymentamount, paymentdate),
       SimpleCashFlow(paymentamount*0.5, paymentdate+180),
       SimpleCashFlow(paymentamount*2, paymentdate+360)]
print(CashFlows.npv(cfs, discount_curve, True))
</code>```

Finally, if you want to do the same with an instrument, you can use the base Bond class and pass the cashflows directly:

```<code>custom_bond = Bond(0, TARGET(), 100.0, Date(), Date(), cfs)
custom_bond.setPricingEngine(bond_engine)
print(custom_bond.NPV())
</code>```

this works but is kind of a kludge: the bond uses the passed cashflows directly and ignores the passed face amount and maturity date.

Title: How to price a SimpleCashFlow

Body:
I would like to use QuantLib to price a portfolio of liabilities, which are modeled to be deterministic future cash-flows. I am now modelling them as a strip of FixedRateBonds with zero coupons, which seems like a very inelegant solution.

Problem:

Question 1: Is there a way to create an 'Instrument' that is just a 'SimpleCashFlow', 'Redemption' etc. and price it on a discount curve?

Question 2: Is it possible to construct a 'CashFlows' object or Instrument from multiple SimpleCashFlow's and price it on a curve?

Many thanks in advance

Code Example:

See code below for an example of what I am trying to do.

from QuantLib import *

# set params
calc_date = Date(30, 3, 2017)
risk_free_rate = 0.01
discount_curve = YieldTermStructureHandle(
                     FlatForward(calc_date, risk_free_rate, ActualActual()))
bond_engine = DiscountingBondEngine(discount_curve)

# characteristics of the cash-flow that I am trying to NPV
paymentdate = Date(30, 3, 2018)
paymentamount = 1000

# this works: pricing a fixed rate bond with no coupons
schedule = Schedule(paymentdate-1, paymentdate, Period(Annual),  TARGET(),
Unadjusted, Unadjusted, DateGeneration.Backward, False)
fixed_rate_bond = FixedRateBond(0, paymentamount, schedule, [0.0],ActualActual())
bond_engine = DiscountingBondEngine(discount_curve)
fixed_rate_bond.setPricingEngine(bond_engine)
print(fixed_rate_bond.NPV())

# create a simple cashflow
simple_cash_flow = SimpleCashFlow(paymentamount, paymentdate)
# Q1: how to create instrument, set pricing engine and price a SimpleCashFlow?
#wrongcode:# simple_cash_flow.setPricingEngine(bond_engine)
#wrongcode:# print(simple_cash_flow.NPV())

# Q2: can I stick multiple cashflows into a single instrument, e.g.:
# how do I construct and price a CashFlows object from multiple 'SimpleCashFlow's?
simple_cash_flow2 = SimpleCashFlow(paymentamount, Date(30, 3, 2019))
#wrongcode:# cashflows_multiple = CashFlows([simple_cash_flow, simple_cash_flow2])
#wrongcode:# cashflows_multiple.setPricingEngine(bond_engine)
#wrongcode:# print(cashflows_multiple.NPV())

Body:
There are a couple of possible approaches.  If you want to use an instrument, you can use a ZeroCouponBond instead of the fixed-rate one you're currently using:

bond = ZeroCouponBond(0, TARGET(), paymentamount, paymentdate)
bond.setPricingEngine(bond_engine)
print(bond.NPV())

Using an instrument will give you notifications and recalculation if the discount curve were to change, but might be overkill if you want a single pricing.  In that case, you might work directly with the cashflows by using the methods of the CashFlows class:

cf = SimpleCashFlow(paymentamount, paymentdate)
print(CashFlows.npv([cf], discount_curve, True))

where the last parameter is True if you want to include any cashflow happening on today's date and False otherwise (note that this will give you a result a bit different from your calculation; that's because the payment date you used is a TARGET holiday, and the FixedRateBond constructor adjusts it to the next business day).

The above also works with several cash flows:

cfs = [SimpleCashFlow(paymentamount, paymentdate),
       SimpleCashFlow(paymentamount*0.5, paymentdate+180),
       SimpleCashFlow(paymentamount*2, paymentdate+360)]
print(CashFlows.npv(cfs, discount_curve, True))

Finally, if you want to do the same with an instrument, you can use the base Bond class and pass the cashflows directly:

custom_bond = Bond(0, TARGET(), 100.0, Date(), Date(), cfs)
custom_bond.setPricingEngine(bond_engine)
print(custom_bond.NPV())

this works but is kind of a kludge: the bond uses the passed cashflows directly and ignores the passed face amount and maturity date.


问:
Perform procedural function on varchar field
I have a dataset merged from two databases, one American (imperial units) and one European (metric units). I have cleaned up the records duplicated between the two data sets, and converted the data to be in inches, but the single database feeds both a United States web store and a European web store.

The European web store needs to display units in CM, not inches. This is not a problem for most of the fields, as the measurements are stored as integers and can be converted in a view. I want to convert the instances of inch based measurements in the text fields to centimeters, but the only custom functions I've ever seen for SQL are set based functions, not the traditional procedure based operation I need which would involve looping through the text field.

Current

```<code>table productData
id    |  height  |  width  |  detail
00001 |      12  |     18  |  Up to 12" of steel
00002 |      24  |     18  |  Up to 24" of steel
00003 |       8  |      8  |  Brace with multiple 2" x 3" brackets
...   |      ..  |     ..  |  ...

view productData_EU
SELECT
    id,
    CEILING(height * 5 / 2) height,
    CEILING(width * 5 / 2) width,
    detail
FROM productData

id    |  height  |  width  |  detail
00001 |      30  |     45  |  Up to 12" of steel
00002 |      60  |     45  |  Up to 24" of steel
00003 |      20  |     20  |  Brace with multiple 2" x 3" brackets
...   |      ..  |     ..  |  ...
</code>```

Desired

```<code>view productData_EU
SELECT
    id,
    CEILING(height * 5 / 2) height,
    CEILING(width * 5 / 2) width,
    CUSTOMFUNCTION(detail) detail
FROM productData

id    |  height  |  width  |  detail
00001 |      30  |     45  |  Up to 30 cm of steel
00002 |      60  |     45  |  Up to 60 cm of steel
00003 |      20  |     20  |  Brace with multiple 5 cm x 8 cm brackets
...   |      ..  |     ..  |  ...
</code>```

How do I perform a traditional function (CUSTOMFUNCTION) on each record when making this view? I have the option of a scalar UDF which nests a lot of CHARINDEX() and REPLACE(), but a loop would be far more flexible.

答:
I modified my EXTRACT Table-Valued Function to perform a global search and replace and conversion to CM.  Assuming this is the only conversion required.

Now, I didn't like converting a TVF to a scalar, but the performance should still be respectable.

This will convert any value begining with a space and ending with a double-quote.  For example Some value 12" of steel

This can be further parametrized but I didn't want to over-engineer it

Example

```<code>Declare @productData table (id varchar(25),height int,width int ,detail varchar(100))
Insert Into @productData values
('00001', 12, 18,'Up to 12" of steel'),
('00002', 24, 18,'Up to 24" of steel'),
('00003',  8,  8,'Brace with multiple 2" x 3" brackets')

Select id
      ,height = ceiling(height * 5 / 2.0)
      ,width  = ceiling(width * 5 / 2.0)
      ,detail = [dbo].[CUSTOMFUNCTION1](A.detail)
 From  @productData A
</code>```

Returns

The UDF

```<code>CREATE FUNCTION [dbo].[CUSTOMFUNCTION1](@String varchar(max))
Returns varchar(max) as
Begin
    with   cte1(N)   As (Select Top (IsNull(DataLength(@String),0)) N=Row_Number() Over (Order By (Select null)) From master..spt_values N1,master..spt_values N2 ),
           cte2(N)   As (Select 1 Union All Select t.N+DataLength(' ') From cte1 t Where Substring(@String,t.N,DataLength(' ')) = ' '),
           cte3(N,L) As (Select S.N,IsNull(NullIf(CharIndex(' ',@String,s.N),0)-S.N,8000) From cte2 S)

    Select @String = Replace(@String,' '+RetVal+'"',concat(' ',ceiling(RetVal * 5 / 2.0),' cm'))
    From (
            Select RetVal = left(RetVal,charindex('"',RetVal)-1)
             From  (Select *,RetVal = Substring(@String, N, L) From cte3) A
             Where charindex('"',RetVal)>1
         ) R1

    Return @String

End
</code>```

Body:
I have a dataset merged from two databases, one American (imperial units) and one European (metric units). I have cleaned up the records duplicated between the two data sets, and converted the data to be in inches, but the single database feeds both a United States web store and a European web store.

The European web store needs to display units in CM, not inches. This is not a problem for most of the fields, as the measurements are stored as integers and can be converted in a view. I want to convert the instances of inch based measurements in the text fields to centimeters, but the only custom functions I've ever seen for SQL are set based functions, not the traditional procedure based operation I need which would involve looping through the text field.

Current

table productData
id    |  height  |  width  |  detail
00001 |      12  |     18  |  Up to 12" of steel
00002 |      24  |     18  |  Up to 24" of steel
00003 |       8  |      8  |  Brace with multiple 2" x 3" brackets
...   |      ..  |     ..  |  ...

view productData_EU
SELECT
    id,
    CEILING(height * 5 / 2) height,
    CEILING(width * 5 / 2) width,
    detail
FROM productData

id    |  height  |  width  |  detail
00001 |      30  |     45  |  Up to 12" of steel
00002 |      60  |     45  |  Up to 24" of steel
00003 |      20  |     20  |  Brace with multiple 2" x 3" brackets
...   |      ..  |     ..  |  ...

Desired

view productData_EU
SELECT
    id,
    CEILING(height * 5 / 2) height,
    CEILING(width * 5 / 2) width,
    CUSTOMFUNCTION(detail) detail
FROM productData

id    |  height  |  width  |  detail
00001 |      30  |     45  |  Up to 30 cm of steel
00002 |      60  |     45  |  Up to 60 cm of steel
00003 |      20  |     20  |  Brace with multiple 5 cm x 8 cm brackets
...   |      ..  |     ..  |  ...

How do I perform a traditional function (CUSTOMFUNCTION) on each record when making this view? I have the option of a scalar UDF which nests a lot of CHARINDEX() and REPLACE(), but a loop would be far more flexible.

Body:
I modified my EXTRACT Table-Valued Function to perform a global search and replace and conversion to CM.  Assuming this is the only conversion required.

Now, I didn't like converting a TVF to a scalar, but the performance should still be respectable.

This will convert any value begining with a space and ending with a double-quote.  For example Some value 12" of steel

This can be further parametrized but I didn't want to over-engineer it

Example

Declare @productData table (id varchar(25),height int,width int ,detail varchar(100))
Insert Into @productData values
('00001', 12, 18,'Up to 12" of steel'),
('00002', 24, 18,'Up to 24" of steel'),
('00003',  8,  8,'Brace with multiple 2" x 3" brackets')

Select id
      ,height = ceiling(height * 5 / 2.0)
      ,width  = ceiling(width * 5 / 2.0)
      ,detail = [dbo].[CUSTOMFUNCTION1](A.detail)
 From  @productData A

Returns

The UDF

CREATE FUNCTION [dbo].[CUSTOMFUNCTION1](@String varchar(max))
Returns varchar(max) as
Begin
    with   cte1(N)   As (Select Top (IsNull(DataLength(@String),0)) N=Row_Number() Over (Order By (Select null)) From master..spt_values N1,master..spt_values N2 ),
           cte2(N)   As (Select 1 Union All Select t.N+DataLength(' ') From cte1 t Where Substring(@String,t.N,DataLength(' ')) = ' '),
           cte3(N,L) As (Select S.N,IsNull(NullIf(CharIndex(' ',@String,s.N),0)-S.N,8000) From cte2 S)

    Select @String = Replace(@String,' '+RetVal+'"',concat(' ',ceiling(RetVal * 5 / 2.0),' cm'))
    From (
            Select RetVal = left(RetVal,charindex('"',RetVal)-1)
             From  (Select *,RetVal = Substring(@String, N, L) From cte3) A
             Where charindex('"',RetVal)>1
         ) R1

    Return @String

End


问:
Found a Customizer setting that did not have a sanitization callback function. wordpress theme check plugin
i have added  'sanitize_callback' to every add_setting() function but it still show the error. Please anyone Check My Code snippet and give me suggestion

```<code>function bookish_customize_register( $wp_customize ) {

$wp_customize->get_setting( 'blogname' )->transport        = 'postMessage';
$wp_customize->get_setting( 'blogdescription' )->transport = 'postMessage';

$wp_customize->remove_control( 'header_textcolor' );
$wp_customize->remove_control( 'background_color' );
$wp_customize->remove_section( 'background_image' );
$wp_customize->remove_section( 'header_image' );

/*-----------------------------------------------------------*
 * Assent Color  section
 *-----------------------------------------------------------*/

$wp_customize->add_setting(
    'tcx_link_color',
    array(
        'default'     => '#000000',
        'sanitize_callback' => 'bookish_sanitize_text',
        'transport'   => 'postMessage',

    )
);

$wp_customize->add_control(
    new WP_Customize_Color_Control(
        $wp_customize,
        'link_color',
        array(
            'label'      => __( 'Link Color', 'tcx' ),
            'section'    => 'colors',
            'settings'   => 'tcx_link_color'
        )
    )
);
/*-----------------------------------------------------------*
 * Defining General Setting  section
 *-----------------------------------------------------------*/

$wp_customize->add_section(
    'bookish_general_setting',
    array(
        'title'     => 'General Settings',
        'priority'  => 1

    )
);

$wp_customize->add_setting(
            'bookish-logo',
            array(
                'default' => '',
                'sanitize_callback' => 'esc_url_raw',
                'transport'   => 'postMessage',

            )
        );

$wp_customize->add_control(
    new WP_Customize_Image_Control(
        $wp_customize,
        'bookish-logo',
        array(
            'label'    => __( ' Logo', 'bookish' ),
            'section'  => 'bookish_general_setting',
            'settings' => 'bookish-logo',
            'priority' => 1

        )
    )
);

$wp_customize->add_setting(
        'bookish-retina-logo',
        array(
            'default' => '',
            'sanitize_callback' => 'esc_url_raw',
            'transport'   => 'postMessage',
        )
    );

$wp_customize->add_control(
    new WP_Customize_Image_Control(
        $wp_customize,
        'bookish-retina-logo',
        array(
            'label'    => __( 'Retina Logo', 'bookish' ),
            'section'  => 'bookish_general_setting',
            'settings' => 'bookish-retina-logo',
            'priority' => 2

        )
    )
);

$wp_customize->add_setting(
    'bookish-favicon',
    array(
        'default'  => '',
        'sanitize_callback' => 'esc_url_raw',
        'transport'   => 'postMessage',

    )
);

$wp_customize->add_control(
    new WP_Customize_Image_Control(
        $wp_customize,
        'bookish-favicon',
        array(
            'label'    => __( ' Favicon', 'bookish' ),
            'section'  => 'bookish_general_setting',
            'settings' => 'bookish-favicon',
            'priority' => 3

        )
    )
);

$wp_customize->add_setting(
    'bookish-avatar',
    array(
        'default'          => '',
        'sanitize_callback' => 'esc_url_raw',
        'transport'   => 'postMessage',

    )
);

$wp_customize->add_control(
    new WP_Customize_Image_Control(
        $wp_customize,
        'bookish-avatar',
        array(
            'label'    => __( 'Avatar', 'bookish' ),
            'section'  => 'bookish_general_setting',
            'settings' => 'bookish-avatar',
            'priority' => 4
        )
    )
);

$wp_customize->add_setting(
    'bookish-retina-avatar',
    array(
        'default'          => '',
        'sanitize_callback' => 'esc_url_raw',
        'transport'   => 'postMessage',

    )
);

$wp_customize->add_control(
    new WP_Customize_Image_Control(
        $wp_customize,
        'bookish-retina-avatar',
        array(
            'label'    => __( 'Retina Avatar', 'bookish' ),
            'section'  => 'bookish_general_setting',
            'settings' => 'bookish-retina-avatar',
            'priority' => 5
        )
    )
);

$wp_customize->add_setting(
    'bookish_profile_name',
    array(
        'default'    =>  'Vincent Doe',
        'sanitize_callback' => 'bookish_sanitize_text',
        'transport'  =>  'postMessage',
    )
);

$wp_customize->add_control(
    'bookish_profile_name',
    array(
        'section'   => 'bookish_general_setting',
        'label'     => 'Profile Name',
        'type'      => 'text'
    )
);

$wp_customize->add_setting(
    'bookish_profile_desc',
    array(
        'default'    =>  'I lie close to the earth, a thousand unknown plants are noticed by me: when I hear the buzz of the little world among the stalks.',
        'sanitize_callback' => 'bookish_sanitize_textarea',
        'transport'  =>  'postMessage',

    )
);

$wp_customize->add_control(
    'bookish_profile_desc',
    array(
        'section'   => 'bookish_general_setting',
        'label'     => 'Profile Description',
        'type'      => 'textarea'
    )
);

$wp_customize->add_section(
    'contact_setting',
    array(
        'title'     => 'Contact Info',
        'priority'  => 2
    )
);

$wp_customize->add_setting(
    'contact_heading',
    array(
        'default'    =>  'Get in touch',
        'sanitize_callback' => 'bookish_sanitize_text',
        'transport'  =>  'postMessage',
    )
);

$wp_customize->add_control(
    'contact_heading',
    array(
        'section'   => 'contact_setting',
        'label'     => 'Contact Heading',
        'type'      => 'text'
    )
);

$wp_customize->add_setting(
    'contact_email',
    array(
        'default'    =>  '',
        'sanitize_callback' => 'bookish_sanitize_email',
        'transport'  =>  'postMessage',
    )
);

$wp_customize->add_control(
    'contact_email',
    array(
        'section'   => 'contact_setting',
        'label'     => 'Email',
        'type'      =>  'email'

    )
);

$wp_customize->add_setting(
    'contact_phone',
    array(
        'default'    =>  '',
        'sanitize_callback' => 'bookish_sanitize_number',
        'transport'  =>  'postMessage',
    )
);

$wp_customize->add_control(
    'contact_phone',
    array(
        'section'   => 'contact_setting',
        'label'     => 'Phone Number',
        'type'      => 'text'
    )
);

}

add_action( 'customize_register', 'bookish_customize_register', 11 );

/**
 * Binds JS handlers to make Theme Customizer preview reload changes asynchronously.
 */
function bookish_customize_preview_js() {
    wp_enqueue_script( 'bookish_customizer', get_template_directory_uri() . '/assets/js/customizer.js', array( 'customize-preview' ), '20130508', true );
}
add_action( 'customize_preview_init', 'bookish_customize_preview_js' );

function bookish_sanitize_text( $str ) {
    return sanitize_text_field( $str );
}

function bookish_sanitize_textarea( $text ) {
    return esc_textarea( $text );
}

function bookish_sanitize_number( $int ) {
    return absint( $int );
}

function bookish_sanitize_email( $email ) {
    if(is_email( $email )){
        return $email;
    }else{
        return '';
    }
}

function bookish_sanitize_file_url( $url ) {
    $output = '';
    $filetype = wp_check_filetype( $url );
    if ( $filetype["ext"] ) {
        $output = esc_url( $url );
    }
    return $output;
}

function tcx_customizer_css() {
?>
     <style type="text/css">

        .TopBanner { background-color: <?php echo get_theme_mod( 'tcx_link_color' ); ?>!important; }

     </style>
<?php
}
add_action( 'wp_head', 'tcx_customizer_css' );
</code>```

Thanks in Advance

答:
I have got new solution if above issue

```<code>'sanitize_callback' => 'esc_attr',
</code>```

Then after check theme on theme checker, i can not get any error there
i hope help some one.

Body:
i have added  'sanitize_callback' to every add_setting() function but it still show the error. Please anyone Check My Code snippet and give me suggestion

function bookish_customize_register( $wp_customize ) {

$wp_customize->get_setting( 'blogname' )->transport        = 'postMessage';
$wp_customize->get_setting( 'blogdescription' )->transport = 'postMessage';

$wp_customize->remove_control( 'header_textcolor' );
$wp_customize->remove_control( 'background_color' );
$wp_customize->remove_section( 'background_image' );
$wp_customize->remove_section( 'header_image' );

/*-----------------------------------------------------------*
 * Assent Color  section
 *-----------------------------------------------------------*/

$wp_customize->add_setting(
    'tcx_link_color',
    array(
        'default'     => '#000000',
        'sanitize_callback' => 'bookish_sanitize_text',
        'transport'   => 'postMessage',

    )
);

$wp_customize->add_control(
    new WP_Customize_Color_Control(
        $wp_customize,
        'link_color',
        array(
            'label'      => __( 'Link Color', 'tcx' ),
            'section'    => 'colors',
            'settings'   => 'tcx_link_color'
        )
    )
);
/*-----------------------------------------------------------*
 * Defining General Setting  section
 *-----------------------------------------------------------*/

$wp_customize->add_section(
    'bookish_general_setting',
    array(
        'title'     => 'General Settings',
        'priority'  => 1

    )
);

$wp_customize->add_setting(
            'bookish-logo',
            array(
                'default' => '',
                'sanitize_callback' => 'esc_url_raw',
                'transport'   => 'postMessage',

            )
        );

$wp_customize->add_control(
    new WP_Customize_Image_Control(
        $wp_customize,
        'bookish-logo',
        array(
            'label'    => __( ' Logo', 'bookish' ),
            'section'  => 'bookish_general_setting',
            'settings' => 'bookish-logo',
            'priority' => 1

        )
    )
);

$wp_customize->add_setting(
        'bookish-retina-logo',
        array(
            'default' => '',
            'sanitize_callback' => 'esc_url_raw',
            'transport'   => 'postMessage',
        )
    );

$wp_customize->add_control(
    new WP_Customize_Image_Control(
        $wp_customize,
        'bookish-retina-logo',
        array(
            'label'    => __( 'Retina Logo', 'bookish' ),
            'section'  => 'bookish_general_setting',
            'settings' => 'bookish-retina-logo',
            'priority' => 2

        )
    )
);

$wp_customize->add_setting(
    'bookish-favicon',
    array(
        'default'  => '',
        'sanitize_callback' => 'esc_url_raw',
        'transport'   => 'postMessage',

    )
);

$wp_customize->add_control(
    new WP_Customize_Image_Control(
        $wp_customize,
        'bookish-favicon',
        array(
            'label'    => __( ' Favicon', 'bookish' ),
            'section'  => 'bookish_general_setting',
            'settings' => 'bookish-favicon',
            'priority' => 3

        )
    )
);

$wp_customize->add_setting(
    'bookish-avatar',
    array(
        'default'          => '',
        'sanitize_callback' => 'esc_url_raw',
        'transport'   => 'postMessage',

    )
);

$wp_customize->add_control(
    new WP_Customize_Image_Control(
        $wp_customize,
        'bookish-avatar',
        array(
            'label'    => __( 'Avatar', 'bookish' ),
            'section'  => 'bookish_general_setting',
            'settings' => 'bookish-avatar',
            'priority' => 4
        )
    )
);

$wp_customize->add_setting(
    'bookish-retina-avatar',
    array(
        'default'          => '',
        'sanitize_callback' => 'esc_url_raw',
        'transport'   => 'postMessage',

    )
);

$wp_customize->add_control(
    new WP_Customize_Image_Control(
        $wp_customize,
        'bookish-retina-avatar',
        array(
            'label'    => __( 'Retina Avatar', 'bookish' ),
            'section'  => 'bookish_general_setting',
            'settings' => 'bookish-retina-avatar',
            'priority' => 5
        )
    )
);

$wp_customize->add_setting(
    'bookish_profile_name',
    array(
        'default'    =>  'Vincent Doe',
        'sanitize_callback' => 'bookish_sanitize_text',
        'transport'  =>  'postMessage',
    )
);

$wp_customize->add_control(
    'bookish_profile_name',
    array(
        'section'   => 'bookish_general_setting',
        'label'     => 'Profile Name',
        'type'      => 'text'
    )
);

$wp_customize->add_setting(
    'bookish_profile_desc',
    array(
        'default'    =>  'I lie close to the earth, a thousand unknown plants are noticed by me: when I hear the buzz of the little world among the stalks.',
        'sanitize_callback' => 'bookish_sanitize_textarea',
        'transport'  =>  'postMessage',

    )
);

$wp_customize->add_control(
    'bookish_profile_desc',
    array(
        'section'   => 'bookish_general_setting',
        'label'     => 'Profile Description',
        'type'      => 'textarea'
    )
);

$wp_customize->add_section(
    'contact_setting',
    array(
        'title'     => 'Contact Info',
        'priority'  => 2
    )
);

$wp_customize->add_setting(
    'contact_heading',
    array(
        'default'    =>  'Get in touch',
        'sanitize_callback' => 'bookish_sanitize_text',
        'transport'  =>  'postMessage',
    )
);

$wp_customize->add_control(
    'contact_heading',
    array(
        'section'   => 'contact_setting',
        'label'     => 'Contact Heading',
        'type'      => 'text'
    )
);

$wp_customize->add_setting(
    'contact_email',
    array(
        'default'    =>  '',
        'sanitize_callback' => 'bookish_sanitize_email',
        'transport'  =>  'postMessage',
    )
);

$wp_customize->add_control(
    'contact_email',
    array(
        'section'   => 'contact_setting',
        'label'     => 'Email',
        'type'      =>  'email'

    )
);

$wp_customize->add_setting(
    'contact_phone',
    array(
        'default'    =>  '',
        'sanitize_callback' => 'bookish_sanitize_number',
        'transport'  =>  'postMessage',
    )
);

$wp_customize->add_control(
    'contact_phone',
    array(
        'section'   => 'contact_setting',
        'label'     => 'Phone Number',
        'type'      => 'text'
    )
);

}

add_action( 'customize_register', 'bookish_customize_register', 11 );

/**
 * Binds JS handlers to make Theme Customizer preview reload changes asynchronously.
 */
function bookish_customize_preview_js() {
    wp_enqueue_script( 'bookish_customizer', get_template_directory_uri() . '/assets/js/customizer.js', array( 'customize-preview' ), '20130508', true );
}
add_action( 'customize_preview_init', 'bookish_customize_preview_js' );

function bookish_sanitize_text( $str ) {
    return sanitize_text_field( $str );
}

function bookish_sanitize_textarea( $text ) {
    return esc_textarea( $text );
}

function bookish_sanitize_number( $int ) {
    return absint( $int );
}

function bookish_sanitize_email( $email ) {
    if(is_email( $email )){
        return $email;
    }else{
        return '';
    }
}

function bookish_sanitize_file_url( $url ) {
    $output = '';
    $filetype = wp_check_filetype( $url );
    if ( $filetype["ext"] ) {
        $output = esc_url( $url );
    }
    return $output;
}

function tcx_customizer_css() {
?>

<?php
}
add_action( 'wp_head', 'tcx_customizer_css' );

Thanks in Advance

Body:
I have got new solution if above issue

'sanitize_callback' => 'esc_attr',

Then after check theme on theme checker, i can not get any error there
i hope help some one.


问:
Wordpress site - using custom PHP and database
I have finally finished coding a project with an HTML form for file upload, and a large PHP file that submits a 200 field CSV into my database. It first uploads to a staging table and then splits the data into smaller tables.

This all works perfectly but I'm having problems with the next step: This is needed to run on a wordpress site that already exists. I have a database just for this project with tables for users, clients, staging, meters, etc. I need all of these tables in their own database because these users are separate from the WP users.

I found a plugin that allows you to insert PHP into pages, but I need to know how to work with a custom database in WP, I've only ever worked with the actual database. Any help is greatly appreciated.

答:
Include wordpress db file in your script 'wp-admin/includes/upgrade.php' and then call

```<code>global $wpdb;
$wpdb->query($your_query_string);
</code>```

This way you can use wordpress database. But go through wordpress once so you will be aware of tables. Because wordpress save specific data to specific tables, say - any informartion about user to user_meta table.

If you are trying to insert new users then you may need to enter data into user table.

Another method is there.

You can open your wordpress theme's function.php then you can write scripts to enter your data or what ever fuctionality you are looking for. And I think that is a better way to work with wordpress.

Body:
Include wordpress db file in your script 'wp-admin/includes/upgrade.php' and then call

global $wpdb;
$wpdb->query($your_query_string);

This way you can use wordpress database. But go through wordpress once so you will be aware of tables. Because wordpress save specific data to specific tables, say - any informartion about user to user_meta table.

If you are trying to insert new users then you may need to enter data into user table.

Another method is there.

You can open your wordpress theme's function.php then you can write scripts to enter your data or what ever fuctionality you are looking for. And I think that is a better way to work with wordpress.


问:
Player-turn based Dice game (having trouble with loops)
Background; I'm trying to create a dice game for multi-players where you can choose how many players, sides on the die and dice's themselves you want in the game. And players each take a turn rolling n amount of dices and per each roll the score gets appended to the player classes playerScore property. Once a player reaches X amount of points, player is declared a winner.

Problem; The below code is part of the "Game" class. When I compile the code, the game does what I expect for the most part; it rolls 5 dices each turn per player and appends the points to said player, but once the player reaches 100 points, the player is declared a winner, but the die's are rolled again for another player, despite the fact that the while loop is invalidated. The way i see it, the problem is with the for loop, but I have no idea how to fix this, i tried "break" but it only breaks from the if statement.

My program has 3 classes; Die, Player, Game. If you need more information or screen shots. I can provide them.

P.S. If you think this code could be improved, please comment, I'd be glad to hear it out.

答:
You could do like this:</p>

```<code>public void StartGame(int maxPoints)
    {
        //playerArray[0].PlayerTurn = true; // Is it necessary?

        while (true)
        {
            for (int i = 0; i < playerArray.Length; i++)
            {
                Player currentPlayer = playerArray[i];
                currentPlayer.PlayerScore += rollAllDice();
                Console.WriteLine("'{0}': {1}", currentPlayer.PlayerName, currentPlayer.PlayerScore);

                if (currentPlayer.PlayerScore >= maxPoints)
                {
                    Console.WriteLine("Congratulations, Player '{0}' has won by reaching {1} points.", currentPlayer.PlayerName, currentPlayer.PlayerScore);
                    return;
                }
            }
        }
    }
</code>```

Body:
You could do like this:

public void StartGame(int maxPoints)
    {
        //playerArray[0].PlayerTurn = true; // Is it necessary?

        while (true)
        {
            for (int i = 0; i < playerArray.Length; i++)
            {
                Player currentPlayer = playerArray[i];
                currentPlayer.PlayerScore += rollAllDice();
                Console.WriteLine("'{0}': {1}", currentPlayer.PlayerName, currentPlayer.PlayerScore);

                if (currentPlayer.PlayerScore >= maxPoints)
                {
                    Console.WriteLine("Congratulations, Player '{0}' has won by reaching {1} points.", currentPlayer.PlayerName, currentPlayer.PlayerScore);
                    return;
                }
            }
        }
    }


问:
How to edit list in C#
I would like to have an edit function in my program. I am creating a phone book wherein I use list in saving data (no database yet). I would like to have an edit function whenever i click an item in the list but I do not know how to do it.

This is my code for adding:

```<code>Person contact = new Person();
private ObservableCollection<Person> person = new ObservableCollection<Person>();
person.Add(new Person()
    {
        Name = contact.Name,
        Contact = contact.Contact,
        ImagePath = contact.ImagePath,
        Gender = contact.Gender
    });
</code>```

I used selection changed when determining the selected item in the list. A help would be greatly appreciated. Thanks!

答:
You should add an ID to your list, it will make your life easier, anyway here's mine from my previous assignment.

```<code>var vPersonID = YourListGoesHere.Where(pID => pID.personID == id).FirstOrDefault()
if (vPersonID !=null)
{
 vPersonID.Name = "ganda mo po";
//etc etc.
}
</code>```

more info here Best way to update an element in a generic List .

Title: How to edit list in C#

Body:
I would like to have an edit function in my program. I am creating a phone book wherein I use list in saving data (no database yet). I would like to have an edit function whenever i click an item in the list but I do not know how to do it.

This is my code for adding:

Person contact = new Person();
private ObservableCollection<Person> person = new ObservableCollection<Person>();
person.Add(new Person()
    {
        Name = contact.Name,
        Contact = contact.Contact,
        ImagePath = contact.ImagePath,
        Gender = contact.Gender
    });

I used selection changed when determining the selected item in the list. A help would be greatly appreciated. Thanks!

Body:
You should add an ID to your list, it will make your life easier, anyway here's mine from my previous assignment.

var vPersonID = YourListGoesHere.Where(pID => pID.personID == id).FirstOrDefault()
if (vPersonID !=null)
{
 vPersonID.Name = "ganda mo po";
//etc etc.
}

more info here Best way to update an element in a generic List .


问:
Laravel 5.1 - Token Mismatch issue with Iframes on Safari Browser Only
I have created few forms in laravel 5.1, now i am using those forms on another site using IFrame. Those forms works in all browsers except Safari. When i try to submit/post data after filling up forms, i get error "CSRF Token Mismatch", I dont know what the issue here, csrf token is also being created and sent. This is only happening in case of safari browser.

Can someone guide me that how i can get rid of this issue??

Steps To Reproduce:

create a form and then use it via IFrame. after form is submitted, CSRF Token Mismatch error is generated.

How to solve this? Please help!

CODE SAMPLE:

```<code><form method="post" action="/step1/{{$voucher->user_id}}" accept-charset="UTF-8">
<input name="_method" type="hidden" value="post">
{!! csrf_field() !!}
<div class="row" style="margin-top:15px; margin-bottom:15px;">
<div class="col-md-4 col-xs-5 hidden">
<input name="voucher_id" type="hidden" value="{{$voucher->id}}" id="voucher_id">

  <input  class="form-control spin text-center  qty1" name="qty" id="qty" type="text" value="1" >
  <input name="r_full_name" type="hidden" value="" id="r_full_name">

</div>

<div class="col-md-3 col-xs-3">
<button type="submit" class="btn btn-theme"><i class="fa fa-shopping-cart" aria-hidden="true"></i> | BUY</button>
</div>
</form>
</code>```

this is sample code... AGAIN all this works perfect in any other browser (FF, Chrome) but when I put this forms into iframe in another site then I get TokenMissmatch error...

答:
This is most likely related to how Safari handles cookies and iframes, please see the answer from this question which quotes what seems like an older version of the Safari Developer FAQ which states

Safari ships with a conservative cookie policy which limits cookie
  writes to only the pages chosen ("navigated to") by the user. This
  default conservative policy may confuse frame based sites that attempt
  to write cookies and fail.

That would explain why you are having trouble with this.

The second answer to that question proposes a solution which can be found here. This is basically the same thing as doing a redirect to the domain that owns the cookies, setting the session and redirecting back, which is another solution which is mentioned here.

Body:
I have created few forms in laravel 5.1, now i am using those forms on another site using IFrame. Those forms works in all browsers except Safari. When i try to submit/post data after filling up forms, i get error "CSRF Token Mismatch", I dont know what the issue here, csrf token is also being created and sent. This is only happening in case of safari browser.

Can someone guide me that how i can get rid of this issue??

Steps To Reproduce:

create a form and then use it via IFrame. after form is submitted, CSRF Token Mismatch error is generated.

How to solve this? Please help!

CODE SAMPLE:

<form method="post" action="/step1/{{$voucher->user_id}}" accept-charset="UTF-8">
<input name="_method" type="hidden" value="post">
{!! csrf_field() !!}

<input name="voucher_id" type="hidden" value="{{$voucher->id}}" id="voucher_id">

  <input  class="form-control spin text-center  qty1" name="qty" id="qty" type="text" value="1" >
  <input name="r_full_name" type="hidden" value="" id="r_full_name">

<button type="submit" class="btn btn-theme"> | BUY</button>

</form>

this is sample code... AGAIN all this works perfect in any other browser (FF, Chrome) but when I put this forms into iframe in another site then I get TokenMissmatch error...


问:
Having problems selecting items from mySQL database
Tables:

```<code>User:
ID
gender
looking_for_gender

User_Status:
User_ID1
User_ID2
Status
</code>```

While this select works, I also want to select users that has no status. In other words I want to select everyone that has no status or != FRIENDS. Somehow AND & OR does not do the trick.

Currently working query:

```<code>SELECT u.* FROM User u
JOIN User_Status us ON u.ID = us.User_ID1
WHERE us.Status != "FRIENDS"
AND us.User_ID2 =4 AND gender ="f"
</code>```

Sample Data User_Status:

User_ID1 ----- User_ID2 ----- Status

---- 1 ---------------- 4 ------------ has_send_request

---- 2 ---------------- 4 ------------ friends

---- 3 ---------------- 4 ------------ friends

Sample Data User:

ID

0

1

2

3

4

5

答:
when you evaluate null u need to use is null, otherwise it will always return false.</p>

```<code>SELECT u.*
FROM User u
INNER JOIN User_Status us
    ON u.ID = us.User_ID1
WHERE (us.STATUS != "FRIENDS" OR us.STATUS IS NULL)
    AND us.User_ID2 = 4
    AND gender = "f"
</code>```

Body:
Tables:

User:
ID
gender
looking_for_gender

User_Status:
User_ID1
User_ID2
Status

While this select works, I also want to select users that has no status. In other words I want to select everyone that has no status or != FRIENDS. Somehow AND & OR does not do the trick.

Currently working query:

SELECT u.* FROM User u
JOIN User_Status us ON u.ID = us.User_ID1
WHERE us.Status != "FRIENDS"
AND us.User_ID2 =4 AND gender ="f"

Sample Data User_Status:

User_ID1 ----- User_ID2 ----- Status

---- 1 ---------------- 4 ------------ has_send_request

---- 2 ---------------- 4 ------------ friends

---- 3 ---------------- 4 ------------ friends

Sample Data User:

ID

0

1

2

3

4

5

Body:
when you evaluate null u need to use is null, otherwise it will always return false.

SELECT u.*
FROM User u
INNER JOIN User_Status us
    ON u.ID = us.User_ID1
WHERE (us.STATUS != "FRIENDS" OR us.STATUS IS NULL)
    AND us.User_ID2 = 4
    AND gender = "f"


问:
webpack error warning in png svg deprecated
I have a very strange error. I got this exact same here mentioned here

Webpack 2: WARNING in .png, .svg, .. DEPRECATED. Configure optipng's optimizationLevel option in it's own options. (optipng.optimizationLevel)

Ii impleted the solution and now my webpack looks like this

https://codepaste.net/8owse4

But now i get this error

```<code>/home/ubuntu/workspace/node_modules/webpack/node_modules/webpack-core/lib/LoadersList.js:60
    throw new Error("Element from loaders list should have one of the fields 'loader' or 'loaders'");
    ^
</code>```

Error: Element from loaders list should have one of the fields 'loader' or 'loaders'

So, I am in kind of loop. I am using webpack 2. I understand I have to reconfigure webpack . But, its kind of loop. Its just not working. Can someone help me out.

答:
As Doodlebot said above, webpack2 now uses module.rules instead of module.loaders but module.loaders still works according to the documentation:

The old loader configuration was superseded by a more powerful rules system, which allows configuration of loaders and more. For compatibility reasons, the old module.loaders syntax is still valid and the old names are parsed. The new naming conventions are easier to understand and are a good reason to upgrade the configuration to using module.rules.

So it's not the problem here. If you choose to use module.loaders, you need to pass an array of objects to it and each of those objects must have a field loader as your error points out:

Error: Element from loaders list should have one of the fields 'loader' or 'loaders'

This is what you have currently:

var webpack = require("webpack");
var path = require("path");
var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
    entry: {
        app: './src/app.js'
    },
    output: {
        filename: 'public/build/bundle.js',
        sourceMapFilename: 'public/build/bundle.map'
    },
    devtool: '#source-map',
    //loaders
    module: {
        loaders: [
  {
    test: /\.jsx?$/,
    exclude: /node_modules/,
    loader: 'babel-loader',
    query: {
        presets: ['stage-0','react','es2015'],
        plugins: ["transform-decorators-legacy","transform-class-properties"]
    }
  },
  {
    test: /\.css$/,
    loaders: [ 'style-loader', 'css-loader' ],
  },
  {
                test: /\.(eot|svg|ttf|woff|woff2)$/,
                loader: 'file?name=public/fonts/[name].[ext]'
            },

            {
    test: /\.(jpe?g|png|gif|svg)$/i,
    use: [
    {
      loader: 'file-loader',
      options: {
        query: {
          name:'assets/[name].[ext]'
        }
      }
    },
    {
      loader: 'image-webpack-loader',
      options: {
        query: {
          mozjpeg: {
            progressive: true,
          },
          gifsicle: {
            interlaced: true,
          },
          optipng: {
            optimizationLevel: 7,
          }
        }
      }
    }]
  },

]
    }
};```
</div>
</div>
</p>

<p>And from that you had spelled the <code>loader</code> field for your css as <code>loaders</code></p>

```loaders: [ 'style-loader', 'css-loader' ]
```

<p>That should be</p>

```loader: ['style-loader', 'css-loader']
```

<p>I also noticed you are mixing syntax. If you use <code>module.loaders</code> then your objects should have <code>test</code> and <code>loader</code>, if you use <code>module.rules</code> then your objects have <code>test</code> and <code>use</code>. Don't mix them. Here are examples:</p>

```module{ loaders: [{test: /\.css$/, loader: [ 'style-loader', 'css-loader' ]}] }

module{ rules: [{test: /\.css$/, use: [ 'style-loader', 'css-loader' ]}] }
```

Your use or loader field can take a string (style-loader!css-loader) or array ([ 'style-loader', 'css-loader' ]) but that shouldn't make you pluralize the field name

Body:
I have a very strange error. I got this exact same here mentioned here

Webpack 2: WARNING in .png, .svg, .. DEPRECATED. Configure optipng's optimizationLevel option in it's own options. (optipng.optimizationLevel)

Ii impleted the solution and now my webpack looks like this

https://codepaste.net/8owse4

But now i get this error

/home/ubuntu/workspace/node_modules/webpack/node_modules/webpack-core/lib/LoadersList.js:60
    throw new Error("Element from loaders list should have one of the fields 'loader' or 'loaders'");
    ^

Error: Element from loaders list should have one of the fields 'loader' or 'loaders'

So, I am in kind of loop. I am using webpack 2. I understand I have to reconfigure webpack . But, its kind of loop. Its just not working. Can someone help me out.

Body:
As Doodlebot said above, webpack2 now uses module.rules instead of module.loaders but module.loaders still works according to the documentation:

The old loader configuration was superseded by a more powerful rules system, which allows configuration of loaders and more. For compatibility reasons, the old module.loaders syntax is still valid and the old names are parsed. The new naming conventions are easier to understand and are a good reason to upgrade the configuration to using module.rules.

So it's not the problem here. If you choose to use module.loaders, you need to pass an array of objects to it and each of those objects must have a field loader as your error points out:

Error: Element from loaders list should have one of the fields 'loader' or 'loaders'

This is what you have currently:

var webpack = require("webpack");
var path = require("path");
var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
    entry: {
        app: './src/app.js'
    },
    output: {
        filename: 'public/build/bundle.js',
        sourceMapFilename: 'public/build/bundle.map'
    },
    devtool: '#source-map',
    //loaders
    module: {
        loaders: [
  {
    test: /\.jsx?$/,
    exclude: /node_modules/,
    loader: 'babel-loader',
    query: {
        presets: ['stage-0','react','es2015'],
        plugins: ["transform-decorators-legacy","transform-class-properties"]
    }
  },
  {
    test: /\.css$/,
    loaders: [ 'style-loader', 'css-loader' ],
  },
  {
                test: /\.(eot|svg|ttf|woff|woff2)$/,
                loader: 'file?name=public/fonts/[name].[ext]'
            },

            {
    test: /\.(jpe?g|png|gif|svg)$/i,
    use: [
    {
      loader: 'file-loader',
      options: {
        query: {
          name:'assets/[name].[ext]'
        }
      }
    },
    {
      loader: 'image-webpack-loader',
      options: {
        query: {
          mozjpeg: {
            progressive: true,
          },
          gifsicle: {
            interlaced: true,
          },
          optipng: {
            optimizationLevel: 7,
          }
        }
      }
    }]
  },

]
    }
};

And from that you had spelled the loader field for your css as loaders

loaders: [ 'style-loader', 'css-loader' ]

That should be

loader: ['style-loader', 'css-loader']

I also noticed you are mixing syntax. If you use module.loaders then your objects should have test and loader, if you use module.rules then your objects have test and use. Don't mix them. Here are examples:

module{ loaders: [{test: /\.css$/, loader: [ 'style-loader', 'css-loader' ]}] }

module{ rules: [{test: /\.css$/, use: [ 'style-loader', 'css-loader' ]}] }

Your use or loader field can take a string (style-loader!css-loader) or array ([ 'style-loader', 'css-loader' ]) but that shouldn't make you pluralize the field name


问:
Scala How to transform Seq[((A, B, C, D), Seq[(E, F, G)])] to Seq[(A, B, C, D, Seq[(E, F, G)])]?
I'd like to transform the following sequence.

```<code>Seq[((A, B, C, D), Seq[(E, F, G)])]
</code>```

to

```<code>Seq[(A, B, C, D, Seq[(E, F, G)])]
</code>```

Could anyone kindly suggest a solution?

Thanks!

答:
Simply:</p>

```<code>val original: Seq[((A, B, C, D), Seq[(E, F, G)])] = ...
val res: Seq[(A, B, C, D, Seq[(E, F, G)])] =
  original.map { case ((a, b, c, d), seq) => (a, b, c, d, seq) }
</code>```

Body:
I'd like to transform the following sequence.

Seq[((A, B, C, D), Seq[(E, F, G)])]

to

Seq[(A, B, C, D, Seq[(E, F, G)])]

Could anyone kindly suggest a solution?

Thanks!

Body:
Simply:

val original: Seq[((A, B, C, D), Seq[(E, F, G)])] = ...
val res: Seq[(A, B, C, D, Seq[(E, F, G)])] =
  original.map { case ((a, b, c, d), seq) => (a, b, c, d, seq) }


问:
Using pointers in Objective C for NSMutableArray objects
When retrieving objects from an NSMutableArray in cocoa-touch is the below code ok? Should I be allocating([alloc]) new Page objects each time or is just pointing to it alright? Do I need to do anything to the Page *pageObj after, such as set it to nil?

```<code>const char *sql = "insert into Page(Book_ID, Page_Num, Page_Text) Values(?, ?, ?)";
for (i = 0; i < ([[self pagesArray] count] - 1); i++) {
    if(addStmt == nil) {
        if(sqlite3_prepare_v2(database, sql, -1, &addStmt, NULL) != SQLITE_OK) {
            NSAssert1(0, @"Error while creating add statement. '%s'", sqlite3_errmsg(database));
        }
    }
    Page *pageObj = [[self pagesArray] objectAtIndex:i];
    if(pageObj.isNew) {
        sqlite3_bind_int(addStmt, 1, self.book_ID);
        sqlite3_bind_int(addStmt, 2, pageObj.page_Number);
        sqlite3_bind_text(addStmt, 3, [[pageObj page_Text] UTF8String], -1, SQLITE_TRANSIENT);
        if(SQLITE_DONE != sqlite3_step(addStmt)) {
            NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database));
        }
        NSLog(@"Inserted Page: %i into DB. Page text: %@", pageObj.page_Number, pageObj.page_Text);
    }
    //Reset the add statement.
    sqlite3_reset(addStmt);
}
</code>```

Thanks. I also understand this should probably be in a transaction but I didn't quite get that working just yet.

答:
Aside from the previously mentioned count error, it looks good.

As far as transactions go, I highly recommend wrapping this write loop in one.  It will greatly increase your write performance and I found that it helps with memory usage as well.  I use the following class method to begin a transaction:

```<code>+ (BOOL)beginTransactionWithDatabase:(sqlite3 *)database;
{
    const char *sql1 = "BEGIN EXCLUSIVE TRANSACTION";
    sqlite3_stmt *begin_statement;
    if (sqlite3_prepare_v2(database, sql1, -1, &begin_statement, NULL) != SQLITE_OK)
    {
        return NO;
    }
    if (sqlite3_step(begin_statement) != SQLITE_DONE)
    {
        return NO;
    }
    sqlite3_finalize(begin_statement);
    return YES;
}
</code>```

and this one to end a transaction:

```<code>+ (BOOL)endTransactionWithDatabase:(sqlite3 *)database;
{
    const char *sql2 = "COMMIT TRANSACTION";
    sqlite3_stmt *commit_statement;
    if (sqlite3_prepare_v2(database, sql2, -1, &commit_statement, NULL) != SQLITE_OK)
    {
        return NO;
    }
    if (sqlite3_step(commit_statement) != SQLITE_DONE)
    {
        return NO;
    }
    sqlite3_finalize(commit_statement);
    return YES;
}
</code>```

I should probably store the SQL statements for later reuse, but these transaction statements are called much less frequently than my other queries.

OwnerDisplayName: Sean

ContentLicense: CC BY-SA 2.5

Body:
When retrieving objects from an NSMutableArray in cocoa-touch is the below code ok? Should I be allocating([alloc]) new Page objects each time or is just pointing to it alright? Do I need to do anything to the Page *pageObj after, such as set it to nil?

const char *sql = "insert into Page(Book_ID, Page_Num, Page_Text) Values(?, ?, ?)";
for (i = 0; i < ([[self pagesArray] count] - 1); i++) {
    if(addStmt == nil) {
        if(sqlite3_prepare_v2(database, sql, -1, &addStmt, NULL) != SQLITE_OK) {
            NSAssert1(0, @"Error while creating add statement. '%s'", sqlite3_errmsg(database));
        }
    }
    Page *pageObj = [[self pagesArray] objectAtIndex:i];
    if(pageObj.isNew) {
        sqlite3_bind_int(addStmt, 1, self.book_ID);
        sqlite3_bind_int(addStmt, 2, pageObj.page_Number);
        sqlite3_bind_text(addStmt, 3, [[pageObj page_Text] UTF8String], -1, SQLITE_TRANSIENT);
        if(SQLITE_DONE != sqlite3_step(addStmt)) {
            NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database));
        }
        NSLog(@"Inserted Page: %i into DB. Page text: %@", pageObj.page_Number, pageObj.page_Text);
    }
    //Reset the add statement.
    sqlite3_reset(addStmt);
}

Thanks. I also understand this should probably be in a transaction but I didn't quite get that working just yet.

LastEditorDisplayName: Chris Hanson

Body:
Aside from the previously mentioned count error, it looks good.

As far as transactions go, I highly recommend wrapping this write loop in one.  It will greatly increase your write performance and I found that it helps with memory usage as well.  I use the following class method to begin a transaction:

+ (BOOL)beginTransactionWithDatabase:(sqlite3 *)database;
{
    const char *sql1 = "BEGIN EXCLUSIVE TRANSACTION";
    sqlite3_stmt *begin_statement;
    if (sqlite3_prepare_v2(database, sql1, -1, &begin_statement, NULL) != SQLITE_OK)
    {
        return NO;
    }
    if (sqlite3_step(begin_statement) != SQLITE_DONE)
    {
        return NO;
    }
    sqlite3_finalize(begin_statement);
    return YES;
}

and this one to end a transaction:

+ (BOOL)endTransactionWithDatabase:(sqlite3 *)database;
{
    const char *sql2 = "COMMIT TRANSACTION";
    sqlite3_stmt *commit_statement;
    if (sqlite3_prepare_v2(database, sql2, -1, &commit_statement, NULL) != SQLITE_OK)
    {
        return NO;
    }
    if (sqlite3_step(commit_statement) != SQLITE_DONE)
    {
        return NO;
    }
    sqlite3_finalize(commit_statement);
    return YES;
}

I should probably store the SQL statements for later reuse, but these transaction statements are called much less frequently than my other queries.

OwnerDisplayName: Brad Larson


问:
WCF WebService using POST. Namespace error?
I have a RESTful service with the interface below, using POST.
When I try to go to the service URL I get a server error saying something like there is a namespace conflict, but I don't think that is the case. Here is a shortened version of the error message.

```<code>System.InvalidOperationException: DataContract for type 'xyz.EntityList`1[zxc]' cannot be added to DataContractSet since type 'xyz.EntityList`1[zxc]' with the same data contract name 'EntityList' in namespace 'Bugg' is already present and the contracts are not equivalent.
</code>```

The rest of the error is given below.

```<code>namespace MyComp.RestApi.Interfaces
{
    [ServiceContract]
    public interface ISiteService
    {
        [OperationContract]
        [WebInvoke(Method = "POST", UriTemplate = "Sites/{customerId}/Organizations/",
            BodyStyle = WebMessageBodyStyle.Bare,
            RequestFormat = WebMessageFormat.Xml,
            ResponseFormat = WebMessageFormat.Xml)]
        EntityList<Organization> GetOrganizationsById(string customerId, string ids);
    }
}
</code>```

with this service implementation:

```<code>public SiteServiceClass{
    public EntityList<Organization> GetOrganizationsById(string customerId, string ids)
    {
        Authenticate();
        //Div Code
        var hierarchyCollection = GetHierarchies(customerId);
        var organizations = new EntityList<Organization>();
        foreach (Organization hierarchy in hierarchyCollection)
        {
            organizations.EntityArray.Add(hierarchy);
        }
        organizations.Total = organizations.EntityArray.Count;
        return organizations;
    }
}

using System.Collections.Generic;
using System.Runtime.Serialization;

namespace MyComp.RestApi.Entities.Utils
{
    /// <summary>
    /// Generic entity collection with sorting, paging and filtering.
    /// </summary>
    /// <typeparam name="T">Entity type.</typeparam>
    [DataContract(Name="EntityList")]
    public class EntityList<T>
    {
        /// <summary>
        /// Initializes a new instance of the class.
        /// </summary>
        public EntityList()
        {
            EntityArray = new List<T>();
        }

        /// <summary>
        /// Entity list.
        /// </summary>
        [DataMember]
        public List<T> EntityArray { get; set; }

        /// <summary>
        /// Totle count.
        /// </summary>
        [DataMember]
        public int Total { get; set; }

        /// <summary>
        /// Page number.
        /// </summary>
        [DataMember]
        public int CurrentPageIndex { get; set; }

        /// <summary>
        /// Page size.
        /// </summary>
        [DataMember]
        public int PageSize { get; set; }
    }
}
</code>```

Trying to go to the service URL I get this exception:

```<code>An ExceptionDetail, likely created by IncludeExceptionDetailInFaults=true, whose value is:
System.InvalidOperationException: An exception was thrown in a call to a WSDL export extension: System.ServiceModel.Description.DataContractSerializerOperationBehavior
 contract: http://tempuri.org/:ISiteService ----> System.InvalidOperationException: DataContract for type 'MyComp.RestApi.Entities.Utils.EntityList`1[[MyComp.RestApi.Entities.Organization, MyComp.RestApi.Entities, Version=1.0.0.0, Culture=neutral, PublicKeyToken=85d7c8ed1eb8be9b]]' cannot be added to DataContractSet since type 'MyComp.RestApi.Entities.Utils.EntityList`1[[MyComp.RestApi.Entities.Site, MyComp.RestApi.Entities, Version=1.0.0.0, Culture=neutral, PublicKeyToken=85d7c8ed1eb8be9b]]' with the same data contract name 'EntityList' in namespace 'Bugg' is already present and the contracts are not equivalent.
   at System.Runtime.Serialization.DataContractSet.Add(XmlQualifiedName name, DataContract dataContract)
   at System.Runtime.Serialization.DataContractSet.Add(Type type)
   at System.Runtime.Serialization.XsdDataContractExporter.Export(Type type)
   at System.ServiceModel.Description.MessageContractExporter.ExportType(Type type, String partName, String operationName, XmlSchemaType& xsdType)
   at System.ServiceModel.Description.DataContractSerializerMessageContractExporter.ExportBody(Int32 messageIndex, Object state)
   at System.ServiceModel.Description.MessageContractExporter.ExportMessage(Int32 messageIndex, Object state)
   at System.ServiceModel.Description.MessageContractExporter.ExportMessageContract()
   at System.ServiceModel.Description.DataContractSerializerOperationBehavior.System.ServiceModel.Description.IWsdlExportExtension.ExportContract(WsdlExporter exporter, WsdlContractConversionContext contractContext)
   at System.ServiceModel.Description.WsdlExporter.CallExtension(WsdlContractConversionContext contractContext, IWsdlExportExtension extension)
   --- End of inner ExceptionDetail stack trace ---
   at System.ServiceModel.Description.WsdlExporter.CallExtension(WsdlContractConversionContext contractContext, IWsdlExportExtension extension)
   at System.ServiceModel.Description.WsdlExporter.CallExportContract(WsdlContractConversionContext contractContext)
   at System.ServiceModel.Description.WsdlExporter.ExportContract(ContractDescription contract)
   at System.ServiceModel.Description.WsdlExporter.ExportEndpoint(ServiceEndpoint endpoint, XmlQualifiedName wsdlServiceQName)
   at System.ServiceModel.Description.WsdlExporter.ExportEndpoints(IEnumerable`1 endpoints, XmlQualifiedName wsdlServiceQName)
   at System.ServiceModel.Description.ServiceMetadataBehavior.MetadataExtensionInitializer.GenerateMetadata()
   at System.ServiceModel.Description.ServiceMetadataExtension.EnsureInitialized()
   at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.InitializationData.InitializeFrom(ServiceMetadataExtension extension)
   at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.GetInitData()
   at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.TryHandleDocumentationRequest(Message httpGetRequest, String[] queries, Message& replyMessage)
   at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.ProcessHttpRequest(Message httpGetRequest)
   at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.Get(Message message)
   at SyncInvokeGet(Object , Object[] , Object[] )
   at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
   at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
   at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
   at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc)
   at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc& rpc)
   at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc)
   at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc& rpc)
   at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)
</code>```

Excerpts from web config:

```<code><services>
<service behaviorConfiguration="MyComp.RestApi.Services.SiteServiceBehavior"
                name="MyComp.RestApi.Services.SiteService">
                <endpoint behaviorConfiguration="webHttp" binding="webHttpBinding"
                    contract="MyComp.RestApi.Interfaces.ISiteService" />
                <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
            </service>
</services>
 <behaviors>
            <endpointBehaviors>
                <behavior name="webHttp">
                    <webHttp />
                </behavior>
            </endpointBehaviors>
            <serviceBehaviors>
<behavior name="MyComp.RestApi.Services.SiteServiceBehavior">
                  <serviceMetadata httpGetEnabled="true" />
                    <serviceDebug includeExceptionDetailInFaults="true" />
                </behavior>

</serviceBehaviors>
</behaviors>
</code>```

答:
Remove the name from DataContract attribute. You are using generic data contract but you are giving it static name. It is not possible because the contract name for each generic type argument has to be different (auto-generated). That is the reason for your exception.

Also remove mex endpoint and service metadata behavior from your configuration file because it is for SOAP service, not for REST services.

Body:
I have a RESTful service with the interface below, using POST.
When I try to go to the service URL I get a server error saying something like there is a namespace conflict, but I don't think that is the case. Here is a shortened version of the error message.

System.InvalidOperationException: DataContract for type 'xyz.EntityList`1[zxc]' cannot be added to DataContractSet since type 'xyz.EntityList`1[zxc]' with the same data contract name 'EntityList' in namespace 'Bugg' is already present and the contracts are not equivalent.

The rest of the error is given below.

namespace MyComp.RestApi.Interfaces
{
    [ServiceContract]
    public interface ISiteService
    {
        [OperationContract]
        [WebInvoke(Method = "POST", UriTemplate = "Sites/{customerId}/Organizations/",
            BodyStyle = WebMessageBodyStyle.Bare,
            RequestFormat = WebMessageFormat.Xml,
            ResponseFormat = WebMessageFormat.Xml)]
        EntityList<Organization> GetOrganizationsById(string customerId, string ids);
    }
}

with this service implementation:

public SiteServiceClass{
    public EntityList<Organization> GetOrganizationsById(string customerId, string ids)
    {
        Authenticate();
        //Div Code
        var hierarchyCollection = GetHierarchies(customerId);
        var organizations = new EntityList<Organization>();
        foreach (Organization hierarchy in hierarchyCollection)
        {
            organizations.EntityArray.Add(hierarchy);
        }
        organizations.Total = organizations.EntityArray.Count;
        return organizations;
    }
}

using System.Collections.Generic;
using System.Runtime.Serialization;

namespace MyComp.RestApi.Entities.Utils
{
    ///
    /// Generic entity collection with sorting, paging and filtering.
    ///
    /// <typeparam name="T">Entity type.</typeparam>
    [DataContract(Name="EntityList")]
    public class EntityList<T>
    {
        ///
        /// Initializes a new instance of the class.
        ///
        public EntityList()
        {
            EntityArray = new List<T>();
        }

        ///
        /// Entity list.
        ///
        [DataMember]
        public List<T> EntityArray { get; set; }

        ///
        /// Totle count.
        ///
        [DataMember]
        public int Total { get; set; }

        ///
        /// Page number.
        ///
        [DataMember]
        public int CurrentPageIndex { get; set; }

        ///
        /// Page size.
        ///
        [DataMember]
        public int PageSize { get; set; }
    }
}

Trying to go to the service URL I get this exception:

An ExceptionDetail, likely created by IncludeExceptionDetailInFaults=true, whose value is:
System.InvalidOperationException: An exception was thrown in a call to a WSDL export extension: System.ServiceModel.Description.DataContractSerializerOperationBehavior
 contract: http://tempuri.org/:ISiteService ----> System.InvalidOperationException: DataContract for type 'MyComp.RestApi.Entities.Utils.EntityList`1[[MyComp.RestApi.Entities.Organization, MyComp.RestApi.Entities, Version=1.0.0.0, Culture=neutral, PublicKeyToken=85d7c8ed1eb8be9b]]' cannot be added to DataContractSet since type 'MyComp.RestApi.Entities.Utils.EntityList`1[[MyComp.RestApi.Entities.Site, MyComp.RestApi.Entities, Version=1.0.0.0, Culture=neutral, PublicKeyToken=85d7c8ed1eb8be9b]]' with the same data contract name 'EntityList' in namespace 'Bugg' is already present and the contracts are not equivalent.
   at System.Runtime.Serialization.DataContractSet.Add(XmlQualifiedName name, DataContract dataContract)
   at System.Runtime.Serialization.DataContractSet.Add(Type type)
   at System.Runtime.Serialization.XsdDataContractExporter.Export(Type type)
   at System.ServiceModel.Description.MessageContractExporter.ExportType(Type type, String partName, String operationName, XmlSchemaType& xsdType)
   at System.ServiceModel.Description.DataContractSerializerMessageContractExporter.ExportBody(Int32 messageIndex, Object state)
   at System.ServiceModel.Description.MessageContractExporter.ExportMessage(Int32 messageIndex, Object state)
   at System.ServiceModel.Description.MessageContractExporter.ExportMessageContract()
   at System.ServiceModel.Description.DataContractSerializerOperationBehavior.System.ServiceModel.Description.IWsdlExportExtension.ExportContract(WsdlExporter exporter, WsdlContractConversionContext contractContext)
   at System.ServiceModel.Description.WsdlExporter.CallExtension(WsdlContractConversionContext contractContext, IWsdlExportExtension extension)
   --- End of inner ExceptionDetail stack trace ---
   at System.ServiceModel.Description.WsdlExporter.CallExtension(WsdlContractConversionContext contractContext, IWsdlExportExtension extension)
   at System.ServiceModel.Description.WsdlExporter.CallExportContract(WsdlContractConversionContext contractContext)
   at System.ServiceModel.Description.WsdlExporter.ExportContract(ContractDescription contract)
   at System.ServiceModel.Description.WsdlExporter.ExportEndpoint(ServiceEndpoint endpoint, XmlQualifiedName wsdlServiceQName)
   at System.ServiceModel.Description.WsdlExporter.ExportEndpoints(IEnumerable`1 endpoints, XmlQualifiedName wsdlServiceQName)
   at System.ServiceModel.Description.ServiceMetadataBehavior.MetadataExtensionInitializer.GenerateMetadata()
   at System.ServiceModel.Description.ServiceMetadataExtension.EnsureInitialized()
   at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.InitializationData.InitializeFrom(ServiceMetadataExtension extension)
   at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.GetInitData()
   at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.TryHandleDocumentationRequest(Message httpGetRequest, String[] queries, Message& replyMessage)
   at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.ProcessHttpRequest(Message httpGetRequest)
   at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.Get(Message message)
   at SyncInvokeGet(Object , Object[] , Object[] )
   at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
   at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
   at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
   at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc)
   at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc& rpc)
   at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc)
   at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc& rpc)
   at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)

Excerpts from web config:

<services>
<service behaviorConfiguration="MyComp.RestApi.Services.SiteServiceBehavior"
                name="MyComp.RestApi.Services.SiteService">
                <endpoint behaviorConfiguration="webHttp" binding="webHttpBinding"
                    contract="MyComp.RestApi.Interfaces.ISiteService" />
                <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
            </service>
</services>
 <behaviors>
            <endpointBehaviors>
                <behavior name="webHttp">
                    <webHttp />
                </behavior>
            </endpointBehaviors>
            <serviceBehaviors>
<behavior name="MyComp.RestApi.Services.SiteServiceBehavior">
                  <serviceMetadata httpGetEnabled="true" />
                    <serviceDebug includeExceptionDetailInFaults="true" />
                </behavior>

</serviceBehaviors>
</behaviors>