问:
How to verify a text is present on a webpage for 'n' times
I wanted to verify a text in a webpage exist for  2 times or ‘n’ times. I have used “Page Should Contain” keyword but it says “Pass” when it identifies single occurrence. I don’t want to verify using locator.

Ex: I want to verify the text "Success" is available in a current webpage for 3 times using robot framework

Any inputs/suggesstions would be helpful.

答:
Too bad you don't want to use a locator, as robotframework has a keyword just for that:

```<code>Xpath Should Match X Times  //*[contains(., "Success")]  2
</code>```

The caveat is the locator should not be prepended with xpath= - just straight expression.

The library keyword Page Should Contain does pretty much exactly that, by the way.

And if you want to find how many times the string is present in the page - easy:

```<code>${count}=  Get Matching Xpath Count  //*[contains(., "Success")]
</code>```

And then do any kind of checks on the result, e.g.

```<code>Should Be Equal      ${count}      2
</code>```

Body:
Too bad you don't want to use a locator, as robotframework has a keyword just for that:

Xpath Should Match X Times  //*[contains(., "Success")]  2

The caveat is the locator should not be prepended with xpath= - just straight expression.

The library keyword Page Should Contain does pretty much exactly that, by the way.

And if you want to find how many times the string is present in the page - easy:

${count}=  Get Matching Xpath Count  //*[contains(., "Success")]

And then do any kind of checks on the result, e.g.

Should Be Equal      ${count}      2


来源: stackexchange

问:
Checking for empty or null List<string>
I have a List where sometimes it is empty or null. I want to be able to check if it contains any List-item and if not then add an object to the List.</p>

```<code> // I have a list, sometimes it doesn't have any data added to it
    var myList = new List<object>();
 // Expression is always false
    if (myList == null)
        Console.WriteLine("List is never null");
    if (myList[0] == null)
        myList.Add("new item");
    //Errors encountered:  Index was out of range. Must be non-negative and less than the size of the collection.
    // Inner Exception says "null"
</code>```

答:
For anyone who doesn't have the guarantee that the list will not be null, you can use the null-conditional operator to safely check for null and empty lists in a single conditional statement:

```<code>if (list?.Any() != true)
{
    // Handle null or empty list
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Checking for empty or null List<string>

Body:
I have a List where sometimes it is empty or null. I want to be able to check if it contains any List-item and if not then add an object to the List.

 // I have a list, sometimes it doesn't have any data added to it
    var myList = new List<object>();
 // Expression is always false
    if (myList == null)
        Console.WriteLine("List is never null");
    if (myList[0] == null)
        myList.Add("new item");
    //Errors encountered:  Index was out of range. Must be non-negative and less than the size of the collection.
    // Inner Exception says "null"

Body:
For anyone who doesn't have the guarantee that the list will not be null, you can use the null-conditional operator to safely check for null and empty lists in a single conditional statement:

if (list?.Any() != true)
{
    // Handle null or empty list
}

ContentLicense: CC BY-SA 3.0


问:
C: Passing an arbitrary sized array to a function
I am attempting to write a C program which reads input from a text file and puts it into a 2D-array where Rows are lines and columns are characters.

However I am confused after reading the following article:

http://c-faq.com/aryptr/pass2dary.html

The function definition which I am thinking of is

```<code>int processArray(char **text) {
    ...
    ...
}
</code>```

where I am attempting to pass in a pointer to a 2D array whose dimensions I don't know until runtime. I would like to be able to access the elements using two square brackets [] []

However in the link it says the following:

An intermediate pointer would have to be used when attempting to call
  it with a two-dimensional array:

```<code>extern g(int **ipp);
int *ip = &array[0][0];
g(&ip);       /* PROBABLY WRONG */
</code>```

but this usage
  is misleading and almost certainly incorrect, since the array has been
  ``flattened'' (its shape has been lost).

What is wrong with the above declaration?

How should you define an array to multiple dimensions?

答:
Leaving aside VLAs you can use a simple pointer to point your matrix:</p>

```<code>#include "stdio.h"

#define MAX_ROWS 2
#define MAX_COLS 2

void test (int *matrix, int col_max, int row_max)
{
    for (int i=0; i<row_max; i++)
    {
        for (int j=0; j<col_max; j++)
        {
            printf("matrix[%d][%d]= %d\n", i, j, *(matrix+(i*col_max)+j) );
        }
    }

}
int main(void)
{
    int matrix[MAX_ROWS][MAX_COLS] = { {1,2}, {3,4} };

    test(&matrix[0][0], MAX_ROWS, MAX_COLS);

    return 0;
}
</code>```

Body:
I am attempting to write a C program which reads input from a text file and puts it into a 2D-array where Rows are lines and columns are characters.

However I am confused after reading the following article:

http://c-faq.com/aryptr/pass2dary.html

The function definition which I am thinking of is

int processArray(char **text) {
    ...
    ...
}

where I am attempting to pass in a pointer to a 2D array whose dimensions I don't know until runtime. I would like to be able to access the elements using two square brackets [] []

However in the link it says the following:

An intermediate pointer would have to be used when attempting to call
  it with a two-dimensional array:

extern g(int **ipp);
int *ip = &array[0][0];
g(&ip);       /* PROBABLY WRONG */

but this usage
  is misleading and almost certainly incorrect, since the array has been
  ``flattened'' (its shape has been lost).

What is wrong with the above declaration?

How should you define an array to multiple dimensions?

Body:
Leaving aside VLAs you can use a simple pointer to point your matrix:

#include "stdio.h"

#define MAX_ROWS 2
#define MAX_COLS 2

void test (int *matrix, int col_max, int row_max)
{
    for (int i=0; i<row_max; i++)
    {
        for (int j=0; j<col_max; j++)
        {
            printf("matrix[%d][%d]= %d\n", i, j, *(matrix+(i*col_max)+j) );
        }
    }

}
int main(void)
{
    int matrix[MAX_ROWS][MAX_COLS] = { {1,2}, {3,4} };

    test(&matrix[0][0], MAX_ROWS, MAX_COLS);

    return 0;
}


问:
How to check that a string being entered isn't a unique string. Java (SQLite database)
Hi I am new to android development and I am attempting to make an app which stores appointments. My fragments and activities are all fine however I am trying to work out how to check my sqlite database that the string I am trying to enter isn't already stored as a unique string already, any help is much appreciated.

Here is my code for the database so far.

```<code>public class MyDataBase extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 4;
    private static final String DATABASE_NAME = "appointments.db";
    public static final String TABLE_APPOINTMENTS = "appointments";
    public static final String COLUMN_DAY = "day";
    public static final String COLUMN_MONTH = "month";
    public static final String COLUMN_YEAR = "year";
    public static final String COLUMN_TITLE = "title";
    public static final String COLUMN_TIME = "time";
    public static final String COLUMN_DESCRIPTION = "details";

    public MyDataBase(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        String query = "CREATE TABLE " + TABLE_APPOINTMENTS
                + "(" + COLUMN_DAY + " INTEGER, " + COLUMN_MONTH + " INTEGER, " + COLUMN_YEAR + " INTEGER, "
                + COLUMN_TITLE + " TEXT NOT NULL UNIQUE, " + COLUMN_TIME + " TEXT, " + COLUMN_DESCRIPTION + " TEXT" + ")";
        db.execSQL(query);
    }

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

    public void addAppointment(Appointment app){
        SQLiteDatabase db = getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(COLUMN_DAY, app.get_day());
        values.put(COLUMN_MONTH, app.get_month());
        values.put(COLUMN_YEAR, app.get_year());
        values.put(COLUMN_TITLE, app.get_title()); // need to check that string being entered isn't already a unique entry
        values.put(COLUMN_TIME, app.get_time());
        values.put(COLUMN_DESCRIPTION, app.get_details());
        db.insert(TABLE_APPOINTMENTS, null, values);
        db.close();
    }

}
</code>```

答:
Call this method and check return true mean its exist otherwise not.</p>

```<code>public boolean checkAppointmentExist(String name){
        booolean isExist = false;

        String selection = COLUMN_TITLE + " = ? ";
        String[] selectionArgs = new String[]{name};
        Cursor cursor = database.query(TABLE_APPOINTMENTS, null, selection, selectionArgs, null, null, null);
        if (cursor != null) {
            if (cursor.getCount() > 0) {
               isExist = true;
            }
        }

   return isExist;

}

public void addAppointment(Appointment app){

      if(!checkAppointmentExist(app.get_title())){
        SQLiteDatabase db = getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(COLUMN_DAY, app.get_day());
        values.put(COLUMN_MONTH, app.get_month());
        values.put(COLUMN_YEAR, app.get_year());
        values.put(COLUMN_TITLE, app.get_title()); // need to check that string being entered isn't already a unique entry
        values.put(COLUMN_TIME, app.get_time());
        values.put(COLUMN_DESCRIPTION, app.get_details());
        db.insert(TABLE_APPOINTMENTS, null, values);
        db.close();
      }

    }
</code>```

Body:
Hi I am new to android development and I am attempting to make an app which stores appointments. My fragments and activities are all fine however I am trying to work out how to check my sqlite database that the string I am trying to enter isn't already stored as a unique string already, any help is much appreciated.

Here is my code for the database so far.

public class MyDataBase extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 4;
    private static final String DATABASE_NAME = "appointments.db";
    public static final String TABLE_APPOINTMENTS = "appointments";
    public static final String COLUMN_DAY = "day";
    public static final String COLUMN_MONTH = "month";
    public static final String COLUMN_YEAR = "year";
    public static final String COLUMN_TITLE = "title";
    public static final String COLUMN_TIME = "time";
    public static final String COLUMN_DESCRIPTION = "details";

    public MyDataBase(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        String query = "CREATE TABLE " + TABLE_APPOINTMENTS
                + "(" + COLUMN_DAY + " INTEGER, " + COLUMN_MONTH + " INTEGER, " + COLUMN_YEAR + " INTEGER, "
                + COLUMN_TITLE + " TEXT NOT NULL UNIQUE, " + COLUMN_TIME + " TEXT, " + COLUMN_DESCRIPTION + " TEXT" + ")";
        db.execSQL(query);
    }

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

    public void addAppointment(Appointment app){
        SQLiteDatabase db = getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(COLUMN_DAY, app.get_day());
        values.put(COLUMN_MONTH, app.get_month());
        values.put(COLUMN_YEAR, app.get_year());
        values.put(COLUMN_TITLE, app.get_title()); // need to check that string being entered isn't already a unique entry
        values.put(COLUMN_TIME, app.get_time());
        values.put(COLUMN_DESCRIPTION, app.get_details());
        db.insert(TABLE_APPOINTMENTS, null, values);
        db.close();
    }

}

Body:
Call this method and check return true mean its exist otherwise not.

public boolean checkAppointmentExist(String name){
        booolean isExist = false;

        String selection = COLUMN_TITLE + " = ? ";
        String[] selectionArgs = new String[]{name};
        Cursor cursor = database.query(TABLE_APPOINTMENTS, null, selection, selectionArgs, null, null, null);
        if (cursor != null) {
            if (cursor.getCount() > 0) {
               isExist = true;
            }
        }

   return isExist;

}

public void addAppointment(Appointment app){

      if(!checkAppointmentExist(app.get_title())){
        SQLiteDatabase db = getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(COLUMN_DAY, app.get_day());
        values.put(COLUMN_MONTH, app.get_month());
        values.put(COLUMN_YEAR, app.get_year());
        values.put(COLUMN_TITLE, app.get_title()); // need to check that string being entered isn't already a unique entry
        values.put(COLUMN_TIME, app.get_time());
        values.put(COLUMN_DESCRIPTION, app.get_details());
        db.insert(TABLE_APPOINTMENTS, null, values);
        db.close();
      }

    }


问:
iOS Cloudsight error response crashing app
I am executing this code here

```<code>self.cloudSightQuery = [[CloudSightQuery alloc] initWithImage:imageData
                                              atLocation:CGPointZero
                                            withDelegate:self
                                             atPlacemark:nil
                                            withDeviceId:@""];
