问:
FCM sending notification through fcm console to my ios device but from php service it is not sending the notification
FCM sending notification through fcm console to my ios device but from php service it is not sending the notification . I want to send notification to my app using FCM . I have implemented web services in php to send message to app on my app server. I created 4 services for this purpose.

group_create.php

device_add.php

device_remove.php

send_comments.php

after creating group i got a notification key successfully and register a registraion id with fcm . when i call send_comments.php with notification key , it returns json data with {"success":1,"failure":0} . But i didn't get any notification on my ios. I have implemented all methods properly. It working well with fcm console but not with php service. Can anyon eknow about this. I am attaching all 4 php files with it. Please help me.

group_create.php

```<code><?php
$url = 'https://android.googleapis.com/gcm/notification';

$notification_key_name = $_REQUEST['notification_key_name'];
$regid = $_REQUEST['regid'];
    $fields = array(
       "operation"=>"create",
       "notification_key_name"=>$notification_key_name,
       "registration_ids"=> array($regid)
);
$fields = json_encode( $fields );

$headers = array (
        "Authorization:key=A************************",
        "Content-Type:application/json",
        "project_id:78508******"
);

$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_POST, true );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $fields );

$result = curl_exec ( $ch );

//echo $result;
$res_notification_key = json_decode($result,true);

 if(array_key_exists('notification_key', $res_notification_key)){

$notification_key = $res_notification_key['notification_key'];

 echo $notification_key;

}

else{

echo $result;

}
curl_close ( $ch );
?>
</code>```

device_add.php

```<code><?php

$senderId = "785********";
$notification_key_name= $_REQUEST['notification_key_name'];
$reg_id = $_REQUEST['regid'];
$notification_key = $_REQUEST['not_key'];
$apiKey =

$url = 'https://android.googleapis.com/gcm/notification';

  $headers = array (
        "Accept:application/json",
        "Authorization:key=A******************",
        "Content-Type:application/json",
        "project_id:78508*****"
);

 $fields = array(
       "operation"=>"add",
       "notification_key_name"=> $notification_key_name,
       "registration_ids"=> array($reg_id),
       "notification_key"=>$notification_key
);
$fields = json_encode( $fields );

 $ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_POST, true );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $fields );

$result = curl_exec ( $ch );

echo $result;
$res_notification_key = json_decode($result,true);

if(array_key_exists('notification_key', $res_notification_key)){

$notification_key = $res_notification_key['notification_key'];

 echo $notification_key;

}

else{

echo $result;

}
curl_close ( $ch );
?>
</code>```

device_remove.php

```<code><?php

$senderId = "78508*****";
$notification_key_name= $_REQUEST['notification_key_name'];
$reg_id = $_REQUEST['regid'];
$notification_key = $_REQUEST['not_key'];
$apiKey =

$url = 'https://android.googleapis.com/gcm/notification';

  $headers = array (
        "Accept:application/json",
        "Authorization:key=A***********",
        "Content-Type:application/json",
        "project_id:78508*****"
);

 $fields = array(
       "operation"=>"remove",
       "notification_key_name"=> $notification_key_name,
       "registration_ids"=> array($reg_id),
       "notification_key"=>$notification_key
);
$fields = json_encode( $fields );

 $ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_POST, true );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $fields );

$result = curl_exec ( $ch );

echo $result;
$res_notification_key = json_decode($result,true);

if(array_key_exists('notification_key', $res_notification_key)){

$notification_key = $res_notification_key['notification_key'];

 echo $notification_key;

}

else{

echo $result;

}
curl_close ( $ch );
?>
</code>```

send_comments.php

```<code><?php

$senderId = "78508*****";
$notification_key = $_REQUEST['not_key'];

$url = 'https://fcm.googleapis.com/fcm/send';

  $headers = array (
        "Authorization:key=A*****************",
        "Content-Type:application/json",

);

$msg = array("hello"=>"This is a Firebase Cloud Messaging Device Group Message!");

$msg_dict = json_encode($msg);

//echo $msg_dict;

 $fields = array(
       "to"=>$notification_key,
       "data"=>array(
            "message" => "hell",

    ),
);
$fields = json_encode( $fields );

 $ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_POST, true );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $fields );

$result = curl_exec ( $ch );

echo $result;
$res_notification_key = json_decode($result,true);

curl_close ( $ch );
?>
</code>```

答:
APNs follows a format

```<code>{"aps":{"alert":"Testing.. (0)","badge":1,"sound":"default"}}
</code>```

i.e.,

```<code>{
"aps":{
"alert":"message here"
}
}
</code>```

if the format sending from server side is this,then only iPhone will display notifications,other wise notification data will only print in console through

```<code>- (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage         *)remoteMessage {
// Print full message
NSLog(@"Notification :%@", remoteMessage.appData);
}
</code>```

but not display in notifications list.

Body:
FCM sending notification through fcm console to my ios device but from php service it is not sending the notification . I want to send notification to my app using FCM . I have implemented web services in php to send message to app on my app server. I created 4 services for this purpose.

group_create.php

device_add.php

device_remove.php

send_comments.php

after creating group i got a notification key successfully and register a registraion id with fcm . when i call send_comments.php with notification key , it returns json data with {"success":1,"failure":0} . But i didn't get any notification on my ios. I have implemented all methods properly. It working well with fcm console but not with php service. Can anyon eknow about this. I am attaching all 4 php files with it. Please help me.

group_create.php

<?php
$url = 'https://android.googleapis.com/gcm/notification';

$notification_key_name = $_REQUEST['notification_key_name'];
$regid = $_REQUEST['regid'];
    $fields = array(
       "operation"=>"create",
       "notification_key_name"=>$notification_key_name,
       "registration_ids"=> array($regid)
);
$fields = json_encode( $fields );

$headers = array (
        "Authorization:key=A************************",
        "Content-Type:application/json",
        "project_id:78508******"
);

$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_POST, true );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $fields );

$result = curl_exec ( $ch );

//echo $result;
$res_notification_key = json_decode($result,true);

 if(array_key_exists('notification_key', $res_notification_key)){

$notification_key = $res_notification_key['notification_key'];

 echo $notification_key;

}

else{

echo $result;

}
curl_close ( $ch );
?>

device_add.php

<?php

$senderId = "785********";
$notification_key_name= $_REQUEST['notification_key_name'];
$reg_id = $_REQUEST['regid'];
$notification_key = $_REQUEST['not_key'];
$apiKey =

$url = 'https://android.googleapis.com/gcm/notification';

  $headers = array (
        "Accept:application/json",
        "Authorization:key=A******************",
        "Content-Type:application/json",
        "project_id:78508*****"
);

 $fields = array(
       "operation"=>"add",
       "notification_key_name"=> $notification_key_name,
       "registration_ids"=> array($reg_id),
       "notification_key"=>$notification_key
);
$fields = json_encode( $fields );

 $ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_POST, true );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $fields );

$result = curl_exec ( $ch );

echo $result;
$res_notification_key = json_decode($result,true);

if(array_key_exists('notification_key', $res_notification_key)){

$notification_key = $res_notification_key['notification_key'];

 echo $notification_key;

}

else{

echo $result;

}
curl_close ( $ch );
?>

device_remove.php

<?php

$senderId = "78508*****";
$notification_key_name= $_REQUEST['notification_key_name'];
$reg_id = $_REQUEST['regid'];
$notification_key = $_REQUEST['not_key'];
$apiKey =

$url = 'https://android.googleapis.com/gcm/notification';

  $headers = array (
        "Accept:application/json",
        "Authorization:key=A***********",
        "Content-Type:application/json",
        "project_id:78508*****"
);

 $fields = array(
       "operation"=>"remove",
       "notification_key_name"=> $notification_key_name,
       "registration_ids"=> array($reg_id),
       "notification_key"=>$notification_key
);
$fields = json_encode( $fields );

 $ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_POST, true );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $fields );

$result = curl_exec ( $ch );

echo $result;
$res_notification_key = json_decode($result,true);

if(array_key_exists('notification_key', $res_notification_key)){

$notification_key = $res_notification_key['notification_key'];

 echo $notification_key;

}

else{

echo $result;

}
curl_close ( $ch );
?>

send_comments.php

<?php

$senderId = "78508*****";
$notification_key = $_REQUEST['not_key'];

$url = 'https://fcm.googleapis.com/fcm/send';

  $headers = array (
        "Authorization:key=A*****************",
        "Content-Type:application/json",

);

$msg = array("hello"=>"This is a Firebase Cloud Messaging Device Group Message!");

$msg_dict = json_encode($msg);

//echo $msg_dict;

 $fields = array(
       "to"=>$notification_key,
       "data"=>array(
            "message" => "hell",

    ),
);
$fields = json_encode( $fields );

 $ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_POST, true );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $fields );

$result = curl_exec ( $ch );

echo $result;
$res_notification_key = json_decode($result,true);

curl_close ( $ch );
?>

Body:
APNs follows a format

{"aps":{"alert":"Testing.. (0)","badge":1,"sound":"default"}}

i.e.,

{
"aps":{
"alert":"message here"
}
}

if the format sending from server side is this,then only iPhone will display notifications,other wise notification data will only print in console through

- (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage         *)remoteMessage {
// Print full message
NSLog(@"Notification :%@", remoteMessage.appData);
}

but not display in notifications list.


来源: stackexchange

问:
Increment enum or set enum value by index
I have an enum type:

```<code>enum Day {sunday, monday, tuesday...}
</code>```

and a variable:

```<code>Day day = Day.sunday;
</code>```

I would like to be able to increment the day. something like this:

```<code>day++; // this would be wonderful
day = Day.getByIndex(day.index + 1); // something like this can also work
</code>```

But I couldn't find anything like this. Is the only option to use a switch on all days?

答:
DartPad example

```<code>enum Day {sunday, monday, tuesday}
void main() {
    var day = Day.sunday;
  print(day);
  print(Day.values[day.index + 1]);
}
</code>```

Dart enums are known to not be very powerful. I guess they'll get some overhaul eventually.

ContentLicense: CC BY-SA 3.0

Body:
I have an enum type:

enum Day {sunday, monday, tuesday...}

and a variable:

Day day = Day.sunday;

I would like to be able to increment the day. something like this:

day++; // this would be wonderful
day = Day.getByIndex(day.index + 1); // something like this can also work

But I couldn't find anything like this. Is the only option to use a switch on all days?

Body:
DartPad example

enum Day {sunday, monday, tuesday}
void main() {
    var day = Day.sunday;
  print(day);
  print(Day.values[day.index + 1]);
}

Dart enums are known to not be very powerful. I guess they'll get some overhaul eventually.


问:
Table layout panel scroll bar
given a table layout panel with 2 columns and many rows, how can i attatch a scroll bar to it as sometimes it grows much greater than the size of the form .

Thank you

答:
For shortcut :

