问:
Import xlsx file into Python using xlrd
Trying to import a .xlsx file into Python. I've google and google. I had this code written and working for .csv but it needs to be for .xlsx files. So I basically pieced together and did a hail mary in hopes that it would work. Any and all help is greatly appreciated!

** Added my whole code and a snippet of the data file. I need it to import .xlsx and execute the data.

```<code>import xlrd

workbook = xlrd.open_workbook('GAT_US_PartReview_2017-06-23.xlsx')

worksheet = workbook.get_sheet(0, update_pos=True)

header = []
report_card = []

# Count Stmnts for Required Data
valid_count = 0
app_req_count = 0
intr_req_count = 0
oe_intr_req_count = 0
part_img_req_count = 0
upc_req_count = 0
unspsc_req_count = 0
msds_req_count = 0

# Count Stmts for Missing Data
missing_app_count = 0
missing_intr_count = 0
missing_oe_intr_count = 0
missing_mpcc_count = 0
missing_attr_values_count = 0
missing_part_img_count = 0
missing_upc_count = 0
missing_warr_text_count = 0
missing_warr_pdf_count = 0
missing_unspsc_count = 0
missing_msds_count = 0

for row_num, row in enumerate(worksheet):
    if row_num <= 4:
        #  print(row)  # Print out the header
        header.append([row[0], row[2]])
    else:
        hq_line, part_no, part_class, appl_req, appl_count, intr_req,
        intr_count, oe_intr_req, has_oe_intr, has_attr_editor,
        has_attr_values, part_img_req, has_part_img, has_mpcc, warr_req,
        has_warr_txt, has_warr_pdf, msds_req, has_msds, upc_req, has_upc,
        has_unspsc, attr_count, attrval_count, valid_part = row

    if valid_part == 'YES':
        valid_count += 1

        # Required Parts Count
        if appl_req == 'YES':
            app_req_count += 1
        if intr_req == 'YES':
            intr_req_count += 1
        if oe_intr_req == 'YES':
            oe_intr_req_count += 1
        if part_img_req == 'YES':
            part_img_req_count += 1
        if upc_req == 'YES':
            upc_req_count += 1
        if msds_req == 'YES':
            msds_req_count += 1

        # Missing Data Counts
        if appl_req == 'YES' and appl_count == '0':
            missing_app_count += 1
        if intr_req == 'YES' and intr_count == '0':
            missing_intr_count += 1
        if oe_intr_req == 'YES' and has_oe_intr == '0':
             missing_oe_intr_count += 1
        if has_mpcc == 'NO':
             missing_mpcc_count += 1
        if has_attr_values == 'NO':
            missing_attr_values_count += 1
        if has_part_img == 'NO':
            missing_part_img_count += 1
        if upc_req == 'YES' and has_upc == '0':
            missing_upc_count += 1
        if warr_req == 'YES' and has_warr_txt == 'NO':
            missing_warr_text_count += 1
        if warr_req == 'YES' and has_warr_pdf == 'NO':
            missing_warr_pdf_count += 1
        if has_unspsc == 'NO':
            missing_unspsc_count += 1
        if msds_req == 'YES' and has_msds == 'NO':
            missing_msds_count += 1

# Statements for Required Counts
valid_parts = ('Number of Valid Parts: ', '{:,}'.format(valid_count))
application_required = ('Application Records Required: ',
'{:,}'.format(app_req_count))
interchange_required = ('Interchange Records Required: ',
'{:,}'.format(intr_req_count))
oe_interchange_required = ('OE Interchange Records Required: ',
'{:,}'.format(oe_intr_req_count))
mpcc = ('MPCC Required: ', '{:,}'.format(valid_count))  # Every valid part
requires a MPCC
attributes = ('Attributes Required: ', '{:,}'.format(valid_count))  # Every
valid part requires attributes
image_required = ('Image Required: ', '{:,}'.format(part_img_req_count))
upc = ('UPC Requited: ', '{:,}'.format(upc_req_count))
warranties = ('Warranty Text/PDF Required: ', '{:,}'.format(valid_count))  #
Require warranty text/pdf on all parts
unspsc = ('UNSPSC Code Required: ', '{:,}'.format(valid_count))  # Require
UNSPSC Codes for all parts
msds = ('MSDS Required: ', '{:,}'.format(msds_req_count))

# Statements for Missing Counts
missing_applications = ('Missing Applications: ',
'{:,}'.format(missing_app_count))
missing_interchange = ('Missing Interchange: ',
'{:,}'.format(missing_intr_count))
missing_oe_interchange = ('Missing OE Interchange: ',
'{:,}'.format(missing_oe_intr_count))
missing_mpcc = ('Missing MPCC: ', '{:,}'.format(missing_mpcc_count))
missing_attributes = ('Missing Attributes: ',
'{:,}'.format(missing_attr_values_count))
missing_image = ('Missing Image: ', '{:,}'.format(missing_part_img_count))
missing_UPC = ('Missing UPC: ', '{:,}'.format(missing_upc_count))
missing_warranty_text = ('Missing Warranty Text: ',
'{:,}'.format(missing_warr_text_count))
missing_warranty_pdf = ('Missing Warranty PDF: ',
'{:,}'.format(missing_warr_pdf_count))
missing_unspsc = ('Missing UNSPSC Code: ',
'{:,}'.format(missing_unspsc_count))
missing_msds = ('Missing MSDS: ', '{:,}'.format(missing_msds_count))

# CSV Output
report_card.append(valid_parts)
report_card.append(application_required)
report_card.append(interchange_required)
report_card.append(oe_interchange_required)
report_card.append(mpcc)
report_card.append(attributes)
report_card.append(image_required)
report_card.append(upc)
report_card.append(warranties)
report_card.append(unspsc)
report_card.append(msds)
report_card.append(missing_applications)
report_card.append(missing_interchange)
report_card.append(missing_oe_interchange)
report_card.append(missing_mpcc)
report_card.append(missing_attributes)
report_card.append(missing_image)
report_card.append(missing_UPC)
report_card.append(missing_warranty_text)
report_card.append(missing_warranty_pdf)
report_card.append(missing_unspsc)
report_card.append(missing_msds)

for row in header:
    print(row)

for x in report_card:
    print(x)

with open('Report_Card.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerows(header)
    writer.writerows(report_card)
</code>```

CSV file:

```<code>Supplier Line:,,Gates Rubber - Denver (GAT),,,,,,,,,,,,,,,,,,,,,,
Summary:,,Parts HQ Abbr,,,,,,,,,,,,,,,,,,,,,,
ACCT No:,,40013586,,,,,,,,,,,,,,,,,,,,,,
RecCount:,,10221,,,,,,,,,,,,,,,,,,,,,,
Applicable Date:,,"June 14, 2017 (Wednesday)",,,,,,,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,,,,,,,,,
HQ Line,Part No,Part Class,Appl Req,Appl Count ,Intr Req,Intr Count ,OE Intr Req,Has OE Intr,Has Attr Editor, Has Attr Values,Part IMG Req,Has Part IMG,Has MPCC,Warr Req,Has Warr TXT,Has Warr PDF,MSDS Req,Has MSDS,UPC Req,Has UPC,Has UNSPSC,Attr Count ,AttrVal Count ,Valid Part
GAT,'27210',S,NO,0,YES,1,YES,NO,YES,YES,YES,YES,YES,YES,YES,YES,NO,NO,YES,YES,YES,30,13,YES
GAT,'27211',O,NO,0,YES,1,YES,NO,YES,YES,YES,YES,YES,YES,YES,YES,NO,NO,YES,YES,YES,30,14,YES
GAT,'27212',S,NO,0,YES,1,YES,NO,YES,YES,YES,YES,YES,YES,YES,YES,NO,NO,YES,YES,YES,30,13,YES
GAT,'27213',S,NO,0,YES,1,YES,NO,YES,YES,YES,YES,YES,YES,YES,YES,NO,NO,YES,YES,YES,30,13,YES
GAT,'27220',S,NO,0,YES,2,YES,NO,YES,YES,YES,YES,YES,YES,YES,YES,NO,NO,YES,YES,YES,35,20,YES
GAT,'27221',S,NO,0,YES,2,YES,NO,YES,YES,YES,YES,YES,YES,YES,YES,NO,NO,YES,YES,YES,35,20,YES
</code>```

答:
This script allows you to transform an excel data table to a list of dictionaries:

```<code>import xlrd

workbook = xlrd.open_workbook('GAT_US_PartReview_2017-06-23.xlsx', on_demand = True)
worksheet = workbook.sheet_by_index(0)
first_row = [] # The row where we stock the name of the column
for col in range(worksheet.ncols):
    first_row.append( worksheet.cell_value(0,col) )
# transform the workbook to a list of dictionaries
data =[]
for row in range(1, worksheet.nrows):
    elm = {}
    for col in range(worksheet.ncols):
        elm[first_row[col]]=worksheet.cell_value(row,col)
    data.append(elm)
print data
</code>```

You can also use Pandas

```<code>from pandas import *
xls = ExcelFile('GAT_US_PartReview_2017-06-23.xlsx')
df = xls.parse(xls.sheet_names[0])
print df.to_dict()
</code>```

Title: Import xlsx file into Python using xlrd

Body:
Trying to import a .xlsx file into Python. I've google and google. I had this code written and working for .csv but it needs to be for .xlsx files. So I basically pieced together and did a hail mary in hopes that it would work. Any and all help is greatly appreciated!

** Added my whole code and a snippet of the data file. I need it to import .xlsx and execute the data.

import xlrd

workbook = xlrd.open_workbook('GAT_US_PartReview_2017-06-23.xlsx')

worksheet = workbook.get_sheet(0, update_pos=True)

header = []
report_card = []

# Count Stmnts for Required Data
valid_count = 0
app_req_count = 0
intr_req_count = 0
oe_intr_req_count = 0
part_img_req_count = 0
upc_req_count = 0
unspsc_req_count = 0
msds_req_count = 0

# Count Stmts for Missing Data
missing_app_count = 0
missing_intr_count = 0
missing_oe_intr_count = 0
missing_mpcc_count = 0
missing_attr_values_count = 0
missing_part_img_count = 0
missing_upc_count = 0
missing_warr_text_count = 0
missing_warr_pdf_count = 0
missing_unspsc_count = 0
missing_msds_count = 0

for row_num, row in enumerate(worksheet):
    if row_num <= 4:
        #  print(row)  # Print out the header
        header.append([row[0], row[2]])
    else:
        hq_line, part_no, part_class, appl_req, appl_count, intr_req,
        intr_count, oe_intr_req, has_oe_intr, has_attr_editor,
        has_attr_values, part_img_req, has_part_img, has_mpcc, warr_req,
        has_warr_txt, has_warr_pdf, msds_req, has_msds, upc_req, has_upc,
        has_unspsc, attr_count, attrval_count, valid_part = row

    if valid_part == 'YES':
        valid_count += 1

        # Required Parts Count
        if appl_req == 'YES':
            app_req_count += 1
        if intr_req == 'YES':
            intr_req_count += 1
        if oe_intr_req == 'YES':
            oe_intr_req_count += 1
        if part_img_req == 'YES':
            part_img_req_count += 1
        if upc_req == 'YES':
            upc_req_count += 1
        if msds_req == 'YES':
            msds_req_count += 1

        # Missing Data Counts
        if appl_req == 'YES' and appl_count == '0':
            missing_app_count += 1
        if intr_req == 'YES' and intr_count == '0':
            missing_intr_count += 1
        if oe_intr_req == 'YES' and has_oe_intr == '0':
             missing_oe_intr_count += 1
        if has_mpcc == 'NO':
             missing_mpcc_count += 1
        if has_attr_values == 'NO':
            missing_attr_values_count += 1
        if has_part_img == 'NO':
            missing_part_img_count += 1
        if upc_req == 'YES' and has_upc == '0':
            missing_upc_count += 1
        if warr_req == 'YES' and has_warr_txt == 'NO':
            missing_warr_text_count += 1
        if warr_req == 'YES' and has_warr_pdf == 'NO':
            missing_warr_pdf_count += 1
        if has_unspsc == 'NO':
            missing_unspsc_count += 1
        if msds_req == 'YES' and has_msds == 'NO':
            missing_msds_count += 1

