答:
I putted this to fix this problem in the beggining (ob_clean) doesn't change PDF structure:</p>

```<code>require('fpdf/fpdf.php');
ob_clean();
</code>```

Title: FPDF pdf file opening

Body:
"Adobe Reader could not open beacuse it is either not a supported file type"

Php Fpdf file has generate but it not opening via Adobe Reader but opening via browser and other pdf reader, any idea?

function viewfortressmonthly($datese, $location_idnew) {

        $companyid = $_SESSION['companyid'];
        $pieces = explode("-", $location_idnew);
        $location_id = $pieces[0];
        $site_id = $pieces[1];
        $this->selectLocationFromSite($companyid, $site_id, $location_id);
        $monthnumber = substr($datese, 2, 2);
        $monthname = date('F', strtotime("2000-$monthnumber-01"));

        if (substr($datese, 2, 2) == "01" || substr($datese, 2, 2) == "03" || substr($datese, 2, 2) == "05" || substr($datese, 2, 2) == "07" || substr($datese, 2, 2) == "08" || substr($datese, 2, 2) == "10" || substr($datese, 2, 2) == "12") {
            $array_day = array("01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31");
        } else if (substr($datese, 2, 2) == "04" || substr($datese, 2, 2) == "06" || substr($datese, 2, 2) == "09" || substr($datese, 2, 2) == "11") {
            $array_day = array("01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30");
        } else {
            $array_day = array("01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29");
        }
        $array_time = array('00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23');
        $conn = new mysqli($this->dbHost, $this->dbUser, $this->dbPass, $this->dbName) or die('error connect');

        $pdf = new PDF("L", "in", "A4");
        $pdf->SetMargins(.1, .05, .05);
        $pdf->AddFont('gothic', '', 'gothic.php');
        $pdf->AddPage();
        $pdf->SetFillColor(255, 255, 255);
        $pdf->AddFont('UNIVERS0_0', '', 'UNIVERS0_0.php');
        $pdf->SetFont('UNIVERS0_0', 'U', 18);
        $pdf->SetFont('gothic', '', 16);
        $pdf->Cell(7.7, .30, 'PATROL RECORDS-' . "20" . substr($datese, 0, 2) . "-" . substr($datese, 2, 2) . "[" . $monthname . "]", 0, 2, "C", 1);
        $pdf->Cell(7.7, .30, $this->location, 0, 2, "C", 1);
        $pdf->SetFont('gothic', '', 10);
        $pdf->Cell(.36, .25, "D/H", 'LTRB', 0, "C", 1);
        foreach ($array_day as $days) {
            $pdf->Cell(.36, .25, $days, 'LTRB', 0, "C", 1);
        }
        $pdf->Ln();
        $pdf->SetFont('gothic', '', 6);
        for ($i = 0; $i < sizeof($array_time); $i++) {
            $pdf->Cell(.36, .25, $array_time[$i], 'LTRB', 0, "C", 1);
            foreach ($array_day as $days) {
                $datefinal = $datese . $days . $array_time[$i];
                $query2 = "select DATETIME from $this->dbName.$this->dbViewTable where DATETIME LIKE '$datefinal%' AND  COMPANY_ID='$companyid' AND SITE_ID='$site_id' AND LOCATION_ID='$location_id' order by ID DESC LIMIT 1";
                $result = $conn->query($query2);
                $row2 = $result->fetch_assoc();
                $date = $row2['DATETIME'];
                $timec = substr($date, 6, 2) . ":" . substr($date, 8, 2) . ":" . substr($date, 10, 2);
                if ($timec == "::") {
                    $imagefill = "images/colors/bg.png";
                    $pdf->Cell(.36, .25, "" . $pdf->Image($imagefill, $pdf->GetX(), $pdf->GetY(), .36, .25), 'LTBR', 0, 'C');
                } else {
                    $pdf->Cell(.36, .25, $timec, 'LTRB', 0, "C", 1);
                }
            }
            $pdf->Ln();
        }
        ob_clean();
        $pdf->Output("Reports-$location_id-$datese.pdf", 'D');
        $conn->close();
    }

can any one help resolve this problem

Body:
I putted this to fix this problem in the beggining (ob_clean) doesn't change PDF structure:

require('fpdf/fpdf.php');
ob_clean();


来源: stackexchange

问:
jquery clone and add event
I'm trying to clone a "div" and all inside it but one of the events disappear in the cloned div (I'm pretty new to web developing so ... I "cloned" a code found on SO).

The missing event is added with the following javascript:

```<code>var MyClass = document.querySelectorAll(".BtnOptList");
for (var ii = 0; ii < MyClass.length; ii++) {
    MyClass[ii].addEventListener('click', H_S_Btns_Func, false);
}
</code>```

Then, to clone the div, I use the following function:

```<code>$('#btnAddFlds').click(function () {
    //Count "cloned divs" we currently have
    //This will be also used as numeric ID of the new input(s) field(s) (1st have no number)
    var DivNum = $('.SDetails').length;
    // clone() element and update its id(s)
    var newElem2 = $('.SDetails:first').clone().attr('id', function( i, val ) {
                                                            return val + DivNum;
                                                            });
    // manipulate the id values of the input inside the new element
    newElem2.find('input,.BtnOptList,.HideIt').each(function(){
                                        $(this).attr('id', function( i, val ) {
                                                            return val + '_' + DivNum;
                                                            });
                                        });
    //Try to add function (DOESN'T WORK)
    newElem2.find('.BtnOptList').each().addEventListener('click', H_S_Divs_Func, false);

    //I omitted other stuff
});
</code>```

I've already tried clone(true,true) but doesn't worked

答:
This (newElem2.find('.BtnOptList').each().addEventListener('click', H_S_Divs_Func, false);) is not how you use jQuery's each. Have a look at https://api.jquery.com/each/

Spoiler:
newElem2.find('.BtnOptList').each(function(i,e){e.addEventListener('click', H_S_Divs_Func, false)})

PS: Since you're using jQuery, you can use it's own event methods and add the listeners to the whole list:

newElem2.find('.BtnOptList').on('click', H_S_Divs_Func, false)

ContentLicense: CC BY-SA 3.0

Title: jquery clone and add event

Body:
I'm trying to clone a "div" and all inside it but one of the events disappear in the cloned div (I'm pretty new to web developing so ... I "cloned" a code found on SO).

The missing event is added with the following javascript:

var MyClass = document.querySelectorAll(".BtnOptList");
for (var ii = 0; ii < MyClass.length; ii++) {
    MyClass[ii].addEventListener('click', H_S_Btns_Func, false);
}

Then, to clone the div, I use the following function:

$('#btnAddFlds').click(function () {
    //Count "cloned divs" we currently have
    //This will be also used as numeric ID of the new input(s) field(s) (1st have no number)
    var DivNum = $('.SDetails').length;
    // clone() element and update its id(s)
    var newElem2 = $('.SDetails:first').clone().attr('id', function( i, val ) {
                                                            return val + DivNum;
                                                            });
    // manipulate the id values of the input inside the new element
    newElem2.find('input,.BtnOptList,.HideIt').each(function(){
                                        $(this).attr('id', function( i, val ) {
                                                            return val + '_' + DivNum;
                                                            });
                                        });
    //Try to add function (DOESN'T WORK)
    newElem2.find('.BtnOptList').each().addEventListener('click', H_S_Divs_Func, false);

    //I omitted other stuff
});

I've already tried clone(true,true) but doesn't worked


问:
.NET hot deploy/undeploy of bundled code. How to? Which container?
We are new to the .NET world and have built a small C# application on top of Nancy

We are looking for a way to "package" the application code so that we can programmatically hot deploy and undeploy it on top of a minimal Nancy based container (or any other appropriate container you may suggest)

How do we do this in the .NET world ?

In the JVM world, one way to do it is to package a Web Application Resource (war) that is deployed on top of a servlet engine, typically Jetty or Tomcat. There are other solutions (micro-containers, using class loaders directly, etc..). We are looking of an equivalent .NET paradigm.

EDIT Dec 5

There seems to be solutions around building Assemblies and using methods such as Assembly.LoadFromString.

This still seems pretty manual and we are looking for a C# library/framework to help with loading/unloading

答:
You can load your code into separate AppDomain and use shadow copying for hot reload. Suppose you have nancy application like this:

```<code>static void Main(string[] args) {
    using (var host = new NancyHost(new Uri("http://localhost:34455"))) {
        host.Start();
        Console.WriteLine("started");
        Console.ReadKey();
    }
}

public class SampleModule : Nancy.NancyModule {
    public SampleModule() {
        Get["/"] = _ => "Hello World!";
    }
}
</code>```

And you want to be able to update it without restarting hosting process. You can do it like this (warning - non-production ready code, just sample). Create another application like this:

```<code>static void Main() {
    while (true) {
        var setup = new AppDomainSetup();
        setup.ApplicationBase = @"Path to directory with your nancy app";
        setup.ShadowCopyFiles = "true";
        var domain = AppDomain.CreateDomain("Nancy", new Evidence(), setup);
        domain.ExecuteAssembly(@"Path to your nancy app exe");
        AppDomain.Unload(domain);
    }
}
</code>```

Then start your second (host) application. It will create new app domain and start your nancy application in it. Now you can update your nancy application while host application is running (right in that folder - because of shadow copying, files are not locked). To apply updates - press any key in host application. This will tear down app domain with your old version and create new app domain with new version, without restarting process.

Using this technique you can for example watch directory with your application via FileSystemWatcher and replace app domain on changes to application files. You can also minimize downtime by first loading new appdomain to the point before starting your nancy host, then tearing down old app domain and then start nancy host in new app domain.

Body:
You can load your code into separate AppDomain and use shadow copying for hot reload. Suppose you have nancy application like this:

static void Main(string[] args) {
    using (var host = new NancyHost(new Uri("http://localhost:34455"))) {
        host.Start();
        Console.WriteLine("started");
        Console.ReadKey();
    }
}

public class SampleModule : Nancy.NancyModule {
    public SampleModule() {
        Get["/"] = _ => "Hello World!";
    }
}

And you want to be able to update it without restarting hosting process. You can do it like this (warning - non-production ready code, just sample). Create another application like this:

static void Main() {
    while (true) {
        var setup = new AppDomainSetup();
        setup.ApplicationBase = @"Path to directory with your nancy app";
        setup.ShadowCopyFiles = "true";
        var domain = AppDomain.CreateDomain("Nancy", new Evidence(), setup);
        domain.ExecuteAssembly(@"Path to your nancy app exe");
        AppDomain.Unload(domain);
    }
}

Then start your second (host) application. It will create new app domain and start your nancy application in it. Now you can update your nancy application while host application is running (right in that folder - because of shadow copying, files are not locked). To apply updates - press any key in host application. This will tear down app domain with your old version and create new app domain with new version, without restarting process.

Using this technique you can for example watch directory with your application via FileSystemWatcher and replace app domain on changes to application files. You can also minimize downtime by first loading new appdomain to the point before starting your nancy host, then tearing down old app domain and then start nancy host in new app domain.


问:
Launch app from Android Studio stopped to work
There is very weird issue... One time I opened my project and noticed that I don't have opportunity to launch app from studio... Triangle sing cover with black color like it disable

But if I build the apk file and install it with adb command adb install -r path_to_apk it does work.

I have already tried to delete and download new android studio, but nothing changed...

And one more, if I am connecting my device and trying to attach debugger to android process so, android studio doesn't see my device as well as virtual device...

What I need to check? It look like some studio configuration broke or I don't know

