问:
How to check if IP is in one of these subnets
I have ~12600 subnets:

eg. 123.123.208.0/20

and an IP.

I can use a SQLite Database or an array or whatever

There was a similar question asked about a month ago, however I am not looking for checking one IP against one subnet but a bunch of subnets (obviously the most efficient way, hopefully not O(total subnets)) :)

How can I check that the IP is one of in one of these subnets, I need true or false not the subnet if that helps optimisation.

There are similar subnets in the current list eg.:
(actual extract)

```<code>123.123.48.0/22 <-- not a typo
123.123.48.0/24 <-- not a typo
123.123.90.0/24
123.123.91.0/24
123.123.217.0/24
</code>```

In total they range from 4.x.y.z to 222.x.y.z

答:
Keywords: Binary searching, preprocessing, sorting

I had a similar problem and binary search appears to be very efficient if you can pre-process your subnet list and sort it. Then you can achieve an asymptotic time complexity of O(log n).

Here's my code (MIT License, original location: https://github.com/iBug/pac/blob/854289a674578d096f60241804f5893a3fa17523/code.js):

function belongsToSubnet(host, list) {
  var ip = host.split(".").map(Number);
  ip = 0x1000000 * ip[0] + 0x10000 * ip[1] + 0x100 * ip[2] + ip[3];

  if (ip < list[0][0])
    return false;

  // Binary search
  var x = 0, y = list.length, middle;
  while (y - x > 1) {
    middle = Math.floor((x + y) / 2);
    if (list[middle][0] < ip)
      x = middle;
    else
      y = middle;
  }

  // Match
  var masked = ip & list[x][1];
  return (masked ^ list[x][0]) == 0;
}
```

<p>And an example usage:</p>

<pre class="lang-js prettyprint-override"><code>function isLan(host) {
  return belongsToSubnet(host, LAN);
}

var LAN = [
  [0x0A000000, 0xFF000000], // 10.0.0.0/8
  [0x64400000, 0xFFC00000], // 100.64.0.0/10
  [0x7F000000, 0xFF000000], // 127.0.0.0/8
  [0xA9FE0000, 0xFFFF0000], // 169.254.0.0/16
  [0xAC100000, 0xFFF00000], // 172.16.0.0/12
  [0xC0A80000, 0xFFFF0000]  // 192.168.0.0/16
];
</code>```

isLan("127.12.34.56"); // => true
isLan("8.8.8.8"); // => false (Google's Public DNS)
```

You can get a PAC script* and see how it performs (it loads a China IP list from somewhere else, sorts them and formats them appropriately) against 5000s of subnets. In practice its speed is surprisingly satisfactory.

The preprocessing code can be inspected using F12 Dev Tools on the above page. In short, you need to convert 1.2.3.4/16 to [0x01020304, 0xFFFF0000], i.e. 32-bit unsigned integer for the IP address and network mask.

* Link goes to my personal website.

OwnerDisplayName: Steve

Body:
I have ~12600 subnets:

eg. 123.123.208.0/20

and an IP.

I can use a SQLite Database or an array or whatever

There was a similar question asked about a month ago, however I am not looking for checking one IP against one subnet but a bunch of subnets (obviously the most efficient way, hopefully not O(total subnets)) :)

How can I check that the IP is one of in one of these subnets, I need true or false not the subnet if that helps optimisation.

There are similar subnets in the current list eg.:
(actual extract)

123.123.48.0/22 <-- not a typo
123.123.48.0/24 <-- not a typo
123.123.90.0/24
123.123.91.0/24
123.123.217.0/24

In total they range from 4.x.y.z to 222.x.y.z

LastEditorDisplayName: Steve

Body:
Keywords: Binary searching, preprocessing, sorting

I had a similar problem and binary search appears to be very efficient if you can pre-process your subnet list and sort it. Then you can achieve an asymptotic time complexity of O(log n).

Here's my code (MIT License, original location: https://github.com/iBug/pac/blob/854289a674578d096f60241804f5893a3fa17523/code.js):

function belongsToSubnet(host, list) {
  var ip = host.split(".").map(Number);
  ip = 0x1000000 * ip[0] + 0x10000 * ip[1] + 0x100 * ip[2] + ip[3];

  if (ip < list[0][0])
    return false;

  // Binary search
  var x = 0, y = list.length, middle;
  while (y - x > 1) {
    middle = Math.floor((x + y) / 2);
    if (list[middle][0] < ip)
      x = middle;
    else
      y = middle;
  }

  // Match
  var masked = ip & list[x][1];
  return (masked ^ list[x][0]) == 0;
}

And an example usage:

function isLan(host) {
  return belongsToSubnet(host, LAN);
}

var LAN = [
  [0x0A000000, 0xFF000000], // 10.0.0.0/8
  [0x64400000, 0xFFC00000], // 100.64.0.0/10
  [0x7F000000, 0xFF000000], // 127.0.0.0/8
  [0xA9FE0000, 0xFFFF0000], // 169.254.0.0/16
  [0xAC100000, 0xFFF00000], // 172.16.0.0/12
  [0xC0A80000, 0xFFFF0000]  // 192.168.0.0/16
];

isLan("127.12.34.56"); // => true
isLan("8.8.8.8"); // => false (Google's Public DNS)

You can get a PAC script* and see how it performs (it loads a China IP list from somewhere else, sorts them and formats them appropriately) against 5000s of subnets. In practice its speed is surprisingly satisfactory.

The preprocessing code can be inspected using F12 Dev Tools on the above page. In short, you need to convert 1.2.3.4/16 to [0x01020304, 0xFFFF0000], i.e. 32-bit unsigned integer for the IP address and network mask.

* Link goes to my personal website.


来源: stackexchange

问:
create ActiveRecord model at runtime rails3
I want to create an ActiveRecord model at run time.

In my system I'm generating some reports and all of them bind with a database table/ views. So the only difference will be the table name.

So what I want to do is have an active record common class (preferably generated at runtime) and assign the table name at runtime. and i should be able to assign a a scope to select a date range. And I'm thinking of getting the column names at runtime to display data.

can anyone help me out on how to
create ActiveRecord model at runtime

assign scope method

and I'm on rails3

thanks in advance

cheers

sameera

答:
Borrowing create_class from the article you linked, how about something like this:

```<code>TABLE_NAMES = %w[customers products purchases]

def create_class(class_name, superclass, &block)
  klass = Class.new superclass, &block
  Object.const_set class_name, klass
end

def create_model_class(table_name)
  create_class(table_name.classify, ActiveRecord::Base) do
    scope :in_date_range, lambda {|start_date, end_date| where("start_date >= ?", start_date).where("end_date <= ?", end_date) }
  end
end

TABLE_NAMES.each {|table_name| create_model_class(table_name) }
</code>```

If you wanted to use all tables in the database, you could do this:

```<code>TABLE_NAMES = ActiveRecord::Base.connection.tables
</code>```

But unless you're treating all tables identically, I'm guessing you wouldn't want to do that.

Once you've created your model classes, you should now be able to print objects from each table with their respective columns:

```<code>def print_attributes(model_obj)
  puts model_obj.attributes.map {|k,v| "#{k}=#{v.inspect}" }.join(', ')
end