self.cloudSightQuery.queryDelegate = self;
[self.cloudSightQuery start];
</code>```

However some times it crashes with the following reason

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ImageViewController
  cloudSightQueryDidFail:withError:]: unrecognized selector sent to
  instance 0x100514c40'

First throw call stack:

How am I able to capture this error and show the user a response as opposed to the app crashing?

答:
Have you looked at the backtrace?  You can use the debugger (in XCode) to show a backtrace.

The error itself indicates that there's an invalid method call [ImageViewController cloudSightQueryDidFail:withError:] sent to that instance (0x100514c40).  Considering we're dealing with a delegate pattern, it seems likely that method was just never defined in your parent class and it's required by the protocol.  You'll want to make sure to define that method first and then it should work.

TL;DR - You'll want to add this method to your delegate (self):

```<code>- (void)cloudSightQueryDidFail:(CloudSightQuery *)query withError:(NSError *)error
{
    // TODO: Fill in your logic here
    NSLog(@"query: %@, experienced an error: %@", query, error);
}
</code>```

You can see an example of this at: https://github.com/cloudsight/cloudsight-objc/tree/master/Example-objc

Body:
I am executing this code here

self.cloudSightQuery = [[CloudSightQuery alloc] initWithImage:imageData
                                              atLocation:CGPointZero
                                            withDelegate:self
                                             atPlacemark:nil
                                            withDeviceId:@""];
self.cloudSightQuery.queryDelegate = self;
[self.cloudSightQuery start];

However some times it crashes with the following reason

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ImageViewController
  cloudSightQueryDidFail:withError:]: unrecognized selector sent to
  instance 0x100514c40'

First throw call stack:

How am I able to capture this error and show the user a response as opposed to the app crashing?

Body:
Have you looked at the backtrace?  You can use the debugger (in XCode) to show a backtrace.

The error itself indicates that there's an invalid method call [ImageViewController cloudSightQueryDidFail:withError:] sent to that instance (0x100514c40).  Considering we're dealing with a delegate pattern, it seems likely that method was just never defined in your parent class and it's required by the protocol.  You'll want to make sure to define that method first and then it should work.

TL;DR - You'll want to add this method to your delegate (self):

- (void)cloudSightQueryDidFail:(CloudSightQuery *)query withError:(NSError *)error
{
    // TODO: Fill in your logic here
    NSLog(@"query: %@, experienced an error: %@", query, error);
}

You can see an example of this at: https://github.com/cloudsight/cloudsight-objc/tree/master/Example-objc


问:
How do I create a doPost(e) function in Apps Script project to capture HTTP POST data from web service?
I'm trying to create a script to capture data via HTTP POST from Ejunkie. When someone makes a purchase on ejunkie, they can transmit all the order data via HTTP POST to a common notification url (documentation). I want to capture that data so I can get it into a Google Sheet.

So I've setup a sheet with a doPost(e) function like so:

```<code>// attempt 1
function doPost(e) {
  if(typeof e !== 'undefined')
  Logger.log(e.parameters);
}

// attempt 2
function doPost(e) {
  var data = JSON.stringify(e);
  Logger.log(data);
}
</code>```

which I've published as a Web App with access to anyone, and then entered this script URL as the common notification URL in ejunkie.

I've tried a couple of test transactions, but I'm getting nothing in the Logs.

Any ideas? Thanks in advance for any help.

Here's the ejunkie documentation on this subject.

答:
Could try something like this? Also you might look @ this thread: doPost(e) does not return parameters but doGet(e) does?

function doPost(e) {

  if(typeof e !== 'undefined')
    return ContentService.createTextOutput(JSON.stringify(e.parameter));

}```

Body:
I'm trying to create a script to capture data via HTTP POST from Ejunkie. When someone makes a purchase on ejunkie, they can transmit all the order data via HTTP POST to a common notification url (documentation). I want to capture that data so I can get it into a Google Sheet.

So I've setup a sheet with a doPost(e) function like so:

// attempt 1
function doPost(e) {
  if(typeof e !== 'undefined')
  Logger.log(e.parameters);
}

// attempt 2
function doPost(e) {
  var data = JSON.stringify(e);
  Logger.log(data);
}

which I've published as a Web App with access to anyone, and then entered this script URL as the common notification URL in ejunkie.

I've tried a couple of test transactions, but I'm getting nothing in the Logs.

Any ideas? Thanks in advance for any help.

Here's the ejunkie documentation on this subject.


问:
Bootstrap in xpages
I have Domino Designer version 9.0.1 FP4 installed on my computer. I downloaded an nsf database with xpages and demo bootstrap. How much do I try to load any xpages the error below is displayed in the browser. The library org.openntf.xsp.bootstrap.library is enabled in the xsp property file. Do I have to do any procedure for the bootstrap to work? Does it no longer come in the Domino Designer extension library?

Error 500
HTTP Web Server: Command Not Handled Exception

答:
Whenever you receive an Error 500, to have a good chance of receiving a correct answer, please follow the instructions outputted to the console along with the error, and look in the logs in IBM_TECHNICAL_SUPPORT folder for more details. "Error 500" means "something went wrong". The logs it points to will tell you what went wrong.

One possible cause, is the OpenNTF version of the Extension Library will also need installing on the server you're running the demo bootstrap application on. If you're using Designer local preview, the location DDE installs the plugins for its own use is not the location Designer local preview requires. You'll need to manually copy the features and plugins files into the required location, which I believe is <Notes>\osgi\shared\eclipse\plugins and <Notes>\osgi\shared\eclipse\features.

Title: Bootstrap in xpages


问:
Crystal Report converting value to number with symbol
I have an issue with a Crystal Report that I'm creating.  I am using fields from a database and am pulling in the result value where the analysis field is equal to certain values.
In the condition the first check looks at the analysis field and checks if its equal to "Conf".  The result for this is "<10"
The second check looks at the analysis field and checks if its equal to "Original".  The result for this is "20".

I want the results to display in the order above however with the following basic logic it returns the result of 20.

```<code>if analysis = "conf" then result
else if analysis = "Original" then result
</code>```

I was having this issue with multiple records however solved it by converting both results to numbers (toNumber(Result)).  However this record has the less than symbol contained within the field value which causes the conf result to "be skipped" and will display the original result instead.  I've tried a few things without success.  Here is the code for the condition of where I'm at below.  I fell this is way to complex logic but I've just added to it as I've had ideas and it shows what I've tried.

```<code>if {UNITS} = "CFU_G" then
if {ANALYSIS} = "CONF" and
{RESULT}="" or
{RESULT} = "0" then 0
else if {ANALYSIS} = "CONF"
then if isNumeric({RESULT}) then
tonumber({RESULT}) else
tonumber(Replace ({RESULT}, "<", ""))

else

if {UNITS} = "CFU_G" then
if {ANALYSIS} = "Original" and
{RESULT}="" or
{RESULT} = "0" then 0
else if {ANALYSIS} = "Original"
then if isNumeric({RESULT}) then
tonumber({RESULT}) else
tonumber(Replace ({RESULT}, "<", ""))
</code>```

Thanks,
Tom

答:
This was the solution I came up with.</p>

```<code>Field 1
whileprintingrecords;
stringvar vResult := "";

Field 2
whileprintingrecords;
stringvar vResult;
vResult :=  if {RESULT.UNITS} = "CFU_G"
and {RESULT.ANALYSIS} = "CRA_LIS_ENU_CONF_MPCRAM29"
then {RESULT.FORMATTED_ENTRY}

else if {RESULT.ANALYSIS} = "CRA_LIST_ENU_MPCRAM29"
and {RESULT.UNITS} = "CFU_G"
and vResult = ""
then {RESULT.FORMATTED_ENTRY}

Field 3
whileprintingrecords;
stringvar vResult;
vResult;
</code>```

Body:
I have an issue with a Crystal Report that I'm creating.  I am using fields from a database and am pulling in the result value where the analysis field is equal to certain values.
In the condition the first check looks at the analysis field and checks if its equal to "Conf".  The result for this is "<10"
The second check looks at the analysis field and checks if its equal to "Original".  The result for this is "20".

I want the results to display in the order above however with the following basic logic it returns the result of 20.

if analysis = "conf" then result
else if analysis = "Original" then result

I was having this issue with multiple records however solved it by converting both results to numbers (toNumber(Result)).  However this record has the less than symbol contained within the field value which causes the conf result to "be skipped" and will display the original result instead.  I've tried a few things without success.  Here is the code for the condition of where I'm at below.  I fell this is way to complex logic but I've just added to it as I've had ideas and it shows what I've tried.

if {UNITS} = "CFU_G" then
if {ANALYSIS} = "CONF" and
{RESULT}="" or
{RESULT} = "0" then 0
else if {ANALYSIS} = "CONF"
then if isNumeric({RESULT}) then
tonumber({RESULT}) else
tonumber(Replace ({RESULT}, "<", ""))

else

if {UNITS} = "CFU_G" then
if {ANALYSIS} = "Original" and
{RESULT}="" or
{RESULT} = "0" then 0
else if {ANALYSIS} = "Original"
then if isNumeric({RESULT}) then
tonumber({RESULT}) else
tonumber(Replace ({RESULT}, "<", ""))

Thanks,
Tom

Body:
This was the solution I came up with.

Field 1
whileprintingrecords;
stringvar vResult := "";

Field 2
whileprintingrecords;
stringvar vResult;
vResult :=  if {RESULT.UNITS} = "CFU_G"
and {RESULT.ANALYSIS} = "CRA_LIS_ENU_CONF_MPCRAM29"
then {RESULT.FORMATTED_ENTRY}

else if {RESULT.ANALYSIS} = "CRA_LIST_ENU_MPCRAM29"
and {RESULT.UNITS} = "CFU_G"
and vResult = ""
then {RESULT.FORMATTED_ENTRY}