Fell free to ask

My plugins

My configuration

答:
The problem "Error: Please select Android SDK" can sometimes happen with Android Studio 3.0, when downloading new build tools.

A temporary workaround is to change the versionCode or versionName in the app/build.gradle, then do a gradle sync, then change it back and gradle sync. See:
Error: Please select Android SDK in Android Studio 2.0


问:
int max = ~0; What does it mean?
int max = ~0;

What does it mean?

答: ~ is the complement operator, which flips the bits of the operand. Since zero has no bits set, the complement will have all bits set, which is also the maximum sized integer (assuming unsigned). For signed numbers, you're going to get -1 instead, so calling it "max" is a bit of a misnomer. </p>

ContentLicense: CC BY-SA 2.5

Title: int max = ~0; What does it mean?

Body:
int max = ~0;

What does it mean?


问:
Table and Synonym of the same table produce different results
In OracleEBS, there are modules like, AP, AR, XLA etc. Each module has its own schema named the same as the corresponding module name. There's also the APPS schema. You can access different tables from different schema via a synonym for that objects created in the APPS schema. For example, there's a table in xla schema named xla.xla_transaction_entities and the table has a synonym in apps schema. That's, the following two select queries should produce identical result set:

```<code>select distinct entity_code from xla.xla_transaction_entities
</code>```

and

```<code>select distinct entity_code from apps.xla_transaction_entities
</code>```

However, the second query produced less results than the first one. Then, I dropped and recreated the apps.xla_transaction_entities synonym. Only after recreating the synonym, the above two queries produced identical result sets.
The question is, why would it happen? What caused the synonym to produce different result set? As far as I know, synonyms are just that - synonyms. As the name implies they should produce the same result set as their corresponding tables.

Edit:
In another test instance, I reproduced the same problem:

```<code>select distinct entity_code from apps.xla_transaction_entities
</code>```

produces the following:

```<code>THIRD_PARTY_MERGE
MANUAL
INTER_ASSET_TRANSACTIONS
TRANSACTIONS
DEPRECIATION
</code>```

```<code>select distinct entity_code from xla.xla_transaction_entities
</code>```

produces the following:

```<code>AP_PAYMENTS
RCV_ACCOUNTING_EVENTS
THIRD_PARTY_MERGE
MANUAL
ADJUSTMENTS
PURCHASE_ORDER
MTL_ACCOUNTING_EVENTS
RECEIPTS
INTER_ASSET_TRANSACTIONS
AP_INVOICES
TRANSACTIONS
DEPRECIATION
</code>```

```<code>  select * from dba_synonyms
  where synonym_name = 'XLA_TRANSACTION_ENTITIES'
</code>```

gives me the following:

```<code>OWNER   SYNONYM_NAME              TABLE_OWNER   TABLE_NAME,               DB_LINK
APPS    XLA_TRANSACTION_ENTITIES  XLA           XLA_TRANSACTION_ENTITIES
</code>```

```<code>select * from dba_synonyms
where TABLE_NAME = 'XLA_TRANSACTION_ENTITIES'
</code>```

outputs the following:

```<code>OWNER    SYNONYM_NAME                   TABLE_OWNER    TABLE_NAME               DB_LINK
APPS     XLA_TRANSACTION_ENTITIES       XLA            XLA_TRANSACTION_ENTITIES
APPS     XLA_TRANSACTION_ENTITIES_UPG   XLA            XLA_TRANSACTION_ENTITIES
</code>```

So, you can see that APPS.XLA_TRANSACTION_ENTITES points to XLA.XLA_TRANSACTION_ENTITIES. And again, once I recreate the synonym, the problem is gone.
The reason why this bothers me so much is because most of the customized reports we have coded used synonyms instead of actual table names. So, I am wondering whether unless I recreate all synonyms in the APPS schema the problem will persist or not.

答:
The xla_transaction_entities table is VPD(Virtual Private Database) enable .

VPD is a security feature which allows user to restrict accessing data from database at database level. Suppose a user is restricted to fetch data from application but he can use tools like SQLPlus to fetch data from table. To restrict this, the security administrator adds a security level(One of 3 types)
does not all the rows/column are fetched .

so instead of using apps.xla_transaction_entities use xla.xla_transaction_entities.

for more info on VPD

Body:
In OracleEBS, there are modules like, AP, AR, XLA etc. Each module has its own schema named the same as the corresponding module name. There's also the APPS schema. You can access different tables from different schema via a synonym for that objects created in the APPS schema. For example, there's a table in xla schema named xla.xla_transaction_entities and the table has a synonym in apps schema. That's, the following two select queries should produce identical result set:

select distinct entity_code from xla.xla_transaction_entities

and

select distinct entity_code from apps.xla_transaction_entities

However, the second query produced less results than the first one. Then, I dropped and recreated the apps.xla_transaction_entities synonym. Only after recreating the synonym, the above two queries produced identical result sets.
The question is, why would it happen? What caused the synonym to produce different result set? As far as I know, synonyms are just that - synonyms. As the name implies they should produce the same result set as their corresponding tables.

Edit:
In another test instance, I reproduced the same problem:

select distinct entity_code from apps.xla_transaction_entities

produces the following:

THIRD_PARTY_MERGE
MANUAL
INTER_ASSET_TRANSACTIONS
TRANSACTIONS
DEPRECIATION

select distinct entity_code from xla.xla_transaction_entities

produces the following:

AP_PAYMENTS
RCV_ACCOUNTING_EVENTS
THIRD_PARTY_MERGE
MANUAL
ADJUSTMENTS
PURCHASE_ORDER
MTL_ACCOUNTING_EVENTS
RECEIPTS
INTER_ASSET_TRANSACTIONS
AP_INVOICES
TRANSACTIONS
DEPRECIATION

  select * from dba_synonyms
  where synonym_name = 'XLA_TRANSACTION_ENTITIES'

gives me the following:

OWNER   SYNONYM_NAME              TABLE_OWNER   TABLE_NAME,               DB_LINK
APPS    XLA_TRANSACTION_ENTITIES  XLA           XLA_TRANSACTION_ENTITIES

select * from dba_synonyms
where TABLE_NAME = 'XLA_TRANSACTION_ENTITIES'

outputs the following:

OWNER    SYNONYM_NAME                   TABLE_OWNER    TABLE_NAME               DB_LINK
APPS     XLA_TRANSACTION_ENTITIES       XLA            XLA_TRANSACTION_ENTITIES
APPS     XLA_TRANSACTION_ENTITIES_UPG   XLA            XLA_TRANSACTION_ENTITIES

So, you can see that APPS.XLA_TRANSACTION_ENTITES points to XLA.XLA_TRANSACTION_ENTITIES. And again, once I recreate the synonym, the problem is gone.
The reason why this bothers me so much is because most of the customized reports we have coded used synonyms instead of actual table names. So, I am wondering whether unless I recreate all synonyms in the APPS schema the problem will persist or not.


问:
Multiple contexts with the same path error running web service in Eclipse using Tomcat
This is the error that I got when I created my first Axis2 web service using Eclipse. After I wrote the class, I created the web service with Apache Axis2. When I click the start server button in eclipse it gives an error message:

Could not publish server configuration for Tomcat v6.0 Server at
  localhost.

  Multiple contexts have a path of "/FirstApache".

FirstApache is the dynamic web project that I created before. I selected the correct web project from the configuration part in the web service wizard.

How can I fix this?

答: If you are using STS and your server is Pivotal Just double click on the server and go to >Modules tab >display Configure the Web Modules on this server.>you can just remove modules and run once again.</p>


问:
HERE Maps Distance to Destination always returns high Value
I had calculated a route in here maps and started Turn-by-Turn Navigation using that route. Everything is working fine in offline and when i tried to calculate the distance to reach the destination using

```<code>double distance = [NMANavigationManager sharedNavigationManager].distanceToDestination;
</code>```

The above method returned value which is very high such as 184467440737095520000. The returned value is always 184467440737095520000 even for different routes. when i referred the navigation manager delegate i found that this method will return values in metres. But even this returned value is too high of my destination's distance..Please guide me how to calculate the distance to my destination correctly..  thanks in advance

```<code>-(void)CalculateRoute:(NMARoutingMode *)routingMode
{

routeManager = [NMARouteManager sharedRouteManager];
routeManager.delegate = self;
NSMutableArray* stopList = [NSMutableArray array];
[stopList addObject:_StartCoordinate];
[stopList addObject:_DestinationCoordinate];

NSLog(@"routing from [%.5f,%.5f] to [%.5f,%.5f]", ((NMAGeoCoordinates*)stopList[0]).latitude, ((NMAGeoCoordinates*)stopList[0]).longitude,
      ((NMAGeoCoordinates*)stopList[1]).latitude, ((NMAGeoCoordinates*)stopList[1]).longitude);
NSLog(@"routingMode===>%@",routingMode.description);

[routeManager calculateRouteWithStops:stopList routingMode:routingMode];
 }

-(IBAction)StartNav:(UIButton*)sender
{
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(positionDidUpdate)
                                             name:NMAPositioningManagerDidUpdatePositionNotification

                                           object:[NMAPositioningManager sharedPositioningManager]];
[NMANavigationManager sharedNavigationManager].map = self.mapView;
[NMANavigationManager sharedNavigationManager].delegate = self;
[NMANavigationManager sharedNavigationManager].mapTrackingAutoZoomEnabled = YES;
[NMANavigationManager sharedNavigationManager].mapTrackingEnabled = YES;
[NMANavigationManager sharedNavigationManager].mapTrackingOrientation = NMAMapTrackingOrientationDynamic;
[NMANavigationManager sharedNavigationManager].speedWarningEnabled = YES;
[NMANavigationManager sharedNavigationManager].mapTrackingTilt = NMAMapTrackingTilt2D;
[[NMANavigationManager sharedNavigationManager]startTurnByTurnNavigationWithRoute:_route];
}
</code>```

答:
You're getting an error when computing the distance. The value 184467440737095520000 is equal to the NMANavigationManagerInvalidValue constant.

Try to compute the distance when your position is updated, so do it in your positionDidUpdate method as you mentioned:

```<code>double distance = [NMANavigationManager sharedNavigationManager].distanceToDestination;
</code>```

If you would like to do it the first time after calling the startTurnByTurnNavigationWithRoute method, you should get such information from the route:

```<code>double distance = _route.length;
</code>```

Btw, if you try to do the same with the timeToArrival, you will get a high value too.

Body:
I had calculated a route in here maps and started Turn-by-Turn Navigation using that route. Everything is working fine in offline and when i tried to calculate the distance to reach the destination using

double distance = [NMANavigationManager sharedNavigationManager].distanceToDestination;

The above method returned value which is very high such as 184467440737095520000. The returned value is always 184467440737095520000 even for different routes. when i referred the navigation manager delegate i found that this method will return values in metres. But even this returned value is too high of my destination's distance..Please guide me how to calculate the distance to my destination correctly..  thanks in advance

-(void)CalculateRoute:(NMARoutingMode *)routingMode
{

routeManager = [NMARouteManager sharedRouteManager];
routeManager.delegate = self;
NSMutableArray* stopList = [NSMutableArray array];
[stopList addObject:_StartCoordinate];
[stopList addObject:_DestinationCoordinate];

NSLog(@"routing from [%.5f,%.5f] to [%.5f,%.5f]", ((NMAGeoCoordinates*)stopList[0]).latitude, ((NMAGeoCoordinates*)stopList[0]).longitude,
      ((NMAGeoCoordinates*)stopList[1]).latitude, ((NMAGeoCoordinates*)stopList[1]).longitude);
NSLog(@"routingMode===>%@",routingMode.description);

[routeManager calculateRouteWithStops:stopList routingMode:routingMode];
 }