```<code>tableLayoutPanel1.MaximumSize = new Size(tableLayoutPanel1.Width, tableLayoutPanel1.Height);
tableLayoutPanel1.AutoScroll = true;
</code>```

ContentLicense: CC BY-SA 2.5

Title: Table layout panel scroll bar

Body:
For shortcut :

tableLayoutPanel1.MaximumSize = new Size(tableLayoutPanel1.Width, tableLayoutPanel1.Height);
tableLayoutPanel1.AutoScroll = true;


问:
How to export multiple tables to single pdf
I have three tables with different columns. I want to export those three tables to single pdf.

```<code><table>
 <thead><th>test header</th></thead>
 <tbody><td>test</td></tbody>
</table>
</code>```

答:
Using jspdf Yo can export multiple tables to single pdf

Demo

JS need to add

```<code>http://cdnjs.cloudflare.com/ajax/libs/jspdf/0.9.0rc1/jspdf.min.js
</code>```

HTML

```<code><div id="content">
     <table><thead><th>test header</th></thead>
 <tbody><td>test</td></tbody>
</table>
</div>
<div id="editor"></div>
<button id="cmd">generate PDF</button>
</code>```

Script

```<code>var doc = new jsPDF();
var specialElementHandlers = {
    '#editor': function (element, renderer) {
        return true;
    }
};

$('#cmd').click(function () {
    doc.fromHTML($('#content').html(), 15, 15, {
        'width': 170,
            'elementHandlers': specialElementHandlers
    });
    doc.save('sample-file.pdf');
});
</code>```

Body:
I have three tables with different columns. I want to export those three tables to single pdf.

test header

test

Body:
Using jspdf Yo can export multiple tables to single pdf

Demo

JS need to add

http://cdnjs.cloudflare.com/ajax/libs/jspdf/0.9.0rc1/jspdf.min.js

HTML

<div id="content">
     <table><thead><th>test header</th></thead>
 <tbody><td>test</td></tbody>
</table>
</div>
<div id="editor"></div>
<button id="cmd">generate PDF</button>

Script

var doc = new jsPDF();
var specialElementHandlers = {
    '#editor': function (element, renderer) {
        return true;
    }
};

$('#cmd').click(function () {
    doc.fromHTML($('#content').html(), 15, 15, {
        'width': 170,
            'elementHandlers': specialElementHandlers
    });
    doc.save('sample-file.pdf');
});


问:
How to drop a table if it exists?
The table name is Scores.

Is it correct to do the following?

```<code>IF EXISTS(SELECT *
          FROM   dbo.Scores)
  DROP TABLE dbo.Scores
</code>```

