问:
Error of self edges in hive plot
Absolutely cannot figure out why the error is coming even though there are no self edges.

Below is a reproducible code. Any help would be great

```<code>library(HiveR)

nodes = data.frame(id = 1:9, lab = c("A","B","C","E","F","G","H","I","J"),
axis = c(1,1,1,2,3,2,2,2,3), radius = rep(50,9),size = rep(10,9),
color = c("yellow","yellow","yellow", "green","red","green","green","green","red"))

edges = data.frame(id1 = c(1,2,3,4,5,4,1,9,8,6,1),id2 = c(2,3,4,1,9,9,9,8,7,7,6),
weight = rep(1,11),
color = c(rep("green",7), rep("red",4)))
        test3 <- ranHiveData(nx = 3)
        test3$nodes = nodes
        test3$edges = edges
        test3$edges$color <- as.character(test3$edges$color)
        test3$edges$id1 <- as.integer(test3$edges$id1)
        test3$edges$id2 <- as.integer(test3$edges$id2)
        test3$nodes$color <- as.character(test3$nodes$color)
        test3$nodes$lab <- as.character(test3$nodes$lab)
        test3$nodes$axis = as.integer(test3$nodes$axis)
        test3$nodes$id = as.integer(test3$nodes$id)
        test3$nodes$radius = as.numeric(test3$nodes$radius)
        test3$nodes$size = as.numeric(test3$nodes$size)
        test3$edges$weight = as.numeric(test3$edges$weight)
        test3$desc = "3 axes --9 nodes -- 11 edges"
        sumHPD(test3, chk.sm.pt = TRUE)
</code>```

The code is giving self edges and the the plot is not rendering plotHive(test3) showing

Error in calcCurveGrob(x,x$debug) : end points must not be identical

答:
In your code the position of the nodes of the axis (radius) are all set to 50.
Hence there are overlapping points (3 on axis 1, 4 on axes 2 and 2 on axis 3).

A correct definition of radius solves the problem.

```<code>library(HiveR)

# radius has been changed !
nodes = data.frame(id = 1:9, lab = c("A","B","C","E","F","G","H","I","J"),
axis = c(1,1,1,2,3,2,2,2,3), radius = c(1,2,3,1,1,2,3,4,2),size = rep(1,9),
color = c("yellow","yellow","yellow", "green","red","green","green","green","red"))

edges = data.frame(id1 = c(1,2,3,4,5,4,1,9,8,6,1),id2 = c(2,3,4,1,9,9,9,8,7,7,6),
weight = rep(1,11),
color = c(rep("green",7), rep("red",4)))
        test3 <- ranHiveData(nx = 3)
        test3$nodes = nodes
        test3$edges = edges
        test3$edges$color <- as.character(test3$edges$color)
        test3$edges$id1 <- as.integer(test3$edges$id1)
        test3$edges$id2 <- as.integer(test3$edges$id2)
        test3$nodes$color <- as.character(test3$nodes$color)
        test3$nodes$lab <- as.character(test3$nodes$lab)
        test3$nodes$axis = as.integer(test3$nodes$axis)
        test3$nodes$id = as.integer(test3$nodes$id)
        test3$nodes$radius = as.numeric(test3$nodes$radius)
        test3$nodes$size = as.numeric(test3$nodes$size)
        test3$edges$weight = as.numeric(test3$edges$weight)
        test3$desc = "3 axes --9 nodes -- 11 edges"
        sumHPD(test3, chk.sm.pt = TRUE)

plotHive(test3)
</code>```

Title: Error of self edges in hive plot

Body:
Absolutely cannot figure out why the error is coming even though there are no self edges.

Below is a reproducible code. Any help would be great

library(HiveR)

nodes = data.frame(id = 1:9, lab = c("A","B","C","E","F","G","H","I","J"),
axis = c(1,1,1,2,3,2,2,2,3), radius = rep(50,9),size = rep(10,9),
color = c("yellow","yellow","yellow", "green","red","green","green","green","red"))

edges = data.frame(id1 = c(1,2,3,4,5,4,1,9,8,6,1),id2 = c(2,3,4,1,9,9,9,8,7,7,6),
weight = rep(1,11),
color = c(rep("green",7), rep("red",4)))
        test3 <- ranHiveData(nx = 3)
        test3$nodes = nodes
        test3$edges = edges
        test3$edges$color <- as.character(test3$edges$color)
        test3$edges$id1 <- as.integer(test3$edges$id1)
        test3$edges$id2 <- as.integer(test3$edges$id2)
        test3$nodes$color <- as.character(test3$nodes$color)
        test3$nodes$lab <- as.character(test3$nodes$lab)
        test3$nodes$axis = as.integer(test3$nodes$axis)
        test3$nodes$id = as.integer(test3$nodes$id)
        test3$nodes$radius = as.numeric(test3$nodes$radius)
        test3$nodes$size = as.numeric(test3$nodes$size)
        test3$edges$weight = as.numeric(test3$edges$weight)
        test3$desc = "3 axes --9 nodes -- 11 edges"
        sumHPD(test3, chk.sm.pt = TRUE)

The code is giving self edges and the the plot is not rendering plotHive(test3) showing

Error in calcCurveGrob(x,x$debug) : end points must not be identical

Body:
In your code the position of the nodes of the axis (radius) are all set to 50.
Hence there are overlapping points (3 on axis 1, 4 on axes 2 and 2 on axis 3).

A correct definition of radius solves the problem.

library(HiveR)

# radius has been changed !
nodes = data.frame(id = 1:9, lab = c("A","B","C","E","F","G","H","I","J"),
axis = c(1,1,1,2,3,2,2,2,3), radius = c(1,2,3,1,1,2,3,4,2),size = rep(1,9),
color = c("yellow","yellow","yellow", "green","red","green","green","green","red"))

edges = data.frame(id1 = c(1,2,3,4,5,4,1,9,8,6,1),id2 = c(2,3,4,1,9,9,9,8,7,7,6),
weight = rep(1,11),
color = c(rep("green",7), rep("red",4)))
        test3 <- ranHiveData(nx = 3)
        test3$nodes = nodes
        test3$edges = edges
        test3$edges$color <- as.character(test3$edges$color)
        test3$edges$id1 <- as.integer(test3$edges$id1)
        test3$edges$id2 <- as.integer(test3$edges$id2)
        test3$nodes$color <- as.character(test3$nodes$color)
        test3$nodes$lab <- as.character(test3$nodes$lab)
        test3$nodes$axis = as.integer(test3$nodes$axis)
        test3$nodes$id = as.integer(test3$nodes$id)
        test3$nodes$radius = as.numeric(test3$nodes$radius)
        test3$nodes$size = as.numeric(test3$nodes$size)
        test3$edges$weight = as.numeric(test3$edges$weight)
        test3$desc = "3 axes --9 nodes -- 11 edges"
        sumHPD(test3, chk.sm.pt = TRUE)

plotHive(test3)


来源: stackexchange

问:
Why do Sublime Text 3 Themes not affect the sidebar?
I generally only use dark themes for coding, so it's really annoying that Sublime Text 3's sidebar stays light themed whatever theme you apply.

Does anyone know how to change this?

My configuration: Mac OSX 10.10.1 Yosemite, Sublime Text 3 Stable Channel, Build 3065

答: Just install package SyncedSidebarBg:it will change the sidebar theme based on current color scheme.But it seems that every time you change the color scheme,sidebar will be changed after you open file Preferences.sublime-settings

ContentLicense: CC BY-SA 3.0


问:
Can I use LINQ to get more than 100 records back from a Quickbooks Online ServiceContext?
For my Quickbooks Online integration, I'm using the .NET SDK and was previously using LINQ to access data from a ServiceContext:

```<code>var paymentMethodsService = new QueryService<PaymentMethod>(ServiceContext);
_paymentMethods = paymentMethodsService.Select(x => x).ToList();
</code>```

When testing, we noticed that this only returns the first 100 records. (Presumably because this is the default page size?)

We can get around this by using a query containing MAXRESULTS:

```<code>var itemsService = new QueryService<Item>(ServiceContext);
_items = itemsService.ExecuteIdsQuery("SELECT * FROM Item MAXRESULTS 1000").ToList();
</code>```

My question is, can I achieve the same result without using a query string?

答: I must admit I have no idea what Quickbooks Online even is, but nevertheless I think you can override default page size with LINQ Take(yourPageSize). Though it's still not clear how to fetch ALL items in a collection this way, without knowing total count beforehand. Hopefully you don't need to do this in your scenario (or if you do - maybe you can just use arbitrary large number for Take if you won't find another way).

Body:
For my Quickbooks Online integration, I'm using the .NET SDK and was previously using LINQ to access data from a ServiceContext:

var paymentMethodsService = new QueryService<PaymentMethod>(ServiceContext);
_paymentMethods = paymentMethodsService.Select(x => x).ToList();

When testing, we noticed that this only returns the first 100 records. (Presumably because this is the default page size?)

We can get around this by using a query containing MAXRESULTS:

var itemsService = new QueryService<Item>(ServiceContext);
_items = itemsService.ExecuteIdsQuery("SELECT * FROM Item MAXRESULTS 1000").ToList();

My question is, can I achieve the same result without using a query string?


问:
How to get height of Popup after it is set to wrap_content?
Helo,

I've got this popup:

```<code>    // Inflate the popup_layout.xml
    LinearLayout viewGroup = (LinearLayout) context.findViewById(R.id.popup);
    LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    final View layout = layoutInflater.inflate(R.layout.day_popup_date, viewGroup);

    layout.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
            View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));

    int popupWidth = width;
    final int popupHeight = height;

    // Creating the PopupWindow
    final PopupWindow popup = new PopupWindow(context);

    popup.setContentView(layout);
    popup.setWidth(popupWidth);
    popup.setHeight(ListPopupWindow.WRAP_CONTENT);
    popup.setFocusable(false);
</code>```

As you see, popup.setHeight(ListPopupWindow.WRAP_CONTENT); is set to wrap content.

But I want enlarge the popup to 600px if the size is smaller than 100px.

How can I do that?

Thanks :-)

答:
simply write...</p>

```<code> popup.setHeight(600);
</code>```

Body:
Helo,

I've got this popup:

    // Inflate the popup_layout.xml
    LinearLayout viewGroup = (LinearLayout) context.findViewById(R.id.popup);
    LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    final View layout = layoutInflater.inflate(R.layout.day_popup_date, viewGroup);

    layout.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
            View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));

    int popupWidth = width;
    final int popupHeight = height;

    // Creating the PopupWindow
    final PopupWindow popup = new PopupWindow(context);

    popup.setContentView(layout);
    popup.setWidth(popupWidth);
    popup.setHeight(ListPopupWindow.WRAP_CONTENT);
    popup.setFocusable(false);

As you see, popup.setHeight(ListPopupWindow.WRAP_CONTENT); is set to wrap content.

But I want enlarge the popup to 600px if the size is smaller than 100px.

How can I do that?

Thanks :-)

Body:
simply write...

 popup.setHeight(600);


问:
Make image larger onclick
hello i need to achieve this --->Make image larger onclick.  After different image is selected previous image gets on the size it was before the click and selected image becomes larger

