问:
Subcategory inside category in the Codeigniter framework
I want to show subcategory inside the main category. My table looks like this. but when i print_r($cat_id) it returns only the last id of the category. How can I fix this? Here is my controller:

```<code>$data['categories'] = $this->courses_model->get_all_categories_for_courses();

            foreach($data['categories'] as $ct){

                        $cat_id = $ct['id'];
                }

            $data['subcategories'] = $this->courses_model->get_all_subcategories_for_courses($cat_id);

            $this->load->view('templates/header');
            $this->load->view('courses/courses-grid-fullwidth', $data);
            $this->load->view('templates/footer');
        }
</code>```

and here is my model:

```<code>public function get_all_categories_for_courses() {
        $query = $this->db->get_where('categories', array('parent_id' => NULL));
        return $query->result_array();
    }

    function get_all_subcategories_for_courses($cat_id) {
        $query = $this->db->get_where('categories', array('parent_id' => $cat_id));
        return $query->result_array();
    }
</code>```

and here is my view page:

```<code><?php foreach($categories as $cat): ?>
          <div class="col-md-3 col-sm-6 incat">

             <h4>
               <a href="#" class="catname"><i class="fa <?= $cat['icon']; ?>" aria-hidden="true"></i>
               <?= $cat['name_rus']; ?></a>
             </h4>

            <ul>
              <?php foreach($subcategories as $subcat): ?>
              <li><a href="#"><?= $subcat['name_rus']; ?></a></li>
              <?php endforeach; ?>
            </ul>
          </div>
        <?php endforeach; ?>
</code>```

Thanks in advance!

答:
As Ukasyah said in a comment on your question, you're overwriting the $cat_id value each time you loop through your categories.

What you will need to do is get an array populated with the IDs and use $this->db->where_in() to match an array rather than a single value.

Your controller will need to look more like this:

```<code>$data['categories'] = $this->courses_model->get_all_categories_for_courses();

$cat_ids = [];
foreach($data['categories'] as $ct){

    $cat_ids[] = $ct['id'];
}

$data['subcategories'] = $this->courses_model->get_all_subcategories_for_courses($cat_ids);

$this->load->view('templates/header');
$this->load->view('courses/courses-grid-fullwidth', $data);
$this->load->view('templates/footer');
</code>```

While you will need to change your model function to look like this:

```<code>function get_all_subcategories_for_courses($cat_ids) {
    $query = $this->db->where_in('parent_id', $cat_ids)->get('categories');
    return $query->result_array();
}
</code>```

Best of luck.

Body:
I want to show subcategory inside the main category. My table looks like this. but when i print_r($cat_id) it returns only the last id of the category. How can I fix this? Here is my controller:

$data['categories'] = $this->courses_model->get_all_categories_for_courses();

            foreach($data['categories'] as $ct){

                        $cat_id = $ct['id'];
                }

            $data['subcategories'] = $this->courses_model->get_all_subcategories_for_courses($cat_id);

            $this->load->view('templates/header');
            $this->load->view('courses/courses-grid-fullwidth', $data);
            $this->load->view('templates/footer');
        }

and here is my model:

public function get_all_categories_for_courses() {
        $query = $this->db->get_where('categories', array('parent_id' => NULL));
        return $query->result_array();
    }

    function get_all_subcategories_for_courses($cat_id) {
        $query = $this->db->get_where('categories', array('parent_id' => $cat_id));
        return $query->result_array();
    }

and here is my view page:

<?php foreach($categories as $cat): ?>

               <i class="fa <?= $cat['icon']; ?>" aria-hidden="true">
               <?= $cat['name_rus']; ?>

              <?php foreach($subcategories as $subcat): ?>

<?= $subcat['name_rus']; ?>

              <?php endforeach; ?>

        <?php endforeach; ?>

Thanks in advance!

Body:
As Ukasyah said in a comment on your question, you're overwriting the $cat_id value each time you loop through your categories.

What you will need to do is get an array populated with the IDs and use $this->db->where_in() to match an array rather than a single value.

Your controller will need to look more like this:

$data['categories'] = $this->courses_model->get_all_categories_for_courses();

$cat_ids = [];
foreach($data['categories'] as $ct){

    $cat_ids[] = $ct['id'];
}

$data['subcategories'] = $this->courses_model->get_all_subcategories_for_courses($cat_ids);

$this->load->view('templates/header');
$this->load->view('courses/courses-grid-fullwidth', $data);
$this->load->view('templates/footer');

While you will need to change your model function to look like this:

function get_all_subcategories_for_courses($cat_ids) {
    $query = $this->db->where_in('parent_id', $cat_ids)->get('categories');
    return $query->result_array();
}

Best of luck.


来源: stackexchange

问:
Rounding decimals up PHP if 0.001
Can You help me to figure this out. I need to round number to cents if there is atleast one 0.001. So it has to be 0.01 or if 1.133 it has to be 1.14. I tried many ways like

```<code>number_format(round($number, 1, PHP_ROUND_HALF_UP), 2);
</code>```

and etc... Still nothing helps.

答:
You can use ceil() to round up. Unfortunately, you can't specify to how many decimals, so you'll have to multiply and divide:

```<code>$number = ceil($number * 100) / 100;
</code>```

ContentLicense: CC BY-SA 3.0

Title: Rounding decimals up PHP if 0.001

Body:
Can You help me to figure this out. I need to round number to cents if there is atleast one 0.001. So it has to be 0.01 or if 1.133 it has to be 1.14. I tried many ways like

number_format(round($number, 1, PHP_ROUND_HALF_UP), 2);

and etc... Still nothing helps.

Body:
You can use ceil() to round up. Unfortunately, you can't specify to how many decimals, so you'll have to multiply and divide:

$number = ceil($number * 100) / 100;


问:
Editable console listview in python
I'm trying to find a way to make an editable listview in python to be used in a terminal.

Basically each line of that listview will have a single word and I would like to be able to check or uncheck some words in the listview. Then, once I'm done editing I want to be able to close the listview and continue the rest of the program. How can I do this?

答:
The curses library is a good way to do this. It allows you to write strings to the screen in a specific position instead of just constantly scrolling down like a typical Python program. And it has the ability to grab key  inputs so you could use arrow keys and space bar to select individual lines.

Because you can write strings to a specific position on the screen you can use a string like '[ ]' to represent an unselected option and '[*]' to represent a selected option. So when a user hits space you can toggle the current lines' selection status.

https://docs.python.org/3/howto/curses.html#the-python-curses-module

Title: Editable console listview in python


问:
Possible to make the VS debugger pause only when an exception different from the expected one is raised?
I wrote a test method to test another method, with input data randomly generated. So in different runs of the test method, different inputs are randomly generated, in order to provide good coverage of the input space.

The test method is supposed to pass, when the method being tested raises an exception instance of a specific exception type InvalidDataException. I did it by adding an attribute to the test method:

```<code>[ExpectedException(typeof(InvalidDataException))]
</code>```

But the test method may also raise an exception instance of an unexpected exception type different from InvalidDataException. So I  would like to debug the test method.

In Visual Studio 2015 for C#, when I am debugging the test method, the debugger pauses when an exception instance is raised, whether the exception instance belongs to  InvalidDataException or an unexpected different exception type. Is it possible to make the debugger pause only when an exception instance of an exception type different from the one expected (i.e. InvalidDataException) is raised?

Thanks.

答: Visual Studio does allow you to only break on certain exceptions. To set the settings go to the debug menu -> Windows -> Exceptions Settings. From there you can select which exceptions the debugger will break on.</p>

Body:
I wrote a test method to test another method, with input data randomly generated. So in different runs of the test method, different inputs are randomly generated, in order to provide good coverage of the input space.

The test method is supposed to pass, when the method being tested raises an exception instance of a specific exception type InvalidDataException. I did it by adding an attribute to the test method:

[ExpectedException(typeof(InvalidDataException))]

But the test method may also raise an exception instance of an unexpected exception type different from InvalidDataException. So I  would like to debug the test method.

In Visual Studio 2015 for C#, when I am debugging the test method, the debugger pauses when an exception instance is raised, whether the exception instance belongs to  InvalidDataException or an unexpected different exception type. Is it possible to make the debugger pause only when an exception instance of an exception type different from the one expected (i.e. InvalidDataException) is raised?

Thanks.


问:
In Google Maps V3, how can I get a draggable marker to pan the map?
I have found several V2 examples of how to pan the map while a marker is being dragged.  For example:  http://www.putyourlightson.net/projects/coordinates

```<code>    // create map and add controls
var map = new GMap2(document.getElementById("map"));
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());

// set centre point of map
var centrePoint = new GLatLng('53.34870686020199', '-6.267356872558594');
map.setCenter(centrePoint, 14);

// add a draggable marker
var marker = new GMarker(centrePoint, {draggable: true});
map.addOverlay(marker);

// add a drag listener to the map
GEvent.addListener(marker, "dragend", function() {
    var point = marker.getPoint();
    map.panTo(point);
    document.getElementById("latitude").value = point.lat();
    document.getElementById("longitude").value = point.lng();
});
</code>```

This page seems to "auto-pan" while the marker is being dragged; note that its only event listener is for "dragend".  But I assure you that that map pans while the marker is being dragged.

I am trying to achieve the same thing with the V3 API, without any success.  I even tried calling map.panTo() while the icon is being dragged, with unsatisfying results:  http://www.publicgloucester.com/test.html