答:
```<code>IF EXISTS (SELECT NAME FROM SYS.OBJECTS WHERE object_id = OBJECT_ID(N'Scores') AND TYPE in (N'U'))
    DROP TABLE Scores
GO
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to drop a table if it exists?

Body:
The table name is Scores.

Is it correct to do the following?

IF EXISTS(SELECT *
          FROM   dbo.Scores)
  DROP TABLE dbo.Scores


问:
Split column using awk or sed
I have a file containing  the following text.

dog

  aa  6469

  bb  5946

  cc  715

cat

  aa  5692

Bird

  aa  3056

  bb  2893

  cc  1399

  dd  33

I need the following output:

A-Z   ,aa ,bb,    cc, dd

    dog,    6469,   5946    ,715,   0

    cat ,5692,  0,  0,  0

    Bird    ,3056,  2893,   1399,   33

I tried:
awk '{$1=$1}1' OFS="," RS=
But is not giving the format I need.

Thanks in advance for your help.

Cris

答:
With Perl

```<code>perl -00 -nE'
    ($t, %p) = split /[\n\s]/; $h{$t} = {%p};     # Top line, Pairs on lines
    $o{$t} = ++$c;                                # remember Order
    %k = map { $_, 1} keys %p;                    # find full set of subKeys
    }{                                            # END block starts
    say join ",", "A-Z", sort keys %k;
    for $t (sort { $o{$a} <=> $o{$b} } keys %h) {
        say join ",", $k, map { ($h{$k}{$_} // 0) } sort keys %k;
    }
' data.txt
</code>```

prints, in the original order

```
A-Z,aa,bb,cc,dd
dog,6469,5946,715,0
cat,5692,0,0,0
Bird,3056,2893,1399,33
```

Title: Split column using awk or sed

Body:
With Perl

perl -00 -nE'
    ($t, %p) = split /[\n\s]/; $h{$t} = {%p};     # Top line, Pairs on lines
    $o{$t} = ++$c;                                # remember Order
    %k = map { $_, 1} keys %p;                    # find full set of subKeys
    }{                                            # END block starts
    say join ",", "A-Z", sort keys %k;
    for $t (sort { $o{$a} <=> $o{$b} } keys %h) {
        say join ",", $k, map { ($h{$k}{$_} // 0) } sort keys %k;
    }
' data.txt

prints, in the original order

A-Z,aa,bb,cc,dd
dog,6469,5946,715,0
cat,5692,0,0,0
Bird,3056,2893,1399,33


问:
3 Scaling images inline
So, I created an image in photoshop that is 1920x1080 and I've spliced it into sections, so that the images that require a link can have an javascript tag attached to them for a link.

I want the images to scale depending on the type of monitor you're using, as long as you're in a 16:9 ratio. The problem I'm having, is in regards to the way the images align 3 in a row. Either the 3rd image in the row gets pushed down, for sections with 3 images. Or, the image is the full size 1920x1080, but no scaling and gaps between images.

My HTML looks like this:

```<code><main>
    <section>
        <img src="images/NuclearFuelCycle1.png"/>
    </section>
    <section>
        <div><img id="1" src="images/NuclearFuelCycle2.png"/><span style="cursor:pointer" onclick="openMining()"><img id="2" src="images/NuclearFuelCycle3.png"/></span><img id="3" src="images/NuclearFuelCycle4.png"/></div>
    </section>
    <section>
        <img src="images/NuclearFuelCycle5.png"/></section>
    <section>
        <img src="images/NuclearFuelCycle6.png"/><span style="cursor:pointer" onclick="openConversion()"><img src="images/NuclearFuelCycle7.png"/></span><img src="images/NuclearFuelCycle8.png"/>
    </section>
    <section>
        <img src="images/NuclearFuelCycle9.png"/>
    </section>
    <section>
        <img src="images/NuclearFuelCycle10.png"/><span style="cursor:pointer" onclick="openEnrichment()"><img src="images/NuclearFuelCycle11.png"/></span><img src="images/NuclearFuelCycle12.png"/>
    </section>
    <section>
        <img src="images/NuclearFuelCycle13.png"/>
    </section>
    <section>
        <img src="images/NuclearFuelCycle14.png"/><span style="cursor:pointer" onclick="openReactor()"><img src="images/NuclearFuelCycle15.png"/></span><img src="images/NuclearFuelCycle16.png"/>
    </section>
    <section>
        <img src="images/NuclearFuelCycle17.png"/>
    </section>
    <section>
        <img src="images/NuclearFuelCycle18.png"/><span style="cursor:pointer" onclick="openSpentFuel()"><img src="images/NuclearFuelCycle19.png"/></span><img src="images/NuclearFuelCycle20.png"/>
    </section>
    <section>
        <img src="images/NuclearFuelCycle21.png"/>
    </section>
    <section>
        <img src="images/NuclearFuelCycle22.png"/><span style="cursor:pointer" onclick="openFuelFabrication()"><img src="images/NuclearFuelCycle23.png"/></span><img src="images/NuclearFuelCycle24.png"/>
    </section>
    <section>
        <img src="images/NuclearFuelCycle25.png"/></section>
    <section>
        <img src="images/NuclearFuelCycle26.png"/><span style="cursor:pointer" onclick="openStorageDisposal()"><img src="images/NuclearFuelCycle27.png"/></span><img src="images/NuclearFuelCycle28.png"/>
    </section>
    <section>
        <img src="images/NuclearFuelCycle29.png"/>
    </section>
</main>
</code>```

My CSS looks like this:

```<code>* {
    margin: 0;
    padding: 0;
    border: 0;
    border-collapse: collapse;
}

body {
    max-width: 100% !important;
    height: auto;
}

main {
    display: inline-block;
    padding: 10px;
}

section div img{
    width: auto;
}
</code>```

Some of this code is not useful... It's me experimenting to try and create a solution. Any help would be greatly appreciated, I have to submit this in 2 days P

答:
If I'm understanding correctly your sliced image segments are repositioning incorrectly as the browser window resizes.

Rather than slicing up your image and using javascript, why not try a pure HTML solution and use the <map> tag to insert your links at various parts of the image?

Here's a Fiddle demonstrating a scalable HTML image map (uses the image-map-resizer plugin)

You can learn more about image maps here.

Title: 3 Scaling images inline

Body:
So, I created an image in photoshop that is 1920x1080 and I've spliced it into sections, so that the images that require a link can have an javascript tag attached to them for a link.

I want the images to scale depending on the type of monitor you're using, as long as you're in a 16:9 ratio. The problem I'm having, is in regards to the way the images align 3 in a row. Either the 3rd image in the row gets pushed down, for sections with 3 images. Or, the image is the full size 1920x1080, but no scaling and gaps between images.

My HTML looks like this:

My CSS looks like this:

* {
    margin: 0;
    padding: 0;
    border: 0;
    border-collapse: collapse;
}

body {
    max-width: 100% !important;
    height: auto;
}

main {
    display: inline-block;
    padding: 10px;
}

section div img{
    width: auto;
}

Some of this code is not useful... It's me experimenting to try and create a solution. Any help would be greatly appreciated, I have to submit this in 2 days P


问:
How to set maximum and minimum date range in fullcalendar jquery
i am working in FullCalendar v2.2.5. i need to set max and min date in my full calender same as we do in datepicker.
Disable all those dates before min date and after max dates.
Please help me to sort out this issue.
Thanks in advance ..</p>

答:
```<code>$('#calendar').fullCalendar({
    defaultView: 'month',
    visibleRange: {
        start: '2017-03-22',
        end: '2017-03-25'
    }
});
</code>```

This will make only the defined date range visible in full calendar. Just put your desired start and end date with in above piece of code.

Body:
$('#calendar').fullCalendar({
    defaultView: 'month',
    visibleRange: {
        start: '2017-03-22',
        end: '2017-03-25'
    }
});

This will make only the defined date range visible in full calendar. Just put your desired start and end date with in above piece of code.


问:
Php -MySQL query failing - error Fatal error: Uncaught Error: Call to a member function fetch_assoc() on boolean
I have following php code :

```<code><?php
    $connect = mysqli_connect("localhost","root", "","archit") or die("Couldn't connect to database");
    $str = "SET @id := (SELECT ID FROM users where Name ='$u_name'); SELECT UID FROM useratt where ID = '@id';";
    echo $str;
    $query12 = mysqli_multi_query($connect,$str);
    echo $query12;
    while($row = $query12->fetch_assoc())
    {
        $str1 = "SET @UID := '".$row."';
         SELECT AttributeValue FROM att_value where UID=@UID;
         SET @AID := (SELECT AID FROM att_value WHERE UID=@UID);
         SELECT AttributeName FROM att_name WHERE AID=@AID;";
         echo $str1;
        $query1= mysqli_multi_query($connect,$str1);
        echo $row[0];
    }
?>
</code>```

I get the generic error but when I run the same code on MySQL then it works without error. Can someone please help me what am I missing .

I even tried exception handling but it didn't help.

NOTE : code fails in the while loop condition.

答:
```<code><?php
    $connect = mysqli_connect("localhost","root", "","archit") or die("Couldn't connect to database");
    $str = "SET @id := (SELECT ID FROM users where Name ='$u_name'); SELECT UID FROM useratt where ID = '@id';";
    echo $str;
    $query12 = mysqli_multi_query($connect,$str);
    echo $query12;
    while($row = mysqli_fetch_assoc($query12))
    {
        $str1 = "SET @UID := '".$row."';
         SELECT AttributeValue FROM att_value where UID=@UID;
         SET @AID := (SELECT AID FROM att_value WHERE UID=@UID);
         SELECT AttributeName FROM att_name WHERE AID=@AID;";
         echo $str1;
        $query1= mysqli_multi_query($connect,$str1);
        echo $row[0];
    }
?>
</code>```

Body:
I have following php code :

<?php
    $connect = mysqli_connect("localhost","root", "","archit") or die("Couldn't connect to database");
    $str = "SET @id := (SELECT ID FROM users where Name ='$u_name'); SELECT UID FROM useratt where ID = '@id';";
    echo $str;
    $query12 = mysqli_multi_query($connect,$str);
    echo $query12;
    while($row = $query12->fetch_assoc())
    {
        $str1 = "SET @UID := '".$row."';
         SELECT AttributeValue FROM att_value where UID=@UID;
         SET @AID := (SELECT AID FROM att_value WHERE UID=@UID);
         SELECT AttributeName FROM att_name WHERE AID=@AID;";
         echo $str1;
        $query1= mysqli_multi_query($connect,$str1);
        echo $row[0];
    }
?>

I get the generic error but when I run the same code on MySQL then it works without error. Can someone please help me what am I missing .

I even tried exception handling but it didn't help.

NOTE : code fails in the while loop condition.


问:
Rss feed on a Repeater is giving an error
I am trying to parce the Rss feed on a Repeater (or Gridview) But I am unable to. Keeps "Data at the root level is invalid. Line 1, position 1." error.         </p>

```<code>XmlDocument rssXmlDoc = new XmlDocument();
// Load the RSS file from the RSS URL
rssXmlDoc.Load("http://feeds.skynews.com/feeds/rss/home.xml");
// Parse the Items in the RSS file
XmlNodeList rssNodes = rssXmlDoc.SelectNodes("rss/channel/item");
StringBuilder rssContent = new StringBuilder();
// Iterate through the items in the RSS file
foreach (XmlNode rssNode in rssNodes)
{
    XmlNode rssSubNode = rssNode.SelectSingleNode("title");
    string title = rssSubNode != null ? rssSubNode.InnerText : "";
    rssSubNode = rssNode.SelectSingleNode("link");
    string link = rssSubNode != null ? rssSubNode.InnerText : "";
    rssSubNode = rssNode.SelectSingleNode("description");
    string description = rssSubNode != null ? rssSubNode.InnerText : "";
    // rssContent.Append("<a href='" + link + "'>" + title + "</a><br>" + description);
    rssContent.Append(description);
}
// Return the string that contain the RSS items
DataSet ds = new DataSet();
XmlTextReader reader = new XmlTextReader(new StringReader(rssContent.ToString()));
ds.ReadXml(reader);
rssRepeater.DataSource = ds.Tables[2];
rssRepeater.DataBind();
</code>```

答:
You are getting exception due to this lines of code:

```<code>XmlTextReader reader = new XmlTextReader(new StringReader(rssContent.ToString()));
ds.ReadXml(reader);
</code>```

That behavior is expected because you are trying to read rssContent as a XML which is not.

This is your rssContent after constructing StringBuilder:

Patients will have to wait longer for non-urgent operations and go
  without some new drugs under plans to be announced today.The European
  Union's approach to talks which will shape its future relationship
  with the UK is set to be laid out by European Council president Donald
  Tusk.Donald Trump's former national security adviser has reportedly
  offered to testify at hearings into alleged Russian meddling in the US
  election in exchange for immunity.Islamic State is using civilians as
  bait for coalition air strikes to create public outcry as the
  offensive in Mosul continues.Scotland's First Minister Nicola Sturgeon
  will tell Theresa May in a letter that they need to make a start on
  arrangements for an independence referendum.Excitement is building for
  the latest instalment of Game Of Thrones after a new trailer for the
  show's seventh season was released.Facebook, Google, Twitter and
  Microsoft have said they will ramp up efforts to fight terrorist
  content after a meeting with the Home Secretary.A former Power Rangers
  star has been jailed for six years after killing his roommate with a
  sword.Five people who died in a helicopter crash in Snowdonia were all
  from the same family, police have confirmed.Westminster terror killer
  Khalid Masood died from a single shot to his chest, an inquest has
  been told.

In order to prevent that issue, you must construct valid rssContent XML, or you need to completely avoid using XmlTextReader.

I would personally use XmlSerializer to deserialize XML, and then I would pass that as a DataSource into repeater.

However, this is possible solution, using your approach via XmlDocument. Firstly, you need to create class which collection will be DataSource of your repeater.

```<code>public class FeedItem
{
    public string Title { get; set; }

    public string Link { get; set; }

    public string Description { get; set; }
}
</code>```

Then, while you are traversing through the nodes, you need to populate FeedItem collection and pass that collection into repeater.

```<code>List<FeedItem> feedItems = new List<FeedItem>();
foreach (XmlNode rssNode in nodes)
{
    var feedItem = new FeedItem();

    XmlNode rssSubNode = rssNode.SelectSingleNode("title");
    feedItem.Title = rssSubNode != null ? rssSubNode.InnerText : "";

    rssSubNode = rssNode.SelectSingleNode("link");
    feedItem.Link = rssSubNode != null ? rssSubNode.InnerText : "";

    rssSubNode = rssNode.SelectSingleNode("description");
    feedItem.Description = rssSubNode != null ? rssSubNode.InnerText : "";
    // rssContent.Append("<a href='" + link + "'>" + title + "</a><br>" + description);

    feedItems.Add(feedItem);
}
rssRepeater.DataSource = feedItems; //Repeater datasource is list of FeedItem objects.
rssRepeater.DataBind();
</code>```

Body:
I am trying to parce the Rss feed on a Repeater (or Gridview) But I am unable to. Keeps "Data at the root level is invalid. Line 1, position 1." error.

XmlDocument rssXmlDoc = new XmlDocument();
// Load the RSS file from the RSS URL
rssXmlDoc.Load("http://feeds.skynews.com/feeds/rss/home.xml");
// Parse the Items in the RSS file
XmlNodeList rssNodes = rssXmlDoc.SelectNodes("rss/channel/item");
StringBuilder rssContent = new StringBuilder();
// Iterate through the items in the RSS file
foreach (XmlNode rssNode in rssNodes)
{
    XmlNode rssSubNode = rssNode.SelectSingleNode("title");
    string title = rssSubNode != null ? rssSubNode.InnerText : "";
    rssSubNode = rssNode.SelectSingleNode("link");
    string link = rssSubNode != null ? rssSubNode.InnerText : "";
    rssSubNode = rssNode.SelectSingleNode("description");
    string description = rssSubNode != null ? rssSubNode.InnerText : "";
    // rssContent.Append("" + title + "
" + description);
    rssContent.Append(description);
}
// Return the string that contain the RSS items
DataSet ds = new DataSet();
XmlTextReader reader = new XmlTextReader(new StringReader(rssContent.ToString()));
ds.ReadXml(reader);
rssRepeater.DataSource = ds.Tables[2];
rssRepeater.DataBind();

Body:
You are getting exception due to this lines of code:

XmlTextReader reader = new XmlTextReader(new StringReader(rssContent.ToString()));
ds.ReadXml(reader);

That behavior is expected because you are trying to read rssContent as a XML which is not.

This is your rssContent after constructing StringBuilder:

Patients will have to wait longer for non-urgent operations and go
  without some new drugs under plans to be announced today.The European
  Union's approach to talks which will shape its future relationship
  with the UK is set to be laid out by European Council president Donald
  Tusk.Donald Trump's former national security adviser has reportedly
  offered to testify at hearings into alleged Russian meddling in the US
  election in exchange for immunity.Islamic State is using civilians as
  bait for coalition air strikes to create public outcry as the
  offensive in Mosul continues.Scotland's First Minister Nicola Sturgeon
  will tell Theresa May in a letter that they need to make a start on
  arrangements for an independence referendum.Excitement is building for
  the latest instalment of Game Of Thrones after a new trailer for the
  show's seventh season was released.Facebook, Google, Twitter and
  Microsoft have said they will ramp up efforts to fight terrorist
  content after a meeting with the Home Secretary.A former Power Rangers
  star has been jailed for six years after killing his roommate with a
  sword.Five people who died in a helicopter crash in Snowdonia were all
  from the same family, police have confirmed.Westminster terror killer
  Khalid Masood died from a single shot to his chest, an inquest has
  been told.

In order to prevent that issue, you must construct valid rssContent XML, or you need to completely avoid using XmlTextReader.

I would personally use XmlSerializer to deserialize XML, and then I would pass that as a DataSource into repeater.

However, this is possible solution, using your approach via XmlDocument. Firstly, you need to create class which collection will be DataSource of your repeater.

public class FeedItem
{
    public string Title { get; set; }

    public string Link { get; set; }

    public string Description { get; set; }
}

Then, while you are traversing through the nodes, you need to populate FeedItem collection and pass that collection into repeater.

List<FeedItem> feedItems = new List<FeedItem>();
foreach (XmlNode rssNode in nodes)
{
    var feedItem = new FeedItem();

    XmlNode rssSubNode = rssNode.SelectSingleNode("title");
    feedItem.Title = rssSubNode != null ? rssSubNode.InnerText : "";

    rssSubNode = rssNode.SelectSingleNode("link");
    feedItem.Link = rssSubNode != null ? rssSubNode.InnerText : "";

    rssSubNode = rssNode.SelectSingleNode("description");
    feedItem.Description = rssSubNode != null ? rssSubNode.InnerText : "";
    // rssContent.Append("<a href='" + link + "'>" + title + "</a><br>" + description);

    feedItems.Add(feedItem);
}
rssRepeater.DataSource = feedItems; //Repeater datasource is list of FeedItem objects.
rssRepeater.DataBind();


问:
Prestashop console error "TypeError: jsonData is null"
I'm a newbie in Prestashop and I have problem. When somebody click the button "Add to cart", console shows error "TypeError: jsonData is null" and you can't see that product added to the cart, but if you refresh the page it will appears there.

May somebody help me solve this problem?

答:
Try replacing the all the contents of "/themes/default-bootstrap/modules/ blockcart" directory from the raw PrestaShop installation of same PrestaShop version.

Note: Don't forget to take a backup of the original file before replacing them.


问:
How to improve 2 million data query speed in Django RESTful APIs
I have a scientific research publications data of 2 Million records. I used django restframework to write apis for searching the data in title and abstract. This is taking me 12 seconds while using postgres as db, but if I used MongoDB as db, it goes down to 6seconds.

But even 6 seconds sounds a lot of waiting for user to me. I indexed the title and abstract, but abstract indexing failed because some of the abstract texts are too lengthy.

Here is the django Model using MongoDB(MongoEngine as ODM):

```<code>class Journal(Document):
    title = StringField()
    journal_title = StringField()
    abstract = StringField()
    full_text = StringField()
    pub_year = IntField()
    pub_date = DateTimeField()
    pmid = IntField()
    link = StringField()
</code>```

How do I improve the query performance, what stack makes the search and retrieval more faster?.

答:
Some pointers about optimisation for the Django ORM with Postgres:

Use db_index=True on fields that will be search upon often and have some degree of repetition between entries, like "title".

Use values() and values_list() to select only the columns you want from a QuerySet.

If you're doing full text search in any of those columns (like a contains query), bear in mind that Django has support for full text search directly on a Postgres database.

Use print queryset.query to check what kind of SQL query is going into your database and if it can be improved upon.

Many Postgres optimisation techniques rely in custom SQL queries that can be made in Django by using RawSQL expressions.

Remember that there are many, many ways to search for data in a database, be it relational or not-relational in nature. In your case, MongoDB is not "faster" than Postgres, it's just doing a better job at querying what you really want.

Body:
I have a scientific research publications data of 2 Million records. I used django restframework to write apis for searching the data in title and abstract. This is taking me 12 seconds while using postgres as db, but if I used MongoDB as db, it goes down to 6seconds.

But even 6 seconds sounds a lot of waiting for user to me. I indexed the title and abstract, but abstract indexing failed because some of the abstract texts are too lengthy.

Here is the django Model using MongoDB(MongoEngine as ODM):

class Journal(Document):
    title = StringField()
    journal_title = StringField()
    abstract = StringField()
    full_text = StringField()
    pub_year = IntField()
    pub_date = DateTimeField()
    pmid = IntField()
    link = StringField()

How do I improve the query performance, what stack makes the search and retrieval more faster?.


问:
Understanding how parameters are passed to functions in Assembly
I am reading this writeup on how to perform a ret2libc exploit.  It states that the arguments passed to a function are stored at ebp+8.

Now, if I take a simple C program

```<code>#include <stdlib.h>

int main() {
  system("/bin/sh");
}
</code>```

And compile it:
gcc -m32 -o test_sh test_sh.c

and look at the disassembly of it with
objdump -d -M intel test_sh

```<code>0804840b <main>:
 804840b:       8d 4c 24 04             lea    ecx,[esp+0x4]
 804840f:       83 e4 f0                and    esp,0xfffffff0
 8048412:       ff 71 fc                push   DWORD PTR [ecx-0x4]
 8048415:       55                      push   ebp
 8048416:       89 e5                   mov    ebp,esp
 8048418:       51                      push   ecx
 8048419:       83 ec 04                sub    esp,0x4
 804841c:       83 ec 0c                sub    esp,0xc
 804841f:       68 c4 84 04 08          push   0x80484c4
 8048424:       e8 b7 fe ff ff          call   80482e0 <system@plt>
 8048429:       83 c4 10                add    esp,0x10
 804842c:       b8 00 00 00 00          mov    eax,0x0
 8048431:       8b 4d fc                mov    ecx,DWORD PTR [ebp-0x4]
 8048434:       c9                      leave
 8048435:       8d 61 fc                lea    esp,[ecx-0x4]
 8048438:       c3                      ret
 8048439:       66 90                   xchg   ax,ax
 804843b:       66 90                   xchg   ax,ax
 804843d:       66 90                   xchg   ax,ax
 804843f:       90                      nop
</code>```

The line

```<code>804841f:       68 c4 84 04 08          push   0x80484c4
</code>```

Pushes the address of the string "/bin/sh" onto the stack.  Immediately afterwards the system@plt function is called.  So how does one arrive to ebp+8 from the above output?

Help would be appreciated!

答:
You don't because EBP + 8 is only relevant after the prologue in system@plt after creating a new procedure frame.

```<code>push    ebp
mov     ebp, esp
</code>```

at this point in system@plt the contents of memory location pointed to by EBP + 8 will equal 0x80484C4.

Body:
I am reading this writeup on how to perform a ret2libc exploit.  It states that the arguments passed to a function are stored at ebp+8.

Now, if I take a simple C program

#include <stdlib.h>

int main() {
  system("/bin/sh");
}

And compile it:
gcc -m32 -o test_sh test_sh.c

and look at the disassembly of it with
objdump -d -M intel test_sh

0804840b :
 804840b:       8d 4c 24 04             lea    ecx,[esp+0x4]
 804840f:       83 e4 f0                and    esp,0xfffffff0
 8048412:       ff 71 fc                push   DWORD PTR [ecx-0x4]
 8048415:       55                      push   ebp
 8048416:       89 e5                   mov    ebp,esp
 8048418:       51                      push   ecx
 8048419:       83 ec 04                sub    esp,0x4
 804841c:       83 ec 0c                sub    esp,0xc
 804841f:       68 c4 84 04 08          push   0x80484c4
 8048424:       e8 b7 fe ff ff          call   80482e0 <system@plt>
 8048429:       83 c4 10                add    esp,0x10
 804842c:       b8 00 00 00 00          mov    eax,0x0
 8048431:       8b 4d fc                mov    ecx,DWORD PTR [ebp-0x4]
 8048434:       c9                      leave
 8048435:       8d 61 fc                lea    esp,[ecx-0x4]
 8048438:       c3                      ret
 8048439:       66 90                   xchg   ax,ax
 804843b:       66 90                   xchg   ax,ax
 804843d:       66 90                   xchg   ax,ax
 804843f:       90                      nop

The line

804841f:       68 c4 84 04 08          push   0x80484c4

Pushes the address of the string "/bin/sh" onto the stack.  Immediately afterwards the system@plt function is called.  So how does one arrive to ebp+8 from the above output?

Help would be appreciated!

Body:
You don't because EBP + 8 is only relevant after the prologue in system@plt after creating a new procedure frame.

push    ebp
mov     ebp, esp

at this point in system@plt the contents of memory location pointed to by EBP + 8 will equal 0x80484C4.


问:
Silverlight 4 Hosting Requirement
I would like to know if what are the technical specification both hardware and software (windows OS, IIS and the like) of a server to be able to host a silverlight 4 / .net 4 / wcf web service application.

Thank you

答:
If you do not need any server-side functionality, you can use any server you want because it will just post .xap file to user. On the other hand, in you are going to  implement RIA services for example, you gonna need .net 4.0 hosting platform.

Hope this helps,
Ilya

Title: Silverlight 4 Hosting Requirement


问:
UISplitScreenController with very many (over 20) detail views
I have inherited an app that I am to update to Swift. It currently contains a TableView that selects one of twenty-six specialized calculators, each in its own ViewController/XIB file.

My first instinct is to use a Master-Detail project template and gain the advantages of the SplitView controller. All examples I have seen for a Swift app of this sort use a storyboard with explicit DetailViewControllers and Segues. It seems wrong for me to storyboard 26 separate view controllers! Is there a way to programmatically select/instantiate the DetailViewController but still use the Master-Detail paradigm?

答:
What you seek to do is achievable, but not without some custom code.

Master detail is supposed to present you with a list of similar items in the master view, with the detail view presenting you with the contents of that item. The key is that your detail vc is supposed to represent data of the same type.

If you absolutely want to use the UISplitViewController to display unrelated app flows, you will need to programatically use the showDetailViewController method on your split view controller instance to manually specify the current detail view controller. AFAIK, this doesn't seem to be doable at all with storyboards.


答:
A. The first problem is your SELECT, you write:

```<code>SELECT UID FROM useratt where ID = '@id';
</code>```

You must remove the quote at @id variable to this:

```<code>SELECT UID FROM useratt where ID = @id;
</code>```

B. After mysqli_multi_query execute, you must add two others call to get result:

Your query will return two result, first result is for set variable. And the second is that your data query. Thus, we next to move next to second result to get data:

mysqli_next_result($connect);

After move next to second result, we must get result using mysqli_store_result:

$query12 = mysqli_store_result($connect);

Hope this can help you!

Title: Php -MySQL query failing - error Fatal error: Uncaught Error: Call to a member function fetch_assoc() on boolean

Body:
A. The first problem is your SELECT, you write:

SELECT UID FROM useratt where ID = '@id';

You must remove the quote at @id variable to this:

SELECT UID FROM useratt where ID = @id;

B. After mysqli_multi_query execute, you must add two others call to get result:

Your query will return two result, first result is for set variable. And the second is that your data query. Thus, we next to move next to second result to get data:

mysqli_next_result($connect);

After move next to second result, we must get result using mysqli_store_result:

$query12 = mysqli_store_result($connect);

Hope this can help you!


问:
Show div class one by one
In blade.php file in Laravel I create a class name flip, when I click on it a class named panel is showed. Here $post_list contains some data which is collected from database table in previous controller. Using @for I can create many flip and slide class, but problem is when I click any of the flip class all slide class is showed. How can I click on one flip class and show the respective slide class?

Here is code for creating flip and panel class

```<code>@foreach($post_list as $post_list)
<div class="flip">Click to slide the panel down or up</div>
<div class="panel">
<ul>
<li>
<input type="checkbox" name="selected[]">
<label>
<img src="{{ URL::asset($post_list-->image)}}" />
<p>{{$post_list->id->name}}</p>
</label>
</li>
</ul>
</div>
@endforeach
</code>```

And here is my javascript code -

```<code><script>
$(document).ready(function(){
$(".flip").click(function(){
    $(".panel").slideToggle("slow");
});
});
</script>
</code>```

答:
```<code><script>
$(".flip").click(function(){
    $(this).closest(".panel").slideDown(500, function(){
         // do additional stuff here..
    });
});
</script>
</code>```

Title: Show div class one by one

Body:
In blade.php file in Laravel I create a class name flip, when I click on it a class named panel is showed. Here $post_list contains some data which is collected from database table in previous controller. Using @for I can create many flip and slide class, but problem is when I click any of the flip class all slide class is showed. How can I click on one flip class and show the respective slide class?

Here is code for creating flip and panel class

@foreach($post_list as $post_list)

Click to slide the panel down or up

<input type="checkbox" name="selected[]">

image)}}" />

{{$post_list->id->name}}

@endforeach

And here is my javascript code -


问:
Adding validation to upload form using jQuery validation plugin
I've got a simple HTML file upload form. I'm using the jQuery validation plugin in other forms to check for required values and would like to use this in the file upload form to ensure the user has clicked the Browse . . . button first and selected a file. The relevant code is below which is based on how other forms are setup but this one isn't working like the others:

```<code><script src="lib/jquery.js" type="text/javascript" charset="utf-8"></script>
    <script src="lib/jquery.validate.min.js" type="text/javascript" charset="utf-8"></script>
    <script src="lib/jquery.metadata.js" type="text/javascript" charset="utf-8"></script>

    <script type="text/javascript">
    $.metadata.setType("attr", "validate");

    $(document).ready(function(){
    $("#upload").validate();
    });
    </script>

<form enctype="multipart/form-data" action="fileupload.php" method="POST" id='upload'>
Choose a file to upload: <input name="new_file" type="file" validate = "required:true">
<label for = "new_file" class = "error">You must select a file first before you can upload</label>
<input type="submit" name="action" value="Upload">

</form>
</code>```

Grateful if someone can point out what I'm doing wrong.

Many thanks,
Steve

答:
Try by putting your validation script inside document.ready method. i.e.

```<code>$(document).ready(function(){
    $.metadata.setType("attr", "validate");

    $(document).ready(function(){
         $("#upload").validate();
    });
});
</code>```

working demo

Body:
I've got a simple HTML file upload form. I'm using the jQuery validation plugin in other forms to check for required values and would like to use this in the file upload form to ensure the user has clicked the Browse . . . button first and selected a file. The relevant code is below which is based on how other forms are setup but this one isn't working like the others:

<form enctype="multipart/form-data" action="fileupload.php" method="POST" id='upload'>
Choose a file to upload: <input name="new_file" type="file" validate = "required:true">
You must select a file first before you can upload
<input type="submit" name="action" value="Upload">

</form>

Grateful if someone can point out what I'm doing wrong.

Many thanks,
Steve

Body:
Try by putting your validation script inside document.ready method. i.e.

$(document).ready(function(){
    $.metadata.setType("attr", "validate");

    $(document).ready(function(){
         $("#upload").validate();
    });
});

working demo


问:
Regular expression to match (name="myName".*house="myHouse"|house="myHouse".*name="myName") without using OR
I am writing a regular expression which needs below criteria to satisfy.

```<code>(name="myName".*house="myHouse"|house="myHouse".*name="myName")
</code>```

Either name or house can come first. My Regex should match both.

Actually my real code is even more bigger after writing the repeated code.

Is there any way to use the regular expression without Repetition like above ?

答:
The only possible way to do this without the | pipe operator is to do two separate regex searches. So the answer is no, there is no other way.

Also, if this is XML or HTML that you are searching, it is highly advised that you use a parser such as Beautiful Soup instead of regex.

Body:
I am writing a regular expression which needs below criteria to satisfy.

(name="myName".*house="myHouse"|house="myHouse".*name="myName")

Either name or house can come first. My Regex should match both.

Actually my real code is even more bigger after writing the repeated code.

Is there any way to use the regular expression without Repetition like above ?


问:
python saving xlsx as csv date saves as date time
I need to read an xlsx, format the date from dd-mm-yy to yyyy-mm-dd and then save as csv for the inport to sqllite

I have everything working but when it saves as csv it converts the date to date time, e.g. 2016-11-29 becomes 2016-11-29 00:00:00. How can I have the csv be formatted to only date?

```<code>import win32com.client
from win32com.client import constants

import openpyxl
import csv
import pandas as pd
import sqlite3

f = r"Services.xlsx"

exc = win32com.client.gencache.EnsureDispatch("Excel.Application")
exc.Visible = 0
exc.Workbooks.Open(Filename=f)
exc.Rows("1:1").Select()
exc.Selection.Delete(Shift=constants.xlUp)
exc.Range("K:M").Select()
exc.Selection.NumberFormat = "yyyy-mm-dd"

exc.ActiveWorkbook.Save()
exc.Quit()

data_xls = pd.read_excel('c:\Data\Programs\Cashflow\Database\Services.xlsx', 'Sheet', index_col=None)
data_xls.to_csv('c:\Data\Programs\Cashflow\Database\Services.csv', encoding='utf-8')
</code>```

答:
You should read this answer. In your case, before calling to_csv(), add something like this:

```<code>data_xls['some_column'] = data_xls['some_column'].map(pd.Timestamp.date)
</code>```

Body:
I need to read an xlsx, format the date from dd-mm-yy to yyyy-mm-dd and then save as csv for the inport to sqllite

I have everything working but when it saves as csv it converts the date to date time, e.g. 2016-11-29 becomes 2016-11-29 00:00:00. How can I have the csv be formatted to only date?

import win32com.client
from win32com.client import constants

import openpyxl
import csv
import pandas as pd
import sqlite3

f = r"Services.xlsx"

exc = win32com.client.gencache.EnsureDispatch("Excel.Application")
exc.Visible = 0
exc.Workbooks.Open(Filename=f)
exc.Rows("1:1").Select()
exc.Selection.Delete(Shift=constants.xlUp)
exc.Range("K:M").Select()
exc.Selection.NumberFormat = "yyyy-mm-dd"

exc.ActiveWorkbook.Save()
exc.Quit()

data_xls = pd.read_excel('c:\Data\Programs\Cashflow\Database\Services.xlsx', 'Sheet', index_col=None)
data_xls.to_csv('c:\Data\Programs\Cashflow\Database\Services.csv', encoding='utf-8')

Body:
You should read this answer. In your case, before calling to_csv(), add something like this:

data_xls['some_column'] = data_xls['some_column'].map(pd.Timestamp.date)


问:
Position of a point in a circle
Hello again first part is working like a charm, thank you everyone.

But I've another question...

As I've no interface, is there a way to do the same thing with out not knowing the radius of the circle?

Should have refresh the page CodeMonkey solution is exactly what I was looking for...

Thank you again.

============================

First I'm not a developer, I'm a simple woodworker that left school far too early...

I'm trying to make one of my tool to work with an autonomous robot.
I made them communicate by reading a lot of tutorials.

But I have one problem I cant figure out.

Robot expect position of the tool as (X,Y) but tool's output is (A,B,C)
A is the distance from tool to north
B distance to east
C distance at 120 degree clockwise from east axe

the border is a circle, radius may change, and may or may not be something I know.

I've been on that for 1 month, and I can't find a way to transform those value into the position.

I made a test with 3 nails on a circle I draw on wood, and if I have the distance there is only one position possible, so I guess its possible.
But how?

Also, if someone as an answer I'd love pseudo code not code so I can practice.

If there is a tool to make a drawing I can use to make it clearer can you point it out to me?

Thank you.

hope it helps :

X, Y are coordinate from center, Da,Db, Dc are known.

Trying to make it more clear (sorry its so clear in my head).

X,Y are the coordinate of the point where is the tool (P).
Center is at 0,0

A is the point where vertical line cut the circle from P, with Da distance P to A;

B is the point where horizontal line cuts the circle fom P, with Db distance P to B.

C is the point where the line at 120 clockwise from horizontal cuts the circle from P, with Dc distance P to C.

Output from tool is an array of int (unit mm): A=123, B=114, C=89
Those are the only informations I have

thanks for all the ideas I'll try them at home later,
Hope it works :)

答:
Your problem is know a "circumscribed circle". You have a triangle define by 3 distances at given angles from your robot position, then you can construct the circumscribed circle from these three points (see Circumscribed circle from Wikipedia - section "Other properties"). So you know the diameter (if needed).

It is also known that the meeting point of perpendicular bisector of triangle sides is the center of the circumscribed circle.

Title: Position of a point in a circle


问:
How to export multiple tables to single pdf
I have three tables with different columns. I want to export those three tables to single pdf.

```<code><table>
 <thead><th>test header</th></thead>
 <tbody><td>test</td></tbody>
</table>
</code>```

答:
Simple way is that,

COPY and PASTE tables content from Browser to MS-Word

Do proper alignment of the content

Save this .doc file by selecting 'SAVE As Type' - PDF(*.pdf)

there you will get required pdf file.

Body:
I have three tables with different columns. I want to export those three tables to single pdf.

test header

test


答:
The 'spaces' problem is most likely due to the way display:inline works, which is what an image and a span is. Any newlines, etc get treated as a space char. An easy fix could be something that uses display:flex.

The second (and main part) of your problem is that you want to scale based on width. A little bit of javascript and use of transform: scale(...) fixes that. Below is a snippet (which can't show resizing), so here's a CodePen too: https://codepen.io/anon/pen/PpXpwO

window.onresize = resizer;
resizer();
function resizer() {
  console.log("resized")
  var _main = document.querySelector("main");
  var image_width = 600; // the original image width
  var ratio  = _main.offsetWidth/image_width;
  _main.style.transform = "scale("+ratio+")";
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>main {
  transform-origin: 0 0;
}
section {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
}
section * {
  flex: 0 0 auto;
  display: block;
}</code>```

```

Title: 3 Scaling images inline

Body:
The 'spaces' problem is most likely due to the way display:inline works, which is what an image and a span is. Any newlines, etc get treated as a space char. An easy fix could be something that uses display:flex.

The second (and main part) of your problem is that you want to scale based on width. A little bit of javascript and use of transform: scale(...) fixes that. Below is a snippet (which can't show resizing), so here's a CodePen too: https://codepen.io/anon/pen/PpXpwO

window.onresize = resizer;
resizer();
function resizer() {
  console.log("resized")
  var _main = document.querySelector("main");
  var image_width = 600; // the original image width
  var ratio  = _main.offsetWidth/image_width;
  _main.style.transform = "scale("+ratio+")";
};

main {
  transform-origin: 0 0;
}
section {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
}
section * {
  flex: 0 0 auto;
  display: block;
}

<main>
  <section>
    <img src="https://placehold.it/600x150g" />
  </section>
  <section>
    <img id="1" src="https://placehold.it/100x150" />
    <a style="cursor:pointer" onclick="openMining()"><img id="2" src="https://placehold.it/300x150/370000" /></a>
    <img id="3" src="https://placehold.it/200x150" />
  </section>
  <section>
    <img src="https://placehold.it/600x150g" />
  </section>
</main>


问:
When should correctly call RecyclerView's holder.itemView.performClick()?
I develop android application with adaptive design.
For "large-land" screen configuration (i.e. for tablet) user has dual-panel interface with RecyclerView header list on the left and details information (for pointed header item) on the right.

At application start, for such configuration, it will be good to emulate user's click on the first headers list item in order to cover empty details info panel.

The question "HOW" to emulate item click for RecyclerView is very popular and has been answered:
Clicking on item programmatically in RecyclerView , etc..

But I can not find the answer for the question "WHEN" I can properly call itemView.performClick() from my fragment owning the views?

My method:

```<code>public void clickItem(int position) {
  if (null == mRecyclerView)
    return;
  SingerViewHolder holder = (SingerViewHolder) mRecyclerView.findViewHolderForAdapterPosition(position);
  if (null == holder)
    return;
  holder.itemView.performClick();
}
</code>```

The performClick() skips because holder is null for any position (e.g.,0).
I've found the obvious answer: RecyclerView has not created its content yet to the moment when I call mAdapter.clickItem(0);
Of course, I call it AFTER setting the adapter and even after getting the header list info from network with notifyDataSetChanged();

Here: Clicking on item programmatically in RecyclerView suggested just to add a small pause before call itemView.performClick() in order to give android to create RecyclerView content.
Is it a correct and the only one way? I do not think so..

Not sure am I right, I've tried other workaround: How to know when the RecyclerView has finished laying down the items?
But doing that:

```<code>  mRecyclerView.getViewTreeObserver().addOnGlobalLayoutListener(
    new ViewTreeObserver.OnGlobalLayoutListener() {
  @Override
  public void onGlobalLayout() {
    if (ScreenConfiguration.getScreenConfigurationState() ==
        Constants.ScreenConfigurationState.TABLET_LANDSCAPE)
      /// dual-panel mode => click 1'st singer list item
      mAdapter.clickItem(1);
    }
  });
</code>```

we get nulled ViewHolder anyway. Also, this listener fires many-many times and has to be removed ASAP..

(sorry for looooong prehistory)

So, the question is: is there any correct callback for RecyclerView to properly get its ViewHolder valuable?

答:
You can try this</p>

```<code> new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
          recyclerView.findViewHolderForAdapterPosition(position).itemView.performClick();

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

Body:
I develop android application with adaptive design.
For "large-land" screen configuration (i.e. for tablet) user has dual-panel interface with RecyclerView header list on the left and details information (for pointed header item) on the right.

At application start, for such configuration, it will be good to emulate user's click on the first headers list item in order to cover empty details info panel.

The question "HOW" to emulate item click for RecyclerView is very popular and has been answered:
Clicking on item programmatically in RecyclerView , etc..

But I can not find the answer for the question "WHEN" I can properly call itemView.performClick() from my fragment owning the views?

My method:

public void clickItem(int position) {
  if (null == mRecyclerView)
    return;
  SingerViewHolder holder = (SingerViewHolder) mRecyclerView.findViewHolderForAdapterPosition(position);
  if (null == holder)
    return;
  holder.itemView.performClick();
}

The performClick() skips because holder is null for any position (e.g.,0).
I've found the obvious answer: RecyclerView has not created its content yet to the moment when I call mAdapter.clickItem(0);
Of course, I call it AFTER setting the adapter and even after getting the header list info from network with notifyDataSetChanged();

Here: Clicking on item programmatically in RecyclerView suggested just to add a small pause before call itemView.performClick() in order to give android to create RecyclerView content.
Is it a correct and the only one way? I do not think so..

Not sure am I right, I've tried other workaround: How to know when the RecyclerView has finished laying down the items?
But doing that:

  mRecyclerView.getViewTreeObserver().addOnGlobalLayoutListener(
    new ViewTreeObserver.OnGlobalLayoutListener() {
  @Override
  public void onGlobalLayout() {
    if (ScreenConfiguration.getScreenConfigurationState() ==
        Constants.ScreenConfigurationState.TABLET_LANDSCAPE)
      /// dual-panel mode => click 1'st singer list item
      mAdapter.clickItem(1);
    }
  });

we get nulled ViewHolder anyway. Also, this listener fires many-many times and has to be removed ASAP..

(sorry for looooong prehistory)

So, the question is: is there any correct callback for RecyclerView to properly get its ViewHolder valuable?

Body:
You can try this

 new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
          recyclerView.findViewHolderForAdapterPosition(position).itemView.performClick();

        }
    },100);