Customer.in_date_range(Date.today, Date.today + 1.day).each {|c| print_attributes(c) }
Product.in_date_range(Date.yesterday, Date.today + 2.days).each {|c| print_attributes(c)
Purchase.in_date_range(Date.yesterday, Date.today + 3.days).each {|c| print_attributes(c) }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Borrowing create_class from the article you linked, how about something like this:

TABLE_NAMES = %w[customers products purchases]

def create_class(class_name, superclass, &block)
  klass = Class.new superclass, &block
  Object.const_set class_name, klass
end

def create_model_class(table_name)
  create_class(table_name.classify, ActiveRecord::Base) do
    scope :in_date_range, lambda {|start_date, end_date| where("start_date >= ?", start_date).where("end_date <= ?", end_date) }
  end
end

TABLE_NAMES.each {|table_name| create_model_class(table_name) }

If you wanted to use all tables in the database, you could do this:

TABLE_NAMES = ActiveRecord::Base.connection.tables

But unless you're treating all tables identically, I'm guessing you wouldn't want to do that.

Once you've created your model classes, you should now be able to print objects from each table with their respective columns:

def print_attributes(model_obj)
  puts model_obj.attributes.map {|k,v| "#{k}=#{v.inspect}" }.join(', ')
end

Customer.in_date_range(Date.today, Date.today + 1.day).each {|c| print_attributes(c) }
Product.in_date_range(Date.yesterday, Date.today + 2.days).each {|c| print_attributes(c)
Purchase.in_date_range(Date.yesterday, Date.today + 3.days).each {|c| print_attributes(c) }


问:
ASP.NET MVC: Mock controller.Url.Action
Urls for menus in my ASP.NET MVC apps are generated from controller/actions. So, they call

```<code>controller.Url.Action(action, controller)
</code>```

Now, how do I make this work in unit tests?
I use MVCContrib successfully with

```<code>var controller = new TestControllerBuilder().CreateController<OrdersController>();
</code>```

but whatever I try to do with it I get controller.Url.Action(action, controller) failing with NullReferenceException because Url == null.

Update: it's not about how to intercept HttpContext. I did this in several ways, using MVCContrib, Scott Hanselman's example of faking, and also the one from http://stephenwalther.com/blog/archive/2008/07/01/asp-net-mvc-tip-12-faking-the-controller-context.aspx. This doesn't help me because I need to know WHAT values to fake... is it ApplicationPath? How do I set it up? Does it need to match the called controller/action? That is, how do Url.Action works and how do I satisfy it?

Also, I know I can do IUrlActionAbstraction and go with it... but I'm not sure I want to do this. After all, I have MVCContrib/Mock full power and why do I need another abstraction.

答:
Here is another way to solve the problem with NSubstitute. Hope, it helps someone.</p>

```<code>// _accountController is the controller that we try to test
var urlHelper = Substitute.For<UrlHelper>();
urlHelper.Action(Arg.Any<string>(), Arg.Any<object>()).Returns("/test_Controller/test_action");

var context = Substitute.For<HttpContextBase>();
_accountController.Url = urlHelper;
_accountController.ControllerContext = new ControllerContext(context, new RouteData(), _accountController);
</code>```

ContentLicense: CC BY-SA 2.5

Title: ASP.NET MVC: Mock controller.Url.Action

Body:
Urls for menus in my ASP.NET MVC apps are generated from controller/actions. So, they call

controller.Url.Action(action, controller)

Now, how do I make this work in unit tests?
I use MVCContrib successfully with

var controller = new TestControllerBuilder().CreateController<OrdersController>();

but whatever I try to do with it I get controller.Url.Action(action, controller) failing with NullReferenceException because Url == null.

Update: it's not about how to intercept HttpContext. I did this in several ways, using MVCContrib, Scott Hanselman's example of faking, and also the one from http://stephenwalther.com/blog/archive/2008/07/01/asp-net-mvc-tip-12-faking-the-controller-context.aspx. This doesn't help me because I need to know WHAT values to fake... is it ApplicationPath? How do I set it up? Does it need to match the called controller/action? That is, how do Url.Action works and how do I satisfy it?

Also, I know I can do IUrlActionAbstraction and go with it... but I'm not sure I want to do this. After all, I have MVCContrib/Mock full power and why do I need another abstraction.

Body:
Here is another way to solve the problem with NSubstitute. Hope, it helps someone.

// _accountController is the controller that we try to test
var urlHelper = Substitute.For<UrlHelper>();
urlHelper.Action(Arg.Any<string>(), Arg.Any<object>()).Returns("/test_Controller/test_action");

var context = Substitute.For<HttpContextBase>();
_accountController.Url = urlHelper;
_accountController.ControllerContext = new ControllerContext(context, new RouteData(), _accountController);

ContentLicense: CC BY-SA 4.0


问:
jQuery .attribute for p tags in HTML
I want to add an attribute of 'data-class' to every paragraph in an HTML element, the 'data-class' should be set to the value of the class. I have used .attr but not able to assign the same value.
There are currently 9 paragraphs on the page with a numbered class of

p1, p2, p3 etc...

How would I just set the data-class to the same p-tag as well?

I have jQuery like this so far:

```<code>$('p').attr('data-class', 'p'}
</code>```

答:
Just try it</p>

```<code>var data_class = "value";

$("p").each(function(index) {
  $(this).attr("data-class", data_class);
});
</code>```

Title: jQuery .attribute for p tags in HTML

Body:
I want to add an attribute of 'data-class' to every paragraph in an HTML element, the 'data-class' should be set to the value of the class. I have used .attr but not able to assign the same value.
There are currently 9 paragraphs on the page with a numbered class of

p1, p2, p3 etc...

How would I just set the data-class to the same p-tag as well?

I have jQuery like this so far:

$('p').attr('data-class', 'p'}

Body:
Just try it

var data_class = "value";

$("p").each(function(index) {
  $(this).attr("data-class", data_class);
});


答:
```<code><!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>

<p>P1</p>
<p>P2</p>
<p>P3</p>
<script>
$(function(){
    // $('p').attr('data-class', 'p');
   //This will attach a new attribute o you dom element and that you can visible in  when in you inspect.
or
     $('p').data('class', 'p');
     // This may not visible in dom.
     console.log($('p').data('class'));
     // Dynamic creation
     $('<p />').data('class', 'p').appendTo('body');
     // Append with loop
     const data = ['p1', 'p2', 'p3'];
     $('p').each((index,element)=>{
           console.log(index,element)});
           $(element).data('class', data[index]);
     });
});
</script>
</body>
</html>
</code>```

Title: jQuery .attribute for p tags in HTML


问:
range along row or column of tensor in tensorflow
In tensorflow, how can I calculate the the range along rows or columns of a tensor?
Where range is max - min.

In Matlab this can be done with 'range'

```<code>a=[ 1 2 3; 4 5 6]
range(a) = [3 3 3] %this is the range along columns of a
range(a') = [2 2]  %range along rows of a
</code>```

答:
You can do the following,

Assuming (range = max - min)

```<code># Axis 0
res_1 = tf.reduce_max(a, axis=0) - tf.reduce_min(a, axis=0)
# Axis 1
res_2 = tf.reduce_max(a, axis=1) - tf.reduce_min(a, axis=1)
</code>```

Body:
In tensorflow, how can I calculate the the range along rows or columns of a tensor?
Where range is max - min.

In Matlab this can be done with 'range'

a=[ 1 2 3; 4 5 6]
range(a) = [3 3 3] %this is the range along columns of a
range(a') = [2 2]  %range along rows of a

Body:
You can do the following,

Assuming (range = max - min)

# Axis 0
res_1 = tf.reduce_max(a, axis=0) - tf.reduce_min(a, axis=0)
# Axis 1
res_2 = tf.reduce_max(a, axis=1) - tf.reduce_min(a, axis=1)


问:
Why use static_cast rather than dynamic_cast in here?
I copy the following text from the book More Effective C++.

Item 31:  Making functions virtual with respect to more than one object.

```<code>class GameObject { ... };
class SpaceShip: public GameObject { ... };
class SpaceStation: public GameObject { ... };
class Asteroid: public GameObject { ... };
</code>```

The most common approach to double-dispatching returns us to the unforgiving world of virtual function emulation via chains of if-then-elses. In this harsh world, we first discover the real type of otherObject, then we test it against all the possibilities:

```<code>void SpaceShip::collide(GameObject& otherObject)
{
  const type_info& objectType = typeid(otherObject);

  if (objectType == typeid(SpaceShip)) {
    SpaceShip& ss = static_cast<SpaceShip&>(otherObject);

    process a SpaceShip-SpaceShip collision;

  }
  else if (objectType == typeid(SpaceStation)) {
    SpaceStation& ss =
      static_cast<SpaceStation&>(otherObject);

    process a SpaceShip-SpaceStation collision;

  }
...
}
</code>```

Here is the question:

Q1> Why we use static_cast here rather than obvious dynamic_cast?

Q2>　Are they same in this case?

thank you

// updated //

In fact, I am more interested in question 2.

For example,

```<code>class base {};
class subclass : public base {};

base *pSubClass = new subclass;

subclass *pSubClass1 = static_cast<subClass*> (pSubClass);
</code>```

// does the static_cast do the job correctly in this case although I know we should use dynamic_cast here?

答:
For the record, here is the idiomatic way of doing that:

```<code>void SpaceShip::collide(GameObject& otherObject)
{
    if (SpaceShip* ss = dynamic_cast<SpaceShip*>(&otherObject)) {
        // process a SpaceShip-SpaceShip collision;
    }
    else if (SpaceStation* ss = dynamic_cast<SpaceStation*>(&otherObject)) {
        // process a SpaceShip-SpaceStation collision;
    }

    // ...
}
</code>```

It's shorter, exhibits identical performance characteristics, and again, most importantly, is idiomatic C++ that won't make other programmers scratch their heads and wonder what the point is.

EDIT (in response to the OP's edit):

Yes, that is well defined behavior. Here's what the C++03 standard says, §5.2.9/8:

An rvalue of type “pointer to cv1 B”, where B is a class type, can be converted to an rvalue of type “pointer to cv2 D”, where D is a class derived from B, if a valid standard conversion from “pointer to D” to “pointer to B” exists, cv2 is the same cv-qualification as, or greater cv-qualification than, cv1, and B is not a virtual base class of D. The null pointer value is converted to the null pointer value of the destination type. If the rvalue of type “pointer to cv1 B” points to a B that is actually a sub-object of an object of type D, the resulting pointer points to the enclosing object of type D. Otherwise, the result of the cast is undefined.

Body:
I copy the following text from the book More Effective C++.

Item 31:  Making functions virtual with respect to more than one object.

class GameObject { ... };
class SpaceShip: public GameObject { ... };
class SpaceStation: public GameObject { ... };
class Asteroid: public GameObject { ... };

The most common approach to double-dispatching returns us to the unforgiving world of virtual function emulation via chains of if-then-elses. In this harsh world, we first discover the real type of otherObject, then we test it against all the possibilities:

void SpaceShip::collide(GameObject& otherObject)
{
  const type_info& objectType = typeid(otherObject);

  if (objectType == typeid(SpaceShip)) {
    SpaceShip& ss = static_cast<SpaceShip&>(otherObject);

    process a SpaceShip-SpaceShip collision;

  }
  else if (objectType == typeid(SpaceStation)) {
    SpaceStation& ss =
      static_cast<SpaceStation&>(otherObject);

    process a SpaceShip-SpaceStation collision;

  }
...
}

Here is the question:

Q1> Why we use static_cast here rather than obvious dynamic_cast?

Q2>　Are they same in this case?

thank you

// updated //

In fact, I am more interested in question 2.

For example,

class base {};
class subclass : public base {};

base *pSubClass = new subclass;

subclass *pSubClass1 = static_cast<subClass*> (pSubClass);

// does the static_cast do the job correctly in this case although I know we should use dynamic_cast here?

Body:
For the record, here is the idiomatic way of doing that:

void SpaceShip::collide(GameObject& otherObject)
{
    if (SpaceShip* ss = dynamic_cast<SpaceShip*>(&otherObject)) {
        // process a SpaceShip-SpaceShip collision;
    }
    else if (SpaceStation* ss = dynamic_cast<SpaceStation*>(&otherObject)) {
        // process a SpaceShip-SpaceStation collision;
    }

    // ...
}

It's shorter, exhibits identical performance characteristics, and again, most importantly, is idiomatic C++ that won't make other programmers scratch their heads and wonder what the point is.

EDIT (in response to the OP's edit):

Yes, that is well defined behavior. Here's what the C++03 standard says, §5.2.9/8:

An rvalue of type “pointer to cv1 B”, where B is a class type, can be converted to an rvalue of type “pointer to cv2 D”, where D is a class derived from B, if a valid standard conversion from “pointer to D” to “pointer to B” exists, cv2 is the same cv-qualification as, or greater cv-qualification than, cv1, and B is not a virtual base class of D. The null pointer value is converted to the null pointer value of the destination type. If the rvalue of type “pointer to cv1 B” points to a B that is actually a sub-object of an object of type D, the resulting pointer points to the enclosing object of type D. Otherwise, the result of the cast is undefined.


问:
detecting lane lines on a binary mask
I have a binary mask of a road, the mask is a little irregular(sometimes even more than depicted in the image).

I have tried houghLine in OpenCV to detect boundary lines, but the boundary lines are not as expected. I tried erosion and dilation to smooth out things, but no luck. Also since the path is curved it becomes even difficult to detect boundary lines using houghLines. How can I modify the code to detect lines better?

```<code>    img2=cv2.erode(img2,None,iterations=2)
    img2=cv2.dilate(img2,None,iterations=2)
    can=cv2.Canny(img2,150,50)
    lines=cv2.HoughLinesP(can,1,np.pi/180,50,maxLineGap=50,minLineLength=10)
    if(lines is not None):
        for x in lines:
            #print(lines[0])
            #mask=np.zeros(frame2.shape,dtype=np.uint8)
            #roi=lines
            #cv2.fillPoly(mask,roi,(255,255,255))
            #cv2.imshow(mask)
            for x1,y1,x2,y2 in x:
                cv2.line(frame2,(x1,y1),(x2,y2),(255,0,0),2)
</code>```

答:
You say that Hough is failing but you don't say why. Why is your output "not as expected"? In my experience, Hough Line Detection’s critical points are two: 1) The edges mask you pass to it and 2) how you filter the resulting lines. You should be fine-tuning those two steps and Hough should be enough for your problem.

I don't know what kind of problems the line detector is giving you, but suppose you are interested (as your question suggests) in other methods for lane detection. There are at least two things you could try:  1) Bird's eye transform of the road – which makes line detection much easier since all your lines are now parallel lines. And 2) Contour detection (instead of lines).

Let's examine 2 and what kind of results you can obtain. Listen, man, I offer my answer in C++, but I make notes along with it. I try to highlight the important ideas, so you can implement them in your language of choice. However, if all you want is a CTRL+C and CTRL+V solution, that's ok, but this answer won't help you.

Ok, let's start by reading the image and converting it to binary. Our goal here is to first obtain the edges. Pretty standard stuff:

```<code>//Read input image:
std::string imagePath = "C://opencvImages//lanesMask.png";
cv::Mat testImage = cv::imread( imagePath );

//Convert BGR to Gray:
cv::Mat grayImage;
cv::cvtColor( testImage, grayImage, cv::COLOR_RGB2GRAY );

//Get binary image via Otsu:
cv::Mat binaryImage;
cv::threshold( grayImage, binaryImage, 0, 255, cv::THRESH_OTSU );
</code>```

Now, simply pass this image to Canny's Edge detector. The parameters are also pretty standard. As per Canny's documentation, the ratios between lower and upper thresholds are related by a factor of 3:

```<code>//Get Edges via Canny:
cv::Mat testEdges;

//Setup lower and upper thresholds for edge detection:
float lowerThreshold = 30;
float upperThreshold = 3 * lowerThreshold;

cv::Canny( binaryImage, testEdges, lowerThreshold, upperThreshold );
</code>```

Your mask is pretty good; these are the edges Canny finds:

Now, here's where we are trying something different. We won't use Hough's line detection, instead, let's find the contours of the mask. Each contour is made of points. What we are looking for is actually lines, straight lines that can be fitted to these points. There's more than a method for achieving that. I propose K-means, a clustering algorithm.

The idea is that the points, as you can see, can be clustered in 4 groups: The vanishing point of the lanes (those should be 2 endpoints there) and the 2 starting points of the road. If we give K-means the points of the contour and tell it to cluster the data in 4 separate groups, we should get the means (location) of those 4 points.

Let's try it out. The first step is to find the contours in the edges mask:

```<code>//Get contours:
std::vector< std::vector<cv::Point> > contours;
std::vector< cv::Vec4i > hierarchy;

cv::findContours( testEdges, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0) );
</code>```

K-means needs a specific data type on its input. I'll use a cv::Point2f vector to store all the contour points. Let's set up the variables used by K-means:

```<code>//Set up the data containers used by K-means:
cv::Mat centers; cv::Mat labels;
std::vector<cv::Point2f> points; //the data for clustering is stored here
</code>```

Next, let's loop through the contours and store each point inside the Point2f vector, so we can further pass it to K-means. Let’s use the loop to also draw the contours and make sure we are not messing things up:

```<code>//Loop thru the found contours:
for( int i = 0; i < (int)contours.size(); i++ ){

  //Set a color & draw contours:
  cv::Scalar color = cv::Scalar( 0, 256, 0 );
  cv::drawContours( testImage, contours, i, color, 2, 8, hierarchy, 0, cv::Point() );

  //This is the current vector of points that is being processed:
  std::vector<cv::Point> currentVecPoint = contours[i];

    //Loop thru it and store each point as a float point inside a plain vector:
    for(int k = 0; k < (int)currentVecPoint.size(); k++){

       cv::Point currentPoint = currentVecPoint[k];
       //Push (store) the point into the vector:
       points.push_back( currentPoint );
    }
}
</code>```

These are the contours found:

There, now, I have the contour points in my vector. Let's pass the info on to K-means:

```<code>//Setup K-means:
int clusterCount = 4; //Number of clusters to split the set by
int attempts = 5; //Number of times the algorithm is executed using different initial labels

int flags = cv::KMEANS_PP_CENTERS;
cv::TermCriteria criteria = cv::TermCriteria( CV_TERMCRIT_ITER | CV_TERMCRIT_EPS, 10, 0.01 );

//The call to kmeans:
cv::kmeans( points, clusterCount, labels, criteria, attempts, flags, centers );
</code>```

And that's all. The result of K-means is in the centers matrix. Each row of the matrix should have 2 columns, denoting a point center. In this case, the matrix is of size 4 x 2.  Let's draw that info:

As expected, 4 center points, each is the mean of a cluster. Very cool, now, is this approximation enough for your application? Only you know that! You could work with those points and extend both lines, but that's a possible improvement of this result.

Title: detecting lane lines on a binary mask

Body:
I have a binary mask of a road, the mask is a little irregular(sometimes even more than depicted in the image).

I have tried houghLine in OpenCV to detect boundary lines, but the boundary lines are not as expected. I tried erosion and dilation to smooth out things, but no luck. Also since the path is curved it becomes even difficult to detect boundary lines using houghLines. How can I modify the code to detect lines better?

    img2=cv2.erode(img2,None,iterations=2)
    img2=cv2.dilate(img2,None,iterations=2)
    can=cv2.Canny(img2,150,50)
    lines=cv2.HoughLinesP(can,1,np.pi/180,50,maxLineGap=50,minLineLength=10)
    if(lines is not None):
        for x in lines:
            #print(lines[0])
            #mask=np.zeros(frame2.shape,dtype=np.uint8)
            #roi=lines
            #cv2.fillPoly(mask,roi,(255,255,255))
            #cv2.imshow(mask)
            for x1,y1,x2,y2 in x:
                cv2.line(frame2,(x1,y1),(x2,y2),(255,0,0),2)

Body:
You say that Hough is failing but you don't say why. Why is your output "not as expected"? In my experience, Hough Line Detection’s critical points are two: 1) The edges mask you pass to it and 2) how you filter the resulting lines. You should be fine-tuning those two steps and Hough should be enough for your problem.

I don't know what kind of problems the line detector is giving you, but suppose you are interested (as your question suggests) in other methods for lane detection. There are at least two things you could try:  1) Bird's eye transform of the road – which makes line detection much easier since all your lines are now parallel lines. And 2) Contour detection (instead of lines).

Let's examine 2 and what kind of results you can obtain. Listen, man, I offer my answer in C++, but I make notes along with it. I try to highlight the important ideas, so you can implement them in your language of choice. However, if all you want is a CTRL+C and CTRL+V solution, that's ok, but this answer won't help you.

Ok, let's start by reading the image and converting it to binary. Our goal here is to first obtain the edges. Pretty standard stuff:

//Read input image:
std::string imagePath = "C://opencvImages//lanesMask.png";
cv::Mat testImage = cv::imread( imagePath );

//Convert BGR to Gray:
cv::Mat grayImage;
cv::cvtColor( testImage, grayImage, cv::COLOR_RGB2GRAY );

//Get binary image via Otsu:
cv::Mat binaryImage;
cv::threshold( grayImage, binaryImage, 0, 255, cv::THRESH_OTSU );

Now, simply pass this image to Canny's Edge detector. The parameters are also pretty standard. As per Canny's documentation, the ratios between lower and upper thresholds are related by a factor of 3:

//Get Edges via Canny:
cv::Mat testEdges;

//Setup lower and upper thresholds for edge detection:
float lowerThreshold = 30;
float upperThreshold = 3 * lowerThreshold;

cv::Canny( binaryImage, testEdges, lowerThreshold, upperThreshold );

Your mask is pretty good; these are the edges Canny finds:

Now, here's where we are trying something different. We won't use Hough's line detection, instead, let's find the contours of the mask. Each contour is made of points. What we are looking for is actually lines, straight lines that can be fitted to these points. There's more than a method for achieving that. I propose K-means, a clustering algorithm.

The idea is that the points, as you can see, can be clustered in 4 groups: The vanishing point of the lanes (those should be 2 endpoints there) and the 2 starting points of the road. If we give K-means the points of the contour and tell it to cluster the data in 4 separate groups, we should get the means (location) of those 4 points.

Let's try it out. The first step is to find the contours in the edges mask:

//Get contours:
std::vector< std::vector<cv::Point> > contours;
std::vector< cv::Vec4i > hierarchy;

cv::findContours( testEdges, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0) );

K-means needs a specific data type on its input. I'll use a cv::Point2f vector to store all the contour points. Let's set up the variables used by K-means:

//Set up the data containers used by K-means:
cv::Mat centers; cv::Mat labels;
std::vector<cv::Point2f> points; //the data for clustering is stored here

Next, let's loop through the contours and store each point inside the Point2f vector, so we can further pass it to K-means. Let’s use the loop to also draw the contours and make sure we are not messing things up:

//Loop thru the found contours:
for( int i = 0; i < (int)contours.size(); i++ ){

  //Set a color & draw contours:
  cv::Scalar color = cv::Scalar( 0, 256, 0 );
  cv::drawContours( testImage, contours, i, color, 2, 8, hierarchy, 0, cv::Point() );

  //This is the current vector of points that is being processed:
  std::vector<cv::Point> currentVecPoint = contours[i];

    //Loop thru it and store each point as a float point inside a plain vector:
    for(int k = 0; k < (int)currentVecPoint.size(); k++){

       cv::Point currentPoint = currentVecPoint[k];
       //Push (store) the point into the vector:
       points.push_back( currentPoint );
    }
}

These are the contours found:

There, now, I have the contour points in my vector. Let's pass the info on to K-means:

//Setup K-means:
int clusterCount = 4; //Number of clusters to split the set by
int attempts = 5; //Number of times the algorithm is executed using different initial labels

int flags = cv::KMEANS_PP_CENTERS;
cv::TermCriteria criteria = cv::TermCriteria( CV_TERMCRIT_ITER | CV_TERMCRIT_EPS, 10, 0.01 );

//The call to kmeans:
cv::kmeans( points, clusterCount, labels, criteria, attempts, flags, centers );

And that's all. The result of K-means is in the centers matrix. Each row of the matrix should have 2 columns, denoting a point center. In this case, the matrix is of size 4 x 2.  Let's draw that info:

As expected, 4 center points, each is the mean of a cluster. Very cool, now, is this approximation enough for your application? Only you know that! You could work with those points and extend both lines, but that's a possible improvement of this result.


问:
python MVC, how to make the function run automatically without pressing the button?
this is simplified version of a program that I am writing, and as it is, works.
I use the last button to test to see my fiction works, and it does.

I need to make the

```<code>self.controller.show_orders
</code>```

function run by itself every few seconds, instead of pressing the button every few seconds.

I tried to take out the codes that made the button, and only have the function, but it does not run.

I also tried

```<code>        self.show_orders_on_grid()
    def show_orders_on_grid(self):
        self.controller.show_orders
</code>```

and it does not work either.

my last effort was to put the mainloop after the function, and that works, which I understand why.

```<code>        for i in range(len(self.model.row_list)):
            self.view.listbox_list[i].delete(0, "end",)
            for element in self.model.row_list[i]:
                self.view.listbox_list[i].insert("end", element)

        self.root.mainloop()
if __name__ == "__main__":
    c = Controller()
</code>```

would you please help me how i can make the function run myself?  thank you in advance.

```<code>from datetime import datetime
import time
import os
import tkinter as tk
import sqlite3
from apscheduler.schedulers.background import BackgroundScheduler
import socket
import json
import tkinter as tk

class Model():
    def __init__(self):

        self.row_list = []
        self.path = '/Users/paul/Documents/python/GUI/gui class/ordering
                     app/4th.db'

        self.get_data_from_sql()
    def get_data_from_sql(self):
        self.conn = sqlite3.connect(self.path)
        self.cursor = self.conn.cursor()
        self.cursor.execute('SELECT * FROM main')
        self.data = self.cursor.fetchall()
        for row in self.data:
            self.row_list.append(row)
        self.conn.commit()

class View(tk.Frame):
    def  __init__(self, parent, controller):
        super().__init__(parent, bd =2, relief = tk.RIDGE)
        self.parent = parent
        self.controller = controller
        self.pack(fill=tk.BOTH, expand=1)

        self.frame_list = []
        self.listbox_list = []
        self.button_list = []

        for r in range(2):
            self.rowconfigure(r, weight=1)
            for c in range(4):
                self.columnconfigure(c, weight=1)
                self.frame=Small_Frame(self)
                self.frame.grid(row = r, column = c, padx=1, pady = 1,  sticky=
                               (tk.N, tk.S, tk.W, tk.E))
                self.frame_list.append(self.frame)

        self.button_list[7].configure(command = self.controller.show_orders)

class Small_Frame(tk.Frame):
    def __init__(self, parent):
        super().__init__(parent, borderwidth=1, relief="groove")
        self.parent = parent
        self.pack()

        self.box = tk.Listbox(self, borderwidth=0)
        self.box.pack()
        self.parent.listbox_list.append(self.box)

        self.button = tk.Button(self, text = "get")
        self.button.pack()
        self.parent.button_list.append(self.button)

class Controller():
    def __init__(self):
        self.root = tk.Tk()
        self.model = Model()
        self.view = View(self.root, self)
        self.root.title("notbook my own try")
        self.root.geometry("1200x650")
        self.root.config(bg="LightBlue4")
        self.root.mainloop()

    def show_orders(self):
        for i in range(len(self.model.row_list)):
            self.view.listbox_list[i].delete(0, "end",)
            for element in self.model.row_list[i]:
                self.view.listbox_list[i].insert("end", element)

if __name__ == "__main__":
    c = Controller()
</code>```

答:
You can use after() to execute show_orders() repeatedly:

```<code>class Controller:
    def __init__(self):
        ...
        self.show_orders()
        self.root.mainloop()

    def show_orders(self):
        ...
        # call show_orders every 5 seconds
        self.root.after(5000, self.show_orders)
</code>```

Body:
this is simplified version of a program that I am writing, and as it is, works.
I use the last button to test to see my fiction works, and it does.

I need to make the

self.controller.show_orders

function run by itself every few seconds, instead of pressing the button every few seconds.

I tried to take out the codes that made the button, and only have the function, but it does not run.

I also tried

        self.show_orders_on_grid()
    def show_orders_on_grid(self):
        self.controller.show_orders

and it does not work either.

my last effort was to put the mainloop after the function, and that works, which I understand why.

        for i in range(len(self.model.row_list)):
            self.view.listbox_list[i].delete(0, "end",)
            for element in self.model.row_list[i]:
                self.view.listbox_list[i].insert("end", element)

        self.root.mainloop()
if __name__ == "__main__":
    c = Controller()

would you please help me how i can make the function run myself?  thank you in advance.

from datetime import datetime
import time
import os
import tkinter as tk
import sqlite3
from apscheduler.schedulers.background import BackgroundScheduler
import socket
import json
import tkinter as tk

class Model():
    def __init__(self):

        self.row_list = []
        self.path = '/Users/paul/Documents/python/GUI/gui class/ordering
                     app/4th.db'

        self.get_data_from_sql()
    def get_data_from_sql(self):
        self.conn = sqlite3.connect(self.path)
        self.cursor = self.conn.cursor()
        self.cursor.execute('SELECT * FROM main')
        self.data = self.cursor.fetchall()
        for row in self.data:
            self.row_list.append(row)
        self.conn.commit()

class View(tk.Frame):
    def  __init__(self, parent, controller):
        super().__init__(parent, bd =2, relief = tk.RIDGE)
        self.parent = parent
        self.controller = controller
        self.pack(fill=tk.BOTH, expand=1)

        self.frame_list = []
        self.listbox_list = []
        self.button_list = []

        for r in range(2):
            self.rowconfigure(r, weight=1)
            for c in range(4):
                self.columnconfigure(c, weight=1)
                self.frame=Small_Frame(self)
                self.frame.grid(row = r, column = c, padx=1, pady = 1,  sticky=
                               (tk.N, tk.S, tk.W, tk.E))
                self.frame_list.append(self.frame)

        self.button_list[7].configure(command = self.controller.show_orders)

class Small_Frame(tk.Frame):
    def __init__(self, parent):
        super().__init__(parent, borderwidth=1, relief="groove")
        self.parent = parent
        self.pack()

        self.box = tk.Listbox(self, borderwidth=0)
        self.box.pack()
        self.parent.listbox_list.append(self.box)

        self.button = tk.Button(self, text = "get")
        self.button.pack()
        self.parent.button_list.append(self.button)

class Controller():
    def __init__(self):
        self.root = tk.Tk()
        self.model = Model()
        self.view = View(self.root, self)
        self.root.title("notbook my own try")
        self.root.geometry("1200x650")
        self.root.config(bg="LightBlue4")
        self.root.mainloop()

    def show_orders(self):
        for i in range(len(self.model.row_list)):
            self.view.listbox_list[i].delete(0, "end",)
            for element in self.model.row_list[i]:
                self.view.listbox_list[i].insert("end", element)

if __name__ == "__main__":
    c = Controller()

Body:
You can use after() to execute show_orders() repeatedly:

class Controller:
    def __init__(self):
        ...
        self.show_orders()
        self.root.mainloop()

    def show_orders(self):
        ...
        # call show_orders every 5 seconds
        self.root.after(5000, self.show_orders)


问:
My code doesnt check if X and Y and Z is in the list, but goes through if only one is covered. What am I doing wrong?
I'm Making A Tic-Tac-Toe game, and I'm trying to make a function to check if a player has won or not.

This is my Function:

```<code>def win_check(playerpicks, player):
    #HORIZONTAL CHECK
    if 1 and 2 and 3 in playerpicks or 4 and 5 and 6 in playerpicks or 7 and 8 and 9 in playerpicks:
        print("Player " + str(player) + " Wins!")

   #Vertical Check
    elif 1 and 4 and 7 in playerpicks or 2 and 5 and 8 in playerpicks or 3 and 6 and 9 in playerpicks:
        print("Player " + str(player) +" Wins!")

    #Diagonal Check
    elif 1 and 5 and 9 in playerpicks or 3 and 5 and 7 in playerpicks:
        print("Player " + str(player) +" Wins!")
</code>```

The board is going to be can be referenced by the num pad.

Here is the flow of my game where the win check is used:

```<code>def flow():

    global turn

    if turn == 1:
        position1 = input("P{} choose your position (1-9)".format(turn))

        if 9 >= int(position1) >= 1:
            if int(position1) in p1_list or int(position1) in p2_list:
                print("Spot Taken")
            else:
                p1_list.append(int(position1))
                win_check(p1_list, 1)
                turn = 2
                print(p1_list)
        else:
            print("INVALID INPUT")

    elif turn == 2:
        position2 = input("P{} choose your position (1-9)".format(turn))

        if 9 >= int(position2) >= 1:
            if int(position2) in p2_list or int(position2) in p1_list:
                print("Spot Taken")
            else:
                p2_list.append(int(position2))
                win_check(p2_list, 2)
                turn = 1
                print(p2_list)
        else:
            print("INVALID INPUT")
</code>```

I know that I'm probably over complicating my code, and that's why its not working correctly. But it's been a couple months since I've written a line of code, and I'm trying to refresh my brain.

Here is the Output I'm getting:

```<code>Player 1 or player 2? (Enter 1 or 2)1
You are Player 1
P1 choose your position (1-9)2
[2]
P2 choose your position (1-9)3
Player 2 Wins!
[3]
P1 choose your position (1-9)
</code>```

Easiest game ever right? I'm confused because and isn't doing what I thought it was meant for. Any help?

答:
You need to change your conditionals to be like the following:

if (1 in playerpicks and 2 in playerpicks and 3 in playerpicks) or \
   (4 in playerpicks and 5 in playerpicks and 6 in playerpicks) or \
   (7 in playerpicks and 8 in playerpicks and 9 in playerpicks):
    print("Player " + str(player) + " Wins!")
```

Body:
I'm Making A Tic-Tac-Toe game, and I'm trying to make a function to check if a player has won or not.

This is my Function:

def win_check(playerpicks, player):
    #HORIZONTAL CHECK
    if 1 and 2 and 3 in playerpicks or 4 and 5 and 6 in playerpicks or 7 and 8 and 9 in playerpicks:
        print("Player " + str(player) + " Wins!")

   #Vertical Check
    elif 1 and 4 and 7 in playerpicks or 2 and 5 and 8 in playerpicks or 3 and 6 and 9 in playerpicks:
        print("Player " + str(player) +" Wins!")

    #Diagonal Check
    elif 1 and 5 and 9 in playerpicks or 3 and 5 and 7 in playerpicks:
        print("Player " + str(player) +" Wins!")

The board is going to be can be referenced by the num pad.

Here is the flow of my game where the win check is used:

def flow():

    global turn

    if turn == 1:
        position1 = input("P{} choose your position (1-9)".format(turn))

        if 9 >= int(position1) >= 1:
            if int(position1) in p1_list or int(position1) in p2_list:
                print("Spot Taken")
            else:
                p1_list.append(int(position1))
                win_check(p1_list, 1)
                turn = 2
                print(p1_list)
        else:
            print("INVALID INPUT")

    elif turn == 2:
        position2 = input("P{} choose your position (1-9)".format(turn))

        if 9 >= int(position2) >= 1:
            if int(position2) in p2_list or int(position2) in p1_list:
                print("Spot Taken")
            else:
                p2_list.append(int(position2))
                win_check(p2_list, 2)
                turn = 1
                print(p2_list)
        else:
            print("INVALID INPUT")

I know that I'm probably over complicating my code, and that's why its not working correctly. But it's been a couple months since I've written a line of code, and I'm trying to refresh my brain.

Here is the Output I'm getting:

Player 1 or player 2? (Enter 1 or 2)1
You are Player 1
P1 choose your position (1-9)2
[2]
P2 choose your position (1-9)3
Player 2 Wins!
[3]
P1 choose your position (1-9)

Easiest game ever right? I'm confused because and isn't doing what I thought it was meant for. Any help?


问:
CORS error: Turning CSV file into Javascript array
I am trying convert a CSV file into a javascript array. In the CSV file, all of the values are on separate lines. Anyway, I found this piece of code in another post on Stackoverflow to turn such a file into an array:

```<code>var adressesList = []

  $(document).ready(function() {
    $.ajax({
      type: "GET",
      url: "Filepath",
      dataType: "text",
      success: function(data) {
        processData(data);
      }
    });
  });

  function processData(allText) {
    var allTextLines = allText.split(/\r\n|\n/);
    for (var i = 1; i < allTextLines.length; i++) {
      adressesList.push(allTextLines[i]);
    }
  }
</code>```

I have tried this but I keep getting an error saying that I am not allowed to access the file (it is local on my computer in the same folder as the code).

This is the error I see:

```<code>Access to XMLHttpRequest at 'filepat' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

GET filepath net::ERR_FAILED
</code>```

How could I solve it? I saw that you could put the file on a server. But, shouldn't there just be an easy way to do it locally?

Thank you.

答:
If the file is static (you write it once and it stays the same), then you can export it as a constant and won't need to use ajax. See more about how to do that here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export

If the file is dynamic and will change over time, you'll need to put it on a webserver you can request the file from, often called an "endpoint". If you're on a different domain (say the server is on foo.com and your website is on bar.com) you'll need to add permission on the server settings to allow requests from other domains.

Body:
I am trying convert a CSV file into a javascript array. In the CSV file, all of the values are on separate lines. Anyway, I found this piece of code in another post on Stackoverflow to turn such a file into an array:

var adressesList = []

  $(document).ready(function() {
    $.ajax({
      type: "GET",
      url: "Filepath",
      dataType: "text",
      success: function(data) {
        processData(data);
      }
    });
  });

  function processData(allText) {
    var allTextLines = allText.split(/\r\n|\n/);
    for (var i = 1; i < allTextLines.length; i++) {
      adressesList.push(allTextLines[i]);
    }
  }

I have tried this but I keep getting an error saying that I am not allowed to access the file (it is local on my computer in the same folder as the code).

This is the error I see:

Access to XMLHttpRequest at 'filepat' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

GET filepath net::ERR_FAILED

How could I solve it? I saw that you could put the file on a server. But, shouldn't there just be an easy way to do it locally?

Thank you.


问:
why same material can make different effect on a model
I wonder why one material can have different effect on the different part of one model .
For example , a material can make up the horror face of the zombie and also the limbs of it .

Please answer with full explaination ,your help would be greatly appreciated!

答:
The keyword should be shader effect, instead of material.
In general, you need to write a shader which support multiple textures.

Also, based on UV position, you can adjust different part of your 3D model. It could be color, texture, vertex.

If you are interested in this topic in Unity3D, you have to learn basic of writing a shader.


问:
CocoaPods requires your terminal to be using UTF-8 encoding
I am trying to run Flutter app on iOS Simulator. But it is returning me error:

```<code>Error output from CocoaPods:
↳
        [33mWARNING: CocoaPods requires your terminal to be using UTF-8 encoding.
        Consider adding the following to ~/.profile:

        export LANG=en_US.UTF-8
        [0m

Error running pod install
Error launching application on iPhone Xʀ.
</code>```

It is working perfectly with my Android emulator.

答:
You can try
1) flutter clean
2) flutter run</p>

Body:
I am trying to run Flutter app on iOS Simulator. But it is returning me error:

Error output from CocoaPods:
↳
        [33mWARNING: CocoaPods requires your terminal to be using UTF-8 encoding.
        Consider adding the following to ~/.profile:

        export LANG=en_US.UTF-8
        [0m

Error running pod install
Error launching application on iPhone Xʀ.

It is working perfectly with my Android emulator.


问:
How to pull conditional values from lists inside javascript objects
I have an object, with a list inside each key. What is the best way of returning the key, if the url string matches what's in the array.

For example in the code below, 'entertainment' would be returned as "/video" is in the entertainment array.

```<code>const url = "https://example.com/video";

const verticalList = {
    autos:[],
    entertainment:["/video", "/tech"],
    foodanddrink:[],
    healthandfitness:[],
    homepage:["/home"],
    lifestyle:["/ideas", "/executive-life"],
    money:["/money-markets",],
    news:["/briefing"],
    sports:[],
    travel:[],
    weather:[]
}
</code>```

答:
You can use Object.entries to get a list of key-value pairs from your object and then run Array.filter to compare values against your url. In the last step you have to run Array.map to retrieve corresponding keys. String.includes can be used to check if one string is a substring of another.

const url = "https://example.com/video";

const verticalList = {
    autos:[],
    entertainment:["/video", "/tech"],
    foodanddrink:[],
    healthandfitness:[],
    homepage:["/home"],
    lifestyle:["/ideas", "/executive-life"],
    money:["/money-markets",],
    news:["/briefing"],
    sports:[],
    travel:[],
    weather:[]
}

let matches = Object.entries(verticalList)
                    .filter(([key,value]) => value.some(x => url.includes(x)))
                    .map(([key,value]) => key);

console.log(matches)```

Body:
I have an object, with a list inside each key. What is the best way of returning the key, if the url string matches what's in the array.

For example in the code below, 'entertainment' would be returned as "/video" is in the entertainment array.

const url = "https://example.com/video";

const verticalList = {
    autos:[],
    entertainment:["/video", "/tech"],
    foodanddrink:[],
    healthandfitness:[],
    homepage:["/home"],
    lifestyle:["/ideas", "/executive-life"],
    money:["/money-markets",],
    news:["/briefing"],
    sports:[],
    travel:[],
    weather:[]
}


问:
Javascript - TypeError: Cannot find function startsWith in object
I'm trying to write a custom function in Google Sheets to format some phone numbers.

Each cell contains numbers like this:

434268713

800270963

300303544

741244611

And I want to write a formula that outputs them like this:

Anything that starts with 4: 434268713 -> 0434 268 713

Anything that starts with 8: 800270963 -> 1800 270 965

Anything that starts with 3: 300303544 -> 1300 303 544

Anything that starts with 7: 741244611 -> (07) 4124 4611

I have been writing this function, but Google Sheets gives me an error:

"TypeError: Cannot find function startsWith in object 800270963. (line 2)."

```<code>function D7PHONE(phone) {
  if (phone.startsWith(4)) {
    return "0" + str.substring(0, 2) + " " + str.substring(3, 5) + " " + str.substring(6, 8);
  } else if (phone.startsWith(8)) {
    return "1" + str.substring(0, 2) + " " + str.substring(3, 5) + " " + str.substring(6, 8);
  } else if (phone.startsWith(3)) {
    return "1" + str.substring(0, 2) + " " + str.substring(3, 5) + " " + str.substring(6, 8);
  } else if (phone.startsWith(7)) {
    return "(0" + str.substring(0, 1) + ") " + str.substring(3, 5) + " " + str.substring(6, 8);
  }
}
</code>```

答:
As @rb612 pointed out Sheets does not support startsWith() so I made a work around using regex.

```<code>function D7PHONE(phone) {
  phone = phone.toString();
  if (/^4/.test(phone)) {
    return "0" + phone.substring(0, 3) + " " + phone.substring(3, 6) + " " + phone.substring(6, 9);
  } else if (/^8/.test(phone)) {
    return "1" + phone.substring(0, 3) + " " + phone.substring(3, 6) + " " + phone.substring(6, 9);
  } else if (/^3/.test(phone)) {
    return "1" + phone.substring(0, 3) + " " + phone.substring(3, 6) + " " + phone.substring(6, 9);
  } else if (/^7/.test(phone)) {
    return "(0" + phone.substring(0, 1) + ") " + phone.substring(1, 5) + " " + phone.substring(5, 9);
  }
}
</code>```

Body:
I'm trying to write a custom function in Google Sheets to format some phone numbers.

Each cell contains numbers like this:

434268713

800270963

300303544

741244611

And I want to write a formula that outputs them like this:

Anything that starts with 4: 434268713 -> 0434 268 713

Anything that starts with 8: 800270963 -> 1800 270 965

Anything that starts with 3: 300303544 -> 1300 303 544

Anything that starts with 7: 741244611 -> (07) 4124 4611

I have been writing this function, but Google Sheets gives me an error:

"TypeError: Cannot find function startsWith in object 800270963. (line 2)."

function D7PHONE(phone) {
  if (phone.startsWith(4)) {
    return "0" + str.substring(0, 2) + " " + str.substring(3, 5) + " " + str.substring(6, 8);
  } else if (phone.startsWith(8)) {
    return "1" + str.substring(0, 2) + " " + str.substring(3, 5) + " " + str.substring(6, 8);
  } else if (phone.startsWith(3)) {
    return "1" + str.substring(0, 2) + " " + str.substring(3, 5) + " " + str.substring(6, 8);
  } else if (phone.startsWith(7)) {
    return "(0" + str.substring(0, 1) + ") " + str.substring(3, 5) + " " + str.substring(6, 8);
  }
}

Body:
As @rb612 pointed out Sheets does not support startsWith() so I made a work around using regex.

function D7PHONE(phone) {
  phone = phone.toString();
  if (/^4/.test(phone)) {
    return "0" + phone.substring(0, 3) + " " + phone.substring(3, 6) + " " + phone.substring(6, 9);
  } else if (/^8/.test(phone)) {
    return "1" + phone.substring(0, 3) + " " + phone.substring(3, 6) + " " + phone.substring(6, 9);
  } else if (/^3/.test(phone)) {
    return "1" + phone.substring(0, 3) + " " + phone.substring(3, 6) + " " + phone.substring(6, 9);
  } else if (/^7/.test(phone)) {
    return "(0" + phone.substring(0, 1) + ") " + phone.substring(1, 5) + " " + phone.substring(5, 9);
  }
}


问:
In flutter, how to add an outline button that look like a text field with underline?
In flutter, how to add an outline button that look like a text field with underline? I only need a bottom underline.</p>

```<code>           OutlineButton(
              color: Theme.of(context).buttonColor,
              textColor: Theme.of(context).textTheme.bodyText1.color,
              // disabledColor: Colors.grey,
              disabledTextColor: Colors.black,
              borderSide: (),
              onPressed: () {

              },
          child: Center(
            child: Text(
              "No Reminder",
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 18.0),
            ),
          ),
            )
</code>```

答:
```<code>GestureDetector(
  onTap: () => print('tapped'),
  child: Container(
    // optional
    padding: const EdgeInsets.only(bottom: 1.0),
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(
            width: 2.0, color: Colors.lightBlue.shade900))),
    child: Text('button')),
)
</code>```

I don't know how it would turn out, but I hope it helps to give you idea to reach your need

Body:
In flutter, how to add an outline button that look like a text field with underline? I only need a bottom underline.

           OutlineButton(
              color: Theme.of(context).buttonColor,
              textColor: Theme.of(context).textTheme.bodyText1.color,
              // disabledColor: Colors.grey,
              disabledTextColor: Colors.black,
              borderSide: (),
              onPressed: () {

              },
          child: Center(
            child: Text(
              "No Reminder",
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 18.0),
            ),
          ),
            )

Body:
GestureDetector(
  onTap: () => print('tapped'),
  child: Container(
    // optional
    padding: const EdgeInsets.only(bottom: 1.0),
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(
            width: 2.0, color: Colors.lightBlue.shade900))),
    child: Text('button')),
)

I don't know how it would turn out, but I hope it helps to give you idea to reach your need


问:
How to access an Objective-C class method from Swift language
In my Swift app, I need to access a class method called weibo() as below from Objective-C

```<code>@interface Weibo : NSObject
+ (Weibo*)weibo;
@end
</code>```

I have configured the bridging header and tried the following statement

```<code>let w = Weibo.weibo() as Weibo
</code>```

It doesn't work.

UPDATE:
I have forked the repo and fixed this issue as below.

```<code>let w = Weibo.getWeibo() as Weibo // the method has been changed.
</code>```

The reason why it didn't work because Swift treats + (Weibo*)weibo; as a convenience constructor. Since weibo is same as the Class name Weibo although the case is different. I need to change the name to getWeibo to fix this issue to support Swift.

Thanks for every one contributing to this answer. Special thanks to @Anil and @David

Jake

答:
In my situation, my Obj-c class method returned a pointer to a new class not added to my bridging header so the compiler did not make that class method accessible.

You need both the class with the class method you want to call and any class in the class method's description to be included in your bridging header.

Body:
In my Swift app, I need to access a class method called weibo() as below from Objective-C

@interface Weibo : NSObject
+ (Weibo*)weibo;
@end

I have configured the bridging header and tried the following statement

let w = Weibo.weibo() as Weibo

It doesn't work.

UPDATE:
I have forked the repo and fixed this issue as below.

let w = Weibo.getWeibo() as Weibo // the method has been changed.

The reason why it didn't work because Swift treats + (Weibo*)weibo; as a convenience constructor. Since weibo is same as the Class name Weibo although the case is different. I need to change the name to getWeibo to fix this issue to support Swift.

Thanks for every one contributing to this answer. Special thanks to @Anil and @David

Jake


问:
Open Form and Close Form with Checkbox
So I'm trying to open and close/show and hide a form named "InfoOverLay" using a metro checkbox.
But every time the box gets checked it creates a new version of its self.

How could I change this to open and close only one version of itself?

```<code>    private void metroChecker1_CheckedChanged(object sender, bool isChecked)
    {
        if (metroChecker1.Checked == true)
        {
            InfoOverLay f = new InfoOverLay();
            f.Show();
        }
        if (metroChecker1.Checked == false)
        {
            InfoOverLay f = new InfoOverLay();
            f.Hide();
        }
</code>```

答:
You need to add an additional check to see if it's already open
pseudo code:

```<code>if (alreadyIsActive)
  operationCancel();
</code>```

Also make sure you aren't calling multiple instances of it's self like  – vasily.sib said which can be done like:

```<code> private void metroChecker1_CheckedChanged(object sender, bool isChecked)
    {
        InfoOverLay f = new InfoOverLay();
        if (metroChecker1.Checked == true)
        {
            f.Show();
        }
        if (metroChecker1.Checked == false)
        {
            f.Hide();
        }
</code>```

Have a good day!

Title: Open Form and Close Form with Checkbox

Body:
So I'm trying to open and close/show and hide a form named "InfoOverLay" using a metro checkbox.
But every time the box gets checked it creates a new version of its self.

How could I change this to open and close only one version of itself?

    private void metroChecker1_CheckedChanged(object sender, bool isChecked)
    {
        if (metroChecker1.Checked == true)
        {
            InfoOverLay f = new InfoOverLay();
            f.Show();
        }
        if (metroChecker1.Checked == false)
        {
            InfoOverLay f = new InfoOverLay();
            f.Hide();
        }

Body:
You need to add an additional check to see if it's already open
pseudo code:

if (alreadyIsActive)
  operationCancel();

Also make sure you aren't calling multiple instances of it's self like  – vasily.sib said which can be done like:

 private void metroChecker1_CheckedChanged(object sender, bool isChecked)
    {
        InfoOverLay f = new InfoOverLay();
        if (metroChecker1.Checked == true)
        {
            f.Show();
        }
        if (metroChecker1.Checked == false)
        {
            f.Hide();
        }

Have a good day!


问:
Laravel/Homestead Invalid IP Address
I am using Laravel 6.2, Vagrant 2.2.6 and VirtualBox 5.2. Followed the tutorial for Homestead setup. But when I visited myapp.local (out of the box without modifying any code), I got the following error message:

```<code>NotFoundHttpException in RouteCollection.php line 161
</code>```

(Please see my comment below explaining why I was getting this error)

Mistakenly, I modified the ip address in my Homestead.yaml file and now, no matter what I do, I am getting the following error message.

```<code>Network settings specified in your Vagrantfile define an invalid
IP address. Please review the error message below and update your
Vagrantfile network settings:

  Address: 192.168.10:10
  Netmask:
  Error: invalid address
</code>```

Example:

```<code>machine1234:Homestead my_user_name$ vagrant destroy
    homestead: Are you sure you want to destroy the 'homestead' VM? [y/N] y
==> homestead: Destroying VM and associated drives...
machine1234:Homestead my_user_name$ vagrant up --provision
Bringing machine 'homestead' up with 'virtualbox' provider...
==> homestead: Importing base box 'laravel/homestead'...
==> homestead: Matching MAC address for NAT networking...
==> homestead: Checking if box 'laravel/homestead' version '9.2.0' is up to date...
==> homestead: Setting the name of the VM: homestead
==> homestead: Clearing any previously set network interfaces...
Network settings specified in your Vagrantfile define an invalid
IP address. Please review the error message below and update your
Vagrantfile network settings:

  Address: 192.168.10:10
  Netmask:
  Error: invalid address
</code>```

Homestead.yaml looks like this:

```<code>> --- ip: "192.168.10:10" memory: 2048 cpus: 2 provider: virtualbox
>
> authorize: ~/.ssh/id_rsa.pub
>
> keys:
>     - ~/.ssh/id_rsa
>
> folders:
>     - map: ~/Sites/myapp
>       to: /home/vagrant/myapp
>
>
> sites:
>     - map: myapp.local
>       to: /home/vagrant/myapp/public

> databases:
>     - MY_APP_DEV
>
> features:
>     - mariadb: false
>     - ohmyzsh: false
>     - webdriver: false "Homestead.yaml" 41L, 667C
</code>```

Any idea on how I can fix this issue?

答:
Your IP address has a colon!

Change:

```<code>  Address: 192.168.10:10
</code>```

To:

```<code>  Address: 192.168.10.10
</code>```

Title: Laravel/Homestead Invalid IP Address

Body:
I am using Laravel 6.2, Vagrant 2.2.6 and VirtualBox 5.2. Followed the tutorial for Homestead setup. But when I visited myapp.local (out of the box without modifying any code), I got the following error message:

NotFoundHttpException in RouteCollection.php line 161

(Please see my comment below explaining why I was getting this error)

Mistakenly, I modified the ip address in my Homestead.yaml file and now, no matter what I do, I am getting the following error message.

Network settings specified in your Vagrantfile define an invalid
IP address. Please review the error message below and update your
Vagrantfile network settings:

  Address: 192.168.10:10
  Netmask:
  Error: invalid address

Example:

machine1234:Homestead my_user_name$ vagrant destroy
    homestead: Are you sure you want to destroy the 'homestead' VM? [y/N] y
==> homestead: Destroying VM and associated drives...
machine1234:Homestead my_user_name$ vagrant up --provision
Bringing machine 'homestead' up with 'virtualbox' provider...
==> homestead: Importing base box 'laravel/homestead'...
==> homestead: Matching MAC address for NAT networking...
==> homestead: Checking if box 'laravel/homestead' version '9.2.0' is up to date...
==> homestead: Setting the name of the VM: homestead
==> homestead: Clearing any previously set network interfaces...
Network settings specified in your Vagrantfile define an invalid
IP address. Please review the error message below and update your
Vagrantfile network settings:

  Address: 192.168.10:10
  Netmask:
  Error: invalid address

Homestead.yaml looks like this:

> --- ip: "192.168.10:10" memory: 2048 cpus: 2 provider: virtualbox
>
> authorize: ~/.ssh/id_rsa.pub
>
> keys:
>     - ~/.ssh/id_rsa
>
> folders:
>     - map: ~/Sites/myapp
>       to: /home/vagrant/myapp
>
>
> sites:
>     - map: myapp.local
>       to: /home/vagrant/myapp/public

> databases:
>     - MY_APP_DEV
>
> features:
>     - mariadb: false
>     - ohmyzsh: false
>     - webdriver: false "Homestead.yaml" 41L, 667C

Any idea on how I can fix this issue?

Body:
Your IP address has a colon!

Change:

  Address: 192.168.10:10

To:

  Address: 192.168.10.10


问:
Memory Leak Using NSXMLParser in NSConcreteMapTable
I'm using NSXMLParser and I get a memory leak that points to NSConcreteMapTable, whatever that is:

The leak occurs at this line of code when calling the parser from my AppDelegate.m:

I have searched for a solution and can't see what I'm doing wrong.
Here is my code.
Any help is greatly appreciated.
lq

```<code>// * * * XMLParser.h * * *

#import <Foundation/Foundation.h>

@protocol NSXMLParserDelegate;

@interface XMLParser : NSObject
<NSXMLParserDelegate>
{
    NSMutableArray  *xmlArray;
    BOOL        storingCharacters;
    float       xmlDataVersion;
}

@property (nonatomic, retain) NSMutableArray *xmlArray;
@property (nonatomic)  BOOL storingCharacters;
@property (nonatomic, assign) float xmlDataVersion;

-(BOOL)parseXMLFileAtURL:(NSURL *)URL parseError:(NSError **)error;

@end

// * * * XMLParser.m * * *

#import "XMLParser.h"

@implementation XMLParser

@synthesize xmlArray;
@synthesize storingCharacters;
@synthesize xmlDataVersion;

- (BOOL)parseXMLFileAtURL:(NSURL *)URL parseError:(NSError **)error {

    BOOL result = YES;

    if (xmlArray == nil) {
        // this array holds row data extracted from the XML parser didStartElement method
        xmlArray = [[NSMutableArray alloc] init];
    }

    [[NSURLCache sharedURLCache] setMemoryCapacity:0];
    [[NSURLCache sharedURLCache] setDiskCapacity:0];
    NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:URL];

    if (parser != nil) {
        [parser setDelegate:self];
        [parser setShouldProcessNamespaces:NO];
        [parser setShouldReportNamespacePrefixes:NO];
        [[parser setShouldResolveExternalEntities:NO];
    }

    [parser parse];

    if (parseError && error) {
        *error = parseError;
        result = NO;
    }

    [parser release];
    return result;

}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {

    if (qName) {
        elementName = qName;
    }

    // Check the data version of the XML Data against my stored value

    if ([elementName isEqualToString:@"data"]) {

        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        self.xmlDataVersion = [[attributeDict objectForKey:@"version"] floatValue];
        float storedDataVersion = [userDefaults floatForKey:kDataVersion];

       if (self.xmlDataVersion <= storedDataVersion) {
           // - - - - -> Abort parsing if the same or earlier data versions
           [parser abortParsing];
       }

    }

    if ([elementName isEqualToString:@"FirstColumnName"]) {
        storingCharacters = YES;
    } else if ([elementName isEqualToString:@"SecondColumnName"]) {
        storingCharacters = YES;
        // ... total of 16 elements
    }

}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    if (storingCharacters) {
        [self.xmlArray addObject:string];
    }
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {

    if (qName) {
        elementName = qName;
    }

    // - - - - -> If at the end of a data row, save changes to object model

    if ([elementName isEqualToString:@"ROW"]) {

        // - - - - -> Make sure the data has the required number of elements before taking any action

        if ([self.xmlArray count] == 16) {

            // … //Store or Update Data in SQLite store depending on data values

        }

        [self.xmlArray removeAllObjects];

    }

    storingCharacters = NO;
}

-(void)dealloc {
    [xmlArray release];
    [super dealloc];
}

// * * * AppDelegate.m * * *

#import "XMLParser.h"

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(UIApplication *)application {

    NSURL *xmlURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"FileName" ofType:@"xml"]];

    NSError *parseError = nil;

    XMLParser *xmlParse = [[XMLParser alloc] init];
    [xmlParse parseXMLFileAtURL:xmlURL parseError:&parseError];
    [xmlParse release];

    . . .
</code>```

}

答:
I found a solution in another SO post:

Use:

```<code>NSData * dataXml = [[NSData alloc] initWithContentsOfURL:URL];
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:dataXml];
[dataXml release];
</code>```

Instead of:

```<code>NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:URL];
</code>```

The leak goes away.

Body:
I'm using NSXMLParser and I get a memory leak that points to NSConcreteMapTable, whatever that is:

The leak occurs at this line of code when calling the parser from my AppDelegate.m:

I have searched for a solution and can't see what I'm doing wrong.
Here is my code.
Any help is greatly appreciated.
lq

// * * * XMLParser.h * * *

#import <Foundation/Foundation.h>

@protocol NSXMLParserDelegate;

@interface XMLParser : NSObject
<NSXMLParserDelegate>
{
    NSMutableArray  *xmlArray;
    BOOL        storingCharacters;
    float       xmlDataVersion;
}

@property (nonatomic, retain) NSMutableArray *xmlArray;
@property (nonatomic)  BOOL storingCharacters;
@property (nonatomic, assign) float xmlDataVersion;

-(BOOL)parseXMLFileAtURL:(NSURL *)URL parseError:(NSError **)error;

@end

// * * * XMLParser.m * * *

#import "XMLParser.h"

@implementation XMLParser

@synthesize xmlArray;
@synthesize storingCharacters;
@synthesize xmlDataVersion;

- (BOOL)parseXMLFileAtURL:(NSURL *)URL parseError:(NSError **)error {

    BOOL result = YES;

    if (xmlArray == nil) {
        // this array holds row data extracted from the XML parser didStartElement method
        xmlArray = [[NSMutableArray alloc] init];
    }

    [[NSURLCache sharedURLCache] setMemoryCapacity:0];
    [[NSURLCache sharedURLCache] setDiskCapacity:0];
    NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:URL];

    if (parser != nil) {
        [parser setDelegate:self];
        [parser setShouldProcessNamespaces:NO];
        [parser setShouldReportNamespacePrefixes:NO];
        [[parser setShouldResolveExternalEntities:NO];
    }

    [parser parse];

    if (parseError && error) {
        *error = parseError;
        result = NO;
    }

    [parser release];
    return result;

}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {

    if (qName) {
        elementName = qName;
    }

    // Check the data version of the XML Data against my stored value

    if ([elementName isEqualToString:@"data"]) {

        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        self.xmlDataVersion = [[attributeDict objectForKey:@"version"] floatValue];
        float storedDataVersion = [userDefaults floatForKey:kDataVersion];

       if (self.xmlDataVersion <= storedDataVersion) {
           // - - - - -> Abort parsing if the same or earlier data versions
           [parser abortParsing];
       }

    }

    if ([elementName isEqualToString:@"FirstColumnName"]) {
        storingCharacters = YES;
    } else if ([elementName isEqualToString:@"SecondColumnName"]) {
        storingCharacters = YES;
        // ... total of 16 elements
    }

}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    if (storingCharacters) {
        [self.xmlArray addObject:string];
    }
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {

    if (qName) {
        elementName = qName;
    }

    // - - - - -> If at the end of a data row, save changes to object model

    if ([elementName isEqualToString:@"ROW"]) {

        // - - - - -> Make sure the data has the required number of elements before taking any action

        if ([self.xmlArray count] == 16) {

            // … //Store or Update Data in SQLite store depending on data values

        }

        [self.xmlArray removeAllObjects];

    }

    storingCharacters = NO;
}

-(void)dealloc {
    [xmlArray release];
    [super dealloc];
}

// * * * AppDelegate.m * * *

#import "XMLParser.h"

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(UIApplication *)application {

    NSURL *xmlURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"FileName" ofType:@"xml"]];

    NSError *parseError = nil;

    XMLParser *xmlParse = [[XMLParser alloc] init];
    [xmlParse parseXMLFileAtURL:xmlURL parseError:&parseError];
    [xmlParse release];

    . . .

}