```<code>function initialize ()
   {
   Gloucester = new google.maps.LatLng (42.6159285, -70.6619888);

   myOptions =
      {
      zoom: 14,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      center: Gloucester,
      streetViewControl: false
      }

   map = new google.maps.Map (document.getElementById ("map_canvas"), myOptions);

   marker = new google.maps.Marker ({position: Gloucester, title: "Gloucester, MA"});
   marker.setMap (map);
   marker.setDraggable (true);

   google.maps.event.addListener (marker, 'drag', function (event)
      {
      // Pan to this position (doesn't work!)
      map.panTo (marker.getPosition());
      });

   }
</code>```

It makes sense to me that this wouldn't work, since panning to place the marker in the center of the map, while the map is moving, is bogus.

Is it as simple as the V2 API doing this automatically, while the V3 API does not?  How can I achieve this effect with the V3 API?

Thanks.

答:
Google has fixed this:  http://code.google.com/p/gmaps-api-issues/issues/detail?id=2404

You can see the fix in action at http://www.publicgloucester.com/test2.html.  Ignore the comment that says "it doesn't do what I want"; that comment is obsolete.

ContentLicense: CC BY-SA 2.5

Body:
I have found several V2 examples of how to pan the map while a marker is being dragged.  For example:  http://www.putyourlightson.net/projects/coordinates

    // create map and add controls
var map = new GMap2(document.getElementById("map"));
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());

// set centre point of map
var centrePoint = new GLatLng('53.34870686020199', '-6.267356872558594');
map.setCenter(centrePoint, 14);

// add a draggable marker
var marker = new GMarker(centrePoint, {draggable: true});
map.addOverlay(marker);

// add a drag listener to the map
GEvent.addListener(marker, "dragend", function() {
    var point = marker.getPoint();
    map.panTo(point);
    document.getElementById("latitude").value = point.lat();
    document.getElementById("longitude").value = point.lng();
});

This page seems to "auto-pan" while the marker is being dragged; note that its only event listener is for "dragend".  But I assure you that that map pans while the marker is being dragged.

I am trying to achieve the same thing with the V3 API, without any success.  I even tried calling map.panTo() while the icon is being dragged, with unsatisfying results:  http://www.publicgloucester.com/test.html

function initialize ()
   {
   Gloucester = new google.maps.LatLng (42.6159285, -70.6619888);

   myOptions =
      {
      zoom: 14,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      center: Gloucester,
      streetViewControl: false
      }

   map = new google.maps.Map (document.getElementById ("map_canvas"), myOptions);

   marker = new google.maps.Marker ({position: Gloucester, title: "Gloucester, MA"});
   marker.setMap (map);
   marker.setDraggable (true);

   google.maps.event.addListener (marker, 'drag', function (event)
      {
      // Pan to this position (doesn't work!)
      map.panTo (marker.getPosition());
      });

   }

It makes sense to me that this wouldn't work, since panning to place the marker in the center of the map, while the map is moving, is bogus.

Is it as simple as the V2 API doing this automatically, while the V3 API does not?  How can I achieve this effect with the V3 API?

Thanks.


问:
python how to get name of the enum
I have an enum like this

```<code>class testEnum(Enum):
   Code_1 = "successful response"
   Code_2 = "failure response"
</code>```

Then I have a method that takes the enum key name Code_1 and enum key value successful response as inputs.

If I send testEnum.Code_1 then that resolves to successful response and not Code_1.

I checked some documentation online that suggests to use testEnum.Code_1.name but that throws an error saing that 'name' doesn't exist for the enum item.

Does anyone know how to get the name of the enum key ?

答:
I suspect that what's happened is that you're using the outdated pip-installable library called enum.  If you did, you'd get something like

```<code>>>> from enum import Enum
>>> class testEnum(Enum):
...    Code_1 = "successful response"
...    Code_2 = "failure response"
...
>>> testEnum.Code_1
'successful response'
>>> testEnum.Code_1.name
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'name'
</code>```

whereas with the "real" enum (either enum in the standard library if you're using modern Python, or the enum34 backport if you're not), you'd see

```<code>>>> from enum import Enum
>>> class testEnum(Enum):
...    Code_1 = "successful response"
...    Code_2 = "failure response"
...
>>> testEnum.Code_1
<testEnum.Code_1: 'successful response'>
>>> testEnum.Code_1.name
'Code_1'
</code>```

You can confirm this independently by typing help(enum) and seeing whether you see "NAME / enum / MODULE REFERENCE / https://docs.python.org/3.6/library/enum" (as you should) or simply "NAME / enum - Robust enumerated type support in Python" if you're using the older one.

Title: python how to get name of the enum

Body:
I have an enum like this

class testEnum(Enum):
   Code_1 = "successful response"
   Code_2 = "failure response"

Then I have a method that takes the enum key name Code_1 and enum key value successful response as inputs.

If I send testEnum.Code_1 then that resolves to successful response and not Code_1.

I checked some documentation online that suggests to use testEnum.Code_1.name but that throws an error saing that 'name' doesn't exist for the enum item.

Does anyone know how to get the name of the enum key ?

Body:
I suspect that what's happened is that you're using the outdated pip-installable library called enum.  If you did, you'd get something like

>>> from enum import Enum
>>> class testEnum(Enum):
...    Code_1 = "successful response"
...    Code_2 = "failure response"
...
>>> testEnum.Code_1
'successful response'
>>> testEnum.Code_1.name
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'name'

whereas with the "real" enum (either enum in the standard library if you're using modern Python, or the enum34 backport if you're not), you'd see

>>> from enum import Enum
>>> class testEnum(Enum):
...    Code_1 = "successful response"
...    Code_2 = "failure response"
...
>>> testEnum.Code_1
<testEnum.Code_1: 'successful response'>
>>> testEnum.Code_1.name
'Code_1'

You can confirm this independently by typing help(enum) and seeing whether you see "NAME / enum / MODULE REFERENCE / https://docs.python.org/3.6/library/enum" (as you should) or simply "NAME / enum - Robust enumerated type support in Python" if you're using the older one.


问:
Twitter Bootstrap Modal stop Youtube video
I'm very new to javascript and trying to use Twitter bootstrap to get a good looking website up and running quickly.  I know this has something to do with jquery, but I'm not sure how to stop my video when I push the close button or the close icon. </p>

<p>Can someone explain how I can get my video to stop playing because even when I close the window, I can still hear it in the background.  </p>

```<code><!-- Button to trigger modal -->
    <a href="#myModal" role="button" class="btn" data-toggle="modal"><img src="img/play.png"></a>

<!-- Modal -->
  <div id="myModal" class="modal hide fade" tabindex="-1" role=labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal" aria>×</button>
      <h3 id="myModalLabel">I am the header</h3>
    </div>
    <div class="modal-body">
      <p><iframe width="100%" height="315" src="http:com/embed/662KGcqjT5Q" frameborder="0" allowfullscreen></iframe></p>
    </div>
    <div class="modal-footer">
      <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
    </div>
  </div>
</code>```

答:
This one does it perfectly:

```<code>$("#myModal").on("hidden.bs.modal", function(t) {
   var o = $(t.target).find("iframe");
   o.each(function(t, o) {
      $(o).attr("src", $(o).attr("src"))
   });
});
</code>```

If you however want to have it start when modal opens / stop when it closes use this code:

But make sure to add enablejsapi=1 in your src, like this for example:

```<code><iframe src="https://www.youtube.com/embed/YOUR_VIDEO_CODE?rel=0&controls=0&showinfo=0&enablejsapi=1" frameborder="0" allowfullscreen></iframe>

function playStopVideo() {
    var youtubeFunc ='';
    var outerDiv = $("#myModal");
    var youtubeIframe = outerDiv.find("iframe")[0].contentWindow;
    outerDiv.on('hidden.bs.modal', function (e) {
        youtubeFunc = 'stopVideo';
        youtubeIframe.postMessage('{"event":"command","func":"' + youtubeFunc + '","args":""}', '*');
    });
    outerDiv.on('shown.bs.modal', function (e) {
        youtubeFunc = 'playVideo';
        youtubeIframe.postMessage('{"event":"command","func":"' + youtubeFunc + '","args":""}', '*');
    });
}

playStopVideo();
</code>```

Body:
I'm very new to javascript and trying to use Twitter bootstrap to get a good looking website up and running quickly.  I know this has something to do with jquery, but I'm not sure how to stop my video when I push the close button or the close icon.

Can someone explain how I can get my video to stop playing because even when I close the window, I can still hear it in the background.

      <button type="button" class="close" data-dismiss="modal" aria>×</button>

I am the header

      <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>

Body:
This one does it perfectly:

$("#myModal").on("hidden.bs.modal", function(t) {
   var o = $(t.target).find("iframe");
   o.each(function(t, o) {
      $(o).attr("src", $(o).attr("src"))
   });
});

If you however want to have it start when modal opens / stop when it closes use this code:

But make sure to add enablejsapi=1 in your src, like this for example:

<iframe src="https://www.youtube.com/embed/YOUR_VIDEO_CODE?rel=0&amp;controls=0&amp;showinfo=0&enablejsapi=1" frameborder="0" allowfullscreen></iframe>

function playStopVideo() {
    var youtubeFunc ='';
    var outerDiv = $("#myModal");
    var youtubeIframe = outerDiv.find("iframe")[0].contentWindow;
    outerDiv.on('hidden.bs.modal', function (e) {
        youtubeFunc = 'stopVideo';
        youtubeIframe.postMessage('{"event":"command","func":"' + youtubeFunc + '","args":""}', '*');
    });
    outerDiv.on('shown.bs.modal', function (e) {
        youtubeFunc = 'playVideo';
        youtubeIframe.postMessage('{"event":"command","func":"' + youtubeFunc + '","args":""}', '*');
    });
}