问:
AWS service endpoint region vs. signing region
Is it at all possible to invoke an AWS service whose endpoint is in a region other than the one hosting my account?

For instance, my account is in us-west-1 and SES has been removed from that region. Can I somehow invoke the SES service from us-west-2? When creating a request to send an email I cannot seem to find a way to set the service endpoint region that does not also set the signing region.

答:
Apparently, yes. The class EndpointConfiguration allows that.

http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/client/builder/AwsClientBuilder.EndpointConfiguration.html


问:
iOS VoIP Push Notification stops automatically after 1-2 seconds
I have implemented the VoIP Push. everything works fine but when app recieves push, mobile starts ringing and just after 1-2 sec(the length of my .wav file) it stops.

I want: Sound should ring until user accept/reject the call.

My solutions

I should place the lengthy sound so it keeps on
ringing?

Or i should send the Voip Push Again and again untill user cancels/attend call?

After recieving push I should localy fire the push again and again.

答:
I hope once you receive pushkit payload, then you are scheduling local notification and local notification is having sound file.

Sound file plays on 2 things, length of sound file ( 5 / 10 / 15 Seconds ) or max upto 30 seconds.

So if your sound file is less then 30 seconds, then edit your sound file and make repetitive till 30 seconds.

If you want to play sound file for more than 30 seconds then either you have reschedule local notification with sound file at each 30 seconds till user accept call or resend push kit payload from back end.