Body:
I found a solution in another SO post:

Use:

NSData * dataXml = [[NSData alloc] initWithContentsOfURL:URL];
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:dataXml];
[dataXml release];

Instead of:

NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:URL];

The leak goes away.


问:
How can I get a list of all classes within current module in Python?
I've seen plenty of examples of people extracting all of the classes from a module, usually something like:

```<code># foo.py
class Foo:
    pass

# test.py
import inspect
import foo

for name, obj in inspect.getmembers(foo):
    if inspect.isclass(obj):
        print obj
</code>```

Awesome.

But I can't find out how to get all of the classes from the current module.

```<code># foo.py
import inspect

class Foo:
    pass

def print_classes():
    for name, obj in inspect.getmembers(???): # what do I do here?
        if inspect.isclass(obj):
            print obj

# test.py
import foo

foo.print_classes()
</code>```

This is probably something really obvious, but I haven't been able to find anything. Can anyone help me out?

答:
```<code>import Foo
dir(Foo)

import collections
dir(collections)
</code>```

Body:
I've seen plenty of examples of people extracting all of the classes from a module, usually something like:

# foo.py
class Foo:
    pass

# test.py
import inspect
import foo

for name, obj in inspect.getmembers(foo):
    if inspect.isclass(obj):
        print obj