# Statements for Required Counts
valid_parts = ('Number of Valid Parts: ', '{:,}'.format(valid_count))
application_required = ('Application Records Required: ',
'{:,}'.format(app_req_count))
interchange_required = ('Interchange Records Required: ',
'{:,}'.format(intr_req_count))
oe_interchange_required = ('OE Interchange Records Required: ',
'{:,}'.format(oe_intr_req_count))
mpcc = ('MPCC Required: ', '{:,}'.format(valid_count))  # Every valid part
requires a MPCC
attributes = ('Attributes Required: ', '{:,}'.format(valid_count))  # Every
valid part requires attributes
image_required = ('Image Required: ', '{:,}'.format(part_img_req_count))
upc = ('UPC Requited: ', '{:,}'.format(upc_req_count))
warranties = ('Warranty Text/PDF Required: ', '{:,}'.format(valid_count))  #
Require warranty text/pdf on all parts
unspsc = ('UNSPSC Code Required: ', '{:,}'.format(valid_count))  # Require
UNSPSC Codes for all parts
msds = ('MSDS Required: ', '{:,}'.format(msds_req_count))

# Statements for Missing Counts
missing_applications = ('Missing Applications: ',
'{:,}'.format(missing_app_count))
missing_interchange = ('Missing Interchange: ',
'{:,}'.format(missing_intr_count))
missing_oe_interchange = ('Missing OE Interchange: ',
'{:,}'.format(missing_oe_intr_count))
missing_mpcc = ('Missing MPCC: ', '{:,}'.format(missing_mpcc_count))
missing_attributes = ('Missing Attributes: ',
'{:,}'.format(missing_attr_values_count))
missing_image = ('Missing Image: ', '{:,}'.format(missing_part_img_count))
missing_UPC = ('Missing UPC: ', '{:,}'.format(missing_upc_count))
missing_warranty_text = ('Missing Warranty Text: ',
'{:,}'.format(missing_warr_text_count))
missing_warranty_pdf = ('Missing Warranty PDF: ',
'{:,}'.format(missing_warr_pdf_count))
missing_unspsc = ('Missing UNSPSC Code: ',
'{:,}'.format(missing_unspsc_count))
missing_msds = ('Missing MSDS: ', '{:,}'.format(missing_msds_count))

# CSV Output
report_card.append(valid_parts)
report_card.append(application_required)
report_card.append(interchange_required)
report_card.append(oe_interchange_required)
report_card.append(mpcc)
report_card.append(attributes)
report_card.append(image_required)
report_card.append(upc)
report_card.append(warranties)
report_card.append(unspsc)
report_card.append(msds)
report_card.append(missing_applications)
report_card.append(missing_interchange)
report_card.append(missing_oe_interchange)
report_card.append(missing_mpcc)
report_card.append(missing_attributes)
report_card.append(missing_image)
report_card.append(missing_UPC)
report_card.append(missing_warranty_text)
report_card.append(missing_warranty_pdf)
report_card.append(missing_unspsc)
report_card.append(missing_msds)

for row in header:
    print(row)

for x in report_card:
    print(x)

with open('Report_Card.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerows(header)
    writer.writerows(report_card)

CSV file:

Supplier Line:,,Gates Rubber - Denver (GAT),,,,,,,,,,,,,,,,,,,,,,
Summary:,,Parts HQ Abbr,,,,,,,,,,,,,,,,,,,,,,
ACCT No:,,40013586,,,,,,,,,,,,,,,,,,,,,,
RecCount:,,10221,,,,,,,,,,,,,,,,,,,,,,
Applicable Date:,,"June 14, 2017 (Wednesday)",,,,,,,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,,,,,,,,,
HQ Line,Part No,Part Class,Appl Req,Appl Count ,Intr Req,Intr Count ,OE Intr Req,Has OE Intr,Has Attr Editor, Has Attr Values,Part IMG Req,Has Part IMG,Has MPCC,Warr Req,Has Warr TXT,Has Warr PDF,MSDS Req,Has MSDS,UPC Req,Has UPC,Has UNSPSC,Attr Count ,AttrVal Count ,Valid Part
GAT,'27210',S,NO,0,YES,1,YES,NO,YES,YES,YES,YES,YES,YES,YES,YES,NO,NO,YES,YES,YES,30,13,YES
GAT,'27211',O,NO,0,YES,1,YES,NO,YES,YES,YES,YES,YES,YES,YES,YES,NO,NO,YES,YES,YES,30,14,YES
GAT,'27212',S,NO,0,YES,1,YES,NO,YES,YES,YES,YES,YES,YES,YES,YES,NO,NO,YES,YES,YES,30,13,YES
GAT,'27213',S,NO,0,YES,1,YES,NO,YES,YES,YES,YES,YES,YES,YES,YES,NO,NO,YES,YES,YES,30,13,YES
GAT,'27220',S,NO,0,YES,2,YES,NO,YES,YES,YES,YES,YES,YES,YES,YES,NO,NO,YES,YES,YES,35,20,YES
GAT,'27221',S,NO,0,YES,2,YES,NO,YES,YES,YES,YES,YES,YES,YES,YES,NO,NO,YES,YES,YES,35,20,YES

Body:
This script allows you to transform an excel data table to a list of dictionaries:

import xlrd

workbook = xlrd.open_workbook('GAT_US_PartReview_2017-06-23.xlsx', on_demand = True)
worksheet = workbook.sheet_by_index(0)
first_row = [] # The row where we stock the name of the column
for col in range(worksheet.ncols):
    first_row.append( worksheet.cell_value(0,col) )
# transform the workbook to a list of dictionaries
data =[]
for row in range(1, worksheet.nrows):
    elm = {}
    for col in range(worksheet.ncols):
        elm[first_row[col]]=worksheet.cell_value(row,col)
    data.append(elm)
print data

You can also use Pandas

from pandas import *
xls = ExcelFile('GAT_US_PartReview_2017-06-23.xlsx')
df = xls.parse(xls.sheet_names[0])
print df.to_dict()


来源: stackexchange

问:
How to send JSONObject request in retrofit?
I was trying to send JSONObject request (POST method) using retrofit and get the  results as JSONObject, how can i achieve that.? my content type is (application/json)
Could you share some of your best methods ?

retrofit Interface class

```<code>public interface RequestClient {
@Headers("Content-Type: application/json")
@POST("TripmakersLowFareShopping")
Call<FlightResponse>pushRequest(@Body FlightRequest request);  }
</code>```

Request Model Class

```<code>public class FlightRequest {

@SerializedName("AgencyID")
@Expose
private String agencyID;
@SerializedName("BranchID")
@Expose
private String branchID;
@SerializedName("OriginDestinationInformations")
@Expose
private ArrayList<OriginDestinationInformation> originDestinationInformations = null;
@SerializedName("PassengerTypeQuantities")
@Expose
private ArrayList<PassengerTypeQuantity> passengerTypeQuantities = null;
@SerializedName("Password")
@Expose
private String password;
@SerializedName("PricingSourceType")
@Expose
private Integer pricingSourceType;
@SerializedName("RequestOptions")
@Expose
private Integer requestOptions;
@SerializedName("SessionId")
@Expose
private Object sessionId;
@SerializedName("SupplierParameterList")
@Expose
private ArrayList<SupplierParameterList> supplierParameterList = null;
@SerializedName("Target")
@Expose
private Integer target;
@SerializedName("TravelPreferences")
@Expose
private TravelPreferences travelPreferences;
@SerializedName("UserName")
@Expose
private String userName;

/**
 * No args constructor for use in serialization
 *
 */

public FlightRequest() {
    super();
    this.agencyID = "20083";
    this.branchID = "10161";
    this.password = "Tj9%2f30XvS59GOBsjHuMd%2bg%3d%3d";
    this.pricingSourceType = 0;
    this.requestOptions = 0;
    this.sessionId = null;
    this.target = 0;
    this.userName = "qc@*****.com";
}

public String getAgencyID() {
    return agencyID;
}

public void setAgencyID(String agencyID) {
    this.agencyID = agencyID;
}

public String getBranchID() {
    return branchID;
}

public void setBranchID(String branchID) {
    this.branchID = branchID;
}

public List<OriginDestinationInformation> getOriginDestinationInformations() {
    return originDestinationInformations;
}

public void setOriginDestinationInformations(ArrayList<OriginDestinationInformation> originDestinationInformations) {
    this.originDestinationInformations = originDestinationInformations;
}

public List<PassengerTypeQuantity> getPassengerTypeQuantities() {
    return passengerTypeQuantities;
}

public void setPassengerTypeQuantities(ArrayList<PassengerTypeQuantity> passengerTypeQuantities) {
    this.passengerTypeQuantities = passengerTypeQuantities;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public Integer getPricingSourceType() {
    return pricingSourceType;
}

public void setPricingSourceType(Integer pricingSourceType) {
    this.pricingSourceType = pricingSourceType;
}

public Integer getRequestOptions() {
    return requestOptions;
}

public void setRequestOptions(Integer requestOptions) {
    this.requestOptions = requestOptions;
}

public Object getSessionId() {
    return sessionId;
}

public void setSessionId(Object sessionId) {
    this.sessionId = sessionId;
}

public List<SupplierParameterList> getSupplierParameterList() {
    return supplierParameterList;
}

public void setSupplierParameterList(ArrayList<SupplierParameterList> supplierParameterList) {
    this.supplierParameterList = supplierParameterList;
}

public Integer getTarget() {
    return target;
}

public void setTarget(Integer target) {
    this.target = target;
}

public TravelPreferences getTravelPreferences() {
    return travelPreferences;
}

public void setTravelPreferences(TravelPreferences travelPreferences) {
    this.travelPreferences = travelPreferences;
}

public String getUserName() {
    return userName;
}

public void setUserName(String userName) {
    this.userName = userName;
}
</code>```

}
Response model class

```<code>public class FlightResponse {

private JSONObject responceData;

public JSONObject getResponceData() {
    return responceData;
}

public void setResponceData(JSONObject responceData) {
    this.responceData = responceData;
}
</code>```

}

Retrofit declaration and functional part