After all this things still your sound file stops in 1/2 seconds, then do check may be your app is crashing in background or terminated state.

Code

```<code>@available(iOS 8.0, *)
func pushRegistry(registry: PKPushRegistry!, didReceiveIncomingPushWithPayload payload: PKPushPayload!, forType type: String!) {
        // Process the received push

        var arrTemp = [NSObject : AnyObject]()
        arrTemp = payload.dictionaryPayload

        let dict : Dictionary <String, AnyObject> = arrTemp["aps"] as! Dictionary<String, AnyObject>

        if "IfUserHasLoggedInWithApp" // Check this flag then only proceed
        {

            if UIApplication.sharedApplication().applicationState == UIApplicationState.Background || UIApplication.sharedApplication().applicationState == UIApplicationState.Inactive
            {

                if "CheckForIncomingCall" // Check this flag to know incoming call or something else
                {

                    var strTitle : String = dict["alertTitle"] as? String ?? ""
                    let strBody : String = dict["alertBody"] as? String ?? ""
                    strTitle = strTitle + "\n" + strBody

                    let notificationIncomingCall = UILocalNotification()

                    notificationIncomingCall.fireDate = NSDate(timeIntervalSinceNow: 1)
                    notificationIncomingCall.alertBody =  strTitle
                    notificationIncomingCall.alertAction = "Open"
                    notificationIncomingCall.soundName = "SoundFile.mp3"
                    notificationIncomingCall.category = dict["category"] as? String ?? ""

                    notificationIncomingCall.userInfo = "As per payload you receive"

                    UIApplication.sharedApplication().scheduleLocalNotification(notificationIncomingCall)

                    }
                    else
                    {
                        //  something else
                    }

        }
    }

}
</code>```