Awesome.

But I can't find out how to get all of the classes from the current module.

# foo.py
import inspect

class Foo:
    pass

def print_classes():
    for name, obj in inspect.getmembers(???): # what do I do here?
        if inspect.isclass(obj):
            print obj

# test.py
import foo

foo.print_classes()

This is probably something really obvious, but I haven't been able to find anything. Can anyone help me out?


问:
Azure Logic App API Pagination using Until condition
Wondering if you could help with this problem please. I am ingesting data from an API using Azure logic App. I have managed to set up everything else but struggling with pagination in Until condition.Logic App continues to ingest/consume data and creates blank json files with data[]. I have added the screenshots (with and without data in the page). When data is completed, empty or blank page looks like data[].
Any idea what could be my condition in "Until" ?

enter image description here

答:
In your question I can't see the "Until" condition but just a "If" condition, but I think you just want to know how to check if the "data" field is empty and then do different actions (If I misunderstand your requirements, please provide more details and I will try to help you on it).

Please refer to the steps below:

1. We need to use a "Parse JSON" action to parse your json data, when click "Use sample payload to generate schema", you can put the json data which "data" field is not empty into it. And then it will generate the schema automatically.

2. Then we can use "length()" method in the "If" condition.

The whole expression of "length()" method above is:

Below provide the code for you to copy.