```<code>   rqbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ArrayList<OriginDestinationInformation> originlist = new ArrayList<>();
            originlist.add(new OriginDestinationInformation(null,"/Date(1503599400000)/",null,"COK","DXB"));
            ArrayList<PassengerTypeQuantity> typeQuantities = new ArrayList<>();
            ArrayList<SupplierParameterList>supplierParameterLists = new ArrayList<SupplierParameterList>();
            supplierParameterLists.add(new SupplierParameterList(false,"EndUserIPAddress","61.0.250.97"));
            supplierParameterLists.add(new SupplierParameterList(false,"EndUserBrowserAgent","Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"));
            supplierParameterLists.add(new SupplierParameterList(false,null,null));
            supplierParameterLists.add(new SupplierParameterList(false,"UserData","qc@tripmakers.com,971_527564545,Fateh"));
            supplierParameterLists.add(new SupplierParameterList(false,"RequestOrigin","US-localhost"));

            typeQuantities.add(new PassengerTypeQuantity(1,1));
            TravelPreferences travelPreferences = new TravelPreferences(1,1);
            FlightRequest request = new FlightRequest();
            request.setOriginDestinationInformations(originlist);
            request.setPassengerTypeQuantities(typeQuantities);
            request.setTravelPreferences(travelPreferences);
            request.setSupplierParameterList(supplierParameterLists);

            requestCall(request);
        }
    });
}

private void requestCall(FlightRequest request) {
     OkHttpClient.Builder httpClient ;

    Retrofit.Builder builder = new Retrofit.Builder()
            .baseUrl("http://192.168.1.125:8013/flight/").addConverterFactory(GsonConverterFactory.create());
    Retrofit retrofit = builder.build();
    RequestClient client = retrofit.create(RequestClient.class);

    Call<FlightResponse> requestCall = client.pushRequest(request);
    requestCall.enqueue(new Callback<FlightResponse>() {
        @Override
        public void onResponse(Call<FlightResponse> call, Response<FlightResponse> response) {
            Toast.makeText(RetrofitResults.this, "Sucess", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFailure(Call<FlightResponse> call, Throwable t) {
            Toast.makeText(RetrofitResults.this, "Something went wrong", Toast.LENGTH_SHORT).show();
        }
    });
}
</code>```

答:
You can see this link
 for complete request/response types and how to send requset and other examples of retrofit calls.

here is an example of completely working service request :

1.after adding dependencies for retrofit, first create your retrofit serviceGenerator :

```<code>public class ServiceGenerator {

//main donate server
private static final String SERVICE_BASE_URL = "127.0.0.1"; //add your server ip here
private static Retrofit retrofit;
private static OkHttpClient.Builder httpClient ;
private static ServiceGenerator instance;
private static Retrofit.Builder builder =
        new Retrofit.Builder()
                .baseUrl(SERVICE_BASE_URL)
                .addConverterFactory(GsonConverterFactory.create());

private ServiceGenerator() {
    init();
}

public static ServiceGenerator getInstance() {

    if (instance == null) {
        instance = new ServiceGenerator();
    }
    return instance;
}

public static <S> S createService(Class<S> serviceClass) {
    return retrofit.create(serviceClass);
}

public static void init(){
    httpClient =new OkHttpClient.Builder()
            .sslSocketFactory(getSSLConfig(KarizApplication.appContext).getSocketFactory());

    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(Config.HTTP_LOG_LEVEL);

    httpClient.addInterceptor(logging);
    httpClient.connectTimeout(50, TimeUnit.SECONDS);
    httpClient.readTimeout(50, TimeUnit.SECONDS);
    OkHttpClient client = httpClient.build();
    retrofit = builder.client(client).build();
}
    public static Retrofit retrofit() {
    return retrofit;
}

private static SSLContext getSSLConfig(Context context) {
    try {
        // Loading CAs from an InputStream
        CertificateFactory cf = null;
        cf = CertificateFactory.getInstance("X.509");

        Certificate ca;
        // I'm using Java7. If you used Java6 close it manually with finally.
        InputStream cert = context.getResources().openRawResource(R.raw.donate_apache_selfsigned);
        ca = cf.generateCertificate(cert);

        // Creating a KeyStore containing our trusted CAs
        String keyStoreType = KeyStore.getDefaultType();
        KeyStore keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(null, null);
        keyStore.setCertificateEntry("ca", ca);

        // Creating a TrustManager that trusts the CAs in our KeyStore.
        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(keyStore);

        // Creating an SSLSocketFactory that uses our TrustManager
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, tmf.getTrustManagers(), null);

        return sslContext;
    }
    catch (Exception e){
        throw new RuntimeException(e);
    }
}

}
</code>```

after that you need to create your desired service and request / response classes :

```<code>public interface UserProfileServices {

@POST("setting/update")
Call<SettingsResponse> saveSettings(@Body SettingsRequest settingsRequest);
  }
</code>```

SettingRequest class :

```<code>public class SettingsRequest {
@SerializedName("id")
@Expose
private String userId;
@SerializedName("settings")
@Expose
private String settingsData;

public String getUserId() {
return userId;
}

public void setUserId(String userId) {
this.userId = userId;
}

public String getSettingsData() {
return settingsData;
}

public void setSettingsData(String settingsData) {
this.settingsData = settingsData;
}
}
</code>```

SettingResponse class :

```<code>public class SettingsResponse  {
@SerializedName("settings")
@Expose
private JSONObject settingsData;
public JSONObject getSettingsData() {
return settingsData;
}

public void setSettingsData(JSONObject settingsData) {
this.settingsData = settingsData;
}
}
</code>```

and the usage is like bellow :

```<code> private void sendSettingsToServer(Settings setting) {
final SettingsRequest settingsRequest = new SettingsRequest();
settingsRequest.setUserId(KarizApplication.getUserId());
settingsRequest.setSettingsData(setting.getSettingsData().toString());
userProfileServices = ServiceGenerator.getInstance().createService(UserProfileServices.class);
Call<SettingsResponse> saveSettings = userProfileServices.saveSettings(settingsRequest);
saveSettings.enqueue(new Callback<SettingsResponse>() {
    @Override
    public void onResponse(Call<SettingsResponse> call, Response<SettingsResponse> response) {
        if (response.isSuccessful()) {
            Log.d("saveSettings", "successful");
        } else {
            if (response.code() < 500) {}
            else {}
        }
    }

    @Override
    public void onFailure(Call<SettingsResponse> call, Throwable t) {

        }
    }
});
}
</code>```

hope this helps.

ContentLicense: CC BY-SA 3.0

Body:
I was trying to send JSONObject request (POST method) using retrofit and get the  results as JSONObject, how can i achieve that.? my content type is (application/json)
Could you share some of your best methods ?

retrofit Interface class

public interface RequestClient {
@Headers("Content-Type: application/json")
@POST("TripmakersLowFareShopping")
Call<FlightResponse>pushRequest(@Body FlightRequest request);  }

Request Model Class

public class FlightRequest {

@SerializedName("AgencyID")
@Expose
private String agencyID;
@SerializedName("BranchID")
@Expose
private String branchID;
@SerializedName("OriginDestinationInformations")
@Expose
private ArrayList<OriginDestinationInformation> originDestinationInformations = null;
@SerializedName("PassengerTypeQuantities")
@Expose
private ArrayList<PassengerTypeQuantity> passengerTypeQuantities = null;
@SerializedName("Password")
@Expose
private String password;
@SerializedName("PricingSourceType")
@Expose
private Integer pricingSourceType;
@SerializedName("RequestOptions")
@Expose
private Integer requestOptions;
@SerializedName("SessionId")
@Expose
private Object sessionId;
@SerializedName("SupplierParameterList")
@Expose
private ArrayList<SupplierParameterList> supplierParameterList = null;
@SerializedName("Target")
@Expose
private Integer target;
@SerializedName("TravelPreferences")
@Expose
private TravelPreferences travelPreferences;
@SerializedName("UserName")
@Expose
private String userName;

/**
 * No args constructor for use in serialization
 *
 */

public FlightRequest() {
    super();
    this.agencyID = "20083";
    this.branchID = "10161";
    this.password = "Tj9%2f30XvS59GOBsjHuMd%2bg%3d%3d";
    this.pricingSourceType = 0;
    this.requestOptions = 0;
    this.sessionId = null;
    this.target = 0;
    this.userName = "qc@*****.com";
}

public String getAgencyID() {
    return agencyID;
}

public void setAgencyID(String agencyID) {
    this.agencyID = agencyID;
}

public String getBranchID() {
    return branchID;
}

public void setBranchID(String branchID) {
    this.branchID = branchID;
}

public List<OriginDestinationInformation> getOriginDestinationInformations() {
    return originDestinationInformations;
}

public void setOriginDestinationInformations(ArrayList<OriginDestinationInformation> originDestinationInformations) {
    this.originDestinationInformations = originDestinationInformations;
}

public List<PassengerTypeQuantity> getPassengerTypeQuantities() {
    return passengerTypeQuantities;
}

public void setPassengerTypeQuantities(ArrayList<PassengerTypeQuantity> passengerTypeQuantities) {
    this.passengerTypeQuantities = passengerTypeQuantities;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public Integer getPricingSourceType() {
    return pricingSourceType;
}

public void setPricingSourceType(Integer pricingSourceType) {
    this.pricingSourceType = pricingSourceType;
}

public Integer getRequestOptions() {
    return requestOptions;
}

public void setRequestOptions(Integer requestOptions) {
    this.requestOptions = requestOptions;
}

public Object getSessionId() {
    return sessionId;
}

public void setSessionId(Object sessionId) {
    this.sessionId = sessionId;
}

public List<SupplierParameterList> getSupplierParameterList() {
    return supplierParameterList;
}

public void setSupplierParameterList(ArrayList<SupplierParameterList> supplierParameterList) {
    this.supplierParameterList = supplierParameterList;
}

public Integer getTarget() {
    return target;
}

public void setTarget(Integer target) {
    this.target = target;
}

public TravelPreferences getTravelPreferences() {
    return travelPreferences;
}

public void setTravelPreferences(TravelPreferences travelPreferences) {
    this.travelPreferences = travelPreferences;
}

public String getUserName() {
    return userName;
}

public void setUserName(String userName) {
    this.userName = userName;
}

}
Response model class

public class FlightResponse {

private JSONObject responceData;

public JSONObject getResponceData() {
    return responceData;
}

public void setResponceData(JSONObject responceData) {
    this.responceData = responceData;
}

}

Retrofit declaration and functional part

   rqbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ArrayList<OriginDestinationInformation> originlist = new ArrayList<>();
            originlist.add(new OriginDestinationInformation(null,"/Date(1503599400000)/",null,"COK","DXB"));
            ArrayList<PassengerTypeQuantity> typeQuantities = new ArrayList<>();
            ArrayList<SupplierParameterList>supplierParameterLists = new ArrayList<SupplierParameterList>();
            supplierParameterLists.add(new SupplierParameterList(false,"EndUserIPAddress","61.0.250.97"));
            supplierParameterLists.add(new SupplierParameterList(false,"EndUserBrowserAgent","Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"));
            supplierParameterLists.add(new SupplierParameterList(false,null,null));
            supplierParameterLists.add(new SupplierParameterList(false,"UserData","qc@tripmakers.com,971_527564545,Fateh"));
            supplierParameterLists.add(new SupplierParameterList(false,"RequestOrigin","US-localhost"));

            typeQuantities.add(new PassengerTypeQuantity(1,1));
            TravelPreferences travelPreferences = new TravelPreferences(1,1);
            FlightRequest request = new FlightRequest();
            request.setOriginDestinationInformations(originlist);
            request.setPassengerTypeQuantities(typeQuantities);
            request.setTravelPreferences(travelPreferences);
            request.setSupplierParameterList(supplierParameterLists);

            requestCall(request);
        }
    });
}

