text:
Q: Save in a google sheet the modifications of the events of my google calendar in a google apps script, I have created a trigger that is triggered when an event in the calendar is modified. With the following script, I manage to write in the google sheet the modification date but I would like to have the event id as well.
function recordModification() {
  var calendarID = 'xxx@gmail.com';

  var calendar = CalendarApp.getCalendarById(calendarID);
  var lastModifiedEventId="???";
  var sheet = SpreadsheetApp.getActiveSheet();
  var now=new Date();
  sheet.appendRow([now, lastModifiedEventId]);
}

I found variable triggerUid in https://developers.google.com/apps-script/guides/triggers/events#eventupdated but I don't know how to use it.

A: I believe your goal as follows.

*

*You want to retrieve the event ID of latest updated event in Google Calendar.

*Your function recordModification can be executed by the trigger when the event is updated.

*When the existing event is modified, you want to put the date object and the event ID to the Spreadsheet.

In this case, I would like to propose the following flow.

*

*Retrieve the event list of all events from the calendar.

*Sort the event list with the updated time.

*Check whether the event is modified.

*Put the date object and the event ID to the Spreadsheet.

Sample script:
In this script, Calendar API is used. So, before you use this script, please enable Calendar API at Advances Google Services.
function recordModification() {
  var calendarID = 'xxx@gmail.com';
  var now = new Date();

  // 1. Retrieve the event list of all events from the calendar.
  var eventList = [];
  var pageToken = "";
  do {
    var events = Calendar.Events.list(calendarID, { maxResults: 2500, pageToken: pageToken });
    if (events.items.length > 0) eventList = eventList.concat(events.items);
    pageToken = events.nextPageToken;
  } while (pageToken);
  if (eventList.length == 0) return;

  // 2. Sort the event list with the updated time.
  eventList.sort((a, b) => new Date(a.updated).getTime() < new Date(b.updated).getTime() ? 1 : -1);

  // 3. Check whether the event is modified.
  var updated = new Date(eventList[0].updated);
  var created = new Date(eventList[0].created);
  if (updated.toString() == created.toString() || updated.getTime() < now.getTime() - (3 * 60 * 1000)) {

    // In this case, the event is not updated. The event is created.
    // When you want to process for this situation, please put the script here.
    console.log("Event is not updated. Event was created and/or others.")

  } else {

    // 4. Put the date object and the event ID to the Spreadsheet.
    var lastModifiedEventId = eventList[0].id + "@google.com";
    var sheet = SpreadsheetApp.getActiveSheet();
    sheet.appendRow([now, lastModifiedEventId]);
  }
}

*

*In this script, from your question, when the existing event is modified, the values are put to the Spreadsheet. Even when the event is created, the values are not put to Spreadsheet. If you want to also run this when the event is created, please modify the script as follows.
  function recordModification() {
    var calendarID = 'xxx@gmail.com';
    var now = new Date();

    // 1. Retrieve the event list of all events from the calendar.
    var eventList = [];
    var pageToken = "";
    do {
      var events = Calendar.Events.list(calendarID, { maxResults: 2500, pageToken: pageToken });
      if (events.items.length > 0) eventList = eventList.concat(events.items);
      pageToken = events.nextPageToken;
    } while (pageToken);
    if (eventList.length == 0) return;

    // 2. Sort the event list with the updated date.
    eventList.sort((a, b) => new Date(a.updated).getTime() < new Date(b.updated).getTime() ? 1 : -1);

    // 3. Put the date object and the event ID to the Spreadsheet.
    var lastModifiedEventId = eventList[0].id + "@google.com";
    var sheet = SpreadsheetApp.getActiveSheet();
    sheet.appendRow([now, lastModifiedEventId]);
  }

Note:

*

*In this script, as the event ID, ###@google.com is used. If you are required to use only ### of ###@google.com, please modify above script.

*In this script, in order to check whether the event is modified, the created time and updated time are compared. For this, when the function is run, the event created within 3 minutes is retrieved. About this, when you want to modify this, please modify (3 * 60 * 1000) of above script.

*When the trigger doesn't work, please install it again.

Reference:

*

*Events: list


text:
Q: How to rename existing styles in CKEditor? In my webpage we'll only allow users to use H3 and H4, but it's confusing to see these as "Title 3" and "Title 4". I wanted to rename these as "Title" and "Subtitle", but setting format_h3.name doesn't seem to affect that.
I can't write custom JS to configure the editor as I'm using a Django Plugin, that actually converts a python dictionary into the final JSON config used.
The relevant part of what I tried is as follows:
CKEDITOR_CONFIGS = {
    'default': {
        'allowedContent': 'h3 h4 p b i u a[*]',
        'format_p': {'name': 'Standard text', 'element': 'p'},
        'format_h3': {'name': 'Title', 'element': 'h3'},
        'format_h4': {'name': 'Subtitle', 'element': 'h4'},
        'toolbar': [
            {'name': 'styles', 'items': ['Format']},
            {'name': 'basicstyles', 'items': ['Bold', 'Italic', 'Underline', '-', 'RemoveFormat']},
            {'name': 'links', 'items': ['Link', 'Unlink']},
        ]
    }
}

A: Unfortunately there is no ability to change formats names in CKEditor via configuration. I've filled a feature request for that.
However if you are able to modify editor's files, you could always alter language entries directly, located in plugins/format/lang/<language>.js.
The second workaround is to modify format plugin source, especially init function:
init: function() {
    this.startGroup( lang.panelTitle );

    for ( var tag in styles ) {
        var label = config[ 'format_' + tag ] && config[ 'format_' + tag ].name || lang[ 'tag_' + tag ];

        // Add the tag entry to the panel list.
        this.add( tag, styles[ tag ].buildPreview( label ), label );
    }
}

A: This still isn't solved officially in CKEditor 4, but I did figure this sledgehammer approach out...
CKEDITOR.lang.load('en', 'en', function(lc, data) {
    data.format.tag_p = 'Standard text';
    data.format.tag_h3 = 'Title';
    data.format.tag_h4 = 'Subtitle';
});

According to the manual, the first 'en' is the language code you wish to load, and the second is the fallback language. You need to override the tag in the callback, otherwise you will get errors about the tag not existing.
This sample will change the text for EVERY CKEditor instance on the page you run this. It will also change it for every plugin that uses those translations in said instances.
I haven't found a per instance way of doing this yet.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to find Image (Coding in Atom for Visual Novel Creation in Ren'py Visual Novel Engine) While loading <'Image' u'Volume1.png'>:
  File "game/script.rpy", line 7, in script
    "Welcome."
  File "renpy/common/000window.rpy", line 98, in _window_auto_callback
    _window_show()
  File "renpy/common/000window.rpy", line 60, in _window_show
    renpy.with_statement(trans)
IOError: Couldn't find file 'Volume1.png'.

I get this error when I run this code in Atom. I do have the image on file where it's supposed to be. I'm developing a visual novel in Ren'Py. The language is Python.
This is the code -
image Volume1 = "Volume1.png"

label start:

scene Volume1

"Welcome."

return

A: Assuming you have Volume1.png in the images folder, it should work. Check that name of the image is indeed Volume1 and not volume1, as Ren'Py is pretty picky about upper and lower case.
Test that you can show the image: show Volume1. If the problem persist, rename the file to something else, as VolumeN may be a reserver word.