Field 3
whileprintingrecords;
stringvar vResult;
vResult;


问:
How can I stop a character in pygame from leaving the edge of the screen?
I have created a small program in pygame where the player controls a blue square moving around the screen, but I want to stop the player from moving past the edge of the screen. Here is the code I have so far, how can I do this?</p>

```<code>import pygame

pygame.init()
screen = pygame.display.set_mode((800, 600))
done = False
x = 30
y = 30

clock = pygame.time.Clock()

while not done:
        for event in pygame.event.get():
                if event.type == pygame.QUIT:
                        done = True
                if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                        is_blue = not is_blue

    pressed = pygame.key.get_pressed()
    if pressed[pygame.K_UP]: y -= 5
    if pressed[pygame.K_DOWN]: y += 5
    if pressed[pygame.K_LEFT]: x -= 5
    if pressed[pygame.K_RIGHT]: x += 5

    screen.fill((0, 0, 0))
    color = (0, 128, 255)
    pygame.draw.rect(screen, color, pygame.Rect(x, y, 60, 60))

    pygame.display.flip()
    clock.tick(60)
</code>```

答:
Something like:

```<code>if pressed[pygame.K_UP]:
    if not (y > maxwidth or y < 0):
        y += 5
</code>```

And so on for the others. the maxwidth looks like 600 in your code but I'd put it at the top of your code so you dont keep having to change it in different places.

Body:
I have created a small program in pygame where the player controls a blue square moving around the screen, but I want to stop the player from moving past the edge of the screen. Here is the code I have so far, how can I do this?

import pygame

pygame.init()
screen = pygame.display.set_mode((800, 600))
done = False
x = 30
y = 30

clock = pygame.time.Clock()

while not done:
        for event in pygame.event.get():
                if event.type == pygame.QUIT:
                        done = True
                if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                        is_blue = not is_blue

    pressed = pygame.key.get_pressed()
    if pressed[pygame.K_UP]: y -= 5
    if pressed[pygame.K_DOWN]: y += 5
    if pressed[pygame.K_LEFT]: x -= 5
    if pressed[pygame.K_RIGHT]: x += 5

    screen.fill((0, 0, 0))
    color = (0, 128, 255)
    pygame.draw.rect(screen, color, pygame.Rect(x, y, 60, 60))

    pygame.display.flip()
    clock.tick(60)

Body:
Something like:

if pressed[pygame.K_UP]:
    if not (y > maxwidth or y < 0):
        y += 5

And so on for the others. the maxwidth looks like 600 in your code but I'd put it at the top of your code so you dont keep having to change it in different places.


问:
Scheme using input parameter in inner function
I'm new to Scheme and to functional programming in general.

As part of an exercise, I try to implement a function that that takes a number n and prints line by line first n Fibonacci numbers

The problem is that when the program reaches the recursive call, it doesn't recognize n and so I get contract violation error.

From exploring the web I think I need to use let function in some way but I'm not sure how.

Here's the code:

```<code>(define fibo (lambda (n)
           (if (= n 1)
                 1
                 (if (= n 2)
                   (begin
                     (display "1")
                     (newline)
                     1)
                   (begin
                     (display
                      (+ (fibo (- n 1)) (fibo (- n 2))))
                     )))))
</code>```

And the error I get is:

```<code>contract violation
expected: number?
  given: #<void>
  argument position: 1st
  other arguments...:
</code>```

Thank you

答:
The reason of the error is the fact that fibo is supposed to be a function that returns an integer, while in the second case of the inner if you simply print a value (and display returns #<void>, which is not an integer).

This is immediately clear if you indent properly your code:

```<code>(define fibo
  (lambda (n)
    (if (= n 1)
        1
        (if (= n 2)
            (begin
              (display "1")
              (newline)
              1)
            (begin
              (display (+ (fibo (- n 1)) (fibo (- n 2)))))))))
</code>```

You can note that the first branch of the second if terminates with 1, which is returned, while the second branch returns the result of the display.

If you remove the various display calls (which are not useful since the values printed contains many repetitions), the function produces the correct result:

```<code>(define fibo
  (lambda (n)
    (if (= n 1)
        1
        (if (= n 2)
            1
            (+ (fibo (- n 1)) (fibo (- n 2)))))))
</code>```

Note that it can be rewritten in a more concise form:

```<code>(define fibo
  (lambda (n)
    (if (<= n 2)
        1
        (+ (fibo (- n 1)) (fibo (- n 2))))))
</code>```

Finally, if you want to display all the numbers of Fibonacci until a certain value, you could define a function like:

```<code>(define display-all-fibo
  (lambda (n)
    (define display-fibo
      (lambda (i)
        (if (<= i n)
            (begin
              (display (fibo i))
              (newline)
              (display-fibo (+ i 1)))
            (display "Done!"))))
    (display-fibo 1)))

(display-all-fibo 9)

1
1
2
3
5
8
13
21
34
Done!
</code>```

Body:
I'm new to Scheme and to functional programming in general.

As part of an exercise, I try to implement a function that that takes a number n and prints line by line first n Fibonacci numbers

The problem is that when the program reaches the recursive call, it doesn't recognize n and so I get contract violation error.

From exploring the web I think I need to use let function in some way but I'm not sure how.

Here's the code:

(define fibo (lambda (n)
           (if (= n 1)
                 1
                 (if (= n 2)
                   (begin
                     (display "1")
                     (newline)
                     1)
                   (begin
                     (display
                      (+ (fibo (- n 1)) (fibo (- n 2))))
                     )))))

And the error I get is:

contract violation
expected: number?
  given: #<void>
  argument position: 1st
  other arguments...:

Thank you

Body:
The reason of the error is the fact that fibo is supposed to be a function that returns an integer, while in the second case of the inner if you simply print a value (and display returns #<void>, which is not an integer).

This is immediately clear if you indent properly your code:

(define fibo
  (lambda (n)
    (if (= n 1)
        1
        (if (= n 2)
            (begin
              (display "1")
              (newline)
              1)
            (begin
              (display (+ (fibo (- n 1)) (fibo (- n 2)))))))))

You can note that the first branch of the second if terminates with 1, which is returned, while the second branch returns the result of the display.

If you remove the various display calls (which are not useful since the values printed contains many repetitions), the function produces the correct result:

(define fibo
  (lambda (n)
    (if (= n 1)
        1
        (if (= n 2)
            1
            (+ (fibo (- n 1)) (fibo (- n 2)))))))

Note that it can be rewritten in a more concise form:

(define fibo
  (lambda (n)
    (if (<= n 2)
        1
        (+ (fibo (- n 1)) (fibo (- n 2))))))

Finally, if you want to display all the numbers of Fibonacci until a certain value, you could define a function like:

(define display-all-fibo
  (lambda (n)
    (define display-fibo
      (lambda (i)
        (if (<= i n)
            (begin
              (display (fibo i))
              (newline)
              (display-fibo (+ i 1)))
            (display "Done!"))))
    (display-fibo 1)))

(display-all-fibo 9)

1
1
2
3
5
8
13
21
34
Done!


问:
How to change icon colors in android studio
I downloaded some icons from material.io but they only offer the icons in black.  I saw a youtube video where they use to allow you to choose the color.  Anyway, I am trying to change the colors of the icons to white.  I am not having any luck.  I tried to change the fill color in android studio  but it doesn't work.  Any assistance would be appreciated such as exact code and files to add the code to.  Thanks.</p>

答: You can download white icons from material.io. also look at themes and theme overlays


问:
how to pass array of model from one actvtiy to another in android
```<code>public class DataModel implements Serializable, Parcelable {

    /**  */
    private static final long serialVersionUID = 4861597073026532544L;

    private String cid;
    private String name;

    /**
     * @return the cid
     */
    public String getCid() {
        return cid;
    }

    /**
     * @param cid
     *            the cid to set
     */
    public void setCid(String cid) {
        this.cid = cid;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name
     *            the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    public DataModel(Parcel in) {
        super();
        readFromParcel(in);
    }

    public static final Parcelable.Creator<DataModel> CREATOR = new Parcelable.Creator<DataModel>() {
        public DataModel createFromParcel(Parcel in) {
            return new DataModel(in);
        }

        public DataModel[] newArray(int size) {

            return new DataModel[size];
        }

    };

    public void readFromParcel(Parcel in) {
        String[] result = new String[23];
        in.readStringArray(result);

        this.cid = result[0];
        this.name = result[1];

    }

    public int describeContents() {
        return 0;
    }

    public void writeToParcel(Parcel dest, int flags) {
        dest.writeStringArray(new String[] { this.cid,
                this.name});

    }}
</code>```

this is my Datamodel:

```<code>public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        DataModel _modeDataModel=new DataModel(MainActivity.this);
        _modeDataModel.setCid("1");
        _modeDataModel.setName("Anil");

        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList("channel",(ArrayList<DataModel>) model);
        Intent intent = new Intent(MainActivity.this,SecondActivity.class);
        intent.putExtras(bundle);
        startActivity(intent);

    }

}
</code>```

main activtiy

```<code>public class SecondActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Bundle getBundle = this.getIntent().getExtras();
        List<DataModel> channelsList = getBundle.getParcelableArrayList("channel");
    }
}
</code>```

second actvity

i want to pass data between one activity to another activity from One List but i am unable to set value  model also unable to send one activity to another there is compile time Error is coming please suggest me where am doing mistake and ho to send data from one activity to another ,

答:
Change your MainActivity to this:

```<code>public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        DataModel _modeDataModel=new DataModel();
        _modeDataModel.setCid("1");
        _modeDataModel.setName("Anil");

        ArrayList<DataModel> dataModelList = new ArrayList<>();
        dataModelList.add(_modeDataModel);

        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList("channel",dataModelList);
        Intent intent = new Intent(MainActivity.this,SecondActivity.class);
        intent.putExtras(bundle);
        startActivity(intent);
    }
}
</code>```

and in your DataModel, change String length to 2 in readFromParcel method:-

```<code>public void readFromParcel(Parcel in) {
        String[] result = new String[2];
        in.readStringArray(result);

        this.cid = result[0];
        this.name = result[1];

    }
</code>```

and add an empty parameter constructor to DataModel:-

```<code>public DataModel() {
        super();
    }
</code>```

Body:
public class DataModel implements Serializable, Parcelable {

    /**  */
    private static final long serialVersionUID = 4861597073026532544L;

    private String cid;
    private String name;

    /**
     * @return the cid
     */
    public String getCid() {
        return cid;
    }

    /**
     * @param cid
     *            the cid to set
     */
    public void setCid(String cid) {
        this.cid = cid;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name
     *            the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    public DataModel(Parcel in) {
        super();
        readFromParcel(in);
    }

    public static final Parcelable.Creator<DataModel> CREATOR = new Parcelable.Creator<DataModel>() {
        public DataModel createFromParcel(Parcel in) {
            return new DataModel(in);
        }

        public DataModel[] newArray(int size) {

            return new DataModel[size];
        }

    };

    public void readFromParcel(Parcel in) {
        String[] result = new String[23];
        in.readStringArray(result);

        this.cid = result[0];
        this.name = result[1];

    }

    public int describeContents() {
        return 0;
    }

    public void writeToParcel(Parcel dest, int flags) {
        dest.writeStringArray(new String[] { this.cid,
                this.name});

    }}

this is my Datamodel:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        DataModel _modeDataModel=new DataModel(MainActivity.this);
        _modeDataModel.setCid("1");
        _modeDataModel.setName("Anil");

        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList("channel",(ArrayList<DataModel>) model);
        Intent intent = new Intent(MainActivity.this,SecondActivity.class);
        intent.putExtras(bundle);
        startActivity(intent);

    }

}

main activtiy

public class SecondActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Bundle getBundle = this.getIntent().getExtras();
        List<DataModel> channelsList = getBundle.getParcelableArrayList("channel");
    }
}