playStopVideo();


问:
Installing an Android app : ADT vs Terminal
When an app is launched via ADT the avg. execution of a specific code took ~150ms (note the debugger is not attached)
When the same app is installed via adb and installed manually clicking on the icon the avg. time took to execute the same piece of code took ~58ms

So the difference in time is ~100ms - and there is no difference in code base except the way app is installed and launched.

Questions :
What is the additional processing the app is doing when launched via ADT launcher?
Did anyone came across this kind of scenario?
What are the best/recommended ways/tools to measure/instrument execution times.

Thanks!

答: The reasons being AOT vs JIT compilation. ADT defers AOT compilation and do it as when using the app, whereas adb do the AOT ahead and then install it. https://www.youtube.com/watch?v=fwMM6g7wpQ8&feature=youtu.be is helpful.</p>


问:
How to assert element is not present/visible on page
Using Selenium, what is the best way (most reliable) to assert that an element is not present on the page?

We give the element an id:

```<code><div id="12345"></div>
</code>```

in our Selenium code, we have something like this:

```<code>      let el = await driver.findElement(By.id(`12345`));
      await driver.wait(until.elementIsVisible(el), 6000).then(function () {
          // we would fail the test here
          throw new Error('element was not supposed to be found!')
      });
</code>```

should we simply expect a timeout when searching for the element? Or is there a better way than expecting a timeout?

答:
You should utilize a combination of WebDriverWait and the ExpectedCondition utilities. The WebDriverWait establishes the time it will wait for the element to not be visible. In the example below, it is set to 10 seconds, but you can adjust this to whatever works for you. The ExpectedCondition, particularly the invisibility_of_element_located() method is what you would use. So something like this is what you need (in Python):

```<code>WebDriverWait(driver, 10).until(ExpectedCondition.invisibility_of_element_located((By.ID, elementIdentifier)))
</code>```

Body:
Using Selenium, what is the best way (most reliable) to assert that an element is not present on the page?

We give the element an id:

in our Selenium code, we have something like this:

      let el = await driver.findElement(By.id(`12345`));
      await driver.wait(until.elementIsVisible(el), 6000).then(function () {
          // we would fail the test here
          throw new Error('element was not supposed to be found!')
      });

should we simply expect a timeout when searching for the element? Or is there a better way than expecting a timeout?

Body:
You should utilize a combination of WebDriverWait and the ExpectedCondition utilities. The WebDriverWait establishes the time it will wait for the element to not be visible. In the example below, it is set to 10 seconds, but you can adjust this to whatever works for you. The ExpectedCondition, particularly the invisibility_of_element_located() method is what you would use. So something like this is what you need (in Python):

WebDriverWait(driver, 10).until(ExpectedCondition.invisibility_of_element_located((By.ID, elementIdentifier)))


问:
Bulk update using model's method in SQLAlchemy
I'm developing an application with SQLAlchemy and I've run into a bit of an issue. I would like to run a method on all models returned by a query and make all that in a single SQL query, while preserving the readability the ORM offers.

The method in question is very simple and doesn't depend on any external data nor makes any more queries. It's also fine if all the models in the bulk update use the same exact value, so the value itself needs to be evaluated only once.

Here's my model:

```<code>class Item(db.Model):
    last_fetch = db.Column(db.DateTime)

    def refresh(self):
        self.last_fetch = datetime.utcnow()
</code>```

I would like to call the refresh() function on all models returned by a query - for the sake of example let's assume it's Item.query.all().

I can iterate through them and run the method on each model but that would run a separate query for each one of them:

```<code>items = Item.query.all()

for item in items:
    item.refresh()
</code>```

Or I could do the following which works however I've now moved my refresh() logic from the model to the code that would otherwise just call that method:

```<code>items = Item.query.all()

items.update({Item.last_fetch: datetime.utcnow()})
</code>```

Is there a better solution? A way to define a "smart" method on the model that would somehow allow the ORM to run it in bulk while still keeping it a model method?

Regards.

答:
Since SQLAlchemy doesn't recreate queried objects using __init__ but __new__.

You could either override __new__ on your model or  try and see if the @orm.reconstructor decorator explained in Constructors and Object Initialization would work.

Using the reconstructor:

```<code>class Item(db.Model):
last_fetch = db.Column(db.DateTime)

@orm.reconstructor
def set_last_fetch_on_load(self):
    self.last_fetch = datetime.datetime.now()
</code>```

Overriding __new__:

```<code>class Item(db.Model):
last_fetch = db.Column(db.DateTime)

def __new__(cls, *args, **kwargs):
    obj = object.__new__(cls, *args, **kwargs)
    obj.last_fetch = datetime.datetime.now()
    return obj
</code>```

Note: Haven't tested it.

Body:
I'm developing an application with SQLAlchemy and I've run into a bit of an issue. I would like to run a method on all models returned by a query and make all that in a single SQL query, while preserving the readability the ORM offers.

The method in question is very simple and doesn't depend on any external data nor makes any more queries. It's also fine if all the models in the bulk update use the same exact value, so the value itself needs to be evaluated only once.

Here's my model:

class Item(db.Model):
    last_fetch = db.Column(db.DateTime)

    def refresh(self):
        self.last_fetch = datetime.utcnow()

I would like to call the refresh() function on all models returned by a query - for the sake of example let's assume it's Item.query.all().

I can iterate through them and run the method on each model but that would run a separate query for each one of them:

items = Item.query.all()

for item in items:
    item.refresh()

Or I could do the following which works however I've now moved my refresh() logic from the model to the code that would otherwise just call that method:

items = Item.query.all()

items.update({Item.last_fetch: datetime.utcnow()})

Is there a better solution? A way to define a "smart" method on the model that would somehow allow the ORM to run it in bulk while still keeping it a model method?

Regards.

Body:
Since SQLAlchemy doesn't recreate queried objects using __init__ but __new__.

You could either override __new__ on your model or  try and see if the @orm.reconstructor decorator explained in Constructors and Object Initialization would work.

Using the reconstructor:

class Item(db.Model):
last_fetch = db.Column(db.DateTime)

@orm.reconstructor
def set_last_fetch_on_load(self):
    self.last_fetch = datetime.datetime.now()

Overriding __new__:

class Item(db.Model):
last_fetch = db.Column(db.DateTime)

def __new__(cls, *args, **kwargs):
    obj = object.__new__(cls, *args, **kwargs)
    obj.last_fetch = datetime.datetime.now()
    return obj

Note: Haven't tested it.


问:
How will I know when to create an interface?
I'm at a point in my development learning where I feel like I must learn more about interfaces.

I frequently read about them but it just seems like I cannot grasp them.

I've read examples like: Animal base class, with IAnimal interface for things like 'Walk', 'Run', 'GetLegs', etc - but I've never been working on something and felt like "Hey I should use an interface here!"

What am I missing? Why is it such a hard concept for me to grasp! I am just intimidated by the fact that I might not ever realize a concrete need for one - mostly due to some missing aspect of understanding them! It makes me feel like I'm missing something up top in terms of being a developer! If anyone has had an experience like this and had a breakthrough I would appreciate some tips on how to understand this concept. Thank you.

答:
Some non-programming examples that might help you see the appropriate uses of interfaces in programming.

There's an interface between electrical devices and the electricity network - it's the set of conventions about the shape of the plugs and sockets and the voltages/currents across them. If you want to implement a new electrical device, as long as your plug follows the rules it will be able to get services from the network. This makes extensibility very easy and removes or lowers the costs of coordination: you don't have to notify the electricity provider about how your new device works and come to a separate agreement about how to plug your new device into the network.

Countries have standard rail gauges. This allows a division of labour between engineering companies who put down rails and engineering companies who build trains to run on those rails, and it makes it possible for rail companies to replace and upgrade trains without rearchitecting the whole system.

The service a business presents to a client can be described as an interface: a well defined interface emphasises the service and hides the means. When you put a letter in a mailbox, you expect the postal system to deliver the letter within a given time but you have no expectations about how the letter is delivered: you don't need to know, and the postal service has the flexibility to choose the means of delivery that best meets the requirements and current circumstances. An exception to this is the ability of customers to choose airmail - that's not the kind of interface a modern computer programmer would have designed, since it reveals too much of the implementation.

Examples from nature: I'm not too keen on the eats(), makesSound(), moves(), etc examples. They do describe behaviour, which is correct, but they don't describe interactions and how they're enabled. The obvious examples of interfaces that enable interactions in nature are to do with reproduction, for example a flower provides a certain interface to a bee so that pollination can take place.

LastEditorDisplayName: ALassek


问:
Operating over a pointer with ranges
The C++ codebase I'm working on calls a C API that returns both a pointer to a list of structs and the length of the list.  What would be the idiomatic means of processing this list with ranges?  Is there an existing adapter or is creating a custom range_facade type the best way of handling this?

答: You want to use view::counted(ptr, length) to make a range of length elements starting at ptr.

Title: Operating over a pointer with ranges


问:
ListView displays nothing
I would like to send selected item from listview to another listview with sharedprefences. I can save item but cannot see this item another listview. Activity class