text:
Q: PHP how to count xml elements in object returned by simplexml_load_file(), I have inherited some PHP code (but I've little PHP experience) and can't find how to count some elements in the object returned by simplexml_load_file()
The code is something like this
$xml = simplexml_load_file($feed);
for ($x=0; $x<6; $x++) {
   $title = $xml->channel[0]->item[$x]->title[0];
   echo "
" . $title . "
\n";
}

It assumes there will be at least 6 <item> elements but sometimes there are fewer so I get warning messages in the output on my development system (though not on live).
How do I extract a count of <item> elements in $xml->channel[0]?

A: Here are several options, from my most to least favourite (of the ones provided).

*

*One option is to make use of the SimpleXMLIterator in conjunction with LimitIterator.
$xml   = simplexml_load_file($feed, 'SimpleXMLIterator');
$items = new LimitIterator($xml->channel->item, 0, 6);
foreach ($items as $item) {
    echo "
{$item->title}
\n";
}

*If that looks too scary, or not scary enough, then another is to throw XPath into the mix.
$xml = simplexml_load_file($feed);
$items = $xml->xpath('/rss/channel/item[position() <= 6]');
foreach ($items as $item) {
    echo "
{$item->title}
\n";
}

*Finally, with little change to your existing code, there is also.
$xml = simplexml_load_file($feed);
for ($x=0; $x<6; $x++) {
    // Break out of loop if no more items
    if (!isset($xml->channel[0]->item[$x])) {
        break;
    }
    $title = $xml->channel[0]->item[$x]->title[0];
    echo "
" . $title . "
\n";
}

A: The easiest way is to use SimpleXMLElement::count() as:
$xml = simplexml_load_file($feed);
$num = $xml->channel[0]->count();
for ($x=0; $x<$num; $x++) {
   $title = $xml->channel[0]->item[$x]->title[0];
   echo "
" . $title . "
\n";
}

Also note that the return of $xml->channel[0] is a SimpleXMLElement object. This class implements the Traversable interface so we can use it directly in a foreach loop:
$xml = simplexml_load_file($feed);
foreach($xml->channel[0] as $item {
   $title = $item->title[0];
   echo "
" . $title . "
\n";
}

A: You get count by count($xml).
I always do it like this:
 $xml = simplexml_load_file($feed);
 foreach($xml as $key => $one_row) {
        echo $one_row->some_xml_chield;
  }


text:
Q: Constructor Formatting c# - PadLeft Property of Class Is there a better way to do what is done in the code that follows?  I added a PadLeft in the constructor because I need the leading zero and 10 characters.  The leading zero is stripped off, for some reason, in my call to the API that returns the "wbd10" value.  I did this the old way, but was just wondering if there is a better way to do this?
public class wqpWBD10
{
    string _wbd10;

    public string WBD10
    {
        get { return _wbd10; }
        set { _wbd10 = value.PadLeft(10, '0'); }
    }
    public string WBD10Name { get; set; }
    public string HUC8 { get; set; }
    public string HUC8Name { get; set; }
}

A: That looks fine. If value = 1234, you'll set 0000001234 to your local variable.
You may want to check that value is not null, or the call to PadLeft will throw an exception.
public string WBD10
{
    get { return _wbd10; }
    set
    {
        if (!String.IsNullOrEmpty(value))
            _wbd10 = value.PadLeft(10, '0');

        // If value is null, take some other action (or do nothing)
    }
}

Also, you're dealing with a property setter. The constructor (which I don't see here) would be:
public wqpWBD10()
{
}


text:
Q: C++: Minimization Using Levenberg Marquardt to Solve for Two Variables I am trying to solve this equation using C++:
X and Y are both given sets of data.
X = [x1, x2, ... , xn], Y = [y1, y2, ... , yn]
a is a given integer.
The goal is to find a pair z and k that fulfills this equation based on the given data.
I am currently attempting to solve this equation using non-linear least squares with the Levenberg Marquardt algorithm and I am using ALGLIB as the library to implement it in C++.
The issue that I am having is that all the examples I see solve for one variable (This one in particular). However, I am trying to find the best pair that fits the solution (z and k).
What would be the best way to go about doing this?
Thanks!


text:
Q: Redirect to category tree page after success I want to redirect administrator to category tree page after success using controller.How can i achieve this
this is my custom module controller method
public function createsamplesAction(){

 $this->_redirect('catalog_category');

}

but it's showing 404

A: Try with
$this->_redirect(Mage::helper('adminhtml')->getUrl('adminhtml/catalog_category'));


text:
Q: SharePoint Search Display Template I am working on Office 365 and I need to fetch Value of Location, Start date and End Date fields (Calendar fields) in Search Display Template (Item_CommonItem_Body.html). But everytime it returns Either null or undefined.
Any suggestions would be much appreciated.

A: I have had issues with these crawled properties not being mapped correctly to Managed Properties by default.  In Site Administration > Search Schema, this is what I have done:

*

*RefinableDate01 – This is a SharePoint provided Managed Property of Type = Date that is provided for configuration.  It should be mapped to the Crawled Properties: "ows_q_DATE_EventDate" and "ows_EventDate".  This is the Start Date field in a Calendar.

*RefinableDate02 - This is another SharePoint provided Managed Property of Type = Date that is provided for configuration.  It should be mapped to the Crawled Properties: "ows_q_DATE_EndDate" and "ows_EndDate".  This is the End Date field in a Calendar.
My guess is that you could do the same for Location.  Also make sure that the calendar has been re-indexed after you do your search configuration. I have had to go back into the calendar list settings and under Advanced Settings > Reindex List if the list items have been out there for awhile and are not getting indexed.


text:
Q: window.print() prints multiple copies instead of 1 I have the following CSS code to print a div. The issue is that when printed, it prints duplicates.
@page {

    size: 3in 2in;
    margin: 0mm;
}

@media print {
      .printDiv{
        background-color: rgb(5, 3, 3);
        height: 100%;
        width: 100%;
        position: fixed;
        top: 0;
        left: 0;
        margin: 0;
        line-height: 18px;
        border: 11px solid #000000;

    }
}

Sample HTML Code:

                        1
                        2
                        3
                        4

                        1
                        2
                        3
                        4

                        1
                        2
                        3
                        4

                        1
                        2
                        3
                        4

Sample Image:
I tried out the following solution but it did not work: Solution
Any help as to why this issue occurs and how to fix it would be great.
Thank you.


text:
Q: Dynamic JQUERY array works for some records Thanks to the help from StackOverflow I have got as far as creating a single line entry with fields and then this adds each field to an array but the Hours SQL statement isn't working e.g. it will have blank sql entries for the first 2 records and then work correctly on another but I cannot see what I am doing wrong. Any help would be very appreciated.

 Hours Labour :

 Start Time:
          <input type="time" name="add_start" size="4" />
          Finish Time:
          <input type="time" name="add_finish" size="4" />
          Date:
          <input type="date" name="add_date" size="4" />
          OVT:
          <input type="checkbox" name="add_overtime_hours" id="add_overtime_hours" size="1" maxlength="1" />

        <input onclick="addhours(this, event);" type="button" value="Add Labour" />

          (This row will not be saved unless you click on "Add Labour" first)

var rownumhours = 1;

function addhours(obj, e) {
  rownumhours++;
  var hoursrow = '
Start Time: <input type="time" name="add_start[' + rownumhours + ']" size="4" value="' +
  $(obj).closest('span.headings').find('[name="add_start"]').val() + '">  Finish Time: <input type="time" name="add_finish[' + rownumhours + ']" value="' +
  $(obj).closest('span.headings').find('[name="add_finish"]').val() + '"> Date: <input type="date" name="add_date[' + rownumhours + ']" value="' +
  $(obj).closest('span.headings').find('[name="add_date"]').val() + '"> Show_Overtime: <input type="text" name="show_overtime_hours[' + rownumhours + ']" size="1" value="' +
  (($(obj).closest('span.headings').find('[name="add_overtime_hours"]').is(':checked')) ? '1' : '0' ) + '"> Overtime: <input type="checkbox" name="add_overtime_hours[' + rownumhours + ']" size="1" value="'                       +
  $(obj).closest('span.headings').find('[name="add_overtime_hours"]').val() + '"' +
      (($(obj).closest('span.headings').find('[name="add_overtime_hours"]').is(':checked')) ? 'checked' : '') +
  ' "> <input type="button" value="Remove" onclick="removeRow(' +
      rownumhours + ');">
';
  jQuery('#hoursrow').append(hoursrow);

    $(obj).closest('span.headings').find('[name="add_start"]').val("");
    $(obj).closest('span.headings').find('[name="add_finish"]').val("");
    $(obj).closest('span.headings').find('[name="add_date"]').val("");
    $(obj).closest('span.headings').find('[name="show_overtime_hours"]').val("");
        $(obj).closest('span.headings').find('[name="add_overtime_hours"]').removeAttr('checked');
 }
function removeRow(rnum) {
  jQuery('#rownumhours' + rnum).remove();
}

So it is showing on the page properly as I want it to but then the major problem is is won't add properly to the database.
I have echo'd the sql that is to be inserted into the database and it shows the following.
INSERT INTO hours(job_number,start_time,finish_time,date,overtime)
       VALUES('904','','','','')
INSERT INTO hours(job_number,start_time,finish_time,date,overtime)
       VALUES('904','','','','')
INSERT INTO hours(job_number,start_time,finish_time,date,overtime)
       VALUES('904','10:10','11:11','2017-01-03','') //

The Sql part is as follows
        if (
                 !empty($_POST['add_start']) && !empty($_POST['add_finish']) && !empty($_POST['add_date']) && !empty($_POST['show_overtime_hours'])&&
                 is_array($_POST['add_start']) && is_array($_POST['add_finish']) && is_array($_POST['add_date']) && is_array($_POST['show_overtime_hours'])&&
                count($_POST['show_overtime_hours']) && count($_POST['add_finish']) && count($_POST['add_date']) === count($_POST['add_start'])
                ) {
                $add_start_array = $_POST['add_start'];
                $add_finish_array = $_POST['add_finish'];
                $add_overtime_hours_array = $_POST['show_overtime_hours'];
                $add_date_array =$_POST['add_date'];
                     for ($i = 0; $i < count($add_start_array); $i++) {
                        $add_start_values = $mysqli->real_escape_string($add_start_array[$i]);
                        $add_finish_values = $mysqli->real_escape_string($add_finish_array[$i]);
                        $add_date_values = $mysqli-> real_escape_string($add_date_array[$i]);
                        $add_overtime_hours_boolean = $mysqli-> real_escape_string($add_overtime_hours_array[$i]);
                        $sql_add_hours = "INSERT INTO hours(job_number,start_time,finish_time,date,overtime) VALUES('$increment_job_number','$add_start_values','$add_finish_values','$add_date_values','$add_overtime_hours_boolean')";

                        $mysqli-> query($sql_add_hours);
                        // This next section is for debugging only
                        //echo ($add_date_values);
                        //echo ($add_start_values);
                        //echo ($add_finish_values);
                        echo ($sql_add_hours);
                        //echo ($add_overtime_hours_values);

                }

A: Ok, after doing some inspections, actually the first group of the html  components produced from the JQuery is :
"Start Time:"
<input type="time" name="add_start[2]" size="4" value="23:57">
"Finish Time:"
<input type="time" name="add_finish[2]" size="4" value="22:57">
"Date:"
<input type="date" name="add_date[2]" value="2017-01-13">
"Show_overtime:"
<input type="text" name="show_overtime_hours[2]" size="1" value="0">
"Overtime:"
<input type="checkbox" name="add_overtime_hours[2]" size="1" value="on">
<input type="button" value="Remove" onclick="removeRow(2)">

You see there...,the counter (rownumhours) starts from 2.
Thus in your php part, the first entries for these array :
$add_start_array = $_POST['add_start'];
$add_finish_array = $_POST['add_finish'];
$add_overtime_hours_array = $_POST['show_overtime_hours'];
$add_date_array =$_POST['add_date'];

Also at 2nd-index, but as your loop starts from zero , hence the entry for the location is empty.
So start the  rownumhours in javascript part from  -1:
var rownumhours = -1;

A: Quick Fix
You increment the rownumhours before dynamically adding a new row of fields.
The quickest fix is change the rownumhours value to 0
var rownumhours = 0;

So the newly added row of fields will have the index of 1 and up.
Also add [] to the name tag to the first/default row:
<input type="time" name="add_start[]" size="4">

Recommendation
But what you can actually do is do not bother with the assigning of index.
Just put [] to the given row of fields:

                Hours Labour :

                            Start Time: <input type="time" name="add_start[]" size="4" />
                            Finish Time: <input type="time" name="add_finish[]" size="4" />
                            Date: <input type="date" name="add_date[]" size="4" />
                            OVT: <input type="checkbox" name="add_overtime_hours[]" id="add_overtime_hours" size="1" maxlength="1" />

                            <input onclick="addhours(this, event);" type="button" value="Add Labour" />

                        (This row will not be saved unless you click on "Add Labour" first)

Then remove the rownumhours and do not assign index for dynamically added input fields:
var hoursrow = '
Start Time: <input type="time" name="add_start[]" size="4" value="' +  $(obj).closest('span.headings').find('[name="add_start"]').val() + '"> /*** JUST CONTINUE THE REST OF THE INPUT FIELDS ***/

A: Thank you all so very much for the help. I am sorry It took a few days to reply. I have made the changes by taking the rownumhours ++ off and using the [] for the naming to be taken care of itself which I had no idea it was clever enough to do it on its own.
The Mysql Section worked well and I also left the html section because I only wanted to have different names for the multiple hours into the entries

 var rownumhours = 0;

 function addhours(obj, e) {
  var hoursrow = '
Start Time: <input type="time" name="add_start[]" size="4" value="' +
  $(obj).closest('span.headings').find('[name="add_start"]').val() + '">  Finish Time: <input type="time" name="add_finish[]" value="' +
  $(obj).closest('span.headings').find('[name="add_finish"]').val() + '"> Date: <input type="date" name="add_date[]" value="' +
  $(obj).closest('span.headings').find('[name="add_date"]').val() + '"> <input type="hidden" name="show_overtime_hours[]" size="1" value="' +
  (($(obj).closest('span.headings').find('[name="add_overtime_hours"]').is(':checked')) ? '1' : '0' ) + '"> Overtime: <input type="checkbox" name="add_overtime_hours[]" size="1" value="'                      +
  $(obj).closest('span.headings').find('[name="add_overtime_hours"]').val() + '"' +
      (($(obj).closest('span.headings').find('[name="add_overtime_hours"]').is(':checked')) ? 'checked' : '') +
  ' "> <input type="button" value="Remove" onclick="removeRow(' +
  rownumhours + ');">
';
  jQuery('#hoursrow').append(hoursrow);
  rownumhours++;

    $(obj).closest('span.headings').find('[name="add_start"]').val("");
    $(obj).closest('span.headings').find('[name="add_finish"]').val("");
    $(obj).closest('span.headings').find('[name="add_date"]').val("");
    $(obj).closest('span.headings').find('[name="show_overtime_hours"]').val("");
    $(obj).closest('span.headings').find('[name="add_overtime_hours"]').removeAttr('checked');
   }
function removeRow(rnum) {
  jQuery('#rownumhours' + rnum).remove();
   }

</script>


text:
Q: Derived Column created in Visual Studio not working in SQL Server I'm working on a package in SSIS to populate a table after some joining and sorting processes.
I've created a Derived Column in Visual Studio to assign 0 to any null value in a column named fraud_flag using the following expression:
ISNULL(FRAUD_FLAG)?0:FRAUD_FLAG.

The package execution works fine when I run it within the Visual Studio and the destination table is properly populated. However, the table is populated with null values whenever I run the package in SQL Server. The values are set to null for the fraud_flag column even when the sources are not null.

A: You can also try using REPLACENULL() function:
REPLACENULL([fraud_flag],0)

and make sure that you are mapping the derived column to the destination


text:
Q: Qt thick database client architecture My goal is to create a thick client to the database. Basically it is all about managing three lists of data.
I would like to slice my application into decoupled layers so using Qt's Model/View framework seems natural to me.

*

*When should I create QSql*Model instances?

I need to be able to connect/disconnect to/from the database several times (I have menu items for that). I'm not happy with deleting a bunch of models and creating them once again upon every connect/disconnect.
Is there any alternative approach?

*

*Where should I create QSql*Model instances?

I don't think MainWindow or any other GUI-related class is supposed to hold the code like this:
m_goodsModel->setRelation(1, QSqlRelation("Level", "LevelId", "Name"));

I want to decouple the GUI from the data structure. Any ideas how to do that?

*

*When and where should I bind my views to models?

I need to represent my three lists in a dozen of ways. If I recreate the models every time I connect/disconnect I will need to inject newly created models into all the views again.
It would be great if I could do that only once, but I have no clue how.

*

*What to do with the nasty QSqlTableModel::select() method?

This one drives me crazy. In contrast to other models (e.g. QStringListModel, QFileSystemModel, etc) where the data is ready to use out of the box, models derived from QSqlTableModel are useless until you manually invoke their select() method. Before that invocation the model is empty so as the views using that model; the header data is not populated either, so the view doesn't even know what columns does it have to render.
As I cannot avoid select() invocation I wonder where should I put it so that it fits nice? I don't think MainWindow or any other GUI-related classes should contain that code.

*

*Performance and robustness

I'm not happy to reinitialize everything upon db reconnection. It takes too long to do that (I mean during execution). I also would like to avoid crashes during model recreation process as the views may still refer to them.
Isn't there any other way to set everything just once and handle reconnection gracefully?

A: It seems to me that the straight forward answer to all of these questions is to wrap all database related actions in a dedicated class, and hold a pointer to an instance of this class in your MainWindow/Dialog/whatever.
A possible design could be something like this:
class DatabaseAccess : public QObject
{
       Q_OBJECT
    public:
       void connectToDatabase(const QString & hostname, const QString & db, const QString & user, const QString & password);
       void disconnectFromDatabse();

       QAbstractItemModel * getModelForX();
       QAbstractItemModel * getModelForY();

    private:
       QSqlTableModel * modelForX;
       QSqlRelationalTableModel * modelForY;
}

Here, X and Y are just placeholders for the types of queries you have in your application.
You can create your models in connectToDatabase() and invoke select() when you need fresh data in the getModelForX/Y methods.
As far as I know, you can't keep using the same model instances with different database connections, as QSqlTableModel and its decedents are bound to a QSqlDatabase instance. You will need to refresh your views after a successful connection.


text:
Q: Как обработать двойной клик по toolstripmenuitem? Добавил на форму notifyicon к нему привязал contextmenustrip, к элементу применил toolstripmenuitem.doubleclick = true; и привязал к нему событие doubleclick которое выводит MessageBox.Show("что-нибудь"); Но по toolstripmenuitem не получается кликнуть 2 раза, после первого клика оно пропадает как бы быстро я не кликал. В чём проблема?

A: Данная опция (toolStripMenuItem1.DoubleClickEnabled = true;) нужна когда есть выпадающее меню, например

Тогда двойной клик уместен и сработает.  (кроме того toolstripmenuitem.doubleclick это событие, свойство было указано выше).
Если же выпадающего меню нет, то нужда в двойном клике отпадает.


text:
Q: Ubuntu Unsafe AuthorizedKeysCommand bad ownership I'm having trouble with creating a user on an AWS Lightsail instance running Ubuntu 20.04.
While attempting to login with the new user, tail -f /var/log/auth.log reports sshd[1713]: error: Unsafe AuthorizedKeysCommand "/usr/share/ec2-instance-connect/eic_run_authorized_keys": bad ownership or modes for directory /
I've switched to the new user using su user-name, and I've set file permissions using these.
sudo chmod 700 ~/.ssh
sudo chmod 600 ~/.ssh/authorized_keys
sudo chown $USER:$USER ~/.ssh -R
ls -l ~/.ssh reports...
-rw------- 1 user-name user-name 397 Oct 19 18:04 authorized_keys
I'm stumped on what else I'm supposed to be doing to diagnose this. The setup looks the same as the other users. I don't know how to continue diagnosing this.


text:
Q: Accessing samba shares over the internet What's a good, secure (ish) way to access a samba server over the internet?
My first thought is to just forward the necessary ports on the router to the samba server, but I'm not sure how secure that would be.
My second thought is to somehow tunnel over ssh.
I tried this for my second thought, but it didn't seem to work.

A: I'd recommend using SSHFS instead - which if you're on a Mac you can just install MacFusion.

A:
My first thought is to just forward the necessary ports on the router to the samba server, but I'm not sure how secure that would be.

That's something you definitely don't want to do. SMB is something you need to protect from the Internet, not expose to it.
I semi-regularly use SMB over a VPN connection and have to agree with Evan that when the latency goes up it's time to use a different protocol. I'd suggest looking into something like SFTP.

A: If you're dealing with a share that's used by multiple clients who can't/won't use other protocols, you can create this setup:
 clients.lan | <--SMB through LAN--> | \\proxy.lan\share
 proxy.lan/share | <--SSHFS through Internet--> | server.in.the.internet/share

In other words, on the remote server (server.in.the.internet), enable SSH;
On a local server (in your network proxy.lan), mount the remote folder through SSHFS
and share this folder on the local server via SMB.
That way, clients in the local network can access the Samba share on proxy.lan, yet it's transparently (for them) proxied from your remote server; you could even set up caching on the proxy so that the access is even faster.

A: You're going to find out that the SMB protocol sucks-like-a-vacuum-cleaner over links that have high latency. You're better off using a different protocol to access the files like, say, WebDAV, rather than trying to run SMB over the 'net.
Whatever you do, use encryption. If you're going to do SMB, use a VPN protocol (OpenVPN, IPSEC ESP, PPTP, etc) to tunnel SMB across. If you're using WebDAV you can just use HTTPS as the transport.

A: It depends somewhat on your environment, intended user base, and client platform.  First thing that comes to my mind is using an openvpn setup of some sort.  Takes a bit of configuring, but it works well once set up properly.

A: Why not use a plain old ftp server. It was meant for things like this.

A: A plain old ftp server prevents you from accessing a file without fully downloading it.
I'm thinking of movies you want to watch across Internet.


text:
Q: Pandas toCSV function deletes data in existing file I just run a python script that writes a dataframe into a csv file. 5 executions of the script (with different arguments) are running at the same time and are writing into the same csv sheet.
I just read the csv file with the pandas read_csv function and realized that some of my data is missing. I had like 2600 1 hour ago and now it is only 1400 rows.
It looks like sth. is going wrong when saving the data frame into the csv..
I just do:
evaluation_df.to_csv('Evaluation_Scen1.csv')

Does anyone know what is going on here?


text:
Q: Embedded ApacheDS 2.0.0-M16 (on 2nd run only): ERR_250_ENTRY_ALREADY_EXISTS ou=system already exists Using this example as base, my embedded ApacheDS server runs fine the first time, then, when I stop the JBoss server on which my app runs and start again, and re-deploy, the log returns a load of errors starting with:
'(ERROR [stderr] (MSC service thread 1-1) org.apache.directory.api.ldap.model.exception.LdapEntryAlreadyExistsException: ERR_250_ENTRY_ALREADY_EXISTS ou=system already exists!)'
followed by others that have been accurately identified in this Apache JIRA issue
Every time I stop and start JBoss thereafter, the ApacheDS server starts just fine (same as in the JIRA issue)
The JIRA page states that the issue has been fixed with a little workaround, which I have applied
public EmbeddedADSVerTrunkV2(final File workDir) throws Exception
{
    if (!workDir.exists())
    {
        workDir.mkdirs();
        this.initDirectoryService(workDir);
        this.service.shutdown();
    }

    this.initDirectoryService(workDir);
}

but the problem remains for me. The second run always fails before succeeding on the third and subsequent runs.
Are there any new workarounds or fixes that I have missed? Many thanks!

A: This issue was already fixed, please verify if you have the correct version of the jar file(s).


text:
Q: Extracting corresponding dataframe values from multiple records using a function I have a dataframe (df1) containing many records Each record has up to three trials, each trial can be repeat up to five times. Below is an example of some data I have:
Record   Trial   Start    End    Speed     Number
     1       2       1      4       12         9
     1       2       4      6       11        10
     1       3       1      3       10        17
     2       1       1      5       14         5

I have the following code that calculates the longest 'Distance' and 'Maximum Number' for each Record.:
getInfo <- function(race_df) {
  race_distance <- as.data.frame(race_df %>% group_by(record,trial) %>% summarise(max.distance = max(End - Start)))
  race_max_number = as.data.frame(race_df %>% group_by(record,trial) %>% summarise(max.N = max(Number)))
  rd_rmn_merge <- as.data.frame(merge(x = race_distance, y = race_max_number)
  total_summary <- as.data.frame(rd_rmn_merge[order(rd_rmn_merge$trial,])
  return(list(race_distance, race_max_number, total_summary)
}

list_summary <- getInfo(race_df)
total_summary <- list_of_races[[3]]

list_summary gives me an output like this:
 [[1]]
 Record   Trial    Max.Distance
      1       2       3
      1       3       2
      2       1       4

 [[2]]
 Record    Trial    Max.Number
      1       2       10
      1       3       17
      2       1        5

 [[3]]
 Record  Trial    Max.Distance    Max.Number
      1       2        3             10
      1       3        2             17
      2       1        4              5

I am now trying to seek the longest distance with the corresponding 'Number' regardless if it being maximum. So having Record 1, Trial 2 look like this instead:
Record   Trial     Max.Distance  Corresponding Number
     1       2          3                9

Eventually I would like to be able to create a function that is able to take arguments 'Record' and 'Trial' through the 'race_df' dataframe to make searching for a specific record and trial's longest distance easier.
Any help on this would be much appreciated.

A: The data (in case anyone else wants to offer their solution):
df <- data.frame( Record = c(1,1,1,2),
                  Trial = c(2,2,3,1),
                  Start = c(1,4,1,1),
                  End = c(4,6,3,5),
                  Speed = c(12,11,10,14),
                  Number = c(9,10,17,5))

Here's a tidyverse solution:
library(tidyverse)
df %>%
  mutate( Max.Distance = End - Start) %>%
  select(-Start,-End,-Speed) %>%
  group_by(Record) %>%
  nest() %>%
  mutate( data = map( data, ~ filter(.x, Max.Distance == max(Max.Distance)) )) %>%
  unnest()

The output:
  Record Trial Number Max.Distance
   <dbl> <dbl>  <dbl>        <dbl>
1      1     2      9            3
2      2     1      5            4

Note if you want to keep all of your columns in the final data frame, just remove select....

A: I hope I get right what your function is supposed to do. In the end it should take a record and a trial and put out the row(s) where we have the maximum distance, right?
So, it boils down to two filters:

*

*filter rows for the record and trial.

*filter the row inside that subset that has the maximum distance

Between those two filters, we have to calculate the distance although I suggest you move that outside the function because it is basically a one time operation.
race_df <- data.frame(Record = c(1, 1, 1, 2), Trial = c(2, 2, 3, 1),
                 Start = c(1, 4, 1, 1), End = c(4, 6, 3, 5), Speed = c(12, 11, 10, 14),
                 Number = c(9, 10, 17, 5))

get_longest <- function(df, record, trial){
  df %>%
    filter(Record == record & Trial == trial) %>%
    mutate(Distance = End - Start) %>%
    filter(Distance == max(Distance)) %>%
    select(Number, Distance)
}
get_longest(race_df, 1, 2)


text:
Q: Rename subkey in json output Is it possible to rename a subkey in JSON or add a new subkey?
For example, I have this log output:
{
    "kubernetes": {
        "pod_name": "kube-apiserver-tst",
        "namespace_name": "kube-system",
        "pod_id": "93a2b43a-46e6-4539-8674-06dede2619fa",
        "labels": {
            "component": "kube-apiserver",
            "tier": "control-plane"
        }
}

I know that with record_transformer I can add a new key:
<record>
  pod_labels "something ..."
</record>

but it seems that it can only create a new key at the root of JSON:
{
    "kubernetes": {
        "pod_name": "kube-apiserver-tst",
        "namespace_name": "kube-system",
        "pod_id": "93a2b43a-46e6-4539-8674-06dede2619fa",
        "labels": {
            "component": "kube-apiserver",
            "tier": "control-plane"
        }
    "pod_labels": "something ..."
}

But can I make it look like this?
{
    "kubernetes": {
        "pod_name": "kube-apiserver-tst",
        "namespace_name": "kube-system",
        "pod_id": "93a2b43a-46e6-4539-8674-06dede2619fa",
        "labels": {
            "component": "kube-apiserver",
            "tier": "control-plane"
        }
        "pod_labels": {
            "component": "kube-apiserver",
            "tier": "control-plane"
        }
}

or this:
{
    "kubernetes": {
        "pod_name": "kube-apiserver-tst",
        "namespace_name": "kube-system",
        "pod_id": "93a2b43a-46e6-4539-8674-06dede2619fa",
        "pod_labels": {
            "component": "kube-apiserver",
            "tier": "control-plane"
        }
}

A: The JSON is not valid. A closing curly brace is missing.
Here's the valid JSON:
{
    "kubernetes": {
        "pod_name": "kube-apiserver-tst",
        "namespace_name": "kube-system",
        "pod_id": "93a2b43a-46e6-4539-8674-06dede2619fa",
        "labels": {
            "component": "kube-apiserver",
            "tier": "control-plane"
        }
    }
}

Minified JSON (echo '{JSON}' | jq -c .):
{"kubernetes":{"pod_name":"kube-apiserver-tst","namespace_name":"kube-system","pod_id":"93a2b43a-46e6-4539-8674-06dede2619fa","labels":{"component":"kube-apiserver","tier":"control-plane"}}}

The record_transformer filter plugin can be used with Ruby support (via enable_ruby option) to manipulate an existing key and then the unwanted keys can be removed with its remove_keys option.
Here's the sample config:
<filter debug.test>
  @type         record_transformer
  enable_ruby   true
  <record>
    temp        ${ l = record["kubernetes"]["labels"]; record["kubernetes"]["pod_labels"] = l; nil; }
  </record>
  remove_keys   temp, $.kubernetes.labels
</filter>

Here's the complete test:
fluent.conf
<source>
  @type       forward
</source>

<filter debug.test>
  @type         record_transformer
  enable_ruby   true
  <record>
    temp        ${ l = record["kubernetes"]["labels"]; record["kubernetes"]["pod_labels"] = l; nil; }
  </record>
  remove_keys   temp, $.kubernetes.labels
</filter>

<match debug.test>
  @type       stdout
</match>

Start fluentd with this config:
fluentd -c fluent.conf

On another terminal, send an event with fluent-cat (echo '{JSON}' | fluent-cat debug.test):
echo '{"kubernetes":{"pod_name":"kube-apiserver-tst","namespace_name":"kube-system","pod_id":"93a2b43a-46e6-4539-8674-06dede2619fa","labels":{"component":"kube-apiserver","tier":"control-plane"}}}' | fluent-cat debug.test

In fluentd logs, you should see the desired output:
2022-02-16 23:08:25.919967225 +0500 debug.test: {"kubernetes":{"pod_name":"kube-apiserver-tst","namespace_name":"kube-system","pod_id":"93a2b43a-46e6-4539-8674-06dede2619fa","pod_labels":{"component":"kube-apiserver","tier":"control-plane"}}}

Formatted output with jq (echo '{JSON}' | jq .):
echo '{"kubernetes":{"pod_name":"kube-apiserver-tst","namespace_name":"kube-system","pod_id":"93a2b43a-46e6-4539-8674-06dede2619fa","pod_labels":{"component":"kube-apiserver","tier":"control-plane"}}}' | jq .

Output:
{
  "kubernetes": {
    "pod_name": "kube-apiserver-tst",
    "namespace_name": "kube-system",
    "pod_id": "93a2b43a-46e6-4539-8674-06dede2619fa",
    "pod_labels": {
      "component": "kube-apiserver",
      "tier": "control-plane"
    }
  }
}


text:
Q: Opencv video frame giving me an error Trying to perform grayscale transformation on frames on a video ,but keep getting Assertation failed error when I get to cvCvtColor.
Does anyone see where my error is?
    IplImage *frame, *frame_copy = 0;

// capture frames from video
CvCapture *capture = cvCaptureFromFile( "lightinbox1.avi");
//Allows Access to video propertys
cvQueryFrame(capture);

//Get the number of frames
int nframe=(int) cvGetCaptureProperty(capture,CV_CAP_PROP_FRAME_COUNT);

    //Name window
cvNamedWindow( "video:", 1 );

    //start loop
for(int i=0;i<nframe;i++){
//prepare capture frame extraction
cvGrabFrame(capture);
cout<<"We are on frame "<<i<<"\n";
//Get this frame
frame = cvRetrieveFrame( capture );
con2txt(frame);
    frame_copy = cvCreateImage(cvSize(frame->width,frame->height),IPL_DEPTH_8U,frame->nChannels );
//show and destroy frame
    cvCvtColor( frame,frame,CV_RGB2GRAY);

cvShowImage("video:",frame);
cvWaitKey(33);}
cvReleaseCapture(&capture);

}

A: Actually, the problem is that cvCvtColor() with CV_RGB2GRAY expects an output image with nChannels == 1.
To solve the issue, you must adjust your copy procedure to:
frame_copy = cvCreateImage(cvSize(frame->width,frame->height), IPL_DEPTH_8U, 1);
cvCvtColor(frame, frame_copy, CV_RGB2GRAY);

A: You're calling cvCvtColor with the same frame as source and destination image.
This isn't possible, since cvCvtColor must change the number of channels in the image in order to convert rgb to grey.
Call cvtColor with a new image as the destination, instead.


text:
Q: How to make sure windows 8 uses all computing power for only 1 process? If I render an image in windows 8 commandline for example with blender/cycles my machine sometimes has a low cpu usage. The render task starts with 100% cpu usage, fall down after 2-4 hours to 25%, stays there for 3-6 hours and sometimes it raises up to 100% again. It cant be a blender issue, because when I render the same in windows 7 it works as expected.
Any Ideas on this?

A: *

*First you should try to set the priority and affinity of the process in the Task Manager just to give it  a little bump up in comparison to other USER programs (note the user part as this doesn't affect much the SYSTEM processes, the efficiency of this is debated as the priority queue used by Windows depends on many things, so as you said this works as expected in Windows 7 so maybe its some background process particular of Windows 8 that is stalling the process)

*I have heard many users complaining of idle/background maintenance in Windows 8 and 8.1, you should try to deactivate this and try again, ill leave a link to a tutorial on deactivating the background maintenance that sometimes may be bothersome to other programs executing as well Background Maintenance
Here you can find the superuser question: Disable "automatic maintenance" in Windows 8


text:
Q: URL in Symfony automatically adds me params ?Symfony= I have a concern in my URL. Symfony automatically adds me params ?Symfony=
How to remove?
I think it's a server setting to change.
http://mysite.com/?symfony=123456789
Symfony: Symfony 1.4

A: It looks like the session id.
Set session.use_only_cookies to 1 to only use cookies to store the session id on the client side.


text:
Q: Iterate through dependent getjson() calls I'm trying to perform the following actions at a high level:

*

*Make an API call to generate an array of cardIDs for a Trello board

*Iterate and make an API call for each cardID, pull some action (history) data for each card and store that in the action_tableData table

*Once complete, append action_tableData to the table object

The way I understand things is that I need to perform a getJSON call, let that finish and then perform another getJSON on top of that. I've looked around and understand the $.when() function might help, but I can't seem to even remotely make that work.
I think there could be an issue when the getJSON returns an undefined object, but I'm not sure how to skip those. Any help would be most appreciated!
cardIDapiCall = "https://api.trello.com/1/boards/" + boardID + "/cards?fields=id&key=" + appKey + "&token=" + tokenKey;
        $.getJSON(cardIDapiCall, function(cardID) {
            var cardID_tableData = [];

            // Iterate over the JSON object
            for (var i = 0, len = cardID.length; i < len; i++) {
                cardID_tableData.push({
                    "card_id": cardID[i].id,
                });
            }

            //get action data
            for (var j = 1, len = cardID_tableData.length; j < len; j++) {

                //this alert works
                alert("card id: " + cardID_tableData[j].card_id);

                var actionapiCall = "https://api.trello.com/1/cards/" + cardID_tableData[j].card_id + "/actions?key=" + appKey + "&token=" + tokenKey;

                //why isn't this getting called???
                $.getJSON(actionapiCall, function() {
                    //this alert doesn't work
                    alert("action call successful");
                });
                    var action_tableData = [];

                    action_tableData.push({
                        "action_id": action[j].id,
                        "action_type": action[j].type,
                    })

                table.appendRows(action_tableData);
                doneCallback();

            }
        });


text:
Q: Modal Factory to be used in place of Confirm() I have created an Angular Modal factory that passes a couple parameters to create dynamic modals based upon templates and options passed back. However I want to replace all of the Confirm dialogues in my app but am struggling with this.
modal factory
(function () {

    var testApp= angular.module('test');

    testApp.factory('myModals', ['$uibModal', function ($uibModal) {
        // called from various methods within factory
        function openModal(template, data, options) {
            //build all of the modal options
            var modalOpts = {
                animation: true,
                templateUrl: template,
                controller: function ($scope, $uibModalInstance, alert_data) {
                    $scope.alert_data = alert_data;
                    $scope.okToProceed = function () {
                        $scope.goodToGo = true;
                        console.log("true")

                    };
                    $scope.cancel = function () {
                        $uibModalInstance.dismiss('cancel');
                        console.log("modal cancelled")
                    };
                },
                resolve: {
                    alert_data: data
                },
                size: '480',
                backdrop: 'static'
            };
            // extend options set in each use type function
            if (options) {
                angular.extend(modalOpts, modalOpts);

            }
            var modalInstance = $uibModal.open(modalOpts);

            modalInstance.result.then(function (data) {
                // always do something when close called
                return data;
            }, function (data) {
                //always do something when dismiss called
                return data
            });

            return modalInstance;
        }

        function alert(type, text, size) {

            var template;
            // enter in template and string being passed back to identify modal type
            switch (type) {
                case 'test1':
                    template = 'test1.popup.html';
                    break;
                case 'test2':
                    template = 'test2.popup.html';
                    break;

            }

            var opts = {
                //default but should be passed back
                size: size || 'sm'
            };
            var data = {
                title: type === 'success' ? "OK" : "Error",
                text: text
            };

            return openModal(template, data, opts);

        }

        return {
            alert: alert
        }

    }])
})();

template.html

{{alert_data.text}}

    <button class="btn btn-warning" type="button" ng-click="okToProceed()">Ok</button>
    <button class="btn btn-warning" type="button" ng-click="cancel()">Cancel</button>

example of confirm to be replaced
 $scope.discardSource = function(currentIndex) {
                if (confirm("Press 'OK' to confirm.")) {
                    $log.debug("discardDataSource currentIndex: " + currentIndex);
                    $log.debug($scope.model.dataSamples[currentIndex]);


text:
Q: Is it a good idea to hold reference to both recyclerview and its adapter separately in a fragment/activity What I would like to know is will it cause a big difference in performance/efficiency if I held class variables for both my recyclerview as well as the adapter, just because I want to reduce the amount of code I have to type every time I want to call notifydatasetchanged on the adapter.

A: There is no downside in having a reference to the adapter as well. In fact it's even more performant (but insignificantly) because you will save some extra method calls (like recyclerView.getAdapter()). Also, the code is more readable and easier to maintain this way ;)
Consider having a look on this presentation from Jake Wharton to learn more optimization tips.


text:
Q: What's wrong in my code for this output? My application is divided into Server and Client.
through the client (stdin) I write the values name, phone.
Server opens a txt file called "elenco" in which he writes the values.
my output is:
righetti
ilaria
à|÷UˇÄÈ 4648585858

why this strange symbols on telefono? ideas?
Here's my whole code,take a look and help me please.I'm going to crazy
http://pastebin.com/hsDu9S1H
http://pastebin.com/tzeUKd6C


text:
Q: How to SPSiteDataQuery from one SharePoint farm to another farm? I want to use SPSiteDataQuery to query from one SP farm to another. Both farms exist on the same active directory. What would be the most suitable approach? A custom web service might do it? An ideas will be appreciated

A: I would suggest creating a web service, and querying the web service from the other farm. I don't think you'll be able to use the SPSiteDataQuery object itself across the farm boundary.

A: If you want to query across farms, the best way I think is Search. If you efficiently use keyword and full text queries, you can fine tune your search results similar to SPSiteDataQuery (or even better) across many farms without compromising on performance
Taking the step forward, If you have the powerful FAST search you can find almost anything!


text:
Q: How to change value of an item of a collection With this code (in excel-vba) I add to a collection a number of items depending on an array.
I use the value of the array as key and the string "NULL" as value for each item added.
Dim Coll As New collection
Dim myArr()

Set Coll = New collection
myArr() = Array("String1", "String2", "String3")

For i = LBound(myArr) To UBound(myArr)
    Coll.Add "NULL", myArr(i)
Next i

Now, if I want to change the value of an item, identifying it by the key, I must remove the item and then add an item with same key or is it possible to change the item value?
This below is the only way?
Coll.Remove "String1"
Coll.Add "myString", "String1"

Or is there something like: (I know that doesn't work)
Coll("String1") = "myString"

A: Can't you use the Before argument to fulfill this requirement?
Example:
Option Explicit

Sub TestProject()
    Dim myStrings As New Collection

    myStrings.Add item:="Text 1"
    myStrings.Add item:="Text 2"
    myStrings.Add item:="Text 3"

    ' Print out the content of collection "myStrings"
    Debug.Print "--- Initial collection content ---"
    PrintCollectionContent myStrings
    ' Or with the "Call" keyword: Call PrintCollectionContent(myStrings)
    Debug.Print "--- End Initial collection content ---"

    ' Now we want to change "Text 2" into "New Text"
    myStrings.Add item:="New Text", Before:=2 ' myStrings will now contain 4 items
    Debug.Print "--- Collection content after adding the new content ---"
    ' Print out the 'in-between' status of collection "myStrings" where we have
    ' both the new string and the string to be replaced still in.
    PrintCollectionContent myStrings
    Debug.Print "--- End Collection content after adding the new content ---"

    myStrings.Remove 3
    ' Print out the final status of collection "myStrings" where the obsolete
    ' item is removed
    Debug.Print "--- Collection content after removal of the old content ---"
    PrintCollectionContent myStrings
    Debug.Print "--- End Collection content after removal of the old content ---"

End Sub

Private Sub PrintCollectionContent(ByVal myColl As Variant)
    Dim i as Integer

    For i = 1 To myColl.Count()
        Debug.Print myColl.Item(i)
    Next i
End Sub

Shouldn't this do the job?

A: Here is a solution where Coll("String1") = "myString" does work.
When you .Add an object to a VBA collection, the object itself is added, not its value. This means you can change the object's properties while it is in the collection. I've created a class module which wraps a single variant in a class object, with .Value as its default property. Save this to a .cls file, then File > Import File in the VBA editor.
VERSION 1.0 CLASS
BEGIN
  MultiUse = -1  'True
END
Attribute VB_Name = "clsValue"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = False
Option Compare Database
Option Explicit
Private MyValue As Variant
Property Get Value() As Variant
    Attribute Value.VB_UserMemId = 0
    Value = MyValue
End Property
Property Let Value(v As Variant)
    Attribute Value.VB_UserMemId = 0
    MyValue = v
End Property

Now this version of your code works the way you had hoped:
Private Sub clsValue_test()
Dim Coll As New Collection
Dim myArr()
Dim v As Variant
myArr = Array("String1", "String2", "String3")
For Each v In myArr
    Coll.Add New clsValue, v
    Coll(v) = "NULL"
Next v
Coll("String1") = "myString"    ' it works!
For Each v In myArr
    Debug.Print v, ": "; Coll(v)
Next v
End Sub

Produces the result:
String1       : myString
String2       : NULL
String3       : NULL

A: You can also write a (public) function to make updates to a collection.
public function updateCollectionWithStringValue(coll as Collection, key as string, value as string) as collection
    coll.remove key
    coll.add value, key
    set updateCollectionWithStringValue = coll
end function

You can invoke this function by:
set coll = updateCollectionWithStringValue(coll, "String1","myString")

Then you have a one liner to invoke.

A: A variant of making a function that deletes the collection item by its key, is implementing it as a VBA Property
Public Property Let CollectionValue(coll As Collection, key As String, value As String)
    On Error Resume Next
    coll.Remove key
    On Error GoTo 0
    coll.Add value, key
End Property

Public Property Get CollectionValue(coll As Collection, key As String) As String
    CollectionValue = coll(key)
End Property

And Used like this
'Writing
CollectionValue(coll, "Date") = Now()

'Reading
Debug.Print(CollectionValue(coll, "Date"))

By ignoring if key not exists, it can be used to add items as well

A: just loop the collection and add the new values to a new collection...
function prep_new_collection(my_old_data as collection) as collection

dim col_data_prep as new collection

for i = 1 to my_old_data.count

if my_old_data(i)(0)= "whatever" then

  col_data_prep.add array("NULL", my_old_data(i)(1))

else

 col_data_prep.add array(my_old_data(i)(0), my_old_data(i)(1))

end if

next i

 set prep_new_collection = col_data_prep

end function

A: I just ran into the same issue an thought to post my solution here for any one who might need it. my solution was to make a class called
EnhancedCollection that has an update function.  save this code to a file named EnhancedCollection.cls and then import into your project.
    VERSION 1.0 CLASS
    BEGIN
      MultiUse = -1  'True
    END
    Attribute VB_Name = "EnhancedCollection"
    Attribute VB_GlobalNameSpace = False
    Attribute VB_Creatable = False
    Attribute VB_PredeclaredId = False
    Attribute VB_Exposed = False
    Option Explicit

    Private data As New Collection

    '=================================ADD

    If IsMissing(key) Then
        If IsMissing(before) Then
            If IsMissing(after) Then
                data.Add Value
            Else
                data.Add Value, , , after
            End If
        Else
            data.Add Value, , before
        End If
    ElseIf key = "TEMP_ITEM" Then
        Exit Sub
    Else
        If IsMissing(before) Then
            If IsMissing(after) Then
                data.Add Value, key
            Else
                data.Add Value, key, , after
            End If
        Else
            data.Add Value, key, before
        End If
    End If
End Sub
'=================================REMOVE

Sub Remove(key As Variant)
    data.Remove key
End Sub

    '=================================COUNT

    Function Count() As Integer
        Count = data.Count
    End Function
    '=================================ITEM

    Function Item(key As Variant) As Variant
    'This is the default Function of the class
    Attribute Item.VB_Description = "returns the item"
    Attribute Item.VB_UserMemId = 0
    On Error GoTo OnError
        If VarType(key) = vbString Or VarType(key) = vbInteger Then
            Item = data.Item(key)
        End If
        Exit Function
    OnError:
        Item = Null
    End Function
    '=================================Update

    Function Update(key As Variant, Value As Variant) As Variant
    On Error GoTo OnError
        If VarType(key) = vbString Or VarType(key) = vbInteger Then
            data.Add "", "TEMP_ITEM", , key
            data.Remove key
            data.Add Value, key, "TEMP_ITEM"
            data.Remove "TEMP_ITEM"
        End If
        Exit Function
    OnError:
        Update = Null
    End Function

And as an added benefit, you can always add more functionality.

A: Sub tcoll()
 Dim c As New Collection
 c.Add Array("1", 2, False)
 c.Add Array("2", 3, False)
 c.Add Array("1", 4, False)
 For Each ci In c:  Debug.Print ci(0), ci(1), ci(2): Next
 If 1 Then
  'ok
  For X = c.Count To 1 Step -1
   Select Case c(X)(0)
   Case "1"
    c.Add Array(c(X)(0), c(X)(1), 1), after:=X
    c.Remove X
   Case "2"
    c.Remove X
   End Select
  Next
 Else
  'Subscript out of range
  For X = 1 To c.Count
   Select Case c(X)(0)
   Case "1"
    c(X)(2) = 1 'no error but collection is not changed
   Case "2"
    c.Remove X
   End Select
  Next
 End If
 For Each ci In c:  Debug.Print ci(0), ci(1), ci(2): Next
 Set c = Nothing
End Sub


text:
Q: Is it possible to restore a MySQL database to a previous state in time? I just realized that the MySQLWorkBench destroys the target (makes a replacement) when performing synchronize model.
Making changes on the source and model between synchronizations leaves you with a weird bastard.
So is it possible to return to a given snapshot in time?

A: A recent backup of the database taken using mysqldmp should be sufficient for you to restore the database to the time of the last backup.
After a restore, it's possible to roll forward changes from the binary log to a particular point in time.  http://dev.mysql.com/doc/refman/5.1/en/point-in-time-recovery.html
Aside from that, there is no rollback to a "snapshot in time" and no "flashback query" functionality in MySQL (at least not in the MySQL 5.1 Community Edition.)


text:
Q: What would be the most convenient way to connect Visual Studio 2005 (C#) to Oracle8? I'm looking for best practices for establishing connections between Oracle 8 and Visual Studio 2005 applications. The target would be a Windows Forms application written in C# that hits the database once a second to monitor tables looking for their last inserted record. I'm considering using "Application settings" to store the connection string there, but I'd love to hear from you guys. Thanks in advance!
This is a very rudimentary draft:
using System.Data;
using System.Data.OracleClient;

        try
        {
            StringBuilder str = new StringBuilder();
            string ora = Properties.Settings.Default.OracleConnectionString;

            OracleConnection con = new OracleConnection(ora);
            OracleCommand cmd = new OracleCommand();

            cmd.Connection = con;
            cmd.CommandText = "SELECT timestamp FROM jde_out WHERE rownum = 1";
            cmd.CommandType = CommandType.Text;

            con.Open();
            OracleDataReader rdr = cmd.ExecuteReader();
            rdr.Read();

            str.AppendLine(cmd.ExecuteScalar().ToString());
            this.lblJDEtime.Text = str.ToString();
            rdr.Close();
            con.Close();
        }
        catch (OracleException err)
        {
            MessageBox.Show("Exception caught:\n\n" + err.ToString());
        }

I've just updated the code needed to perform the connection. Changed the Exception type to the more specific OracleException. Added the connection string via Properties.Settings.

A: ConnectionStrings.com has pretty much every type of connection string you'll ever want including Oracle.

A: Here's a sample from our environment:
<add key="ODP.NET.ConnectionString" value="Password=abcdefg;Persist Security Info=True;User ID=abc123;Data Source=blah;"/>

Where the username and password are set appropriately, and the Data Source is the entry from Oracle's TNSNAMES.ORA we're connecting to.

A: Based on my experience with Oracle 10g....
I recommend using the Oracle data provider (ODP.Net) and not using the Microsoft for Oracle data provider based on my experience with Oracle 10g. Microsoft's has not been updated in years and does not support everything in Oracle 10g, so I would definitely check into that for Oracle 8.
Following Microsoft guidance on connection string in the app.config file, you should store it like:
<?xml version='1.0' encoding='utf-8'?>
  <configuration>
    <connectionStrings>
      <clear />
      <add name="Name"
       providerName="System.Data.ProviderName"
       connectionString="Valid Connection String;" />
    </connectionStrings>
  </configuration>

I've also worked on apps with the connection information stored in application settings, which worked fine for our application.

A: @Loscas
AFAIK ODP.NET data provider is supported only on Oracle 9i up.
MS Oracle data provider works on 8.1.7 and up.
@BQ

Opening a new connection to the database to poll for changes every second is an expensive operation.

Actually the connection is not opened on con.Open(). It is just taken from the pool of open connections. con.Close() returns the connection to the pool. So, there is really nothing wrong with this connection handling.

A: I would warn against building an architecture like you're suggesting. Opening a new connection to the database to poll for changes every second is an expensive operation. It gets worse if you're trying to scale this Windows Form application beyond a few users.
Instead, you should look into the built-in Oracle packages that can support monitoring such activity.
EDIT: "WHERE ROWNUM=1" from your example isn't useful here. Oracle isn't guaranteed to order the results in any specific way according to your query.
Your issue is really an architectural problem. Polling database tables as you suggest is NOT a good way to do application health monitoring. At a bare minimum, you're better off having a component in the middle tier, or even the database, periodically write to a log file, Windows Event Log, table, etc. that essentially says "I'm still listening" and only poll THAT singular source.

A: If you want to monitor tables, have you consider using triggers?  An example might be:

*

*Your application listens on a TCP
port

*You install a trigger on an
Oracle table

*The trigger calls some Oracle Java
code that ...

*... sends
a simple message to your app's TCP
port

*The message could just be a
notification and you could then read
from the table.  Alternatively, you
could send the entire SQL that
affected the table as the message
payload.

This might work better.

A: Regarding the connection string, since you are using System.Data.OracleClient, I would also recommend formatting the Oracle connection string to make it independent of tnsname.ora:
string connectionString = @"
SERVER=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP
(HOST=OracleHost)(PORT=OraclePort))
(CONNECT_DATA=(SERVICE_NAME=OracleServiceName)))
;uid=UserID;pwd=Password;";

You can store it in your App.config file like so:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
  <add key="My.Database.Connection" value="SERVER=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP
    (HOST=OracleHost)(PORT=OraclePort))
    (CONNECT_DATA=(SERVICE_NAME=OracleServiceName)))
    ;uid=UserID;pwd=Password;" />
  </appSettings>
</configuration>

and then access it with:
connectionString = ConfigurationSettings.AppSettings["My.Database.Connection"];

FYI, here is a blog post by me on this subject:
Quick and dirty connection to Oracle using ADO.NET


text:
Q: JButton action listener issue. Slider values being displayed in fields So I have a program that is due tomorrow and I have held out as long as I can trying to figure out what is wrong with my code. First and biggest issue that has had me stumped for quiet a while is my reset buttons action listener. It just wont compile properly and says value not found? I commented it out so I could at least run the program you should be able to see clearly where I commented them out at. Also second issue is I have to make one text field display the MAX value between the two sliders when moving them and the other give me the TOTAL value between the two sliders. I honestly don't know what to do for the logical end of that and just simply attached both jtextfields to the left slider. For this I would appreciate a push in the right direction?  If you give me code I would be much appreciated but I would also like to explain why it works/ what was wrong with my code. Thanks!
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;

/**
   This class displays a window with a slider component.
   The user can slide the left or right slider. As the
    sliders are adjusted it displays the maximum sound
    level coming from either slider as well as the total.
*/

public class SoundLevels extends JFrame
{
   private JLabel label1, label2, label3, label4;     // Message labels
   private JTextField maxSound;     // Max Sound Level
   private JTextField totalSound;   // Total Sound Level
   private JPanel mpanel;           // Max sound level panel
   private JPanel tpanel;           // Total sound level panel
   private JPanel sliderPanel1;     // Slider panel 1
    private JPanel sliderPanel2;     // Slider panel 2
    private JPanel resetpanel;       // Reset button panel
   private JSlider slider1;         // Left sound adjuster
    private JSlider slider2;         // Right sound adjuster
    private JButton resetButton;     // Reset button
   /**
      Constructor
   */

   public SoundLevels()
   {
      // Set the title.
      setTitle("Sound Levels");

      // Specify an action for the close button.
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Creates reset button
        resetButton = new JButton("Reset");

      // Create the message labels.
      label1 = new JLabel("Left:  ");
      label2 = new JLabel("Right: ");
        label3 = new JLabel("Max:   ");
        label4 = new JLabel("Total: ");

      // Create the read-only text fields.
      maxSound = new JTextField("0", 10);
      maxSound.setEditable(false);
      totalSound = new JTextField("0", 10);
      totalSound.setEditable(false);

      // Create the slider.
      slider1 = new JSlider(JSlider.HORIZONTAL, 0, 100, 0);
        slider2 = new JSlider(JSlider.HORIZONTAL, 0, 100, 0);
      slider1.addChangeListener(new SliderListener());

      // Create panels and place the components in them.
      mpanel = new JPanel();
        resetpanel = new JPanel();
        tpanel = new JPanel();
        sliderPanel1 = new JPanel();
        sliderPanel2 = new JPanel();

        //Add components to panels
        mpanel.add(label1);
      mpanel.add(maxSound);

        tpanel.add(label2);
      tpanel.add(totalSound);

        sliderPanel1.add(label1);
      sliderPanel1.add(slider1);

        sliderPanel2.add(label2);
        sliderPanel2.add(slider2);

        resetpanel.add(resetButton);

      // Initialize event listener
//      resetButton.addActionListener(new ResetButtonListener());

        // Sets window to a border layout format.
      setLayout(new GridLayout(1, 5));

      // Add the panels to the content pane.
      add(sliderPanel1);
        add(sliderPanel2);
        add(resetpanel);
        add(mpanel);
      add(tpanel);

      // Pack and display the frame.
      pack();
      setVisible(true);
   }

   /**
      Private inner class that handles the event when
      the user clicks the Reset button.
   */

/* COMMENTED THIS OUT SO IT AT LEAST RUNS
      private class ResetButtonListener implements ActionListener
      {
         public void actionPerformed(ActionEvent e)
         {
         // Set the panel's background to red.
            max = 0;  //should reset sliders to 0
                total = 0; //should reset sliders to 0
         }
      }
*/

   /**
      Private inner class to handle the change events
      that are generated when the slider is moved.
   */

   private class SliderListener implements ChangeListener
   {
      public void stateChanged(ChangeEvent e)
      {
         int max, total;

         // Get the slider value.
         max = slider1.getValue();
            total = slider1.getValue();

         // Store the total sound level in its display field.
         totalSound.setText(Integer.toString(total));

         // Store the max sound level in its display field.
         maxSound.setText(Integer.toString(max));
      }
   }

   /*
      The main method creates an instance of the
      class, which displays a window with a slider.
   */

   public static void main(String[] args)
   {
      new SoundLevels();
   }
}

A: I recommend 2 changes.
slider1.addChangeListener(new SliderListener());
slider2.addChangeListener(new SliderListener()); // newly added

& in the listener:
// Get the slider value.
max = slider1.getValue();
total = slider2.getValue(); // change from 1 -> 2

What is wrong with my action private reset button listener class?

It is about the scope and visibility of the two int attributes.  Consider this code, but note that the action performed will not change the slider values, which might be confusing to the user.
// class level attributes that are visible to both
// ResetButtonListener & ResetButtonListener
private int max, total;

/**
Private inner class that handles the event when
the user clicks the Reset button.
 */
private class ResetButtonListener implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        // Set the panel's background to red.
        max = 0;  //should reset sliders to 0
        total = 0; //should reset sliders to 0
    }
}

/**
Private inner class to handle the change events
that are generated when the slider is moved.
 */
private class SliderListener implements ChangeListener
{
    public void stateChanged(ChangeEvent e)
    {

        // Get the slider value.
        max = slider1.getValue();
        total = slider2.getValue();

        // Store the total sound level in its display field.
        totalSound.setText(Integer.toString(total));

        // Store the max sound level in its display field.
        maxSound.setText(Integer.toString(max));
    }
}

A: What I changed was adding a the listener to both sliders-
slider1.addChangeListener(new SliderListener());
slider2.addChangeListener(new SliderListener());

And also making a change to the slider listener -
private class SliderListener implements ChangeListener {
        public void stateChanged(ChangeEvent e) {
            int max = 0;
            int total = 0;
            // Get the slider value.
            int slider1Val = slider1.getValue();
            int slider2Val = slider2.getValue();
            if (slider1Val > slider2Val) {
                max = slider1Val;
            } else {
                max = slider2Val;
            }
            total = slider2Val + slider1Val;
            // Store the total sound level in its display field.
            totalSound.setText(Integer.toString(total));

            // Store the max sound level in its display field.
            maxSound.setText(Integer.toString(max));
        }
    }

Below is the way the entire edited code -
package org.dchan.orm;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

/**
 * This class displays a window with a slider component. The user can slide the
 * left or right slider. As the sliders are adjusted it displays the maximum
 * sound level coming from either slider as well as the total.
 */

public class SoundLevels extends JFrame {
    private JLabel label1, label2, label3, label4; // Message labels
    private JTextField maxSound; // Max Sound Level
    private JTextField totalSound; // Total Sound Level
    private JPanel mpanel; // Max sound level panel
    private JPanel tpanel; // Total sound level panel
    private JPanel sliderPanel1; // Slider panel 1
    private JPanel sliderPanel2; // Slider panel 2
    private JPanel resetpanel; // Reset button panel
    private JSlider slider1; // Left sound adjuster
    private JSlider slider2; // Right sound adjuster
    private JButton resetButton; // Reset button

    /**
     * Constructor
     */

    public SoundLevels() {
        // Set the title.
        setTitle("Sound Levels");

        // Specify an action for the close button.
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Creates reset button
        resetButton = new JButton("Reset");

        // Create the message labels.
        label1 = new JLabel("Left:  ");
        label2 = new JLabel("Right: ");
        label3 = new JLabel("Max:   ");
        label4 = new JLabel("Total: ");

        // Create the read-only text fields.
        maxSound = new JTextField("0", 10);
        maxSound.setEditable(false);
        totalSound = new JTextField("0", 10);
        totalSound.setEditable(false);

        // Create the slider.
        slider1 = new JSlider(JSlider.HORIZONTAL, 0, 100, 0);
        slider2 = new JSlider(JSlider.HORIZONTAL, 0, 100, 0);
        slider1.addChangeListener(new SliderListener());
        slider2.addChangeListener(new SliderListener());
        // Create panels and place the components in them.
        mpanel = new JPanel();
        resetpanel = new JPanel();
        tpanel = new JPanel();
        sliderPanel1 = new JPanel();
        sliderPanel2 = new JPanel();

        // Add components to panels
        mpanel.add(label1);
        mpanel.add(maxSound);

        tpanel.add(label2);
        tpanel.add(totalSound);

        sliderPanel1.add(label1);
        sliderPanel1.add(slider1);

        sliderPanel2.add(label2);
        sliderPanel2.add(slider2);

        resetpanel.add(resetButton);

        // Initialize event listener
        // resetButton.addActionListener(new ResetButtonListener());

        // Sets window to a border layout format.
        setLayout(new GridLayout(1, 5));

        // Add the panels to the content pane.
        add(sliderPanel1);
        add(sliderPanel2);
        add(resetpanel);
        add(mpanel);
        add(tpanel);

        // Pack and display the frame.
        pack();
        setVisible(true);
    }

    /**
     * Private inner class that handles the event when the user clicks the Reset
     * button.
     */

    /*
     * COMMENTED THIS OUT SO IT AT LEAST RUNS
     */private class ResetButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            // Set the panel's background to red.
            // max = 0; // should reset sliders to 0
            // total = 0; // should reset sliders to 0
            slider1.setValue(0);
            slider2.setValue(0);
        }
    }

    /*
*/

    /**
     * Private inner class to handle the change events that are generated when
     * the slider is moved.
     */

    private class SliderListener implements ChangeListener {
        public void stateChanged(ChangeEvent e) {
            int max = 0;
            int total = 0;
            // Get the slider value.
            int slider1Val = slider1.getValue();
            int slider2Val = slider2.getValue();
            if (slider1Val > slider2Val) {
                max = slider1Val;
            } else {
                max = slider2Val;
            }
            total = slider2Val + slider1Val;
            // Store the total sound level in its display field.
            totalSound.setText(Integer.toString(total));

            // Store the max sound level in its display field.
            maxSound.setText(Integer.toString(max));
        }
    }

    /*
     * The main method creates an instance of the class, which displays a window
     * with a slider.
     */

    public static void main(String[] args) {
        new SoundLevels();
    }
}

Creation of the listener requires a bit of logical understanding. But you need to understand that to get an event you from both sliders the listener should be applied to both. The gist for the entire code is available at - https://gist.github.com/4193279.
For future reference I would suggest you to break your question to few parts.


text:
Q: group the json based on specific field I have a JSON response I want to get the username,geo,salesstage,count of particular user in specific geo in particular sales stage and pipeline value same as count.
Now count worked based on geo. Now is getting a wrong count.
eg  Jaison Clinton has 4 count for proposed submitted  in geo :nsu with pipeline value 12
    Jaison Clinton has 1 count for qualified  in geo :nsu with pipeline value 3
     Jaison Clinton has 1 count in geo :Us East with pipeline value 3

  expected output
    [{"UserName":"Jaison Clinton", "Geo":"NSU", "SalesStage":"Proposal Submitted","count":"4","PipelineValue":12},
{"UserName":"Jaison Clinton", "Geo":"NSU", "SalesStage":"Qualified","count":"4","PipelineValue":3}
{"UserName":"Jaison Clinton", "Geo":"US East", "SalesStage":"Proposal Submitted","count":"1","PipelineValue":3}},
 {"UserName":"Kaviarasan Selvaraj", "Geo":"NSU", "SalesStage":"Proposal Submitted","count":"2","PipelineValue":9},
{"UserName":"Vivek Sharma", "Geo":"NSU", "SalesStage":"close won","count":"1","PipelineValue":13} ]

const data ={
   "pipeline":{
      "data":[
         {
            "UserName":"Jaison Clinton",
            "Geo":"NSU",
            "SalesStage":"Proposal Submitted",
            "PipelineValue":"3,"

         },
         {
            "UserName":"Jaison Clinton",
            "Geo":"NSU",
            "SalesStage":"qualified",
            "PipelineValue":"3"

         },
         {
            "UserName":"Jaison Clinton",
            "Geo":"US East",
            "SalesStage":"Proposal Submitted",
            "PipelineValue":"4"

         },
         {
            "UserName":"Jaison Clinton",
            "Geo":"NSU",
            "SalesStage":"Proposal Submitted",
            "PipelineValue":"5"

         },
         {
            "UserName":"Jaison Clinton",
            "Geo":"NSU",
            "SalesStage":"Proposal Submitted",
            "PipelineValue":"3"
         },
         {
            "UserName":"Kaviarasan Selvaraj",
            "Geo":"NSU",
            "SalesStage":"Proposal Submitted",
            "PipelineValue":"7"
         },
         {
            "UserName":"Kaviarasan Selvaraj",
            "Geo":"NSU",
            "SalesStage":"Proposal Submitted",
            "PipelineValue":"2"
         },
         {
            "UserName":"Vivek Sharma",
            "Geo":"NSU",
            "SalesStage":"close won",
            "PipelineValue":"13"

        }
      ]
   }
};
const result = Object.entries(data.pipeline.data.reduce((acc,cur) => {
      let k=cur.Geo+'|'+cur.SalesStage;
      (acc[k]=acc[k] || []).push(+cur.PipelineValue.replace(/,/g,''))
      return acc}, {}))
    .map(e=>{
      let k=e[0].split('|');
      return {Geo:k[0],SalesStage:k[1],count:e[1].length,PipelineValue:e[1].reduce((a,c)=>a+c)}
     });

console.log(result);

A: You could group by the wanted keys and get the part of PipelineValue for summing and a count for the items of the same group.

var data = [{ UserName: "Jaison Clinton", Geo: "NSU", SalesStage: "Proposal Submitted", PipelineValue: "3," }, { UserName: "Jaison Clinton", Geo: "NSU", SalesStage: "qualified", PipelineValue: "3" }, { UserName: "Jaison Clinton", Geo: "US East", SalesStage: "Proposal Submitted", PipelineValue: "4" }, { UserName: "Jaison Clinton", Geo: "NSU", SalesStage: "Proposal Submitted", PipelineValue: "5" }, { UserName: "Jaison Clinton", Geo: "NSU", SalesStage: "Proposal Submitted", PipelineValue: "3" }, { UserName: "Kaviarasan Selvaraj", Geo: "NSU", SalesStage: "Proposal Submitted", PipelineValue: "7" }, { UserName: "Kaviarasan Selvaraj", Geo: "NSU", SalesStage: "Proposal Submitted", PipelineValue: "2" }, { UserName: "Vivek Sharma", Geo: "NSU", SalesStage: "close won", PipelineValue: "13" }],
    keys = ['UserName', 'Geo', 'SalesStage'],
    result = Object.values(data.reduce((r, o) => {
        const key = keys.map(k => o[k]).join('|');
        if (!r[key]) r[key] = Object.fromEntries(keys.map(k => [k, o[k]]));
        r[key].count = (r[key].count || 0) + 1;
        r[key].PipelineValue = (r[key].PipelineValue || 0) + +(o.PipelineValue || '0').toString().match(/\d+/)[0];
        return r;
    }, {}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }


text:
Q: Safely parametrize WHERE ... IN lists for SQL queries in R library(DBI)
library(RSQLite)
library(dplyr)

con <- dbConnect(RSQLite::SQLite(), ":memory:")
iris_id <- iris |>
  mutate(id = row_number())
dbWriteTable(con, "iris_id", iris_id)

params <- list(id = c(5,6,7))
q <- "SELECT COUNT(*) FROM iris_id WHERE id IN ($id)"
res <- dbSendQuery(con, q)
dbBind(res, params)
dbFetch(res)

As per documentation, this performs the query once per entry in params$id and returns c(1,1,1).
This also doesn't work, because this query is actually WHERE id IN ('5,6,7'):
id <- c(5L,6L,7L)
stopifnot(is.integer(id))
params <- list(id = paste(id, collapse=","))
res <- dbSendQuery(con, q)
dbBind(res, params)
dbFetch(res)

The answer to question [0] suggests using positional ? and pasting a list of ? together. However, this loses the possibility of using named params, which would be beneficial if I have multiple parameters. Is there another way?
[0] Passing DataFrame column into WHERE clause in SQL query embedded in R via parametrized queries

A: One solution would be to pass all the ids as a comma separated string (no spaces) and use instead of IN the operator LIKE:
params <- list(id = "5,6,7")
q <- "SELECT COUNT(*) FROM iris_id WHERE ',' || $id || ',' LIKE '%,' || id || ',%'"
res <- dbSendQuery(con, q)
dbBind(res, params)
dbFetch(res)

A: library(dbplyr)
translate_sql(id %in% c(4L,5L,6L))


text:
Q: Can we create Desktop application in php My concern is to know, That can we create desktop application in PHP Like:- other applications on our desktop. If yes then give some references or ideas, How to create desktop applications

A: Yes some how you can.
PHP Desktop is an open source project founded by Czarek Tomczak in 2012 to provide a way for developing native desktop GUI applications using web technologies such as PHP, HTML5, JavaScript and SQLite. Follow here
Some of the tutorials are here.
Here is youtube tutorial
Here is another useful tutorial

A: You can make desktop apps with php using tools such as Nightrain, WXPHP or TideSDK
https://www.sitepoint.com/3-ways-develop-cross-platform-desktop-apps-php/


text:
Q: VBA-Excel return the latest date I am a newbie to using VBA to program functions in Excel (just started this morning actually). Here is my problem including my almost but non-working solution.
Problem outline:
I have 2 columns of data, a userID and a Date column. I want to create a function that returns the maximum date (latest) for a userID. A userID may appear once, or many times (number varies from user to user, but doesn't exceed 20).
Now to make this problem a easier for my little brain, I pre-sort the userIDs to appear one after another, and then created a third column to mark the first instance of a userID (not necessarily the one with the earliest/latest date) using a simple excel If statement: If its the first instance it is the userID, else it is empty.
Then I created a function that takes in a range of cells (userIDs), and a single other value (the third column cell containing a single value of userID)
A typical excel worksheet will look like this:
userID   Date     First Instance
    1    3/3/12   1
    1    3/2/11
    1    2/3/14
    2              2
    2    3/4/15
    2
    2    5/6/15
    3    5/5/16    3
    4    4/4/14    4
    4
    4    6/7/08
    ...

I wrote the function below, which takes in userID as the iRange (I select more than 20 so that for other users which may have 20 instances of userID are also included), and idCell as the single identifier of the first instance of userId.
The logic behind the code is:

*

*Loop through iRange and compare it to idCell

*If it's equal, check that the next cell (next to the element from iRange is a date) and if it is

*Check whether it is larger than the maxDate, store it if true

*At the end I return maxDate

The result:
I get a number back, but it isn't a date and I don't think it has any bearing on a date.
Function returnDate2(iRange As Range, idCell As Range) As Date
    Dim elem As Variant
    Dim i As Long
    Dim maxDate As Date
    For Each elem In iRange
        If elem = idCell Then
            If IsDate(elem.Offset(0, 1)) Then
                If elem.Offset(0, 1) > maxDate Then
                    maxDate = DateValue(elem.Offset(0, 1))
                End If
                returnDate2 = maxDate
            End If
        End If
    Next elem
End Function

Thanks in advance!


text:
Q: wordpress pagination display blank? my question is here when i am click on pagination page like 1 2 4 next when i click anyone they show a blank page . please help me ? where i am wrong.
<?php
  global $wpdb;
$pagenum = isset( $_GET['pagenum'] ) ? absint( $_GET['pagenum'] ) : 1;
$limit = 7;
 $offset = ($pagenum-1) * $limit;
 $total = $wpdb->get_var( "SELECT COUNT(*) FROM $protype" );
 $num_of_pages = ceil( $total / $limit );

  $qry="select * from $protype LIMIT $offset, $limit";
$result=$wpdb->get_results($qry);
if($result):
foreach($result as $results)
{
    ?>

<?php
 echo "
$".$results->Addl_mo_fee." for sale
";
 echo "
mls#:".$results->Ml_num."

";
  echo "
Lot Size:".$results->Lp_dol."Sq.ft

";
echo "
Lot Size:".$results->S_r."Sq.ft

";

?>
<a class="view_bt" href="<?php echo $urls;?>/?Property=<?php echo $results->Ml_num; ?   >&ptype=<?php echo $protype; ?>"> View More Details & Photos

<img src="<?php echo $url.$results->Ml_num;?>/0.jpg" width="220" height="200" bo rder="0">

    <?php

}

//Link for Pagination
$page_links = paginate_links( array(
    'base' => add_query_arg( 'pagenum', '%#%' ),
    'format' => '',
    'prev_text' => __( '«', 'aag' ),
    'next_text' => __( '»', 'aag' ),
    'total' => $num_of_pages,
    'current' => $pagenum
) );
if ( $page_links ) {
    echo '

' . $page_links . '

';
  }
 endif;
   }
  }
    ?>

thank you sir please help me please check my code and where i am wrong also suggest me.
thank you in advance.


text:
Q: What's the proper way to clean the earpiece? When I'm  just back from exercise, or work, and when I've used the earpiece they get really dirty or oily.   After I've bathed I don't want to use that same earpiece again without cleaning it properly.
Usually I'd take a tissue paper and just clean it.
Is there a proper way to clean the earpieces?

A: For Earbuds

*

*Use a gentle cleaner, like soap and warm water. No need to go too heavy-duty here; try a mix of dishwashing detergent and water. (To wipe! Not to dunk!)

*Use a gentle cloth with just a small amount of the soap mixture. Too
much soap could leave a residue on your earbuds, and too much water,
well that goes without saying.

*If there's a lot of dirt or dust in the metal part of your earbuds,
try brushing them with a dry toothbrush to dislodge the dust.

*Take a little rubbing alcohol and a q-tip. Barely wet the q-tip and clean the earbuds.
Also if you have just done some form of exercise and are really dirty then take a bath first! =>


text:
Q: Batch converting AIFF to WAV I have a few dozen AIF files that I need to convert to WAV. I have converted a few by opening them in Audacity and exporting them to WAV, but this is very slow. I would like to convert them all in batch. Is there a way to do this on OS X?

A: If you want to go for a shell solution, you can do it with ffmpeg.

*

*Option 1: download ffmpeg and extract the executable ffmpeg file. Copy it to a directory that is in your executable path, e.g. /usr/bin.
sudo cp ~/Downloads/ffmpeg /usr/bin/ffmpeg
sudo chmod +x /usr/bin/ffmpeg

*Option 2: Use Homebrew and brew install ffmpeg.
Now, in the folder with the AIF files, run this:
for f in *.aiff; do ffmpeg -i "$f" "${f%.aiff}.wav"; done

A: You should be able to convert between the two formats using iTunes instead of manually writing something yourself:
1.Open iTunes Preferences.
Windows: Choose Edit > Preferences.
Mac: Choose iTunes > Preferences.
2.Click the General button, then click the Importing Settings… button in the lower section of the window.
3.From the Import Using pop-up menu, choose the encoding format that you want to convert the song to, then click OK to save the settings.
4.Select one or more songs in your library, then from the File > Create New Version menu, choose one of the following (the menu item changes to show what's selected in your Importing preferences):
Create MP3 version
Create AAC version
Create AIFF version
Create WAV version
Create Apple Lossless version

Source: http://support.apple.com/kb/ht1550


text:
Q: Import conditionally a Library/Pod (Firebase) only if device runs iOS 10+ I observed crashes of my app when using Firebase/Analytics on devices running iOS 9.
When Firebase is completely removed from the target (I use cocoapods), the app runs stable.
How could I import Firebase module only in case the end device on which my target runs is > iOS 9 ?
I surrounded all calls to Firebase module within " #available(iOS 10, *)", e.g:
if #available(iOS 10, *) {
            FirebaseApp.configure()
}"

but still the module is imported because of:
import Firebase

How could I mark this module as "optional" within cocoapods so that it get imported only in case device is running iOS 10+?
PS:

*

*It seems possible to mark a library as "Optional" inside the target options: "Link Binaries with Libraries" but this only when using Swift Packet Manager. I could not find how to manage this using Cocoapods.


text:
Q: how to get the touching position of large image in android I need to get the touching position of image in android. Let me explain in detail as i am having a image user can touch and do pinchzoom for image resizing. When user touch the certain position i need to show the details about the particular position of image in seperate position.
If the image is in the fixed size of screen size then no problem to find position  it should fized for all device. How it possible? can any please help me..

A: OnTouchListener{
  @Override
  public boolean onTouch(View v, MotionEvent mv) {
    float x = mv.getRawX();
    float y = mv.getRawY();
    return true;
  }

This will give you the screen position of the touch. If you need to calculate the X/Y within the image which isn't the full size of the screen you can get the start X/Y coordinates of the image with
v = (ImageView) findViewById(R.id.myImageView);
float v_x = v.getTop();
float v_y = v.getLeft();
float real_x = x - v_x;
float real_y = y - v_y;


text:
Q: For loop not looping through all items in Outlook email folder I have written a number of macros in excel which open up emails from my inbox, save the attachment and then do some processing on the attachments. I now want to tidy everything up by moving all the emails from a specific sender to a specified folder and marking them as read.
I have written (for which read borrowed and modified) the following VBA. The problem is that it doesn't loop through all of the Items in the inbox.
Const olFolderInbox As Integer = 6

Sub MoveMail()

Dim oOlAp As Object, oOlns As Object, oOlInb As Object
Dim oOlItm As Object, oOlAtch As Object, SubFolder As Object
Dim eSender  As String
Dim i As Integer
i = 1

Set oOlAp = GetObject(, "Outlook.application")
Set oOlns = oOlAp.GetNamespace("MAPI")
Set oOlInb = oOlns.GetDefaultFolder(olFolderInbox)

Set SubFolder = oOlInb.Folders("FolderLevel2Name").Folders("FolderLevel3Name").Folders("FolderLevel4Name")

Debug.Print oOlInb.Items.Count

For Each oOlItm In oOlInb.Items
    eSender = oOlItm.SenderEmailAddress
    Debug.Print i & " --> " & eSender

    If eSender Like "name@domain.co.uk" Then
        'Debug.Print eSender
        oOlItm.UnRead = False
        DoEvents
        oOlItm.Save
        oOlItm.Move SubFolder
    End If

    i = i + 1

Next

End Sub

When I run this some of the items from name@domain.co.uk are moved to the correct folder, but not all. However without changing anything at all simply running it again moves more of the emails. Eventually if I run the macro enough times it eventually moves them all, without me changing a thing.
For example I tried to run it with 15 emails from name@domain.co.uk and 4 from other senders. The for loop stopped after processing 11 of the items in the inbox, 9 of which were from the specified sender and were moved the other two were correctly left in the inbox.
I then ran it again with the remaining 10 emails of which now 6 were from the specified sender. This time it looped through 6, 4 of which were from the specified sender and were moved. Eventually upon the third attempt it eventually looped through all of the remaining 6 items in the inbox, moving the remaining 2 from the specified sender. What's going wrong?


text:
Q: VF page to Division/Department breakdown of the Installed Package License Consumption VF page to Division/Department breakdown of the Installed Package License Consumption
I want to create a visual force page which will show all the installed packages we have .. how many licenses are consumed and which department/division(field on User Detail) consume them. I anyone have any ideas please share.

A: You can use following objects to get the details about the managed package and users which has been assigned licenses for the package.
PackageLicense
UserPackageLicense
Now, I am sure, once you have the user ids then you can all the information related to their departments in your apex and then can show them on the visualforce page.