private void requestCall(FlightRequest request) {
     OkHttpClient.Builder httpClient ;

    Retrofit.Builder builder = new Retrofit.Builder()
            .baseUrl("http://192.168.1.125:8013/flight/").addConverterFactory(GsonConverterFactory.create());
    Retrofit retrofit = builder.build();
    RequestClient client = retrofit.create(RequestClient.class);

    Call<FlightResponse> requestCall = client.pushRequest(request);
    requestCall.enqueue(new Callback<FlightResponse>() {
        @Override
        public void onResponse(Call<FlightResponse> call, Response<FlightResponse> response) {
            Toast.makeText(RetrofitResults.this, "Sucess", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFailure(Call<FlightResponse> call, Throwable t) {
            Toast.makeText(RetrofitResults.this, "Something went wrong", Toast.LENGTH_SHORT).show();
        }
    });
}

Body:
You can see this link
 for complete request/response types and how to send requset and other examples of retrofit calls.

here is an example of completely working service request :

1.after adding dependencies for retrofit, first create your retrofit serviceGenerator :

public class ServiceGenerator {

//main donate server
private static final String SERVICE_BASE_URL = "127.0.0.1"; //add your server ip here
private static Retrofit retrofit;
private static OkHttpClient.Builder httpClient ;
private static ServiceGenerator instance;
private static Retrofit.Builder builder =
        new Retrofit.Builder()
                .baseUrl(SERVICE_BASE_URL)
                .addConverterFactory(GsonConverterFactory.create());

private ServiceGenerator() {
    init();
}

public static ServiceGenerator getInstance() {

    if (instance == null) {
        instance = new ServiceGenerator();
    }
    return instance;
}

public static <S> S createService(Class<S> serviceClass) {
    return retrofit.create(serviceClass);
}

public static void init(){
    httpClient =new OkHttpClient.Builder()
            .sslSocketFactory(getSSLConfig(KarizApplication.appContext).getSocketFactory());

    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(Config.HTTP_LOG_LEVEL);

    httpClient.addInterceptor(logging);
    httpClient.connectTimeout(50, TimeUnit.SECONDS);
    httpClient.readTimeout(50, TimeUnit.SECONDS);
    OkHttpClient client = httpClient.build();
    retrofit = builder.client(client).build();
}
    public static Retrofit retrofit() {
    return retrofit;
}

private static SSLContext getSSLConfig(Context context) {
    try {
        // Loading CAs from an InputStream
        CertificateFactory cf = null;
        cf = CertificateFactory.getInstance("X.509");

        Certificate ca;
        // I'm using Java7. If you used Java6 close it manually with finally.
        InputStream cert = context.getResources().openRawResource(R.raw.donate_apache_selfsigned);
        ca = cf.generateCertificate(cert);

        // Creating a KeyStore containing our trusted CAs
        String keyStoreType = KeyStore.getDefaultType();
        KeyStore keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(null, null);
        keyStore.setCertificateEntry("ca", ca);

        // Creating a TrustManager that trusts the CAs in our KeyStore.
        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(keyStore);

        // Creating an SSLSocketFactory that uses our TrustManager
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, tmf.getTrustManagers(), null);

        return sslContext;
    }
    catch (Exception e){
        throw new RuntimeException(e);
    }
}

}

after that you need to create your desired service and request / response classes :

public interface UserProfileServices {

@POST("setting/update")
Call<SettingsResponse> saveSettings(@Body SettingsRequest settingsRequest);
  }

SettingRequest class :

public class SettingsRequest {
@SerializedName("id")
@Expose
private String userId;
@SerializedName("settings")
@Expose
private String settingsData;

public String getUserId() {
return userId;
}

public void setUserId(String userId) {
this.userId = userId;
}

public String getSettingsData() {
return settingsData;
}

public void setSettingsData(String settingsData) {
this.settingsData = settingsData;
}
}

SettingResponse class :

public class SettingsResponse  {
@SerializedName("settings")
@Expose
private JSONObject settingsData;
public JSONObject getSettingsData() {
return settingsData;
}

public void setSettingsData(JSONObject settingsData) {
this.settingsData = settingsData;
}
}

and the usage is like bellow :

 private void sendSettingsToServer(Settings setting) {
final SettingsRequest settingsRequest = new SettingsRequest();
settingsRequest.setUserId(KarizApplication.getUserId());
settingsRequest.setSettingsData(setting.getSettingsData().toString());
userProfileServices = ServiceGenerator.getInstance().createService(UserProfileServices.class);
Call<SettingsResponse> saveSettings = userProfileServices.saveSettings(settingsRequest);
saveSettings.enqueue(new Callback<SettingsResponse>() {
    @Override
    public void onResponse(Call<SettingsResponse> call, Response<SettingsResponse> response) {
        if (response.isSuccessful()) {
            Log.d("saveSettings", "successful");
        } else {
            if (response.code() < 500) {}
            else {}
        }
    }

    @Override
    public void onFailure(Call<SettingsResponse> call, Throwable t) {

        }
    }
});
}

hope this helps.


问:
Call to undefined method CI_DB_mysqli_result::fetch_assoc() in CodeIgniter
I have following function

```<code>function getQuery($sql,$returnType = ''){
    $data = array();
    $result = $this->db->query($sql);
    if($result){
        switch($returnType){
            case 'count':
                $data = $result->num_rows;
                break;
            case 'single':
                $data = $result->fetch_assoc();  //Line 55
                break;
            default:
                if($result->num_rows > 0){
                    while($row = $result->fetch_assoc()){
                        $data[] = $row;
                    }
                }
        }
    }
    if(!empty($data)) {
        return $data;
    }
    return false;
}
</code>```

When this method is executed following error is returned

Type: Error

Message: Call to undefined method CI_DB_mysqli_result::fetch_assoc()

Line Number: 55

I can't understand why the error is being shown. Please help!!!

答:
fetch_assoc() is not a method of Codeignetor query builder it's actaullay method of mysqli  but you are use "Codeignetor query builder"

for single row use like

```<code>$query = $this->db->query("YOUR QUERY");

$row = $query->row();

if (isset($row))
{
        echo $row->title;
        echo $row->name;
        echo $row->body;
}
</code>```

for multiple row :

```<code>$query = $this->db->query("YOUR QUERY");

foreach ($query->result_array() as $row)
{
        echo $row['title'];
        echo $row['name'];
        echo $row['body'];
}
</code>```

You have to use Below Code

```<code>function getQuery($sql,$returnType = ''){
    $data = array();
    $result = $this->db->query($sql);
    if($result){
        switch($returnType){
            case 'count':
                $data = $result->num_rows();
                break;
            case 'single':
                $data = $result->row_array(); // return result as array
                 or
                $data = $result->row(); //  return result as object
                break;
            default:
                $data = $result->result_array(); // result in array
                or
                $data =  $result->result(); // return a objects
        }
    }
    if(!empty($data)) {
        return $data;
    }
    return false;
}
</code>```

Body:
I have following function

function getQuery($sql,$returnType = ''){
    $data = array();
    $result = $this->db->query($sql);
    if($result){
        switch($returnType){
            case 'count':
                $data = $result->num_rows;
                break;
            case 'single':
                $data = $result->fetch_assoc();  //Line 55
                break;
            default:
                if($result->num_rows > 0){
                    while($row = $result->fetch_assoc()){
                        $data[] = $row;
                    }
                }
        }
    }
    if(!empty($data)) {
        return $data;
    }
    return false;
}

When this method is executed following error is returned

Type: Error

Message: Call to undefined method CI_DB_mysqli_result::fetch_assoc()

Line Number: 55

I can't understand why the error is being shown. Please help!!!

Body:
fetch_assoc() is not a method of Codeignetor query builder it's actaullay method of mysqli  but you are use "Codeignetor query builder"

for single row use like

$query = $this->db->query("YOUR QUERY");

$row = $query->row();

if (isset($row))
{
        echo $row->title;
        echo $row->name;
        echo $row->body;
}

for multiple row :

$query = $this->db->query("YOUR QUERY");

foreach ($query->result_array() as $row)
{
        echo $row['title'];
        echo $row['name'];
        echo $row['body'];
}

You have to use Below Code

function getQuery($sql,$returnType = ''){
    $data = array();
    $result = $this->db->query($sql);
    if($result){
        switch($returnType){
            case 'count':
                $data = $result->num_rows();
                break;
            case 'single':
                $data = $result->row_array(); // return result as array
                 or
                $data = $result->row(); //  return result as object
                break;
            default:
                $data = $result->result_array(); // result in array
                or
                $data =  $result->result(); // return a objects
        }
    }
    if(!empty($data)) {
        return $data;
    }
    return false;
}


问:
Javascript validation - sync with server
In the interests of DRY, is there a framework / library / design pattern for specifying validation rules in one place, and having them evaluated on both the client and server sides? It seems like an obvious requirement, but I haven't come across anything like it.

To clarify: I'm not interested in server-side code that generates forms with the required javascript to validate it - I want the validation rules to be decoupled from the client and server side implementations, e.g. request the validation rules through a web-based API.

Is there anything of the sort?

答:
Nice question!

I have done some MVC validation that gets the rules from database definition. Taking from that experience I would create a handler that takes a column specification string "namespace.table.column" and returns a set of rules to validate, preferably in JSON. Then use css classes to denote the input elements that will be validated (1) and set a validation event on all the ".validate" elements with JQuery, passing the validation object to that function.

Note that with this approach you would have to do some server side rendering of the rules, to not have to expose your database structure in javascript!

(1):
<input type="text" id="name" class="validate" />

The validation object:

perhaps start with some basic type checks, moving on with size checks?

```<code>JSON structure: validationObject =
{
    type: 'integer',
    length: '4',
    min: '0',
    max: '10000'
}

function validate(input) {

    var validation = getValidationObject(); // Ajax call

    // perform type check

    // perform length check

    // perform min/max/disallowed content checks

}
</code>```

Not elaborated enough, but something in this direction.

ContentLicense: CC BY-SA 2.5

Body:
Nice question!

I have done some MVC validation that gets the rules from database definition. Taking from that experience I would create a handler that takes a column specification string "namespace.table.column" and returns a set of rules to validate, preferably in JSON. Then use css classes to denote the input elements that will be validated (1) and set a validation event on all the ".validate" elements with JQuery, passing the validation object to that function.

Note that with this approach you would have to do some server side rendering of the rules, to not have to expose your database structure in javascript!

(1):
<input type="text" id="name" class="validate" />

The validation object:

perhaps start with some basic type checks, moving on with size checks?

JSON structure: validationObject =
{
    type: 'integer',
    length: '4',
    min: '0',
    max: '10000'
}

function validate(input) {

    var validation = getValidationObject(); // Ajax call

    // perform type check

    // perform length check

    // perform min/max/disallowed content checks

}

Not elaborated enough, but something in this direction.


问:
Python extract numbers after a specific string has appeared
I'm new to python and would like to write a script to extract some numbers from a bunch of files. This is a representative example of what I'm trying to do:

```<code>File_name_1: Bob-01
File content:
...(Lots of text)
Tea cups: 3
Tea cups: 4
Tea cups: 6
...(Lots of text)
Completed the first task, proceed to the next task.
...(Lots of text)
Tea cups: 7
Termination
</code>```

Let's say we also have another file:

```<code>File_name_2: Bob-02
File content:
...(Lots of text)
Tea cups: 2
Tea cups: 7
Tea cups: 3
Tea cups: 8
...(Lots of text)
Completed the first task, proceed to the next task.
...(Lots of text)
Tea cups: 1
Termination.
</code>```

At the moment I have written codes to extract the file name (eg. Bob-01), number after each Bob (eg. 01), and the file content (eg. every line in the first file) and store in a variable called list_of_file

```<code>print list_of_file

[["Bob-01"],
  01,
 [".......", "Tea Cups: 3", "Tea Cups: 4", "Tea cups: 6", "....", "Completed the first task, proceed to the next task.", "....", "Tea cups: 7", "Termination"],
 ["Bob-02"],
  02,
 [".......", "Tea Cups: 2", "Tea Cups: 7", "Tea cups: 3", "Tea cups: 8", "....", "Completed the first task, proceed to the next task.", "....", "Tea cups: 1", "Termination]]
</code>```

What I wanted to do is to extract the number of tea cups after the line "Complete first task, proceed to the next task." in each file. So I've written the following code:

```<code>def get_tea_cups (list_of_files):
   list_of_cup = []
   for line in file[2]:
      if "Completed the first task" in line:
         for line in file[2]:
            if "Tea cups:" in line:
              tea_cups_line = line.split()
              cup_num = tea_cups_line [2]
              list_of_cup.append(file[0], file[1], cup_num)
   return list_of_cup
</code>```

My though process: if I can find "Complete first task" in list_of_file, then hopefully I can extract the number of tea cups (eg. 7 for Bob-01 and 1 for Bob-02) after the string containing "Complete first task" has appeared. However, when I executed my code, I seems to have extracted all number of tea cups, which is not what I want.

I think the reason why this has happened is because the if statement will always be true so I ended up extracting all numbers of tea cups.

Is there a way I can get around this problem?? I know if I only do the extraction for one file I can store all the tea cup numbers found as a list and take the last value (by slicing backward). Can I do something similar when I perform extraction for multiple files?

I tried to look around but haven't found anything helpful yet. If you have come across anything which is related to this question please post the link below.

Thank you!!

答:
Yes, there's a way. I'd recommend you read the file backwards, find the first occurrence of tea, then break and parse the next file. My solution assumes your file is fitting into the memory. Most probably this can take a while to read large files

You can read a file from end by doing:

```<code>for line in reversed(list(open("filename"))):
    print(line.rstrip())
</code>```

Now, to get only the desired tea cups you can do:

```<code>cups = []
for line in reversed(list(open("filename"))):
    if "Tea cups" in line.rstrip():
        cups.append(line.rstrip().split()[2])
        break
print(cups)
</code>```

Body:
I'm new to python and would like to write a script to extract some numbers from a bunch of files. This is a representative example of what I'm trying to do:

File_name_1: Bob-01
File content:
...(Lots of text)
Tea cups: 3
Tea cups: 4
Tea cups: 6
...(Lots of text)
Completed the first task, proceed to the next task.
...(Lots of text)
Tea cups: 7
Termination

Let's say we also have another file:

File_name_2: Bob-02
File content:
...(Lots of text)
Tea cups: 2
Tea cups: 7
Tea cups: 3
Tea cups: 8
...(Lots of text)
Completed the first task, proceed to the next task.
...(Lots of text)
Tea cups: 1
Termination.

At the moment I have written codes to extract the file name (eg. Bob-01), number after each Bob (eg. 01), and the file content (eg. every line in the first file) and store in a variable called list_of_file

print list_of_file

[["Bob-01"],
  01,
 [".......", "Tea Cups: 3", "Tea Cups: 4", "Tea cups: 6", "....", "Completed the first task, proceed to the next task.", "....", "Tea cups: 7", "Termination"],
 ["Bob-02"],
  02,
 [".......", "Tea Cups: 2", "Tea Cups: 7", "Tea cups: 3", "Tea cups: 8", "....", "Completed the first task, proceed to the next task.", "....", "Tea cups: 1", "Termination]]

What I wanted to do is to extract the number of tea cups after the line "Complete first task, proceed to the next task." in each file. So I've written the following code:

def get_tea_cups (list_of_files):
   list_of_cup = []
   for line in file[2]:
      if "Completed the first task" in line:
         for line in file[2]:
            if "Tea cups:" in line:
              tea_cups_line = line.split()
              cup_num = tea_cups_line [2]
              list_of_cup.append(file[0], file[1], cup_num)
   return list_of_cup

My though process: if I can find "Complete first task" in list_of_file, then hopefully I can extract the number of tea cups (eg. 7 for Bob-01 and 1 for Bob-02) after the string containing "Complete first task" has appeared. However, when I executed my code, I seems to have extracted all number of tea cups, which is not what I want.

I think the reason why this has happened is because the if statement will always be true so I ended up extracting all numbers of tea cups.

Is there a way I can get around this problem?? I know if I only do the extraction for one file I can store all the tea cup numbers found as a list and take the last value (by slicing backward). Can I do something similar when I perform extraction for multiple files?

I tried to look around but haven't found anything helpful yet. If you have come across anything which is related to this question please post the link below.

Thank you!!

Body:
Yes, there's a way. I'd recommend you read the file backwards, find the first occurrence of tea, then break and parse the next file. My solution assumes your file is fitting into the memory. Most probably this can take a while to read large files

You can read a file from end by doing:

for line in reversed(list(open("filename"))):
    print(line.rstrip())

Now, to get only the desired tea cups you can do:

cups = []
for line in reversed(list(open("filename"))):
    if "Tea cups" in line.rstrip():
        cups.append(line.rstrip().split()[2])
        break
print(cups)


问:
Get NumericProperty of ReferenceListProperty kivy
I have some code:

```<code>A = NumericProperty(1)
B = NumericProperty(2)

C = ReferenceListProperty(A, B)
</code>```

How I can get NumericProperty of ReferenceListProperty back?

答:
C[0] returns A and C[1] returns B

Here is a small Example App with your values, which prints A and B from C (.py)

```<code>from kivy.app import App
from kivy.base import Builder
from kivy.properties import NumericProperty, ReferenceListProperty
from kivy.uix.boxlayout import BoxLayout

Builder.load_string("""
<rootwi>:
    Button:
        text: 'print A via ReferenceListProperty'
        on_press: print(root.C[0])
    Button:
        text: 'print B via ReferenceListProperty'
        on_press: print(root.C[1])
""")
class rootwi(BoxLayout):
    A = NumericProperty(1)
    B = NumericProperty(2)
    C = ReferenceListProperty(A, B)

class MyApp(App):
    def build(self):
        return rootwi()

if __name__ == '__main__':
    MyApp().run()

class MyApp(App):
    def build(self):
        return rootwi()

if __name__ == '__main__':
    MyApp().run()
</code>```

Body:
I have some code:

A = NumericProperty(1)
B = NumericProperty(2)

C = ReferenceListProperty(A, B)

How I can get NumericProperty of ReferenceListProperty back?

Body:
C[0] returns A and C[1] returns B

Here is a small Example App with your values, which prints A and B from C (.py)

from kivy.app import App
from kivy.base import Builder
from kivy.properties import NumericProperty, ReferenceListProperty
from kivy.uix.boxlayout import BoxLayout

Builder.load_string("""
<rootwi>:
    Button:
        text: 'print A via ReferenceListProperty'
        on_press: print(root.C[0])
    Button:
        text: 'print B via ReferenceListProperty'
        on_press: print(root.C[1])
""")
class rootwi(BoxLayout):
    A = NumericProperty(1)
    B = NumericProperty(2)
    C = ReferenceListProperty(A, B)

class MyApp(App):
    def build(self):
        return rootwi()

if __name__ == '__main__':
    MyApp().run()

class MyApp(App):
    def build(self):
        return rootwi()

if __name__ == '__main__':
    MyApp().run()


问:
Best way to pass the value in Some to a function with a default parameter value?
I have a function from a third party library as below :

```<code>def myfunction(input:String = "some constant value")
</code>```

I have a

```<code>myinput:Option[String]
</code>```

with me and I need to pass the function. Right now I am doing this:

```<code>myfunction(myinput.getOrElse("some constant value"))
</code>```

But I dont want to look into the third party library for its default value.
What is the ideal way to do this?

答:
You can try:

```<code>myinput.map(v => myfunction(v)).getOrElse(myfunction())
</code>```

or more concise (as suggested by Pablo in the comments):

```<code>myinput.map(myfunction).getOrElse(myfunction())
</code>```

Body:
I have a function from a third party library as below :

def myfunction(input:String = "some constant value")

I have a

myinput:Option[String]

with me and I need to pass the function. Right now I am doing this:

myfunction(myinput.getOrElse("some constant value"))

But I dont want to look into the third party library for its default value.
What is the ideal way to do this?

Body:
You can try:

myinput.map(v => myfunction(v)).getOrElse(myfunction())

or more concise (as suggested by Pablo in the comments):

myinput.map(myfunction).getOrElse(myfunction())


问:
How to correctly expose Android SDK to Jenkins user?
Few days ago I installed Jenkins on my Mac. As you probably already know installer creates dedicated jenkins user. My question is: how to correctly expose Android SDK to jenkins user? Or how to share Android SDK between OSX users?

Some people advise to keep it in /opt/. What's the proper way to do it?

答: I think /opt/ is a pretty good place for it, yes. It's probably the most common place to store the SDK. In the end, it doesn't matter where you put it as long as it fits your needs. Alternatively you could also install a second instance of the SDK just for the Jenkins user but i see no reason to do so.


问:
Push Notification Error in Ionic 3
I am trying to configure push notification in my Ionic 3 application. I have already configured my Ionic Cloud and Firebase. But I am getting an Error saying:

Can't resolve all parameters for Push: (?, ?) in both browser and device.

Here is my app.module.ts file.

```<code>import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';
import { CloudSettings, CloudModule } from '@ionic/cloud-angular';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { PushPageModule } from '../pages/push/push.module';

const cloudSettings: CloudSettings = {
  'core': {
    'app_id': 'fe5f8133'
  },
  'push': {
    'sender_id': '77303616548',
    'pluginConfig': {
      'ios': {
        'badge': true,
        'sound': true
      },
      'android': {
        'iconColor': '#343434'
      }
    }
  }
};

@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    BrowserModule,
    HttpModule,
    PushPageModule,
    CloudModule.forRoot(cloudSettings),
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}
</code>```

And this is my app.component.ts

```<code>import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

import { HomePage } from '../pages/home/home';

import {
  Push,
  PushToken
} from '@ionic/cloud-angular';

@Component({
  templateUrl: 'app.html',
  providers: [Push]
})
export class MyApp {
  rootPage:any = HomePage;
  logs;

  constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen, private push: Push) {
    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      statusBar.styleDefault();
      splashScreen.hide();

      this.push.register().then((t: PushToken) => {
        return this.push.saveToken(t);
      }).then((t: PushToken) => {
        console.log('Token saved:', t.token);
        this.logs = 'Token saved:', t.token;
      });

      this.push.rx.notification()
      .subscribe((msg) => {
        console.log('I received awesome push: ' + msg);
        this.logs = 'I received awesome push: ' + msg;
      });

    });
  }
}
</code>```

This is the Error message:

答:
You should not set Push as provider in your component or in AppModule. This will be set in cloud-angular module.

Remove:

```<code>@Component({
  templateUrl: 'app.html',
  // providers: [Push] -> remove this
})
export class MyApp {
</code>```

Check the code here of ionic-cloud-angular.

They have already set Push as provider when you set CloudModule.forRoot(config). Also Push requires two parameters PushOptions and PushDependencies which were missing in your dependency injection.

```<code>@NgModule()
    export class CloudModule {
      static forRoot(settings: CloudSettings): ModuleWithProviders {
        return {
          ngModule: CloudModule,
          providers: [
            { provide: CloudSettingsToken, useValue: settings },
            { provide: DIContainer, useFactory: provideContainer, deps: [ CloudSettingsToken ] },
            { provide: Auth, useFactory: provideAuth, deps: [ DIContainer ] },
            { provide: Client, useFactory: provideClient, deps: [ DIContainer ] },
            { provide: Config, useFactory: provideConfig, deps: [ DIContainer ] },
            { provide: Deploy, useFactory: provideDeploy, deps: [ DIContainer ] },
            { provide: Push, useFactory: providePush, deps: [ DIContainer ] },
            { provide: User, useFactory: provideUser, deps: [ DIContainer ] },
            { provide: FacebookAuth, useFactory: provideFacebookAuth, deps: [ DIContainer ]},
            { provide: GoogleAuth, useFactory: provideGoogleAuth, deps: [ DIContainer ]}
          ]
        };
      }
</code>```

Title: Push Notification Error in Ionic 3

Body:
I am trying to configure push notification in my Ionic 3 application. I have already configured my Ionic Cloud and Firebase. But I am getting an Error saying:

Can't resolve all parameters for Push: (?, ?) in both browser and device.

Here is my app.module.ts file.

import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';
import { CloudSettings, CloudModule } from '@ionic/cloud-angular';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { PushPageModule } from '../pages/push/push.module';

const cloudSettings: CloudSettings = {
  'core': {
    'app_id': 'fe5f8133'
  },
  'push': {
    'sender_id': '77303616548',
    'pluginConfig': {
      'ios': {
        'badge': true,
        'sound': true
      },
      'android': {
        'iconColor': '#343434'
      }
    }
  }
};

@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    BrowserModule,
    HttpModule,
    PushPageModule,
    CloudModule.forRoot(cloudSettings),
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}

And this is my app.component.ts

import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

import { HomePage } from '../pages/home/home';

import {
  Push,
  PushToken
} from '@ionic/cloud-angular';

@Component({
  templateUrl: 'app.html',
  providers: [Push]
})
export class MyApp {
  rootPage:any = HomePage;
  logs;

  constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen, private push: Push) {
    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      statusBar.styleDefault();
      splashScreen.hide();

      this.push.register().then((t: PushToken) => {
        return this.push.saveToken(t);
      }).then((t: PushToken) => {
        console.log('Token saved:', t.token);
        this.logs = 'Token saved:', t.token;
      });

      this.push.rx.notification()
      .subscribe((msg) => {
        console.log('I received awesome push: ' + msg);
        this.logs = 'I received awesome push: ' + msg;
      });

    });
  }
}