second actvity

i want to pass data between one activity to another activity from One List but i am unable to set value  model also unable to send one activity to another there is compile time Error is coming please suggest me where am doing mistake and ho to send data from one activity to another ,

Body:
Change your MainActivity to this:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        DataModel _modeDataModel=new DataModel();
        _modeDataModel.setCid("1");
        _modeDataModel.setName("Anil");

        ArrayList<DataModel> dataModelList = new ArrayList<>();
        dataModelList.add(_modeDataModel);

        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList("channel",dataModelList);
        Intent intent = new Intent(MainActivity.this,SecondActivity.class);
        intent.putExtras(bundle);
        startActivity(intent);
    }
}

and in your DataModel, change String length to 2 in readFromParcel method:-

public void readFromParcel(Parcel in) {
        String[] result = new String[2];
        in.readStringArray(result);

        this.cid = result[0];
        this.name = result[1];

    }

and add an empty parameter constructor to DataModel:-

public DataModel() {
        super();
    }


问:
AngularJS ng-model binding with numerical value
In angularJs ng-model i m binding with some name with ++ operator like

```<code><div ng-app="myApp" ng-controller="myCtrl">
    <input type="text" ng-model="firstname++hkjnh">
    {{firstname+" "+lastname}}
</div>
</code>```

output -> FirstName0
from where 0 comes in text

or

```<code>  <div ng-app="myApp" ng-controller="myCtrl">
        <input type="text" ng-model="+124343">
        {{firstname+" "+lastname}}
    </div>
</code>```

output ->124343

so plese tell me how angular work with these type of things

答:
ng-model="firstname++hkjnh" trying to create an variable with controller as  $scope.firstname++hkjnh, since in js variable name can't hold any type of operator it will generate an error.

here ++ operator trying to evaluate with RHS value which is undefined,hence model value will be uncertain(varies on machine to machine).

In 2nd case model just evaluate the value(only with numeric value).

Body:
In angularJs ng-model i m binding with some name with ++ operator like

    <input type="text" ng-model="firstname++hkjnh">
    {{firstname+" "+lastname}}

output -> FirstName0
from where 0 comes in text

or

        <input type="text" ng-model="+124343">
        {{firstname+" "+lastname}}

output ->124343

so plese tell me how angular work with these type of things


问:
How can i get my Json formate data in ajax success?
Thank you to all of you to providing so much dedicated support

Today i am getting some issue regarding Json string, I am returning some value in json and try to retrieve in Ajax Success but i am not able to get value to the variable

```<code> //Return the value from registration.aspx.cs page
 [WebMethod]
public static string verifyAadhar(string aadharNum)
{

    HttpContext context = HttpContext.Current;

    //try
    //{

    context.Session["aadharNum"] = aadharNum;
    string url = "http://localhost:3787/api/login/login?aadharID=908765478921";
    HttpWebRequest request = HttpWebRequest.CreateHttp(url);

    request.Method = "POST";
    /*Optional*/

    request.KeepAlive = true;
    request.AllowAutoRedirect = false;
    request.Accept = "application/json, text/javascript, */*; q=0.01";
    request.ContentType = "application/json; charset=utf-8"; //"application/x-www-form-urlencoded";
                                                             ///*Optional*/
    string userId = "abc";
    string Passwd = "123456";
    string RequestLink = context.Request.Url.Authority;

    request.Headers.Add(HttpRequestHeader.Authorization, "Basic " + Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes("" + userId + ":" + Passwd + "")));

    using (var streamWriter = new StreamWriter(request.GetRequestStream()))
    {
        //?aadharID = 908765478921
        string json = "{\"aadharID\":\"" + 908765478921 + "\"" +  "\"}";
        streamWriter.Write(json);
        streamWriter.Flush();
        streamWriter.Close();
    }
    //try
    //{
    HttpWebResponse response = request.GetResponse() as HttpWebResponse;

        Stream stream = response.GetResponseStream();
        StreamReader sr = new StreamReader(stream);
        var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        dynamic jsonObject = serializer.DeserializeObject(sr.ReadToEnd());
        response.Close();
        sr.Close();
    return new JavaScriptSerializer().Serialize(new { jsonObject });
    //}
    //catch (Exception ex)
    //{
    //    return ex.Message.ToString();
    //}
}

 //Receiving data here in ajax success
 var verfAadhar = '{"aadharNum":"' + aadharNum + '"}';
 $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "http://localhost:28331/register/registration.aspx/verifyAadhar",
        data: verfAadhar,
        datatype: 'json',
        async: false,
        success: function (data) {

            var objData = jQuery.parseJSON(data);

            $("#fname").val(objData[4]);
        },
        error: function ()
        { console.log('Check your credentials'); }
    });
</code>```

Please tell me how can i get my all in success data are available like [name, fname, dob, gen, mob.

答:
Thank you to all of you guys have got my answer of question.

```<code>success: function (data) {
            var arr = eval("(" + data.d + ")");
            alert(arr.jsonObject.message + "," + arr.jsonObject.error);
            var fatharName = arr.jsonObject.data.fathername;
            alert(fatharName);
</code>```

}

by using that the method i can get my values from json..

Body:
Thank you to all of you to providing so much dedicated support

Today i am getting some issue regarding Json string, I am returning some value in json and try to retrieve in Ajax Success but i am not able to get value to the variable

 //Return the value from registration.aspx.cs page
 [WebMethod]
public static string verifyAadhar(string aadharNum)
{

    HttpContext context = HttpContext.Current;

    //try
    //{

    context.Session["aadharNum"] = aadharNum;
    string url = "http://localhost:3787/api/login/login?aadharID=908765478921";
    HttpWebRequest request = HttpWebRequest.CreateHttp(url);

    request.Method = "POST";
    /*Optional*/

    request.KeepAlive = true;
    request.AllowAutoRedirect = false;
    request.Accept = "application/json, text/javascript, */*; q=0.01";
    request.ContentType = "application/json; charset=utf-8"; //"application/x-www-form-urlencoded";
                                                             ///*Optional*/
    string userId = "abc";
    string Passwd = "123456";
    string RequestLink = context.Request.Url.Authority;

    request.Headers.Add(HttpRequestHeader.Authorization, "Basic " + Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes("" + userId + ":" + Passwd + "")));

    using (var streamWriter = new StreamWriter(request.GetRequestStream()))
    {
        //?aadharID = 908765478921
        string json = "{\"aadharID\":\"" + 908765478921 + "\"" +  "\"}";
        streamWriter.Write(json);
        streamWriter.Flush();
        streamWriter.Close();
    }
    //try
    //{
    HttpWebResponse response = request.GetResponse() as HttpWebResponse;

        Stream stream = response.GetResponseStream();
        StreamReader sr = new StreamReader(stream);
        var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        dynamic jsonObject = serializer.DeserializeObject(sr.ReadToEnd());
        response.Close();
        sr.Close();
    return new JavaScriptSerializer().Serialize(new { jsonObject });
    //}
    //catch (Exception ex)
    //{
    //    return ex.Message.ToString();
    //}
}

 //Receiving data here in ajax success
 var verfAadhar = '{"aadharNum":"' + aadharNum + '"}';
 $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "http://localhost:28331/register/registration.aspx/verifyAadhar",
        data: verfAadhar,
        datatype: 'json',
        async: false,
        success: function (data) {

            var objData = jQuery.parseJSON(data);

            $("#fname").val(objData[4]);
        },
        error: function ()
        { console.log('Check your credentials'); }
    });