```<code>length(body('Parse_JSON')?['data'])
</code>```

Hope it helps~

Body:
In your question I can't see the "Until" condition but just a "If" condition, but I think you just want to know how to check if the "data" field is empty and then do different actions (If I misunderstand your requirements, please provide more details and I will try to help you on it).

Please refer to the steps below:

1. We need to use a "Parse JSON" action to parse your json data, when click "Use sample payload to generate schema", you can put the json data which "data" field is not empty into it. And then it will generate the schema automatically.

2. Then we can use "length()" method in the "If" condition.

The whole expression of "length()" method above is:

Below provide the code for you to copy.

length(body('Parse_JSON')?['data'])

Hope it helps~


问:
Istream function to read with istream parameter
I'm trying to understand this code

```<code>istream &read(istream &is, Sales_data &item)
{
    double price = 0;
    is >> item.bookNo >> item.units_sold >> price;
    item.revenue = price * item.units_sold;
    return is;
}

ostream &print(ostream &os, const Sales_data &item)
{
    os << item.isbn() << " " << item.units_sold << " "
        << item.revenue << " " << item.avg_price();
    return os;
}
</code>```

I don't understand what are these function ,  also I can't understand why we use istream for reading and ostream for printing instead of using cin and cout.

答:
There are more than a few subtleties at play that you need to understand to understand what is taking place in the read and print functions. From the overview standpoint istream and ostream are general input and output classes that provide a basis for stream I/O in C++. As the other answer and comments correctly indicate, std::cin and std::cout are derived from istream and ostream to provide input/output from the standard stream stdin and stdout.

