问:
How to create a custom arrow with two colors?
I would like to create a custom shape like this image

My HTML :

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

            aaaaa

                mmm

                nnnn

```

答:
You can simply use pseudo element and data attribute. You will be able de generate the HTML from backend without changing CSS (you simply need to adjust the color as you need) :

* {
  box-sizing: border-box;
}

.element {
  display: inline-block;
  position: relative;
  padding: 10px 40px;
  background: #ccc;
  border: 1px solid #000;
}

.element:before {
  content: attr(data-before);
  position: absolute;
  top: 0;
  bottom: 50%;
  right: -42px;
  width: 40px;
  background-image: linear-gradient(45deg, black, red);
  border-top-right-radius: 100%;
  border: 1px solid #000;
  color: #fff;
  z-index:99;
}

.element:after {
  content: attr(data-after);
  position: absolute;
  top: 50%;
  bottom: 0;
  right: -42px;
  width: 40px;
  background-image: linear-gradient(45deg, black, green);
  border-bottom-right-radius: 100%;
  border: 1px solid #000;
  color: #fff;
  z-index:99;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="element" data-before="A" data-after="B">
  content 1
</div>
<div class="element" data-before="C" data-after="D">
  content 2
</div>
<div class="element" data-before="E" data-after="F">
  content 3
</div></code>```

Body:
You can simply use pseudo element and data attribute. You will be able de generate the HTML from backend without changing CSS (you simply need to adjust the color as you need) :

* {
  box-sizing: border-box;
}

.element {
  display: inline-block;
  position: relative;
  padding: 10px 40px;
  background: #ccc;
  border: 1px solid #000;
}

.element:before {
  content: attr(data-before);
  position: absolute;
  top: 0;
  bottom: 50%;
  right: -42px;
  width: 40px;
  background-image: linear-gradient(45deg, black, red);
  border-top-right-radius: 100%;
  border: 1px solid #000;
  color: #fff;
  z-index:99;
}

.element:after {
  content: attr(data-after);
  position: absolute;
  top: 50%;
  bottom: 0;
  right: -42px;
  width: 40px;
  background-image: linear-gradient(45deg, black, green);
  border-bottom-right-radius: 100%;
  border: 1px solid #000;
  color: #fff;
  z-index:99;
}

<div class="element" data-before="A" data-after="B">
  content 1
</div>
<div class="element" data-before="C" data-after="D">
  content 2
</div>
<div class="element" data-before="E" data-after="F">
  content 3
</div>


来源: stackexchange

问:
Java FXScene Builder load into NetBeans throwing errors
I'm trying to stumble through integrating fxml into java for a GUI for the final phase of a solution, and it's throwing errors on autogenerated code:

```<code>  <TableView layoutX="297.0" layoutY="156.0" prefHeight="237.0" prefWidth="523.0">
    <columns>
      <TableColumn editable="false" prefWidth="64.0" text="Element" />
      <TableColumn editable="false" prefWidth="171.0" text="Weight Fraction" />
        <TableColumn editable="false" prefWidth="188.0" text="Atom Fraction" />
    </columns>
     <columnResizePolicy>
        <TableView fx:constant="CONSTRAINED_RESIZE_POLICY" /> <-------
     </columnResizePolicy>
  </TableView>
</code>```

is giving

```<code>Constant 'CONSTRAINED_RESIZE_POLICY' is not defined for 'TableView'
</code>```

Given that I already am having trouble following the guide at https://docs.oracle.com/javafx/scenebuilder/1/use_java_ides/sb-with-nb.htm , specifically regarding the drag and drop functionality (dragging object into a make controller just gives xml instead of anything I can use), this is just further confusing.

答:
The application will still build and run correctly despite this error being shown in the IDE.  However, it is annoying to see false red explanation points all over the place.  So until a fix can be applied, a safe alternative is to set this property in the java code by using the TableView's columnResizePolicy method: </p>

```<code>myTableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to stumble through integrating fxml into java for a GUI for the final phase of a solution, and it's throwing errors on autogenerated code:

  <TableView layoutX="297.0" layoutY="156.0" prefHeight="237.0" prefWidth="523.0">
    <columns>
      <TableColumn editable="false" prefWidth="64.0" text="Element" />
      <TableColumn editable="false" prefWidth="171.0" text="Weight Fraction" />
        <TableColumn editable="false" prefWidth="188.0" text="Atom Fraction" />
    </columns>
     <columnResizePolicy>
        <TableView fx:constant="CONSTRAINED_RESIZE_POLICY" /> <-------
     </columnResizePolicy>
  </TableView>

is giving

Constant 'CONSTRAINED_RESIZE_POLICY' is not defined for 'TableView'

Given that I already am having trouble following the guide at https://docs.oracle.com/javafx/scenebuilder/1/use_java_ides/sb-with-nb.htm , specifically regarding the drag and drop functionality (dragging object into a make controller just gives xml instead of anything I can use), this is just further confusing.

Body:
The application will still build and run correctly despite this error being shown in the IDE.  However, it is annoying to see false red explanation points all over the place.  So until a fix can be applied, a safe alternative is to set this property in the java code by using the TableView's columnResizePolicy method:

myTableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);


问:
How to use SearchManager in local app?
Hi all,

I have a activity which have a listview. I need to refine the listview by people's inputs.

I have tried to implement it by following the topic http://developer.android.com/guide/topics/search/search-dialog.html. but the problem is that I can only get the default searchbar (which can search contacts or any words in browser) from system after press the search button.

So my question is how to implement a search locally?

Thank you in advance.

In the searchable activity ListActivity:

```<code>@Override
public boolean onSearchRequested(){
    Bundle bundle=new Bundle();
    bundle.putString("data", "data");
    startSearch(null, false, bundle, false);
    return true;
}
</code>```

In the manifest:

```<code><searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="DiseaseListActivity"
android:hint="Search Diseases..."
android:searchMode="showSearchLabelAsBadge"
android:voiceSearchMode="showVoiceSearchButton|launchRecognizer"
android:voiceLanguageModel="free_form"
android:voicePromptText="Please Speak"
</code>```

/>

The searchable.xml:

```<code><searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="DiseaseListActivity"
android:hint="Search Diseases..."
android:searchMode="showSearchLabelAsBadge"
android:voiceSearchMode="showVoiceSearchButton|launchRecognizer"
android:voiceLanguageModel="free_form"
android:voicePromptText="Please Speak"/>
</code>```

答:
Problem solved, in searchable.xml, we cannot use static string, instead, we should use reference like

```<code>android:label="@string/app_name"
</code>```

Thank you all.

Chris

ContentLicense: CC BY-SA 2.5

Title: How to use SearchManager in local app?

Body:
Hi all,

I have a activity which have a listview. I need to refine the listview by people's inputs.

I have tried to implement it by following the topic http://developer.android.com/guide/topics/search/search-dialog.html. but the problem is that I can only get the default searchbar (which can search contacts or any words in browser) from system after press the search button.

So my question is how to implement a search locally?

Thank you in advance.

In the searchable activity ListActivity:

@Override
public boolean onSearchRequested(){
    Bundle bundle=new Bundle();
    bundle.putString("data", "data");
    startSearch(null, false, bundle, false);
    return true;
}

In the manifest:

<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="DiseaseListActivity"
android:hint="Search Diseases..."
android:searchMode="showSearchLabelAsBadge"
android:voiceSearchMode="showVoiceSearchButton|launchRecognizer"
android:voiceLanguageModel="free_form"
android:voicePromptText="Please Speak"

/>

The searchable.xml:

<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="DiseaseListActivity"
android:hint="Search Diseases..."
android:searchMode="showSearchLabelAsBadge"
android:voiceSearchMode="showVoiceSearchButton|launchRecognizer"
android:voiceLanguageModel="free_form"
android:voicePromptText="Please Speak"/>

Body:
Problem solved, in searchable.xml, we cannot use static string, instead, we should use reference like

android:label="@string/app_name"

Thank you all.

Chris


问:
how to connect to DSLR camera by OTG cable on iPhone
I have tried to use EAAccessoryManager with swift:

```<code>let eaManager = EAAccessoryManager.shared()
let devices = eaManager.connectedAccessories
</code>```

but the devices list is always empty, I searched this problem for two days on Google, but did not get any useful infomation, the Canon official remote control app connect to camera by BLE or Wifi, while the iPhone's photos app can access the DSLR camera and import photos from it by OTG cable. so I think there must be a way to implement solve it.

答:
I found even if I connect to DSLR camera by OTG cable, user can't use the camera while connecting, because iPhone doesn't support PTP protocol, the connection is established by mount the camera's SD card, camera lose the sdcard once iPhone mounted it.

so the only way to connect to DSLR camera on iPhone is BLE or Wifi.

Body:
I have tried to use EAAccessoryManager with swift:

let eaManager = EAAccessoryManager.shared()
let devices = eaManager.connectedAccessories

but the devices list is always empty, I searched this problem for two days on Google, but did not get any useful infomation, the Canon official remote control app connect to camera by BLE or Wifi, while the iPhone's photos app can access the DSLR camera and import photos from it by OTG cable. so I think there must be a way to implement solve it.


问:
Unable to run Testng Maven Project with TestComplete
I have one Maven Project that have TestNg Classes and it is running fine with eclipse. I want to run same project with TestComplete , perform all the prerequisites as defined under TestComplete integration. I have attached the screen shot of error that i am facing.

Please Help it is urgent.error.png

答:
i want to share my experience as maven System environment was not set correctly under PATH system variable..
It was - %M2_HOME%bin
I changed it to correct - %M2_HOME%**/**bin

and it start working.


问:
Unable to redirect from index.php to home.php
```<code>{
      ?>
      <?php
      $sql1 = mysqli_query($sql1,"select * from register where email='$name' AND password='$pass'");
      $r = mysqli_fetch_array($sql1);
      $id = $r['id'];
      echo $_SESSION['id'] = $id;
      ?>
      <script>
        **window.location = 'Home.php?id=<?php echo $id?>';**
      </script>
      <?php
  }
?>
</code>```

I am using window.location instead of header to redirect to the next page with session id in the URL.

This leads me to this:

This page isn’t working

localhost redirected you too many times.

Try clearing your cookies.

ERR_TOO_MANY_REDIRECTS

Check out the index file:

Index.php

```<code><?php
require("user_agent.php");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>:: Online Bus-Ticket Reservation ::</title>
<!--<link rel="stylesheet" href="style.css" />-->
<style>
.table tr td {
    border-bottom-width: 1px;
    border-right-width: 1px;
    border-bottom-style: solid;
    border-right-style: outset
    border-right-color: darkred;
    border-bottom-color: darkred;
}

.table {
    border-left-width: 1px;
    border-top-width: 1px;
    border-left-style: outset;
    border-top-style: solid;
    border-left-color: darkred;
    border-top-color: darkred;
    font-size: 16px;
}
a{
    background-color:#3366FF;
    text-align:center;
    text-decoration:none;
    font-family:Verdana, Geneva, sans-serif;
    color:#FFF;
    border:groove;
    font-weight:550;
}
</style>