Please tell me how can i get my all in success data are available like [name, fname, dob, gen, mob.

Body:
Thank you to all of you guys have got my answer of question.

success: function (data) {
            var arr = eval("(" + data.d + ")");
            alert(arr.jsonObject.message + "," + arr.jsonObject.error);
            var fatharName = arr.jsonObject.data.fathername;
            alert(fatharName);

}

by using that the method i can get my values from json..


问:
java util zip ZipException: duplicate entry
While running the project I'm getting this error

Error:Execution failed for task ':..........'.
  com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: javax/annotation/CheckForNull.class

This is how my app:gradle looks like :

```<code>apply plugin: 'com.android.application'

android {
compileSdkVersion 24
buildToolsVersion "24.0.3"
useLibrary  'org.apache.http.legacy'

defaultConfig {
    applicationId "com.sample.Example"
    minSdkVersion 15
    targetSdkVersion 24
    multiDexEnabled true
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
    }
}
}

dependencies {
compile (project(':library')){
    exclude module: 'support-v4'
}
compile (project(':facebookLib')){
    exclude module: 'support-v4'
}
compile 'com.google.http-client:google-http-client-gson:1.20.0'
compile 'com.google.code.gson:gson:2.4'
compile files('libs/CWAC-SackOfViewsAdapter.jar')
compile files('libs/FlurryAgent.jar')
compile files('libs/google-api-client-1.15.0-rc.jar')
compile files('libs/google-api-client-android-1.15.0-rc.jar')
compile files('libs/google-api-services-androidpublisher-v1-rev15-1.15.0-rc.jar')
compile files('libs/google-http-client-1.15.0-rc.jar')
compile files('libs/google-http-client-android-1.15.0-rc.jar')
compile files('libs/google-http-client-jackson-1.15.0-rc.jar')
compile files('libs/google-http-client-jackson2-1.15.0-rc.jar')
compile files('libs/google-oauth-client-1.15.0-rc.jar')
compile files('libs/google-oauth-client-java6-1.15.0-rc.jar')
compile files('libs/httpmime-4.2.jar')
compile files('libs/in-app-purchasing-1.0.3.jar')
compile files('libs/jackson-core-2.1.3.jar')
compile files('libs/jackson-core-asl-1.9.11.jar')
compile files('libs/json_simple-1.1.jar')
compile files('libs/jsr305-1.3.9.jar')
compile files('libs/picasso-2.1.1.jar')
compile files('libs/signpost-commonshttp4-1.2.1.1.jar')
compile files('libs/signpost-core-1.2.1.1.jar')
compile files('libs/signpost-jetty6-1.2.1.1.jar')
compile files('libs/twitter4j-core-4.0.1.jar')
compile files('libs/amazon-device-messaging-1.0.1.jar')
compile 'com.google.android.gms:play-services:9.6.1'
compile 'com.android.support:appcompat-v7:24.2.1'
compile 'com.android.support:support-v4:24.2.1'
compile 'com.android.support:design:24.2.1'
compile 'com.android.support:recyclerview-v7:24.2.1'
compile 'com.android.support:cardview-v7:24.2.1'
compile 'com.android.support:multidex:1.0.1'
}
</code>```

volley:gradle

```<code>android {
compileSdkVersion 17
buildToolsVersion "24.0.3"

defaultConfig {
    minSdkVersion 8
    targetSdkVersion 8
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
    }
}
}
</code>```

library:gradle

```<code>android {
compileSdkVersion 16
buildToolsVersion "23.0.3"

defaultConfig {
    minSdkVersion 4
    targetSdkVersion 4
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
    }
}
}

dependencies {
compile 'com.android.support:support-v4:18.0.0'
}
</code>```

facebookLib:gradle

```<code>android {
compileSdkVersion 17
buildToolsVersion "24.0.3"

defaultConfig {
    minSdkVersion 8
    targetSdkVersion 8
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
    }
}
}

dependencies {
compile 'com.android.support:support-v4:18.0.0'
}
</code>```

Can someone suggest a way out of this error ?
Thanks in advance.

答:
You could do a dependencies cleanup in Android Studio. When doing this you will find the referenced libraries per module in tree view. In that way you will find which dependencies are generating the duplicate entry error.
Search in your project which files are using o referencing CheckForNull.class. Take note of the package who contain it.

Open the terminal window in your project and excecute the follow command

```<code>gradlew clean app:dependencies
</code>```

Please note that ALL dependencies will be remove and re-downloaded. If you have a lot of gradle libraries it may take a couple of minutes to download again. After that you will find a summary  where you could filter the package you fin. In my case the problem was with the apache.commons package. I do the filter and find something like this:

```<code>+--- com.amazonaws:aws-android-sdk-s3:2.4.0
|    +--- com.amazonaws:aws-android-sdk-core:2.4.0 (*)
|    +--- com.amazonaws:aws-android-sdk-kms:2.4.0
|    |    \--- com.amazonaws:aws-android-sdk-core:2.4.0 (*)
|    +--- org.apache.commons:commons-io:1.3.2
|    |    \--- commons-io:commons-io:1.3.2 -> 2.4
|    +--- commons-io:commons-io:2.4
|    \--- org.bouncycastle:bcprov-jdk16:1.44
</code>```

In my case it was a duplicate entry generated by AWS Android SDK, refered to the commons-io dependency.

Finally, just make the exclusion in your gradle file like this (Remember that in my case it was a diffenrt dependency):

```<code>compile('com.amazonaws:aws-android-sdk-s3:2.4.0')
        {
            exclude group: 'org.apache.commons'
        }
</code>```

Body:
While running the project I'm getting this error

Error:Execution failed for task ':..........'.
  com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: javax/annotation/CheckForNull.class

This is how my app:gradle looks like :

apply plugin: 'com.android.application'

android {
compileSdkVersion 24
buildToolsVersion "24.0.3"
useLibrary  'org.apache.http.legacy'

defaultConfig {
    applicationId "com.sample.Example"
    minSdkVersion 15
    targetSdkVersion 24
    multiDexEnabled true
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
    }
}
}

dependencies {
compile (project(':library')){
    exclude module: 'support-v4'
}
compile (project(':facebookLib')){
    exclude module: 'support-v4'
}
compile 'com.google.http-client:google-http-client-gson:1.20.0'
compile 'com.google.code.gson:gson:2.4'
compile files('libs/CWAC-SackOfViewsAdapter.jar')
compile files('libs/FlurryAgent.jar')
compile files('libs/google-api-client-1.15.0-rc.jar')
compile files('libs/google-api-client-android-1.15.0-rc.jar')
compile files('libs/google-api-services-androidpublisher-v1-rev15-1.15.0-rc.jar')
compile files('libs/google-http-client-1.15.0-rc.jar')
compile files('libs/google-http-client-android-1.15.0-rc.jar')
compile files('libs/google-http-client-jackson-1.15.0-rc.jar')
compile files('libs/google-http-client-jackson2-1.15.0-rc.jar')
compile files('libs/google-oauth-client-1.15.0-rc.jar')
compile files('libs/google-oauth-client-java6-1.15.0-rc.jar')
compile files('libs/httpmime-4.2.jar')
compile files('libs/in-app-purchasing-1.0.3.jar')
compile files('libs/jackson-core-2.1.3.jar')
compile files('libs/jackson-core-asl-1.9.11.jar')
compile files('libs/json_simple-1.1.jar')
compile files('libs/jsr305-1.3.9.jar')
compile files('libs/picasso-2.1.1.jar')
compile files('libs/signpost-commonshttp4-1.2.1.1.jar')
compile files('libs/signpost-core-1.2.1.1.jar')
compile files('libs/signpost-jetty6-1.2.1.1.jar')
compile files('libs/twitter4j-core-4.0.1.jar')
compile files('libs/amazon-device-messaging-1.0.1.jar')
compile 'com.google.android.gms:play-services:9.6.1'
compile 'com.android.support:appcompat-v7:24.2.1'
compile 'com.android.support:support-v4:24.2.1'
compile 'com.android.support:design:24.2.1'
compile 'com.android.support:recyclerview-v7:24.2.1'
compile 'com.android.support:cardview-v7:24.2.1'
compile 'com.android.support:multidex:1.0.1'
}

volley:gradle

android {
compileSdkVersion 17
buildToolsVersion "24.0.3"

defaultConfig {
    minSdkVersion 8
    targetSdkVersion 8
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
    }
}
}

library:gradle

android {
compileSdkVersion 16
buildToolsVersion "23.0.3"

defaultConfig {
    minSdkVersion 4
    targetSdkVersion 4
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
    }
}
}

dependencies {
compile 'com.android.support:support-v4:18.0.0'
}

facebookLib:gradle

android {
compileSdkVersion 17
buildToolsVersion "24.0.3"

defaultConfig {
    minSdkVersion 8
    targetSdkVersion 8
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
    }
}
}

dependencies {
compile 'com.android.support:support-v4:18.0.0'
}

Can someone suggest a way out of this error ?
Thanks in advance.

Body:
You could do a dependencies cleanup in Android Studio. When doing this you will find the referenced libraries per module in tree view. In that way you will find which dependencies are generating the duplicate entry error.
Search in your project which files are using o referencing CheckForNull.class. Take note of the package who contain it.

Open the terminal window in your project and excecute the follow command

gradlew clean app:dependencies

Please note that ALL dependencies will be remove and re-downloaded. If you have a lot of gradle libraries it may take a couple of minutes to download again. After that you will find a summary  where you could filter the package you fin. In my case the problem was with the apache.commons package. I do the filter and find something like this:

+--- com.amazonaws:aws-android-sdk-s3:2.4.0
|    +--- com.amazonaws:aws-android-sdk-core:2.4.0 (*)
|    +--- com.amazonaws:aws-android-sdk-kms:2.4.0
|    |    \--- com.amazonaws:aws-android-sdk-core:2.4.0 (*)
|    +--- org.apache.commons:commons-io:1.3.2
|    |    \--- commons-io:commons-io:1.3.2 -> 2.4
|    +--- commons-io:commons-io:2.4
|    \--- org.bouncycastle:bcprov-jdk16:1.44

In my case it was a duplicate entry generated by AWS Android SDK, refered to the commons-io dependency.

Finally, just make the exclusion in your gradle file like this (Remember that in my case it was a diffenrt dependency):

compile('com.amazonaws:aws-android-sdk-s3:2.4.0')
        {
            exclude group: 'org.apache.commons'
        }


问:
Import nested JSON to MySQL with relations using php
I'm looking for a simple workaround to import an existing nested JSON data into several MySQL tables. JSON does not have bidirectional relations so they should be generated automatically, I think.

Here is a data sample:

```<code>[
    {
        "targetgroup": "Staff",
        "plan": "this field just exists and should be ignored in database",
        "budgetlevel": "Government",
        "spots": 5,
        "edutype": "Bachelor",
        "qualilevel": "Specialist",
        "speciality": "Mathematician",
        "qualification": "Finished",
        "faculty": "Applied mathematics",
        "institute": "this field is sometimes empty in input data",
        "eduform": "Full-time",
        "profiles": [
            "Jr. Arithmetic manager"
        ],
        "entrancetests": [
            {
                "subject": "math",
                "typeoftest": "GOV",
                "minscore": "37",
                "ratingtype": "out of 100"
            },
            {
                "subject": "language",
                "typeoftest": "GOV",
                "minscore": "27",
                "ratingtype": "out of 100"
            },
            {
                "subject": "physics",
                "typeoftest": "GOV",
                "minscore": "40",
                "ratingtype": "out of 100"
            }
        ]
    },
  {
        "targetgroup": "Educational workers",
        "plan": "fridge",
        "budgetlevel": "Legacy",
        "spots": 26,
        "edutype": "Bachelor",
        "qualilevel": "Master",
        "speciality": "Data analysis",
        "qualification": "Finished",
        "faculty": "Machine learning mathematics",
        "institute": "",
        "eduform": "Full-time",
        "profiles": [
            "Head counting manager"
        ],
        "entrancetests": [
            {
                "subject": "Discrete mathematics",
                "typeoftest": "GOV",
                "minscore": "32",
                "ratingtype": "Out of 100"
            },
            {
                "subject": "Algorythm theory",
                "typeoftest": "GOV",
                "minscore": "51",
                "ratingtype": "Out of 100"
            },
            {
                "subject": "Advanced exception catching",
                "typeoftest": "GOV",
                "minscore": "56",
                "ratingtype": "Out of 100"
            }
        ]
    }
]
</code>```

Database structure:

table "dep:"

id(auto increment) | targetgroup | budgetlevel | spots | edutype ... etc, same as JSON field names

table "profiles"

id (relative to corresponding parent block) | name

table "entrancetests":

id (relative to corresponding parent block) | subject | typeoftest | minscore | ratingtype

I have a general idea about how to import non-nested JSON but I have a hard time figuring out how do I add relations, how do I define parent block inside the loop?

答:
Below is a fully functional transactional pdo process for your exact case. I've tested on my server with 3 MyISAM tables that match your structure. Now, it is possible that you are not into pdo at the moment; if not, I hope my offering will compel you to try something new and modernize the way you query your database.