-(IBAction)StartNav:(UIButton*)sender
{
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(positionDidUpdate)
                                             name:NMAPositioningManagerDidUpdatePositionNotification

                                           object:[NMAPositioningManager sharedPositioningManager]];
[NMANavigationManager sharedNavigationManager].map = self.mapView;
[NMANavigationManager sharedNavigationManager].delegate = self;
[NMANavigationManager sharedNavigationManager].mapTrackingAutoZoomEnabled = YES;
[NMANavigationManager sharedNavigationManager].mapTrackingEnabled = YES;
[NMANavigationManager sharedNavigationManager].mapTrackingOrientation = NMAMapTrackingOrientationDynamic;
[NMANavigationManager sharedNavigationManager].speedWarningEnabled = YES;
[NMANavigationManager sharedNavigationManager].mapTrackingTilt = NMAMapTrackingTilt2D;
[[NMANavigationManager sharedNavigationManager]startTurnByTurnNavigationWithRoute:_route];
}

Body:
You're getting an error when computing the distance. The value 184467440737095520000 is equal to the NMANavigationManagerInvalidValue constant.

Try to compute the distance when your position is updated, so do it in your positionDidUpdate method as you mentioned:

double distance = [NMANavigationManager sharedNavigationManager].distanceToDestination;

If you would like to do it the first time after calling the startTurnByTurnNavigationWithRoute method, you should get such information from the route:

double distance = _route.length;

Btw, if you try to do the same with the timeToArrival, you will get a high value too.


问:
Showing on console: Slow network is detected. Fallback font will be used while loading
what can I do in this case?
I'm seeing this on my console when ran on the browser the AngularJS App:

Slow network is detected. Fallback font will be used while loading: /bootstrap/dist/fonts/glyphicons-halflings-regular.woff2

I also see the fonts changing while loading.

答: This is a fail safe for chrome to speed up their chromium engine. that way if your website is loading slowly then local font will be used to show your website than later when everything is loaded your original font will appears. as mentioned you can go ahead and disable it chrome://flags/#enable-webfonts-intervention-v2 and you won't see this anymore