The stream themselves have a state that determines if the stream is good and can be read from or written to, or whether a stream error has occurred preventing further I/O (some failures are recoverable, some not) See std::basic_ios::rdstate and std::basic_ios::setstate for a discussion of the bits (goodbit, badbit, failbit, eofbit) that make up the stream state.

Now looking at your function prototyes:

```<code>istream &read(istream &is, Sales_data &item)
</code>```

and

```<code>ostream &print(ostream &os, const Sales_data &item)
</code>```

Notice how the first parameter is a refernce to the current stream? And notice how the return is also a reference to that same stream? That's important, because it passes a reference to the stream so any changes to the Steam State occurring within the function will be available on return. So if eof is encountered within the read function, that change in state will be available on return. The same for your print function (though the potential errors that would change the stream are fewer and different)

Within read, you are reading 3-pieces of information from the stream, item.bookNo, item.units_sold and price and updating item.revenue:

```<code>is >> item.bookNo >> item.units_sold >> price;
item.revenue = price * item.units_sold;
</code>```

You can read from std::cin by passing that as the argument for is or you can pass an open file-stream. The stream operations will work for any valid stream.

The print function does the opposite, it outputs the return of item.isbn(), item.units_sold, item.revenue and the return from item.avg_price() as output. If you pass std::cout as os