```<code>$json='[
    {
        "targetgroup": "Staff",
        "plan": "this field just exists and should be ignored in database",
        "budgetlevel": "Government",
        "spots": 5,
        "edutype": "Bachelor",
        "qualilevel": "Specialist",
        "speciality": "Mathematician",
        "qualification": "Finished",
        "faculty": "Applied mathematics",
        "institute": "this field is sometimes empty in input data",
        "eduform": "Full-time",
        "profiles": [
            "Jr. Arithmetic manager"
        ],
        "entrancetests": [
            {
                "subject": "math",
                "typeoftest": "GOV",
                "minscore": "37",
                "ratingtype": "out of 100"
            },
            {
                "subject": "language",
                "typeoftest": "GOV",
                "minscore": "27",
                "ratingtype": "out of 100"
            },
            {
                "subject": "physics",
                "typeoftest": "GOV",
                "minscore": "40",
                "ratingtype": "out of 100"
            }
        ]
    },
  {
        "targetgroup": "Educational workers",
        "plan": "fridge",
        "budgetlevel": "Legacy",
        "spots": 26,
        "edutype": "Bachelor",
        "qualilevel": "Master",
        "speciality": "Data analysis",
        "qualification": "Finished",
        "faculty": "Machine learning mathematics",
        "institute": "",
        "eduform": "Full-time",
        "profiles": [
            "Head counting manager"
        ],
        "entrancetests": [
            {
                "subject": "Discrete mathematics",
                "typeoftest": "GOV",
                "minscore": "32",
                "ratingtype": "Out of 100"
            },
            {
                "subject": "Algorythm theory",
                "typeoftest": "GOV",
                "minscore": "51",
                "ratingtype": "Out of 100"
            },
            {
                "subject": "Advanced exception catching",
                "typeoftest": "GOV",
                "minscore": "56",
                "ratingtype": "Out of 100"
            }
        ]
    }
]';

$db=new PDO("mysql:host=yourhost;dbname=yourdbname;charset=utf8","username","password");

try{
    $db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);  // this will deny subsequent queries from being executed if there is an error and permit exception handle at the bottom
    $db->beginTransaction();

    // dep
    $dep_cols=array("targetgroup","budgetlevel","spots",
        "edutype","qualilevel","speciality","qualification",
        "faculty","institute","eduform");  // declare columns
    $dep_keys=array_map(function($v){return ":$v";},$dep_cols);  // build :keys
    $dep_cols=array_combine($dep_keys,$dep_cols);   // assign :keys
    var_export($dep_cols);
    $dep_query="INSERT INTO `dep` (`".implode('`,`',$dep_cols)."`)"; // list columns as csv
    $dep_query.=" VALUES (".implode(',',array_keys($dep_cols)).");";
    echo "<div>$dep_query</div>";
    $stmt_add_dep=$db->prepare($dep_query);

    // profile
    $profile_cols=array('name');
    $profile_query="INSERT INTO `profile` (`id`,`".implode('`,`',$profile_cols)."`)"; // list columns as csv
    $profile_query.=" VALUES (LAST_INSERT_ID(),".implode(',',array_fill(0,sizeof($profile_cols),"?")).");";
    echo "<div>$profile_query</div>";

    // entrancetests
    $entrance_cols=array('subject','typeoftest','minscore','ratingtype');  // declare columns
    $entrance_keys=array_map(function($v){return ":$v";},$entrance_cols);  // build :keys
    $entrance_cols=array_combine($entrance_keys,$entrance_cols);  // assign :keys
    var_export($entrance_cols);
    $entrance_query="INSERT INTO `entrancetests` (`id`,`".implode('`,`',$entrance_cols)."`)"; // list columns as csv
    $entrance_query.=" VALUES (LAST_INSERT_ID(),".implode(',',array_keys($entrance_cols)).");";
    echo "<div>$entrance_query</div>";
    $stmt_add_entrance=$db->prepare($entrance_query);

    foreach(json_decode($json) as $d){
        foreach($dep_cols as $k=>$v){
            $stmt_add_dep->bindValue($k,(property_exists($d,$v)?$d->$v:""));
            echo "<div>$k => {$d->$v}</div>";
        }
        $stmt_add_dep->execute();
        echo "<div>Dep Affected Rows: ",$stmt_add_dep->rowCount(),"</div><br>";

        $stmt_add_profile=$db->prepare($profile_query);
        foreach($d->profiles as $k=>$v){
            $stmt_add_profile->bindValue($k+1,$v);
            echo "<div>",$k+1," => $v</div>";
        }
        $stmt_add_profile->execute();
        echo "<div>Profile Affected Rows: ",$stmt_add_profile->rowCount(),"</div><br>";

        foreach($d->entrancetests as $o){
            foreach($entrance_cols as $k=>$v){
                $stmt_add_entrance->bindValue($k,(property_exists($o,$v)?$o->$v:""));
                echo "<div>$k => {$o->$v}</div>";
            }
        }
        $stmt_add_entrance->execute();
        echo "<div>Entrance Affected Rows: ",$stmt_add_entrance->rowCount(),"</div><br>";
    }

    // $db->commit();  // Only use with InnoDB tables.  MyISAM is auto-commit

}
catch(PDOException $e){
    // $db->rollBack();  // Only works if InnoDB table.  If MyISAM table, it doesn't rollback.
    echo "Error message: {$e->getMessage()}. File: {$e->getFile()}. Line: {$e->getLine()}";
    // do not show these error messages to users when you go live
}
</code>```

As is, this script will stop executing subsequent queries if a query has an error.

Body:
I'm looking for a simple workaround to import an existing nested JSON data into several MySQL tables. JSON does not have bidirectional relations so they should be generated automatically, I think.

Here is a data sample:

[
    {
        "targetgroup": "Staff",
        "plan": "this field just exists and should be ignored in database",
        "budgetlevel": "Government",
        "spots": 5,
        "edutype": "Bachelor",
        "qualilevel": "Specialist",
        "speciality": "Mathematician",
        "qualification": "Finished",
        "faculty": "Applied mathematics",
        "institute": "this field is sometimes empty in input data",
        "eduform": "Full-time",
        "profiles": [
            "Jr. Arithmetic manager"
        ],
        "entrancetests": [
            {
                "subject": "math",
                "typeoftest": "GOV",
                "minscore": "37",
                "ratingtype": "out of 100"
            },
            {
                "subject": "language",
                "typeoftest": "GOV",
                "minscore": "27",
                "ratingtype": "out of 100"
            },
            {
                "subject": "physics",
                "typeoftest": "GOV",
                "minscore": "40",
                "ratingtype": "out of 100"
            }
        ]
    },
  {
        "targetgroup": "Educational workers",
        "plan": "fridge",
        "budgetlevel": "Legacy",
        "spots": 26,
        "edutype": "Bachelor",
        "qualilevel": "Master",
        "speciality": "Data analysis",
        "qualification": "Finished",
        "faculty": "Machine learning mathematics",
        "institute": "",
        "eduform": "Full-time",
        "profiles": [
            "Head counting manager"
        ],
        "entrancetests": [
            {
                "subject": "Discrete mathematics",
                "typeoftest": "GOV",
                "minscore": "32",
                "ratingtype": "Out of 100"
            },
            {
                "subject": "Algorythm theory",
                "typeoftest": "GOV",
                "minscore": "51",
                "ratingtype": "Out of 100"
            },
            {
                "subject": "Advanced exception catching",
                "typeoftest": "GOV",
                "minscore": "56",
                "ratingtype": "Out of 100"
            }
        ]
    }
]

Database structure:

table "dep:"

id(auto increment) | targetgroup | budgetlevel | spots | edutype ... etc, same as JSON field names

table "profiles"

id (relative to corresponding parent block) | name

table "entrancetests":

id (relative to corresponding parent block) | subject | typeoftest | minscore | ratingtype

I have a general idea about how to import non-nested JSON but I have a hard time figuring out how do I add relations, how do I define parent block inside the loop?

Body:
Below is a fully functional transactional pdo process for your exact case. I've tested on my server with 3 MyISAM tables that match your structure. Now, it is possible that you are not into pdo at the moment; if not, I hope my offering will compel you to try something new and modernize the way you query your database.

$json='[
    {
        "targetgroup": "Staff",
        "plan": "this field just exists and should be ignored in database",
        "budgetlevel": "Government",
        "spots": 5,
        "edutype": "Bachelor",
        "qualilevel": "Specialist",
        "speciality": "Mathematician",
        "qualification": "Finished",
        "faculty": "Applied mathematics",
        "institute": "this field is sometimes empty in input data",
        "eduform": "Full-time",
        "profiles": [
            "Jr. Arithmetic manager"
        ],
        "entrancetests": [
            {
                "subject": "math",
                "typeoftest": "GOV",
                "minscore": "37",
                "ratingtype": "out of 100"
            },
            {
                "subject": "language",
                "typeoftest": "GOV",
                "minscore": "27",
                "ratingtype": "out of 100"
            },
            {
                "subject": "physics",
                "typeoftest": "GOV",
                "minscore": "40",
                "ratingtype": "out of 100"
            }
        ]
    },
  {
        "targetgroup": "Educational workers",
        "plan": "fridge",
        "budgetlevel": "Legacy",
        "spots": 26,
        "edutype": "Bachelor",
        "qualilevel": "Master",
        "speciality": "Data analysis",
        "qualification": "Finished",
        "faculty": "Machine learning mathematics",
        "institute": "",
        "eduform": "Full-time",
        "profiles": [
            "Head counting manager"
        ],
        "entrancetests": [
            {
                "subject": "Discrete mathematics",
                "typeoftest": "GOV",
                "minscore": "32",
                "ratingtype": "Out of 100"
            },
            {
                "subject": "Algorythm theory",
                "typeoftest": "GOV",
                "minscore": "51",
                "ratingtype": "Out of 100"
            },
            {
                "subject": "Advanced exception catching",
                "typeoftest": "GOV",
                "minscore": "56",
                "ratingtype": "Out of 100"
            }
        ]
    }
]';

$db=new PDO("mysql:host=yourhost;dbname=yourdbname;charset=utf8","username","password");