This work's only after image is clicked again

```<code>$(document).ready(function () {
    var small={width: "127px",height: "128px"};
    var large={width: "200px",height: "201px"};
    var count=1;
    $("#weekly").css(small).on('click',function () {
        $(this).animate((count==1)?large:small);
        count = 1-count;
    });
});
</code>```

need to achieve that it makes image smaller after another is selected

答:
You can use the JQuery addClass and removeClass

$('.make_bigger').click(function() {
  $('.active').not(this).addClass('non_active');
  $('.active').not(this).removeClass('active');
  if ($(this).hasClass('active')) {
    $(this).addClass('non_active');
    $(this).removeClass('active');
  } else {
    $(this).removeClass('non_active');
    $(this).addClass('active');
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.active {
  animation: make_bigger 1s ease;
  width: 200px;
  height: 201px;
}
@keyframes make_bigger {
  from { width: 127px; height: 128px; }
  to { width: 200px; height: 201px; }
}
.non_active {
  animation: make_smaller 1s ease;
  width: 127px;
  height: 128px;
}
@keyframes make_smaller {
  from { width: 200px; height: 201px; }
  to { width: 127px; height: 128px; }
}
.container {
  width: 200px;
  height: 201px;
}</code>```

```

Title: Make image larger onclick

Body:
hello i need to achieve this --->Make image larger onclick.  After different image is selected previous image gets on the size it was before the click and selected image becomes larger

This work's only after image is clicked again

$(document).ready(function () {
    var small={width: "127px",height: "128px"};
    var large={width: "200px",height: "201px"};
    var count=1;
    $("#weekly").css(small).on('click',function () {
        $(this).animate((count==1)?large:small);
        count = 1-count;
    });
});

need to achieve that it makes image smaller after another is selected

Body:
You can use the JQuery addClass and removeClass

$('.make_bigger').click(function() {
  $('.active').not(this).addClass('non_active');
  $('.active').not(this).removeClass('active');
  if ($(this).hasClass('active')) {
    $(this).addClass('non_active');
    $(this).removeClass('active');
  } else {
    $(this).removeClass('non_active');
    $(this).addClass('active');
  }
});

.active {
  animation: make_bigger 1s ease;
  width: 200px;
  height: 201px;
}
@keyframes make_bigger {
  from { width: 127px; height: 128px; }
  to { width: 200px; height: 201px; }
}
.non_active {
  animation: make_smaller 1s ease;
  width: 127px;
  height: 128px;
}
@keyframes make_smaller {
  from { width: 200px; height: 201px; }
  to { width: 127px; height: 128px; }
}
.container {
  width: 200px;
  height: 201px;
}

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<div class="container">
  <img width="127px" height="128px" class="make_bigger" src="http://www.lyricsmode.com/i/upictures/205882.gif">
</div>
<div class="container">
  <img width="127px" height="128px" class="make_bigger" src="http://www.lyricsmode.com/i/upictures/205882.gif">
</div>
<div class="container">
  <img width="127px" height="128px" class="make_bigger" src="http://www.lyricsmode.com/i/upictures/205882.gif">
</div>


问:
bootstrap datetimepicker not working in DIV class
I am trying to put in a bootstrap datetimepicker in my customized table. But it just won't work. i understood that you can't placed a script in th, so i placed it in td, but it's still not working.

Simple and working datepicker.

```<code><tr>
<td>Date</td>
<td><!-- mktime(hour, minute, second, month, day, year) -->
<input type="text" name="call_date" value="<?php echo $adjdate;?>" id="datepicker" class="input-small">
</td>
</tr>
</code>```

When i tried to implement bootstrap date time picker, it just won't work. I think i've misplaced something in the code below here.

```<code><tr>
<td>Date</td>
<td>
<div class="container">
<div class="row">
    <div class='col-sm-6'>
        <div class="form-group">
            <div class='input-group date' id='datetimepicker1'>
                <input type='text' class="form-control" />
                <span class="input-group-addon">
                    <span class="glyphicon glyphicon-calendar"></span>
                </span>
            </div>
        </div>
    </div>
    <script type="text/javascript">
        $(function () {
            $('#datetimepicker1').datetimepicker();
        });
    </script>
</div>
</div>
</td>
</tr>
</code>```

Additional info:
i forgot to mention that i've added in

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
</code>```

But if i placed code outside instead of putting inside td, it will work

```<code><div class="container">
<div class="row">
   <div class='col-sm-6'>
    <div class="form-group">
        <div class='input-group date' id='datetimepicker1'>
            <input type='text' class="form-control" />
            <span class="input-group-addon">
                <span class="glyphicon glyphicon-calendar"></span>
            </span>
        </div>
    </div>
</div>
<script type="text/javascript">
    $(function () {
        $('#datetimepicker1').datetimepicker();
    });
</script>
</code>```

I just need advice regarding this, and thanks for showing me those examples, it helps a lot, thank you

答:
install the package
Install-Package Bootstrap.v3.Datetimepicker.CSS

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>   <!-- Bootstrap v3.3.5 -->
<script src="~/Scripts/moment.js"></script>
<script src="~/Scripts/bootstrap-datetimepicker.min.js"></script>
<script src="~/Scripts/Core.js"></script></code>```

Body:
I am trying to put in a bootstrap datetimepicker in my customized table. But it just won't work. i understood that you can't placed a script in th, so i placed it in td, but it's still not working.

Simple and working datepicker.

Date

<input type="text" name="call_date" value="<?php echo $adjdate;?>" id="datepicker" class="input-small">

When i tried to implement bootstrap date time picker, it just won't work. I think i've misplaced something in the code below here.

Date

                <input type='text' class="form-control" />

Additional info:
i forgot to mention that i've added in

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

But if i placed code outside instead of putting inside td, it will work

            <input type='text' class="form-control" />

I just need advice regarding this, and thanks for showing me those examples, it helps a lot, thank you

Body:
install the package
Install-Package Bootstrap.v3.Datetimepicker.CSS

<script>
jQuery(document).ready(function () {

    jQuery('.datepicker').datetimepicker({ format: 'DD/MM/YYYY' });
    jQuery('.datetimepicker').datetimepicker();

});
</script>

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>   <!-- Bootstrap v3.3.5 -->
<script src="~/Scripts/moment.js"></script>
<script src="~/Scripts/bootstrap-datetimepicker.min.js"></script>
<script src="~/Scripts/Core.js"></script>


问:
WebApi Put how to tell not specified properties from specified properties set to null?
Here is the scenario. There is an web api put call to change an object in sql server database. We want only to change the fields on the database object if they were explicitly specified on webapi call json. For example:

```<code>{ "Name":"newName", "Colour":null }
</code>```

That should change the Name field to "newName" and "Colour" field to null. As opposed to this json:

```<code>{ "Name":"newName" }
</code>```

that should only change the Name field, leaving the old Colour value intact.

What is a good way with WebApi to detect whether a property was passed or not?

If I define my method like this:

```<code>[HttpPut]
[Route("/item/{id}")]
public void ChangeItem(int id, Item item)
{
    ...
}
</code>```

item.Colour will be null in either case. Note, that I'm working with a variety of data types here and property Colour in the example could be int, string, DateTime, Guid, etc.

I understand that I can get the raw json with [FromBody] attribute and then parse it myself, but it seems that the default binder is already doing most of the work (including validation), so I would be curious how I could reuse it, but also achieve what I want. What is the easiest way?

Update:

I'd like to clarify that mine is an "occasionally connected" scenario. That is, the devices that are using the API are out of network coverage most of the time, and they sync using the API from time to time.

Practically this means that most of the data that is needed to sync are aggregated into zero or one "push updates to server" call followed by "get latest state from server" call. With Sql Server and EF in the back-end that leads to several different (and sometimes unrelated) entities are contained within single json. Eg:

```<code>class TaskData
{
    public IList<User> AssignedUsers {get; set;}
    public IList<Product> Products {get; set;}
    public Task Task {get; set}
}
</code>```

Also the model classes that are used to generate json for GET calls are separate from EF Entites, as the database schema does not exactly match the API object model.

答:
I solved the problem by using this pattern.</p>

```<code>public class ValuesController : ApiController
{
    public void Put(int id, [FromBody]Item value)
    {
        if (value.NameSpecified)
        {

        }
        else
        {

        }
    }
}

public class Item
{
    internal bool NameSpecified = false;
    private string name;
    public string Name
    {
        get { return name; }
        set
        {
            name = value;
            NameSpecified = true;
        }
    }
}
</code>```

Body:
Here is the scenario. There is an web api put call to change an object in sql server database. We want only to change the fields on the database object if they were explicitly specified on webapi call json. For example:

{ "Name":"newName", "Colour":null }

That should change the Name field to "newName" and "Colour" field to null. As opposed to this json:

{ "Name":"newName" }

that should only change the Name field, leaving the old Colour value intact.

What is a good way with WebApi to detect whether a property was passed or not?

If I define my method like this:

[HttpPut]
[Route("/item/{id}")]
public void ChangeItem(int id, Item item)
{
    ...
}

item.Colour will be null in either case. Note, that I'm working with a variety of data types here and property Colour in the example could be int, string, DateTime, Guid, etc.

I understand that I can get the raw json with [FromBody] attribute and then parse it myself, but it seems that the default binder is already doing most of the work (including validation), so I would be curious how I could reuse it, but also achieve what I want. What is the easiest way?

Update:

I'd like to clarify that mine is an "occasionally connected" scenario. That is, the devices that are using the API are out of network coverage most of the time, and they sync using the API from time to time.

Practically this means that most of the data that is needed to sync are aggregated into zero or one "push updates to server" call followed by "get latest state from server" call. With Sql Server and EF in the back-end that leads to several different (and sometimes unrelated) entities are contained within single json. Eg:

class TaskData
{
    public IList<User> AssignedUsers {get; set;}
    public IList<Product> Products {get; set;}
    public Task Task {get; set}
}

Also the model classes that are used to generate json for GET calls are separate from EF Entites, as the database schema does not exactly match the API object model.

Body:
I solved the problem by using this pattern.

public class ValuesController : ApiController
{
    public void Put(int id, [FromBody]Item value)
    {
        if (value.NameSpecified)
        {

        }
        else
        {

        }
    }
}

public class Item
{
    internal bool NameSpecified = false;
    private string name;
    public string Name
    {
        get { return name; }
        set
        {
            name = value;
            NameSpecified = true;
        }
    }
}


问:
Python: Google API if loop
I'm checking Google API response:

```<code>url = 'https://maps.googleapis.com/maps/api/place/textsearch/json?'
params = {'location': '-38.30000000,176.15000000',
          'radius': '5000',
          'type': 'movie_theater',
          'key': 'MY_KEY'}
response = requests.get(url = url, params=params)
# if response.status_code == 200:
response_data = response.json()

if 'results' in response_data:
    print ('There are results')
elif response_data['status'] == 'ZERO_RESULTS':
    print ('nothing')
</code>```

If you search with Postman for that specific location:

```<code>https://maps.googleapis.com/maps/api/place/textsearch/json?location=-38.30000000,176.15000000&radius=5000&type=movie_theater&key=MY_KEY
</code>```

there are no cinemas and Google API reports:

```<code>{
  "html_attributions": [],
  "results": [],
  "status": "ZERO_RESULTS"
}
</code>```

unfortunately my if, elif seems not working because it doesn't print nothing.
Where am I wrong?

答: you are checking for the existence of the result key in the response_data, which exists, so the "there are results" is correct. You might check for the len of reponse_data['results'] and in case of 0 length print nothing.</p>

Title: Python: Google API if loop

Body:
I'm checking Google API response:

url = 'https://maps.googleapis.com/maps/api/place/textsearch/json?'
params = {'location': '-38.30000000,176.15000000',
          'radius': '5000',
          'type': 'movie_theater',
          'key': 'MY_KEY'}
response = requests.get(url = url, params=params)
# if response.status_code == 200:
response_data = response.json()

if 'results' in response_data:
    print ('There are results')
elif response_data['status'] == 'ZERO_RESULTS':
    print ('nothing')

If you search with Postman for that specific location:

https://maps.googleapis.com/maps/api/place/textsearch/json?location=-38.30000000,176.15000000&radius=5000&type=movie_theater&key=MY_KEY

there are no cinemas and Google API reports:

{
  "html_attributions": [],
  "results": [],
  "status": "ZERO_RESULTS"
}

unfortunately my if, elif seems not working because it doesn't print nothing.
Where am I wrong?


问:
Account Linking - OAUTH2 auth code exchange using Basic HTTP Auth?
Our OAuth 2.0 server expects the client credentials for the auth-code-to-token exchange to be in a Basic HTTP Auth header, a common strategy detailed in the OAuth 2.0 RFC. Is there a flag that can be set on our account to enable this?</p>

答: We are also facing similar issue. Our OAuth 2.0 server expects client credentials should be coming in Basic HTTP Auth header, but looks like from the Actions console it is coming as a part of request body. As you have mentioned that provision is there in your infrastructure, so if you can have that provision in Actions console as well to send client credentials in Basic Auth header it would be great !</p>


问:
Google Tag Manager cannot working in Ionic+Angular App
I'm working a SPA/hybrid App using Ionic+AngluarJs (v1), it's nearly done but now stuck on GTM issue.

GTM provides solution for SPA and it's working well, I can track everything I needed on mobile side (I make the SPA as a mobile site as well, just use content in www folder as a website), however if I build it into Android or IOS, then GTM not working anymore, seems to me after complied, App blocks all request to GTM? But in the SPA I do many external API calls and they are working well.

I searched for help online for a long time but cannot get any idea, I've already  tried to add those settings:
<allow-navigation href="*" />
<allow-intent href="*" /> <meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'">
in config.xml/index.html according to this document: https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-whitelist/
but not working.

My way to use GTM for SPA/hybrid App is almost the same as in this article:
https://www.multiminds.eu/2016/12/06/google-analytics-tag-manager-ionic-cordova/
and I've already make it work well on web pages, why it doesn't after build into App I really confused, it should be just like running a website in a built-in web browser in Android/IOS. Please help me, thank you very much!

答:
I have found this article about this and it seems to work ok for me, people should stop thinking about cordova apps as native, they are just webviews that have access to native components of the device.

Article:

Google Analytics and Tag Manager with Ionic and Cordova apps


问:
Invoke a function by statement in click event

How can we invoke a function with parameter if a statement is return true?

Something Like this below way

```<code>(click)="datavalue.elementDataCollection.length > 1 ? AddNewDialog
(datavalue,datavalue.COCLabel,mainindex,i) : return false"
</code>```

I don't want this below ways:

I won't check this statement in AddNewDialog(). I need call the function directly in click event if the statement is true.

I don't want create duplicate DOM elements

And also I got a answer from this discussion: Call function on condition in Angular 2.
  but I don't know how to handle this way with function parameters.

答:
You can normally try this where AlertUser is custom function

```<code><button (click)="data.length && AlertUser('user')">Click Me</button>
</code>```

Body:
How can we invoke a function with parameter if a statement is return true?

Something Like this below way

(click)="datavalue.elementDataCollection.length > 1 ? AddNewDialog
(datavalue,datavalue.COCLabel,mainindex,i) : return false"

I don't want this below ways:

I won't check this statement in AddNewDialog(). I need call the function directly in click event if the statement is true.

I don't want create duplicate DOM elements

And also I got a answer from this discussion: Call function on condition in Angular 2.
  but I don't know how to handle this way with function parameters.

Body:
You can normally try this where AlertUser is custom function

<button (click)="data.length && AlertUser('user')">Click Me</button>


问:
Adding/Removing url patterns from django during runtime
For example I have a url in my urls.py-

```<code>url(r'^my-url/$', views.my_view)
</code>```

Now on a particular action from views, I want to remove this url from urlpatterns and add a new url during runtime. Is it possible, if so, how?

答:
Changing url handler during runtime is not best practice instead you could have the checkpoint in db and handle all the incoming request

models.py

```<code>class Version(models.Model):
    version_number = models.IntegerField()
    is_latest = models.BooleanField(default=False)
</code>```

urls.py

```<code>url(r'^handler/(?P<version>\d+)/$', views.handler)
</code>```

views.py

```<code>from django.shortcuts import get_object_or_404

def handler(request, version):
    obj = get_object_or_404(Version, version_number=4)
    if obj.is_latest:
        return render(request,'base.html')
    else:
        return render(request, 'old.html')
</code>```

Above code authorise only version 4 ( /handler/4 )

Body:
For example I have a url in my urls.py-

url(r'^my-url/$', views.my_view)

Now on a particular action from views, I want to remove this url from urlpatterns and add a new url during runtime. Is it possible, if so, how?

Body:
Changing url handler during runtime is not best practice instead you could have the checkpoint in db and handle all the incoming request

models.py

class Version(models.Model):
    version_number = models.IntegerField()
    is_latest = models.BooleanField(default=False)

urls.py

url(r'^handler/(?P<version>\d+)/$', views.handler)

views.py

from django.shortcuts import get_object_or_404

def handler(request, version):
    obj = get_object_or_404(Version, version_number=4)
    if obj.is_latest:
        return render(request,'base.html')
    else:
        return render(request, 'old.html')

Above code authorise only version 4 ( /handler/4 )


问:
Java generic understanding Type
I am learning Java generic from: https://docs.oracle.com/javase/tutorial/java/generics/bounded.html and I have some doubts on the code sample below:

```<code>public class Box<T> {

    private T t;

    public void set(T t) {
        this.t = t;
    }

    public T get() {
        return t;
    }

    public <U extends Number> void inspect(U u) {
        System.out.println("T: " + t.getClass().getName());
        System.out.println("U: " + u.getClass().getName());
    }

    public static void main(String[] args) {
        Box<Integer> integerBox = new Box<Integer>();
        integerBox.set(new Integer(10));
        integerBox.inspect("some text"); // error: this is still String!
    }
}
</code>```

Why wasnt the inspect() method to be written as shown below instead it was ?

```<code> public <T extends Number> void inspect(T t) { }
</code>```

There are some other code samples which has the following syntax. What does the 1st pair  stands for?

```<code>public <K,V> SomeClass<K,V>
</code>```

What does static  stands for?

```<code>public static <T> int countGreaterThan(T[] anArray, T elem)
</code>```

答:
```<code>public <U extends Number> void inspect(U u) {
</code>```

waits for a parameter that is of Number type or a derived of it.

So  you cannot of course pass a String value :

```<code>integerBox.inspect("some text"); // error: this is still String!
</code>```

In your class, you declare two parameterized type :

one in the class declaration : public class Box<T> {

another in the public  void inspect(U u) method.

These set two distinct constraints.

When you declare an instance of Box with Integer as generic type:

```<code>Box<Integer> integerBox = new Box<>();
</code>```

This following field using the T type will be associated to an Integer type :

```<code>private T t;
</code>```

but the public  void inspect(U u) method doesn't use the T
type.

So you can use distinct types in the two cases:

```<code>    Box<Integer> integerBox = new Box<Integer>();
    integerBox.set(new Integer(10));
    integerBox.inspect(Float.valueOf(10)); // I pass a float and it is valid.
</code>```

If you would declare the method in this way :

```<code> public <T extends Number> void inspect(T t) { }
</code>```

you would have the same behavior as T in the declared method would be another T type as which one declared in the class.

But this way is misleading as you use use twice the same type name (T) while these are distinct types.

Otherwise, to constraint the parameter of the method to the type declared in the class, you have not to declare still a type.

This is enough :

```<code> public void inspect(T t) { }
</code>```

Now you can only use the same type in the two cases:

```<code>    Box<Integer> integerBox = new Box<Integer>();
    integerBox.set(new Integer(10));
    integerBox.inspect(Float.valueOf(10)); // doesn't compile
</code>```

Title: Java generic understanding Type

Body:
I am learning Java generic from: https://docs.oracle.com/javase/tutorial/java/generics/bounded.html and I have some doubts on the code sample below:

public class Box<T> {

    private T t;

    public void set(T t) {
        this.t = t;
    }

    public T get() {
        return t;
    }

    public  void inspect(U u) {
        System.out.println("T: " + t.getClass().getName());
        System.out.println("U: " + u.getClass().getName());
    }

    public static void main(String[] args) {
        Box<Integer> integerBox = new Box<Integer>();
        integerBox.set(new Integer(10));
        integerBox.inspect("some text"); // error: this is still String!
    }
}

Why wasnt the inspect() method to be written as shown below instead it was ?

 public <T extends Number> void inspect(T t) { }

There are some other code samples which has the following syntax. What does the 1st pair  stands for?

public <K,V> SomeClass<K,V>

What does static  stands for?

public static <T> int countGreaterThan(T[] anArray, T elem)

Body:
public <U extends Number> void inspect(U u) {

waits for a parameter that is of Number type or a derived of it.

So  you cannot of course pass a String value :

integerBox.inspect("some text"); // error: this is still String!

In your class, you declare two parameterized type :

one in the class declaration : public class Box<T> {

another in the public <U extends Number> void inspect(U u) method.

These set two distinct constraints.

When you declare an instance of Box with Integer as generic type:

Box<Integer> integerBox = new Box<>();

This following field using the T type will be associated to an Integer type :

private T t;

but the public <U extends Number> void inspect(U u) method doesn't use the T
type.

So you can use distinct types in the two cases:

    Box<Integer> integerBox = new Box<Integer>();
    integerBox.set(new Integer(10));
    integerBox.inspect(Float.valueOf(10)); // I pass a float and it is valid.

If you would declare the method in this way :

 public <T extends Number> void inspect(T t) { }

you would have the same behavior as T in the declared method would be another T type as which one declared in the class.

But this way is misleading as you use use twice the same type name (T) while these are distinct types.

Otherwise, to constraint the parameter of the method to the type declared in the class, you have not to declare still a type.

This is enough :

 public void inspect(T t) { }

Now you can only use the same type in the two cases:

    Box<Integer> integerBox = new Box<Integer>();
    integerBox.set(new Integer(10));
    integerBox.inspect(Float.valueOf(10)); // doesn't compile


问:
How can I search within a table of comma-separated values?
I have a MySQL table which contains comma-separated values like this:

```<code>first row=(3,56,78,12)
second row=(6,44,2,3)
third row=(67,4,2,7,1)
fourth row=(88,55,22,33)
fifth row=(88,55,3,1,5)
</code>```

I want to select the rows which have 3 in their set. How can I do this?

答:
How about something like</p>

```<code>SELECT *
FROM Table
WHERE Field LIKE '3,%'
OR Field LIKE '%,3'
OR Field LIKE '%,3,%'
OR Field = '3'
</code>```

Body:
I have a MySQL table which contains comma-separated values like this:

first row=(3,56,78,12)
second row=(6,44,2,3)
third row=(67,4,2,7,1)
fourth row=(88,55,22,33)
fifth row=(88,55,3,1,5)

I want to select the rows which have 3 in their set. How can I do this?

Body:
How about something like

SELECT *
FROM Table
WHERE Field LIKE '3,%'
OR Field LIKE '%,3'
OR Field LIKE '%,3,%'
OR Field = '3'

ContentLicense: CC BY-SA 2.5


问:
Using react natives picker
I am trying out picker in my react native project and this example i took directly from the react native docs

```<code><CardItem>
<Item  floatingLabel>
<Label>Airtime Amount</Label>
<Picker selectedValue={this.state.language} onValueChange={(lang) => this.setState({language: lang})}> <Picker.Item label="Java" value="java" /> <Picker.Item label="JavaScript" value="js" /></Picker>
</Item>
</CardItem>
</code>```

This is the source http://facebook.github.io/react-native/docs/picker.html

I get the error

```<code>null is not an object (evaluating 'this.state.language')
</code>```

How can i correct this.
    render

My class starts like this

```<code>class Form extends Component {

  static propTypes = {
    openDrawer: React.PropTypes.func,
  }
....
</code>```

答:
You need to creat the language and give a value</p>

```<code>constructor(props) {
  super();
  this.state = {
    language: 'english', // or language: '',
  }
}
</code>```

Title: Using react natives picker

Body:
I am trying out picker in my react native project and this example i took directly from the react native docs

<CardItem>
<Item  floatingLabel>
Airtime Amount
<Picker selectedValue={this.state.language} onValueChange={(lang) => this.setState({language: lang})}> <Picker.Item label="Java" value="java" /> <Picker.Item label="JavaScript" value="js" /></Picker>
</Item>
</CardItem>

This is the source http://facebook.github.io/react-native/docs/picker.html

I get the error

null is not an object (evaluating 'this.state.language')

How can i correct this.
    render

My class starts like this

class Form extends Component {

  static propTypes = {
    openDrawer: React.PropTypes.func,
  }
....

Body:
You need to creat the language and give a value

constructor(props) {
  super();
  this.state = {
    language: 'english', // or language: '',
  }
}


问:
Is there a better way to write this switch in JavaScript?
I have a switch with the following conditions:

The first case is or between three names (ROKA, MOKA and TOKA).

The second case is another name (KOKA) but with two additional conditions to display an alert.

Lastly, I have some other conditions to check inside the default block, as I'm unable to use a case for them.

This is my code:

```<code>var myname= 'JOKA';
var dhaba = false;

switch (myname) {
  case ('ROKA'):
  case ('MOKA'):
  case ('TOKA'):
    alert('EEE');
    break;

  case ('KOKA'):
    // This will work as Goto to final default:

    if (condition1 && condition2) {
      alert('FEEE');
      break;
    }

  default:
    if (dhaba && myname != 'ROKA' && myname != 'TOKA') {
      alert('TEEEE');
    } else {
      alert('CHEEE');
    }
}
</code>```

Is there a better way to write this code?

答:
When you reach default, then myname is always unequal to the previously checked values. It is sufficient to use

```<code>default:
    if (dhaba) {
        alert('TEEEE');
    } else {
        alert('CHEEE');
    }
</code>```

Body:
I have a switch with the following conditions:

The first case is or between three names (ROKA, MOKA and TOKA).

The second case is another name (KOKA) but with two additional conditions to display an alert.

Lastly, I have some other conditions to check inside the default block, as I'm unable to use a case for them.

This is my code:

var myname= 'JOKA';
var dhaba = false;

switch (myname) {
  case ('ROKA'):
  case ('MOKA'):
  case ('TOKA'):
    alert('EEE');
    break;

  case ('KOKA'):
    // This will work as Goto to final default:

    if (condition1 && condition2) {
      alert('FEEE');
      break;
    }

  default:
    if (dhaba && myname != 'ROKA' && myname != 'TOKA') {
      alert('TEEEE');
    } else {
      alert('CHEEE');
    }
}

Is there a better way to write this code?

Body:
When you reach default, then myname is always unequal to the previously checked values. It is sufficient to use

default:
    if (dhaba) {
        alert('TEEEE');
    } else {
        alert('CHEEE');
    }


问:
Getting date value null in ajax request
I am using Ajax request to send the value of date to my API Controller here is my ajax call

```<code> $("#txtpdate").on("changeDate", function (e) {
        var Date =$('#txtpdate').val();
        console.log(Date);
        $.ajax({
            type: 'POST',
            contentType: false,
            url: '/api/ServiceProvider/GetUpdatedPrice',
            data:{date: Date  },
            cache: false
        }).done(function (response) {

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

And here is my api controller

```<code>[HttpPost]
[Route("GetUpdatedPrice")]
public  ServiceProviderDocuments GetUpdatedPrice(DateTime date)
{
    return  ServiceProviderDocumentsGateway.GetUpdatedPriceofBike(date);
}
</code>```

I am getting the desired value in console.log(Date) but when I reached to the controller it is showing null value
please take a look on the below image

答:
hi try to parse request into json and your date field into date like to:
new Date</p>

```<code> var promise=jQuery.ajax({
        url: url,
        type: 'POST',
        data: JSON.stringify(data),
        contentType: 'application/json; charset=utf-8'
    }).promise();
</code>```

Title: Getting date value null in ajax request

Body:
I am using Ajax request to send the value of date to my API Controller here is my ajax call

 $("#txtpdate").on("changeDate", function (e) {
        var Date =$('#txtpdate').val();
        console.log(Date);
        $.ajax({
            type: 'POST',
            contentType: false,
            url: '/api/ServiceProvider/GetUpdatedPrice',
            data:{date: Date  },
            cache: false
        }).done(function (response) {

        });
});

And here is my api controller

[HttpPost]
[Route("GetUpdatedPrice")]
public  ServiceProviderDocuments GetUpdatedPrice(DateTime date)
{
    return  ServiceProviderDocumentsGateway.GetUpdatedPriceofBike(date);
}

I am getting the desired value in console.log(Date) but when I reached to the controller it is showing null value
please take a look on the below image

Body:
hi try to parse request into json and your date field into date like to:
new Date

 var promise=jQuery.ajax({
        url: url,
        type: 'POST',
        data: JSON.stringify(data),
        contentType: 'application/json; charset=utf-8'
    }).promise();


问:
What determines the maximum number of concurrent users of a SAS stored process server?
I have heard that the number of logical stored process servers is the maximum number of users that can run stored processes concurrently. Is this true?</p>

答: It's mainly driven by the number of multibridge connections (ports) available.  In a default config there are only three - but it is recommended to have four or five per CPU core.</p>


问:
Flexbox grid 1col 1row 3boxes
How can I make this grid without creating 2 columns?

答:
Something like this?

* {
  box-sizing: border-box;
}
.container {
  width: 100%;
}
.left {
  width: 66.66%;
  height: 400px;
  float: left;
  background-color: blue;
}
.right {
  width: 33.33%;
  height: 200px;
  float: right;
  background-color: red;
  border: thin solid black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="left"></div>
  <div class="right"></div>
  <div class="right"></div>
</div></code>```

Title: Flexbox grid 1col 1row 3boxes

Body:
Something like this?

* {
  box-sizing: border-box;
}
.container {
  width: 100%;
}
.left {
  width: 66.66%;
  height: 400px;
  float: left;
  background-color: blue;
}
.right {
  width: 33.33%;
  height: 200px;
  float: right;
  background-color: red;
  border: thin solid black;
}

<div class="container">
  <div class="left"></div>
  <div class="right"></div>
  <div class="right"></div>
</div>


问:
Distance to a plane
I've written a simple little helper method whoch calculates the distance from a point to a plane. However, it seems to be returning nonsensical results. The code i have for creating a plane is thus:

```<code>Plane = new Plane(vertices.First().Position, vertices.Skip(1).First().Position, vertices.Skip(2).First().Position);
</code>```

Fairly simple, I hope you'll agree. It creates an XNA plane structure using three points.

Now, immediately after this I do:

```<code>foreach (var v in vertices)
{
    float d = Math.Abs(v.ComputeDistance(Plane));
    if (d > Constants.TOLERANCE)
        throw new ArgumentException("all points in a polygon must share a common plane");
}
</code>```

Using the same set of vertices I used to construct the plane, I get that exception thrown! Mathematically this is impossible, since those three points must lie on the plane.

My ComputeDistance method is:

```<code>public static float ComputeDistance(this Vector3 point, Plane plane)
{
    float dot = Vector3.Dot(plane.Normal, point);
    float value = dot - plane.D;
    return value;
}
</code>```

AsI understand it, this is correct. So what could I be doing wrong? Or might I be encountering a bug in the implementation of XNA?

Some example data:

```<code>Points:
{X:0 Y:-0.5000001 Z:0.8660254}
{X:0.75 Y:-0.5000001 Z:-0.4330128}
{X:-0.75 Y:-0.5000001 Z:-0.4330126}

Plane created:
{Normal:{X:0 Y:0.9999999 Z:0} D:0.5} //I believe D should equal -0.5?

Distance from point 1 to plane:
1.0
</code>```

答:
It seems that your Plane is implemented so that D is not the projection of one of your points onto the plane normal, but rather the negative of this. You can think of this as projecting a vector from the plane to the origin onto the normal.

In any case, I believe that changing

```<code>float value = dot - plane.D;
</code>```

to

```<code>float value = dot + plane.D;
</code>```

should fix things. HTH.

Title: Distance to a plane

Body:
I've written a simple little helper method whoch calculates the distance from a point to a plane. However, it seems to be returning nonsensical results. The code i have for creating a plane is thus:

Plane = new Plane(vertices.First().Position, vertices.Skip(1).First().Position, vertices.Skip(2).First().Position);

Fairly simple, I hope you'll agree. It creates an XNA plane structure using three points.

Now, immediately after this I do:

foreach (var v in vertices)
{
    float d = Math.Abs(v.ComputeDistance(Plane));
    if (d > Constants.TOLERANCE)
        throw new ArgumentException("all points in a polygon must share a common plane");
}

Using the same set of vertices I used to construct the plane, I get that exception thrown! Mathematically this is impossible, since those three points must lie on the plane.

My ComputeDistance method is:

public static float ComputeDistance(this Vector3 point, Plane plane)
{
    float dot = Vector3.Dot(plane.Normal, point);
    float value = dot - plane.D;
    return value;
}

AsI understand it, this is correct. So what could I be doing wrong? Or might I be encountering a bug in the implementation of XNA?

Some example data:

Points:
{X:0 Y:-0.5000001 Z:0.8660254}
{X:0.75 Y:-0.5000001 Z:-0.4330128}
{X:-0.75 Y:-0.5000001 Z:-0.4330126}

Plane created:
{Normal:{X:0 Y:0.9999999 Z:0} D:0.5} //I believe D should equal -0.5?

Distance from point 1 to plane:
1.0

Body:
It seems that your Plane is implemented so that D is not the projection of one of your points onto the plane normal, but rather the negative of this. You can think of this as projecting a vector from the plane to the origin onto the normal.

In any case, I believe that changing

float value = dot - plane.D;

to

float value = dot + plane.D;

should fix things. HTH.


问:
stripping of white spaces from a string
I have the following string

```<code>argsStr = "server ('m1.labs.terada')ta.com') username ('user5') password('user)5') dbname ('default')";
</code>```

I want to extract the argument name i.e "server" "username" "password".

I am using the following regex to do that

```<code>boost::regex re1("\\(\'[!-~]+\'\\)");
boost::sregex_token_iterator x(argsStr.begin(), argsStr.end(), re1, -1),x1;   boost::sregex_token_iterator y;
std::copy(x, x1, std::back_inserter(v2));
</code>```

v2 is string vector, where I am extracting the tokens. However, The tokens I am getting are

```<code>"server "    INSTEAD of "server
" username "  INSTEAD of "username".
</code>```

How shall I remove these white spaces?

答:
You can just add a couple of "\s*" to your regexp:

```<code>std::regex re1(R"(\s*\('[!-~]+'\)\s*)");
std::sregex_token_iterator x(argsStr.begin(), argsStr.end(), re1, -1), x1;
std::copy(x, x1, std::back_inserter(v2));
</code>```

\s stands for "whitespace character".

This will leave the leftmost whitespace where it is though - if you want to account for that, you can alter the range:

```<code>std::string::iterator start = std::find_if_not(argsStr.begin(), argsStr.end(), ::isspace);
std::sregex_token_iterator x(start, argsStr.end(), re1, -1), x1;
</code>```

I used std::regex in this example but it works for boost as well. Also I used raw string literal for readability, if it is even a thing for regular expressions.

Title: stripping of white spaces from a string

Body:
I have the following string

argsStr = "server ('m1.labs.terada')ta.com') username ('user5') password('user)5') dbname ('default')";

I want to extract the argument name i.e "server" "username" "password".

I am using the following regex to do that

boost::regex re1("\\(\'[!-~]+\'\\)");
boost::sregex_token_iterator x(argsStr.begin(), argsStr.end(), re1, -1),x1;   boost::sregex_token_iterator y;
std::copy(x, x1, std::back_inserter(v2));

v2 is string vector, where I am extracting the tokens. However, The tokens I am getting are

"server "    INSTEAD of "server
" username "  INSTEAD of "username".

How shall I remove these white spaces?

Body:
You can just add a couple of "\s*" to your regexp:

std::regex re1(R"(\s*\('[!-~]+'\)\s*)");
std::sregex_token_iterator x(argsStr.begin(), argsStr.end(), re1, -1), x1;
std::copy(x, x1, std::back_inserter(v2));

\s stands for "whitespace character".

This will leave the leftmost whitespace where it is though - if you want to account for that, you can alter the range:

std::string::iterator start = std::find_if_not(argsStr.begin(), argsStr.end(), ::isspace);
std::sregex_token_iterator x(start, argsStr.end(), re1, -1), x1;

I used std::regex in this example but it works for boost as well. Also I used raw string literal for readability, if it is even a thing for regular expressions.


问:
Paypal Chained Adaptive Payments
I'm a primary receiver of funds on a delayed, chained, adaptive paypal option and only take 10% cut of the transaction.

Let use a simple example. My site allows students to pay experts to write essays on behalf of students(again an example). So teachers are secondary receivers

How my app currently works is that students post a request online to any teacher willing to help.  The teachers bid as per spec. The student then select the teacher.

Once the student select the teacher, the student must deposit funds on Paypal. The funds come to primary receiver (me). But the teacher does not receive anything yet. Until he delivers the essay and the student is happy.

Example the student must deposit $100 to me the primary receiver (when funding the project). Once the teacher has done the job . The students confirms and the teacher then withdraws $90 leaving me with US$10

All the of the above works fine except that when the teacher withdraws $90, US$100 is deducted from my primary account. Leaving me with nothing.

App is on sandbox. Where could be the problem?

答: The cause may somehow be within your PAY API request. Could you please share them here so that we could help take a look.</p>

Title: Paypal Chained Adaptive Payments


问:
Pass multiple values to query dynamically in java
I am trying to pass multiple values in a SELECT QUERY consisting of two IN clauses. I would like to execute the following query:

```<code>String sql = "select ADDRESS from CDR where APARTY in(?,?,?) intersect select ADDRESS from CDR where BPARTY in (?,?) and USAGETYPE='SMSMT'";
</code>```

How can I pass value using preparedStatement.setString() ?.Thanks in advance.

答:
Here's how you do it :

```<code>PreparedStatement pstmt = yourconnexiontoDB.prepareStatement(sql);
pstmt.setString(1, "your first string");
pstmt.setString(2, "your second string");
</code>```

etc ... for the rest of the values.

Body:
I am trying to pass multiple values in a SELECT QUERY consisting of two IN clauses. I would like to execute the following query:

String sql = "select ADDRESS from CDR where APARTY in(?,?,?) intersect select ADDRESS from CDR where BPARTY in (?,?) and USAGETYPE='SMSMT'";

How can I pass value using preparedStatement.setString() ?.Thanks in advance.

Body:
Here's how you do it :

PreparedStatement pstmt = yourconnexiontoDB.prepareStatement(sql);
pstmt.setString(1, "your first string");
pstmt.setString(2, "your second string");

etc ... for the rest of the values.


问:
My android studio shows graphic on opening activity_main.xml
My android studio shows graphically editing instead of the written xml codes. The online curse that i am studying requires me to write the xml codes so please tell me how can i switch to text editing of the visual of my app.</p>

答: On the bottom of that xml there are 2 tabs. 1st is Design and 2nd is Text. Select text and you should be able to see the xml file of layout.</p>


问:
How do I get an object from Model to AngularJS variable in JSP?
I send an object to my JSP. If I use JSP syntax, it displays just fine, for example

```<code>   <div class="mainTitle">
       <h2>${item.name}</h2>
   </div>
</code>```

But when I try to follow instructions for AngularJS I don't get any result. I tried to do it like this

```<code>   <div class="mainTitle" ng-init="itemAngular = ${item}">
       <h2>${itemAngular.name}</h2>
   </div>
</code>```

But it just doesn't work, there's no output. What am I doing wrong here?

答:
You need to send your object like Json String. Then, client side, parse your String to JSON</p>

```<code>var objJson = ${item}; // String;
$scope.item = JSON.parse(objJson);
</code>```

Body:
I send an object to my JSP. If I use JSP syntax, it displays just fine, for example

${item.name}

But when I try to follow instructions for AngularJS I don't get any result. I tried to do it like this

${itemAngular.name}

But it just doesn't work, there's no output. What am I doing wrong here?

Body:
You need to send your object like Json String. Then, client side, parse your String to JSON

var objJson = ${item}; // String;
$scope.item = JSON.parse(objJson);


问:
jquery color animation throws Invalid property value intermittently
I'm trying to animate the background for an ASP.Net hyperlink to do a yellow fade on an update panels refresh.  So far it works almost all of the time, but occasionally a javascript error is thrown "Invalid Propery value." and it debugs into the jquery color plug-in code to this line...

```<code>fx.elem.style[attr] = "rgb(" + [
     Math.max(Math.min(parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
     Math.max(Math.min(parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
     Math.max(Math.min(parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
].join(",") + ")";</code>```

Here is the order of events as they are currently happening...

First, the window loads so on doc.ready it registers an event to be carried out when the update panel has finished refreshing like so...

```<code>Sys.WebForms.PageRequestManager.getInstance().add_endRequest(yellowFade);
</code>```

Where yellowFade is defined as...

```<code>function yellowFade() {
    window.setTimeout("$('#' + hyperlinkUrlId).animate( { backgroundColor: 'white' }, 2000)", 2000);
    window.clearTimeout();
}
</code>```

Now, rarely I've had it crash right at this point but typically it is later, so I'll continue...

I then click a button titled "Generate" that creates a URL loads the ASP.Net hyperlink with the text for the URL it created and then via javascript sets it's background color to the yellow color to fade from via this...

```<code>$("#" + hyperlinkUrlId).css("background-color", "#FBFF9C");</code>```

I initially had it setting the color in the code behind via this code...

```<code>Url.BackColor = ColorTranslator.FromHtml("#FBFF9C");</code>```

But then I thought maybe the back color was getting set to something the jquery color plug-in couldn't recognize, or since it was being set server side the plug-in couldn't access it's style or something but changing it still had no effect on fixing the bug.

Finally, generate changes the URL's back color from white to yellow then as I said most of the time it fades just fine but rarely it throws an error "Invalid property value."

As far as I can tell my syntax is just the way it should be for using the color animations.  I feel like the fact that I'm using an updatepanel might be wreaking havoc here but I'm not sure.

Does anyone have any insight into what might cause such a thing?  It's been a real mess trying to debug since it happens so infrequently disregarding the fact that javascript is already a pain to debug.

Using jquery 1.3.1 and jquery.color 1.0 on Windows Vista.  Using Visual Studio 2008.  Let me know if there is anything I can clear up.

EDIT: Dang, not a single response yet.  I've taken a bit of a hiatus from working on this but I just found the bug in another part of my app where I am doing the yellow fade.  Both of these pages use an update panel.  I'm not a fan of the update panel in many cases and it has definitely wreaked havoc on my jquery.  I'm wondering if it has something to do with this.  Oh, this was kind of implied with the whole Vista thing but I'll point out that I'm running on IIS7.

Does this provoke any insights?

答:
I was having similar problem with jquery.color.js. Resolved this by using jquery.effects.core.js (jquery ui effects core).

I hope it works for you as well.

OwnerDisplayName: Carter

Body:
I'm trying to animate the background for an ASP.Net hyperlink to do a yellow fade on an update panels refresh.  So far it works almost all of the time, but occasionally a javascript error is thrown "Invalid Propery value." and it debugs into the jquery color plug-in code to this line...

fx.elem.style[attr] = "rgb(" + [
     Math.max(Math.min(parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
     Math.max(Math.min(parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
     Math.max(Math.min(parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
].join(",") + ")";

Here is the order of events as they are currently happening...

First, the window loads so on doc.ready it registers an event to be carried out when the update panel has finished refreshing like so...

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(yellowFade);

Where yellowFade is defined as...

function yellowFade() {
    window.setTimeout("$('#' + hyperlinkUrlId).animate( { backgroundColor: 'white' }, 2000)", 2000);
    window.clearTimeout();
}

Now, rarely I've had it crash right at this point but typically it is later, so I'll continue...

I then click a button titled "Generate" that creates a URL loads the ASP.Net hyperlink with the text for the URL it created and then via javascript sets it's background color to the yellow color to fade from via this...

$("#" + hyperlinkUrlId).css("background-color", "#FBFF9C");

I initially had it setting the color in the code behind via this code...

Url.BackColor = ColorTranslator.FromHtml("#FBFF9C");

But then I thought maybe the back color was getting set to something the jquery color plug-in couldn't recognize, or since it was being set server side the plug-in couldn't access it's style or something but changing it still had no effect on fixing the bug.

Finally, generate changes the URL's back color from white to yellow then as I said most of the time it fades just fine but rarely it throws an error "Invalid property value."

As far as I can tell my syntax is just the way it should be for using the color animations.  I feel like the fact that I'm using an updatepanel might be wreaking havoc here but I'm not sure.

Does anyone have any insight into what might cause such a thing?  It's been a real mess trying to debug since it happens so infrequently disregarding the fact that javascript is already a pain to debug.

Using jquery 1.3.1 and jquery.color 1.0 on Windows Vista.  Using Visual Studio 2008.  Let me know if there is anything I can clear up.

EDIT: Dang, not a single response yet.  I've taken a bit of a hiatus from working on this but I just found the bug in another part of my app where I am doing the yellow fade.  Both of these pages use an update panel.  I'm not a fan of the update panel in many cases and it has definitely wreaked havoc on my jquery.  I'm wondering if it has something to do with this.  Oh, this was kind of implied with the whole Vista thing but I'll point out that I'm running on IIS7.

Does this provoke any insights?

LastEditorDisplayName: Carter


问:
Multiple Prototype cells displaying in one row in tableview in xamarin.ios
I'm having an issue with a tableview in xamarin.ios, I'm trying to use multiple prototype cells but all of the prototype cells are showing on the same row in the table view and I want them to have there own row, does anyone have the solution?

Thanks.

答:
you will likely need to overide the rows in section method of your UITableView's Source class.

```<code>public override nint RowsInSection (UITableView tableView, nint section)
{
     return (nint)MyTableDataList?.Count;
}
</code>```

If you'd like to provide some actual code, we may be able to be more accurate.

Body:
you will likely need to overide the rows in section method of your UITableView's Source class.

public override nint RowsInSection (UITableView tableView, nint section)
{
     return (nint)MyTableDataList?.Count;
}

If you'd like to provide some actual code, we may be able to be more accurate.


问:
Spring Boot @ControllerAdvice partially working, not working for custom exception
I'm having a peculiar situation with my @ControllerAdvice annotated ExceptionHandler in Spring Boot 1.5.3. It catches any exceptions default Exceptions, but if I throw a custom exception it does not fire.

The ExceptionHandler:

```<code>@ControllerAdvice
public class ResponseEntityExceptionHandler {

@ExceptionHandler({ HttpMessageNotReadableException.class })
protected ResponseEntity<ErrorModel> handleInvalidJson(RuntimeException e, WebRequest request) {
    return new ResponseEntity<ErrorModel>(new ErrorModel().message("Could not parse JSON."), HttpStatus.BAD_REQUEST);
}

@ExceptionHandler({ NumberFormatException.class })
protected ResponseEntity<ErrorModel> handleInvalidRequest(RuntimeException e, WebRequest request) {
    return new ResponseEntity<ErrorModel>(new ErrorModel().message("Invalid request parameter."), HttpStatus.BAD_REQUEST);
}

@ExceptionHandler({ CannotCreateTransactionException.class })
protected ResponseEntity<ErrorModel> handleTransactionCreationException(RuntimeException e, WebRequest request) {
    return new ResponseEntity<ErrorModel>(new ErrorModel().message("Error connecting to the database, please make sure it is still available."), HttpStatus.BAD_REQUEST);
}

@ExceptionHandler({ NotFoundException.class })
protected ResponseEntity<ErrorModel> handleApiException(RuntimeException e, WebRequest request) {
    return new ResponseEntity<ErrorModel>(new ErrorModel().message(e.getMessage()), HttpStatus.NOT_FOUND);
}
}
</code>```

The top 3 Exceptions all get caught and handled as they are supposed to, but the bottom Exception gets handled by the default Spring-Boot ExceptionHandler. It is a custom Exception that I throw inside a Controller:

```<code>public ResponseEntity<?> deleteActor(@ApiParam(value = "Used to identify a single actor.", required = true) @PathVariable("actor_id") Integer actorId, @RequestHeader("Accept") String accept) throws Exception {
Actor actor = actorRepository.findOne(actorId);
if (actor == null) {
    throw new NotFoundException(404, "Not found");
}
actorRepository.delete(actorId);
return new ResponseEntity<Void>(HttpStatus.NO_CONTENT);
}
</code>```

I've tried throwing one of the top Exceptions like this:

```<code>public ResponseEntity<?> readActor(@ApiParam(value = "Used to identify a single actor.", required = true) @PathVariable("actor_id") Integer actorId, @RequestHeader("Accept") String accept) throws Exception {
    Actor actor = actorRepository.findOne(actorId);
    if (actor == null) {
        throw new NumberFormatException("");
    }
    return new ResponseEntity<Actor>(actor, HttpStatus.OK);
}
</code>```

and these get handled just fine...

The tomcat logs also show this:

```<code>2017-06-05 11:30:20.080  INFO 9076 --- [           main] .m.m.a.ExceptionHandlerExceptionResolver : Detected @ExceptionHandler methods in responseEntityExceptionHandler
</code>```

The Exception:

```<code>public class NotFoundException extends ApiException {
private int code;
public NotFoundException (int code, String msg) {
    super(code, msg);
    this.code = code;
}
}
</code>```

The exception inherits from this baseclass:

```<code>public class ApiException extends Exception{
private int code;
public ApiException (int code, String msg) {
    super(msg);
    this.code = code;
}
}
</code>```

Any ideas about why the custom Exception avoids detection by the ExceptionHandler?

I would be happy to provide additional information should that be necessary.

答:
For this particular case the answer is to use Exception instead of RuntimeException, since NotFoundException does only inherit from Exception.

Further notable things:

To catch all exceptions one can use an @ExceptionHandler(Exception.class)

If using common names for exceptions, always check if you have imported the right one.

Body:
I'm having a peculiar situation with my @ControllerAdvice annotated ExceptionHandler in Spring Boot 1.5.3. It catches any exceptions default Exceptions, but if I throw a custom exception it does not fire.

The ExceptionHandler:

@ControllerAdvice
public class ResponseEntityExceptionHandler {

@ExceptionHandler({ HttpMessageNotReadableException.class })
protected ResponseEntity<ErrorModel> handleInvalidJson(RuntimeException e, WebRequest request) {
    return new ResponseEntity<ErrorModel>(new ErrorModel().message("Could not parse JSON."), HttpStatus.BAD_REQUEST);
}

@ExceptionHandler({ NumberFormatException.class })
protected ResponseEntity<ErrorModel> handleInvalidRequest(RuntimeException e, WebRequest request) {
    return new ResponseEntity<ErrorModel>(new ErrorModel().message("Invalid request parameter."), HttpStatus.BAD_REQUEST);
}

@ExceptionHandler({ CannotCreateTransactionException.class })
protected ResponseEntity<ErrorModel> handleTransactionCreationException(RuntimeException e, WebRequest request) {
    return new ResponseEntity<ErrorModel>(new ErrorModel().message("Error connecting to the database, please make sure it is still available."), HttpStatus.BAD_REQUEST);
}

@ExceptionHandler({ NotFoundException.class })
protected ResponseEntity<ErrorModel> handleApiException(RuntimeException e, WebRequest request) {
    return new ResponseEntity<ErrorModel>(new ErrorModel().message(e.getMessage()), HttpStatus.NOT_FOUND);
}
}

The top 3 Exceptions all get caught and handled as they are supposed to, but the bottom Exception gets handled by the default Spring-Boot ExceptionHandler. It is a custom Exception that I throw inside a Controller:

public ResponseEntity<?> deleteActor(@ApiParam(value = "Used to identify a single actor.", required = true) @PathVariable("actor_id") Integer actorId, @RequestHeader("Accept") String accept) throws Exception {
Actor actor = actorRepository.findOne(actorId);
if (actor == null) {
    throw new NotFoundException(404, "Not found");
}
actorRepository.delete(actorId);
return new ResponseEntity<Void>(HttpStatus.NO_CONTENT);
}

I've tried throwing one of the top Exceptions like this:

public ResponseEntity<?> readActor(@ApiParam(value = "Used to identify a single actor.", required = true) @PathVariable("actor_id") Integer actorId, @RequestHeader("Accept") String accept) throws Exception {
    Actor actor = actorRepository.findOne(actorId);
    if (actor == null) {
        throw new NumberFormatException("");
    }
    return new ResponseEntity<Actor>(actor, HttpStatus.OK);
}

and these get handled just fine...

The tomcat logs also show this:

2017-06-05 11:30:20.080  INFO 9076 --- [           main] .m.m.a.ExceptionHandlerExceptionResolver : Detected @ExceptionHandler methods in responseEntityExceptionHandler

The Exception:

public class NotFoundException extends ApiException {
private int code;
public NotFoundException (int code, String msg) {
    super(code, msg);
    this.code = code;
}
}

The exception inherits from this baseclass:

public class ApiException extends Exception{
private int code;
public ApiException (int code, String msg) {
    super(msg);
    this.code = code;
}
}

Any ideas about why the custom Exception avoids detection by the ExceptionHandler?

I would be happy to provide additional information should that be necessary.


问:
Django search in multiple field with multiple value
I have a model which stores login logout time and date for users

```<code>class LoginLogout(models.Model):
    username = models.CharField(max_length=30, unique=True)
    date = models.DateField(auto_now_add=True)
    login_time = models.TimeField()
    logout_time = models.TimeField(null=True, blank=True)
</code>```

Now I need to search in this model by the field date and username. I have a form which takes date_from, date_to and username as input. Any field can be blank. If username is blank all results will be returned. Now what will be the queryset for achieving the desired queryset.

答:
try this:</p>

```<code>from django.db.models import Q

if username or date_from or date_to:
    LoginLogout.objects.filter(
                               Q(username=username),
                               Q(date__gt='date_from'),
                               Q(date__lt='date_to')
                              )
else:
    LoginLogout.objects.all()
</code>```

Body:
I have a model which stores login logout time and date for users

class LoginLogout(models.Model):
    username = models.CharField(max_length=30, unique=True)
    date = models.DateField(auto_now_add=True)
    login_time = models.TimeField()
    logout_time = models.TimeField(null=True, blank=True)

Now I need to search in this model by the field date and username. I have a form which takes date_from, date_to and username as input. Any field can be blank. If username is blank all results will be returned. Now what will be the queryset for achieving the desired queryset.

Body:
try this:

from django.db.models import Q

if username or date_from or date_to:
    LoginLogout.objects.filter(
                               Q(username=username),
                               Q(date__gt='date_from'),
                               Q(date__lt='date_to')
                              )
else:
    LoginLogout.objects.all()


问:
Java throws Exception :Selenium 3.4.0,Gecko driver 16.01,FF 53.01
When run,java throws following exception:
Exception in thread "main" org.openqa.selenium.SessionNotCreatedException: Unable to create new remote session. desired capabilities = Capabilities [{marionette=true, browserName=firefox, version=, platform=A.
Im using gecko driver 16.1.When I use gecko 14.01 its navigating till gmail page and then not able to find element even when I set implicit wait.</p>

```<code>    import java.util.concurrent.TimeUnit;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.firefox.MarionetteDriver;
    import org.openqa.selenium.remote.DesiredCapabilities;
    public class login {
    public static void main(String[] args) {
        // Create a new instance of the Firefox driver
    System.setProperty("webdriver.gecko.driver","C:/Users/asdf/Desktop/selenium/gecko32/geckodriver.exe");
    DesiredCapabilities capabilities=DesiredCapabilities.firefox();
    capabilities.setCapability("marionette", true);
    WebDriver driver = new MarionetteDriver(capabilities);
        //WebDriver driver = new FirefoxDriver();
        //  Wait For Page To Load
        // Put a Implicit wait, this means that any search for elements on the page
    driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
        // Navigate to URL
    driver.get("https://mail.google.com/");
    driver.manage().window().maximize();
    //driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        // gmail login
    driver.findElement(By.xpath("//*[@id='identifierId']")).sendKeys("username");
    driver.findElement(By.id("next")).click();
    driver.findElement(By.id("Passwd")).sendKeys("password");
</code>```

答:
Here is the Answer to your Question:

SessionNotCreatedException can be observed for different reasons, such as Selenium-geckodriver version mismatch, dangling geckodriver instances and OS chores. I will suggest you to consider the following steps:

From Task Manager kill all the dangling geckodriver instances manually/programatically. If possible restart your system. If needed, run the CCleaner to wipe away all the unwanted OS chores from your system.

Download Selenium Standalone Server 3.4.0 or Selenium Client 3.4.0 from this page.

Download geckodriver v.0.16.1 from this page.

Ensure you have installed the latest stable GA version of Mozilla Firefox 53.0

The MarionetteDriver implementation is discontinued, you can consider using the FirefoxDriver implementation.

For a detailed discussion on MarionetteDriver and GeckoDriver you can consider having a look at this discussion.

Here is your own code which executes well with some minor tweaks:

```<code>package demo;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;

public class Q44351100_SessionNotCreatedException
{
    public static void main(String[] args)
    {
        System.setProperty("webdriver.gecko.driver","C:/your_directory/geckodriver.exe");
        DesiredCapabilities capabilities=DesiredCapabilities.firefox();
        capabilities.setCapability("marionette", true);
        WebDriver driver = new FirefoxDriver(capabilities);
        driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
        driver.get("https://mail.google.com/");
        driver.manage().window().maximize();
        driver.findElement(By.xpath("//*[@id='identifierId']")).sendKeys("username");
    }
}
</code>```

Let me know if this Answers your Question.

Body:
When run,java throws following exception:
Exception in thread "main" org.openqa.selenium.SessionNotCreatedException: Unable to create new remote session. desired capabilities = Capabilities [{marionette=true, browserName=firefox, version=, platform=A.
Im using gecko driver 16.1.When I use gecko 14.01 its navigating till gmail page and then not able to find element even when I set implicit wait.

    import java.util.concurrent.TimeUnit;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.firefox.MarionetteDriver;
    import org.openqa.selenium.remote.DesiredCapabilities;
    public class login {
    public static void main(String[] args) {
        // Create a new instance of the Firefox driver
    System.setProperty("webdriver.gecko.driver","C:/Users/asdf/Desktop/selenium/gecko32/geckodriver.exe");
    DesiredCapabilities capabilities=DesiredCapabilities.firefox();
    capabilities.setCapability("marionette", true);
    WebDriver driver = new MarionetteDriver(capabilities);
        //WebDriver driver = new FirefoxDriver();
        //  Wait For Page To Load
        // Put a Implicit wait, this means that any search for elements on the page
    driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
        // Navigate to URL
    driver.get("https://mail.google.com/");
    driver.manage().window().maximize();
    //driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        // gmail login
    driver.findElement(By.xpath("//*[@id='identifierId']")).sendKeys("username");
    driver.findElement(By.id("next")).click();
    driver.findElement(By.id("Passwd")).sendKeys("password");

Body:
Here is the Answer to your Question:

SessionNotCreatedException can be observed for different reasons, such as Selenium-geckodriver version mismatch, dangling geckodriver instances and OS chores. I will suggest you to consider the following steps:

From Task Manager kill all the dangling geckodriver instances manually/programatically. If possible restart your system. If needed, run the CCleaner to wipe away all the unwanted OS chores from your system.

Download Selenium Standalone Server 3.4.0 or Selenium Client 3.4.0 from this page.

Download geckodriver v.0.16.1 from this page.

Ensure you have installed the latest stable GA version of Mozilla Firefox 53.0

The MarionetteDriver implementation is discontinued, you can consider using the FirefoxDriver implementation.

For a detailed discussion on MarionetteDriver and GeckoDriver you can consider having a look at this discussion.

Here is your own code which executes well with some minor tweaks:

package demo;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;

public class Q44351100_SessionNotCreatedException
{
    public static void main(String[] args)
    {
        System.setProperty("webdriver.gecko.driver","C:/your_directory/geckodriver.exe");
        DesiredCapabilities capabilities=DesiredCapabilities.firefox();
        capabilities.setCapability("marionette", true);
        WebDriver driver = new FirefoxDriver(capabilities);
        driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
        driver.get("https://mail.google.com/");
        driver.manage().window().maximize();
        driver.findElement(By.xpath("//*[@id='identifierId']")).sendKeys("username");
    }
}

Let me know if this Answers your Question.


问:
How can I search within a table of comma-separated values?
I have a MySQL table which contains comma-separated values like this:

```<code>first row=(3,56,78,12)
second row=(6,44,2,3)
third row=(67,4,2,7,1)
fourth row=(88,55,22,33)
fifth row=(88,55,3,1,5)
</code>```

I want to select the rows which have 3 in their set. How can I do this?

答:
use this condition </p>

```<code>WHERE firstrow LIKE '3,%'
    OR firstrow like '%,3'
    OR firstrow like '3'
</code>```

Body:
I have a MySQL table which contains comma-separated values like this:

first row=(3,56,78,12)
second row=(6,44,2,3)
third row=(67,4,2,7,1)
fourth row=(88,55,22,33)
fifth row=(88,55,3,1,5)

I want to select the rows which have 3 in their set. How can I do this?

Body:
use this condition

WHERE firstrow LIKE '3,%'
    OR firstrow like '%,3'
    OR firstrow like '3'


问:
How to access instance variable in static companion object in Kotlin
I am trying to make utils for performing network operations in kotlin. I have below code where the primary constructor is taking Command and Context.

I am unable to access command variable in command.execute(JSONObject(jsonObj)), getting below error. I am not sure what is causing an issue?

Unresolved reference: command

```<code>class AsyncService(val command: Command, val context: Context) {

    companion object {
        fun doGet(request: String) {
            doAsync {
                val jsonObj = java.net.URL(request).readText()
                command.execute(JSONObject(jsonObj))
            }
        }
    }
}
</code>```

答:
A companion object is not part of an instance of a class.
You can't access members from a companion object, just like in Java you can't access members from a static method.

Instead, don't use a companion object:

```<code>class AsyncService(val command: Command, val context: Context) {

    fun doGet(request: String) {
        doAsync {
            val jsonObj = java.net.URL(request).readText()
            command.execute(JSONObject(jsonObj))
        }
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to make utils for performing network operations in kotlin. I have below code where the primary constructor is taking Command and Context.

I am unable to access command variable in command.execute(JSONObject(jsonObj)), getting below error. I am not sure what is causing an issue?

Unresolved reference: command

class AsyncService(val command: Command, val context: Context) {

    companion object {
        fun doGet(request: String) {
            doAsync {
                val jsonObj = java.net.URL(request).readText()
                command.execute(JSONObject(jsonObj))
            }
        }
    }
}

Body:
A companion object is not part of an instance of a class.
You can't access members from a companion object, just like in Java you can't access members from a static method.

Instead, don't use a companion object:

class AsyncService(val command: Command, val context: Context) {

    fun doGet(request: String) {
        doAsync {
            val jsonObj = java.net.URL(request).readText()
            command.execute(JSONObject(jsonObj))
        }
    }
}


问:
Nunit parallel lifecycle and parallel test failing sometimes
I am having an issue with tests sporadically failing when using nunit 3 and using parallel test running.

We have a number of tests that currently are structured as follows

```<code>[TestFixture]
public class CalculateShipFromStoreShippingCost
{
    private IService_service;
    private IClient _client;

    [SetUp]
    public void SetUp()
    {
        _service = Substitute.For<IService>();
        _client = new Client(_service);
    }

    [Test]
    public async Task WhenScenario1()
    {
        _service.Apply(Args.Any<int>).Returns(1);
        var result = _client.DoTheThing();
        Assert.IsTrue(1,result);
    }

    [Test]
    public async Task WhenScenario2()
    {
        _service.Apply(Args.Any<int>).Returns(2);
        var result = _client.DoTheThing();
        Assert.IsTrue(2,result);
    }
}
</code>```

Sometimes the test fail as one of the substitutes is returning the value for the other test.

How should this test be structured so that with Nunit it will run reliably when done in parallel

答:
You haven't shown any Parallelizable attributes in your example, so I assume you are using the attribute at a higher level, most likely on the assembly. Otherwise, no parallel execution would occur. Further, since you say the test cases are running in parallel, you have apparently specified ParallelScope.Children.

The two test cases shown in your fixture cannot run in parallel. You should bear in mind that the SetUp method runs for each of the tests. So each of your two tests sets the value of _service, which is part of the state of the single instance of CalculateShipFromStoreShippingCost, which is shared by both tests. That is why you are seeing the "wrong" substitute being returned at times.

It is not possible for two test cases to run reliably in parallel if they both change the state of the fixture. Note that it does not matter whether the assignment to _service takes place in the test method itself or in the SetUp method - both are executed as part of the test case. So, you have to either stop running these two cases in parallel or stop changing the state.

To stop running the tests in parallel, you simply add [NonParallelizable] to each test method. If you are not using the latest framework version, use [Parallelizable(ParallelScope.None)] instead. Your other tests will continue to run in parallel, but these two will not.

Alternatively, use ParallelScope.Fixture at the assembly level. This will cause fixtures to run in parallel by default, while the individual test cases within them each run sequentially. When using ParallelizableAttribute at the assembly level, it is sometimes best to take a more conservative approach, adding in more parallelism within some fixtures where it is useful.

An entirely different approach is to make your tests stateless. Eliminate the _service member and use a local value within the test method itself. Each of your tests would add two lines like...

```<code>var service = SubstituteFor<IService>();
var client = new Client(service);
</code>```

As shown in your example, I would imagine you are getting very little performance gain from running the two methods in parallel, so I would not use that last approach unless I saw a specific performance reason to do so.

As a final note... If you use make your fixtures run in parallel by default (either with an assembly-level attribute or with attributes on each fixture) and place no Parallelizable attribute on your test cases, NUnit uses an optimization, whereby all the tests within the fixture run on the same thread. This saving in context changes will often make up for the loss of any performance improvement you hoped to get through running in parallel.

Body:
I am having an issue with tests sporadically failing when using nunit 3 and using parallel test running.

We have a number of tests that currently are structured as follows

[TestFixture]
public class CalculateShipFromStoreShippingCost
{
    private IService_service;
    private IClient _client;

    [SetUp]
    public void SetUp()
    {
        _service = Substitute.For<IService>();
        _client = new Client(_service);
    }

    [Test]
    public async Task WhenScenario1()
    {
        _service.Apply(Args.Any<int>).Returns(1);
        var result = _client.DoTheThing();
        Assert.IsTrue(1,result);
    }

    [Test]
    public async Task WhenScenario2()
    {
        _service.Apply(Args.Any<int>).Returns(2);
        var result = _client.DoTheThing();
        Assert.IsTrue(2,result);
    }
}

Sometimes the test fail as one of the substitutes is returning the value for the other test.

How should this test be structured so that with Nunit it will run reliably when done in parallel

Body:
You haven't shown any Parallelizable attributes in your example, so I assume you are using the attribute at a higher level, most likely on the assembly. Otherwise, no parallel execution would occur. Further, since you say the test cases are running in parallel, you have apparently specified ParallelScope.Children.

The two test cases shown in your fixture cannot run in parallel. You should bear in mind that the SetUp method runs for each of the tests. So each of your two tests sets the value of _service, which is part of the state of the single instance of CalculateShipFromStoreShippingCost, which is shared by both tests. That is why you are seeing the "wrong" substitute being returned at times.

It is not possible for two test cases to run reliably in parallel if they both change the state of the fixture. Note that it does not matter whether the assignment to _service takes place in the test method itself or in the SetUp method - both are executed as part of the test case. So, you have to either stop running these two cases in parallel or stop changing the state.

To stop running the tests in parallel, you simply add [NonParallelizable] to each test method. If you are not using the latest framework version, use [Parallelizable(ParallelScope.None)] instead. Your other tests will continue to run in parallel, but these two will not.

Alternatively, use ParallelScope.Fixture at the assembly level. This will cause fixtures to run in parallel by default, while the individual test cases within them each run sequentially. When using ParallelizableAttribute at the assembly level, it is sometimes best to take a more conservative approach, adding in more parallelism within some fixtures where it is useful.

An entirely different approach is to make your tests stateless. Eliminate the _service member and use a local value within the test method itself. Each of your tests would add two lines like...

var service = SubstituteFor<IService>();
var client = new Client(service);

As shown in your example, I would imagine you are getting very little performance gain from running the two methods in parallel, so I would not use that last approach unless I saw a specific performance reason to do so.

As a final note... If you use make your fixtures run in parallel by default (either with an assembly-level attribute or with attributes on each fixture) and place no Parallelizable attribute on your test cases, NUnit uses an optimization, whereby all the tests within the fixture run on the same thread. This saving in context changes will often make up for the loss of any performance improvement you hoped to get through running in parallel.


问:
I want to remove double quotes from JSON.stringify object for pass it to amchart
I want to remove double quotes from JSON.stringify object for pass it to amchart

```<code> var data = JSON.stringify(ChartData);
</code>```

this line gives me the result given below..

```<code>"[{"USD":"Prod 1","FY 2016":2256},{"USD":"Prod 2","FY 2016":510},{"USD":"Prod 3","FY 2016":503}]"
</code>```

I want to remove begin and last double quotes from the result so that i can pass it to dataprovider of amchart.

Please go through the screenshot.

答:
in javascript you can use:</p>

```<code>dati=dati.split('"').join('');
</code>```

Body:
I want to remove double quotes from JSON.stringify object for pass it to amchart

 var data = JSON.stringify(ChartData);

this line gives me the result given below..

"[{"USD":"Prod 1","FY 2016":2256},{"USD":"Prod 2","FY 2016":510},{"USD":"Prod 3","FY 2016":503}]"

I want to remove begin and last double quotes from the result so that i can pass it to dataprovider of amchart.

Please go through the screenshot.

Body:
in javascript you can use:

dati=dati.split('"').join('');


问:
PDO if condition on row
I am in the process of making a login system using PDO. What I am finding is that users are able to log in despite their info not being in the database.

My PHP code is as follows:

```<code> $error = "";
if(isset($_POST["submit"])){

    if(empty($_POST["youremaildesktop"]) || empty($_POST["yourpassworddesktop"]))
        {$error = "Both fields are required.";}

    else{

        $username=$_POST['youremaildesktop'];
        $password=$_POST['yourpassworddesktop'];

        $username = stripslashes($username);
        $password = stripslashes($password);
        $password = md5($password);

        /*PDO Version*/
        $resulter = $dbh->prepare("
            SELECT uid
            FROM customer
            WHERE username = '$username'
            AND password = '$password'
        ");

 $resulter->fetchColumn();

if($resulter)
{
    $_SESSION['localstorage'] = $username;
    header("Location: userpage.php");
}
else {
$error = "Incorrect username or password.";
}

    }
 }
</code>```

The $dbh PHP variable corresponds to my database connection credentials. The POST values correspond to my login form on my main page.

The goal is to connect users to userpage.php only if their credentials are correct. However, I am able to log in regardless of whether the user details correspond to users in my database.

答:
I was able to fix this query by modifying my code to add the following:

```<code>$resulter->execute();
$resulted = $resulter->fetchAll();

    if($resulted)
    {
        $_SESSION['localstorage'] = $username;
        header('Location:vm913.php');

    }
    else { $error = "Incorrect username or password."; }
</code>```

Thanks to @Options as well for pointing out vulnerabilities in the code. I half posted this question also to see what people thought of it in terms of safety.

Title: PDO if condition on row

Body:
I am in the process of making a login system using PDO. What I am finding is that users are able to log in despite their info not being in the database.

My PHP code is as follows:

 $error = "";
if(isset($_POST["submit"])){

    if(empty($_POST["youremaildesktop"]) || empty($_POST["yourpassworddesktop"]))
        {$error = "Both fields are required.";}

    else{

        $username=$_POST['youremaildesktop'];
        $password=$_POST['yourpassworddesktop'];

        $username = stripslashes($username);
        $password = stripslashes($password);
        $password = md5($password);

        /*PDO Version*/
        $resulter = $dbh->prepare("
            SELECT uid
            FROM customer
            WHERE username = '$username'
            AND password = '$password'
        ");

 $resulter->fetchColumn();

if($resulter)
{
    $_SESSION['localstorage'] = $username;
    header("Location: userpage.php");
}
else {
$error = "Incorrect username or password.";
}

    }
 }

The $dbh PHP variable corresponds to my database connection credentials. The POST values correspond to my login form on my main page.

The goal is to connect users to userpage.php only if their credentials are correct. However, I am able to log in regardless of whether the user details correspond to users in my database.

Body:
I was able to fix this query by modifying my code to add the following:

$resulter->execute();
$resulted = $resulter->fetchAll();

    if($resulted)
    {
        $_SESSION['localstorage'] = $username;
        header('Location:vm913.php');

    }
    else { $error = "Incorrect username or password."; }

Thanks to @Options as well for pointing out vulnerabilities in the code. I half posted this question also to see what people thought of it in terms of safety.


问:
Getting date value null in ajax request
I am using Ajax request to send the value of date to my API Controller here is my ajax call

```<code> $("#txtpdate").on("changeDate", function (e) {
        var Date =$('#txtpdate').val();
        console.log(Date);
        $.ajax({
            type: 'POST',
            contentType: false,
            url: '/api/ServiceProvider/GetUpdatedPrice',
            data:{date: Date  },
            cache: false
        }).done(function (response) {

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

And here is my api controller

```<code>[HttpPost]
[Route("GetUpdatedPrice")]
public  ServiceProviderDocuments GetUpdatedPrice(DateTime date)
{
    return  ServiceProviderDocumentsGateway.GetUpdatedPriceofBike(date);
}
</code>```

I am getting the desired value in console.log(Date) but when I reached to the controller it is showing null value
please take a look on the below image

答:
You should declare the date parameter as DateTime, like:</p>

```<code>[HttpPost]
[Route("GetUpdatedPrice/{pDate:datetime}")]
public  ServiceProviderDocuments GetUpdatedPrice(DateTime pDate)
{
    return ServiceProviderDocumentsGateway.GetUpdatedPriceofBike(pDate);

}
</code>```

Title: Getting date value null in ajax request

Body:
I am using Ajax request to send the value of date to my API Controller here is my ajax call

 $("#txtpdate").on("changeDate", function (e) {
        var Date =$('#txtpdate').val();
        console.log(Date);
        $.ajax({
            type: 'POST',
            contentType: false,
            url: '/api/ServiceProvider/GetUpdatedPrice',
            data:{date: Date  },
            cache: false
        }).done(function (response) {

        });
});

And here is my api controller

[HttpPost]
[Route("GetUpdatedPrice")]
public  ServiceProviderDocuments GetUpdatedPrice(DateTime date)
{
    return  ServiceProviderDocumentsGateway.GetUpdatedPriceofBike(date);
}

I am getting the desired value in console.log(Date) but when I reached to the controller it is showing null value
please take a look on the below image

Body:
You should declare the date parameter as DateTime, like:

[HttpPost]
[Route("GetUpdatedPrice/{pDate:datetime}")]
public  ServiceProviderDocuments GetUpdatedPrice(DateTime pDate)
{
    return ServiceProviderDocumentsGateway.GetUpdatedPriceofBike(pDate);

}


问:
Install VS 2008 Team Developer on Windows 7
Has anyone successfully installed VS 2008 Team Developer edition on the Windows 7 beta yet?  Every time I try, i get an error about insufficient privileges in C:\Windows\Winsxs.

I was able to install the VS 2008 Team Database edition with no problems, and had thought that maybe installing the Dev edition after the DB edition might take care of the winsxs issue, but still no luck.

VS Error Message Image http://img152.imageshack.us/img152/7263/snipimagewd8.jpg

Edit: My install is on the 32 bit version of windows.  Looks like the 64 bit version works - has anyone tried it on 32 bit windows 7?

Edit: I tried turning off UAC, no luck.  Then, tried to install just the "team developer tools" portion (since I already had team DB installed) - and got the same error, only this time it includes an "ignore" button.  Clicked ignore, only to get another error with no ignore, this time for C:\Windows\Winsxs\Policies folder.  Only option at that point is to cancel out of the install.

答:
Yes, I've successfully installed it ( Win7 64bit + Dev edition + SP1 + Team Explorer) and not encountered any issues so far.

I might try installing the smallest possible set of features and see if that works.  If it did I would then add features back in 1 by 1.

OwnerDisplayName: Scott

LastEditorDisplayName: Scott

OwnerDisplayName: it depends