Debug pushkit notification in terminated state

Put debug pointer on delegate methods

Go to edit scheme

Select run option then Launch -> Wait for executable to be launched

Send push kit payload from back end

Once you get payload on device

it will automatically invoke and debug pointer will invoke at delegate methods.

You can refer some details here.

https://github.com/hasyapanchasara/PushKit_SilentPushNotification

Body:
I hope once you receive pushkit payload, then you are scheduling local notification and local notification is having sound file.

Sound file plays on 2 things, length of sound file ( 5 / 10 / 15 Seconds ) or max upto 30 seconds.

So if your sound file is less then 30 seconds, then edit your sound file and make repetitive till 30 seconds.

If you want to play sound file for more than 30 seconds then either you have reschedule local notification with sound file at each 30 seconds till user accept call or resend push kit payload from back end.

After all this things still your sound file stops in 1/2 seconds, then do check may be your app is crashing in background or terminated state.

Code

@available(iOS 8.0, *)
func pushRegistry(registry: PKPushRegistry!, didReceiveIncomingPushWithPayload payload: PKPushPayload!, forType type: String!) {
        // Process the received push

        var arrTemp = [NSObject : AnyObject]()
        arrTemp = payload.dictionaryPayload

        let dict : Dictionary <String, AnyObject> = arrTemp["aps"] as! Dictionary<String, AnyObject>

        if "IfUserHasLoggedInWithApp" // Check this flag then only proceed
        {

            if UIApplication.sharedApplication().applicationState == UIApplicationState.Background || UIApplication.sharedApplication().applicationState == UIApplicationState.Inactive
            {

                if "CheckForIncomingCall" // Check this flag to know incoming call or something else
                {

                    var strTitle : String = dict["alertTitle"] as? String ?? ""
                    let strBody : String = dict["alertBody"] as? String ?? ""
                    strTitle = strTitle + "\n" + strBody

                    let notificationIncomingCall = UILocalNotification()

                    notificationIncomingCall.fireDate = NSDate(timeIntervalSinceNow: 1)
                    notificationIncomingCall.alertBody =  strTitle
                    notificationIncomingCall.alertAction = "Open"
                    notificationIncomingCall.soundName = "SoundFile.mp3"
                    notificationIncomingCall.category = dict["category"] as? String ?? ""

                    notificationIncomingCall.userInfo = "As per payload you receive"

                    UIApplication.sharedApplication().scheduleLocalNotification(notificationIncomingCall)

                    }
                    else
                    {
                        //  something else
                    }

        }
    }

}

Debug pushkit notification in terminated state

Put debug pointer on delegate methods

Go to edit scheme

Select run option then Launch -> Wait for executable to be launched

Send push kit payload from back end

Once you get payload on device

it will automatically invoke and debug pointer will invoke at delegate methods.

You can refer some details here.

https://github.com/hasyapanchasara/PushKit_SilentPushNotification


问:
How do I create a MongoDB dump of my database?
What command should I use to create a MongoDB dump of my database?</p>

答:
mongodump -h hostname -u dbusername -p dbpassword --db dbname --port portnumber --out /path/folder

mongodump -h hostname -u dbusername -p dbpassword --db dbname --port portnumber --out /path/folder.gz


问:
Remove/hide category bar from custom page
I have registered new controller in order to display new page. It works fine I was able to hide left column by calling:

```<code>public function init()
{
    $this->page_name = 'My products';
    $this->disableBlocks();
    parent::init();
}

protected function disableBlocks()
{
    $this->display_column_left = false;
}
</code>```