try{
    $db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);  // this will deny subsequent queries from being executed if there is an error and permit exception handle at the bottom
    $db->beginTransaction();

    // dep
    $dep_cols=array("targetgroup","budgetlevel","spots",
        "edutype","qualilevel","speciality","qualification",
        "faculty","institute","eduform");  // declare columns
    $dep_keys=array_map(function($v){return ":$v";},$dep_cols);  // build :keys
    $dep_cols=array_combine($dep_keys,$dep_cols);   // assign :keys
    var_export($dep_cols);
    $dep_query="INSERT INTO `dep` (`".implode('`,`',$dep_cols)."`)"; // list columns as csv
    $dep_query.=" VALUES (".implode(',',array_keys($dep_cols)).");";
    echo "<div>$dep_query</div>";
    $stmt_add_dep=$db->prepare($dep_query);

    // profile
    $profile_cols=array('name');
    $profile_query="INSERT INTO `profile` (`id`,`".implode('`,`',$profile_cols)."`)"; // list columns as csv
    $profile_query.=" VALUES (LAST_INSERT_ID(),".implode(',',array_fill(0,sizeof($profile_cols),"?")).");";
    echo "<div>$profile_query</div>";

    // entrancetests
    $entrance_cols=array('subject','typeoftest','minscore','ratingtype');  // declare columns
    $entrance_keys=array_map(function($v){return ":$v";},$entrance_cols);  // build :keys
    $entrance_cols=array_combine($entrance_keys,$entrance_cols);  // assign :keys
    var_export($entrance_cols);
    $entrance_query="INSERT INTO `entrancetests` (`id`,`".implode('`,`',$entrance_cols)."`)"; // list columns as csv
    $entrance_query.=" VALUES (LAST_INSERT_ID(),".implode(',',array_keys($entrance_cols)).");";
    echo "<div>$entrance_query</div>";
    $stmt_add_entrance=$db->prepare($entrance_query);

    foreach(json_decode($json) as $d){
        foreach($dep_cols as $k=>$v){
            $stmt_add_dep->bindValue($k,(property_exists($d,$v)?$d->$v:""));
            echo "<div>$k => {$d->$v}</div>";
        }
        $stmt_add_dep->execute();
        echo "<div>Dep Affected Rows: ",$stmt_add_dep->rowCount(),"</div><br>";

        $stmt_add_profile=$db->prepare($profile_query);
        foreach($d->profiles as $k=>$v){
            $stmt_add_profile->bindValue($k+1,$v);
            echo "<div>",$k+1," => $v</div>";
        }
        $stmt_add_profile->execute();
        echo "<div>Profile Affected Rows: ",$stmt_add_profile->rowCount(),"</div><br>";

        foreach($d->entrancetests as $o){
            foreach($entrance_cols as $k=>$v){
                $stmt_add_entrance->bindValue($k,(property_exists($o,$v)?$o->$v:""));
                echo "<div>$k => {$o->$v}</div>";
            }
        }
        $stmt_add_entrance->execute();
        echo "<div>Entrance Affected Rows: ",$stmt_add_entrance->rowCount(),"</div><br>";
    }

    // $db->commit();  // Only use with InnoDB tables.  MyISAM is auto-commit

}
catch(PDOException $e){
    // $db->rollBack();  // Only works if InnoDB table.  If MyISAM table, it doesn't rollback.
    echo "Error message: {$e->getMessage()}. File: {$e->getFile()}. Line: {$e->getLine()}";
    // do not show these error messages to users when you go live
}

As is, this script will stop executing subsequent queries if a query has an error.


问:
ASP.NET CheckboxList checked values not stored
I'm having a bit of trouble with my CheckBoxList control in ASP.NET - it seems to not store the values that I have checked (?)

This is the test-code I have at the moment:

```<code>for (int i = 0; i < cbMemberTypes.Items.Count; i++)
{
   if (cbMemberTypes.Items[i].Selected)
   {
      // do stuff
   }
}
</code>```

I have tried to output the amount of checked items, but it is always returning 0. I'm rather lost here, because in my other usercontrol, it works perfectly! Any hints on this will be greatly appreciated! :-)

答:
Ditto @Shiraz: check to see if you are binding or setting values in the Page_Load.

Since Page_Load fires before the button click event handler, the control is being rebound each time you click and the users' selection is wiped out. Try wrap it in a if(!IsPostBack) { /* bind CBLlist */ }.

ContentLicense: CC BY-SA 2.5

Body:
I'm having a bit of trouble with my CheckBoxList control in ASP.NET - it seems to not store the values that I have checked (?)

This is the test-code I have at the moment:

for (int i = 0; i < cbMemberTypes.Items.Count; i++)
{
   if (cbMemberTypes.Items[i].Selected)
   {
      // do stuff
   }
}

I have tried to output the amount of checked items, but it is always returning 0. I'm rather lost here, because in my other usercontrol, it works perfectly! Any hints on this will be greatly appreciated! :-)


问:
PHP cURL cannot connect to IIS on local machine
I have a PHP script that tries to connect with an other PHP script located on a IIS installation running on a local machine in my office using the cURL protocol but fails to do so.

Local configuration:
I've opened the port 8789 on the firewall, I made the router redirect correctly to the IP of the machine running IIS and I've set the default port of IIS to 8789.
If I try to connect to the script (93.144.xxx.xxx:8987/curl_response.php) through a browser I get the resulting output so this setup is working correctly.