```<code>TextView textUrun = (TextView) view.findViewById(R.id.textUrun);
            TextView textFiyat = (TextView) view.findViewById(R.id.textFiyat);
            String yemek = textUrun.getText().toString();
            String fiyat = textFiyat.getText().toString();
            DataProvider dataProvider = new DataProvider(yemek,fiyat);
            list.add(dataProvider);
            String jsonurun = gson.toJson(list);
            SharedPreferences sharedPreferences = getSharedPreferences("yemekbilgi", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("yemek",jsonurun);
            editor.apply();
            Toast.makeText(getApplicationContext(),"Listeye Kaydedildi",Toast.LENGTH_LONG).show();
</code>```

This is list class which should display items.Listele1

```<code>SharedPreferences sharedPreferences = getSharedPreferences("urun1", Context.MODE_PRIVATE);
    List<DataProvider> list;
    String jsonurun = sharedPreferences.getString("liste1", "");
    Gson gson = new Gson();
    DataProvider[] providers = gson.fromJson(jsonurun, DataProvider[].class);
    list = Arrays.asList(providers);
    listDataAdapter = new ListDataAdapter(getApplicationContext(), list);
    listView = (ListView) findViewById(R.id.liste1);
    listView.setAdapter(listDataAdapter);
</code>```

Finally,this is Adapter Class

```<code>public class ListDataAdapter extends ArrayAdapter {
List list = new ArrayList();

public ListDataAdapter(@NonNull Context context,List<DataProvider> list) {
    super(context, R.layout.be_layout, list);
}

static class LayoutHandler{
    TextView ad,fiyat;
}

@Override
public void add(@Nullable Object object) {
    super.add(object);
    list.add(object);
}

@Override
public int getCount() {
    return list.size();
}

@Nullable
@Override
public Object getItem(int position) {
    return list.get(position);
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    View view = convertView;
    LayoutHandler layoutHandler;
    if (view == null){
        LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = layoutInflater.inflate(R.layout.child_layout,parent,false);
        layoutHandler = new LayoutHandler();
        layoutHandler.ad = (TextView) view.findViewById(R.id.textUrun);
        layoutHandler.fiyat = (TextView) view.findViewById(R.id.textFiyat);
        view.setTag(layoutHandler);
    }
    else
        layoutHandler = (LayoutHandler) view.getTag();
    DataProvider dataProvider = (DataProvider) this.getItem(position);
    layoutHandler.ad.setText(dataProvider.getAd());
    layoutHandler.fiyat.setText(dataProvider.getFiyat());
    return view;
}
</code>```

}

答:
```<code>list = new ArrayList<DataProvider>();
gson = new Gson();
SharedPreferences sharedPreferences = getSharedPreferences("yemekbilgi", Context.MODE_PRIVATE);
String yemek = sharedPreferences.getString("yemek","");
Type type = new TypeToken<List<DataProvider>>(){}.getType();
list = gson.fromJson(yemek,type);
listView = (ListView) findViewById(R.id.liste1);
listDataAdapter = new ListDataAdapter(getApplicationContext(),R.layout.child_layout,list);
listView.setAdapter(listDataAdapter);
</code>```

Title: ListView displays nothing

Body:
I would like to send selected item from listview to another listview with sharedprefences. I can save item but cannot see this item another listview. Activity class