in controller. Although I still have this bar present:

How can I hide it for my current controller (only for my custom one)? Of course prefered way is using some hooks or something, not just override template in theme. Is there maybe any other way to define layout for controller page.

答:
You should render a TPL file using your custom controller and write the following CSS code in it to hide the Top Menu bar:

```<code>#block_top_menu {
    display: none;
}
</code>```

Note: You can also use some JS (or JQuery) to do it using the same procedure.

Body:
I have registered new controller in order to display new page. It works fine I was able to hide left column by calling:

public function init()
{
    $this->page_name = 'My products';
    $this->disableBlocks();
    parent::init();
}

protected function disableBlocks()
{
    $this->display_column_left = false;
}

in controller. Although I still have this bar present:

How can I hide it for my current controller (only for my custom one)? Of course prefered way is using some hooks or something, not just override template in theme. Is there maybe any other way to define layout for controller page.

Body:
You should render a TPL file using your custom controller and write the following CSS code in it to hide the Top Menu bar:

#block_top_menu {
    display: none;
}

Note: You can also use some JS (or JQuery) to do it using the same procedure.


问:
Cannot convert content scheme uri to file path
I put .jpg , .pdf , .docx , .xlx , .mp3 , .mp4  type of fine on same location of sd-card (External memory card)

When i try to choose file then i able to choose only .jpg , .pdf file other type of file not choosen

Chosen file :->

```<code> 1.path : `/storage/emulated/0/123.pdf`  (from this path i successfully attached file)
 2. path : `/storage/emulated/0/Program.docx`
 3. path : `/storage/emulated/0/ApiCalling.mp4`
</code>```

Error is :

file are not exists.. when i get 2. and 3. number of path

Code is :

```<code> public static void showFileChooser(Context context) {
    PICK_IMAGE_REQUEST = 2;
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("*/*");
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    try {
        ((Activity) context).startActivityForResult(
                Intent.createChooser(intent, context.getResources().getString(R.string.select_file_msg)),
                PICK_IMAGE_REQUEST);
    } catch (android.content.ActivityNotFoundException ex) {
       e.print();
    }
}
</code>```

```<code>protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Uri uri = data.getData();
         try {
                String path = Utility.getRealPathFromURI(this, uri);
                Log.e("path -> ",path);
                File f = new File(path);
                if (f.exists()) {
                }
                else
                {
                    Log.e("err -> ","file not exists");
                }
            }
    }
</code>```

```<code>public static String getRealPathFromURI(Context context, Uri uri) throws URISyntaxException {
    String selection = null;
    String[] selectionArgs = null;
    // Uri is different in versions after KITKAT (Android 4.4), we need to
    if (uri != null) {
        if (Build.VERSION.SDK_INT >= 19 && DocumentsContract.isDocumentUri(context.getApplicationContext(), uri)) {
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            } else if (isDownloadsDocument(uri)) {
                final String id = DocumentsContract.getDocumentId(uri);
                uri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
            } else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                if ("image".equals(type)) {
                    uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                selection = "_id=?";
                selectionArgs = new String[]{
                        split[1]
                };
            }
        }

        if ("content".equalsIgnoreCase(uri.getScheme())) {
            String[] projection = {
                    MediaStore.Images.Media.DATA
            };
            Cursor cursor = null;
            try {
                cursor = context.getContentResolver()
                        .query(uri, projection, selection, selectionArgs, null);
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                if (cursor.moveToFirst()) {
                    return cursor.getString(column_index);
                }
            } catch (Exception e) {
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
    }

    return null;
}

public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}
</code>```

答: There's no guarantee that the content the user selected is on external storage and/or is backed by a file. Even if it is, chances are you don't have access to it. But you can simply use ContentResolver.openInputStream() with the Uri from the data field of the result Intent to read the data.

Body:
I put .jpg , .pdf , .docx , .xlx , .mp3 , .mp4  type of fine on same location of sd-card (External memory card)

When i try to choose file then i able to choose only .jpg , .pdf file other type of file not choosen

Chosen file :->

 1.path : `/storage/emulated/0/123.pdf`  (from this path i successfully attached file)
 2. path : `/storage/emulated/0/Program.docx`
 3. path : `/storage/emulated/0/ApiCalling.mp4`

Error is :

file are not exists.. when i get 2. and 3. number of path

Code is :

 public static void showFileChooser(Context context) {
    PICK_IMAGE_REQUEST = 2;
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("*/*");
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    try {
        ((Activity) context).startActivityForResult(
                Intent.createChooser(intent, context.getResources().getString(R.string.select_file_msg)),
                PICK_IMAGE_REQUEST);
    } catch (android.content.ActivityNotFoundException ex) {
       e.print();
    }
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Uri uri = data.getData();
         try {
                String path = Utility.getRealPathFromURI(this, uri);
                Log.e("path -> ",path);
                File f = new File(path);
                if (f.exists()) {
                }
                else
                {
                    Log.e("err -> ","file not exists");
                }
            }
    }

public static String getRealPathFromURI(Context context, Uri uri) throws URISyntaxException {
    String selection = null;
    String[] selectionArgs = null;
    // Uri is different in versions after KITKAT (Android 4.4), we need to
    if (uri != null) {
        if (Build.VERSION.SDK_INT >= 19 && DocumentsContract.isDocumentUri(context.getApplicationContext(), uri)) {
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            } else if (isDownloadsDocument(uri)) {
                final String id = DocumentsContract.getDocumentId(uri);
                uri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
            } else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                if ("image".equals(type)) {
                    uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                selection = "_id=?";
                selectionArgs = new String[]{
                        split[1]
                };
            }
        }

        if ("content".equalsIgnoreCase(uri.getScheme())) {
            String[] projection = {
                    MediaStore.Images.Media.DATA
            };
            Cursor cursor = null;
            try {
                cursor = context.getContentResolver()
                        .query(uri, projection, selection, selectionArgs, null);
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                if (cursor.moveToFirst()) {
                    return cursor.getString(column_index);
                }
            } catch (Exception e) {
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
    }

    return null;
}

public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}


问:
Print page content overwriting on header
page content over writing the header on the second page, please check the below code

```<code> @media screen {
     div.divHeader
            {
                display: none;
            }
    }
    @media print {
      div.divHeader
            {
                position: fixed;
                top: 0;
            }
             div.divContent
            {
                 position: fixed;
                 top: 120px;
            }

    }
</code>```

答: Yes. That's because it is fixed. Therefore, it is shown in every page. Instead, change it to the absolute position.</p>

Body:
page content over writing the header on the second page, please check the below code

 @media screen {
     div.divHeader
            {
                display: none;
            }
    }
    @media print {
      div.divHeader
            {
                position: fixed;
                top: 0;
            }
             div.divContent
            {
                 position: fixed;
                 top: 120px;
            }

    }


问:
How to adjust the indent of the header of a TableView in Swift?
I know how to set the header text and style it, but for the life of me, I cannot find anything that explains how to adjust the indent of the text. This is what I tried:

```<code>func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int){
    let header = view as! UITableViewHeaderFooterView
    header.textLabel?.translatesAutoresizingMaskIntoConstraints = false
    header.textLabel?.leftAnchor.constraint(equalTo: header.leftAnchor, constant: 15).isActive = true
}
</code>```

The code above (and every variation I've tried) results in the error:

Unable to activate constraints because they have no common ancestor.

Which causes me to say to my computer, "If header.textLabel got me to the UILabel, and header is indeed a UITableViewHeaderFooterView, I reckon that you oughta know that one is the ancestor of another!"

答:
You can do this by first setting the separatorInset for the entire TableView like this:

```<code>let headerInset: CGFloat = 50
tableView.separatorInset = UIEdgeInsets.init(top: 0, left: headerInset, bottom: 0, right: 0)
</code>```

Then if you want to position the cells of the table to lineup with the edge of the TableView, you can do this in the forRowAt indexPath method:

```<code>func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

    cell.separatorInset = UIEdgeInsets.zero

}
</code>```

Body:
I know how to set the header text and style it, but for the life of me, I cannot find anything that explains how to adjust the indent of the text. This is what I tried:

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int){
    let header = view as! UITableViewHeaderFooterView
    header.textLabel?.translatesAutoresizingMaskIntoConstraints = false
    header.textLabel?.leftAnchor.constraint(equalTo: header.leftAnchor, constant: 15).isActive = true
}

The code above (and every variation I've tried) results in the error:

Unable to activate constraints because they have no common ancestor.

Which causes me to say to my computer, "If header.textLabel got me to the UILabel, and header is indeed a UITableViewHeaderFooterView, I reckon that you oughta know that one is the ancestor of another!"

Body:
You can do this by first setting the separatorInset for the entire TableView like this:

let headerInset: CGFloat = 50
tableView.separatorInset = UIEdgeInsets.init(top: 0, left: headerInset, bottom: 0, right: 0)

Then if you want to position the cells of the table to lineup with the edge of the TableView, you can do this in the forRowAt indexPath method:

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

    cell.separatorInset = UIEdgeInsets.zero

}


问:
Resize Named Range VBA
VBA
Excel 2016

I'm trying to dynamically resize a range if the number of columns is less for that range after some code is executed. Referenced the MS files and various online examples with no luck. https://msdn.microsoft.com/en-us/library/office/ff193274.aspx

I can achieve the correct resize only if I do something like "testRange.Resize Range("A1:G1"). However I am looking for something along the lines of:

```<code>Sub Test_Range()

  Dim Test As Worksheet
  Set Test = Worksheets("test")

  Dim testTable As Range
  Set testTable = Test.Range("testTable[]")

  Dim testTableWidth, testNumbersWidth As Integer
  Set testTableWidth = testTable.Columns.Count

  'Some code
  'testNumbersWith is defined here

  If testNumbersWidth < testTableWidth Then
    testTable.Resize(, testNumbersWidth)
  End If

End Sub
</code>```

答:
The  method to resize a "Named Range" is different if it is a "normal" named range or a "Table" (ListObject) range. Your title refers to the first case but from your code it seems you are working with a table.

For the case of a named range, you change the scope like this (i.e. to change the number of columns):

```<code>With ThisWorkbook.Names.Item("testTable")
    .RefersTo = .RefersToRange.Resize(, newColumnsCount)
End With
</code>```

For the case of a Table (ListObject), which seems to be your case, you can change the number of columns like this:

```<code>  Dim testTable As ListObject             ' <-- Declare as ListObject
  Set testTable = Test.ListObjects("testTable")
  ' Or Set testTable = Test.Range("testTable")

  'Some code
  ' ....

   testTable.Resize testTable.Range.Resize(, newColumnsCount) ' <-- resize number of cols
</code>```

Title: Resize Named Range VBA

Body:
VBA
Excel 2016