This is the Error message:

Body:
You should not set Push as provider in your component or in AppModule. This will be set in cloud-angular module.

Remove:

@Component({
  templateUrl: 'app.html',
  // providers: [Push] -> remove this
})
export class MyApp {

Check the code here of ionic-cloud-angular.

They have already set Push as provider when you set CloudModule.forRoot(config). Also Push requires two parameters PushOptions and PushDependencies which were missing in your dependency injection.

@NgModule()
    export class CloudModule {
      static forRoot(settings: CloudSettings): ModuleWithProviders {
        return {
          ngModule: CloudModule,
          providers: [
            { provide: CloudSettingsToken, useValue: settings },
            { provide: DIContainer, useFactory: provideContainer, deps: [ CloudSettingsToken ] },
            { provide: Auth, useFactory: provideAuth, deps: [ DIContainer ] },
            { provide: Client, useFactory: provideClient, deps: [ DIContainer ] },
            { provide: Config, useFactory: provideConfig, deps: [ DIContainer ] },
            { provide: Deploy, useFactory: provideDeploy, deps: [ DIContainer ] },
            { provide: Push, useFactory: providePush, deps: [ DIContainer ] },
            { provide: User, useFactory: provideUser, deps: [ DIContainer ] },
            { provide: FacebookAuth, useFactory: provideFacebookAuth, deps: [ DIContainer ]},
            { provide: GoogleAuth, useFactory: provideGoogleAuth, deps: [ DIContainer ]}
          ]
        };
      }


问:
how change the module that python uses?
I'm installing caffe2 in a remote server, and I used pip to install a module called Numpy.

The python(2.7.6) is in :

```<code>/usr/bin/python
</code>```

The pip is in :

```<code>/usr/local/bin/pip
</code>```

when I use 'pip show numpy':

```<code>Name: numpy
Version: 1.13.0
Location: /usr/local/lib/python2.7/dist-packages
</code>```

but when I try to import it in python:

```<code>>>> import numpy as np
>>> n.__version__
'1.8.2'
>>>>>> n.get_include()
'/usr/lib/python2.7/dist-packages/numpy/core/include'
</code>```

so I tried export PYTHONPATH in relative rc files:

```<code>export PYTHONPATH="/usr/local/lib/python2.7/dist-packages":$PYTHONPATH
</code>```

but this doesn't help.

What's the next step should I take?

答: The way to avoid all this confusion is to always use a virtualenv, and install the correct version of numpy there.</p>

Title: how change the module that python uses?

Body:
I'm installing caffe2 in a remote server, and I used pip to install a module called Numpy.

The python(2.7.6) is in :

/usr/bin/python

The pip is in :

/usr/local/bin/pip

when I use 'pip show numpy':

Name: numpy
Version: 1.13.0
Location: /usr/local/lib/python2.7/dist-packages

but when I try to import it in python:

>>> import numpy as np
>>> n.__version__
'1.8.2'
>>>>>> n.get_include()
'/usr/lib/python2.7/dist-packages/numpy/core/include'

so I tried export PYTHONPATH in relative rc files:

export PYTHONPATH="/usr/local/lib/python2.7/dist-packages":$PYTHONPATH

but this doesn't help.

What's the next step should I take?


问:
iPhone making a map like in Fire Emblem
I want to make a RPG where you engage foes utilizing a map/grid. I'm just trying to figure out how this could be done in Objective-C... also, I do not want to use OpenGL; no tilemaps. :P</p>

答: Try using Cocos2d. they have excellent tileset library tools, in addition to sprite manipulation.  Check out Ray Wenderlich's tutorials here. it's really quite easy to use.</p>

Title: iPhone making a map like in Fire Emblem


问:
Zip File - Download - Then Unzip
I'm getting really confused here. So here's whats going on in my project. The user clicks download then select directory to save the file, the file will be a zip file. After that I want to extract that zip file in the same directory the users chooses. Is this even possible in one script?

Here is my php code

```<code><?php
require_once('connect.php');
// Get real path for our folder
$rootPath = realpath($_GET['uniq']);

// Name of the zip derive from the database
$zipname = $_GET['name'] . '.zip';
// Initialize archive object
$zip = new ZipArchive();
$zip->open($zipname, ZipArchive::CREATE | ZipArchive::OVERWRITE);

// Create recursive directory iterator
/** @var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($rootPath),
    RecursiveIteratorIterator::LEAVES_ONLY
);

foreach ($files as $name => $file)
{
    // Skip directories (they would be added automatically)
    if (!$file->isDir())
    {
        // Get real and relative path for current file
        $filePath = $file->getRealPath();
        $relativePath = substr($filePath, strlen($rootPath) + 1);

        // Add current file to archive
        $zip->addFile($filePath, $relativePath);
    }
}

// Zip archive will be created only after closing object
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
?>
</code>```

If its not possible another question. Is it possible to let user choose a zip file then after that it will be extracted at some client directory ie. C://xamp/extracthere/ using javascript.

答:
Once the user has downloaded the file to their machine, it's beyond your control. You can't force them to unzip it, or do anything else with it for that matter.

Imagine if you could control the files on a user's local disk, it would be a hacker's dream. This is impossible using both PHP and JavaScript, for similar reasons in each case.

Title: Zip File - Download - Then Unzip

Body:
I'm getting really confused here. So here's whats going on in my project. The user clicks download then select directory to save the file, the file will be a zip file. After that I want to extract that zip file in the same directory the users chooses. Is this even possible in one script?

Here is my php code

<?php
require_once('connect.php');
// Get real path for our folder
$rootPath = realpath($_GET['uniq']);

// Name of the zip derive from the database
$zipname = $_GET['name'] . '.zip';
// Initialize archive object
$zip = new ZipArchive();
$zip->open($zipname, ZipArchive::CREATE | ZipArchive::OVERWRITE);

// Create recursive directory iterator
/** @var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($rootPath),
    RecursiveIteratorIterator::LEAVES_ONLY
);

foreach ($files as $name => $file)
{
    // Skip directories (they would be added automatically)
    if (!$file->isDir())
    {
        // Get real and relative path for current file
        $filePath = $file->getRealPath();
        $relativePath = substr($filePath, strlen($rootPath) + 1);

        // Add current file to archive
        $zip->addFile($filePath, $relativePath);
    }
}

// Zip archive will be created only after closing object
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
?>

If its not possible another question. Is it possible to let user choose a zip file then after that it will be extracted at some client directory ie. C://xamp/extracthere/ using javascript.


问:
Nested if and Formula
HI i am trying to write the IF function like this.

```<code>=IF(AND(E3="Epyllion",J3="7"),".70","")
</code>```

But result always shows 0 instead of .70.

My point for this function is,

```<code>IF E3="Epyllion" AND J3="7" Then .70 AND IF E3="Epyllion" AND J3="5" Then ".72" AND IF E3="Epyllion" AND J3="3" Then ".80"
</code>```

Can someone help me to write this formula.

答:
Your formula should have been

```<code>=IF(AND(E3="Epyllion",J3=7),".70","")
</code>```

unless Cell J3 is formatted as text.

With all the conditions mentioned in the question formula can be written as

```<code>=IF(E3="Epyllion",IF(J3=7,".70",IF(J3=5,".72","0.8")))
</code>```

provided you just have 7,3,5 for Cell J3. If you have more than these three values then use

```<code>=IF(E3="Epyllion",IF(J3=7,".70",IF(J3=5,".72",IF(J3=3,".80",""))),"")
</code>```

Title: Nested if and Formula

Body:
HI i am trying to write the IF function like this.

=IF(AND(E3="Epyllion",J3="7"),".70","")

But result always shows 0 instead of .70.

My point for this function is,

IF E3="Epyllion" AND J3="7" Then .70 AND IF E3="Epyllion" AND J3="5" Then ".72" AND IF E3="Epyllion" AND J3="3" Then ".80"

Can someone help me to write this formula.

Body:
Your formula should have been

=IF(AND(E3="Epyllion",J3=7),".70","")

unless Cell J3 is formatted as text.

With all the conditions mentioned in the question formula can be written as

=IF(E3="Epyllion",IF(J3=7,".70",IF(J3=5,".72","0.8")))

provided you just have 7,3,5 for Cell J3. If you have more than these three values then use

=IF(E3="Epyllion",IF(J3=7,".70",IF(J3=5,".72",IF(J3=3,".80",""))),"")


问:
Although i have the right informations there is a thread 1 : Signal brt
I have created a login screen for my app and i have chosen a username and password. When i write the wrong infos it works but the right informations don't work please help.Here is my login button.</p>

```<code> @IBAction func loginButton(_ sender: UIButton) {

    if  userTf.text == "bartu" && passTf.text == "1" {
        let myVC = storyboard?.instantiateViewController(withIdentifier: "Tab")
        navigationController?.pushViewController(myVC!, animated: true)

    }

    else {
        errorLabel.text = "Informations are wrong!"
    }

    }

}
</code>```

答:
Try to test your variable, because clearly, your are trying to initiate the wrong view.

```<code>if storyboard != nil{
    let myVC = storyboard!.instantiateViewController(withIdentifier: "Tab")
    if navigationController != nil{
        if myVC != nil {
            navigationController!.pushViewController(myVC!, animated: true)
        }else{
            errorLabel.text = "Unable to find myVC"
        }
    }else{
        errorLabel.text = "Unable to find navigationController"
    }
}else{
    errorLabel.text = "Unable to find storyboard"
}
</code>```

-> This piece of code is not the best way to debug but it would help you to have visual answers to your problem.

Body:
I have created a login screen for my app and i have chosen a username and password. When i write the wrong infos it works but the right informations don't work please help.Here is my login button.

 @IBAction func loginButton(_ sender: UIButton) {

    if  userTf.text == "bartu" && passTf.text == "1" {
        let myVC = storyboard?.instantiateViewController(withIdentifier: "Tab")
        navigationController?.pushViewController(myVC!, animated: true)

    }

    else {
        errorLabel.text = "Informations are wrong!"
    }

    }

}

Body:
Try to test your variable, because clearly, your are trying to initiate the wrong view.

if storyboard != nil{
    let myVC = storyboard!.instantiateViewController(withIdentifier: "Tab")
    if navigationController != nil{
        if myVC != nil {
            navigationController!.pushViewController(myVC!, animated: true)
        }else{
            errorLabel.text = "Unable to find myVC"
        }
    }else{
        errorLabel.text = "Unable to find navigationController"
    }
}else{
    errorLabel.text = "Unable to find storyboard"
}

-> This piece of code is not the best way to debug but it would help you to have visual answers to your problem.


问:
how to do Good SDK 3.1.0 integration with Xcode 8.3.2?
I have installed xcode v8.3.2 and trying to integrate good sdk v3.1.0, but I am unable to do so. When I went through release notes I found that this latest version will not support to Xcode 8.3 and later versions. But one of my colleagues is able to use the latest version of good sdk with Xcode 8.3.1 without any issue. How can we resolve this?</p>

答: As you need to install Xcode and good sdk in the applications folder on the system.This is the way it worked for me.</p>


问:
Setting up @RequestBody when sending a JSON-body containing object of object and arrays
My json object that is sent to backend looks like this:

```<code>{
   "reportAccess":{
      "report":{
         "id":70,
         "reportName":"Test Rapport",
         "created":"2017-06-01",
         "description":"Test report",
         "modifiedDate":"2017-06-01T12:10:00.000+0000",
         "modifiedBy":"111111"
      },
      "accessGroup":{
         "id":1,
         "accessName":"Administrator"
      },
      "validFromDate":"2017-07-24",
      "validToDate":"2017-07-30"
   },
   "users":[
      {
         "id":111111,
         "employeeNumber":"123456",
         "firstName":"Test1",
         "lastName":"Test11",
         "windowsId":"t1234567"
      },
      {
         "id":222222,
         "employeeNumber":"7891011",
         "firstName":"Test2",
         "lastName":"Test22",
         "windowsId":"t7891011"
      }
   ]
}
</code>```

The frontend post call:

```<code>function addAccessForMultipleAgents(access, users) {
            var holderWrapper = {
                reportAccess: access,
                users: users
            };
            return utils.post('/api/v1/reportAccesses/all', holderWrapper);
        }
</code>```

Backend, I have a wrapper Object that looks like this:

HolderWrapper.java

```<code>public class HolderWrapper {
    private List<User> users;
    private ReportAccessCustom reportAccess;

    public HolderWrapper() {
    }

    public HolderWrapper(List<User> users, ReportAccessCustom reportAccess) {
        this.users = users;
        this.reportAccess = reportAccess;
    }

    public List<User> getUsers() {
        return users;
    }

    public ReportAccessCustom getReportAccess() {
        return reportAccess;
    }

    @Override
    public String toString() {
        return "HolderWrapper{" +
                "users=" + users +
                ", reportAccess=" + reportAccess +
                '}';
    }
}
</code>```

ReportAccessCustom.java

```<code>public class ReportAccessCustom {
    private Report report;
    private AccessGroup accessGroup;
    private Date validFromDate;
    private Date validToDate;

    public Report getReport() {
        return report;
    }

    public AccessGroup getAccessGroup() {
        return accessGroup;
    }

    public Date getValidFromDate() {
        return validFromDate;
    }

    public Date getValidToDate() {
        return validToDate;
    }
}
</code>```

And the code that handles the POST-request:

```<code>@RequestMapping(value = "", method = RequestMethod.POST)
    public List<ReportAccess> createMultipleAccesses(@RequestBody Map<String, Object> holderWrapper) {
        List<ReportAccess> response = new ArrayList<>();

        HolderWrapper hw = new HolderWrapper((ArrayList<User>) holderWrapper.get("users"), (ReportAccessCustom) holderWrapper.get("reportAccess"));
        List<User> users = hw.getUsers();
        ReportAccessCustom reportAccessCustom = hw.getReportAccess();

      //rest of code..
        return response;
    }
</code>```

All this leaves me with the error-message:

```<code>java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.tn.reportaccess.ReportAccessCustom
</code>```

Any help as to why this fail would be much appreciated.

答:
There is a typo in your payload. It has a double { for reportAccess:

```<code>{
    "reportAccess": {
        {                 <--- REMOVE THIS AND ...
          "report": {
            "id": 70,
            ...
          },
          "accessGroup": {
            "id": 1,
            ...
          },
          "validFromDate": "2017-07-24",
          "validToDate": "2017-07-30"
        }                <--- ... THIS ONE TOO
    },
    "users": [
        {
            "id": 111111,
            ...
        },
        {
            "id": 222222,
            ...
        }
    ]
}
</code>```

BTW, you do not need to use a Map for your request body, you could use HolderWrapper directly:

```<code>@RequestMapping(value = "", method = RequestMethod.POST)
    public List<ReportAccess> createMultipleAccesses(@RequestBody HolderWrapper holderWrapper) {
   ....
}
</code>```

Body:
My json object that is sent to backend looks like this:

{
   "reportAccess":{
      "report":{
         "id":70,
         "reportName":"Test Rapport",
         "created":"2017-06-01",
         "description":"Test report",
         "modifiedDate":"2017-06-01T12:10:00.000+0000",
         "modifiedBy":"111111"
      },
      "accessGroup":{
         "id":1,
         "accessName":"Administrator"
      },
      "validFromDate":"2017-07-24",
      "validToDate":"2017-07-30"
   },
   "users":[
      {
         "id":111111,
         "employeeNumber":"123456",
         "firstName":"Test1",
         "lastName":"Test11",
         "windowsId":"t1234567"
      },
      {
         "id":222222,
         "employeeNumber":"7891011",
         "firstName":"Test2",
         "lastName":"Test22",
         "windowsId":"t7891011"
      }
   ]
}

The frontend post call:

function addAccessForMultipleAgents(access, users) {
            var holderWrapper = {
                reportAccess: access,
                users: users
            };
            return utils.post('/api/v1/reportAccesses/all', holderWrapper);
        }

Backend, I have a wrapper Object that looks like this:

HolderWrapper.java

public class HolderWrapper {
    private List<User> users;
    private ReportAccessCustom reportAccess;

    public HolderWrapper() {
    }

    public HolderWrapper(List<User> users, ReportAccessCustom reportAccess) {
        this.users = users;
        this.reportAccess = reportAccess;
    }

    public List<User> getUsers() {
        return users;
    }

    public ReportAccessCustom getReportAccess() {
        return reportAccess;
    }

    @Override
    public String toString() {
        return "HolderWrapper{" +
                "users=" + users +
                ", reportAccess=" + reportAccess +
                '}';
    }
}

ReportAccessCustom.java

public class ReportAccessCustom {
    private Report report;
    private AccessGroup accessGroup;
    private Date validFromDate;
    private Date validToDate;

    public Report getReport() {
        return report;
    }

    public AccessGroup getAccessGroup() {
        return accessGroup;
    }

    public Date getValidFromDate() {
        return validFromDate;
    }

    public Date getValidToDate() {
        return validToDate;
    }
}

And the code that handles the POST-request:

@RequestMapping(value = "", method = RequestMethod.POST)
    public List<ReportAccess> createMultipleAccesses(@RequestBody Map<String, Object> holderWrapper) {
        List<ReportAccess> response = new ArrayList<>();

        HolderWrapper hw = new HolderWrapper((ArrayList<User>) holderWrapper.get("users"), (ReportAccessCustom) holderWrapper.get("reportAccess"));
        List<User> users = hw.getUsers();
        ReportAccessCustom reportAccessCustom = hw.getReportAccess();

      //rest of code..
        return response;
    }

All this leaves me with the error-message:

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.tn.reportaccess.ReportAccessCustom

Any help as to why this fail would be much appreciated.

Body:
There is a typo in your payload. It has a double { for reportAccess:

{
    "reportAccess": {
        {                 <--- REMOVE THIS AND ...
          "report": {
            "id": 70,
            ...
          },
          "accessGroup": {
            "id": 1,
            ...
          },
          "validFromDate": "2017-07-24",
          "validToDate": "2017-07-30"
        }                <--- ... THIS ONE TOO
    },
    "users": [
        {
            "id": 111111,
            ...
        },
        {
            "id": 222222,
            ...
        }
    ]
}

BTW, you do not need to use a Map for your request body, you could use HolderWrapper directly:

@RequestMapping(value = "", method = RequestMethod.POST)
    public List<ReportAccess> createMultipleAccesses(@RequestBody HolderWrapper holderWrapper) {
   ....
}


问:
Better way of finding combination for 3 boolean variables
I have 3 bool variables x,y,z. Now at any given moment I can have one out of 2^3=8 combinations as below.

e.g. x=true, y=false and z=false or
x=false, y=true and z=true  and so on.

If I see from programming perspective there are 8 cases or may be 8 or greater if else statement to determine what is the combination at that moment.
At any given moment if I want to know what combination is present(given the values of x,y,z) How can I know without using if-else ladder, which makes code logic little bulky. Is there any better/simple logic/way to do it.

答:
If you must handle 8 situations separately. You could encode the value of x, y, z in a variable and then do a switch case on that variable. Pseudo code below - </p>

```<code>v = 0
if (x) { v += 4 }
if (y) { v += 2 }
if (z) { v += 1 }

switch (v)
{
  case 0 : // all false
  case 1 : // z is true
  case 2 : // y is true
  case 3 : // z and y are true
  case 4 : // x is true
  ...
}
</code>```

Body:
If you must handle 8 situations separately. You could encode the value of x, y, z in a variable and then do a switch case on that variable. Pseudo code below -

v = 0
if (x) { v += 4 }
if (y) { v += 2 }
if (z) { v += 1 }

switch (v)
{
  case 0 : // all false
  case 1 : // z is true
  case 2 : // y is true
  case 3 : // z and y are true
  case 4 : // x is true
  ...
}


问:
Convert from BitArray to Byte
I have a BitArray with the length of 8, and I need a function to convert it to a byte. How to do it?

Specifically, I need a correct function of ConvertToByte:

```<code>BitArray bit = new BitArray(new bool[]
{
    false, false, false, false,
    false, false, false, true
});

//How to write ConvertToByte
byte myByte = ConvertToByte(bit);
var recoveredBit = new BitArray(new[] { myByte });
Assert.AreEqual(bit, recoveredBit);
</code>```

答:
In addition to @JonSkeet's answer you can use an Extension Method as below:

```<code>public static byte ToByte(this BitArray bits)
{
    if (bits.Count != 8)
    {
        throw new ArgumentException("bits");
    }
    byte[] bytes = new byte[1];
    bits.CopyTo(bytes, 0);
    return bytes[0];
}
</code>```

And use like:

```<code>BitArray foo = new BitArray(new bool[]
{
    false, false, false, false,false, false, false, true
});

foo.ToByte();
</code>```

OwnerDisplayName: Ngu Soon Hui

Title: Convert from BitArray to Byte

Body:
I have a BitArray with the length of 8, and I need a function to convert it to a byte. How to do it?

Specifically, I need a correct function of ConvertToByte:

BitArray bit = new BitArray(new bool[]
{
    false, false, false, false,
    false, false, false, true
});

//How to write ConvertToByte
byte myByte = ConvertToByte(bit);
var recoveredBit = new BitArray(new[] { myByte });
Assert.AreEqual(bit, recoveredBit);

Body:
In addition to @JonSkeet's answer you can use an Extension Method as below:

public static byte ToByte(this BitArray bits)
{
    if (bits.Count != 8)
    {
        throw new ArgumentException("bits");
    }
    byte[] bytes = new byte[1];
    bits.CopyTo(bytes, 0);
    return bytes[0];
}

And use like:

BitArray foo = new BitArray(new bool[]
{
    false, false, false, false,false, false, false, true
});

foo.ToByte();

ContentLicense: CC BY-SA 4.0


问:
Are there any good 3rd party GUI products for Python?
In .Net you have companies like DevEpxress, and Infragistics that offer a range of GUI widgets.  Is there any market like that for Python GUI widgets?  I'm thinking specifically about widgets like the DevExpress xtraGrid Suite.

Edit 01-16-09:  For Example:

http://www.devexpress.com/Downloads/NET/OnlineDemos.xml
http://demos.devexpress.com/ASPxGridViewDemos/

http://www.infragistics.com/products/default.aspx

答:
Heaps of GUI apis are available. PyQT, PtGTK, Tkinter... </p>

<p>-T</p>

OwnerDisplayName: mchean

LastEditorDisplayName: mchean

Body:
Heaps of GUI apis are available. PyQT, PtGTK, Tkinter...

-T


Title: Nested if and Formula

Body:
Try this formula in F2 cell

=IF(AND(E2="Epyllion",J2=9),".90",
  IF(AND(E2="Epyllion",J2=7),".70",
  IF(AND(E2="Epyllion",J2=5),".50",
  IF(AND(E2="Epyllion",J2=3),".30",""))))


问:
How to pluralize a symbol
I am using doxygen for my Xcode project. It automatically generates links for symbols automatically and it is awesome. However, I need to use plural to keep the sentence grammatically correct. e.g., Persons. But if I add the 's' in the end, it breaks the link.</p>

答: you can add % markdown in between to keep the link. For example Person%s</p>

Title: How to pluralize a symbol


问:
Android Progress Dialog - Activity has leaked window DecorView
I am making post request using Volley and showing progress dialog. It is working fine but when we change orientation right after making post request. The app crashes with

```<code>AndroidRuntime: FATAL EXCEPTION main
java.lang.IllegalArgumentException: View:DecorView@fbad[Starting Verification Process] not attached to window manager
</code>```

Starting Verification Process is the title of Progress dialog.

How can I resolve this issue?

答: first can i show your respective code. otherwise you can make to finish or dismiss your dialog as well.</p>

Body:
I am making post request using Volley and showing progress dialog. It is working fine but when we change orientation right after making post request. The app crashes with

AndroidRuntime: FATAL EXCEPTION main
java.lang.IllegalArgumentException: View:DecorView@fbad[Starting Verification Process] not attached to window manager

Starting Verification Process is the title of Progress dialog.

How can I resolve this issue?


问:
Create dynamic table editable Android Studio
I have a dynamic table where data is downloaded through a web service, how can I edit a cell, or how else do I do this?</p>

```<code>            tabla.agregarCabecera(R.array.cabecera_);
            do {

                String A = c.getString(0);
                String B = c.getString(1);
                String C = c.getString(2);
                String D = c.getString(3);
                String E = c.getString(4);
                String F = c.getString(5);

                ArrayList<String> elementos = new ArrayList<String>();

                elementos.add(A);
                elementos.add(B);
                elementos.add(C);
                elementos.add(D);
                elementos.add(E);
                elementos.add(F);
                tabla.agregarFilaTabla(elementos);
                array.add(A);
            }
</code>```

答:
You are simply putting an arrayList (in which I presume elements are cell content) in a row and expecting the row object to unwind your arraylist and put in the right cells.

Sadly it doesn't works like this.
The best solution to me, seems in this case:

cycling through the array with a generalized for cycle ( perfect for
this situation )

create a cell for every element (since you declared |string|
type, i assume you haven't numbers to manipulate as numbers,    so
you won't need String.valueof() );

ADD the cell to the row;

AND THEN ADD the row to the table;

But since you've already got the data when you declared the strings from A to F, you won't even need to pass in the arrayList, you could put the string directly into cells, adding them into row, and add the row into the table

Body:
I have a dynamic table where data is downloaded through a web service, how can I edit a cell, or how else do I do this?

            tabla.agregarCabecera(R.array.cabecera_);
            do {

                String A = c.getString(0);
                String B = c.getString(1);
                String C = c.getString(2);
                String D = c.getString(3);
                String E = c.getString(4);
                String F = c.getString(5);

                ArrayList<String> elementos = new ArrayList<String>();

                elementos.add(A);
                elementos.add(B);
                elementos.add(C);
                elementos.add(D);
                elementos.add(E);
                elementos.add(F);
                tabla.agregarFilaTabla(elementos);
                array.add(A);
            }


问:
/signalr/hubs 404 (Not Found) in DNN 7.3.4
I am developing a website using DNN 7.3.4. I am signalr in this.
I have executed this script for AUM_DoNotRewriteRegEx.

```<code>IF NOT EXISTS (SELECT * FROM dnn_hostsettings WHERE SettingName = 'AUM_DoNotRewriteRegEx' )

      insert into dnn_hostsettings
        (SettingName
        , SettingValue
        , SettingIsSecure
        , CreatedByUserId
        , CreatedOnDate
        , LastModifiedByUserId
        , LastModifiedOnDate
        )
        values(
        'AUM_DoNotRewriteRegEx'
        ,'/DesktopModules/|/Providers|/LinkClick\.aspx|/SignalR'
        , 0
        , -1
        , GETDATE()
        , -1
        , GETDATE()
        )

    GO

    IF EXISTS (SELECT * FROM dnn_hostsettings WHERE SettingName = 'AUM_DoNotRewriteRegEx' and SettingValue not like '%/signalr%' )

    update dnn_hostsettings
        set settingValue = (select settingValue + '|/signalr' from dnn_hostsettings where settingname = 'AUM_DoNotRewriteRegEx')
    where settingname = 'AUM_DoNotRewriteRegEx'

    GO
</code>```

And in my page

```<code><script type="text/javascript" src='<%=ResolveClientUrl("~/signalr/hubs") %>'></script>

var objHub = $.connection.myHub;
$.connection.hub.start().done(function () {
    //....
})
</code>```

But it's not working every time it's showing this.

答:
After huge R&D I found this

My owin startup class was not starting. I already have these keys in web config for automatically start owin

```<code><add key="owin:AutomaticAppStartup" value="true" />
<add key="owin:appStartup" value="MyNamespace.MyStartupClass" />
</code>```

But owin startup class was not starting after doing this.

Then I found Microsoft.Owin.Host.SystemWeb is responsible for starting owin startup class. And I missed to add this dll in my project. After adding Microsoft.Owin.Host.SystemWeb owin started and register hub routes successfully.

Body:
I am developing a website using DNN 7.3.4. I am signalr in this.
I have executed this script for AUM_DoNotRewriteRegEx.

IF NOT EXISTS (SELECT * FROM dnn_hostsettings WHERE SettingName = 'AUM_DoNotRewriteRegEx' )

      insert into dnn_hostsettings
        (SettingName
        , SettingValue
        , SettingIsSecure
        , CreatedByUserId
        , CreatedOnDate
        , LastModifiedByUserId
        , LastModifiedOnDate
        )
        values(
        'AUM_DoNotRewriteRegEx'
        ,'/DesktopModules/|/Providers|/LinkClick\.aspx|/SignalR'
        , 0
        , -1
        , GETDATE()
        , -1
        , GETDATE()
        )

    GO

    IF EXISTS (SELECT * FROM dnn_hostsettings WHERE SettingName = 'AUM_DoNotRewriteRegEx' and SettingValue not like '%/signalr%' )

    update dnn_hostsettings
        set settingValue = (select settingValue + '|/signalr' from dnn_hostsettings where settingname = 'AUM_DoNotRewriteRegEx')
    where settingname = 'AUM_DoNotRewriteRegEx'

    GO

And in my page

var objHub = $.connection.myHub;
$.connection.hub.start().done(function () {
    //....
})

But it's not working every time it's showing this.

Body:
After huge R&D I found this

My owin startup class was not starting. I already have these keys in web config for automatically start owin

<add key="owin:AutomaticAppStartup" value="true" />
<add key="owin:appStartup" value="MyNamespace.MyStartupClass" />

But owin startup class was not starting after doing this.

Then I found Microsoft.Owin.Host.SystemWeb is responsible for starting owin startup class. And I missed to add this dll in my project. After adding Microsoft.Owin.Host.SystemWeb owin started and register hub routes successfully.


问:
How to do error handling in a REST API with Express middleware routing
Assume we have a REST API with the following route:

app.post("/accounts/:accountId", isAuthorized, isSelf, updateAccount);

Within this scenario, a lot can go wrong. The user could be unauthorized because he is not logged in, or because he is trying to update an account which is not his, or he is missing a required property value. Using middleware you can extract certain validation, so it can be used across multiple routes.

The situation

I am creating a POST to this route, but I do not sent an authorization header. The isAuthorized, successfully captures the error, and instead of calling the next function, it will use a res.send(403) or something. The isSelf and updateAccount function would do something similair.

The problem

I need to manually follow a pattern across all the functions to return a similar error handling. Which is - as a developer - pretty error prone. Since it's fairly easy to mess up conventions when you would need to manage it across all kind of files.

The question

What is the simplest way to manage errors?

Please note that all the middleware functions are custom functions, so they can be written to follow a generalized approach.

答:
I would create functions that contain "test"s that you often run.

Example:

```<code>function test1(req, res){
    if (typeof req.body.value != undefined){
        return true;
    } else {
        return false;
    }
}
</code>```

Body:
I would create functions that contain "test"s that you often run.

Example:

function test1(req, res){
    if (typeof req.body.value != undefined){
        return true;
    } else {
        return false;
    }
}