<script language="javascript">

    function validate()  {
        if(document.getElementById('user').value==''){
            alert('Please enter Username!');
            document.getElementById('username').focus();
            return false;
        }

        if(document.getElementById('pass').value==''){
            alert('Please enter Password!');
            document.getElementById('pwd').focus();
            return false;
        }

     return true;
    }
</script>

</head>

<body topmargin="0" bottommargin="0" bgcolor="#CCFF99">
<div align="center" style="width:807">

<embed src="banner3.swf" quality="high" type="application/x-shockwave-flash" wmode="transparent" width="807" height="150" pluginspage="http://www.macromedia.com/go/getflashplayer" allowScriptAccess="always"></embed>

</div>
<table bgcolor="#FFCCFF" style="margin-top:0" align="center" width="800px" border="1" cellpadding="0" cellspacing="0">
<tr><td height="5px" align="center" bgcolor="#330000" colspan="2">
<h2 style="text-align:center; color:#FFFFFF; font-family:Verdana, Geneva, sans-serif; margin-top:3px">

Welcome To Online Bus-Ticket Reservation</h2></td></tr>

<tr><td bgcolor="#CC6600" align="center" style="color:#FFFFCC; font-size:14px; display:table" id="clock" colspan="2">

        <script type="text/javascript">
            var lastText = "";

            function updateClock() {
                var d = new Date();
                var s = "";
                s += (10 > d.getHours()   ? "0" : "") + d.getHours()   + ":"
                s += (10 > d.getMinutes() ? "0" : "") + d.getMinutes() + ":"
                s += (10 > d.getSeconds() ? "0" : "") + d.getSeconds();

                if (lastText != s) {
                    setText("clock", s);
                    lastText = s;
                }

            }

            function setText(elemName, text) {
                var elem = document.getElementById(elemName);
                while (elem.childNodes.length > 0)
                    elem.removeChild(elem.firstChild);
                elem.appendChild(document.createTextNode(text));
            }

            updateClock();
            setInterval(updateClock,100);
        </script>
<script language="JavaScript" type="text/javascript">
 var d=new Date();
var monthname=new Array("January","February","March","April","May","June","July","August","September","October","November","December");

var TODAY =d.getDate() +"- " + monthname[d.getMonth()] + "-" + d.getFullYear();

 document.write(TODAY);
</script>

</tr>

<tr><td height="153" colspan="2">

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="800" height="150">
  <param name="movie" value="project.swf" />
  <param name="quality" value="high" />
  <param name="allowFullScreen" value="false" />
  <param name="allowScriptAccess" value="always" />
  <embed src="project.swf"
         quality="high"
         type="application/x-shockwave-flash"
         width="800"
         height="150"
         allowFullScreen="false"
         pluginspage="http://www.macromedia.com/go/getflashplayer"
         allowScriptAccess="always" />
</object>

  </td></tr>

<tr><td bgcolor="#CCCCCC" bordercolordark="#FFFFFF" align="left" colspan="2">
<h3 style="font-family:Verdana, Geneva, sans-serif; color: #000; margin-bottom:0px; margin-top:0px">Login Screen</h3></td></tr>

<tr><td width="398">

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="f">

<p style="font-family:Verdana, Geneva, sans-serif" align="center"> </p>
<p style="font-family:Verdana, Geneva, sans-serif" align="center">     Email: <input style="size:auto; width:150px" id="user" type="text" name="user" value="" />
</p>
<p style="font-family:Verdana, Geneva, sans-serif" align="center">Password:
  <input type="password" id="pass" name="pass" style="size:auto; width:150px" />
</p>
<center>
<input type="submit" onclick="validate()" value="Login" name="s" style="background-color:maroon; height:20px; color:#FFF; font-weight:50" />
<a href="bus_rev.php" style="cursor:default; font-size:12px; background-color:#900;">New User</a></center>
</form>
<?php
session_start();
require("config.php");
if(isset($_POST['s'])){
$name = $_POST['user'];
$pass = $_POST['pass'];

  $sql = mysqli_query($con,"select * from register where email='$name' AND password='$pass'");
  if(mysqli_num_rows($sql)==0)
  {
      ?>
      <script>
      alert("You seem to registered before!!!");
      </script>
      <?php
  }
  else
  {
      ?>
      <?php
      $sql1 = mysqli_query($sql1,"select * from register where email='$name' AND password='$pass'");
      $r = mysqli_fetch_array($sql1);
      $id = $r['id'];
      echo $_SESSION['id'] = $id;
      ?>
      <script>
        window.location.href='Home.php?id=$id';
      </script>
      <?php
  }
}

?>

</td><td width="400">
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="400" height="166">
  <param name="movie" value="project1.swf" />
  <param name="quality" value="high" />
  <param name="allowFullScreen" value="false" />
  <param name="allowScriptAccess" value="always" />
  <embed src="project1.swf"
         quality="high"
         type="application/x-shockwave-flash"
         width="400"
         height="166"
         allowFullScreen="false"
         pluginspage="http://www.macromedia.com/go/getflashplayer"
         allowScriptAccess="always" />
</object></td>
</tr>
</table>
<div align="center"><img align="top" width="806" src="images1/footer.jpg" />
</div>