TextView textUrun = (TextView) view.findViewById(R.id.textUrun);
            TextView textFiyat = (TextView) view.findViewById(R.id.textFiyat);
            String yemek = textUrun.getText().toString();
            String fiyat = textFiyat.getText().toString();
            DataProvider dataProvider = new DataProvider(yemek,fiyat);
            list.add(dataProvider);
            String jsonurun = gson.toJson(list);
            SharedPreferences sharedPreferences = getSharedPreferences("yemekbilgi", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("yemek",jsonurun);
            editor.apply();
            Toast.makeText(getApplicationContext(),"Listeye Kaydedildi",Toast.LENGTH_LONG).show();

This is list class which should display items.Listele1

SharedPreferences sharedPreferences = getSharedPreferences("urun1", Context.MODE_PRIVATE);
    List<DataProvider> list;
    String jsonurun = sharedPreferences.getString("liste1", "");
    Gson gson = new Gson();
    DataProvider[] providers = gson.fromJson(jsonurun, DataProvider[].class);
    list = Arrays.asList(providers);
    listDataAdapter = new ListDataAdapter(getApplicationContext(), list);
    listView = (ListView) findViewById(R.id.liste1);
    listView.setAdapter(listDataAdapter);

Finally,this is Adapter Class

public class ListDataAdapter extends ArrayAdapter {
List list = new ArrayList();

public ListDataAdapter(@NonNull Context context,List<DataProvider> list) {
    super(context, R.layout.be_layout, list);
}

static class LayoutHandler{
    TextView ad,fiyat;
}

@Override
public void add(@Nullable Object object) {
    super.add(object);
    list.add(object);
}

@Override
public int getCount() {
    return list.size();
}

@Nullable
@Override
public Object getItem(int position) {
    return list.get(position);
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    View view = convertView;
    LayoutHandler layoutHandler;
    if (view == null){
        LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = layoutInflater.inflate(R.layout.child_layout,parent,false);
        layoutHandler = new LayoutHandler();
        layoutHandler.ad = (TextView) view.findViewById(R.id.textUrun);
        layoutHandler.fiyat = (TextView) view.findViewById(R.id.textFiyat);
        view.setTag(layoutHandler);
    }
    else
        layoutHandler = (LayoutHandler) view.getTag();
    DataProvider dataProvider = (DataProvider) this.getItem(position);
    layoutHandler.ad.setText(dataProvider.getAd());
    layoutHandler.fiyat.setText(dataProvider.getFiyat());
    return view;
}

}


问:
std::unique_ptr pimpl in dll generates C4251 with visual studio
This is not a breaking issue but I like to clean my code from warnings so this is getting on my nerves.

I have been using the c++11 version of pimpl idiom to hide the class implementation for my library the usual way.

```<code>// dll header
class FrameworkImpl;

class EXPORT_API Framework
{
    Framework(const Framework&) = delete;
    Framework& operator=(const Framework&) = delete;
    Framework(Framework&&) = delete;
    Framework& operator=(Framework&&) = delete;

public:
    Framework();
    ~Framework();

private:
    std::unique_ptr<FrameworkImpl> impl_;
};

// application implementation
int main()
{
    std::unique_ptr<Framework> test = std::make_unique<Framework>();
}
</code>```

Everything will be fine, but I will keep getting the warning:

```<code>warning C4251: 'Framework::impl_': class 'std::unique_ptr<FrameworkImpl,std::default_delete<_Ty>>' needs to have dll-interface to be used by clients of class 'Framework'
</code>```

So I tried have to add:

```<code>template class EXPORT_API std::unique_ptr<FrameworkImpl>;
</code>```

Before the forward declaration but the warning would just change to:

```<code>warning C4251: 'std::_Unique_ptr_base<_Ty,_Dx>::_Mypair': class 'std::_Compressed_pair<_Dx,FrameworkImpl *,true>' needs to have dll-interface to be used by clients of class 'std::_Unique_ptr_base<_Ty,_Dx>'
</code>```

I have being seeing this issue since VS2010 and I cannot figure a good way to fix this. No problems on gcc or clang and it would break my heart to use the old raw pointer version..

答:
Instead of exporting the entire class, you could export public methods only:</p>

```<code>class Framework
{
    Framework(const Framework&) = delete;
    Framework& operator=(const Framework&) = delete;
    Framework(Framework&&) = delete;
    Framework& operator=(Framework&&) = delete;

public:
    EXPORT_API Framework();
    EXPORT_API ~Framework();

private:
    std::unique_ptr<FrameworkImpl> impl_;
};
</code>```

Body:
This is not a breaking issue but I like to clean my code from warnings so this is getting on my nerves.

I have been using the c++11 version of pimpl idiom to hide the class implementation for my library the usual way.

// dll header
class FrameworkImpl;

class EXPORT_API Framework
{
    Framework(const Framework&) = delete;
    Framework& operator=(const Framework&) = delete;
    Framework(Framework&&) = delete;
    Framework& operator=(Framework&&) = delete;

public:
    Framework();
    ~Framework();

private:
    std::unique_ptr<FrameworkImpl> impl_;
};

// application implementation
int main()
{
    std::unique_ptr<Framework> test = std::make_unique<Framework>();
}

Everything will be fine, but I will keep getting the warning:

warning C4251: 'Framework::impl_': class 'std::unique_ptr<FrameworkImpl,std::default_delete<_Ty>>' needs to have dll-interface to be used by clients of class 'Framework'

So I tried have to add:

template class EXPORT_API std::unique_ptr<FrameworkImpl>;

Before the forward declaration but the warning would just change to:

warning C4251: 'std::_Unique_ptr_base<_Ty,_Dx>::_Mypair': class 'std::_Compressed_pair<_Dx,FrameworkImpl *,true>' needs to have dll-interface to be used by clients of class 'std::_Unique_ptr_base<_Ty,_Dx>'

I have being seeing this issue since VS2010 and I cannot figure a good way to fix this. No problems on gcc or clang and it would break my heart to use the old raw pointer version..

Body:
Instead of exporting the entire class, you could export public methods only:

class Framework
{
    Framework(const Framework&) = delete;
    Framework& operator=(const Framework&) = delete;
    Framework(Framework&&) = delete;
    Framework& operator=(Framework&&) = delete;

public:
    EXPORT_API Framework();
    EXPORT_API ~Framework();

private:
    std::unique_ptr<FrameworkImpl> impl_;
};


问:
Sqlite 3 select statemen
I need to do a somewhat complex select in sqlite3 if you guys can help me?

I got a 'messages' table holding the following fields:

```<code>from | to | message_text | message_timestamp
</code>```

and the rows:

```<code>a | b | Hi | 101
a | b | How are you? | 103
b | a | Fine,thanks | 104
c | a | Hey dude! | 115
a | b | I need to tell you something. | 1102
d | b | Yo dude | 1234
b | d | Yea dude, whatsup? | 1443
</code>```

I'd like to select the last messages from the above conversation in chronologic order by disregarding if the message was sent form x to y or form y to x, the xy or yx pair should be taken into account. So for the example above, you'd get something like this:

```<code>b | d | Yea dude, whatsup? | 1443
a | b | I need to tell you something. | 1102
c | a | Hey dude! | 115
</code>```

Thanks!!

答:
One trick which works here to use the scalar min/max trick to collect records sharing the same from/to or to/from pairs into the same logical group.  In the query below, the innermost subquery buckets would collect, for example, from b to d into the same bucket as from d to b.  Then we aggregate over this to find the latest timestamp, and finally join back to your original table to retrieve the entire rows you want.

```<code>SELECT
    m1.*
FROM messages m1
INNER JOIN
(
    SELECT
        t."from",
        t."to",
        MAX(t.message_timestamp) AS max_ts
    FROM
    (
        SELECT
            MIN("from", "to") AS "from",
            MAX("from", "to") AS "to",
            message_text,
            message_timestamp
        FROM messages
    ) t
    GROUP BY
        t."from",
        t."to"
) m2
    ON MIN(m1."from", m1."to") = m2."from" AND
       MAX(m1."from", m1."to") = m2."to"   AND
       m1.message_timestamp  = m2.max_ts
ORDER BY m1.message_timestamp DESC;
</code>```

Note: Please don't use SQL keywords like from and to when naming your columns (or tables, or databases).  I needed to escape from in double quotes to get the query to work.

Output:

Demo here:

Rextester

(The demo is in MySQL since Rextester does not support SQLite.  The only difference is that MIN is replaced by LEAST, and the columns are escaped slightly differently.)

Title: Sqlite 3 select statemen

Body:
I need to do a somewhat complex select in sqlite3 if you guys can help me?

I got a 'messages' table holding the following fields:

from | to | message_text | message_timestamp

and the rows:

a | b | Hi | 101
a | b | How are you? | 103
b | a | Fine,thanks | 104
c | a | Hey dude! | 115
a | b | I need to tell you something. | 1102
d | b | Yo dude | 1234
b | d | Yea dude, whatsup? | 1443

I'd like to select the last messages from the above conversation in chronologic order by disregarding if the message was sent form x to y or form y to x, the xy or yx pair should be taken into account. So for the example above, you'd get something like this:

b | d | Yea dude, whatsup? | 1443
a | b | I need to tell you something. | 1102
c | a | Hey dude! | 115

Thanks!!

Body:
One trick which works here to use the scalar min/max trick to collect records sharing the same from/to or to/from pairs into the same logical group.  In the query below, the innermost subquery buckets would collect, for example, from b to d into the same bucket as from d to b.  Then we aggregate over this to find the latest timestamp, and finally join back to your original table to retrieve the entire rows you want.

SELECT
    m1.*
FROM messages m1
INNER JOIN
(
    SELECT
        t."from",
        t."to",
        MAX(t.message_timestamp) AS max_ts
    FROM
    (
        SELECT
            MIN("from", "to") AS "from",
            MAX("from", "to") AS "to",
            message_text,
            message_timestamp
        FROM messages
    ) t
    GROUP BY
        t."from",
        t."to"
) m2
    ON MIN(m1."from", m1."to") = m2."from" AND
       MAX(m1."from", m1."to") = m2."to"   AND
       m1.message_timestamp  = m2.max_ts
ORDER BY m1.message_timestamp DESC;

Note: Please don't use SQL keywords like from and to when naming your columns (or tables, or databases).  I needed to escape from in double quotes to get the query to work.

Output:

Demo here:

Rextester

(The demo is in MySQL since Rextester does not support SQLite.  The only difference is that MIN is replaced by LEAST, and the columns are escaped slightly differently.)


问:
Data check between source and the target as per transformation rule
I have two tables one is source and the other is target.

I need to check if the data is properly transformed according to the transformation logic or not.

Here is the source table:EmpIn

```<code>empid year  quarter  amount
5     2007    q1       100
5     2007    q2       200
5     2007    q3       300
5     2007    q3       100
5     2007    q4       50
5     2007    q4       100
5     2007    q4       150
</code>```

Target table after the transformation:EmpOut

```<code>empid   year   quarter   amount    sequence number
 5      2007     q1       100          0
 5      2007     q2       200          0
 5      2007     q3       300          0
 5      2007     q3       400          1
 5      2007     q4       50           0
 5      2007     q4       150          1
 5      2007     q4       300          2
</code>```

Transformation logic is : If there is another entry of amount with respect to same quarter and the same year
                          the amount will be addded to the previous amount and the sequence number will be increased by 1 in the target.

for example in the source table in 2007 q3 we have two amounts the first one is 300 it will go as is to the target with sequence number
of zero
the next entry is a addition to the previous amount which is 400 and the sequence number is incresed by 1.
the same transformation is happening to the fourth quarter also

We(I) need to validate if the data is properly transformed according to this logic to the target table or not.

答:
```<code>/*Creating dataset*/
create table #tmp1 (empid int, year int,  quarter  varchar(25), amount int)
Insert into #tmp1
select 5,2007,'q1',100 union
select 5,2007,'q2',200 union
select 5,2007,'q3',300 union
select 5,2007,'q3',100 union
select 5,2007,'q4',50  union
select 5,2007,'q4',100 union
select 5,2007,'q4',150

/*Intermediate dataset*/
select
    ROW_NUMBER() over(partition by empid,quarter order by amount) as ID
    ,*
Into
    #tmp2
from
    #tmp1 order by 2,3,4

/*Desired output dataset*/
select
     a.empid
    ,a.year
    ,a.quarter
    ,sum(b.amount)
    , a.ID-1 as [sequence number]
from #tmp2 a , #tmp2 b
where
    a.empid=b.empid
and
    a.year=b.year
and
    a.quarter=b.quarter
and
    a.ID>=b.ID
group by
    a.ID,
    a.empid,
    a.year,
    a.quarter,
    a.amount
Order By 2,3,4,1
</code>```

Body:
I have two tables one is source and the other is target.

I need to check if the data is properly transformed according to the transformation logic or not.

Here is the source table:EmpIn

empid year  quarter  amount
5     2007    q1       100
5     2007    q2       200
5     2007    q3       300
5     2007    q3       100
5     2007    q4       50
5     2007    q4       100
5     2007    q4       150

Target table after the transformation:EmpOut

empid   year   quarter   amount    sequence number
 5      2007     q1       100          0
 5      2007     q2       200          0
 5      2007     q3       300          0
 5      2007     q3       400          1
 5      2007     q4       50           0
 5      2007     q4       150          1
 5      2007     q4       300          2

Transformation logic is : If there is another entry of amount with respect to same quarter and the same year
                          the amount will be addded to the previous amount and the sequence number will be increased by 1 in the target.

for example in the source table in 2007 q3 we have two amounts the first one is 300 it will go as is to the target with sequence number
of zero
the next entry is a addition to the previous amount which is 400 and the sequence number is incresed by 1.
the same transformation is happening to the fourth quarter also

We(I) need to validate if the data is properly transformed according to this logic to the target table or not.


问:
How to use a CA (like curl's --cacert) with HTTPie
In curl I can connect with a private key, client cert, and a ca cert like this

```<code>curl --cert cert.pem --key key.pem --cacert ca.pem https://example.org
</code>```

I can see the --cert and --cert-key options in HTTPie, but how could I use the --cacert option in HTTPie?

I tried combining cert.pem and ca.pem in a new file and using that as my --cert file, but that didn't work.

答:
I got it. In HTTPie you just pass the ca.pem using --verify like this</p>

```<code>http --cert cert.pem --cert-key key.pem --verify ca.pem http://example.org
</code>```

Body:
In curl I can connect with a private key, client cert, and a ca cert like this

curl --cert cert.pem --key key.pem --cacert ca.pem https://example.org

I can see the --cert and --cert-key options in HTTPie, but how could I use the --cacert option in HTTPie?

I tried combining cert.pem and ca.pem in a new file and using that as my --cert file, but that didn't work.

Body:
I got it. In HTTPie you just pass the ca.pem using --verify like this

http --cert cert.pem --cert-key key.pem --verify ca.pem http://example.org


问:
Is it possible that I request an EC2 instance but can't get fulfilled?
Edit: This question is NOT to ask about "Spot Instances"; this question is to ask regular "On Demand Instance". I think I need to clarify this, after reading comments below.

Basically, my question is about whether I should consider the risk that when I need to launch an EC2 instance, but that EC2 region has run out of capacity and can't fulfill my request.

I understand the chance for the above situation is extremely low, but I'd like to understand if AWS has any SLA to make sure that situation/risk won't happen.

答:
Yes. It is possible your instance request cannot be fulfilled. On-Demand instance does not guarantee you an instance. In particular,t2.small instances are more likely to be not fulfilled based on my experience. It is possible, AWS has only limited number of t2.small instances.

How can you make sure it is always fulfilled?

Reserve the instances for you so that it is not given to anyone else. But there is a cost associated with it. You have pay for the instance irrespective of whether you use it not. I am talking in general terms. Reserved instance is a complex topic, but that is the route you should take if you want AWS to guarantee you an instance.


问:
retrieve sql query from cakephp finder method
I'm creating a behavior that log to a table the sql query executed by a particular Model in a controller. Looking for a method to return me the sql query executed for a particular finder method (like $this->MyModel->find('all') ) I found on the bakery that I can use $this->MyModel->find('sql'), but doesn't work for me. Someone knows how can I achieve this?

Thanks in advance

答:
You can put this function in your app_model.php:

```<code>function getLastQueries()
{
    $dbo = $this->getDatasource();
    $logs = $dbo->_queriesLog;

    return $logs;
}
</code>```

And call it from any model ($this->getLastQueries()) or controller ($this->Model->getLastQueries()) to get them.

Body:
You can put this function in your app_model.php:

function getLastQueries()
{
    $dbo = $this->getDatasource();
    $logs = $dbo->_queriesLog;

    return $logs;
}

And call it from any model ($this->getLastQueries()) or controller ($this->Model->getLastQueries()) to get them.


问:
Regex - get string after full date and before standard text
I'm stuck on another regex. I'm extracting email data. In the below example, only the time, date and message in quotes changes.

```<code>Message Received 6:06pm 21st February "Hello. My name is John Smith" Some standard text.
Message Received 8:08pm 22nd February "Hello. My name is "John Smith"" Some standard text.
</code>```

How can I get the message only if I need to start with the positive lookbehind, (?<=Message Received ) to begin searching at this particular point of the data? The message will always start and end with quotes but the user is able to insert their own quotes as in the second example.

答:
Two out of the other three posted answers on this page provide an incorrect result.  None of the other posted answers are as efficient as they could be:

To correctly extract the substring between the outer double quotes, use one of the following patterns:

/Message Received[^"]+"\K[^\n]+(?=")/ (No capture group, takes 132 steps, Demo)

/Message Received[^"]+"([^\n]+)"/ (Capture group, takes 130 steps, Demo)

Both patterns provide maximum accuracy and efficiency using negated character classes leading up to and including the targeted substring.  The first pattern reduces preg_match_all()'s output array bloat by 50% by using \K instead of a capture group.  For these reasons, one of these patterns should be used in your project.  As your input string increases in size, my patterns provide increasingly better performance versus the other posted patterns.

PHP Implementation:

$in represents your input string.

Pattern #1 Method:

```<code>var_export(preg_match_all('/Message Received[^"]+"\K[^\n]+(?=")/',$in,$out)?$out[0]:[]);
// notice the output array only has elements in the fullstring subarray [0]
</code>```

Output:

```<code>array (
  0 => 'Hello. My name is John Smith',
  1 => 'Hello. My name is "John Smith"',
)
</code>```

Pattern #2 Method:

```<code>var_export(preg_match_all('/Message Received[^"]+"([^\n]+)"/',$in,$out)?$out[1]:[]);
// notice because a capture group is used, [0] subarray is ignored, [1] is used
</code>```

Output:

```<code>array (
  0 => 'Hello. My name is John Smith',
  1 => 'Hello. My name is "John Smith"',
)
</code>```

Both methods provide the desired output.

Anirudha's incorrect pattern: /(?<=Message Received)[^"]*(.*)(?=\s+Some standard text)/ (345 steps + a capture group + includes the unwanted outer double quotes)

Josh Crozier's pattern: /Message Received.*?"([^\n]+)"/ (174 steps + a capture group)

Sahil Gulati's incorrect pattern: /(?=Message Received)[^\"]+\K\"[\w\s\"\.]+\"/ (109 steps + includes the unwanted outer double quotes + unnecessarily escapes characters in the pattern)

Body:
I'm stuck on another regex. I'm extracting email data. In the below example, only the time, date and message in quotes changes.

Message Received 6:06pm 21st February "Hello. My name is John Smith" Some standard text.
Message Received 8:08pm 22nd February "Hello. My name is "John Smith"" Some standard text.

How can I get the message only if I need to start with the positive lookbehind, (?<=Message Received ) to begin searching at this particular point of the data? The message will always start and end with quotes but the user is able to insert their own quotes as in the second example.

Body:
Two out of the other three posted answers on this page provide an incorrect result.  None of the other posted answers are as efficient as they could be:

To correctly extract the substring between the outer double quotes, use one of the following patterns:

/Message Received[^"]+"\K[^\n]+(?=")/ (No capture group, takes 132 steps, Demo)

/Message Received[^"]+"([^\n]+)"/ (Capture group, takes 130 steps, Demo)

Both patterns provide maximum accuracy and efficiency using negated character classes leading up to and including the targeted substring.  The first pattern reduces preg_match_all()'s output array bloat by 50% by using \K instead of a capture group.  For these reasons, one of these patterns should be used in your project.  As your input string increases in size, my patterns provide increasingly better performance versus the other posted patterns.

PHP Implementation:

$in represents your input string.

Pattern #1 Method:

var_export(preg_match_all('/Message Received[^"]+"\K[^\n]+(?=")/',$in,$out)?$out[0]:[]);
// notice the output array only has elements in the fullstring subarray [0]

Output:

array (
  0 => 'Hello. My name is John Smith',
  1 => 'Hello. My name is "John Smith"',
)

Pattern #2 Method:

var_export(preg_match_all('/Message Received[^"]+"([^\n]+)"/',$in,$out)?$out[1]:[]);
// notice because a capture group is used, [0] subarray is ignored, [1] is used

Output:

array (
  0 => 'Hello. My name is John Smith',
  1 => 'Hello. My name is "John Smith"',
)

Both methods provide the desired output.

Anirudha's incorrect pattern: /(?<=Message Received)[^"]*(.*)(?=\s+Some standard text)/ (345 steps + a capture group + includes the unwanted outer double quotes)

Josh Crozier's pattern: /Message Received.*?"([^\n]+)"/ (174 steps + a capture group)

Sahil Gulati's incorrect pattern: /(?=Message Received)[^\"]+\K\"[\w\s\"\.]+\"/ (109 steps + includes the unwanted outer double quotes + unnecessarily escapes characters in the pattern)


问:
How to plotted graph save as a JPEG image in C#
I want to save  my plotted graph as a JPEG image by clicking save button.Please give me to help for solving this.this is my plotted grapg look like.

This is code that I used to plotted the graph.

```<code> private void Output_Load(object sender, EventArgs e)
        {

            List<Graph> ObservingData = new List<Graph>(); // List to store all available Graph objects from the CSV

            // Loops through each lines in the CSV
            foreach (string line in System.IO.File.ReadAllLines(pathToCsv).Skip(1)) // .Skip(1) is for skipping header
            {
                // here line stands for each line in the csv file

                string[] InCsvLine = line.Split(',');

                // creating an object of type Graph based on the each csv line

                Graph Inst1 = new Graph();

                Inst1.AvI = double.Parse(InCsvLine[1]);
                Inst1.AvE = double.Parse(InCsvLine[2]);

                chart1.Series["Speed"].YAxisType = AxisType.Primary;
                chart1.Series["Speed"].Points.AddXY(Inst1.Date.AvI, Inst1.AvE);
                chart1.Series["Speed"].ChartType = SeriesChartType.FastLine;

            }
        }
</code>```

This is my part of .csv file data as follows;

```<code>Name,AvI,AvE,Test
Amal,3.28000,100,TRUE
Kamal,3.30000,150,FALSE
Ann,3.32000,200,FALSE
Jery,3.34000,220,FALSE
TaW,3.39000,130,FALSE
Nane,3.40000,125,TRUE
Petter,3.42000,300,TRUE
Sam,3.46000,265,TRUE
Daniyel,3.50000,245,TRUE
Don,3.62000,146,FALSE
Zip,3.64000,201,FALSE
Sera,3.68000,300,FALSE
Perera,3.70000,200,TRUE
Dam,3.90000,170,TRUE
</code>```

答:
Here is an example with using the SaveFileDialog and outputting the chart as a png image.

```<code>private void buttonSave_Click(object sender, EventArgs e)
{
    try
    {
        string path;
        SaveFileDialog sfd = new SaveFileDialog();
        sfd.Filter = "Png Image (.png)|*.png";

        if (sfd.ShowDialog() == DialogResult.OK)
        {
            path = sfd.FileName;

            if (!string.IsNullOrEmpty(path))
            {
                chart1.SaveImage(path, ChartImageFormat.Png);
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}
</code>```

Body:
I want to save  my plotted graph as a JPEG image by clicking save button.Please give me to help for solving this.this is my plotted grapg look like.

This is code that I used to plotted the graph.

 private void Output_Load(object sender, EventArgs e)
        {

            List<Graph> ObservingData = new List<Graph>(); // List to store all available Graph objects from the CSV

            // Loops through each lines in the CSV
            foreach (string line in System.IO.File.ReadAllLines(pathToCsv).Skip(1)) // .Skip(1) is for skipping header
            {
                // here line stands for each line in the csv file

                string[] InCsvLine = line.Split(',');

                // creating an object of type Graph based on the each csv line

                Graph Inst1 = new Graph();

                Inst1.AvI = double.Parse(InCsvLine[1]);
                Inst1.AvE = double.Parse(InCsvLine[2]);

                chart1.Series["Speed"].YAxisType = AxisType.Primary;
                chart1.Series["Speed"].Points.AddXY(Inst1.Date.AvI, Inst1.AvE);
                chart1.Series["Speed"].ChartType = SeriesChartType.FastLine;

            }
        }

This is my part of .csv file data as follows;

Name,AvI,AvE,Test
Amal,3.28000,100,TRUE
Kamal,3.30000,150,FALSE
Ann,3.32000,200,FALSE
Jery,3.34000,220,FALSE
TaW,3.39000,130,FALSE
Nane,3.40000,125,TRUE
Petter,3.42000,300,TRUE
Sam,3.46000,265,TRUE
Daniyel,3.50000,245,TRUE
Don,3.62000,146,FALSE
Zip,3.64000,201,FALSE
Sera,3.68000,300,FALSE
Perera,3.70000,200,TRUE
Dam,3.90000,170,TRUE

Body:
Here is an example with using the SaveFileDialog and outputting the chart as a png image.

private void buttonSave_Click(object sender, EventArgs e)
{
    try
    {
        string path;
        SaveFileDialog sfd = new SaveFileDialog();
        sfd.Filter = "Png Image (.png)|*.png";

        if (sfd.ShowDialog() == DialogResult.OK)
        {
            path = sfd.FileName;

            if (!string.IsNullOrEmpty(path))
            {
                chart1.SaveImage(path, ChartImageFormat.Png);
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}


问:
Scanner scans first line and only the first input of the second line
I'm creating this code where a scanner should scan every word in the text file and then proceed to save each and every one of them in a specific array. But every time the scanner starts to scan it only reaches the next line and stops at the first word. I don't know what is causing this exactly. I'm using a delimiter where it separates words between commas ",".

Here is the piece of code:

```<code>package ex13a;
import java.util.Scanner;
import java.io.*;
/**
 *
 * @author Work
 */
public class Ex13a {
static Scanner scan = new Scanner(System.in);
static int[] number = new int[100];
static String[] f_users = new String[100];
static String[] l_users = new String[100];
static String[] passwd = new String[100];
static int i = 0;
static String fullName;

/**
 * @param args the command line arguments
 * @throws java.io.IOException
 */
public static void main(String[] args) throws IOException {
String path = "C:\\Users\\Work\\Desktop\\users.txt";
File inFile = new File(path);
Scanner inPut = new Scanner(inFile).useDelimiter(",");
Scanner inPut2 = new Scanner(inFile);
while(inPut.hasNext()){
    System.out.println(number[i] = inPut.nextInt());
    System.out.println(f_users[i] = inPut.next());
    System.out.println(l_users[i] = inPut.next());
    System.out.println(passwd[i] = inPut.next());

    i++;

}
</code>```

It throws me that error:

```<code>1
Ahmed
Dhaif
asdf56
Exception in thread "main" java.util.InputMismatchException
2
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at ex13a.Ex13a.main(Ex13a.java:32)
C:\Users\Work\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53:     Java returned: 1
BUILD FAILED (total time: 0 seconds)
</code>```

答:
Grab line by line, then split the lines around the comma, then parse the strings returned.

```<code>Scanner inPut = new Scanner(inFile);
while(inPut.hasNextLine()){
    String [] data = inPut.nextLine().split(",");
    System.out.println(Integer.parseInt(data[0]));
    number[i] = Integer.parseInt(data[0]); //to add to your arrays
    System.out.println(Integer.parseInt(data[1]));
    System.out.println(Integer.parseInt(data[2]));
    System.out.println(Integer.parseInt(data[3]));
    i++;
}
</code>```

Note you should check that the array is the correct size and the string is actually an Integer. You should be able to do that. But this should get you started.

If you are going to store the values in a data structure, use something dynamic and not a data structure of fixed length like an array.

Body:
I'm creating this code where a scanner should scan every word in the text file and then proceed to save each and every one of them in a specific array. But every time the scanner starts to scan it only reaches the next line and stops at the first word. I don't know what is causing this exactly. I'm using a delimiter where it separates words between commas ",".

Here is the piece of code:

package ex13a;
import java.util.Scanner;
import java.io.*;
/**
 *
 * @author Work
 */
public class Ex13a {
static Scanner scan = new Scanner(System.in);
static int[] number = new int[100];
static String[] f_users = new String[100];
static String[] l_users = new String[100];
static String[] passwd = new String[100];
static int i = 0;
static String fullName;

/**
 * @param args the command line arguments
 * @throws java.io.IOException
 */
public static void main(String[] args) throws IOException {
String path = "C:\\Users\\Work\\Desktop\\users.txt";
File inFile = new File(path);
Scanner inPut = new Scanner(inFile).useDelimiter(",");
Scanner inPut2 = new Scanner(inFile);
while(inPut.hasNext()){
    System.out.println(number[i] = inPut.nextInt());
    System.out.println(f_users[i] = inPut.next());
    System.out.println(l_users[i] = inPut.next());
    System.out.println(passwd[i] = inPut.next());

    i++;

}

It throws me that error:

1
Ahmed
Dhaif
asdf56
Exception in thread "main" java.util.InputMismatchException
2
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at ex13a.Ex13a.main(Ex13a.java:32)
C:\Users\Work\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53:     Java returned: 1
BUILD FAILED (total time: 0 seconds)

Body:
Grab line by line, then split the lines around the comma, then parse the strings returned.

Scanner inPut = new Scanner(inFile);
while(inPut.hasNextLine()){
    String [] data = inPut.nextLine().split(",");
    System.out.println(Integer.parseInt(data[0]));
    number[i] = Integer.parseInt(data[0]); //to add to your arrays
    System.out.println(Integer.parseInt(data[1]));
    System.out.println(Integer.parseInt(data[2]));
    System.out.println(Integer.parseInt(data[3]));
    i++;
}

Note you should check that the array is the correct size and the string is actually an Integer. You should be able to do that. But this should get you started.

If you are going to store the values in a data structure, use something dynamic and not a data structure of fixed length like an array.


问:
session_start() at the top, but still cannot send session cache limiter - headers already sent
Cant understand why Im still having this warning. My session_start() starts at the top of the page. I look all the previous post and they all said that my session_start() is at the wrong position. Is this warning occurring because of using session superglobal?

ERROR

```<code>Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /home/xxx/xxx/xxx/login/logout.php:1) in /home/xxx/xxx/xxx/login/config.php on line 3

Warning: Cannot modify header information - headers already sent by (output started at /home/xxx/xxx/xxx/login/logout.php:1) in /home/xxx/xxx/xxx/login/logout.php on line 8`
</code>```

Config.php

```<code> <?php
    session_start();
    //error_reporting(0);

    /* Andmebaasi konfiguratsioon */
    define('DB_SERVER', 'localhost');
    define('DB_USERNAME', 'xxx');
    define('DB_PASSWORD', 'xxx');
    define('DB_DATABASE', 'xxx');
    define("BASE_URL", "http://www.xxx.ee/xxx/"); // Määrame ära alus urli, et oleks lihtsam linkida lehti

    function getDB()
    {
        $dbhost=DB_SERVER;
        $dbuser=DB_USERNAME;
        $dbpass=DB_PASSWORD;
        $dbname=DB_DATABASE;
        try {
        $dbConnection = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);  //Loo ühendus andmebaasiga
        $dbConnection->exec("set names utf8"); //Teeb tähed utf8 formaati
        $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //Seadistab veamoodi
        return $dbConnection; //Tagastab andmebaasi väärtuse
        }
        catch (PDOException $e) {
        echo 'Connection failed: ' . $e->getMessage(); //Teatab et funktsioon ei õnnestunud tänu veale
        }

    }
    ?>
</code>```

Logout.php

```<code>     <?php
    require_once('config.php'); // Kaasame configu faili
    $session_uid=''; // Muutja sessioon id võrdub tühi väärtus ehk NULL
    $_SESSION['uid']='';   // Sessiooni id võrdub tühi väärtus ehk NULL
    if(empty($session_uid) && empty($_SESSION['uid'])) //Kui sesioonid väärtused on tühjad, siis...
    { //Toimub välja logimine, sest sessiooni muutjad on tühjad
    $url='index.php';
    header("Location: $url"); // URLi suunamine

    }
?>
</code>```

Also I echo my logout.php link in index.php

```<code> <?php  if(empty($_SESSION['uid']))
{echo '<li class="nav_li" style="float:right"><a id="login_button">Logi sisse</a></li>
<li class="nav_li" style="float:right"><a id="register_button">Registeeru</a>';}
        else{echo'<li class="nav_li" style="float:right"><a href="'. BASE_URL.'login/logout.php">Logout</a></li>';}?>
</code>```

答:
You can not generate output before sending headers.
In your code you thought you are not generating any output but you do in an unintentional way: whitespace before <?php or after ?> are considered as output.

Body:
Cant understand why Im still having this warning. My session_start() starts at the top of the page. I look all the previous post and they all said that my session_start() is at the wrong position. Is this warning occurring because of using session superglobal?

ERROR

Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /home/xxx/xxx/xxx/login/logout.php:1) in /home/xxx/xxx/xxx/login/config.php on line 3

Warning: Cannot modify header information - headers already sent by (output started at /home/xxx/xxx/xxx/login/logout.php:1) in /home/xxx/xxx/xxx/login/logout.php on line 8`

Config.php

 <?php
    session_start();
    //error_reporting(0);

    /* Andmebaasi konfiguratsioon */
    define('DB_SERVER', 'localhost');
    define('DB_USERNAME', 'xxx');
    define('DB_PASSWORD', 'xxx');
    define('DB_DATABASE', 'xxx');
    define("BASE_URL", "http://www.xxx.ee/xxx/"); // Määrame ära alus urli, et oleks lihtsam linkida lehti

    function getDB()
    {
        $dbhost=DB_SERVER;
        $dbuser=DB_USERNAME;
        $dbpass=DB_PASSWORD;
        $dbname=DB_DATABASE;
        try {
        $dbConnection = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);  //Loo ühendus andmebaasiga
        $dbConnection->exec("set names utf8"); //Teeb tähed utf8 formaati
        $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //Seadistab veamoodi
        return $dbConnection; //Tagastab andmebaasi väärtuse
        }
        catch (PDOException $e) {
        echo 'Connection failed: ' . $e->getMessage(); //Teatab et funktsioon ei õnnestunud tänu veale
        }

    }
    ?>

Logout.php

     <?php
    require_once('config.php'); // Kaasame configu faili
    $session_uid=''; // Muutja sessioon id võrdub tühi väärtus ehk NULL
    $_SESSION['uid']='';   // Sessiooni id võrdub tühi väärtus ehk NULL
    if(empty($session_uid) && empty($_SESSION['uid'])) //Kui sesioonid väärtused on tühjad, siis...
    { //Toimub välja logimine, sest sessiooni muutjad on tühjad
    $url='index.php';
    header("Location: $url"); // URLi suunamine

    }
?>

Also I echo my logout.php link in index.php

 <?php  if(empty($_SESSION['uid']))
{echo '
Logi sisse

Registeeru';}
        else{echo'
Logout
';}?>


问:
Is a field of a temporary object an rvalue?
This code compiles successfully under Clang 3.8, GCC 6.3 and VS2013 but fails under Clang 4.0:

```<code>struct Foo {
  int x[2];
  Foo() {
    x[0] = 3; // line A: works fine - we can assign to x[0]
    *&x[0] = 4; // line B: works fine - we can take the address of x[0]
  }
};

int main() {
  Foo().x[0] = 5; // line C: error: expression is not assignable
  *(Foo().x + 0) = 6; // line D: works fine
}
</code>```

Which compiler is correct? Is Foo().x[0] an rvalue or an lvalue?

Lines A and B work on all the compilers, and x[0] is definitely an lvalue there, and lines A and B are surely referencing the same x as line C, so it seems like Foo().x[0] ought to be an lvalue. But maybe the rvalue-ness of Foo() propagates to all its fields when accessed in such a way?

Also consider line D, which works on all the compilers. I thought bar[n] was basically just syntactic sugar for *(bar + n) (for arrays) so it seems strange for line D to work but line C to fail.

答:
Foo().x[0] was an lvalue in C++11. In C++11, the result of the built-in subscript operator is always an lvalue, since it involves dereferencing a pointer.

In C++14, the behaviour of the built-in subscript operator was changed:

If a is an lvalue, then a[i] is an lvalue.

Otherwise, a[i] is an xvalue.

Foo() is a prvalue, so accessing a non-static member yields an xvalue. Since Foo.x is an xvalue, Foo.x[0] is also an xvalue and cannot be assigned to.

Body:
This code compiles successfully under Clang 3.8, GCC 6.3 and VS2013 but fails under Clang 4.0:

struct Foo {
  int x[2];
  Foo() {
    x[0] = 3; // line A: works fine - we can assign to x[0]
    *&x[0] = 4; // line B: works fine - we can take the address of x[0]
  }
};

int main() {
  Foo().x[0] = 5; // line C: error: expression is not assignable
  *(Foo().x + 0) = 6; // line D: works fine
}

Which compiler is correct? Is Foo().x[0] an rvalue or an lvalue?

Lines A and B work on all the compilers, and x[0] is definitely an lvalue there, and lines A and B are surely referencing the same x as line C, so it seems like Foo().x[0] ought to be an lvalue. But maybe the rvalue-ness of Foo() propagates to all its fields when accessed in such a way?

Also consider line D, which works on all the compilers. I thought bar[n] was basically just syntactic sugar for *(bar + n) (for arrays) so it seems strange for line D to work but line C to fail.


问:
jquery/javascript/unix graphing, sub categories on x axis
I was wondering what tool/package I can use to create a graph that can put multiple sub categories on x axis. This is very similar to a feature in excel graphs.

For example:

```<code>Apple| Oranges| WaterMelon | Bittermelon | Cucumbers | Lotus Root
    Fruits                 |       Vegetables
</code>```

答:
jqPlot is a jQuery plugin that can do grouping.

This code will generate the following image:

```<code>$(document).ready(function(){
    $.jqplot.config.enablePlugins = true;

    var line1 = [20, 10, 20, 30, 40, 50];
    var xticks = ['Apples', 'Oranges', 'Watermelons', 'Bittermelon', 'Cucumbers', 'Lotus Root'];
    var plot1 = $.jqplot('chart1', [line1], {
        seriesDefaults:{
            renderer:$.jqplot.BarRenderer,
            rendererOptions: {
                groups: 2,
            }
        },
        axes:{
            xaxis:{
                renderer:$.jqplot.CategoryAxisRenderer,
                ticks: xticks,
                rendererOptions: {
                    groupLabels:['Fruits', 'Vegetables']
                }
            }
        }
    });

});
</code>```

Body:
I was wondering what tool/package I can use to create a graph that can put multiple sub categories on x axis. This is very similar to a feature in excel graphs.

For example:

Apple| Oranges| WaterMelon | Bittermelon | Cucumbers | Lotus Root
    Fruits                 |       Vegetables

Body:
jqPlot is a jQuery plugin that can do grouping.

This code will generate the following image:

$(document).ready(function(){
    $.jqplot.config.enablePlugins = true;

    var line1 = [20, 10, 20, 30, 40, 50];
    var xticks = ['Apples', 'Oranges', 'Watermelons', 'Bittermelon', 'Cucumbers', 'Lotus Root'];
    var plot1 = $.jqplot('chart1', [line1], {
        seriesDefaults:{
            renderer:$.jqplot.BarRenderer,
            rendererOptions: {
                groups: 2,
            }
        },
        axes:{
            xaxis:{
                renderer:$.jqplot.CategoryAxisRenderer,
                ticks: xticks,
                rendererOptions: {
                    groupLabels:['Fruits', 'Vegetables']
                }
            }
        }
    });

});


问:
VB6: ShellExecute an EXE inside AppData
I have the following sub:

```<code>Public Sub ShellApp(URL As String)

        Dim vResult As Long
        vResult = ShellExecute(0, "open", URL, vbNullString, vbNullString, vbMinimizedFocus)

   End If
End Sub
</code>```

This is on a layer that cannot be changed due to several functionality needed on that sub.

Now, on our Main() sub for example, we check a list of added plugins saved in a text file beside the EXE, and call the above Sub in for loop with the path of the plugins to run them. So if I have 3 plugins as below in the text file:

C:\App1.EXE

C:\App2.EXE

C:\Users\AhmadMusa\AppData\Roaming\App3.exe

First two apps will run fine on all PCs (Static path), but third app will not work on any PC except mine which is not ok... Note that App3 always installed on AppData on any PC, so how to dynamically access it to run the app from any PC without adjustments on the sub.

What will be the path placed in the text file for third app so it can work on all PCs?

I tried (AppData\Roaming\App3.exe) but it does not work... I found on a thread (http://www.vbforums.com/showthread.php?529776-RESOLVED-Open-a-folder-in-AppData) that I can call something like (shell:AppData\Roaming\App3.exe) it did not work to run the App3.exe, but if I call (shell:AppData\Roaming) it will open the Roaming folder very well. But cannot run the EXE.

Any ideas ?

Thanks.

答:
```<code>sub test()
    dim tmp as string
    tmp = environ("AppData ") & "\calc.exe"

    call  ShellExecute(..., tmp, ...)
end sub
</code>```

fill the other arguments (...) the way you see it right

Title: VB6: ShellExecute an EXE inside AppData

Body:
I have the following sub:

Public Sub ShellApp(URL As String)

        Dim vResult As Long
        vResult = ShellExecute(0, "open", URL, vbNullString, vbNullString, vbMinimizedFocus)

   End If
End Sub

This is on a layer that cannot be changed due to several functionality needed on that sub.

Now, on our Main() sub for example, we check a list of added plugins saved in a text file beside the EXE, and call the above Sub in for loop with the path of the plugins to run them. So if I have 3 plugins as below in the text file:

C:\App1.EXE

C:\App2.EXE

C:\Users\AhmadMusa\AppData\Roaming\App3.exe

First two apps will run fine on all PCs (Static path), but third app will not work on any PC except mine which is not ok... Note that App3 always installed on AppData on any PC, so how to dynamically access it to run the app from any PC without adjustments on the sub.

What will be the path placed in the text file for third app so it can work on all PCs?

I tried (AppData\Roaming\App3.exe) but it does not work... I found on a thread (http://www.vbforums.com/showthread.php?529776-RESOLVED-Open-a-folder-in-AppData) that I can call something like (shell:AppData\Roaming\App3.exe) it did not work to run the App3.exe, but if I call (shell:AppData\Roaming) it will open the Roaming folder very well. But cannot run the EXE.

Any ideas ?

Thanks.

Body:
sub test()
    dim tmp as string
    tmp = environ("AppData ") & "\calc.exe"

    call  ShellExecute(..., tmp, ...)
end sub

fill the other arguments (...) the way you see it right