I'm trying to dynamically resize a range if the number of columns is less for that range after some code is executed. Referenced the MS files and various online examples with no luck. https://msdn.microsoft.com/en-us/library/office/ff193274.aspx

I can achieve the correct resize only if I do something like "testRange.Resize Range("A1:G1"). However I am looking for something along the lines of:

Sub Test_Range()

  Dim Test As Worksheet
  Set Test = Worksheets("test")

  Dim testTable As Range
  Set testTable = Test.Range("testTable[]")

  Dim testTableWidth, testNumbersWidth As Integer
  Set testTableWidth = testTable.Columns.Count

  'Some code
  'testNumbersWith is defined here

  If testNumbersWidth < testTableWidth Then
    testTable.Resize(, testNumbersWidth)
  End If

End Sub

Body:
The  method to resize a "Named Range" is different if it is a "normal" named range or a "Table" (ListObject) range. Your title refers to the first case but from your code it seems you are working with a table.

For the case of a named range, you change the scope like this (i.e. to change the number of columns):

With ThisWorkbook.Names.Item("testTable")
    .RefersTo = .RefersToRange.Resize(, newColumnsCount)
End With

For the case of a Table (ListObject), which seems to be your case, you can change the number of columns like this:

  Dim testTable As ListObject             ' <-- Declare as ListObject
  Set testTable = Test.ListObjects("testTable")
  ' Or Set testTable = Test.Range("testTable")

  'Some code
  ' ....

   testTable.Resize testTable.Range.Resize(, newColumnsCount) ' <-- resize number of cols


问:
Date format issue
I'm facing problem while conversion of date

if I used -- Date.parse("28/01/2011")
it gives me error as

"String was not recognized as a valid DateTime."

so then I modify above code as -- CDate("28/01/2011")
it gives me error as

"Cast from string "28/01/2011" to type 'Date' is not valid."

I used convert.todatetime also date.parseexact but nothing is working...

I'm using VS2003 in asp.net1.1 with vb.net

答:
Probably Parse is using InvariantCulture date format "MM/dd/yyyy". Maybe you can try with

```<code>DateTime.ParseExact("28/01/2011", "dd/MM/yyyy", CultureInfo.InvariantCulture)
</code>```

or passing a correct culture on Parse, like spanish that has date format dd/MM/yyyy

```<code>Date.Parse("28/01/2011", new CultureInfo("es-ES", true));
</code>```

Write from memory, maybe is not accurate

Title: Date format issue

Body:
Probably Parse is using InvariantCulture date format "MM/dd/yyyy". Maybe you can try with

DateTime.ParseExact("28/01/2011", "dd/MM/yyyy", CultureInfo.InvariantCulture)

or passing a correct culture on Parse, like spanish that has date format dd/MM/yyyy

Date.Parse("28/01/2011", new CultureInfo("es-ES", true));

Write from memory, maybe is not accurate


问:
What is the proper way of using Set property in an angular2 model
In one of my models I wish to have a numbers property with unique numbers. Numbers are selectable checkboxes and I wish to use 2 way data binding with a set. What is the correct way to do it? Here's my code

Model

```<code>export class User {
    constructor(
        public id: number,
        public numbers: any
    ){}
}
</code>```

Component

```<code>import {Component} from '@angular/core';
import {User} from "./user.model";

@Component({
  selector: 'my-page-user',
  styleUrls: ['./user.component.scss'],
  templateUrl: './user.component.html',
})

export class PageUserComponent {
numbers: number[];
model: User;
constructor() { }

ngOnInit() {
    this.model = new User(0, new Set());
    this.numbers = Array.from(new Array(10), (x,i) => i+1);

}
</code>```

Template

```<code><form role="form" #userForm="ngForm" (ngSubmit)="onSubmit()">
   <div class="row">
      <div class="col-4 cell" *ngFor="let num of numbers; let i=index" >
         <md-checkbox [(ngModel)]="model.numbers[i]" name="numbers">{{i}}</md-checkbox>
      </div>
  </div>
</form>
{{model.numbers | json}} <!-- {"1": true, "2": true, "3": false } -->
{{model.numbers.size}} <!-- 0 -->
</code>```

答:
It should be length instead of size

```<code>{{model.numbers.length}}
</code>```

Plunker example

Body:
In one of my models I wish to have a numbers property with unique numbers. Numbers are selectable checkboxes and I wish to use 2 way data binding with a set. What is the correct way to do it? Here's my code

Model

export class User {
    constructor(
        public id: number,
        public numbers: any
    ){}
}

Component

import {Component} from '@angular/core';
import {User} from "./user.model";

@Component({
  selector: 'my-page-user',
  styleUrls: ['./user.component.scss'],
  templateUrl: './user.component.html',
})

export class PageUserComponent {
numbers: number[];
model: User;
constructor() { }

ngOnInit() {
    this.model = new User(0, new Set());
    this.numbers = Array.from(new Array(10), (x,i) => i+1);

}

Template

<form role="form" #userForm="ngForm" (ngSubmit)="onSubmit()">

         <md-checkbox [(ngModel)]="model.numbers[i]" name="numbers">{{i}}</md-checkbox>

</form>
{{model.numbers | json}}
{{model.numbers.size}}

Body:
It should be length instead of size

{{model.numbers.length}}

Plunker example


问:
T-SQL : return latest value of each ID
I have a table looks like

```<code>ID, name, Likes, Login_time
</code>```

select * from mytbl

I want to filter this table:

```<code>distinct ID, name like, login_time(last login time)
</code>```

I tried this query, but it didn't work.

```<code>select *
from
    (select
         name, likes, login_time
         rank() over (partition by id order by login_time desc) as rank
     from
         mytbl) t
where
    t.rank = 1
</code>```

答:
use row_number instead of rank</p>

```<code>select *
from
(
select
        id, name, likes, login_time,
         ROW_NUMBER() over (partition by id order by login_time desc) as rank
     from
         mytbl )t
where
    t.rank = 1
</code>```

Title: T-SQL : return latest value of each ID

Body:
I have a table looks like

ID, name, Likes, Login_time

select * from mytbl

I want to filter this table:

distinct ID, name like, login_time(last login time)

I tried this query, but it didn't work.

select *
from
    (select
         name, likes, login_time
         rank() over (partition by id order by login_time desc) as rank
     from
         mytbl) t
where
    t.rank = 1

Body:
use row_number instead of rank

select *
from
(
select
        id, name, likes, login_time,
         ROW_NUMBER() over (partition by id order by login_time desc) as rank
     from
         mytbl )t
where
    t.rank = 1


问:
Show div class one by one
In blade.php file in Laravel I create a class name flip, when I click on it a class named panel is showed. Here $post_list contains some data which is collected from database table in previous controller. Using @for I can create many flip and slide class, but problem is when I click any of the flip class all slide class is showed. How can I click on one flip class and show the respective slide class?

Here is code for creating flip and panel class

```<code>@foreach($post_list as $post_list)
<div class="flip">Click to slide the panel down or up</div>
<div class="panel">
<ul>
<li>
<input type="checkbox" name="selected[]">
<label>
<img src="{{ URL::asset($post_list-->image)}}" />
<p>{{$post_list->id->name}}</p>
</label>
</li>
</ul>
</div>
@endforeach
</code>```

And here is my javascript code -

```<code><script>
$(document).ready(function(){
$(".flip").click(function(){
    $(".panel").slideToggle("slow");
});
});
</script>
</code>```

答:
Try this</p>

```<code><script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

<script type="text/javascript">
    $(document).on('click','.flip',function(){
    $(this).next('.panel').slideToggle("slow");
});
</script>
</code>```

Title: Show div class one by one

Body:
In blade.php file in Laravel I create a class name flip, when I click on it a class named panel is showed. Here $post_list contains some data which is collected from database table in previous controller. Using @for I can create many flip and slide class, but problem is when I click any of the flip class all slide class is showed. How can I click on one flip class and show the respective slide class?

Here is code for creating flip and panel class

@foreach($post_list as $post_list)

Click to slide the panel down or up

<input type="checkbox" name="selected[]">

image)}}" />

{{$post_list->id->name}}

@endforeach

And here is my javascript code -

Body:
Try this

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

<script type="text/javascript">
    $(document).on('click','.flip',function(){
    $(this).next('.panel').slideToggle("slow");
});
</script>


问:
StatusStrip label not visible when text too long
I have a StatusStrip docked to the bottom of a C# Form, it contains a label, the text in it displays fine, except when there is longer length of text then it does not display at all, and I have to widen the form and then all of a sudden it appears. Is it possible to show it in the form below:

```<code>    This is a very long tex...
</code>```

So that the user knows that the app is showing something and then he can widen it himself, because when it is not visible at all, it does not indicate anything to user.

答:
On Visual Studio 2017, the accepted answer didn't work for me. So here is another simple solution.
 Set LayoutStyle property of StatusStrip to Flow. i.e:

```<code> statusStrip1.LayoutStyle= LayoutStyle.Flow;
</code>```

And Set

```<code>`statusStrip1.AutoSize= false;`
</code>```

Body:
I have a StatusStrip docked to the bottom of a C# Form, it contains a label, the text in it displays fine, except when there is longer length of text then it does not display at all, and I have to widen the form and then all of a sudden it appears. Is it possible to show it in the form below:

    This is a very long tex...

So that the user knows that the app is showing something and then he can widen it himself, because when it is not visible at all, it does not indicate anything to user.

Body:
On Visual Studio 2017, the accepted answer didn't work for me. So here is another simple solution.
 Set LayoutStyle property of StatusStrip to Flow. i.e:

 statusStrip1.LayoutStyle= LayoutStyle.Flow;

And Set

`statusStrip1.AutoSize= false;`


问:
SKErrorDomain Code=0 "Cannot connect to iTunes Store" in IAP iOS Objective c
when i tested IAP for my app, it throws following error

```<code>Error Domain=SKErrorDomain Code=0 "Cannot connect to iTunes Store"
UserInfo={NSLocalizedDescription=Cannot connect to iTunes Store}
</code>```

i have tried many links related to this problem but nothing helped.
Moreover the "Product Identifier" are also correct and i also created new sandbox user, but no output. Any help would be great.

答: SKPaymentTransactionStatePurchased is not called in Live purchases, Only SKPaymentTransactionStateFailed is called but amount has been deducted from user account. Now user should click the restore button to restore the purchased products. We don't know the solution for this. Now It is the big headache for all the IOS developers. Apple's servers are down for Sandbox environment.

Body:
when i tested IAP for my app, it throws following error

Error Domain=SKErrorDomain Code=0 "Cannot connect to iTunes Store"
UserInfo={NSLocalizedDescription=Cannot connect to iTunes Store}

i have tried many links related to this problem but nothing helped.
Moreover the "Product Identifier" are also correct and i also created new sandbox user, but no output. Any help would be great.