</body>
</html>
</code>```

Home.php

```<code><?php
session_start();
if(isset($_SESSION['id']))
{
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>:: HOME ::</title>
<script type="text/javascript" src="C:\Users\NARPAT\Desktop\basiccalendar.js"></script>

<link rel="stylesheet" href="style/table.css" />
<link rel="stylesheet" href="style/style.css" />
<style>
a{cursor:default;}
</style>

</head>

<body topmargin="0" bottommargin="0">

<div align="center">
<embed src="banner3.swf" quality="high" type="application/x-shockwave-flash" wmode="transparent" width="807" height="150" pluginspage="http://www.macromedia.com/go/getflashplayer" allowScriptAccess="always"></embed>
</div>
<table bgcolor="#FFFFCC" style="margin-top:0" align="center" width="807" border="1" cellpadding="0" cellspacing="0">

<tr><td colspan="3" bgcolor="#330000" align="center" height="5px">
<h1 style="text-align:center; color:#FFFFFF; font-size:22px; font-family:Verdana, Geneva, sans-serif; margin-top:3px">

Welcome To Online Bus-Ticket Reservation</h1></td></tr>

<tr><td colspan="3" bgcolor="#CC6600" align="center" style="color:#FFFFCC; font-size:14px">
|| <b><?php echo date("D d-M-Y");?></b> ||</td></tr>

<!-- end header -->
<?php
require("config.php");
if(isset($_SESSION['id']))
{
$uid = $_SESSION['id'];
$sql = mysqli_query($con,"select * from register where id = '$uid'");
if(mysqli_num_rows($sql)>0)
{
    $r = mysqli_fetch_array($sql);
    $name = $r['name'];
}
 ?>

 </td></tr>   <tr><td width="200">
<!-- start leftmenu -->
<dl id="browse">
    <!-- <dt>
        <a href=""></a>
    </dt> -->
         <span class="simpletext1">Welcome :<b><?php echo $name;?></b></span>

        <hr />

  <dd   style="text-align: left">
        <img align="absmiddle" src="images/home.png" width="16" height="16" alt="" /><a href="Home.php?id=<?php echo $uid;?>">Home</a>
    </dd>
  <dd style="text-align: left">
        <img align="absmiddle" src="images/password.png" width="16" height="16" alt="" /><a href="password_update.php?id=<?php echo $uid;?>">Change Password</a>
    </dd>
  <dd style="text-align: left">
        <img align="absmiddle" src="images/profile.png" width="16" height="16" alt="" /><a href="profile.php?id=<?php echo $uid;?>">View Profile</a>
    </dd>

  <dd style="text-align: left">
        <img align="absmiddle" src="images/ticket.png" width="16" height="16" alt="" /><a href="myticket.php?id=<?php echo $uid;?>">My Tickets</a>
    </dd>

   <dd style="text-align: left">
        <img align="absmiddle" src="images/logout.png" width="16" height="16" alt="" /><a href="logout.php">Logout</a>
    </dd>
</dl>
<!-- end leftmenu --></td><td width="380">
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="382" height="195">
  <param name="movie" value="rstc.swf" />
  <param name="quality" value="high" />
  <param name="allowFullScreen" value="true" />
  <param name="allowScriptAccess" value="always" />
  <param name="wmode" value="transparent">
  <embed src="rstc.swf"
         quality="high"
         type="application/x-shockwave-flash"
         WMODE="transparent"
         width="382"
         height="195"
         allowFullScreen="true"
         pluginspage="http://www.macromedia.com/go/getflashplayer"
         allowScriptAccess="always" />
</object>

</td>
<td width="217">
<embed src="rightbar.swf" quality="high" type="application/x-shockwave-flash" wmode="transparent" width="217" height="195" pluginspage="http://www.macromedia.com/go/getflashplayer" allowScriptAccess="always"></embed>

</tr></table>

<table cellpadding="0" cellspacing="0" border="0" class="maintable" align="center"
               width="805" valign="middle">
<form method="post">
    <tr class="tabtitle">
            <td colspan="4">
                <table cellspacing="0" cellpadding="0" width="800">
                    <tr>
                        <td  class="titletext" style="background-color:#990000">
                            <font size="3px" style="background-color:#C00; color:#FFF">Search For Bus Services </font>

                        </td>

                  </tr>
                </table>
            </td>
        <tr>
            <td width="20%" class="simpletext">
                From Stop :
            </td>
            <td>
            <select class="html-text-box" style="background-color:; font-style:oblique; width:100px; font-family:Verdana; font-weight:bold" name="from">
            <option value="0" selected="selected">-Select-</option>
            <option value="BARMER">BARMER</option>
            <option value="Delhi">Delhi</option>
            <option value="Jaipur">Jaipur</option>
            <option value="JODHPUR">JODHPUR</option></select>
          </td>
                        <td width="23%"  class="simpletext" align="right">
                To Stop :
            </td>
            <td  align="left">
            <select class="html-text-box" style="font-style:oblique; width:100px; font-family:Verdana; font-weight:bold" name="to">
            <option value="0" selected="selected">-Select-</option>
            <option value="BARMER" >BARMER</option>
            <option value="Delhi">Delhi</option>
            <option value="Jaipur">Jaipur</option>
            <option value="JODHPUR">JODHPUR</option></select>
            </td>
        </tr>

                <tr>
            <td >
                Journey Date :
            </td>
            <td  >
                <input type="text" style="border:2; padding:2" name="journeyDate" maxlength="10" size="10" value="" id="journeyDate">

            </td>

        </tr>

        <tr>
            <td colspan="4" height="45" align="center" valign="middle">
                            <input type="submit" name="search" value="Search" onclick="return callfrm(document.getElementById('currentdate').value);" class="html-button">

                       <input type="submit" name="resert" value="Reset"  class="html-button">

                        </td>
                </tr>
        <tr>
            <td colspan="4">
                <div class="errormessage" align="center">

                </div>
            </td>
            </tr>
    </form>
    </table>

<?php
if(isset($_POST['search']))
{
    require('config.php');
     $from = $_POST['from'];
     $to = $_POST['to'];

     $query = mysqli_query("select * from bus where from_stop ='$from' AND to_stop ='$to'");
     $c = mysqli_stmt_num_rows($query);
    if($c>0)
    {
?>
<table width="805" height="62" align="center" cellpadding="2" cellspacing="2" class="table" bordercolor="#000000" b>

<tr align="center"><td width="115">Bus Name</td><td width="122">From</td><td width="117">To</td><td width="117">Dept Time</td><td width="119">Arrival Time</td><td width="110">Distance</td><td width="110">Fare</td><td>Available</td><td width="101"> </td></tr>
<?php
while($r1 = mysqli_fetch_array($query))
{
    $bus= $r1['id'];
    $bus_name = $r1['bus_name'];
    $from = $r1['from_stop'];
    $to = $r1['to_stop'];
    $dept_time = $r1['dept_time'];
    $arrival_time = $r1['arrival_time'];
    $distance = $r1['distance'];
    $fare = $r1['fare'];

    $bust = $bus.'bus';
    $query1 = mysqli_query("SELECT * from $bust where status='Available'");
    $c = mysqli_num_rows($query1);
?>

<tr align="center"><td><?php echo $bus_name;?></td><td><?php echo $from;?></td><td><?php echo $to;?></td><td><?php echo $dept_time;?></td><td><?php echo $arrival_time;?></td><td nowrap="nowrap"><?php echo $distance;?></td><td><?php echo $fare; ?></td><td><?php echo $c;?></td><td><a href="res.php?id=<?php echo $uid;?>&bus=<?php echo $bus;?>">Book</a>
</td></tr></table>
<?php
}
}
}
?>

     <table class="table" align="center" cellpadding="0" cellspacing="0" width="805">
     <tr><td height="124"><marquee onmouseover="this.stop();" onmouseout="this.start();" draggable="auto" bgcolor="#663333" loop="-1" dropzone="move" direction="left" behavior="alternate" scrollamount="2" scrolldelay="1">
     <img border="1" height="130" width="150" src="images/B1.jpg" />
     <img height="130" width="150" src="images/B2.jpg" />
     <img height="130" width="150" src="images/B3.jpg" />
     <img height="130" width="150" src="images/B4.jpg" />
     <img height="130" width="150" src="images/B5.jpg" />
     <img height="130" width="150" src="images/B6.jpg" />
     <img height="130" width="150" src="images/7.png" />
     <img height="130" width="150" src="images/v (1).jpg" />
     <img height="130" width="150" src="images/v (2).jpg" />
     <img height="130" width="150" src="images/v (3).jpg" />
     <img height="130" width="150" src="images/v (4).jpg" />
     <img height="130" width="150" src="images/v (5).jpg" />
     <img height="130" width="150" src="images/v (6).jpg" />
     <img border="1" height="130" width="150" src="images/v (7).jpg" />

     </marquee></td>
     <div style="position:absolute; float:right; visibility:hidden">
     <script type="text/javascript">

var todaydate=new Date()
var curmonth=todaydate.getMonth()+1 //get current month (1-12)
var curyear=todaydate.getFullYear() //get current year

document.write(buildCal(curmonth ,curyear, "main", "month", "daysofweek", "days", 1));
</script>

<form>
<select onChange="updatecalendar(this.options)">
<script type="text/javascript">

var themonths=['January','February','March','April','May','June',
'July','August','September','October','November','December']

var todaydate=new Date()
var curmonth=todaydate.getMonth()+1 //get current month (1-12)
var curyear=todaydate.getFullYear() //get current year

function updatecalendar(theselection){
var themonth=parseInt(theselection[theselection.selectedIndex].value)+1
var calendarstr=buildCal(themonth, curyear, "main", "month", "daysofweek", "days", 0)
if (document.getElementById)
document.getElementById("calendarspace").innerHTML=calendarstr
}

document.write('<option value="'+(curmonth-1)+'" selected="yes">Current Month</option>')
for (i=0; i<12; i++) //display option for 12 months of the year
document.write('<option value="'+i+'">'+themonths[i]+' '+curyear+'</option>')

</script>
</select>

<div id="calendarspace">
<script>
//write out current month's calendar to start
document.write(buildCal(curmonth, curyear, "main", "month", "daysofweek", "days", 0))
</script>
</div>

</form>

<script type="text/javascript">

var todaydate=new Date()
var curmonth=todaydate.getMonth()+1 //get current month (1-12)
var curyear=todaydate.getFullYear() //get current year

</script>

     </div>
     </tr>

</table>
<div align="center"><img align="top" width="805" src="images1/footer.jpg" />
</div>
<?php
}
else
{
    header("Location:indexm.php");
}
}
else
{
    header("Location:Home.php?id=$uid");
}
?>
</body>
</html>
</code>```

Index.php is uses sql function from config.php file to get database connectivity.

答:
First add session_start(); at the beginning of index.php

Second re-check below code in home.php that results in redirecting of home.php again and again.

```<code>header("Location:Home.php?id=$uid");
</code>```

Body:
{
      ?>
      <?php
      $sql1 = mysqli_query($sql1,"select * from register where email='$name' AND password='$pass'");
      $r = mysqli_fetch_array($sql1);
      $id = $r['id'];
      echo $_SESSION['id'] = $id;
      ?>

      <?php
  }
?>

I am using window.location instead of header to redirect to the next page with session id in the URL.

This leads me to this:

This page isn’t working

localhost redirected you too many times.

Try clearing your cookies.

ERR_TOO_MANY_REDIRECTS

Check out the index file:

Index.php

<?php
require("user_agent.php");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>:: Online Bus-Ticket Reservation ::</title>

<embed src="banner3.swf" quality="high" type="application/x-shockwave-flash" wmode="transparent" width="807" height="150" pluginspage="http://www.macromedia.com/go/getflashplayer" allowScriptAccess="always"></embed>

Welcome To Online Bus-Ticket Reservation

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="800" height="150">
  <param name="movie" value="project.swf" />
  <param name="quality" value="high" />
  <param name="allowFullScreen" value="false" />
  <param name="allowScriptAccess" value="always" />
  <embed src="project.swf"
         quality="high"
         type="application/x-shockwave-flash"
         width="800"
         height="150"
         allowFullScreen="false"
         pluginspage="http://www.macromedia.com/go/getflashplayer"
         allowScriptAccess="always" />
</object>

Login Screen

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="f">

     Email: <input style="size:auto; width:150px" id="user" type="text" name="user" value="" />

Password:
  <input type="password" id="pass" name="pass" style="size:auto; width:150px" />

<input type="submit" onclick="validate()" value="Login" name="s" style="background-color:maroon; height:20px; color:#FFF; font-weight:50" />
New User
</form>
<?php
session_start();
require("config.php");
if(isset($_POST['s'])){
$name = $_POST['user'];
$pass = $_POST['pass'];

  $sql = mysqli_query($con,"select * from register where email='$name' AND password='$pass'");
  if(mysqli_num_rows($sql)==0)
  {
      ?>

      <?php
  }
  else
  {
      ?>
      <?php
      $sql1 = mysqli_query($sql1,"select * from register where email='$name' AND password='$pass'");
      $r = mysqli_fetch_array($sql1);
      $id = $r['id'];
      echo $_SESSION['id'] = $id;
      ?>

      <?php
  }
}

?>

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="400" height="166">
  <param name="movie" value="project1.swf" />
  <param name="quality" value="high" />
  <param name="allowFullScreen" value="false" />
  <param name="allowScriptAccess" value="always" />
  <embed src="project1.swf"
         quality="high"
         type="application/x-shockwave-flash"
         width="400"
         height="166"
         allowFullScreen="false"
         pluginspage="http://www.macromedia.com/go/getflashplayer"
         allowScriptAccess="always" />
</object>

Home.php

<?php
session_start();
if(isset($_SESSION['id']))
{
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>:: HOME ::</title>

<link rel="stylesheet" href="style/table.css" />
<link rel="stylesheet" href="style/style.css" />

<embed src="banner3.swf" quality="high" type="application/x-shockwave-flash" wmode="transparent" width="807" height="150" pluginspage="http://www.macromedia.com/go/getflashplayer" allowScriptAccess="always"></embed>

Welcome To Online Bus-Ticket Reservation

|| <?php echo date("D d-M-Y");?> ||

<?php
require("config.php");
if(isset($_SESSION['id']))
{
$uid = $_SESSION['id'];
$sql = mysqli_query($con,"select * from register where id = '$uid'");
if(mysqli_num_rows($sql)>0)
{
    $r = mysqli_fetch_array($sql);
    $name = $r['name'];
}
 ?>

         Welcome :<?php echo $name;?>

        <a href="Home.php?id=<?php echo $uid;?>">Home

        <a href="password_update.php?id=<?php echo $uid;?>">Change Password

        <a href="profile.php?id=<?php echo $uid;?>">View Profile

        <a href="myticket.php?id=<?php echo $uid;?>">My Tickets

        Logout

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="382" height="195">
  <param name="movie" value="rstc.swf" />
  <param name="quality" value="high" />
  <param name="allowFullScreen" value="true" />
  <param name="allowScriptAccess" value="always" />
  <param name="wmode" value="transparent">
  <embed src="rstc.swf"
         quality="high"
         type="application/x-shockwave-flash"
         WMODE="transparent"
         width="382"
         height="195"
         allowFullScreen="true"
         pluginspage="http://www.macromedia.com/go/getflashplayer"
         allowScriptAccess="always" />
</object>

<embed src="rightbar.swf" quality="high" type="application/x-shockwave-flash" wmode="transparent" width="217" height="195" pluginspage="http://www.macromedia.com/go/getflashplayer" allowScriptAccess="always"></embed>

<form method="post">

                            Search For Bus Services

                From Stop :

            <select class="html-text-box" style="background-color:; font-style:oblique; width:100px; font-family:Verdana; font-weight:bold" name="from">
            <option value="0" selected="selected">-Select-</option>
            <option value="BARMER">BARMER</option>
            <option value="Delhi">Delhi</option>
            <option value="Jaipur">Jaipur</option>
            <option value="JODHPUR">JODHPUR</option></select>

                To Stop :

            <select class="html-text-box" style="font-style:oblique; width:100px; font-family:Verdana; font-weight:bold" name="to">
            <option value="0" selected="selected">-Select-</option>
            <option value="BARMER" >BARMER</option>
            <option value="Delhi">Delhi</option>
            <option value="Jaipur">Jaipur</option>
            <option value="JODHPUR">JODHPUR</option></select>

                Journey Date :

                <input type="text" style="border:2; padding:2" name="journeyDate" maxlength="10" size="10" value="" id="journeyDate">

                            <input type="submit" name="search" value="Search" onclick="return callfrm(document.getElementById('currentdate').value);" class="html-button">

                       <input type="submit" name="resert" value="Reset"  class="html-button">

    </form>

<?php
if(isset($_POST['search']))
{
    require('config.php');
     $from = $_POST['from'];
     $to = $_POST['to'];

     $query = mysqli_query("select * from bus where from_stop ='$from' AND to_stop ='$to'");
     $c = mysqli_stmt_num_rows($query);
    if($c>0)
    {
?>

Bus Name	From	To	Dept Time	Arrival Time	Distance	Fare	Available

<?php
while($r1 = mysqli_fetch_array($query))
{
    $bus= $r1['id'];
    $bus_name = $r1['bus_name'];
    $from = $r1['from_stop'];
    $to = $r1['to_stop'];
    $dept_time = $r1['dept_time'];
    $arrival_time = $r1['arrival_time'];
    $distance = $r1['distance'];
    $fare = $r1['fare'];

    $bust = $bus.'bus';
    $query1 = mysqli_query("SELECT * from $bust where status='Available'");
    $c = mysqli_num_rows($query1);
?>

<?php echo $bus_name;?>	<?php echo $from;?>	<?php echo $to;?>	<?php echo $dept_time;?>	<?php echo $arrival_time;?>	<?php echo $distance;?>	<?php echo $fare; ?>	<?php echo $c;?>	<a href="res.php?id=<?php echo $uid;?>&bus=<?php echo $bus;?>">Book

<?php
}
}
}
?>

<marquee onmouseover="this.stop();" onmouseout="this.start();" draggable="auto" bgcolor="#663333" loop="-1" dropzone="move" direction="left" behavior="alternate" scrollamount="2" scrolldelay="1">

     </marquee>

<form>
<select onChange="updatecalendar(this.options)">

</select>

</form>

<?php
}
else
{
    header("Location:indexm.php");
}
}
else
{
    header("Location:Home.php?id=$uid");
}
?>

Index.php is uses sql function from config.php file to get database connectivity.

Body:
First add session_start(); at the beginning of index.php

Second re-check below code in home.php that results in redirecting of home.php again and again.

header("Location:Home.php?id=$uid");


问:
It's possible to replace existing html code with jQuery
Example current html code

```<code><a rel="tag" title="see questions tagged 'php'" href="/tags/php/" class="tag-link-php">php</a>
</code>```

I want use jQuery to replace it to be

```<code><a href="http://php.net/"><img src="/images/tags/php.gif" height="16" width="16" alt="php" /></a><a rel="tag" title="see questions tagged 'php'" href="/tags/php/" class="tag-link-php">php</a>
</code>```

Let me know

答:
Looks like:</p>

```<code>$("<a/>", {
   "href":  "http://www.php.net"
}).append($("<img>", {
   "src":    "/images/tags/php.gif",
   "height": "16",
   "width":  "16",
   "alt":    "/images/tags/php.gif"
})).insertBefore(".tag-link-php");
</code>```

Body:
Example current html code

php

I want use jQuery to replace it to be

php

Let me know

Body:
Looks like:

$("<a/>", {
   "href":  "http://www.php.net"
}).append($("<img>", {
   "src":    "/images/tags/php.gif",
   "height": "16",
   "width":  "16",
   "alt":    "/images/tags/php.gif"
})).insertBefore(".tag-link-php");


问:
not viewing specific saved conversation Javascript
Basically my application can read saved conversation via Skype For Business. But Skype for business can not read saved conversations via my application.

I use JavaScript while I am developing my application.

Below more details;

I am trying to make a save to conversation history folder and see it properly in the native Skype for Business client.

Here is my SOAP request:

POST /EWS/Exchange.asmx HTTP/1.1
Host: <username>:<password>@<domain>
Content-Type: text/xml

<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope
  xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
  xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages"
  xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <soap:Header>
    <t:RequestServerVersion Version="Exchange2013" />
  </soap:Header>
  <soap:Body>
    <m:CreateItem MessageDisposition="SaveOnly">
      <m:SavedItemFolderId>
        <t:FolderId Id="AAMkADI2ZWUxY2Y4LTM4MjQtNGRiMC04NGU5LWNjMTkwMmI2ZGZhYwAuAAAAAAARYud90uTpQaW383uiLjbQAQBu8bl+jmTVT6UWWk0qHuXQAAAA2qSWAAA=" ChangeKey="AQAAABYAAABu8bl+jmTVT6UWWk0qHuXQAAAA2q+x" />
      </m:SavedItemFolderId>
      <m:Items>
        <t:Message>
          <t:ItemClass>IPM.Note.Microsoft.Conversation</t:ItemClass>
          <t:Subject>Conversation with John Doe</t:Subject>
          <t:Body BodyType="HTML">
            <![CDATA[<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

            My Name
            05:28 PM:

              <meta name="Generator" content="Microsoft Word 15 (filtered)"

                    test

          ]]>
        </t:Body>
        <t:ExtendedProperty>
          <t:ExtendedFieldURI DistinguishedPropertySetId="PublicStrings" PropertyName="ConversationXml.{CA2F170A-A22B-4f0a-B899-93439DEC3FBC}" PropertyType="String" />
          <t:Value><conversations
            xmlns="http://schemas.microsoft.com/2008/10/sip/convItems" minSupportedClientVersion="3.0.0.0"><conversationXml></conversationXml></conversations>
          </t:Value>
        </t:ExtendedProperty>
        <t:ExtendedProperty>
          <t:ExtendedFieldURI DistinguishedPropertySetId="PublicStrings" PropertyName="Direction.{2DA4DF04-920D-4b0b-A1D7-5FC9D21857FE}" PropertyType="Integer" />
          <t:Value>1</t:Value>
        </t:ExtendedProperty>
        <t:ExtendedProperty>
          <t:ExtendedFieldURI DistinguishedPropertySetId="PublicStrings" PropertyName="Modalities.{0885EA21-B7A5-4050-BFDB-AD46DE1D6A87}" PropertyType="Integer" />
          <t:Value>1</t:Value>
        </t:ExtendedProperty>
        <t:ExtendedProperty>
          <t:ExtendedFieldURI DistinguishedPropertySetId="PublicStrings" PropertyName="IsCustomSubject.{703DC3CB-8F24-4e3f-932F-206233656759}" PropertyType="Integer" />
          <t:Value>0</t:Value>
        </t:ExtendedProperty>
        <t:ExtendedProperty>
          <t:ExtendedFieldURI DistinguishedPropertySetId="PublicStrings" PropertyName="DisplayDirection.{4255C773-497E-4b5e-9205-F360CAF3316A}" PropertyType="String" />
          <t:Value>Incoming</t:Value>
        </t:ExtendedProperty>
        <t:ExtendedProperty>
          <t:ExtendedFieldURI DistinguishedPropertySetId="PublicStrings" PropertyName="RemoteParty.{664AD731-19D0-4344-93FD-682FE0440D95}" PropertyType="String" />
          <t:Value>john.doe@domain</t:Value>
        </t:ExtendedProperty>
        <t:ExtendedProperty>
          <t:ExtendedFieldURI DistinguishedPropertySetId="PublicStrings" PropertyName="HistoryInfo.{553F3F08-FC28-41db-859E-63457407F806}" PropertyType="String" />
          <t:Value>john.doe@domain</t:Value>
        </t:ExtendedProperty>
        <t:ExtendedProperty>
          <t:ExtendedFieldURI PropertyTag="3591" PropertyType="Integer" />
          <t:Value>1</t:Value>
        </t:ExtendedProperty>
        <t:ToRecipients>
          <t:Mailbox>
            <t:EmailAddress>john.doe@domain</t:EmailAddress>
          </t:Mailbox>
          <t:Mailbox>
            <t:EmailAddress>my.account@domain</t:EmailAddress>
          </t:Mailbox>
        </t:ToRecipients>
        <t:From>
          <t:Mailbox>
            <t:Name>My Name</t:Name>
            <t:EmailAddress>my.account@domain</t:EmailAddress>
          </t:Mailbox>
        </t:From>
      </t:Message>
    </m:Items>
  </m:CreateItem>
</soap:Body>undefined</soap:Envelope>
```