The last command in both functions returns the stream including any change in the stream state so the caller can check whether the read or print was successful. That is key for the caller being able to determine whether the I/O took place.

Overly Simplified Example

An overly simplified example exercising the function may help the concepts sink in. Here we declare a simplified struct Sales_data with int bookno, units_sold; and double price, revenue; For example:

```<code>#include <iostream>

struct Sales_data
{
    int bookno, units_sold;
    double price, revenue;
};
</code>```

We then simplify read to read only the bookno, units_sold and price and compute the revenue for that single item, e.g.

```<code>std::istream &read(std::istream &is, Sales_data &item)
{
    is >> item.bookno >> item.units_sold >> item.price;

    item.revenue = item.price * item.units_sold;

    return is;
}
</code>```

And simplify print to only output the units_sold and revenue:

```<code>std::ostream &print(std::ostream &os, const Sales_data &item)
{
    os << "units sold: " << item.units_sold << " revenue: $"  << item.revenue << '\n';

    return os;
}
</code>```

Now you can see in a very simple way prompting the user to enter a bookno, units_sold and price how both the read and print functions work, as well as how an error occurring within one of the function changes the stream state. A short main() could be:

```<code>int main (void) {

    Sales_data sd;

    std::cout << "enter bookno units_sold price: ";

    if (read (std::cin, sd))        /* if read succeeds */
        print (std::cout, sd);      /* print data */
    else
        std::cerr << "error: invalid input\n";
}
</code>```