When I try to run the PHP script on a remote webserver though it gives my either cUrl error (#7): couldn't connect to host or cUrl error (#28): connect() timed out! (I'm trying different webservers)

The curl part of my PHP script is the following:

```<code>$url = 'http://93.144.xxx.xxx:8789/curl_response.php';

$verbose = fopen('php://temp', 'w+');
$curl = curl_init();
curl_setopt ($curl, CURLOPT_VERBOSE, true);
curl_setopt ($curl, CURLOPT_STDERR, $verbose);
curl_setopt ($curl, CURLOPT_URL, $rurl);
curl_setopt ($curl, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt ($curl, CURLOPT_HEADER, 0);
curl_setopt ($curl, CURLOPT_RETURNTRANSFER, false);
curl_setopt ($curl, CURLOPT_PORT , 8789);

$response = curl_exec($curl);

if ($response === FALSE) {
    printf("cUrl error (#%d): %s<br>\n", curl_errno($curl),
           htmlspecialchars(curl_error($curl)));
    rewind($verbose);
    $verboseLog = stream_get_contents($verbose);

    echo "Verbose information:\n```", htmlspecialchars($verboseLog),"```\n";
}else{
    curl_close($curl);
    // trim response (serialized array)
    $response = trim($response);
    // unserialize
    $response = unserialize($response);
    print_r($response);
}
</code>```

I've tried several different CURLOPT_ configurations and I've even tried using a dyndns host instead of the IP, but to no avail.

Is there a IIS configuration to set so it will accept incomming cURL requests or is there a specific header to be sent though cURL?

Thanks.

答:
You have a typo:

```<code>curl_setopt ($curl, CURLOPT_URL, $rurl);
</code>```

Should be:

```<code>curl_setopt ($curl, CURLOPT_URL, $url);
</code>```

Here's an example of a working curl request:

```<code><?php

$url = 'http://thepointless.com:80/';

$curl = curl_init();
curl_setopt ($curl, CURLOPT_VERBOSE, true);
curl_setopt ($curl, CURLOPT_URL, $url);
curl_setopt ($curl, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt ($curl, CURLOPT_HEADER, 0);
curl_setopt ($curl, CURLOPT_RETURNTRANSFER, false);
curl_setopt ($curl, CURLOPT_PORT , 80);

$response = curl_exec($curl);

print $response;

?>
</code>```

It's just like yours, except three things:

It's connecting to port 80

It's not setting STDERR

The typo is fixed

Body:
I have a PHP script that tries to connect with an other PHP script located on a IIS installation running on a local machine in my office using the cURL protocol but fails to do so.

Local configuration:
I've opened the port 8789 on the firewall, I made the router redirect correctly to the IP of the machine running IIS and I've set the default port of IIS to 8789.
If I try to connect to the script (93.144.xxx.xxx:8987/curl_response.php) through a browser I get the resulting output so this setup is working correctly.

When I try to run the PHP script on a remote webserver though it gives my either cUrl error (#7): couldn't connect to host or cUrl error (#28): connect() timed out! (I'm trying different webservers)

The curl part of my PHP script is the following:

$url = 'http://93.144.xxx.xxx:8789/curl_response.php';

$verbose = fopen('php://temp', 'w+');
$curl = curl_init();
curl_setopt ($curl, CURLOPT_VERBOSE, true);
curl_setopt ($curl, CURLOPT_STDERR, $verbose);
curl_setopt ($curl, CURLOPT_URL, $rurl);
curl_setopt ($curl, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt ($curl, CURLOPT_HEADER, 0);
curl_setopt ($curl, CURLOPT_RETURNTRANSFER, false);
curl_setopt ($curl, CURLOPT_PORT , 8789);

$response = curl_exec($curl);

if ($response === FALSE) {
    printf("cUrl error (#%d): %s
\n", curl_errno($curl),
           htmlspecialchars(curl_error($curl)));
    rewind($verbose);
    $verboseLog = stream_get_contents($verbose);

    echo "Verbose information:\n
", htmlspecialchars($verboseLog),"
\n";
}else{
    curl_close($curl);
    // trim response (serialized array)
    $response = trim($response);
    // unserialize
    $response = unserialize($response);
    print_r($response);
}

I've tried several different CURLOPT_ configurations and I've even tried using a dyndns host instead of the IP, but to no avail.

Is there a IIS configuration to set so it will accept incomming cURL requests or is there a specific header to be sent though cURL?

Thanks.

Body:
You have a typo:

curl_setopt ($curl, CURLOPT_URL, $rurl);

Should be:

curl_setopt ($curl, CURLOPT_URL, $url);

Here's an example of a working curl request:

<?php

$url = 'http://thepointless.com:80/';

$curl = curl_init();
curl_setopt ($curl, CURLOPT_VERBOSE, true);
curl_setopt ($curl, CURLOPT_URL, $url);
curl_setopt ($curl, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt ($curl, CURLOPT_HEADER, 0);
curl_setopt ($curl, CURLOPT_RETURNTRANSFER, false);
curl_setopt ($curl, CURLOPT_PORT , 80);

$response = curl_exec($curl);

print $response;

?>

It's just like yours, except three things:

It's connecting to port 80

It's not setting STDERR

The typo is fixed


问:
How can one configure Angular2 with a custom index.html location?
I've created an Angular2 application integrated with ASP.NET and served by IIS. This application is to be used by multiple clients and they would like the ability to customize the look and feel of the application to fit their branding. I'm using some aspects of ASP.NET MVC5's framework to make this possible.

The application is working as expected for most things, but I have two big stumbling blocks utilizing the cli that I can't seem to figure out.

Here is the basic folder structure of the application(there are other files and directories, but I'm excluding them as I don't believe they are relevant to the question):

```<code>Solution.sln
Web
  Controllers
  dist
  Models
  src
  Views
    Shared
      _Layout.cshtml
  .angular-cli.json
  package.json
  Web.config
  Global.asax
</code>```

The only relevant update that I've made to my .angular-cli.json file is that I changed the { apps: { index: '' } } value to be "../Views/Shared/_Layout.cshtml" instead of the default "index.html".

When I run ng build from within the Web directory, the application compiles and the correct script tags are placed in the _Layout.cshtml file right before the closing body tag as expected.

I'm not sure if these problems stem from the same root cause. I assume they do which is why I've put both here, but if they seem to be separate questions, I can break them apart.

Issue 1
If I run ng build multiple times, it doesn't remove and replace the script tags it creates in the _Layout.cshtml file as expected, but instead continues to append new script tags before the closing body tag. So if I run ng build twice in development mode, I'll get the same set of script tags in the file twice.

Any ideas as to what I would need to change to get the expected functionality back from ng build?

Issue 2
Now when I run ng build --watch, the build seems to end up in an endless loop. It continues packaging the assets over and over.

Any ideas as to what might be causing the infinite loop and how I can get ng build --watch to work properly with this setup?

I didn't have either of these issues with the index.html file, but unfortunately, I need to use the _Layout.cshtml file as my index file. I can create a custom prebuild npm task to clean up the script tags, but it doesn't seem like I should have to. I have not figured out a work around for the watch task issue.

UPDATE
As I suspected, this has nothing to do with the fact that it is an *.cshtml file, but rather due to the fact that the apps/index location is outside of the src folder.

Steps to reproduce:

npm install @angular/cli

node_modules/.bin/ng new test-custom-index

Movetest-custom-index/src/index.html to test-custom-index/index.html

Update the .angular-cli.json so index property is "index": "../index.html" instead of "index": "index.html"

From the test-custom-index directory run node_modules/.bin/ng build two times consecutively and you will see the duplicate script entries in the index.html file.
OR run node_modules/.bin/ng build --watch and watch it get caught in an infinite loop.

Any help would be greatly appreciated!!!

答:
Currently I have a work around in place that I would like to share if others are experiencing the same issue.

I would still like to know if there is a better way to approach this as it seems a bit hacky to me.

At the same level as the src directory, I created a build directory. In it, I have two files:

prebuild.js

```<code>var fs = require('fs');
var path = require('path');
var inputFilePath = path.join(__dirname, '../Views/Shared/_Layout.cshtml');
var outputFilePath = path.join(__dirname, '../src/_Layout.cshtml');

fs.readFile(inputFilePath, 'utf8', function (err,data) {
  if (err) {
    return console.log(err);
  }
  var result = data.replace(/<\/app-faculty-profile>[\s\S]*<\/body>/g, '</app-faculty-profile>\n\r</body>');

  fs.writeFile(outputFilePath, result, 'utf8', function (err) {
     if (err) return console.log(err);
  });
});
</code>```

postbuild.js

```<code>var fs = require('fs');
var path = require('path');
var inputFilePath = path.join(__dirname, '../dist/_Layout.cshtml');
var outputFilePath = path.join(__dirname, '../Views/Shared/_Layout.cshtml');

fs.readFile(inputFilePath, 'utf8', function (err,data) {
  if (err) {
    return console.log(err);
  }

  fs.writeFile(outputFilePath, data, 'utf8', function (err) {
     if (err) return console.log(err);
  });
});
</code>```

Then in my package.json file I added a few scripts:

```<code>"ng": "ng",
"prebuild": "node build/prebuild.js",
"build": "ng build",
"postbuild": "node build/postbuild.js",
"watch": "npm run build && ng build --watch"
</code>```

Now when I run npm run watch from the command line, it will execute the build script. By convention npm scripts will run the prebuild before it executes the build script and the postbuild script after. The prebuild script removes the script tags from and then copies the _Layout.cshtml file into the src directory. The postbuild script then copies the _Layout.cshtml file back into the location that ASP.NET is expecting it to be in. After all of this the npm script kicks off the ng build command with the --watch flag. This forces the angular build process to execute twice before the watch actually takes effect, but this is the only way I've been able to get this to work so far.

Body:
I've created an Angular2 application integrated with ASP.NET and served by IIS. This application is to be used by multiple clients and they would like the ability to customize the look and feel of the application to fit their branding. I'm using some aspects of ASP.NET MVC5's framework to make this possible.

The application is working as expected for most things, but I have two big stumbling blocks utilizing the cli that I can't seem to figure out.

Here is the basic folder structure of the application(there are other files and directories, but I'm excluding them as I don't believe they are relevant to the question):

Solution.sln
Web
  Controllers
  dist
  Models
  src
  Views
    Shared
      _Layout.cshtml
  .angular-cli.json
  package.json
  Web.config
  Global.asax

The only relevant update that I've made to my .angular-cli.json file is that I changed the { apps: { index: '' } } value to be "../Views/Shared/_Layout.cshtml" instead of the default "index.html".

When I run ng build from within the Web directory, the application compiles and the correct script tags are placed in the _Layout.cshtml file right before the closing body tag as expected.

I'm not sure if these problems stem from the same root cause. I assume they do which is why I've put both here, but if they seem to be separate questions, I can break them apart.

Issue 1
If I run ng build multiple times, it doesn't remove and replace the script tags it creates in the _Layout.cshtml file as expected, but instead continues to append new script tags before the closing body tag. So if I run ng build twice in development mode, I'll get the same set of script tags in the file twice.

Any ideas as to what I would need to change to get the expected functionality back from ng build?

Issue 2
Now when I run ng build --watch, the build seems to end up in an endless loop. It continues packaging the assets over and over.

Any ideas as to what might be causing the infinite loop and how I can get ng build --watch to work properly with this setup?

I didn't have either of these issues with the index.html file, but unfortunately, I need to use the _Layout.cshtml file as my index file. I can create a custom prebuild npm task to clean up the script tags, but it doesn't seem like I should have to. I have not figured out a work around for the watch task issue.

UPDATE
As I suspected, this has nothing to do with the fact that it is an *.cshtml file, but rather due to the fact that the apps/index location is outside of the src folder.

Steps to reproduce:

npm install @angular/cli

node_modules/.bin/ng new test-custom-index

Movetest-custom-index/src/index.html to test-custom-index/index.html

Update the .angular-cli.json so index property is "index": "../index.html" instead of "index": "index.html"

From the test-custom-index directory run node_modules/.bin/ng build two times consecutively and you will see the duplicate script entries in the index.html file.
OR run node_modules/.bin/ng build --watch and watch it get caught in an infinite loop.

Any help would be greatly appreciated!!!

Body:
Currently I have a work around in place that I would like to share if others are experiencing the same issue.

I would still like to know if there is a better way to approach this as it seems a bit hacky to me.

At the same level as the src directory, I created a build directory. In it, I have two files:

prebuild.js

var fs = require('fs');
var path = require('path');
var inputFilePath = path.join(__dirname, '../Views/Shared/_Layout.cshtml');
var outputFilePath = path.join(__dirname, '../src/_Layout.cshtml');

fs.readFile(inputFilePath, 'utf8', function (err,data) {
  if (err) {
    return console.log(err);
  }
  var result = data.replace(/<\/app-faculty-profile>[\s\S]*<\/body>/g, '</app-faculty-profile>\n\r</body>');

  fs.writeFile(outputFilePath, result, 'utf8', function (err) {
     if (err) return console.log(err);
  });
});

postbuild.js

var fs = require('fs');
var path = require('path');
var inputFilePath = path.join(__dirname, '../dist/_Layout.cshtml');
var outputFilePath = path.join(__dirname, '../Views/Shared/_Layout.cshtml');

fs.readFile(inputFilePath, 'utf8', function (err,data) {
  if (err) {
    return console.log(err);
  }

  fs.writeFile(outputFilePath, data, 'utf8', function (err) {
     if (err) return console.log(err);
  });
});

Then in my package.json file I added a few scripts:

"ng": "ng",
"prebuild": "node build/prebuild.js",
"build": "ng build",
"postbuild": "node build/postbuild.js",
"watch": "npm run build && ng build --watch"

Now when I run npm run watch from the command line, it will execute the build script. By convention npm scripts will run the prebuild before it executes the build script and the postbuild script after. The prebuild script removes the script tags from and then copies the _Layout.cshtml file into the src directory. The postbuild script then copies the _Layout.cshtml file back into the location that ASP.NET is expecting it to be in. After all of this the npm script kicks off the ng build command with the --watch flag. This forces the angular build process to execute twice before the watch actually takes effect, but this is the only way I've been able to get this to work so far.


问:
success and failure callbacks in realm xamarin
I am looking for callbacks related to add and read data in realm with xamarin.

Here i am fetching data from server and adding into realm , but i want an event where in i can notify UI that company data has been added to realm successfully and if any error comes i can show that too.

```<code> var content = await response.Content.ReadAsStringAsync();
                    Company company = JsonConvert.DeserializeObject<Company>(content);
                    Realm realm = Realm.GetInstance();
                    await  realm.WriteAsync(tempRealm => {

                        tempRealm.Add(company);

                    });
</code>```

in android native we have following function to execute any transaction in background and can notify for success and failure.

```<code>final Realm realm = Realm.getInstance(App.getRealmConfig());
realm.executeTransactionAsync(new Realm.Transaction() {
    @Override
    public void execute(Realm realm) {

        realm.copyToRealmOrUpdate(userResponseInfo.getCallInfoList());

    }
    }, new Realm.Transaction.OnSuccess() {
    @Override
    public void onSuccess() {

    }
    }, new Realm.Transaction.OnError() {
    @Override
    public void onError(Throwable error) {

    }
    });
</code>```

答:
Realm Xamarin uses the standard .NET mechanism of propagating errors from tasks, which is why you don't need a success and error callbacks. If an error occurred, an exception will be thrown that can be handled in a regular try-catch block:</p>

```<code>try
{
    var realm = Realm.GetInstance();
    await realm.WriteAsync(temp => temp.Add(company));
    // if control reaches this line the transaction executed successfully.
    notifier.NotifySuccess();
}
catch (Exception ex)
{
    // The transaction failed - handle the exception
    notifier.NotifyError(ex.Message);
}
</code>```

Body:
I am looking for callbacks related to add and read data in realm with xamarin.

Here i am fetching data from server and adding into realm , but i want an event where in i can notify UI that company data has been added to realm successfully and if any error comes i can show that too.

 var content = await response.Content.ReadAsStringAsync();
                    Company company = JsonConvert.DeserializeObject<Company>(content);
                    Realm realm = Realm.GetInstance();
                    await  realm.WriteAsync(tempRealm => {

                        tempRealm.Add(company);

                    });

in android native we have following function to execute any transaction in background and can notify for success and failure.

final Realm realm = Realm.getInstance(App.getRealmConfig());
realm.executeTransactionAsync(new Realm.Transaction() {
    @Override
    public void execute(Realm realm) {

        realm.copyToRealmOrUpdate(userResponseInfo.getCallInfoList());

    }
    }, new Realm.Transaction.OnSuccess() {
    @Override
    public void onSuccess() {

    }
    }, new Realm.Transaction.OnError() {
    @Override
    public void onError(Throwable error) {

    }
    });

Body:
Realm Xamarin uses the standard .NET mechanism of propagating errors from tasks, which is why you don't need a success and error callbacks. If an error occurred, an exception will be thrown that can be handled in a regular try-catch block:

try
{
    var realm = Realm.GetInstance();
    await realm.WriteAsync(temp => temp.Add(company));
    // if control reaches this line the transaction executed successfully.
    notifier.NotifySuccess();
}
catch (Exception ex)
{
    // The transaction failed - handle the exception
    notifier.NotifyError(ex.Message);
}