I use dummy data in the request above. Folder Id inside the tag <SavedItemFolderId> is Id of Conversion History folder. The request has also a quite big HTML content with styles.

I can save the item into Conversation History folder and see it in my Outlook client.

Although I can see it as a Conversation History item in native Skype for Business Windows client, I cannot see the conversation content (messages) when I double click it.

I think I am doing configuration or HTML content in wrong way.

Has anyone ever tried to save conversation history and see it in native client? Do you have any suggestion?

答:
I have solved tihs problem.

the real problem is, you are genetaring conversationXml but you do not put your messages body inside of this conversationXML. So if you give the parameter as below, you will solve the problem.

you will see +body+ (body formatted as HTML)

by the way you should give spesifically wihch format you are putting the body (text/HTML, text/RTF)

```<code>let cnvXML ='<conversations xmlns=\"http://schemas.microsoft.com/2008/10/sip/convItems\" minSupportedClientVersion=\"3.0.0.0\"><conversationXml><imReceived xmlns=\"http://schemas.microsoft.com/2008/10/sip/convItems\" ts=\"2017-11-14T07:18:47Z\" from=\"sip:tan.tastan@gbsolutions.work\" displayName=\"Tan Tastan\" firstMessage=\"true\" type=\"text/html\"><messageInfo type=\"text/html\" msgid=\"\" sequenceid=\"0\">'+body+'</messageInfo></imReceived></conversationXml></conversations>';
</code>```

Then you must change these two parameters as below;

...SetExtendedProperty(RemoteParty, "sip:participantsName@yourDomain.com");
...SetExtendedProperty(HistoryInfo, "sip:participantsName@yourDomain.com");

After that, you will realize another problem which is in Native Skype's History tab, you will see message preview is not shown. So if you add the parameter as below, you will solve second problem.

...SetExtendedProperty(PreviewMessage, messagePreview);

I hope I explained the solution clearly.

Body:
Basically my application can read saved conversation via Skype For Business. But Skype for business can not read saved conversations via my application.

I use JavaScript while I am developing my application.

Below more details;

I am trying to make a save to conversation history folder and see it properly in the native Skype for Business client.

Here is my SOAP request:

POST /EWS/Exchange.asmx HTTP/1.1
Host: <username>:<password>@<domain>
Content-Type: text/xml