问:
Error updating EDMX file
I've seen some other posts about this, but none of the answers seem to help. I'm trying to add a stored procedure to an EDMX. I open the diagram, right-mouse-click, and choose "Update Model from Database." I choose "Yes" for including sensitive data and I uncheck the "Save connection settings in App.config." (This EDMX is inside a class library that's sole purpose is housing this EDMX). I click Next, and choose the "Add" tab. I expand "Stored Procedures and Functions" and then find and click the checkbox for my stored proc. I only check the "Import selected stored procedures and functions into the entity model" and click "Finish." The error I receive is:

```<code>An exception of type 'System.ArgumentException' occurred while attempting to update from the database. The exception message is 'Identifier is null or empty!".
</code>```

I save the diagram. I search the entire solution for the name of my proc, and it only exists in the code that is trying to call it - there is no instance inside the EDMX.

The stored proc definition looks like this:

```<code>ALTER Procedure [dbo].[spGetCountableResult]
    @PatientId BIGINT
AS
</code>```

My connection string looks like this:

```<code><add name="DB_Entities" connectionString="metadata=res://*/Models.DBContext.csdl|res://*/Models.DBContext.ssdl|res://*/Models.DBContext.msl;provider=System.Data.SqlClient;provider connection string="data source=DB.com;initial catalog=MyDb;user id=MyUser;password=MyPassword;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
</code>```

My package.config entry is:

```<code><package id="EntityFramework" version="6.1.3" targetFramework="net45" />
</code>```

Anyone know what's going wrong here?

V

答:
After pending hours I found the solution

There must be some SP with IF EXISTS or related check on some entity which is not present e.g some #tempTable etc.

Make sure that all the objects are available for EF even with NULL values then execute it will work.

For me it was one out of 200+ SPs causing all the trouble.

Title: Error updating EDMX file

Body:
I've seen some other posts about this, but none of the answers seem to help. I'm trying to add a stored procedure to an EDMX. I open the diagram, right-mouse-click, and choose "Update Model from Database." I choose "Yes" for including sensitive data and I uncheck the "Save connection settings in App.config." (This EDMX is inside a class library that's sole purpose is housing this EDMX). I click Next, and choose the "Add" tab. I expand "Stored Procedures and Functions" and then find and click the checkbox for my stored proc. I only check the "Import selected stored procedures and functions into the entity model" and click "Finish." The error I receive is:

An exception of type 'System.ArgumentException' occurred while attempting to update from the database. The exception message is 'Identifier is null or empty!".

I save the diagram. I search the entire solution for the name of my proc, and it only exists in the code that is trying to call it - there is no instance inside the EDMX.

The stored proc definition looks like this:

ALTER Procedure [dbo].[spGetCountableResult]
    @PatientId BIGINT
AS

My connection string looks like this:

<add name="DB_Entities" connectionString="metadata=res://*/Models.DBContext.csdl|res://*/Models.DBContext.ssdl|res://*/Models.DBContext.msl;provider=System.Data.SqlClient;provider connection string="data source=DB.com;initial catalog=MyDb;user id=MyUser;password=MyPassword;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />

My package.config entry is:

<package id="EntityFramework" version="6.1.3" targetFramework="net45" />

Anyone know what's going wrong here?

V


问:
2 Where and 1 Group by Condition LINQ C#
I need to fetch the result of the List by using 2 Where Conditions and GroupBy Condition.

The Query which worked to achive part of the solution is

```<code> var errorQuery = AgentOpList.Where(x => x.LastError != "")
                             .GroupBy(x => x.LastError.Substring(0, 30)).ToArray();
</code>```

But now, i should also include another condition in the list, so the condition is
    x.Status != "FINISHED"
So the final query which i tried was

```<code>var errorQuery = AgentOpList.Where(x => x.LastError != "" || x.Status != "FINISHED")
                            .GroupBy(x => x.LastError.Substring(0, 30)).ToArray();
</code>```

However, it throws me the error

Index and length must refer to a location within the string. Parameter
  name: length

I know the reason for this error. However, i would like to know the solution.

答:
LastError is shorter than 30 characters.

If you're using linq to objects, you could create a new function:

```<code>public bool TakeChars(string str, int chars) {
    if (str.Length < 30) { return str; }
    else return str.Substring(0,30);
}
</code>```

And then use it:

```<code>var errorQuery = AgentOpList.Where(x => x.LastError != "" || x.Status != "FINISHED")
                            .GroupBy(x => TakeChars(x.LastError, 30)).ToArray();
</code>```

If you don't want to create a new function or you're using linq to sql, I think this would work (@FCin):

```<code> var errorQuery = AgentOpList.Where(x => x.LastError != "" || x.Status != "FINISHED")
                                .GroupBy(x => x.LastError.Substring(0, Math.Min(30, x.LastError.Length))).ToArray();
</code>```

Also, a small improvement to your Where:

```<code>var errorQuery = AgentOpList.Where(x => !string.IsNullOrEmpty(x.LastError) || x.Status != "FINISHED")
                                .GroupBy(x => .... ).ToArray();
</code>```

Body:
I need to fetch the result of the List by using 2 Where Conditions and GroupBy Condition.

The Query which worked to achive part of the solution is

 var errorQuery = AgentOpList.Where(x => x.LastError != "")
                             .GroupBy(x => x.LastError.Substring(0, 30)).ToArray();

But now, i should also include another condition in the list, so the condition is
    x.Status != "FINISHED"
So the final query which i tried was

var errorQuery = AgentOpList.Where(x => x.LastError != "" || x.Status != "FINISHED")
                            .GroupBy(x => x.LastError.Substring(0, 30)).ToArray();

However, it throws me the error

Index and length must refer to a location within the string. Parameter
  name: length

I know the reason for this error. However, i would like to know the solution.

Body:
LastError is shorter than 30 characters.

If you're using linq to objects, you could create a new function:

public bool TakeChars(string str, int chars) {
    if (str.Length < 30) { return str; }
    else return str.Substring(0,30);
}

And then use it:

var errorQuery = AgentOpList.Where(x => x.LastError != "" || x.Status != "FINISHED")
                            .GroupBy(x => TakeChars(x.LastError, 30)).ToArray();

If you don't want to create a new function or you're using linq to sql, I think this would work (@FCin):

 var errorQuery = AgentOpList.Where(x => x.LastError != "" || x.Status != "FINISHED")
                                .GroupBy(x => x.LastError.Substring(0, Math.Min(30, x.LastError.Length))).ToArray();

Also, a small improvement to your Where:

var errorQuery = AgentOpList.Where(x => !string.IsNullOrEmpty(x.LastError) || x.Status != "FINISHED")
                                .GroupBy(x => .... ).ToArray();


问:
DividerItemDecoration Horizontal not appearing in center
I am using DividerItemDecoration from support library.

following is code to add decoration

```<code> GridLayoutManager gridLayoutManager = new GridLayoutManager(context, 3);
 recyclerView.setLayoutManager(gridLayoutManager);
 recyclerView.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.HORIZONTAL));
</code>```

But the dividers are not appearing in center horizontally.

Following is screen shot of it.

Following is item layout

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:clickable="true"
android:gravity="center"
android:orientation="vertical"
android:paddingBottom="8dp"
android:paddingTop="8dp">

<ImageView
    android:id="@+id/imgFacility"
    android:layout_width="30dp"
    android:layout_height="30dp"
    android:layout_gravity="center"
    android:foreground="@drawable/page_main_category_home_grid_selector"
    android:gravity="center"
    android:src="@drawable/plane_img"
    android:tint="?colorAccent" />

<TextView
    android:id="@+id/txtFacilityName"
    mediumFontPath="fonts/montserrat-medium.ttf"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginTop="2dp"
    android:ellipsize="end"
    android:gravity="center"
    android:maxLines="2"
    android:minLines="2"
    android:text="Facility\nEWlall"
    android:textColor="#353535"
    android:textSize="12sp"
    tools:ignore="MissingPrefix" />

 </LinearLayout>
</code>```

Also I tried using GridDividerDecoration

Following is output of it

Given background color to each layout this is how it looks

答:
First create class using below code

```<code>public class DividerItemDecoration extends RecyclerView.ItemDecoration {

private static final int[] ATTRS = {android.R.attr.listDivider};

private Drawable mDivider;
private int mInsets;

public DividerItemDecoration(Context context) {
    TypedArray a = context.obtainStyledAttributes(ATTRS);
    mDivider = a.getDrawable(0);
    a.recycle();

    mInsets = 1;
}

@Override
public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
    drawVertical(c, parent);
    drawHorizontal(c, parent);
}

/**
 * Draw dividers at each expected grid interval
 */
public void drawVertical(Canvas c, RecyclerView parent) {
    if (parent.getChildCount() == 0) return;

    final int childCount = parent.getChildCount();

    for (int i = 0; i < childCount; i++) {
        final View child = parent.getChildAt(i);
        final RecyclerView.LayoutParams params =
                (RecyclerView.LayoutParams) child.getLayoutParams();

        final int left = child.getLeft() - params.leftMargin - mInsets;
        final int right = child.getRight() + params.rightMargin + mInsets;
        final int top = child.getBottom() + params.bottomMargin + mInsets;
        final int bottom = top + mDivider.getIntrinsicHeight();
        mDivider.setBounds(left, top, right, bottom);
        mDivider.draw(c);
    }
}

/**
 * Draw dividers to the right of each child view
 */
public void drawHorizontal(Canvas c, RecyclerView parent) {
    final int childCount = parent.getChildCount();

    for (int i = 0; i < childCount; i++) {
        final View child = parent.getChildAt(i);
        final RecyclerView.LayoutParams params =
                (RecyclerView.LayoutParams) child.getLayoutParams();

        final int left = child.getRight() + params.rightMargin + mInsets;
        final int right = left + mDivider.getIntrinsicWidth();
        final int top = child.getTop() - params.topMargin - mInsets;
        final int bottom = child.getBottom() + params.bottomMargin + mInsets;
        mDivider.setBounds(left, top, right, bottom);
        mDivider.draw(c);
    }
}

@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
    //We can supply forced insets for each item view here in the Rect
    outRect.set(mInsets, mInsets, mInsets, mInsets);
}
</code>```

}

After this use this decoration class in your recyclarview like this

```<code>recyclerView.addItemDecoration(new DividerItemDecoration(getActivity()));
</code>```

It help to show vertical and horizontal line between item.

Body:
I am using DividerItemDecoration from support library.

following is code to add decoration

 GridLayoutManager gridLayoutManager = new GridLayoutManager(context, 3);
 recyclerView.setLayoutManager(gridLayoutManager);
 recyclerView.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.HORIZONTAL));

But the dividers are not appearing in center horizontally.

Following is screen shot of it.

Following is item layout

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:clickable="true"
android:gravity="center"
android:orientation="vertical"
android:paddingBottom="8dp"
android:paddingTop="8dp">

<ImageView
    android:id="@+id/imgFacility"
    android:layout_width="30dp"
    android:layout_height="30dp"
    android:layout_gravity="center"
    android:foreground="@drawable/page_main_category_home_grid_selector"
    android:gravity="center"
    android:src="@drawable/plane_img"
    android:tint="?colorAccent" />

<TextView
    android:id="@+id/txtFacilityName"
    mediumFontPath="fonts/montserrat-medium.ttf"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginTop="2dp"
    android:ellipsize="end"
    android:gravity="center"
    android:maxLines="2"
    android:minLines="2"
    android:text="Facility\nEWlall"
    android:textColor="#353535"
    android:textSize="12sp"
    tools:ignore="MissingPrefix" />

 </LinearLayout>

Also I tried using GridDividerDecoration

Following is output of it

Given background color to each layout this is how it looks

Body:
First create class using below code

public class DividerItemDecoration extends RecyclerView.ItemDecoration {

private static final int[] ATTRS = {android.R.attr.listDivider};

private Drawable mDivider;
private int mInsets;

public DividerItemDecoration(Context context) {
    TypedArray a = context.obtainStyledAttributes(ATTRS);
    mDivider = a.getDrawable(0);
    a.recycle();

    mInsets = 1;
}

@Override
public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
    drawVertical(c, parent);
    drawHorizontal(c, parent);
}

/**
 * Draw dividers at each expected grid interval
 */
public void drawVertical(Canvas c, RecyclerView parent) {
    if (parent.getChildCount() == 0) return;

    final int childCount = parent.getChildCount();

    for (int i = 0; i < childCount; i++) {
        final View child = parent.getChildAt(i);
        final RecyclerView.LayoutParams params =
                (RecyclerView.LayoutParams) child.getLayoutParams();

        final int left = child.getLeft() - params.leftMargin - mInsets;
        final int right = child.getRight() + params.rightMargin + mInsets;
        final int top = child.getBottom() + params.bottomMargin + mInsets;
        final int bottom = top + mDivider.getIntrinsicHeight();
        mDivider.setBounds(left, top, right, bottom);
        mDivider.draw(c);
    }
}

/**
 * Draw dividers to the right of each child view
 */
public void drawHorizontal(Canvas c, RecyclerView parent) {
    final int childCount = parent.getChildCount();

    for (int i = 0; i < childCount; i++) {
        final View child = parent.getChildAt(i);
        final RecyclerView.LayoutParams params =
                (RecyclerView.LayoutParams) child.getLayoutParams();

        final int left = child.getRight() + params.rightMargin + mInsets;
        final int right = left + mDivider.getIntrinsicWidth();
        final int top = child.getTop() - params.topMargin - mInsets;
        final int bottom = child.getBottom() + params.bottomMargin + mInsets;
        mDivider.setBounds(left, top, right, bottom);
        mDivider.draw(c);
    }
}

@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
    //We can supply forced insets for each item view here in the Rect
    outRect.set(mInsets, mInsets, mInsets, mInsets);
}

}

After this use this decoration class in your recyclarview like this

recyclerView.addItemDecoration(new DividerItemDecoration(getActivity()));

It help to show vertical and horizontal line between item.


问:
Stop Mongoose to create auto index
I am trying to create schema in mongoose it create new index in mongodb named _id?

```<code> const modelSchema = new Schema({
    uid: { type: Number, required: true },
    content: {
        text: { type: String },
        attachments: [{
            type: { type: String, enum: ['IMAGE', 'VIDEO', 'POLL', 'GOAL', 'POST', 'MILESTONE', 'ARTICLE', 'DOCUMENT', 'AUDIO', 'QUOTE', 'USER', 'TIP', 'URL'] },
            object_id: { type: Number }
        }]
    },
    created: { type: String }
});
</code>```

I am expecting this result:

```<code>"content" : {
"text" : "hello",
"attachments" : [
    {
        "type" : "IMAGE",
        "object_id" : 1
    }
]
</code>```

I am getting this result:

```<code>"content" : {
"text" : "hello",
"attachments" : [
    {
        "type" : "IMAGE",
        "object_id" : 1,
        "_id" : ObjectId("5a2664fd6db6672ac43f1823")
    }
]
</code>```

答:
mongo will create _id default if you want to use your own override with your value you can set as

```<code>"_id" : 1
</code>```

ex
if you insert
db.a.insert({"name":"abcd"}) this will create _id default
db.a.insert({"name":"abcd","_id":1}) this will create and set _id as 1

Title: Stop Mongoose to create auto index

Body:
I am trying to create schema in mongoose it create new index in mongodb named _id?

 const modelSchema = new Schema({
    uid: { type: Number, required: true },
    content: {
        text: { type: String },
        attachments: [{
            type: { type: String, enum: ['IMAGE', 'VIDEO', 'POLL', 'GOAL', 'POST', 'MILESTONE', 'ARTICLE', 'DOCUMENT', 'AUDIO', 'QUOTE', 'USER', 'TIP', 'URL'] },
            object_id: { type: Number }
        }]
    },
    created: { type: String }
});

I am expecting this result:

"content" : {
"text" : "hello",
"attachments" : [
    {
        "type" : "IMAGE",
        "object_id" : 1
    }
]

I am getting this result:

"content" : {
"text" : "hello",
"attachments" : [
    {
        "type" : "IMAGE",
        "object_id" : 1,
        "_id" : ObjectId("5a2664fd6db6672ac43f1823")
    }
]

Body:
mongo will create _id default if you want to use your own override with your value you can set as

"_id" : 1

ex
if you insert
db.a.insert({"name":"abcd"}) this will create _id default
db.a.insert({"name":"abcd","_id":1}) this will create and set _id as 1


问:
chromedriver.exe could not be found in my WebDriver wrapper nuget
I'm trying to create WebDriver wrapper nuget package that will be used in my company with supporting .net core.
I added to this package reference to OpenQA.Selenium.Chrome and trying to create new ChromeDriver:

```<code>_browser = new Browser(new ChromeDriver(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)));
</code>```

When I add my nuget package to test and run it, I've got an error:

The file C:\Users\MyUser\
  .nuget\packages\\0.0.0.1\lib\netstandard2.0\chromedriver.exe
  does not exist

The problem is that the true path to the chromedriver is:
c:\Users\MyUser\ .nuget\packages\selenium.chrome.webdriver\2.33.0\driver\

How it could be managed? When you create ChromeDriver from the test project it's easy because it's placed to the bin directory of your project, but what to do in case of nuget package?

答:
Actually the best way that I found out it's to add Selenium.Chrome.Webdriver nuget directly to tests and create webdriver like

```<code>var driver = new ChromeDriver(Directory.GetCurrentDirectory());
</code>```

in my nuget package.
Unfortunately I didn't know how to resolve it without referencing Chrome.Webdriver nuget to tests

Body:
I'm trying to create WebDriver wrapper nuget package that will be used in my company with supporting .net core.
I added to this package reference to OpenQA.Selenium.Chrome and trying to create new ChromeDriver:

_browser = new Browser(new ChromeDriver(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)));

When I add my nuget package to test and run it, I've got an error:

The file C:\Users\MyUser\
  .nuget\packages\\0.0.0.1\lib\netstandard2.0\chromedriver.exe
  does not exist

The problem is that the true path to the chromedriver is:
c:\Users\MyUser\ .nuget\packages\selenium.chrome.webdriver\2.33.0\driver\

How it could be managed? When you create ChromeDriver from the test project it's easy because it's placed to the bin directory of your project, but what to do in case of nuget package?

Body:
Actually the best way that I found out it's to add Selenium.Chrome.Webdriver nuget directly to tests and create webdriver like

var driver = new ChromeDriver(Directory.GetCurrentDirectory());

in my nuget package.
Unfortunately I didn't know how to resolve it without referencing Chrome.Webdriver nuget to tests


问:
Android Service needs to run always (Never pause or stop)
I created a service and want to run this service always until my phone restarts or force closed. The service should run in background.

Sample code of created service and start services:

Start the service:

```<code>Intent service = new Intent(getApplicationContext(), MyService.class);
getApplicationContext().startService(service);
</code>```

The service:

```<code>public class MyService extends Service {

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO do something useful
        HFLAG = true;
        //smsHandler.sendEmptyMessageDelayed(DISPLAY_DATA, 1000);
        return Service.START_NOT_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO for communication return IBinder implementation
        return null;
    }
}
</code>```

Manifest declaration:

```<code><service
    android:name=".MyService"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
</service>
</code>```

Is it possible to run this service always as when the application pauses and anything else.
After some time my application goes pause and the services also go pause or stop.
So how can I run this service in background and always.

答:
Add this in manifest.

```<code>      <service
        android:name=".YourServiceName"
        android:enabled="true"
        android:exported="false" />
</code>```

Add a service class.

```<code>public class YourServiceName extends Service {

    @Override
    public void onCreate() {
        super.onCreate();

      // Timer task makes your service will repeat after every 20 Sec.
       TimerTask doAsynchronousTask = new TimerTask() {
            @Override
            public void run() {
                handler.post(new Runnable() {
                    public void run() {
                       // Add your code here.

                     }

               });
            }
        };
  //Starts after 20 sec and will repeat on every 20 sec of time interval.
        timer.schedule(doAsynchronousTask, 20000,20000);  // 20 sec timer
                              (enter your own time)
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO do something useful

      return START_STICKY;
    }

}
</code>```

Body:
I created a service and want to run this service always until my phone restarts or force closed. The service should run in background.

Sample code of created service and start services:

Start the service:

Intent service = new Intent(getApplicationContext(), MyService.class);
getApplicationContext().startService(service);

The service:

public class MyService extends Service {

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO do something useful
        HFLAG = true;
        //smsHandler.sendEmptyMessageDelayed(DISPLAY_DATA, 1000);
        return Service.START_NOT_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO for communication return IBinder implementation
        return null;
    }
}

Manifest declaration:

<service
    android:name=".MyService"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
</service>

Is it possible to run this service always as when the application pauses and anything else.
After some time my application goes pause and the services also go pause or stop.
So how can I run this service in background and always.

Body:
Add this in manifest.

      <service
        android:name=".YourServiceName"
        android:enabled="true"
        android:exported="false" />

Add a service class.

public class YourServiceName extends Service {

    @Override
    public void onCreate() {
        super.onCreate();

      // Timer task makes your service will repeat after every 20 Sec.
       TimerTask doAsynchronousTask = new TimerTask() {
            @Override
            public void run() {
                handler.post(new Runnable() {
                    public void run() {
                       // Add your code here.

                     }

               });
            }
        };
  //Starts after 20 sec and will repeat on every 20 sec of time interval.
        timer.schedule(doAsynchronousTask, 20000,20000);  // 20 sec timer
                              (enter your own time)
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO do something useful

      return START_STICKY;
    }

}


问:
Xamarin.Forms Bottom Menu for Android
I managed to show menu bar on bottom on Android. I followed this guide exactly : https://asyncawait.wordpress.com/2016/06/16/bottom-menu-for-xamarin-forms-android/#more-24

My issue is that I am working on a RTL (Right to Left) Language app, so I want to show the last tab as the default activated tab on load.
So I changed the following in PopulateChildren Method:

```<code>        LoadPageContent(0);
</code>```

To:

```<code>        LoadPageContent(3); //I have total 4 pages (0,1,2,3)
</code>```

Now the last page is loaded by default but the Selected color of the tab is still on the first tab.

(source: cubeupload.com)

I want to show the selected tab color on the last page. How can I do it??

答:
In PopulateChildren Method in your renderer add these two lines</p>

```<code>LoadPageContent(3); //This will load the 4th page
_bottomBar.SelectTabAtPosition(3, false); //This will move the bottomBar selected tab position to the 4th tab
</code>```

ContentLicense: CC BY-SA 4.0

Title: Xamarin.Forms Bottom Menu for Android

Body:
I managed to show menu bar on bottom on Android. I followed this guide exactly : https://asyncawait.wordpress.com/2016/06/16/bottom-menu-for-xamarin-forms-android/#more-24

My issue is that I am working on a RTL (Right to Left) Language app, so I want to show the last tab as the default activated tab on load.
So I changed the following in PopulateChildren Method:

        LoadPageContent(0);

To:

        LoadPageContent(3); //I have total 4 pages (0,1,2,3)

Now the last page is loaded by default but the Selected color of the tab is still on the first tab.

(source: cubeupload.com)

I want to show the selected tab color on the last page. How can I do it??

Body:
In PopulateChildren Method in your renderer add these two lines

LoadPageContent(3); //This will load the 4th page
_bottomBar.SelectTabAtPosition(3, false); //This will move the bottomBar selected tab position to the 4th tab


问:
How can I use postgres roles and passwords for website authentication
I want a future web application's users to be able to log into a postgres database using their website usernames and passwords.

The website will connect to postgres with a special username (e.g. "web") which will be unavailable as a website username.  (As would "postgres", etc.)

No users or passwords exist yet, so there are no migration issues.  All website users will be postgres users.  The website can hash passwords however postgres does.

What is the most sensible way to achieve this with the least duplication of data?

Can I use/extend postgres's internal roles tables as a general source of username/password authentication?  i.e. I would need to be able to run a query which will tell me if a given username/password combination is valid.

Or is it better to a have a separate store of website usernames and passwords and somehow get postgres to use this?

答:
You can indeed check authentication with select

```<code>t=# select 'md5'||md5('somePass'||usename) = passwd from pg_shadow where usename = 'web';
 ?column?
----------
 t
(1 row)
</code>```

but You should not manipulate pg_authid directly, instead using SQL statements, like:

```<code>t=# create user web password 'somePass';
CREATE ROLE
</code>```

or

```<code>t=# alter user web password 'anotherP';
ALTER ROLE
t=# select 'md5'||md5('somePass'||usename) = passwd from pg_shadow where usename = 'web';
 ?column?
----------
 f
(1 row)

t=# select 'md5'||md5('anotherP'||usename) = passwd from pg_shadow where usename = 'web';
 ?column?
----------
 t
(1 row)
</code>```

and:

```<code>t=# drop user web;
DROP ROLE
t=# select 'md5'||md5('anotherP'||usename) = passwd from pg_shadow where usename = 'web';
 ?column?
----------
(0 rows)
</code>```

to avoid SU role with application, just create wrapups for account manipulations, like:

```<code>t=# create or replace function adduser(_u text,_p text) returns boolean as $$
begin
 execute format('create user %I password %L',_u,_p);
 return true;
end;
$$ language plpgsql security definer;
CREATE FUNCTION
</code>```

security definer will alow app user to create new role:

```<code>t=# select adduser('web','newP');
 adduser
---------
 t
(1 row)

t=# select 'md5'||md5('newP'||usename) = passwd from pg_shadow where usename = 'web';
 ?column?
----------
 t
(1 row)
</code>```

don't forget to add some logic and exceptions, so application would not interfiere with existing SU roles (not droppping, not changing passwords).

Lastly I think such idea can be dangerous. Plan it before implementing...

Body:
You can indeed check authentication with select

t=# select 'md5'||md5('somePass'||usename) = passwd from pg_shadow where usename = 'web';
 ?column?
----------
 t
(1 row)

but You should not manipulate pg_authid directly, instead using SQL statements, like:

t=# create user web password 'somePass';
CREATE ROLE

or

t=# alter user web password 'anotherP';
ALTER ROLE
t=# select 'md5'||md5('somePass'||usename) = passwd from pg_shadow where usename = 'web';
 ?column?
----------
 f
(1 row)

t=# select 'md5'||md5('anotherP'||usename) = passwd from pg_shadow where usename = 'web';
 ?column?
----------
 t
(1 row)

and:

t=# drop user web;
DROP ROLE
t=# select 'md5'||md5('anotherP'||usename) = passwd from pg_shadow where usename = 'web';
 ?column?
----------
(0 rows)

to avoid SU role with application, just create wrapups for account manipulations, like:

t=# create or replace function adduser(_u text,_p text) returns boolean as $$
begin
 execute format('create user %I password %L',_u,_p);
 return true;
end;
$$ language plpgsql security definer;
CREATE FUNCTION

security definer will alow app user to create new role:

t=# select adduser('web','newP');
 adduser
---------
 t
(1 row)

t=# select 'md5'||md5('newP'||usename) = passwd from pg_shadow where usename = 'web';
 ?column?
----------
 t
(1 row)

don't forget to add some logic and exceptions, so application would not interfiere with existing SU roles (not droppping, not changing passwords).

Lastly I think such idea can be dangerous. Plan it before implementing...


问:
How to update database table and change the button using ajax php?
I have a button named Finish Payment in my page:

```<code><button style="background-color:#73bd5a; color:#FFF;" id="finish_payment"
name="finish_payment" type="button" class="btn btn-white active pull-right">
<i class="ion-checkmark-circled"></i></i> Finish Payment</button>
</code>```

What I want to do is when I click this button I want to update the payment status "Unpaid" to "Paid" in table client_payment and after updating change the button text to paid without refreshing the page. The ajax code I have used is given below:

```<code><script>
$(document).ready(function(){
         $(document).on('click', '.finish_payment', function(){

       $.ajax({
            url:"update_payment.php?id=<?php echo $client_id; ?>",
            method:"POST",
            dataType:"json",
            success:function(data){
              alert(data);
            }
       });
  });
</code>```

And the server side code I have is:

```<code>$connection = mysqli_connect("localhost", "root", "", "bn");
 $client_id=$_GET['id'];

 $query="update client_payment set payment_status='true' where
  client_id=$client_id";
 if(mysqli_query($connection, $query)){

echo"Payment Complete";
}
</code>```

答:
Change your update query like this:

```<code>$query="update client_payment set payment_status='true' where
  client_id='".$client_id."'";  // `'` was missing in where clause.
</code>```

And to update button text, you can do the following:

```<code>$(document).ready(function(){
     $(document).on('click', '#finish_payment', function(){  // finish_payment is id attribute not class. So using with #

     $.ajax({
        url:"update_payment.php?id=<?php echo $client_id; ?>",
        method:"POST",
        dataType:"json",
        success:function(data){
            $('.finish_payment').text('Paid');    // Changing button text here.
        }
   });
</code>```

Body:
I have a button named Finish Payment in my page:

<button style="background-color:#73bd5a; color:#FFF;" id="finish_payment"
name="finish_payment" type="button" class="btn btn-white active pull-right">
 Finish Payment</button>

What I want to do is when I click this button I want to update the payment status "Unpaid" to "Paid" in table client_payment and after updating change the button text to paid without refreshing the page. The ajax code I have used is given below:

Body:
Change your update query like this:

$query="update client_payment set payment_status='true' where
  client_id='".$client_id."'";  // `'` was missing in where clause.

And to update button text, you can do the following:

$(document).ready(function(){
     $(document).on('click', '#finish_payment', function(){  // finish_payment is id attribute not class. So using with #

     $.ajax({
        url:"update_payment.php?id=<?php echo $client_id; ?>",
        method:"POST",
        dataType:"json",
        success:function(data){
            $('.finish_payment').text('Paid');    // Changing button text here.
        }
   });


答:
Bitwise complement.

http://msdn.microsoft.com/en-us/library/d2bd4x66.aspx

A literal 0 (as in the code above) is an int.

An int is a 32 bit binary value. The value 0 has all the bits set to 0.

The ~ operator is a bitwise compliment. i.e. I swaps all the bits.

As all the bits were 0 they are all turned into 1. So we have a 32 bit value

with all the bits set to 1.

C# sharp uses 2 compliment. Which encodes -1 in an int as all bits being 1

```<code>0000 0000 0000 0000 0000 0000 0000 0000   == 0

operator ~

1111 1111 1111 1111 1111 1111 1111 1111   == -1
</code>```

So  =>  ~0 == -1

Title: int max = ~0; What does it mean?

Body:
int max = ~0;

What does it mean?

Body:
Bitwise complement.

http://msdn.microsoft.com/en-us/library/d2bd4x66.aspx

A literal 0 (as in the code above) is an int.

An int is a 32 bit binary value. The value 0 has all the bits set to 0.

The ~ operator is a bitwise compliment. i.e. I swaps all the bits.

As all the bits were 0 they are all turned into 1. So we have a 32 bit value

with all the bits set to 1.

C# sharp uses 2 compliment. Which encodes -1 in an int as all bits being 1

0000 0000 0000 0000 0000 0000 0000 0000   == 0

operator ~

1111 1111 1111 1111 1111 1111 1111 1111   == -1

So  =>  ~0 == -1


问:
Unable to install Swagger Php
I am trying to install Swagger php for ubuntu from http://blog.nbostech.com/2016/01/integrating-swagger-ui-for-php-application/

In that link they ask me to run the following command - "php composer.phar require zircote/swagger-php".

When i give, "php composer.phar require zircote/swagger-php" in my terminal it says "Could not open input file: composer.phar". Due to this error i am unable to proceed swagger-php installation from above link.

I am in need of Support.

答:
1) Install composer for your php.
2) Use meantioned command if composer was installed locally.
3) Use "composer require zircote/swagger-php" if composer is used globally.

4) Consult composer documenation for proper syntax if you use something different then Linux/MacOS.

Above commands have to be executed inside php project, which will be annotated

Title: Unable to install Swagger Php


问:
Error: Please select Android SDK in Android Studio 2.0
I am using Android Studio 2.0 Beta2, and i am trying to run old project that uses google maps api v1 (package com.google.android.maps) as *.jar file. To run this old project i need specify compileSdkVersion older than the last one (23). I used

```<code>compileSdkVersion 'Google Inc.:Google APIs:17'
</code>```

But i got Error: Please select  Android SDK error in Android Studio. How i can run this old project with older compileSdkVersion?

答:
It is works for me

intelliJ IDEA 13 error: please select Android SDK

My Problem: "please select Android SDK", But everything is okey :( -> I think one of IntelliJ file was crashed (after blue screen of death)

My resolution:

File -> Settings -> Android SDK -> Android SDK Location Edit -> Next, Next (Android SDK is up to date.), Finished

... and crashed file was repaired!

I hope this will help!

Body:
I am using Android Studio 2.0 Beta2, and i am trying to run old project that uses google maps api v1 (package com.google.android.maps) as *.jar file. To run this old project i need specify compileSdkVersion older than the last one (23). I used

compileSdkVersion 'Google Inc.:Google APIs:17'

But i got Error: Please select  Android SDK error in Android Studio. How i can run this old project with older compileSdkVersion?


问:
How to pass in my meat, rice and beans value, from my Burrito class to the meat class, rice class, and beans class respectively?
I have four classes, I am trying to pass in my meat value, rice value and beans value to their respective classes, and return their value through the Burrito class. I have battled with this for two days but no visible progress, any idea on what to do, apologies for any grammatical error. Below is the first three classes, According to the instructions given am not suppose to touch any line in the first three classes, all my code modifications should be in the Burrito class.

```<code>class Meat:
    def __init__(self, value=False):
        self.set_value(value)

    def get_value(self):
        return self.value

    def set_value(self, value):
        if value in ["chicken", "pork", "steak", "tofu"]:
            self.value = value
        else:
            self.value = False

class Rice:
    def __init__(self, value=False):
        self.set_value(value)

    def get_value(self):
        return self.value

    def set_value(self, value):
        if value in ["brown", "white"]:
            self.value = value
        else:
            self.value = False

class Beans:
    def __init__(self, value=False):
        self.set_value(value)

    def get_value(self):
        return self.value

    def set_value(self, value):
        if value in ["black", "pinto"]:
            self.value = value
        else:
            self.value = False
</code>```

Here is the class were am suppose to pass in value from and return value from as well.

```<code>class Burrito:
    def __init__ (self, meat, to_go, rice, beans):
        self.meat = Meat(meat)
        self.set_to_go(to_go)
        self.rice = Rice(rice)
        self.beans = Beans(beans)

    def set_meat(self, meat):
        self.set_value(meat)

    def set_to_go(self, to_go):
        to_go_list = [True, False]
        if to_go in to_go_list:
            self.to_go = to_go
        else:
            self.to_go = False

    def set_rice(self, rice):
        self.set_value(rice)

    def set_beans(self, beans):
        self.set_value(beans)

    def get_meat(self):
        self.meat_v = Meat()
        return self.meat_v.value

    def get_to_go(self):
        return self.to_go

    def get_rice(self):
        self.rice_v = Rice()
        return self.rice_v.value

    def get_beans(self):
        self.beans_v = Beans()
        return self.beans_v.value
</code>```

Here is the line am using to test my code:

```<code>newburrito = Burrito("pork", True, "brown", "pinto")
print (newburrito.meat)
</code>```

This is the error line am getting:

```<code><__main__.Meat object at 0x7fa5ad8bccf8>
</code>```

Am expecting it to print

```<code>pork
</code>```

答:
This exercise is about Python properties. If you are expecting newburrito.meat to return "pork" this means that meat is a property of the class Burrito, not a method, nor a class instance, which is how your code defines it.

Step 1. Make the class members meat, to go, beans and rice private. The convention is to start the name with an underscore:

```<code>class Burrito:
    def __init__ (self, meat, to_go, rice, beans):
        self._meat = Meat(meat)
        self._to_go = to_go
        self._rice = Rice(rice)
        self._beans = Beans(beans)
</code>```

Step 2: Define properties to return meat, to go, beans and rice. For this you need a getter method (with decorator @property) and a setter method (with decorator @xxxxx.setter). The property definitions go inside the Burrito class: be sure to get the indentation right.

```<code>class Burrito:

    # ... continued ...

    @property
    def meat(self):
        return self._meat.get_value()
    @meat.setter
    def meat(self,value):
        self._meat.set_value(value)

    @property
    def to_go(self):
        return self._to_go
    @to_go.setter
    def to_go(self,value):
        self._to_go  = isinstance(value,bool) and value

    @property
    def rice(self):
        return self._rice.get_value()
    @rice.setter
    def rice(self,value):
        self._rice.set_value(value)

    @property
    def beans(self):
        return self._beans.get_value()
    @beans.setter
    def beans(self, value):
        self._beans.set_value(value)
</code>```

Then you can use the properties .meat, .rice etc as though they were instance variables of Burrito, but instead, when you use them as r-values, the interpreter calls the getter method, and when you use them as l-values, the interpreter calls the setter method.

You can see how that works like this:

```<code>newburrito = Burrito("pork", True, "brown", "pinto")
print (newburrito.meat)
print (newburrito.rice)
print (newburrito.beans)
print (newburrito.to_go)

newburrito.meat = 'tofu'
print (newburrito.meat)
</code>```

Output is

```<code>pork
brown
pinto
True
tofu
</code>```

Body:
I have four classes, I am trying to pass in my meat value, rice value and beans value to their respective classes, and return their value through the Burrito class. I have battled with this for two days but no visible progress, any idea on what to do, apologies for any grammatical error. Below is the first three classes, According to the instructions given am not suppose to touch any line in the first three classes, all my code modifications should be in the Burrito class.

class Meat:
    def __init__(self, value=False):
        self.set_value(value)

    def get_value(self):
        return self.value

    def set_value(self, value):
        if value in ["chicken", "pork", "steak", "tofu"]:
            self.value = value
        else:
            self.value = False

class Rice:
    def __init__(self, value=False):
        self.set_value(value)

    def get_value(self):
        return self.value

    def set_value(self, value):
        if value in ["brown", "white"]:
            self.value = value
        else:
            self.value = False

class Beans:
    def __init__(self, value=False):
        self.set_value(value)

    def get_value(self):
        return self.value

    def set_value(self, value):
        if value in ["black", "pinto"]:
            self.value = value
        else:
            self.value = False

Here is the class were am suppose to pass in value from and return value from as well.

class Burrito:
    def __init__ (self, meat, to_go, rice, beans):
        self.meat = Meat(meat)
        self.set_to_go(to_go)
        self.rice = Rice(rice)
        self.beans = Beans(beans)

    def set_meat(self, meat):
        self.set_value(meat)

    def set_to_go(self, to_go):
        to_go_list = [True, False]
        if to_go in to_go_list:
            self.to_go = to_go
        else:
            self.to_go = False

    def set_rice(self, rice):
        self.set_value(rice)

    def set_beans(self, beans):
        self.set_value(beans)

    def get_meat(self):
        self.meat_v = Meat()
        return self.meat_v.value

    def get_to_go(self):
        return self.to_go

    def get_rice(self):
        self.rice_v = Rice()
        return self.rice_v.value

    def get_beans(self):
        self.beans_v = Beans()
        return self.beans_v.value

Here is the line am using to test my code:

newburrito = Burrito("pork", True, "brown", "pinto")
print (newburrito.meat)

This is the error line am getting:

<__main__.Meat object at 0x7fa5ad8bccf8>

Am expecting it to print

pork

Body:
This exercise is about Python properties. If you are expecting newburrito.meat to return "pork" this means that meat is a property of the class Burrito, not a method, nor a class instance, which is how your code defines it.

Step 1. Make the class members meat, to go, beans and rice private. The convention is to start the name with an underscore:

class Burrito:
    def __init__ (self, meat, to_go, rice, beans):
        self._meat = Meat(meat)
        self._to_go = to_go
        self._rice = Rice(rice)
        self._beans = Beans(beans)

Step 2: Define properties to return meat, to go, beans and rice. For this you need a getter method (with decorator @property) and a setter method (with decorator @xxxxx.setter). The property definitions go inside the Burrito class: be sure to get the indentation right.

class Burrito:

    # ... continued ...

    @property
    def meat(self):
        return self._meat.get_value()
    @meat.setter
    def meat(self,value):
        self._meat.set_value(value)

    @property
    def to_go(self):
        return self._to_go
    @to_go.setter
    def to_go(self,value):
        self._to_go  = isinstance(value,bool) and value

    @property
    def rice(self):
        return self._rice.get_value()
    @rice.setter
    def rice(self,value):
        self._rice.set_value(value)

    @property
    def beans(self):
        return self._beans.get_value()
    @beans.setter
    def beans(self, value):
        self._beans.set_value(value)

Then you can use the properties .meat, .rice etc as though they were instance variables of Burrito, but instead, when you use them as r-values, the interpreter calls the getter method, and when you use them as l-values, the interpreter calls the setter method.

You can see how that works like this:

newburrito = Burrito("pork", True, "brown", "pinto")
print (newburrito.meat)
print (newburrito.rice)
print (newburrito.beans)
print (newburrito.to_go)

newburrito.meat = 'tofu'
print (newburrito.meat)

Output is

pork
brown
pinto
True
tofu


问:
How can I make this code shorter? Is it possible to create this in one loop?
```<code>var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');

var rw = 50;
var rh = 50;
var x = 10;
var y = 10;

for (x=10, y=10; y<240; x=x+60, y=y+57) {
  ctx.fillStyle = "orange";
ctx.fillRect(x,y,rw,rh);
}
  for (x=10, y=67; y<240; x=x+60, y=y+57) {
ctx.fillStyle = "orange";
ctx.fillRect(x,y,rw,rh);
}

  for (x=10, y=124; y<240; x=x+60, y=y+57) {
ctx.fillStyle = "orange";
ctx.fillRect(x,y,rw,rh);
}

  for (x=10, y=181; y<240; x=x+60, y=y+57) {
ctx.fillStyle = "orange";
ctx.fillRect(x,y,rw,rh);
}

  for (x=10, y=238; y<240; x=x+60, y=y+57) {
ctx.fillStyle = "orange";
ctx.fillRect(x,y,rw,rh);
}
</code>```

It's a javascript code. In my html is this

```<code><canvas id="myCanvas" height="300" width="450" style="border: 1px solid black"></canvas>
</code>```

My task is, come this code together below one loop.

Thank you so much for your help!

答:
Try this shorthand with a function. In your code just the y part is changing the rest is the same. So you can create a function and pass y as a parameter into it.

var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');

function fillRect(y, rw = 50, rh = 50) {
   for(var x = 10; y < 240; x += 60, y += 57) {
      ctx.fillStyle = "orange";
      ctx.fillRect(x,y,rw,rh);
   }
}

for (const y of [10, 67, 124, 181, 238]) {
    fillRect(y);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="myCanvas" height="300" width="450" style="border: 1px solid black"></canvas></code>```

Body:
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');

var rw = 50;
var rh = 50;
var x = 10;
var y = 10;

for (x=10, y=10; y<240; x=x+60, y=y+57) {
  ctx.fillStyle = "orange";
ctx.fillRect(x,y,rw,rh);
}
  for (x=10, y=67; y<240; x=x+60, y=y+57) {
ctx.fillStyle = "orange";
ctx.fillRect(x,y,rw,rh);
}

  for (x=10, y=124; y<240; x=x+60, y=y+57) {
ctx.fillStyle = "orange";
ctx.fillRect(x,y,rw,rh);
}

  for (x=10, y=181; y<240; x=x+60, y=y+57) {
ctx.fillStyle = "orange";
ctx.fillRect(x,y,rw,rh);
}

  for (x=10, y=238; y<240; x=x+60, y=y+57) {
ctx.fillStyle = "orange";
ctx.fillRect(x,y,rw,rh);
}

It's a javascript code. In my html is this

<canvas id="myCanvas" height="300" width="450" style="border: 1px solid black"></canvas>

My task is, come this code together below one loop.

Thank you so much for your help!

Body:
Try this shorthand with a function. In your code just the y part is changing the rest is the same. So you can create a function and pass y as a parameter into it.

var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');

function fillRect(y, rw = 50, rh = 50) {
   for(var x = 10; y < 240; x += 60, y += 57) {
      ctx.fillStyle = "orange";
      ctx.fillRect(x,y,rw,rh);
   }
}

for (const y of [10, 67, 124, 181, 238]) {
    fillRect(y);
}

<canvas id="myCanvas" height="300" width="450" style="border: 1px solid black"></canvas>


问:
ConcurrentModificationException despite the using Iterator and synchronized
```<code>public class RetryHandler extends Thread {

private ArrayList<RetryMessage> retryMessages;
private Object syncObject = new Object();

private RetryHandler() {
    this.setName("retryhlr");
}
public Boolean addMessage(IfgExchangeRequestBase msg, int token) {
    synchronized(syncObject) {
        retryMessages.add(new RetryMessage(msg, token));
        return true;
    }
}

public Boolean removeMessage(Integer token) {
    synchronized(syncObject) {
        retryMessages.removeIf(x->x.getToken().equals(token));
        return true;
    }
}

@Override
public void run() {
    while(isRunning) {
        if (!isPaused) {
            synchronized(syncObject) {
                ListIterator<RetryMessage> tempRTMessages = retryMessages.listIterator();
                while(tempRTMessages.hasNext()){
                    RetryMessage rtmsg =tempRTMessages.next();
                    if(....)) {
                        tempRTMessages.remove();
                    } else if(...)
                        try {
                            int token = fetch()
                            rtmsg.retried();
                            rtmsg.setToken(token);
                        } catch (SAGException e) {
                    }
                }
            }
        }
    }
}
</code>```

}

As you see RetryHandler extends Thread which iterating over a internal list retryMessages. Despite the using Iterator and synchronized i 'm getting  ConcurrentModificationException. addMessage and removeMessage has been used in other Threads.

note: I Used ListIterator but result is same. and RetryMessage rtmsg =tempRTMessages.next(); raises this exception.

UPDATE: Exception raises on RetryMessage rtmsg =tempRTMessages.next();

答:
You are encountering the error because of the exception because you are iterating the ArrayList, and while iterating it, you are removing objects from it. This is a fail fast mechanism for this type of collection.

What you can do if you really need to remove items from the ArrayList, is to create a CopyOnWriteArrayList object, this object is the one you will . Please see the code below:

```<code>CopyOnWriteArrayList<RetryMessage> retryMessageCopyOnWrite= new CopyOnWriteArrayList<RetryMessage>(retryMessages);
    Iterator<RetryMessage> retryMessageIterator = retryMessageCopyOnWrite.iterator();
...
<some object modifications here for retryMessageCopyOnWrite>
</code>```

Then just copy the content of the CopyOnWriteArrayList to the retryMessages list object back to the original arrayList.

```<code>retryMessages = new ArrayList<RetryMessage>(retryMessageCopyOnWrite);
</code>```

Since you are also using the iterator itself to remove an item. Please read this link:
CopyOnWriteArrayList

I suggest an alternative way to modify the list, instead of using the iterator itself, use the CopyOnWriteArrayList object.

You can have something like this inside the iteration:

```<code>RetryMessage temp = iterator.next();
if(do some checking) {
    retryMessageCopyOnWrite.remove(temp); //this removes the current element
}
</code>```

Body:
public class RetryHandler extends Thread {

private ArrayList<RetryMessage> retryMessages;
private Object syncObject = new Object();

private RetryHandler() {
    this.setName("retryhlr");
}
public Boolean addMessage(IfgExchangeRequestBase msg, int token) {
    synchronized(syncObject) {
        retryMessages.add(new RetryMessage(msg, token));
        return true;
    }
}

public Boolean removeMessage(Integer token) {
    synchronized(syncObject) {
        retryMessages.removeIf(x->x.getToken().equals(token));
        return true;
    }
}

@Override
public void run() {
    while(isRunning) {
        if (!isPaused) {
            synchronized(syncObject) {
                ListIterator<RetryMessage> tempRTMessages = retryMessages.listIterator();
                while(tempRTMessages.hasNext()){
                    RetryMessage rtmsg =tempRTMessages.next();
                    if(....)) {
                        tempRTMessages.remove();
                    } else if(...)
                        try {
                            int token = fetch()
                            rtmsg.retried();
                            rtmsg.setToken(token);
                        } catch (SAGException e) {
                    }
                }
            }
        }
    }
}

}

As you see RetryHandler extends Thread which iterating over a internal list retryMessages. Despite the using Iterator and synchronized i 'm getting  ConcurrentModificationException. addMessage and removeMessage has been used in other Threads.

note: I Used ListIterator but result is same. and RetryMessage rtmsg =tempRTMessages.next(); raises this exception.

UPDATE: Exception raises on RetryMessage rtmsg =tempRTMessages.next();

Body:
You are encountering the error because of the exception because you are iterating the ArrayList, and while iterating it, you are removing objects from it. This is a fail fast mechanism for this type of collection.

What you can do if you really need to remove items from the ArrayList, is to create a CopyOnWriteArrayList object, this object is the one you will . Please see the code below:

CopyOnWriteArrayList<RetryMessage> retryMessageCopyOnWrite= new CopyOnWriteArrayList<RetryMessage>(retryMessages);
    Iterator<RetryMessage> retryMessageIterator = retryMessageCopyOnWrite.iterator();
...
<some object modifications here for retryMessageCopyOnWrite>

Then just copy the content of the CopyOnWriteArrayList to the retryMessages list object back to the original arrayList.

retryMessages = new ArrayList<RetryMessage>(retryMessageCopyOnWrite);

Since you are also using the iterator itself to remove an item. Please read this link:
CopyOnWriteArrayList

I suggest an alternative way to modify the list, instead of using the iterator itself, use the CopyOnWriteArrayList object.

You can have something like this inside the iteration:

RetryMessage temp = iterator.next();
if(do some checking) {
    retryMessageCopyOnWrite.remove(temp); //this removes the current element
}


问:
How to display sum of row data in view using codeigniter?
This is my view. How can I calculate sum of rows using view without using model and controller</p>

```<code>foreach($requests as $request):
<?php echo SUM($request->unit_price) ?>
<?php  endforeach; ?>
</code>```

答:
```<code>$sum = 0;
foreach ($requests as $request):
    $sum += $request->unit_price;
endforeach;
echo $sum;
</code>```

Body:
This is my view. How can I calculate sum of rows using view without using model and controller

foreach($requests as $request):
<?php echo SUM($request->unit_price) ?>
<?php  endforeach; ?>


问:
c malloc() - do I need to allocate space for the null terminator
I have a snippet of code below that appends the text _dut1_serial_log.txt to a supplied filename. The supplied filename is a variable in the struct pointed to by targetP.

The text _dut1_serial_log.txt is 20 chars long. My question is do I need the +1 when I call malloc for the null terminator?

```<code>char *filename_ending = "_dut1_serial_log.txt";
    char *filename_with_extension;
    prv_instance_t *targetP = threadParams->targetP;

    /*append filename ending "_dut1_serial_log.txt" to filename supplied*/
    filename_with_extension = malloc(strlen(targetP->output_filename)+1+20);
    strcpy(filename_with_extension, targetP->output_filename); /* copy name into the new var */
    strcat(filename_with_extension, filename_ending); /* add the extension */
</code>```

答:
Both strcpy and strcat will copy the NUL-terminator from the source string to the destination buffer.

You do need to reserve space for that terminator in the destination buffer therefore.

To avoid any doubt, "_dut1_serial_log.txt" is a const char[21] type.

Body:
I have a snippet of code below that appends the text _dut1_serial_log.txt to a supplied filename. The supplied filename is a variable in the struct pointed to by targetP.

The text _dut1_serial_log.txt is 20 chars long. My question is do I need the +1 when I call malloc for the null terminator?

char *filename_ending = "_dut1_serial_log.txt";
    char *filename_with_extension;
    prv_instance_t *targetP = threadParams->targetP;

    /*append filename ending "_dut1_serial_log.txt" to filename supplied*/
    filename_with_extension = malloc(strlen(targetP->output_filename)+1+20);
    strcpy(filename_with_extension, targetP->output_filename); /* copy name into the new var */
    strcat(filename_with_extension, filename_ending); /* add the extension */


问:
Is there some kind of functionality, where a pointer dereference gives an rvalue?
Is there some kind of functionality, where a pointer dereference gives an rvalue?

So, a usual pointer gives an lvalue:

```<code>Foo *p = ...;

fn(p[42]);    // p[42] is an lvalue
</code>```

I'd like to have p[42] return an rvalue, so a fn(Foo &&) can be called for fn(p[42]):

```<code><some_pointer_type> p = ...;

fn(p[42]);    // I'd like to have p[42] be an rvalue, so an fn(Foo &&) would be called
</code>```

Note: I'd like to have p has this functionality, the pointer type should have this information, that dereferencing it should give an rvalue.

答:
The type of result of pointer dereferencing, that is type result of some overloaded operator can not depend of some information stored at pointer object at runtime because its signature is defined at compile-time. However it possible to overload operator based on pointer origin:

```<code>#include <string>
#include <iostream>
#include <cstddef>

template<typename TItems>
class t_FancyPointer;

template<typename TItems>
class t_FancyPointer<TItems[]>
{
    private: TItems * m_p_items;

    public: explicit
    t_FancyPointer(TItems * p_items) : m_p_items{p_items} {}

    public: TItems &
    operator [](::std::size_t const index) &
    {
        return(m_p_items[index]);
    }

    public: TItems &&
    operator [](::std::size_t const index) &&
    {
        return(::std::move(m_p_items[index]));
    }
};

void
fn(::std::string &&)
{
    ::std::cout << "rvalue reference" << ::std::endl;
}

void
fn(::std::string &)
{
    ::std::cout << "lvalue reference" << ::std::endl;
}

::std::string items[4];
t_FancyPointer<::std::string[]> perma_storage{items};

t_FancyPointer<::std::string[]> &
Get_PermaStorage(void)
{
    return(perma_storage);
}

t_FancyPointer<::std::string[]>
Get_TempStorage(void)
{
    return(t_FancyPointer<::std::string[]>{items});
}

int main()
{
    // calls fn(::std::string &)
    fn(Get_PermaStorage()[42]);
    // calls fn(::std::string &&)
    fn(Get_TempStorage()[42]);
    return 0;
}
</code>```

Output:

```<code>lvalue reference
rvalue reference
</code>```

If you just want to always return && then you can define a single operator [] returning an rvalue reference:

```<code>public: TItems &&
operator [](::std::size_t const index)
{
    return(::std::move(m_p_items[index]));
}
</code>```

Though I have no idea why would you do something like this.

Body:
Is there some kind of functionality, where a pointer dereference gives an rvalue?

So, a usual pointer gives an lvalue:

Foo *p = ...;

fn(p[42]);    // p[42] is an lvalue

I'd like to have p[42] return an rvalue, so a fn(Foo &&) can be called for fn(p[42]):

<some_pointer_type> p = ...;

fn(p[42]);    // I'd like to have p[42] be an rvalue, so an fn(Foo &&) would be called

Note: I'd like to have p has this functionality, the pointer type should have this information, that dereferencing it should give an rvalue.

Body:
The type of result of pointer dereferencing, that is type result of some overloaded operator can not depend of some information stored at pointer object at runtime because its signature is defined at compile-time. However it possible to overload operator based on pointer origin:

#include <string>
#include <iostream>
#include <cstddef>

template<typename TItems>
class t_FancyPointer;

template<typename TItems>
class t_FancyPointer<TItems[]>
{
    private: TItems * m_p_items;

    public: explicit
    t_FancyPointer(TItems * p_items) : m_p_items{p_items} {}

    public: TItems &
    operator [](::std::size_t const index) &
    {
        return(m_p_items[index]);
    }

    public: TItems &&
    operator [](::std::size_t const index) &&
    {
        return(::std::move(m_p_items[index]));
    }
};

void
fn(::std::string &&)
{
    ::std::cout << "rvalue reference" << ::std::endl;
}

void
fn(::std::string &)
{
    ::std::cout << "lvalue reference" << ::std::endl;
}

::std::string items[4];
t_FancyPointer<::std::string[]> perma_storage{items};

t_FancyPointer<::std::string[]> &
Get_PermaStorage(void)
{
    return(perma_storage);
}

t_FancyPointer<::std::string[]>
Get_TempStorage(void)
{
    return(t_FancyPointer<::std::string[]>{items});
}

int main()
{
    // calls fn(::std::string &)
    fn(Get_PermaStorage()[42]);
    // calls fn(::std::string &&)
    fn(Get_TempStorage()[42]);
    return 0;
}

Output:

lvalue reference
rvalue reference

If you just want to always return && then you can define a single operator [] returning an rvalue reference:

public: TItems &&
operator [](::std::size_t const index)
{
    return(::std::move(m_p_items[index]));
}

Though I have no idea why would you do something like this.


问:
Error while installing gem on Windows 8 - incompatible character encoding
I need to set up environment to start writing cucumber tests on Windows 8. I installed ruby 2.1.5 (from windows installer on ruby-lang.org).
But when I wanted to install gems I faced encoding issue and got stuck.

```<code>ERROR:  While executing gem ... (Encoding::CompatibilityError)
incompatible character encodings: UTF-8 and ASCII-8BIT
    C:/jimi/Ruby21-x64/lib/ruby/2.1.0/resolv.rb:771:in `[]='
    C:/jimi/Ruby21-x64/lib/ruby/2.1.0/resolv.rb:771:in `sender'
    C:/jimi/Ruby21-x64/lib/ruby/2.1.0/resolv.rb:525:in `block in fetch_resource'
    C:/jimi/Ruby21-x64/lib/ruby/2.1.0/resolv.rb:1096:in `block (3 levels) in resolv'
    C:/jimi/Ruby21-x64/lib/ruby/2.1.0/resolv.rb:1094:in `each'
    C:/jimi/Ruby21-x64/lib/ruby/2.1.0/resolv.rb:1094:in `block (2 levels) in resolv'
    C:/jimi/Ruby21-x64/lib/ruby/2.1.0/resolv.rb:1093:in `each'
    C:/jimi/Ruby21-x64/lib/ruby/2.1.0/resolv.rb:1093:in `block in resolv'
    C:/jimi/Ruby21-x64/lib/ruby/2.1.0/resolv.rb:1091:in `each'
    C:/jimi/Ruby21-x64/lib/ruby/2.1.0/resolv.rb:1091:in `resolv'
    C:/jimi/Ruby21-x64/lib/ruby/2.1.0/resolv.rb:520:in `fetch_resource'
    C:/jimi/Ruby21-x64/lib/ruby/2.1.0/resolv.rb:510:in `each_resource'
    C:/jimi/Ruby21-x64/lib/ruby/2.1.0/resolv.rb:491:in `getresource'
    C:/jimi/Ruby21-x64/lib/ruby/site_ruby/2.1.0/rubygems/remote_fetcher.rb:92:in `api_endpoint'
    C:/jimi/Ruby21-x64/lib/ruby/site_ruby/2.1.0/rubygems/source.rb:46:in `api_uri'
    C:/jimi/Ruby21-x64/lib/ruby/site_ruby/2.1.0/rubygems/source.rb:138:in `fetch_spec'
    C:/jimi/Ruby21-x64/lib/ruby/site_ruby/2.1.0/rubygems/resolver/api_specification.rb:76:in `spec'
    C:/jimi/Ruby21-x64/lib/ruby/site_ruby/2.1.0/rubygems/resolver/installer_set.rb:77:in `add_always_install'
    C:/jimi/Ruby21-x64/lib/ruby/site_ruby/2.1.0/rubygems/dependency_installer.rb:463:in `resolve_dependencies'
    C:/jimi/Ruby21-x64/lib/ruby/site_ruby/2.1.0/rubygems/commands/install_command.rb:238:in `install_gem'
    C:/jimi/Ruby21-x64/lib/ruby/site_ruby/2.1.0/rubygems/commands/install_command.rb:299:in `block in install_gems'
    C:/jimi/Ruby21-x64/lib/ruby/site_ruby/2.1.0/rubygems/commands/install_command.rb:295:in `each'
    C:/jimi/Ruby21-x64/lib/ruby/site_ruby/2.1.0/rubygems/commands/install_command.rb:295:in `install_gems'
    C:/jimi/Ruby21-x64/lib/ruby/site_ruby/2.1.0/rubygems/commands/install_command.rb:202:in `execute'
    C:/jimi/Ruby21-x64/lib/ruby/site_ruby/2.1.0/rubygems/command.rb:307:in `invoke_with_build_args'
    C:/jimi/Ruby21-x64/lib/ruby/site_ruby/2.1.0/rubygems/command_manager.rb:168:in `process_args'
    C:/jimi/Ruby21-x64/lib/ruby/site_ruby/2.1.0/rubygems/command_manager.rb:138:in `run'
    C:/jimi/Ruby21-x64/lib/ruby/site_ruby/2.1.0/rubygems/gem_runner.rb:54:in `run'
    C:/jimi/Ruby21-x64/bin/gem:21:in `<main>'
</code>```

Has anyone faced similar problems and found solution to it? Unluckily google wasn't helpful this time.

答:
I get the same error on windows 7, I fixed the problem by doing the change below:

On the file \lib\ruby\{version}\resolv.rb I changed the line below:

```<code>request[0,2] = [id].pack('n')
</code>```

To

```<code>request[0,2] = [id].pack('U')
</code>```

FYI: On the version 2.4.0 the line number is 772.

Body:
I need to set up environment to start writing cucumber tests on Windows 8. I installed ruby 2.1.5 (from windows installer on ruby-lang.org).
But when I wanted to install gems I faced encoding issue and got stuck.

ERROR:  While executing gem ... (Encoding::CompatibilityError)
incompatible character encodings: UTF-8 and ASCII-8BIT
    C:/jimi/Ruby21-x64/lib/ruby/2.1.0/resolv.rb:771:in `[]='
    C:/jimi/Ruby21-x64/lib/ruby/2.1.0/resolv.rb:771:in `sender'
    C:/jimi/Ruby21-x64/lib/ruby/2.1.0/resolv.rb:525:in `block in fetch_resource'
    C:/jimi/Ruby21-x64/lib/ruby/2.1.0/resolv.rb:1096:in `block (3 levels) in resolv'
    C:/jimi/Ruby21-x64/lib/ruby/2.1.0/resolv.rb:1094:in `each'
    C:/jimi/Ruby21-x64/lib/ruby/2.1.0/resolv.rb:1094:in `block (2 levels) in resolv'
    C:/jimi/Ruby21-x64/lib/ruby/2.1.0/resolv.rb:1093:in `each'
    C:/jimi/Ruby21-x64/lib/ruby/2.1.0/resolv.rb:1093:in `block in resolv'
    C:/jimi/Ruby21-x64/lib/ruby/2.1.0/resolv.rb:1091:in `each'
    C:/jimi/Ruby21-x64/lib/ruby/2.1.0/resolv.rb:1091:in `resolv'
    C:/jimi/Ruby21-x64/lib/ruby/2.1.0/resolv.rb:520:in `fetch_resource'
    C:/jimi/Ruby21-x64/lib/ruby/2.1.0/resolv.rb:510:in `each_resource'
    C:/jimi/Ruby21-x64/lib/ruby/2.1.0/resolv.rb:491:in `getresource'
    C:/jimi/Ruby21-x64/lib/ruby/site_ruby/2.1.0/rubygems/remote_fetcher.rb:92:in `api_endpoint'
    C:/jimi/Ruby21-x64/lib/ruby/site_ruby/2.1.0/rubygems/source.rb:46:in `api_uri'
    C:/jimi/Ruby21-x64/lib/ruby/site_ruby/2.1.0/rubygems/source.rb:138:in `fetch_spec'
    C:/jimi/Ruby21-x64/lib/ruby/site_ruby/2.1.0/rubygems/resolver/api_specification.rb:76:in `spec'
    C:/jimi/Ruby21-x64/lib/ruby/site_ruby/2.1.0/rubygems/resolver/installer_set.rb:77:in `add_always_install'
    C:/jimi/Ruby21-x64/lib/ruby/site_ruby/2.1.0/rubygems/dependency_installer.rb:463:in `resolve_dependencies'
    C:/jimi/Ruby21-x64/lib/ruby/site_ruby/2.1.0/rubygems/commands/install_command.rb:238:in `install_gem'
    C:/jimi/Ruby21-x64/lib/ruby/site_ruby/2.1.0/rubygems/commands/install_command.rb:299:in `block in install_gems'
    C:/jimi/Ruby21-x64/lib/ruby/site_ruby/2.1.0/rubygems/commands/install_command.rb:295:in `each'
    C:/jimi/Ruby21-x64/lib/ruby/site_ruby/2.1.0/rubygems/commands/install_command.rb:295:in `install_gems'
    C:/jimi/Ruby21-x64/lib/ruby/site_ruby/2.1.0/rubygems/commands/install_command.rb:202:in `execute'
    C:/jimi/Ruby21-x64/lib/ruby/site_ruby/2.1.0/rubygems/command.rb:307:in `invoke_with_build_args'
    C:/jimi/Ruby21-x64/lib/ruby/site_ruby/2.1.0/rubygems/command_manager.rb:168:in `process_args'
    C:/jimi/Ruby21-x64/lib/ruby/site_ruby/2.1.0/rubygems/command_manager.rb:138:in `run'
    C:/jimi/Ruby21-x64/lib/ruby/site_ruby/2.1.0/rubygems/gem_runner.rb:54:in `run'
    C:/jimi/Ruby21-x64/bin/gem:21:in `'

Has anyone faced similar problems and found solution to it? Unluckily google wasn't helpful this time.

Body:
I get the same error on windows 7, I fixed the problem by doing the change below:

On the file \lib\ruby\{version}\resolv.rb I changed the line below:

request[0,2] = [id].pack('n')

To

request[0,2] = [id].pack('U')

FYI: On the version 2.4.0 the line number is 772.