Example Use/Output

```<code>$ ./bin/readprintstream
enter bookno units_sold price: 12 100 12.95
units sold: 100 revenue: $1295
</code>```

or if an error occurs:

```<code>$ ./bin/readprintstream
enter bookno units_sold price: 23 banannas 12.28
error: invalid input
</code>```

Hopefully the discussion and example helps clear the concept up a bit. If you have further questions, let me know.

Body:
I'm trying to understand this code

istream &read(istream &is, Sales_data &item)
{
    double price = 0;
    is >> item.bookNo >> item.units_sold >> price;
    item.revenue = price * item.units_sold;
    return is;
}

ostream &print(ostream &os, const Sales_data &item)
{
    os << item.isbn() << " " << item.units_sold << " "
        << item.revenue << " " << item.avg_price();
    return os;
}

I don't understand what are these function ,  also I can't understand why we use istream for reading and ostream for printing instead of using cin and cout.

Body:
There are more than a few subtleties at play that you need to understand to understand what is taking place in the read and print functions. From the overview standpoint istream and ostream are general input and output classes that provide a basis for stream I/O in C++. As the other answer and comments correctly indicate, std::cin and std::cout are derived from istream and ostream to provide input/output from the standard stream stdin and stdout.

The stream themselves have a state that determines if the stream is good and can be read from or written to, or whether a stream error has occurred preventing further I/O (some failures are recoverable, some not) See std::basic_ios::rdstate and std::basic_ios::setstate for a discussion of the bits (goodbit, badbit, failbit, eofbit) that make up the stream state.

Now looking at your function prototyes:

istream &read(istream &is, Sales_data &item)

and

ostream &print(ostream &os, const Sales_data &item)

Notice how the first parameter is a refernce to the current stream? And notice how the return is also a reference to that same stream? That's important, because it passes a reference to the stream so any changes to the Steam State occurring within the function will be available on return. So if eof is encountered within the read function, that change in state will be available on return. The same for your print function (though the potential errors that would change the stream are fewer and different)

Within read, you are reading 3-pieces of information from the stream, item.bookNo, item.units_sold and price and updating item.revenue:

is >> item.bookNo >> item.units_sold >> price;
item.revenue = price * item.units_sold;

You can read from std::cin by passing that as the argument for is or you can pass an open file-stream. The stream operations will work for any valid stream.

The print function does the opposite, it outputs the return of item.isbn(), item.units_sold, item.revenue and the return from item.avg_price() as output. If you pass std::cout as os

The last command in both functions returns the stream including any change in the stream state so the caller can check whether the read or print was successful. That is key for the caller being able to determine whether the I/O took place.

Overly Simplified Example

An overly simplified example exercising the function may help the concepts sink in. Here we declare a simplified struct Sales_data with int bookno, units_sold; and double price, revenue; For example:

#include <iostream>

struct Sales_data
{
    int bookno, units_sold;
    double price, revenue;
};

We then simplify read to read only the bookno, units_sold and price and compute the revenue for that single item, e.g.

std::istream &read(std::istream &is, Sales_data &item)
{
    is >> item.bookno >> item.units_sold >> item.price;

    item.revenue = item.price * item.units_sold;

    return is;
}

And simplify print to only output the units_sold and revenue:

std::ostream &print(std::ostream &os, const Sales_data &item)
{
    os << "units sold: " << item.units_sold << " revenue: $"  << item.revenue << '\n';

    return os;
}

Now you can see in a very simple way prompting the user to enter a bookno, units_sold and price how both the read and print functions work, as well as how an error occurring within one of the function changes the stream state. A short main() could be:

int main (void) {

    Sales_data sd;

    std::cout << "enter bookno units_sold price: ";

    if (read (std::cin, sd))        /* if read succeeds */
        print (std::cout, sd);      /* print data */
    else
        std::cerr << "error: invalid input\n";
}

Example Use/Output

$ ./bin/readprintstream
enter bookno units_sold price: 12 100 12.95
units sold: 100 revenue: $1295

or if an error occurs:

$ ./bin/readprintstream
enter bookno units_sold price: 23 banannas 12.28
error: invalid input

Hopefully the discussion and example helps clear the concept up a bit. If you have further questions, let me know.


问:
CheckBox are not working in ListItem rendered with Flatlist
I am using ListItems with checkbox. Every Item in the list contain the checkBox. I am not able to check or unCheck the checkbox and also not able to select all the checkbox in the listItems. I have made both functions with 'checkBoxTest()' and 'selectAll()' I think i am not using the setState correctly. Here is my code</p>

```<code>import React, { Component } from 'react';
import { FlatList, StyleSheet, Text, View, Image, TouchableOpacity } from 'react-native';
import { ListItem, checkBox } from 'react-native-elements';

const list = [
  {
    name: 'PinkMan',
    avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/ladylexy/128.jpg',
    subtitle: 'Vice President'
  },
  {
    name: 'Mr White',
    avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/adhamdannaway/128.jpg',
    subtitle: 'Vice Chairman'
  },
]

export default class Members extends Component {
  constructor(props) {
    super(props);
    this.state = {
      checked: false,

    }
  }
  selectAll(){
    this.setState({checked: !this.state.checked})
  }

  checkBoxTest() {
    this.setState({checked: !this.state.checked})
  }

  keyExtractor = (item, index) => index.toString()
  renderItem = ({ item }) => (
    <ListItem
      title={item.name}
      subtitle={item.subtitle}
      leftAvatar={{
        source: item.avatar_url && { uri: item.avatar_url },
        title: item.name[0]
      }}
      checkBox={{
        checkedColor: '#744DD2',
        uncheckedColor: 'grey',
        onPress: this.checkBoxTest,
        checked: this.state.checked,
      }}
      bottomDivider
    />
  )

  render() {
    return(
      <>
        <View style={{ bottom: 60 }}>
          <FlatList
            keyExtractor={this.keyExtractor}
            data={list}
            renderItem={this.renderItem}
          />
        </View>
        <View>
          <TouchableOpacity onPress={this.selectAll} >
            <Text style={styles.textStyle}>Select All</Text>
          </TouchableOpacity>
        </View>
      </>
    );
  }
}

</code>```

答:
seems like you forgot to bind this.selectAll() and checkBoxTest()

If you wanna pass a function to onPress(), First you need to bind it in constructor.

```<code>this.selectAll = this.selectAll.bind(this);
this.checkBoxTest = this.checkBoxTest.bind(this);
</code>```

Place these two statements in constructor.

Body:
I am using ListItems with checkbox. Every Item in the list contain the checkBox. I am not able to check or unCheck the checkbox and also not able to select all the checkbox in the listItems. I have made both functions with 'checkBoxTest()' and 'selectAll()' I think i am not using the setState correctly. Here is my code

import React, { Component } from 'react';
import { FlatList, StyleSheet, Text, View, Image, TouchableOpacity } from 'react-native';
import { ListItem, checkBox } from 'react-native-elements';

const list = [
  {
    name: 'PinkMan',
    avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/ladylexy/128.jpg',
    subtitle: 'Vice President'
  },
  {
    name: 'Mr White',
    avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/adhamdannaway/128.jpg',
    subtitle: 'Vice Chairman'
  },
]

export default class Members extends Component {
  constructor(props) {
    super(props);
    this.state = {
      checked: false,

    }
  }
  selectAll(){
    this.setState({checked: !this.state.checked})
  }

  checkBoxTest() {
    this.setState({checked: !this.state.checked})
  }

  keyExtractor = (item, index) => index.toString()
  renderItem = ({ item }) => (
    <ListItem
      title={item.name}
      subtitle={item.subtitle}
      leftAvatar={{
        source: item.avatar_url && { uri: item.avatar_url },
        title: item.name[0]
      }}
      checkBox={{
        checkedColor: '#744DD2',
        uncheckedColor: 'grey',
        onPress: this.checkBoxTest,
        checked: this.state.checked,
      }}
      bottomDivider
    />
  )

  render() {
    return(
      <>
        <View style={{ bottom: 60 }}>
          <FlatList
            keyExtractor={this.keyExtractor}
            data={list}
            renderItem={this.renderItem}
          />
        </View>
        <View>
          <TouchableOpacity onPress={this.selectAll} >
            <Text style={styles.textStyle}>Select All</Text>
          </TouchableOpacity>
        </View>
      </>
    );
  }
}

Body:
seems like you forgot to bind this.selectAll() and checkBoxTest()

If you wanna pass a function to onPress(), First you need to bind it in constructor.

this.selectAll = this.selectAll.bind(this);
this.checkBoxTest = this.checkBoxTest.bind(this);

Place these two statements in constructor.


答:
If you only need this as a one time solution running locally, you might find it easier to load and process this file via File API.

Example:

function handleFiles(files) {
  getAsText(files[0])
}

function getAsText(fileToRead) {
  const reader = new FileReader()
  reader.readAsText(fileToRead)
  reader.onload = (event) => processData(event.target.result)
}

function processData(allText) {
  console.log(allText)
  // do your processing below
  var allTextLines = allText.split(/\r\n|\n/)
  for (var i = 1; i < allTextLines.length; i++) {
   adressesList.push(allTextLines[i]);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="file" onchange="handleFiles(this.files)" accept=".csv"></code>```

Title: CORS error: Turning CSV file into Javascript array

Body:
I am trying convert a CSV file into a javascript array. In the CSV file, all of the values are on separate lines. Anyway, I found this piece of code in another post on Stackoverflow to turn such a file into an array:

var adressesList = []

  $(document).ready(function() {
    $.ajax({
      type: "GET",
      url: "Filepath",
      dataType: "text",
      success: function(data) {
        processData(data);
      }
    });
  });

  function processData(allText) {
    var allTextLines = allText.split(/\r\n|\n/);
    for (var i = 1; i < allTextLines.length; i++) {
      adressesList.push(allTextLines[i]);
    }
  }

I have tried this but I keep getting an error saying that I am not allowed to access the file (it is local on my computer in the same folder as the code).

This is the error I see:

Access to XMLHttpRequest at 'filepat' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

GET filepath net::ERR_FAILED

How could I solve it? I saw that you could put the file on a server. But, shouldn't there just be an easy way to do it locally?

Thank you.

Body:
If you only need this as a one time solution running locally, you might find it easier to load and process this file via File API.

Example:

function handleFiles(files) {
  getAsText(files[0])
}

function getAsText(fileToRead) {
  const reader = new FileReader()
  reader.readAsText(fileToRead)
  reader.onload = (event) => processData(event.target.result)
}

function processData(allText) {
  console.log(allText)
  // do your processing below
  var allTextLines = allText.split(/\r\n|\n/)
  for (var i = 1; i < allTextLines.length; i++) {
   adressesList.push(allTextLines[i]);
  }
}

<input type="file" onchange="handleFiles(this.files)" accept=".csv">