<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope
  xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
  xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages"
  xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <soap:Header>
    <t:RequestServerVersion Version="Exchange2013" />
  </soap:Header>
  <soap:Body>
    <m:CreateItem MessageDisposition="SaveOnly">
      <m:SavedItemFolderId>
        <t:FolderId Id="AAMkADI2ZWUxY2Y4LTM4MjQtNGRiMC04NGU5LWNjMTkwMmI2ZGZhYwAuAAAAAAARYud90uTpQaW383uiLjbQAQBu8bl+jmTVT6UWWk0qHuXQAAAA2qSWAAA=" ChangeKey="AQAAABYAAABu8bl+jmTVT6UWWk0qHuXQAAAA2q+x" />
      </m:SavedItemFolderId>
      <m:Items>
        <t:Message>
          <t:ItemClass>IPM.Note.Microsoft.Conversation</t:ItemClass>
          <t:Subject>Conversation with John Doe</t:Subject>
          <t:Body BodyType="HTML">
            <![CDATA[<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

            My Name
            05:28 PM:

              <meta name="Generator" content="Microsoft Word 15 (filtered)"

                    test

          ]]>
        </t:Body>
        <t:ExtendedProperty>
          <t:ExtendedFieldURI DistinguishedPropertySetId="PublicStrings" PropertyName="ConversationXml.{CA2F170A-A22B-4f0a-B899-93439DEC3FBC}" PropertyType="String" />
          <t:Value><conversations
            xmlns="http://schemas.microsoft.com/2008/10/sip/convItems" minSupportedClientVersion="3.0.0.0"><conversationXml></conversationXml></conversations>
          </t:Value>
        </t:ExtendedProperty>
        <t:ExtendedProperty>
          <t:ExtendedFieldURI DistinguishedPropertySetId="PublicStrings" PropertyName="Direction.{2DA4DF04-920D-4b0b-A1D7-5FC9D21857FE}" PropertyType="Integer" />
          <t:Value>1</t:Value>
        </t:ExtendedProperty>
        <t:ExtendedProperty>
          <t:ExtendedFieldURI DistinguishedPropertySetId="PublicStrings" PropertyName="Modalities.{0885EA21-B7A5-4050-BFDB-AD46DE1D6A87}" PropertyType="Integer" />
          <t:Value>1</t:Value>
        </t:ExtendedProperty>
        <t:ExtendedProperty>
          <t:ExtendedFieldURI DistinguishedPropertySetId="PublicStrings" PropertyName="IsCustomSubject.{703DC3CB-8F24-4e3f-932F-206233656759}" PropertyType="Integer" />
          <t:Value>0</t:Value>
        </t:ExtendedProperty>
        <t:ExtendedProperty>
          <t:ExtendedFieldURI DistinguishedPropertySetId="PublicStrings" PropertyName="DisplayDirection.{4255C773-497E-4b5e-9205-F360CAF3316A}" PropertyType="String" />
          <t:Value>Incoming</t:Value>
        </t:ExtendedProperty>
        <t:ExtendedProperty>
          <t:ExtendedFieldURI DistinguishedPropertySetId="PublicStrings" PropertyName="RemoteParty.{664AD731-19D0-4344-93FD-682FE0440D95}" PropertyType="String" />
          <t:Value>john.doe@domain</t:Value>
        </t:ExtendedProperty>
        <t:ExtendedProperty>
          <t:ExtendedFieldURI DistinguishedPropertySetId="PublicStrings" PropertyName="HistoryInfo.{553F3F08-FC28-41db-859E-63457407F806}" PropertyType="String" />
          <t:Value>john.doe@domain</t:Value>
        </t:ExtendedProperty>
        <t:ExtendedProperty>
          <t:ExtendedFieldURI PropertyTag="3591" PropertyType="Integer" />
          <t:Value>1</t:Value>
        </t:ExtendedProperty>
        <t:ToRecipients>
          <t:Mailbox>
            <t:EmailAddress>john.doe@domain</t:EmailAddress>
          </t:Mailbox>
          <t:Mailbox>
            <t:EmailAddress>my.account@domain</t:EmailAddress>
          </t:Mailbox>
        </t:ToRecipients>
        <t:From>
          <t:Mailbox>
            <t:Name>My Name</t:Name>
            <t:EmailAddress>my.account@domain</t:EmailAddress>
          </t:Mailbox>
        </t:From>
      </t:Message>
    </m:Items>
  </m:CreateItem>
</soap:Body>undefined</soap:Envelope>

I use dummy data in the request above. Folder Id inside the tag <SavedItemFolderId> is Id of Conversion History folder. The request has also a quite big HTML content with styles.

I can save the item into Conversation History folder and see it in my Outlook client.

Although I can see it as a Conversation History item in native Skype for Business Windows client, I cannot see the conversation content (messages) when I double click it.

I think I am doing configuration or HTML content in wrong way.

Has anyone ever tried to save conversation history and see it in native client? Do you have any suggestion?

Body:
I have solved tihs problem.

the real problem is, you are genetaring conversationXml but you do not put your messages body inside of this conversationXML. So if you give the parameter as below, you will solve the problem.

you will see +body+ (body formatted as HTML)

by the way you should give spesifically wihch format you are putting the body (text/HTML, text/RTF)

let cnvXML ='<conversations xmlns=\"http://schemas.microsoft.com/2008/10/sip/convItems\" minSupportedClientVersion=\"3.0.0.0\"><conversationXml><imReceived xmlns=\"http://schemas.microsoft.com/2008/10/sip/convItems\" ts=\"2017-11-14T07:18:47Z\" from=\"sip:tan.tastan@gbsolutions.work\" displayName=\"Tan Tastan\" firstMessage=\"true\" type=\"text/html\"><messageInfo type=\"text/html\" msgid=\"\" sequenceid=\"0\">'+body+'</messageInfo></imReceived></conversationXml></conversations>';

Then you must change these two parameters as below;

...SetExtendedProperty(RemoteParty, "sip:participantsName@yourDomain.com");
...SetExtendedProperty(HistoryInfo, "sip:participantsName@yourDomain.com");

After that, you will realize another problem which is in Native Skype's History tab, you will see message preview is not shown. So if you add the parameter as below, you will solve second problem.

...SetExtendedProperty(PreviewMessage, messagePreview);

I hope I explained the solution clearly.


问:
Cordova - cordova-uglify plugin changes content to 'undefined' when uglified
After installing,

```<code>npm install cordova-uglify --save-dev
</code>```

and when running,

```<code>cordova build android --release
</code>```

all the css are minified correctly.

But, JS files contents are replaced with 'undefined'.

What might be the issue?

What kind of information should I give you to solve it?

Please help guys?

SOLUTION:

Reinstall cordova-uglify with the version 0.2.9 (or) follow the accepted answer.

答:
Following this post for Minification and Uglification of Ionic 1 application helped me to solve the issue.

Note: Delete/Rename assets folder which is inside platforms/android, before building app. (It happens automatically when you build but do it manually just to make sure about it)

EDIT 1:
Reinstall cordova-uglify with the version 0.2.9.

Thanks.

Body:
After installing,

npm install cordova-uglify --save-dev

and when running,

cordova build android --release

all the css are minified correctly.

But, JS files contents are replaced with 'undefined'.

What might be the issue?

What kind of information should I give you to solve it?

Please help guys?

SOLUTION:

Reinstall cordova-uglify with the version 0.2.9 (or) follow the accepted answer.


问:
duktape how to parse argument of type String Object (similarly Number object) in duktape c function
How to type check the String object/Number object argument types in duktape c function and parse the value from String object/Number object. There is generic api like duk_is_object() but I need the correct object type to parse the value .</p>

```<code>ex:
ecmascript code
  var str1 = new String("duktape");
   var version = new Number(2.2);
 dukFunPrintArgs(str1,str2);

duktape c function :
dukFunPrintArgs(ctx)
{
  // code to know whether the args is of type String Object / Number Object

}
</code>```

答:
Where did you find the information how to register a C function in duktape? That place certainly also has details on how to access the parameters passed to it. Already on the homepage of duktape.org you can find a Getting Started example:

```<code>3 Add C function bindings

To call a C function from Ecmascript code, first declare your C functions:

/* Being an embeddable engine, Duktape doesn't provide I/O
 * bindings by default.  Here's a simple one argument print()
 * function.
 */
static duk_ret_t native_print(duk_context *ctx) {
  printf("%s\n", duk_to_string(ctx, 0));
  return 0;  /* no return value (= undefined) */
}

/* Adder: add argument values. */
static duk_ret_t native_adder(duk_context *ctx) {
  int i;
  int n = duk_get_top(ctx);  /* #args */
  double res = 0.0;

  for (i = 0; i < n; i++) {
    res += duk_to_number(ctx, i);
  }

  duk_push_number(ctx, res);
  return 1;  /* one return value */
}

Register your functions e.g. into the global object:

duk_push_c_function(ctx, native_print, 1 /*nargs*/);
duk_put_global_string(ctx, "print");
duk_push_c_function(ctx, native_adder, DUK_VARARGS);
duk_put_global_string(ctx, "adder");

You can then call your function from Ecmascript code:

duk_eval_string_noresult(ctx, "print('2+3=' + adder(2, 3));");
</code>```

One of the core concepts in duktape are stacks. The value stack is where parameters are stored. Read more on the Getting Started page.

Body:
How to type check the String object/Number object argument types in duktape c function and parse the value from String object/Number object. There is generic api like duk_is_object() but I need the correct object type to parse the value .

ex:
ecmascript code
  var str1 = new String("duktape");
   var version = new Number(2.2);
 dukFunPrintArgs(str1,str2);

duktape c function :
dukFunPrintArgs(ctx)
{
  // code to know whether the args is of type String Object / Number Object

}

Body:
Where did you find the information how to register a C function in duktape? That place certainly also has details on how to access the parameters passed to it. Already on the homepage of duktape.org you can find a Getting Started example:

3 Add C function bindings

To call a C function from Ecmascript code, first declare your C functions:

/* Being an embeddable engine, Duktape doesn't provide I/O
 * bindings by default.  Here's a simple one argument print()
 * function.
 */
static duk_ret_t native_print(duk_context *ctx) {
  printf("%s\n", duk_to_string(ctx, 0));
  return 0;  /* no return value (= undefined) */
}

/* Adder: add argument values. */
static duk_ret_t native_adder(duk_context *ctx) {
  int i;
  int n = duk_get_top(ctx);  /* #args */
  double res = 0.0;

  for (i = 0; i < n; i++) {
    res += duk_to_number(ctx, i);
  }

  duk_push_number(ctx, res);
  return 1;  /* one return value */
}

Register your functions e.g. into the global object:

duk_push_c_function(ctx, native_print, 1 /*nargs*/);
duk_put_global_string(ctx, "print");
duk_push_c_function(ctx, native_adder, DUK_VARARGS);
duk_put_global_string(ctx, "adder");

You can then call your function from Ecmascript code:

duk_eval_string_noresult(ctx, "print('2+3=' + adder(2, 3));");

One of the core concepts in duktape are stacks. The value stack is where parameters are stored. Read more on the Getting Started page.


问:
NumberFormatException, BigInteger in java
Getting following run-time error

```<code>C:\jdk1.6.0_07\bin>java euler/BigConCheck
Exception in thread "main" java.lang.NumberFormatException: For input string: "z
"
        at java.lang.NumberFormatException.forInputString(NumberFormatException.
java:48)
        at java.lang.Integer.parseInt(Integer.java:447)
        at java.math.BigInteger.<init>(BigInteger.java:314)
        at java.math.BigInteger.<init>(BigInteger.java:447)
        at euler.BigConCheck.conCheck(BigConCheck.java:25)
        at euler.BigConCheck.main(BigConCheck.java:71)
</code>```

My Code

```<code>package euler;
import java.math.BigInteger;
class BigConCheck
{

public int[] conCheck(BigInteger big)
{
    int i=0,q=0,w=0,e=0,r=0,t=0,mul=1;
    int a[]= new int[1000];
    int b[]= new int[7];
    BigInteger rem[]= new BigInteger[4];
    BigInteger num[]= new BigInteger[4];
    for(i=0;i<4;i++)
    num[i]=big;   // intialised num[1 to 4][0] with big
    String s="1",g="0";
    for(i=0;i<999;i++)
    s = s.concat(g);
    BigInteger divi[]= new BigInteger[4];

    for(i=0;i<5;i++)
    {
        divi[i]=new BigInteger(s);
        int z = (int)Math.pow((double)10,(double)i);

        BigInteger zz = new BigInteger("z");    // intialised div[1 to 4][0] with big
        divi[i]=divi[i].divide(zz);
    }

    for(i=0;i<996;i++)   // 5 consecative  numbers.
    {
        for(int k=0;k<5;k++)
        {
            rem[k] = num[k].mod(divi[k]);
            b[k]=rem[k].intValue();
            mul= mul*b[k];
            /*int z = (int)Math.pow((double)10,(double)(k+1));
        String zz = "z";
        BigInteger zzz = new BigInteger(zz);
        num[k]=num[k].divide(zzz);   */
        }

        a[i]=mul;
        for(int p=0;p<5;p++)
        {
            BigInteger qq = new BigInteger("10");
            num[p]=num[p].divide(qq);
        }
    }
    return a;
}

public int bigestEleA(int u[])
{
    int big=0;
    for(int i=0;i<u.length;i++)
    if(big<u[i])
    big=u[i];

    return big;
}

public static void main(String args[])
{
    int con5[]= new int[1000];
    int punCon;
    BigInteger bigest = new BigInteger("7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450");

    BigConCheck bcc = new BigConCheck();
    con5=bcc.conCheck(bigest);
    punCon=bcc.bigestEleA(con5);
    System.out.println(punCon);

}
</code>```

}

please point out whats goes wrong @ runtime and why

thanks in advance...

答:
A common mistake is writing
new BigInteger("",num)
instead of
new BigInteger(""+num)</p>

Body:
Getting following run-time error

C:\jdk1.6.0_07\bin>java euler/BigConCheck
Exception in thread "main" java.lang.NumberFormatException: For input string: "z
"
        at java.lang.NumberFormatException.forInputString(NumberFormatException.
java:48)
        at java.lang.Integer.parseInt(Integer.java:447)
        at java.math.BigInteger.<init>(BigInteger.java:314)
        at java.math.BigInteger.<init>(BigInteger.java:447)
        at euler.BigConCheck.conCheck(BigConCheck.java:25)
        at euler.BigConCheck.main(BigConCheck.java:71)

My Code

package euler;
import java.math.BigInteger;
class BigConCheck
{

public int[] conCheck(BigInteger big)
{
    int i=0,q=0,w=0,e=0,r=0,t=0,mul=1;
    int a[]= new int[1000];
    int b[]= new int[7];
    BigInteger rem[]= new BigInteger[4];
    BigInteger num[]= new BigInteger[4];
    for(i=0;i<4;i++)
    num[i]=big;   // intialised num[1 to 4][0] with big
    String s="1",g="0";
    for(i=0;i<999;i++)
    s = s.concat(g);
    BigInteger divi[]= new BigInteger[4];

    for(i=0;i<5;i++)
    {
        divi[i]=new BigInteger(s);
        int z = (int)Math.pow((double)10,(double)i);

        BigInteger zz = new BigInteger("z");    // intialised div[1 to 4][0] with big
        divi[i]=divi[i].divide(zz);
    }

    for(i=0;i<996;i++)   // 5 consecative  numbers.
    {
        for(int k=0;k<5;k++)
        {
            rem[k] = num[k].mod(divi[k]);
            b[k]=rem[k].intValue();
            mul= mul*b[k];
            /*int z = (int)Math.pow((double)10,(double)(k+1));
        String zz = "z";
        BigInteger zzz = new BigInteger(zz);
        num[k]=num[k].divide(zzz);   */
        }

        a[i]=mul;
        for(int p=0;p<5;p++)
        {
            BigInteger qq = new BigInteger("10");
            num[p]=num[p].divide(qq);
        }
    }
    return a;
}

public int bigestEleA(int u[])
{
    int big=0;
    for(int i=0;i<u.length;i++)
    if(big<u[i])
    big=u[i];

    return big;
}

public static void main(String args[])
{
    int con5[]= new int[1000];
    int punCon;
    BigInteger bigest = new BigInteger("7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450");

    BigConCheck bcc = new BigConCheck();
    con5=bcc.conCheck(bigest);
    punCon=bcc.bigestEleA(con5);
    System.out.println(punCon);

}

}

please point out whats goes wrong @ runtime and why

thanks in advance...


问:
android.view.InflateException: Binary XML file line #2: Error inflating class <unknown>?
Sometimes when my application crash in logs I see this : I put my layout which I use in this adapter. In this layout i use image and I don't know what I did wrong that the my application is crashed. It doesn't happen all the time it happen sometimes and I don't know when.

```<code>PID: 5339
android.view.InflateException: Binary XML file line #2: Error inflating class <unknown>
   at android.view.LayoutInflater.createView(LayoutInflater.java:626)
   at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
   at android.view.LayoutInflater.onCreateView(LayoutInflater.java:675)
   at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:700)
   at android.view.LayoutInflater.inflate(LayoutInflater.java:470)
   at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
   at android.view.LayoutInflater.inflate(LayoutInflater.java:354)
   at pl.teminalmobile.Adapter.ExpandableListAdapter.getGroupView(ExpandableListAdapter.java:92)
</code>```

This is my message_list_row :

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:paddingBottom="@dimen/padding_list_row"
    android:paddingLeft="?listPreferredItemPaddingLeft"
    android:paddingRight="?listPreferredItemPaddingRight"
    android:paddingTop="@dimen/padding_list_row">

    <RelativeLayout
        android:id="@+id/rel"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:paddingLeft="15dp"
        android:paddingRight="@dimen/padding_list_row">

        <LinearLayout
            android:id="@+id/message_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentTop="true">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:src="@drawable/home" />

            <TextView
                android:id="@+id/address"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginLeft="5dp"
                android:layout_marginRight="60dp"
                android:gravity="center_vertical"
                android:textColor="@color/from"
                android:textSize="@dimen/msg_text_primary"
                android:textStyle="bold" />
        </LinearLayout>
        <TextView
            android:id="@+id/count"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:textColor="@color/message"
            android:textSize="@dimen/timestamp"
            android:textStyle="bold" />
        <TextView
            android:id="@+id/tv_distance"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/count"
            android:layout_marginTop="2dp"
            android:text="10km"
            android:textColor="@color/message"
            android:textSize="@dimen/timestamp"
            android:textStyle="bold" />

        <ImageView
            android:id="@+id/iv"
            android:layout_width="@dimen/icon_star"
            android:layout_height="@dimen/icon_star"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/tv_distance"
            android:src="@drawable/confirm" />

    </RelativeLayout>

</RelativeLayout>
</code>```

答: Android resize's images based on the screen size and resolution. Try to use the drawable-ldpi, mdpi, hdpi folders for your images.</p>

Body:
Sometimes when my application crash in logs I see this : I put my layout which I use in this adapter. In this layout i use image and I don't know what I did wrong that the my application is crashed. It doesn't happen all the time it happen sometimes and I don't know when.

PID: 5339
android.view.InflateException: Binary XML file line #2: Error inflating class <unknown>
   at android.view.LayoutInflater.createView(LayoutInflater.java:626)
   at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
   at android.view.LayoutInflater.onCreateView(LayoutInflater.java:675)
   at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:700)
   at android.view.LayoutInflater.inflate(LayoutInflater.java:470)
   at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
   at android.view.LayoutInflater.inflate(LayoutInflater.java:354)
   at pl.teminalmobile.Adapter.ExpandableListAdapter.getGroupView(ExpandableListAdapter.java:92)

This is my message_list_row :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:paddingBottom="@dimen/padding_list_row"
    android:paddingLeft="?listPreferredItemPaddingLeft"
    android:paddingRight="?listPreferredItemPaddingRight"
    android:paddingTop="@dimen/padding_list_row">

    <RelativeLayout
        android:id="@+id/rel"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:paddingLeft="15dp"
        android:paddingRight="@dimen/padding_list_row">

        <LinearLayout
            android:id="@+id/message_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentTop="true">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:src="@drawable/home" />

            <TextView
                android:id="@+id/address"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginLeft="5dp"
                android:layout_marginRight="60dp"
                android:gravity="center_vertical"
                android:textColor="@color/from"
                android:textSize="@dimen/msg_text_primary"
                android:textStyle="bold" />
        </LinearLayout>
        <TextView
            android:id="@+id/count"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:textColor="@color/message"
            android:textSize="@dimen/timestamp"
            android:textStyle="bold" />
        <TextView
            android:id="@+id/tv_distance"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/count"
            android:layout_marginTop="2dp"
            android:text="10km"
            android:textColor="@color/message"
            android:textSize="@dimen/timestamp"
            android:textStyle="bold" />

        <ImageView
            android:id="@+id/iv"
            android:layout_width="@dimen/icon_star"
            android:layout_height="@dimen/icon_star"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/tv_distance"
            android:src="@drawable/confirm" />

    </RelativeLayout>

</RelativeLayout>


问:
Zoom MKMapView to fit polyline points
I have an array, allCollections, that holds programmatically-created arrays of CLLocations the user has recorded through my iOS app. Each sub-array in allCollections holds all the location points in a trip taken.

I draw MKPolylines off of the CLLocations in the arrays in allCollections to represent those trips on an MKMapView. My question is this: With the polylines added to the map, how would I go about programmatically zooming and centering the map to display all of them?

答:
Swift 4 / slightly modified version of fundtimer's answer.

```<code> func setVisibleMapArea(polyline: MKPolyline, edgeInsets: UIEdgeInsets, animated: Bool = false) {
    mapView.setVisibleMapRect(polyline.boundingMapRect, edgePadding: edgeInsets, animated: animated)
}
</code>```

Calling the above using a route's polyline and leaving the default of not animated, and adding small edge insets of 10 all around:

```<code>setVisibleMapArea(polyline: route.polyline, edgeInsets: UIEdgeInsetsMake(10.0, 10.0, 10.0, 10.0))
</code>```

Title: Zoom MKMapView to fit polyline points

Body:
Swift 4 / slightly modified version of fundtimer's answer.

 func setVisibleMapArea(polyline: MKPolyline, edgeInsets: UIEdgeInsets, animated: Bool = false) {
    mapView.setVisibleMapRect(polyline.boundingMapRect, edgePadding: edgeInsets, animated: animated)
}

Calling the above using a route's polyline and leaving the default of not animated, and adding small edge insets of 10 all around:

setVisibleMapArea(polyline: route.polyline, edgeInsets: UIEdgeInsetsMake(10.0, 10.0, 10.0, 10.0))


问:
Mongodb distinct count for combination of two fields
In one of my project, I need to get a distinct count for a combination of two fields in my database collection. I will give a brief description about the structure of my collection below.

It is basically a discussion system, it has a list of rooms where people send messages. I am giving a test data from which I require a count

```<code>/************* First Chat **********************************/
{
    "_id"       : ObjectId("8a1370e00d5b6e0a2a865c01"),
    "users"     : ObjectId("69a7a7c462e1e20c15000001"),
    "rooms"     : ObjectId("89ab16244b964729b3154a11"),
    "message"   : "Hello"
},
{
    "_id"       : ObjectId("8a1370e00d5b6e0a2a865c02"),
    "users"     : ObjectId("69a7a7c462e1e20c15000001"),
    "rooms"     : ObjectId("89ab16244b964729b3154a11"),
    "message"   : "Hello test"
},
{
    "_id"       : ObjectId("8a1370e00d5b6e0a2a865c03"),
    "users"     : ObjectId("69a7a7c462e1e20c15000002"),
    "rooms"     : ObjectId("89ab16244b964729b3154a11"),
    "message"   : "I am here"
},
/************* second Chat **********************************/
{
    "_id"       : ObjectId("8a1370e00d5b6e0a2a865c04"),
    "users"     : ObjectId("69a7a7c462e1e20c15000001"),
    "rooms"     : ObjectId("89ab16244b964729b3154a12"),
    "message"   : "Hello New"
},
{
    "_id"       : ObjectId("8a1370e00d5b6e0a2a865c05"),
    "users"     : ObjectId("69a7a7c462e1e20c15000001"),
    "rooms"     : ObjectId("89ab16244b964729b3154a12"),
    "message"   : "Hello test new"
},
{
    "_id"       : ObjectId("8a1370e00d5b6e0a2a865c06"),
    "users"     : ObjectId("69a7a7c462e1e20c15000002"),
    "rooms"     : ObjectId("89ab16244b964729b3154a12"),
    "message"   : "I am here!!!"
},
{
    "_id"       : ObjectId("8a1370e00d5b6e0a2a865c07"),
    "users"     : ObjectId("69a7a7c462e1e20c15000003"),
    "rooms"     : ObjectId("89ab16244b964729b3154a12"),
    "message"   : "I am 3rd user"
}
</code>```

It has 2 rooms
ObjectId("59ef16244b964729b3154a11") and ObjectId("59ef16244b964729b3154a12")

Room 1 has 2 active members
ObjectId("59a7a7c462e1e20c15000001") and ObjectId("59a7a7c462e1e20c15000002")

Room 2 has 3 active members
ObjectId("59a7a7c462e1e20c15000001"), ObjectId("59a7a7c462e1e20c15000002")and ObjectId("59a7a7c462e1e20c15000003")

I need the result like How may rooms a user participated So for the above example I need result as follows

User 1 ObjectId("59a7a7c462e1e20c15000001")  :  count 2

User 2 ObjectId("59a7a7c462e1e20c15000002")  :  count 2

User 3 ObjectId("59a7a7c462e1e20c15000003")  :  count 1

答:
You can use db.collection.distinct() and specify the query as the second argument:

```<code>db.getCollection('message').distinct('rooms', { users: ObjectId('your-user-id')})
</code>```

If you need to get this for each user, you can use aggregation:

```<code>db.getCollection('messages').aggregate([
  { $group: { _id: "$users", rooms: { $addToSet: "$rooms" } } }
]);
</code>```

Here we are grouping the documents by users field, and we're using $addToSet to select distinct values from $rooms field, and the response of this query would be the array of documents with the fields _id (the user's ID) and rooms (the array of ObjectIds of rooms where this user has posted).

Body:
In one of my project, I need to get a distinct count for a combination of two fields in my database collection. I will give a brief description about the structure of my collection below.

It is basically a discussion system, it has a list of rooms where people send messages. I am giving a test data from which I require a count

/************* First Chat **********************************/
{
    "_id"       : ObjectId("8a1370e00d5b6e0a2a865c01"),
    "users"     : ObjectId("69a7a7c462e1e20c15000001"),
    "rooms"     : ObjectId("89ab16244b964729b3154a11"),
    "message"   : "Hello"
},
{
    "_id"       : ObjectId("8a1370e00d5b6e0a2a865c02"),
    "users"     : ObjectId("69a7a7c462e1e20c15000001"),
    "rooms"     : ObjectId("89ab16244b964729b3154a11"),
    "message"   : "Hello test"
},
{
    "_id"       : ObjectId("8a1370e00d5b6e0a2a865c03"),
    "users"     : ObjectId("69a7a7c462e1e20c15000002"),
    "rooms"     : ObjectId("89ab16244b964729b3154a11"),
    "message"   : "I am here"
},
/************* second Chat **********************************/
{
    "_id"       : ObjectId("8a1370e00d5b6e0a2a865c04"),
    "users"     : ObjectId("69a7a7c462e1e20c15000001"),
    "rooms"     : ObjectId("89ab16244b964729b3154a12"),
    "message"   : "Hello New"
},
{
    "_id"       : ObjectId("8a1370e00d5b6e0a2a865c05"),
    "users"     : ObjectId("69a7a7c462e1e20c15000001"),
    "rooms"     : ObjectId("89ab16244b964729b3154a12"),
    "message"   : "Hello test new"
},
{
    "_id"       : ObjectId("8a1370e00d5b6e0a2a865c06"),
    "users"     : ObjectId("69a7a7c462e1e20c15000002"),
    "rooms"     : ObjectId("89ab16244b964729b3154a12"),
    "message"   : "I am here!!!"
},
{
    "_id"       : ObjectId("8a1370e00d5b6e0a2a865c07"),
    "users"     : ObjectId("69a7a7c462e1e20c15000003"),
    "rooms"     : ObjectId("89ab16244b964729b3154a12"),
    "message"   : "I am 3rd user"
}

It has 2 rooms
ObjectId("59ef16244b964729b3154a11") and ObjectId("59ef16244b964729b3154a12")

Room 1 has 2 active members
ObjectId("59a7a7c462e1e20c15000001") and ObjectId("59a7a7c462e1e20c15000002")

Room 2 has 3 active members
ObjectId("59a7a7c462e1e20c15000001"), ObjectId("59a7a7c462e1e20c15000002")and ObjectId("59a7a7c462e1e20c15000003")

I need the result like How may rooms a user participated So for the above example I need result as follows

User 1 ObjectId("59a7a7c462e1e20c15000001")  :  count 2

User 2 ObjectId("59a7a7c462e1e20c15000002")  :  count 2

User 3 ObjectId("59a7a7c462e1e20c15000003")  :  count 1

Body:
You can use db.collection.distinct() and specify the query as the second argument:

db.getCollection('message').distinct('rooms', { users: ObjectId('your-user-id')})

If you need to get this for each user, you can use aggregation:

db.getCollection('messages').aggregate([
  { $group: { _id: "$users", rooms: { $addToSet: "$rooms" } } }
]);

Here we are grouping the documents by users field, and we're using $addToSet to select distinct values from $rooms field, and the response of this query would be the array of documents with the fields _id (the user's ID) and rooms (the array of ObjectIds of rooms where this user has posted).


答:
Replace whole element / elements:

http://api.jquery.com/replaceWith/

Or just change some attributes:

http://api.jquery.com/attr/

Title: It's possible to replace existing html code with jQuery


问:
Appending php array values with string doesn't give expected output
I have database query which returns an array of string values. I want them to be comma separated and appended to another string.

```<code>$sql1 = "select location.name as name from location,destination where destination.name='".$destination."' AND location.destination_id=destination.destination_id";
$result1 = $conn->query($sql1);
if ($result1->num_rows > 0) {
  $insert = "";
    while($locations = $result1->fetch_assoc()) {
  foreach ($locations as $location) {
$insert .= $location['name'] . ",";
      }
   }

$insert = rtrim($insert, ",");

 }

$sql2 = "select destination.destination_description as description from destination where destination.name='".$destination."'";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
    while($row = $result2->fetch_assoc()) {
    $response->speech = $destination." is the ".$row["description"].". ".$insert . "are some of the places you can try.";
   echo json_encode($response);
  }
}
</code>```

This $insert array doesn't give the expected result. It gives just "N".

答:
If i understand your problem. You need to use implode() function of php.Try this:-

```<code>if ($result1->num_rows > 0) {
$ImplodeArray =array();
while($locations = $result1->fetch_assoc()) {
    foreach ($locations as $location) {
        $ImplodeArray[] = $location['name'];
    }
}
$insert = implode(',',$ImplodeArray);
echo $insert;
}
</code>```

Hope it helps!

Body:
I have database query which returns an array of string values. I want them to be comma separated and appended to another string.

$sql1 = "select location.name as name from location,destination where destination.name='".$destination."' AND location.destination_id=destination.destination_id";
$result1 = $conn->query($sql1);
if ($result1->num_rows > 0) {
  $insert = "";
    while($locations = $result1->fetch_assoc()) {
  foreach ($locations as $location) {
$insert .= $location['name'] . ",";
      }
   }

$insert = rtrim($insert, ",");

 }

$sql2 = "select destination.destination_description as description from destination where destination.name='".$destination."'";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
    while($row = $result2->fetch_assoc()) {
    $response->speech = $destination." is the ".$row["description"].". ".$insert . "are some of the places you can try.";
   echo json_encode($response);
  }
}

This $insert array doesn't give the expected result. It gives just "N".

Body:
If i understand your problem. You need to use implode() function of php.Try this:-

if ($result1->num_rows > 0) {
$ImplodeArray =array();
while($locations = $result1->fetch_assoc()) {
    foreach ($locations as $location) {
        $ImplodeArray[] = $location['name'];
    }
}
$insert = implode(',',$ImplodeArray);
echo $insert;
}

Hope it helps!


问:
How to get a number at the end of a string followed by this character `:` using regex
I need to get a number (integer) at the end of a string followed by this character :.

Basically:

qwe-tyu-iop[-zxc:10  //result  should be 10

::qwe-ty:u-iop[-zxc:10  //result  should be 10

::qwe-ty:u-iop[-zxc:10.10  //result  should be undefined

::qwe-ty:u-iop[-zxc:abc  //result  should be undefined

::qwe-ty:u-iop[-zxc:afdf10  //result  should be undefined

答:
This can be achieved using regex as well as using pure JavaScript.

Below are both options:

Using regex

```<code>const regex = /:(\d+)$/gm;
const str = `qwe-tyu-iop[-zxc:10`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    console.log(`Found match --->  ${m[1]}`);
}
</code>```

Using JavaScript only

```<code>const input = 'qwe-tyu-iop[-zxc:10';
const value = input.substring(input.lastIndexOf(':') + 1);
console.log(Number.parseInt(value) == value ? value : "undefined");
</code>```

Body:
This can be achieved using regex as well as using pure JavaScript.

Below are both options:

Using regex

const regex = /:(\d+)$/gm;
const str = `qwe-tyu-iop[-zxc:10`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    console.log(`Found match --->  ${m[1]}`);
}

Using JavaScript only

const input = 'qwe-tyu-iop[-zxc:10';
const value = input.substring(input.lastIndexOf(':') + 1);
console.log(Number.parseInt(value) == value ? value : "undefined");


问:
Tensorflow error: The value of a feed cannot be a tf.Tensor object
This is my code:

```<code>def next_batch(num, data, labels, length):
    idx = np.arange(0 , length)
    np.random.shuffle(idx)
    idx = idx[:num]
    data_shuffle = []
    labels_shuffle = []
    for i in idx:
        data_shuffle.append(data[i])
        labels_shuffle.append(labels[i])

    a = np.asarray(data_shuffle)
    b = np.zeros((num,len(labels[0]),9))

    for i in range(0, num):
        for j in range(0, len(labels[i])):
            b[i][j][labels_shuffle[i][j]] = 1

    return np.asarray(data_shuffle), b
</code>```

and next_Batch function would be called here:

```<code>def train_step(x_batch, y_batch):
    feed_dict = {
      input_x: x_batch,
      input_y: y_batch,
      dropout_keep_prob: dropout_keep_prob
    }
    _, step, loss, accuracy = sess.run(
        [train_op, global_step, losses, accuracys],
        feed_dict=feed_dict)
 ...

step = 0
while step < num_epochs:
    x_batch, y_batch = next_batch(batch_size,training_x, training_y, training_prot_num)
    v_x_batch, v_y_batch = next_batch(batch_size, validation_x, validation_y, validation_prot_num)
    train_step(x_batch, y_batch)
    currenct_step = tf.train.global_step(sess, gloabl_step)
    if currect_step % evaluate_every == 0:
        print("\nEvaluation:")
        dev_step(v_x_batch,v_y_batch)
        print("")
</code>```

And I got an error message :
in sess.run() of train_step ->
TypeError: The value of a feed cannot be a tf.Tensor object.

I don't know why there is an error in this code. next_batch function would return numpy array, so I think there would be no problem.

答: It looks like you have maybe set dropout_keep_prob = tf.constant(..) instead of a float value.

Body:
This is my code:

def next_batch(num, data, labels, length):
    idx = np.arange(0 , length)
    np.random.shuffle(idx)
    idx = idx[:num]
    data_shuffle = []
    labels_shuffle = []
    for i in idx:
        data_shuffle.append(data[i])
        labels_shuffle.append(labels[i])

    a = np.asarray(data_shuffle)
    b = np.zeros((num,len(labels[0]),9))

    for i in range(0, num):
        for j in range(0, len(labels[i])):
            b[i][j][labels_shuffle[i][j]] = 1

    return np.asarray(data_shuffle), b

and next_Batch function would be called here:

def train_step(x_batch, y_batch):
    feed_dict = {
      input_x: x_batch,
      input_y: y_batch,
      dropout_keep_prob: dropout_keep_prob
    }
    _, step, loss, accuracy = sess.run(
        [train_op, global_step, losses, accuracys],
        feed_dict=feed_dict)
 ...

step = 0
while step < num_epochs:
    x_batch, y_batch = next_batch(batch_size,training_x, training_y, training_prot_num)
    v_x_batch, v_y_batch = next_batch(batch_size, validation_x, validation_y, validation_prot_num)
    train_step(x_batch, y_batch)
    currenct_step = tf.train.global_step(sess, gloabl_step)
    if currect_step % evaluate_every == 0:
        print("\nEvaluation:")
        dev_step(v_x_batch,v_y_batch)
        print("")

And I got an error message :
in sess.run() of train_step ->
TypeError: The value of a feed cannot be a tf.Tensor object.

I don't know why there is an error in this code. next_batch function would return numpy array, so I think there would be no problem.


问:
How to set 'Now' button on jquery UI datetimepicker to set UTC time?
I'm using the datetimepicker here.  How can I set the now button so that it sets time UTC now instead of the current now per browser?</p>

答:
Still a problem for many... although you CAN change the source code to always use UTC time, it is not a solution in many cases, as you might need both UTC functionality AND standard (local time) functionality on the same page.. so.. my solution is this to hide the now button on UTC timepicker types.

NOTE! its not perfect, I know, as the timeout fires after the now button is showed it might give a short "blink".. but its ok for me. It hides the "now button" on in the pickers I need it to, and I dont need to change the datetimepicker script!

```<code>    // hides the "now" button (as fast as possible) for the
    // datetimepickerUTC, as that button only works with local time!
    var datetimepickerUTCNowHider = function( currentDateTime ){
        setTimeout(function () {
           $('.datetimepickerUTC').datepicker("widget").find(".ui-datepicker-current").hide();
        }, 0.001 );
    };

    //the utc time
    var dateNow = new Date();
    var utc = new Date(dateNow.getTime() + dateNow.getTimezoneOffset() * 60000);

    // the datetimepicker
    $('.datetimepickerUTC').datetimepicker({
        dateFormat: 'yymmdd',
        timeFormat: 'HH:mm',
        controlType: 'select',
        hour: utc.getHours(),
        minute: utc.getMinutes(),
        beforeShow: datetimepickerUTCNowHider,
        onSelect: datetimepickerUTCNowHider,
        showWeek: true
    });
</code>```

Body:
Still a problem for many... although you CAN change the source code to always use UTC time, it is not a solution in many cases, as you might need both UTC functionality AND standard (local time) functionality on the same page.. so.. my solution is this to hide the now button on UTC timepicker types.

NOTE! its not perfect, I know, as the timeout fires after the now button is showed it might give a short "blink".. but its ok for me. It hides the "now button" on in the pickers I need it to, and I dont need to change the datetimepicker script!

    // hides the "now" button (as fast as possible) for the
    // datetimepickerUTC, as that button only works with local time!
    var datetimepickerUTCNowHider = function( currentDateTime ){
        setTimeout(function () {
           $('.datetimepickerUTC').datepicker("widget").find(".ui-datepicker-current").hide();
        }, 0.001 );
    };

    //the utc time
    var dateNow = new Date();
    var utc = new Date(dateNow.getTime() + dateNow.getTimezoneOffset() * 60000);

    // the datetimepicker
    $('.datetimepickerUTC').datetimepicker({
        dateFormat: 'yymmdd',
        timeFormat: 'HH:mm',
        controlType: 'select',
        hour: utc.getHours(),
        minute: utc.getMinutes(),
        beforeShow: datetimepickerUTCNowHider,
        onSelect: datetimepickerUTCNowHider,
        showWeek: true
    });


问:
Node Express Response Cookie Value is Encoded
I'm trying to set a cookie on the response using Express, but it's encoding the value. I'm setting a value with an equals sign, but on the client, it's coming through as %3D.

Any advice?

Thanks!

答:
Express req.cookie method accepts the third param as config, you can set the encoding method for cookie value in it. By default it uses encodeURLComponent, so to prevent this, you can define a custom function to override it:

```<code>const myCookieEncode = function (val) {
    return val;
};

...

res.cookie(cookieName, cookieValue, { encode: myCookieEncode })
</code>```

Body:
Express req.cookie method accepts the third param as config, you can set the encoding method for cookie value in it. By default it uses encodeURLComponent, so to prevent this, you can define a custom function to override it:

const myCookieEncode = function (val) {
    return val;
};

...

res.cookie(cookieName, cookieValue, { encode: myCookieEncode })


问:
Alternative to the objective-NSDictionary(contentsOfFile) method in swift
I am trying to parse a plist.

The code snippet is given below:

```<code>if let path = Bundle.main.path(forResource: Constants.plistName,    ofType: Constants.plistType) {

       guard let myDictionary = NSDictionary(contentsOfFile: path) else {
           //throw some error
       } }
</code>```

If I set the type of myDictionary to Dictionary, I can no longer use the contentsOfFile method.
Please help.

答:
The (recommended) alternative is PropertyListSerialization

```<code>let url = Bundle.main.url(forResource: Constants.plistName, withExtension: Constants.plistType)!
let data = try! Data(contentsOf: url)
let myDictionary = try! PropertyListSerialization.propertyList(from: data, format: nil) as! [String:Any]
</code>```

Body:
I am trying to parse a plist.

The code snippet is given below:

if let path = Bundle.main.path(forResource: Constants.plistName,    ofType: Constants.plistType) {

       guard let myDictionary = NSDictionary(contentsOfFile: path) else {
           //throw some error
       } }

If I set the type of myDictionary to Dictionary, I can no longer use the contentsOfFile method.
Please help.

Body:
The (recommended) alternative is PropertyListSerialization

let url = Bundle.main.url(forResource: Constants.plistName, withExtension: Constants.plistType)!
let data = try! Data(contentsOf: url)
let myDictionary = try! PropertyListSerialization.propertyList(from: data, format: nil) as! [String:Any]


问:
Google Maps API V3 Printing Maps
I am looking for a method to efficiently print Google maps that have been implemented on a site using the google maps api v3.

I have seen some people using just the window.print js and then

```<code>@media print
{
    body * { visibility: hidden; }
    #map * { visibility: visible; }
    #map {visibility: visible;position:absolute; top: 5px; left: 5px;}
}
</code>```

Currently a larger map is displayed to users using fancybox and I have added a print button to this. Ideally I just want to add some jquery or similar to print the map.

However this doesn't seem to really work. Has anyone got any suggestions on the best way to do this

答:
You can use html2canvas.js to convert map div to canvas element, then you can print it as image. Below code works perfect for me:

HTML

```<code><div id="map" style="width:500px;height:500px;"></div>
<input type="button" value="Print Map" class="printBtn" />
</code>```

JavaScript

```<code>var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 13,
            center: defLocation,
            mapTypeId: 'satellite',
            streetViewControl: false
        });
$(document).on('click', '.printBtn', function () {
            map.setOptions({
                mapTypeControl: false,
                zoomControl: false,
                streetViewControl: false,
                panControl: false
            });
            var printWin = window.open('', '', 'width=1000,height=700');
            var windowContent = '<!DOCTYPE html>';

            html2canvas($("#map"), {
                useCORS: true,
                onrendered: function (canvas) {
                    windowContent += '<html>'
                    windowContent += '<head><title>Print canvas</title></head>';
                    windowContent += '<body>'
                    windowContent += '<img src="' + canvas.toDataURL() + '">';
                    windowContent += '</body>';
                    windowContent += '</html>';
                    printWin.document.open();
                    printWin.document.write(windowContent);
                    printWin.document.close();
                    printWin.focus();
                    setTimeout(function () { printWin.print(); printWin.close(); }, 500);

                    map.setOptions({
                        mapTypeControl: true,
                        zoomControl: true,
                        streetViewControl: true,
                        panControl: true
                    });
                }
            });
        });
</code>```

Title: Google Maps API V3 Printing Maps

Body:
I am looking for a method to efficiently print Google maps that have been implemented on a site using the google maps api v3.

I have seen some people using just the window.print js and then

@media print
{
    body * { visibility: hidden; }
    #map * { visibility: visible; }
    #map {visibility: visible;position:absolute; top: 5px; left: 5px;}
}

Currently a larger map is displayed to users using fancybox and I have added a print button to this. Ideally I just want to add some jquery or similar to print the map.

However this doesn't seem to really work. Has anyone got any suggestions on the best way to do this

Body:
You can use html2canvas.js to convert map div to canvas element, then you can print it as image. Below code works perfect for me:

HTML

<div id="map" style="width:500px;height:500px;"></div>
<input type="button" value="Print Map" class="printBtn" />

JavaScript

var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 13,
            center: defLocation,
            mapTypeId: 'satellite',
            streetViewControl: false
        });
$(document).on('click', '.printBtn', function () {
            map.setOptions({
                mapTypeControl: false,
                zoomControl: false,
                streetViewControl: false,
                panControl: false
            });
            var printWin = window.open('', '', 'width=1000,height=700');
            var windowContent = '<!DOCTYPE html>';

            html2canvas($("#map"), {
                useCORS: true,
                onrendered: function (canvas) {
                    windowContent += '<html>'
                    windowContent += '<head><title>Print canvas</title></head>';
                    windowContent += '<body>'
                    windowContent += '<img src="' + canvas.toDataURL() + '">';
                    windowContent += '</body>';
                    windowContent += '</html>';
                    printWin.document.open();
                    printWin.document.write(windowContent);
                    printWin.document.close();
                    printWin.focus();
                    setTimeout(function () { printWin.print(); printWin.close(); }, 500);

                    map.setOptions({
                        mapTypeControl: true,
                        zoomControl: true,
                        streetViewControl: true,
                        panControl: true
                    });
                }
            });
        });