text:
Q: AVCaptureSession and AVCaptureMovieFileOutput frame timestamp I am recording a movie with AVCaptureSession and AVCaptureMovieFileOutput. I am also recording  acceleration data and trying to align the acceleration data with the video.
I am trying to figure out a way to get the time the video file recording started. I am doing the following:
currentDate = [NSDate date];
[output startRecordingToOutputFileURL:fileUrl recordingDelegate:self];

However, according to my tests, the video recording starts 0.12 seconds before the call to startRecordingToOutputFileURL is made. I'm assuming this is because the various video buffers are already full of data which get added to the file.
Is there anyway to get the actual NSDate of the first frame of the video?

A: I had the same issue and I finally found the answer. I will write all code below this, but the missing piece I was looking for was:
self.captureSession.masterClock!.time

The masterClock in the captureSession is the clock where the relative time every buffer is based on (presentationTimeStamp).

Full code and explanation
First thing you have to do is convert the AVCaptureMovieFileOutput to AVCaptureVideoDataOutput and AVCaptureAudioDataOutput. So make sure your class implements AVCaptureVideoDataOutputSampleBufferDelegate and AVCaptureAudioDataOutputSampleBufferDelegate. They share the same function, so add it to your class (implementation I will get to later):
    let videoDataOutput = AVCaptureVideoDataOutput()
    let audioDataOutput = AVCaptureAudioDataOutput()

    func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
        // I will get to this
    }

At the capture session adding the output my code looks like this (you can change the videoOrientation and other things if you want)
            if captureSession.canAddInput(cameraInput)
                && captureSession.canAddInput(micInput)
//                && captureSession.canAddOutput(self.movieFileOutput)
                && captureSession.canAddOutput(self.videoDataOutput)
                && captureSession.canAddOutput(self.audioDataOutput)
            {
                captureSession.beginConfiguration()
                captureSession.addInput(cameraInput)
                captureSession.addInput(micInput)
//                self.captureSession.addOutput(self.movieFileOutput)

                let videoAudioDataOutputQueue = DispatchQueue(label: "com.myapp.queue.video-audio-data-output") //Choose any label you want

                self.videoDataOutput.alwaysDiscardsLateVideoFrames = false
                self.videoDataOutput.setSampleBufferDelegate(self, queue: videoAudioDataOutputQueue)
                self.captureSession.addOutput(self.videoDataOutput)

                self.audioDataOutput.setSampleBufferDelegate(self, queue: videoAudioDataOutputQueue)
                self.captureSession.addOutput(self.audioDataOutput)

                if let connection = self.videoDataOutput.connection(with: .video) {
                    if connection.isVideoStabilizationSupported {
                        connection.preferredVideoStabilizationMode = .auto
                    }
                    if connection.isVideoOrientationSupported {
                        connection.videoOrientation = .portrait
                    }
                }

                self.captureSession.commitConfiguration()

                DispatchQueue.global(qos: .userInitiated).async {
                    self.captureSession.startRunning()
                }
            }

To write the video like you would with AVCaptureMovieFileOutput, you can use AVAssetWriter. So add the following to your class:
    var videoWriter: AVAssetWriter?
    var videoWriterInput: AVAssetWriterInput?
    var audioWriterInput: AVAssetWriterInput?

    private func setupWriter(url: URL) {
        self.videoWriter = try! AVAssetWriter(outputURL: url, fileType: AVFileType.mov)

        self.videoWriterInput = AVAssetWriterInput(mediaType: .video, outputSettings: self.videoDataOutput.recommendedVideoSettingsForAssetWriter(writingTo: AVFileType.mov))
        self.videoWriterInput!.expectsMediaDataInRealTime = true
        self.videoWriter!.add(self.videoWriterInput!)

        self.audioWriterInput = AVAssetWriterInput(mediaType: .audio, outputSettings: self.audioDataOutput.recommendedAudioSettingsForAssetWriter(writingTo: AVFileType.mov))
        self.audioWriterInput!.expectsMediaDataInRealTime = true
        self.videoWriter!.add(self.audioWriterInput!)

        self.videoWriter!.startWriting()
    }

Every time you want to record, you first need to setup the writer. The startWriting function doesn't actually start writing to the file, but prepares the writer that something will be written soon.
The next code we will add the code to start or stop recording. But please note I still need to fix the stopRecording. stopRecording actually finishes recording too soon, because the buffer is always delayed. But maybe that doesn't matter to you.
    var isRecording = false
    var recordFromTime: CMTime?
    var sessionAtSourceTime: CMTime?

    func startRecording(url: URL) {
        guard !self.isRecording else { return }
        self.isRecording = true
        self.sessionAtSourceTime = nil
        self.recordFromTime = self.captureSession.masterClock!.time //This is very important, because based on this time we will start recording appropriately
        self.setupWriter(url: url)
        //You can let a delegate or something know recording has started now
    }

    func stopRecording() {
        guard self.isRecording else { return }
        self.isRecording = false
        self.videoWriter?.finishWriting { [weak self] in
            self?.sessionAtSourceTime = nil
            guard let url = self?.videoWriter?.outputURL else { return }

            //Notify finished recording and pass url if needed
        }
    }

And finally the implementation of the function we mentioned at the beginning of this post:
    private func canWrite() -> Bool {
        return self.isRecording && self.videoWriter != nil && self.videoWriter!.status == .writing
    }

    func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
        guard CMSampleBufferDataIsReady(sampleBuffer), self.canWrite() else { return }

        //sessionAtSourceTime is the first buffer we will write to the file
        if self.sessionAtSourceTime == nil {
            //Make sure we start by capturing the videoDataOutput (if we start with the audio the file gets corrupted)
            guard output == self.videoDataOutput else { return }
            //Make sure we don't start recording until the buffer reaches the correct time (buffer is always behind, this will fix the difference in time)
            guard sampleBuffer.presentationTimeStamp >= self.recordFromTime! else { return }
            self.sessionAtSourceTime = sampleBuffer.presentationTimeStamp
            self.videoWriter!.startSession(atSourceTime: sampleBuffer.presentationTimeStamp)
        }

        if output == self.videoDataOutput {
            if self.videoWriterInput!.isReadyForMoreMediaData {
                self.videoWriterInput!.append(sampleBuffer)
            }
        } else if output == self.audioDataOutput {
            if self.audioWriterInput!.isReadyForMoreMediaData {
                self.audioWriterInput!.append(sampleBuffer)
            }
        }
    }

So the most important thing that fixes the time difference start recording and your own code is the self.captureSession.masterClock!.time. We look at the buffer relative time until it reaches the time you started recording. If you want to fix the end time as well, just add a variable recordUntilTime and check if in the didOutput sampleBuffer method.

A: if i get your question correctly, you want to know the timestamp of when the first frame is recorded. you could try
CMTime captureStartTime = nil;

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {

      if !captureStartTime{
         captureStartTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer);
      }
  // do the other things you want
 }


text:
Q: Why do I have to use [0] after a jQuery query Give that code:
 var lastVisibleElement =$('#test > div:visible').last()[0];

Why do I have to use [0] to get my html. What is the [0] for?

A: Just use console.log() to analyse this yourself
var lastVisibleElement = $('#test > div:visible').last()
console.log(lastVisibleElement);

You will see jQuery results/matches are returned as an object with an array type wrapper. So [0] simply refers to the first element. If using for loops the eq(num) function comes in handy
var objects = $('.selector');
for (var i = 0; i < objects.length; i++) {
    console.log(objects.eq(i));
}

A: The array notation [0] is used to get a reference to the actual DOM elements instead of the jQuery object.
$( "#foo" )[ 0 ]; // Equivalent to document.getElementById( "foo" )

Read this

A: When creating new elements (or selecting existing ones), jQuery returns the elements in a collection of jQuery objects. jQuery provides a method named .get() which instead of returning a jQuery-wrapped DOM element, it returns the DOM element itself.
// Selecting only the first <h1> element on the page.

var firstHeadingElem = $( "h1" ).get( 0 );

Alternatively, because the jQuery object is "array-like," it supports array subscripting via brackets:
// Selecting only the first <h1> element on the page (alternate approach).

var firstHeadingElem = $( "h1" )[ 0 ];

From: The jQuery Object

redpajama_set_name: RedPajamaStackExchange


text:
Q: Split string by commas using istringstream I tried this code which can split the string by comma:
string spa ="12,233,434,2";
istringstream iss(spa + ",");
int val;
char dot =',';
while(iss >> val >> dot){
     cout << val << endl;
}

But I have no idea how it works. It seems to extract the value firstly, then right-shifts?

A: iss >> val >> dot reads an int and a char, which happens to match the format of the input.
Their values prior to reading doesn't matter at all.
The while tests if the read was successful, and stops when the input fails.


text:
Q: "Spread" quantities from points to underlying raster map within a radius I need to generate a raster map by "spreading" point values to the surrounding pixels, with spreading criteria based on the pixel Boolean value (T/F) and maximum distance.
For example, if I have a point with value 100 (representing kg of manure), I want to spread those 100 kg in the surrounding pixels within a maximum distance (radius) of 20 km. Ideally I would also like to flag pixels that should not be considered (do not receive manure) using the Boolean value. The spreading can be homogeneous (all pixel get the same value until I reach 100) or follow a distance gradient, it is not so relevant at this stage, but the sum of all pixels must correspond to the sum of all points values.
So far I have prepared the points layer, the underlying raster binary map and the distance map with max radius but I am struggling to find the GIS tools/workflow to accomplish the "spreading", I have checked the distance analysis tools with little success. I ideally work with QGIS but also ArcGis is fine. I am more concerned about the strategy to follow than the tool itself.


text:
Q: How to make sure your Magento 2.0 cron job is running How do I make sure my Magento cron job is running? I setup cron per the Magento 2 installation instructions for the log files.
See screen shot (click to enlarge):

I am running Magento CE 2.0.2
Server Platform:

*

*Operating System:    CENTOS 7.2 x86_64

*CPU: Dual Intel(R) Xeon(R) CPU E5-2620 0 @ 2.00GHz

*RAM: 256 GB

*Storage: SSD Based Cloud Storage

*Network: 20 Gigabits

*Server UI:   cPanel/WHM 54.0 Build 18 (latest/stable)

*Apache:  2.2.26

*MySQL:   5.6.29

*PHP: 5.6.18

Crontab for the cPanel user host account:
*/1 * * * * /usr/local/bin/php -c /usr/local/lib/php.ini /home/abcdefg/public_html/bin/magento cron:run > /home/abcdefg/public_html/var/log/magento.cron.log&
*/1 * * * * /usr/local/bin/php -c /usr/local/lib/php.ini /home/abcdefg/public_html/update/cron.php > /home/abcdefg/public_html/var/log/update.cron.log&
*/1 * * * * /usr/local/bin/php -c /usr/local/lib/php.ini /home/abcdefg/public_html/bin/magento setup:cron:run > /home/abcdefg/public_html/var/log/setup.cron.log&

Added 2016-05-05
I was informed that the MySQL cron_schedule contains cron activity. So I looked at the table and found these entries. Here is a snippet of each of the unique entries in that table showing their latest entry.
55534 aggregate_sales_report_coupons_data running Class Magento\SalesRule\Crone\AggregateSalesReportCouponsData does not exist 2016-05-04 19:54:02 2016-05-04 20:00:00 NULL NULL
56093 captcha_delete_expired_images success NULL 2016-05-05 07:06:03 2016-05-05 07:10:00 2016-05-05 07:10:02 2016-05-05 07:10:02
56081 captcha_delete_old_attempts success NULL 2016-05-05 06:51:02 2016-05-05 07:00:00 2016-05-05 07:00:03 2016-05-05 07:00:03
56070 catalog_index_refresh_price success NULL 2016-05-05 06:51:02 2016-05-05 07:00:00 2016-05-05 07:00:03 2016-05-05 07:00:03
56094 magento_newrelicreporting_cron success NULL 2016-05-05 07:06:03 2016-05-05 07:06:00 2016-05-05 07:07:03 2016-05-05 07:07:03
56092 newsletter_send_all success NULL 2016-05-05 07:06:03 2016-05-05 07:10:00 2016-05-05 07:10:02 2016-05-05 07:10:02
56071 sales_clean_orders success NULL 2016-05-05 06:51:02 2016-05-05 07:00:00 2016-05-05 07:00:03 2016-05-05 07:00:03
56084 sales_grid_order_async_insert success NULL 2016-05-05 07:06:03 2016-05-05 07:06:00 2016-05-05 07:07:03 2016-05-05 07:07:03
56087 sales_grid_order_creditmemo_async_insert success NULL 2016-05-05 07:06:03 2016-05-05 07:06:00 2016-05-05 07:07:03 2016-05-05 07:07:03
56085 sales_grid_order_invoice_async_insert success NULL 2016-05-05 07:06:03 2016-05-05 07:06:00 2016-05-05 07:07:03 2016-05-05 07:07:03
56086 sales_grid_order_shipment_async_insert success NULL 2016-05-05 07:06:03 2016-05-05 07:06:00 2016-05-05 07:07:03 2016-05-05 07:07:03
56091 sales_send_order_creditmemo_emails success NULL 2016-05-05 07:06:03 2016-05-05 07:06:00 2016-05-05 07:07:03 2016-05-05 07:07:03
56088 sales_send_order_emails success NULL 2016-05-05 07:06:03 2016-05-05 07:06:00 2016-05-05 07:07:03 2016-05-05 07:07:03
56089 sales_send_order_invoice_emails success NULL 2016-05-05 07:06:03 2016-05-05 07:06:00 2016-05-05 07:07:03 2016-05-05 07:07:03
56090 sales_send_order_shipment_emails success NULL 2016-05-05 07:06:03 2016-05-05 07:06:00 2016-05-05 07:07:03 2016-05-05 07:07:03

Also, how can I get the 3 log file crons to run that I setup upon initial install:
*/1 * * * * /usr/local/bin/php -c /usr/local/lib/php.ini /home/abcdefg/public_html/bin/magento cron:run >> /home/abcdefg/public_html/var/log/magento.cron.log&
*/1 * * * * /usr/local/bin/php -c /usr/local/lib/php.ini /home/abcdefg/public_html/update/cron.php >> /home/abcdefg/public_html/var/log/update.cron.log&
*/1 * * * * /usr/local/bin/php -c /usr/local/lib/php.ini /home/abcdefg/public_html/bin/magento setup:cron:run >> /home/abcdefg/public_html/var/log/setup.cron.log&

Finally, I remember a few years back when I installed a Magento instance for a client in Magento v1 that somehow the pages index & cache and product index & cache got updated automatically through cron somehow. How can I get Magento 2 to do that same thing? Every time I login into Magento 2 in the Admin UI backend, I need to reindex & flush cache so my client's products can appear on the site.
Test of 2016-05-05 at 12:05 p.m. ET
(1) I truncated the cron_schedule table. Then after 1 minute here is the new table:

Here's the table after cron ran:

A: Truncate the cron_schedule table and see if it gets re-populated with scheduled tasks after a few minutes.
Rough, I know, but should give you an answer.
Also, maybe it's worth doing this on a staging env. first.
Use:
truncate cron_schedule;

After a few minutes use:
select * from cron_schedule;

A: Try specifying the user which is used to run the command. Don't use root for it, just the magento user. For example:
*/1 * * * * username /usr/local/bin/php -c /usr/local/lib/php.ini /home/abcdefg/public_html/bin/magento cron:run > /home/abcdefg/public_html/var/log/magento.cron.log&
*/1 * * * * username /usr/local/bin/php -c /usr/local/lib/php.ini /home/abcdefg/public_html/update/cron.php > /home/abcdefg/public_html/var/log/update.cron.log&
*/1 * * * * username /usr/local/bin/php -c /usr/local/lib/php.ini /home/abcdefg/public_html/bin/magento setup:cron:run > /home/abcdefg/public_html/var/log/setup.cron.log&

Example from my server (CENTOS 7) which is working fine:
*/1 * * * * myuser php -c /etc/php.ini /srv/html/path_to_magento/bin/magento cron:run > /srv/html/path_to_magento/var/log/cron.log

A: Seems to happen every once and awhile with my Vagrant machine. I got the same notice, all I had to do to get rid of it was to reindex data using:

php bin/magento indexer:reindex

A: You should check three things:

*

*sudo service cron status to check if the service is running on the server

*ls -la and check if your files user & group are the same as the one you configured on the cron crontab -u xxx -e

*select * from cron_schedule and check if the cron table is being populated.

A: Following are useful:

*

*MySQL Table "cron_schedule" is your friend, open phpmyadmin or any mysql client, execute this:

select * from cron_schedule;
look for columns "created_at", "executed_at" and "messeges" can give you helpful information regarding cron working or ran.

*Use ssh to connect to server and execute the cron command manually if you see "Ran jobs by schedule.", it mean cron_schedule table has been updated.

A: As per the Magento Dev Docs,
All cron data is written to the cron_schedule table in the Magento database. The table provides a history of cron jobs, including:

*

*Job ID and code

*Status

*Created date

*Scheduled date

*Executed date

*Finished date

To see records in the table, log in to the Magento database on the command line and enter

SELECT * from cron_schedule;

A: Open cron.php at root of the Magento directory and place:
Mage::log('cron is running', null, 'myCronLog.log');

Check this file after some interval and check it whether log file is generated or not under var/log. If it's generated then your cron is running.


text:
Q: How to su to another user in mac OS X? I came from Linux world , and not familiar with OS X admin.
Now I want to su to another user , but it just not working ...
Where goes wrong here ?
smallufo@miniserver:~ $ whoami
smallufo
smallufo@miniserver:~ $ su - postgres
Password:
smallufo@miniserver:~ $ whoami
smallufo
smallufo@miniserver:~ $

I input correct password , but why I cannot su to postgres ?
Sorry if it is a dumb question , but I've been stuck with it the whole night...
Thanks a lot !

A: su should work normally in OS X.  @Scott Warren's idea about the postgres user's shell is a possible explanation, but OS X doesn't use /etc/passwd except during bootup.  Normal users (and groups etc) are stored in .plist files under /var/db/dslocal/nodes/Default/.  The easy way to look at (and modify) them is with the dscl command:
dscl . -read /Users/postgres  # prints all user attributes
dscl . -read /Users/postgres UserShell # prints just the default shell

If necessary, you can set the shell the same way:
sudo dscl . -create /Users/postgres UserShell /bin/bash

A: I don't have Postgres installed but check your /etc/passwd file.  The last entry for that user account will be the shell that user uses.  In my passwd file the accounts that shouldn't login (_lp,_postfix,etc.) have a shell of /usr/bin/false but accounts that can login are usually /bin/sh.


text:
Q: problem in silverlight 4 async how to wait till result come Here is what i have problem
i have following code :
  //Get All master record
        entryE_QuestMaster = new ObservableCollection<E_QuestMaster>();
        QuestVM.getExamsMasterbyExamID(eUtility.ConvertInt32(this.txtID.Text), ref entryE_QuestMaster);
        //

        //Loop to show questions
        int iNumber=1;
        foreach (var oIn in entryE_QuestMaster)
        {
            Node subNode = new Node();
            subNode.Content = oIn.e_Question;
            subNode.Name = "Quest_" + iNumber.ToString().Trim();
            subNode.Tag = oIn.e_QID.ToString();
            subNode.Icon = "/Images/Number/" + iNumber.ToString().Trim() + ".gif";
            iNumber++;
            this.tvMainNode.Nodes.Add(subNode);
        }

here is async method calling wcf service
  /// <summary>
    ///
    /// </summary>
    /// <param name="ID"></param>
    public void getExamsMasterbyExamID(int ID, ref ObservableCollection<E_QuestMaster> iCollectionData)
    {
        ObservableCollection<E_QuestMaster> iCollectionDataResult = iCollectionData;
        eLearningDataServiceClient client = new eLearningDataServiceClient();
        client.getExamsMasterCompleted+=(s,e)=>
            {
                iCollectionDataResult = e.Result;
            };
        client.getExamsMasterAsync(ID);
    }

problem : when ever system run --> QuestVM.getExamsMasterbyExamID(eUtility.ConvertInt32(this.txtID.Text), ref entryE_QuestMaster);
its does not wait till i get e.result its just move to next line of code which is
foreach loop.
plssss help any one or give idea with sample code what should i do to wait till e.result
i wanted to some how wait till i get e.result
any idea ?

A: one simple solution. Move the code that you want to execute after getting e.result in this loop.
client.getExamsMasterCompleted+=(s,e)=>
          {
                iCollectionDataResult = e.Result;
            };

A: Add an Action to the getExamsMasterbyExamID method, then execute the callback after is completed.
public void getExamsMasterbyExamID(int ID, ref ObservableCollection<E_QuestMaster> iCollectionData,Action<object> callback)
{
    ObservableCollection<E_QuestMaster> iCollectionDataResult = iCollectionData;
    eLearningDataServiceClient client = new eLearningDataServiceClient();
    client.getExamsMasterCompleted+=(s,e)=>
        {
            iCollectionDataResult = e.Result;
            //the callback will be executed on the calling method
            callback(e.Result);
        };
    client.getExamsMasterAsync(ID);
}

now when you call the Async method add the loop inside the callback like this:
    entryE_QuestMaster = new ObservableCollection<E_QuestMaster>();
    QuestVM.getExamsMasterbyExamID(eUtility.ConvertInt32(this.txtID.Text), ref entryE_QuestMaster,r=>
    {
        int iNumber=1;
       foreach (var oIn in entryE_QuestMaster)
       {
            Node subNode = new Node();
            subNode.Content = oIn.e_Question;
            subNode.Name = "Quest_" + iNumber.ToString().Trim();
            subNode.Tag = oIn.e_QID.ToString();
            subNode.Icon = "/Images/Number/" + iNumber.ToString().Trim() + ".gif";
            iNumber++;
            this.tvMainNode.Nodes.Add(subNode);
      }
   });

after 2 months prob this wont be useful for the asker but maybe for someone else...


text:
Q: load image inside JavaScript function i have function to get image pixels color
function getImage(imgsrc){
    var img = $( "<img>", {
        src: imgsrc
    });
    var imageMap = new Object();
    img.load(function() {
        var canvas = $('<canvas/>')[0].getContext('2d');
        canvas.width = this.width;
        canvas.height = this.height;
        canvas.drawImage(this, 0, 0, this.width, this.height);
        for(var i = 0;i < this.width;i++){
            imageMap[i] = new Object();
            for(var j = 0;j < this.width;j++){
                var pixelData = canvas.getImageData(i, j, 1, 1).data;
                imageMap[i][j] = rgbToHex(pixelData[0],pixelData[1],pixelData[2]);
            }
        }
            console.log(imageMap[40][40]);
    });
    console.log(imageMap[40][40]);
    return imageMap;
}

but it return undefined(it print 2nd console.log first)
what's wrong?
thx.

A: Your function is returning undefined because load is asynchronous. getImage is trying to return something before load finished loading.
You'll need to pass a callback to execute when the image has loaded, to getImage:
function getImage(imgsrc, callback){
    var img = $( "<img>", {
        src: imgsrc
    });
    var imageMap = new Object();
    img.load(function() {
        var canvas = $('<canvas/>')[0].getContext('2d');
        canvas.width = this.width;
        canvas.height = this.height;
        canvas.drawImage(this, 0, 0, this.width, this.height);
        for(var i = 0;i < this.width;i++){
            imageMap[i] = new Object();
            for(var j = 0;j < this.width;j++){
                var pixelData = canvas.getImageData(i, j, 1, 1).data;
                imageMap[i][j] = rgbToHex(pixelData[0],pixelData[1],pixelData[2]);
            }
        }
        console.log(imageMap[40][40]);
        callback(imageMap)
    });
}

Then you just call the function like this:
getImage("http://some.src.jpg", function(imageMap){
    // Do stuff with imageMap here;
});

Of course, you can also define the callback elsewhere:
var myCallback = function(imageMap){
    // Do stuff with imageMap here;
};

getImage("http://some.src.jpg", myCallback);

A: Now that promises starts to get [have] wide support you can do this instead:

// Define a common load function:
function loadImage(url) {
  return new Promise(function(resolve, reject) {
    var img = new Image;
    img.onload = function() { resolve(this) };
    img.onerror = img.onabort = function() { reject("Error loading image") };
    img.src = url;
  })
}

// Usage:
loadImage("https://i.stack.imgur.com/ynBVu.gif").then(function(image) {

  // Use the `image` here
  document.body.appendChild(image);

})

The promise will take the callback, states etc. internally. IE will get support in next version (there exists polyfill for it).

A: jQuery.load() is asynchronous, meaning the code will continue while it goes of working away.
If you want to process the imagemap, one option could be to pass a callback you execute ones the imagemap is populated, similar to:
function yourCallback(imageMap){
// ...process imageMap;
}

function getImage(imgsrc, yourCallback) {
    var img = $("<img>", {
        src: imgsrc
    });
    var imageMap = new Object();
    img.load(function () {
        var canvas = $('<canvas/>')[0].getContext('2d');
        canvas.width = this.width;
        canvas.height = this.height;
        canvas.drawImage(this, 0, 0, this.width, this.height);

        for (var i = 0; i < this.width; i++) {
            imageMap[i] = new Object();
            for (var j = 0; j < this.width; j++) {
                var pixelData = canvas.getImageData(i, j, 1, 1).data;
                imageMap[i][j] = rgbToHex(pixelData[0], pixelData[1], pixelData[2]);
            }
        }

        yourCallback(imageMap);
    });
}

getImage(imgsrc,yourCallback);


text:
Q: Android-how to count repeated items in a gridview i have a gridview of size 7x7 which is inflated with images at random at each item position; choosen from an array of 7 images (7 color ball images).. now i want to count how many times a particular image is shown in the gridview..i.e how many times lets say red ball image is shown in the grid view ..i have also assigned tags and trying to count  the tag value assigned to each view
in my oncreate method i m using this loop... G1 is the gridview object..balloontag[] is used for storing the tag values and toast is just for checking whether i am able to retrieve tag value or not
       for( int i=0; i<G1.getCount(); i++)
      {

    ImageView v2= (ImageView)G1.getChildAt(i);
    balloontags[i]=(Integer)v2.getTag();
    Toast.makeText(Cacrballoonclass.this, "lets c tag=" +

            balloontags[i], Toast.LENGTH_SHORT).show();

      }

             My adapter getview method

             @Override
     public View getView(int arg0, View arg1, ViewGroup arg2) {

        // TODO Auto-generated method stub

    ImageView balloonimageview;

        if(arg1==null){
            balloonimageview = new ImageView(ballooncontext);
            balloonimageview.setLayoutParams(new GridView.LayoutParams(75,75));
            balloonimageview.setScaleType(ImageView.ScaleType.CENTER_CROP);
            balloonimageview.setPadding(7, 7, 7, 7);
        } else {
                balloonimageview = (ImageView)arg1;
                }
        //lets inflate balloon randomly

        int rballoon = new Random().nextInt(ballooninstruct.length);

   balloonimageview.setImageResource(balloonthumbs[rballoon]);
       balloonimageview.setTag(balloonthumbs[rballoon]);

        return balloonimageview;
    }

A: What i would do is modify the adapter of the Gridview to hold additional information on the Gridview item, like an id / tag, and when i'll need to count items, i'll do it with a HashMap on the data content of the adapter and no the Gridview itself.

A:                 for(int k=0; k<G1.getChildCount(); k++)
                {
                 ImageView ballcountview = (ImageView)G1.getChildAt(k);
                 Integer b = (Integer)ballcountview.getTag();
                if(balloon_myid==b)
                    {
                        b_count++;

                    }

                } //for loop ends

I solved my problem by iterating through each item and retrieving the assigned tag and if matched, count is incremented.


text:
Q: JS for mouseover image upload button (like Facebook) I'm trying to build an image upload system like Facebook's where when you mouseover an image, a button (a div, not an actual html button) appears to select an image.  So far, I'm using jQuery's hover method.  The problem is, when I hover over the image, the button appears, but then when I hover over the button, the function assumes I'm no longer hovering over the image, and the button disappears.  Of course then since the button is gone, I'm hovering over the image again and the button reappears.  The end result is this sort of flickering effect when I move my mouse on the image.
I can't seem to figure out a way around it.  I tried creating a separate hover event for the button itself that removes the hover event for the image and then replaces it on mouseout, but the image mouseout event seems to fire first, and it does nothing.
Only thing I can think is to use a setTimeout, but this seems sloppy.  Seeing as Facebook is doing something similar, I'm sure there's a super clean way to handle it.
Any thoughts?  Thanks!

A: Try using mouseenter() instead of hover() to handle bubbling

The mouseenter event differs from mouseover in the way it handles
  event bubbling. If mouseover were used in this example, then when the
  mouse pointer moved over the Inner element, the handler would be
  triggered. This is usually undesirable behavior. The mouseenter event,
  on the other hand, only triggers its handler when the mouse enters the
  element it is bound to, not a descendant. So in this example, the
  handler is triggered when the mouse enters the Outer element, but not
  the Inner element.


text:
Q: How can get the value of Radio Button Inside Listview Click on Button in Android I have Radio Group of Three Radio Button  and a submit button also inside of ListView. I want to get the Button listener and also get the value of selected radio button. Below to my listview item view. please help me.

A: put this code inside click event
if(rg1.getCheckedRadioButtonId()!=-1){
    int id= rg1.getCheckedRadioButtonId();
    View radioButton = rg1.findViewById(id);
    int radioId = radioGroup.indexOfChild(radioButton);
    RadioButton btn = (RadioButton) rg1.getChildAt(radioId);
    String selection = (String) btn.getText();
}

A: You will need to write onClickListener in your custom adapter's getView method:
public View getView(final int position, View convertView,ViewGroup parent)
{

    Button submit= (Button) convertView.findViewById(R.id.submit);

    submit.setOnClickListener(new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            RadioGroup rGroup = (RadioGroup)convertView.findViewById(R.id.radiogroup);
            int checkedID = rGroup.getCheckedRadioButtonId();
            if(checkedID >=0 )
                RadioButton rButton = (RadioButton) convertView.findViewById(checkedId);
            else{
                //no radio button was checked
            }
        }

    });
    return convertView ;
}

Hope this helps.

A: RadioGroup group=(RadioGroup) findViewById(R.id.radioGroup1);

        group.setOnCheckedChangeListener(new OnCheckedChangeListener()
           {

            public void onCheckedChanged(RadioGroup group, int checkedId)
               {
                // TODO Auto-generated method stub
                if(radiobutton1.isChecked())
                  {
                    //your code
                  }
                else if(radiobutton2.isChecked())
                  {

                     //your code
                  }
             }
        });


text:
Q: How to prevent option to be deselected when pressed key enter in vue multiselect? I have a component that uses Multiselect from @vueform/multiselect. The problem is when the user selects an option and the tag is created, if enter is pressed it will deselect that option. How am I able to control that? I tried adding @keydown.enter.prevent="deselect" but it doesn't work.
Here is how my component looks:
<template>
    <Multiselect
        v-model="propValue"
        :options="this.options"
        :placeholder=this.$filters.translate(this.placeholder)
        :closeOnSelect="false"
        :searchable="this.searchable"
        :noResultsText="$filters.translate(this.labels.noResult)"
        ref="multiselect"
        @change="change"
        @click="click"
        @deselect="remove"
        :mode="this.mode"
        :hideSelected='false'
        :max="this.limit">
        <template v-slot:caret>

        </template>
        <template v-slot:beforelist v-if="showWarning">

{{this.warningMessage}}

        </template>
    </Multiselect>
</template>

Thanks in advance, appreciate the help.


text:
Q: How to use Typescript to define a generic function signature I have this dataset:
const dataset = [
  { date: "2022-01-01", category: "red", value: 10 },
  { date: "2022-01-01", category: "blue", value: 20 },
  { date: "2022-01-01", category: "gold", value: 30 },
  { date: "2022-01-01", category: "green", value: 40 },
  { date: "2022-01-02", category: "red", value: 5 },
  { date: "2022-01-02", category: "blue", value: 15 },
  { date: "2022-01-02", category: "gold", value: 25 },
  { date: "2022-01-02", category: "green", value: 35 }
];

And I need to flat the dataset to get this:
const flattenDataset = [
  { "date": "2022-01-01", "red": 10, "blue": 20, "gold": 30, "green": 40 },
  { "date": "2022-01-02", "red": 5, "blue": 15, "gold": 25, "green": 35 }
]

So group dataset by dates and for each category create a key with value as value.
I created this function:
export function flatDataset(
  dataset: any,
  mainProperty: string,
  categoryProperty: string,
  valueProperty: string
) {
  if (dataset.length === 0 || !mainProperty) {
    return (dataset as unknown);
  }
  const columnToBeFlatValues = uniqBy(dataset, categoryProperty).map(
    (d) => d[categoryProperty]
  );
  const datasetGroupedByMainProperty = groupBy(dataset, mainProperty);
  const datasetGroupedByMainCategoryFlat = Object.entries(
    datasetGroupedByMainProperty
  ).map(([date, datasetForDate]) => {
    const categoriesObject = columnToBeFlatValues.reduce((acc, value) => {
      const datum = datasetForDate.find(
        (d) => d[mainProperty] === date && d[categoryProperty] === value
      );
      acc[value] = datum?.[valueProperty];
      return acc;
    }, {});
    return {
      [mainProperty]: date,
      ...categoriesObject
    };
  });
  return datasetGroupedByMainCategoryFlat;
}

It works but I would like to fix TypeScript.
For example the dataset type should not be any but an array of objects with keys with name mainProperty, categoryProperty, valueProperty.
For example, dataset could also be:
const dataset = [
  { apple: ..., color: ..., something: ... },
  ...
];
const flattenDataset = flatDataset(dataset, 'apple', 'color', 'something')

How can I do that?

A: There's a few way to make it
let obj = { apple: 's', sonic: 'a' , etc: 'd'}

function MyFunction<T, K extends keyof T>(obj: T, ...args:K[]): void { }

MyFunction(obj, 'apple', 'sonic', 'etc')

Using Generics with Rest Arguments. I used this post as example to create the rest args. I recommend you create an interfaces for maintein all sorted

A: I believe this is the right generic types you're looking for.
The main trick is using { [k in Enum]: string }, which allows dynamically restricting a key of an object to be a part of a union of strings.
Please note you're using functions without their implementations, so it's hard to actually test it.
function flatDataset<Main extends string, Category extends string, Value extends string>(
    dataset: ({ [k in Main | Category]: string } & { [k in Value]: number })[],
    mainProperty: Main,
    categoryProperty: Category,
    valueProperty: Value,
): ({ [k in (typeof dataset)[number][Main]]: string }
    & { [k in (typeof dataset)[number][Category]]: number })[]


text:
Q: Can register multiple MongoClient in built-in ASP.NET Core dependency injection? I want to register multiple MongoClient with different connection strings in built-in ASP.NET Core dependency injection.
How can I do this?
Thanks.

A: You can just create a factory for creating IMongoDatabase and inject it instead
public interface IMongoFactory
{
    IMongoDatabase Create(string databaseName);
}

public class MongoFactory : IMongoFactory
{
    public IMongoDatabase Create(string databaseName)
    {
        string connectionString = "some connection string"; //replace with your value or use configuraiton

        var client = new MongoClient(connectionString);
        var database = client.GetDatabase(databaseName);
        return database;
    }
}

Usage
public class TestController : ControllerBase
{
    //...
    private readonly IMongoDatabase _mongoDatabase;

    public TestController(IMongoFactory mongoFactory)
    {
        _mongoDatabase = mongoFactory.Create("TheDB");
    }
    //...
}

Or if you just want to use a predefined set of databases you can just use enum instead of specifying databaseName directly or implement multiple methods in factory
public class MongoFactory : IMongoFactory
{
    public IMongoDatabase Create(MongoDatabaseInstance databaseInstance)
    {
        string connectionString = "some connection string"; //replace with your value or use configuraiton

        string databaseName = GetDatabaseName(databaseInstance);
        var client = new MongoClient(connectionString);
        var database = client.GetDatabase(databaseName);
        return database;
    }

    private string GetDatabaseName(MongoDatabaseInstance databaseInstance)
    {
        switch (databaseInstance)
        {
            case MongoDatabaseInstance.TheDB:
                return "TheDB";
            case MongoDatabaseInstance.Second:
                return "Second";
            case MongoDatabaseInstance.Main:
                return "Main";
            default:
                throw new ArgumentException(nameof(databaseInstance));
        }
    }
}


text:
Q: How do I write function to delay window load for 3 seconds? I want to delay the action performed by the JavaScript code below, for 3 seconds. How do I do this?
window.addEventListener("load", function alertFunc() {
    const loader = document.querySelector(".loader");
    loader.className += " hidden"; //class="loader hidden"
});

A: You can use setTimeout function with 3000 as
 window.addEventListener("load", function alertFunc() {

        setTimeout(()=>{
        const loader = document.querySelector(".loader");
        loader.className += " hidden"; //class="loader hidden"
        }, 3000)
    });

A: window.addEventListener("load", function alertFunc() {
    setTimeout(function() {
        const loader = document.querySelector(".loader");
        loader.className += " hidden"; //class="loader hidden"
    }, 3000);
});

https://www.w3schools.com/jsref/met_win_settimeout.asp

A: You can use setTimeout from javascript

window.addEventListener("load", function() {
  console.log("Doc Loaded");
  setTimeout(callAfter3Second,3000);
});

function callAfter3Second(){
    console.log("3 second Waiting Done");
}


text:
Q: Remove form-inline class I'am using material design bootstrap datatable in my application.
https://datatables.net/examples/styling/material.html
Bootstrap's form-inline class conflicting with the datables style.
html

            Name
            Position
            Office
            Age
            Start date
            Salary

            Name
            Position
            Office
            Age
            Start date
            Salary

            Tiger Nixon
            System Architect
            Edinburgh
            61
            2011/04/25
            $320,800

            Garrett Winters
            Accountant
            Tokyo
            63
            2011/07/25
            $170,750

script

I have seen this solution
https://datatables.net/forums/discussion/40105/prevent-form-inline-class.
but I'am getting this error .

jquery-3.1.1.min.js:2 Uncaught ReferenceError: table is not defined

Actually where to place the below code?
$( table.table().container() ).removeClass( 'form-inline' );

A: Try this code


text:
Q: Is there a way to "cast" an array to (object) as a property of class/trait? In PHP, I like the ability to declare objects (new instances of the stdClass) in one step like so:
$obj = (object) ['a','b','c'];
This works great.. but as a class property:
class Foo {
    public $obj = (object) ['a','b','c'];
}

I get the following error:

syntax error, unexpected '(object)' (object) (T_OBJECT_CAST)

Is there another way to accomplish this? And, does anyone know why the above code is disallowed (perhaps specific to php 5.6)? I couldn't find specific documentation anywhere.

A: Quoting from the PHP Docs:

They [object properties] are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value -- that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

(my emphasis)
And
public $obj = (object) ['a','b','c'];

is dependent on run-time information, namely run-time casting of array to object
The way to get round this is to assign the value in the constructor


text:
Q: How to require already loaded modules in Lua I have a Lua module, which returns an export table (i.e. not using the deprecated module directive). Also, I have a script which wants to load that module via "require" function.
Now I load both files to lua state from C code like this:
luaL_loadstring(lua, someScript);
lua_pcall(lua, 0, LUA_MULTRET, 0);
luaL_loadstring(lua, someModule);
lua_pcall(lua, 0, LUA_MULTRET, 0);

The require call fails, because it looks for the file, rather than the code, which is already loaded. Is it possible to somehow require someModule from someScript in this situation?

A: The documentation for require contains all the information you need to make this work. Specifically it tells you what methodology the require function uses to find the code being requested. Even more specifically the first sentence about package.loaded is what you likely want to be paying attention to.
Documentation from above link:

Loads the given module. The function starts by looking into the package.loaded table to determine whether modname is already loaded. If it is, then require returns the value stored at package.loaded[modname]. Otherwise, it tries to find a loader for the module.
To find a loader, require is guided by the package.loaders array. By changing this array, we can change how require looks for a module. The following explanation is based on the default configuration for package.loaders.
First require queries package.preload[modname]. If it has a value, this value (which should be a function) is the loader. Otherwise require searches for a Lua loader using the path stored in package.path. If that also fails, it searches for a C loader using the path stored in package.cpath. If that also fails, it tries an all-in-one loader (see package.loaders).
Once a loader is found, require calls the loader with a single argument, modname. If the loader returns any value, require assigns the returned value to package.loaded[modname]. If the loader returns no value and has not assigned any value to package.loaded[modname], then require assigns true to this entry. In any case, require returns the final value of package.loaded[modname].
If there is any error loading or running the module, or if it cannot find any loader for the module, then require signals an error.

A: For clarity let's name things: module A returns an export table; script B is a string that requires module A, and I'll assume B returns nothing. Also you want to do the following:
load script B (via luaL_loadstring): puts chunk on stack
run chunk for script B (via lua_pcall): puts whatever B returns on stack
load module A (via luaL_loadstring): puts chunk on stack
run module A (via lua_pcall): puts whatever A returns on stack

Firstly, module A is a file so presumably you've loaded the contents of A into a string.
You say that your issue is that require, called in script B, fails. There could be several reasons, such as B does require 'moduleA', but moduleA.lua is not found in LUA_PATH folders.
So:

*

*print the part of B that requires A so we can see the code

*verify that LUA_PATH is such that moduleA.lua can be found

Once the above is confirmed to be ok, we can look at your C API calls, but I doubt those are the issues.

A: If someModule uses require"modname" then try this code:
lua_getglobal(lua, "package");
lua_getfield(lua, -1, "loaded");
luaL_loadstring(lua, someScript);
lua_pcall(lua, 0, 1, 0);
lua_setfield(lua, -2, modname);
luaL_loadstring(lua, someModule);
lua_pcall(lua, 0, LUA_MULTRET, 0);


text:
Q: jQuery UI datepicker wrong date from JSON dateformat I am trying to set this date as default date in jQuery UI Datepicker 2014-03-13T18:30:00.000Z
I am using JQueryUI datepicker KO binding handler for that. But it is showing wrong JSON date in textbox where the text is bound.
It is showing 10/23/2019 instead of 2014-03-13..
http://jsfiddle.net/rahulrulez/AkBUv/213/
How to parse it in correct format if there is any?

A: This is (indirectly) a duplicate of jQuery UI DatePicker - Change Date Format
To solve your specific example, change your input data-bind expression to
<input data-bind="datepicker: newDate, datepickerOptions: { dateFormat: 'yy-mm-dd' }" />

Your datepicker binding reads the datepickerOptions binding to supplies that object as options to the $.datepicker call.
var options = allBindingsAccessor().datepickerOptions || {};

Be careful when you upgrade to knockout 3.x as the allBindingAccessor has changed.  More details from KO's doco -> Creating custom bindings


text:
Q: migrating big menu to bootstrap I'm looking for migrate my django attendance application to bootstrap UI. This application has a lot of options classifieds in a big menu:

I know that bootstrap supports submenus and can be a solution. But I will like to know if exists some more elegant approach.
Also, a mobile friendly solution will be wellcome.

A: The free CSS BigMenu code is integrated with Bootstrap and here is the code/sample link:
http://www.bootply.com/g53fBbpDYE


text:
Q: Adding additional arguments to overridden functions without pylint complaining I would like to define a function f in a superclass that has a set of required positional arguments, and permit subclasses to provide their own versions of f that share the required arguments, but also have additional named arguments.
Further, I want to do this in such a way that mypy is able to check the types of everything, and pylint3 doesn't complain about anything.
Functions f and g below represent my best attempts thus far:
from typing import Any

class Base:
    def f(self, required_arg: int, *args: Any, **kwargs: Any) -> None:
        print(self, required_arg, args, kwargs)

    def g(self, required_arg: int, **kwargs: Any) -> None:
        print(self, required_arg, kwargs)

class A(Base):
    def f(self, required_arg: int, x: int = 42, *args: Any, **kwargs: Any) -> None:
        print(self, required_arg, x, args, kwargs)

    def g(self, required_arg: int, *, x: int = 42, **kwargs: Any) -> None:
        print(self, required_arg, x, kwargs)

This code works as expected (passing x=20 places it in kwargs for the base class, and x for the derived class), however running pylint3 yields the following warnings:
W: 11, 1: Keyword argument before variable positional arguments list in the definition of f function (keyword-arg-before-vararg)
W: 11, 1: Parameters differ from overridden 'f' method (arguments-differ)
W: 14, 1: Parameters differ from overridden 'g' method (arguments-differ)

There are, of course, a variety of ways to suppress that class of warning, either generally, by file, or by line, but I would like to declare the function in such a way that this is not necessary.
If it makes a difference, I don't actually care if the base class can access any of the additional arguments; kwargs is just part of the declaration so as to permit it to take arbitrary arguments.  Additionally, it is acceptable to require that x be passed as a keyword argument, as long as it ends up in x and not kwargs['x'].

A: You can have parameters in the child class which don't feature in the parent class, so long as they are optional. This would be easiest without args and kwargs.
class Animal:
    def speak(self, volume: int) -> None:
        print(f"Animal speaking at volume {volume}")

class Parrot(Animal):
    def speak(self, volume: int, words: str ="Pretty Polly") -> None:
        print(f"Parrot says {words} at volume {volume}")

a = Animal()
a.speak(4)
p = Parrot()
p.speak(5) # fine, words takes the default as "Pretty Polly"
p.speak(6, "Bye") # Fine, words works from its position
p.speak(7, optional_arg="Yay") # Fine, words can be named

MyPy is happy with that. The basic rule you need to follow is that your child objects can be used as parent objects. In this case MyPy is happy is that a Parrot is still a valid Animal because it's still possible to call p.speak with just volume, like Animal requires.
You can do the same thing with a keyword only argument.
class Parrot(Animal):
    def speak(self, required_arg: int, *, optional_kwarg: str = "Hello again") -> None:
        print(f"A {required_arg} {optional_arg}")

p = P()
p.speak(8) # Fine, as required by base class Animal
p.speak(9, optional_kwarg="Bye again") # fine, as specially allowed of Parrots
p.speak(10, "Oops") # This one won't work, because there isn't a positional argument to put it in.

This is often all that you need. When you know that you have a Parrot, you can tell it what to say. If all you know is that you have some sort of Animal, because it might be a dog and dogs can't speak English [citation needed], you should restrict yourself to instructions that all animals can handle.

It is possible to get your base class using *args and **kwargs. You can use the positional only argument marker /. The cost of doing so is that you commit things to either being a positional argument or a keyword argument. The syntax goes something like this:
class Base:
    def f(self, required_pos_arg: int, /, *args, required_kwarg, **kwargs) -> None:
        print(f"Base {required_pos_arg} {required_kwarg} {args} {kwargs}")

class A(Base):
    def f(self, required_pos_arg: int, optional_pos_arg: float=1.2, /, *args, required_kwarg, optional_kwarg: str ="Hello", **kwargs) -> None:
        print(f"A {required_pos_arg} {optional_pos_arg} {optional_kwarg} {args} {kwargs}")

b = Base()
b.f(9, 0.2, "Additional_pos_arg", required_kwarg="bar", optional_kwarg="Foo", kwarg_member="Additional_kw_arg")

a = A()
a.f(9, 0.2, "Additional_pos_arg", required_kwarg="bar", optional_kwarg="Foo", kwarg_member="Additional_kw_arg")

By using the / marker at the end of the positional ones, and * (or *args) before the start of the keyword ones, you remove the ambiguity that comes from confusing positional and keyword arguments. You can add more positional arguments (again, they must be optional so that the bare bones call still works) to the end of list before *. You can add more keyword arguments (same restrictions) after the *. You'll note that the child class must also take args and kwargs because the child must accept anything the parent would. And then MyPy is happy again.

However, as I mentioned earlier, this is probably not what you want to do.
The fundamental purpose of using MyPy is to get the computer to help your ensure that you're only using things where they make sense. If you add *args and **kwargs you necessarily limit how good a job it can do. It's no longer able to stop you from asking the dog to recite Macbeth, or even to stop you from asking the Parrot to speak with florgle of 9.6.
Except in very specific circumstances where you really want the base class to handle everything, it is safer to restrict yourself to what you actually want to do.
You will of course then find that if you write this code
def EnglishTest(students: List[Animal]):
    for s in students:
        s.speak(5, words="Double, double toil and trouble")

MyPy will yell at you. That's not a bug. It's doing its job. It's telling you that most animals don't do words. And it prompts you to write instead
def EnglishTest(students: List[Animal]):
    for s in students:
        if isinstance(s, Parrot):
            s.speak(5, words="Double, double toil and trouble")
        else:
            print(f"{s} failed its English test.")


text:
Q: How to access base datacontext in Collection in xaml I have a wpf app with the datacontext set to an instance of a viewmodel class. It all works fine except where I need to access a property of the viewmodel in a listbox with the datacontext set to a collection that is contained in the ViewModel class. On msdn it says you can escape using the \ character but that has not worked for me
My code
public class StatusBoardViewModel : INotifyPropertyChanged
   {
    OIConsoleDataContext db = new OIConsoleDataContext();

    // the collection
    private IQueryable<Issue> issues;
    public IQueryable<Issue> Issues
    {
        get
        {
            // Lazy load issues if they have not been instantiated yet
            if (issues == null)
                QueryIssues(); // This just runs a linq query to set the property
            return issues;
        }
        set
        {
            if (issues != value)
            {
                issues = value;
                OnPropertyChanged("Issues");
            }
        }
    }
    // The property I need to access
    private bool showDetailListItems = true;
    public bool ShowDetailListItems
    {
        get
        {
            return showDetailListItems;
        }
        set
        {
            if (showDetailListItems != value)
            {
                showDetailListItems = value;
                OnPropertyChanged("ShowDetailListItems");
            }
        }
    }
}

in the window1.xaml.cs
//instantiate the view model
StatusBoardViewModel statusBoardViewModel = new StatusBoardViewModel();

    public Window1()
    {
        InitializeComponent();
        // setting the datacontext
        this.DataContext = statusBoardViewModel;
    }

And the Xaml
    // This is in the Window1.xaml file
    <ListBox x:Name="IssueListBox"
              ItemsSource="{Binding Issues}" // Binds the listbox to the collection in the ViewModel
              ItemTemplate="{StaticResource ShowIssueDetail}"
              IsSynchronizedWithCurrentItem="True"
              HorizontalContentAlignment="Stretch" BorderThickness="3"
              DockPanel.Dock="Top" VerticalContentAlignment="Stretch"
              Margin="2" MinHeight="50" />

// The datatemplate from the app.xaml file
    <DataTemplate x:Key="ShowIssueDetail">
        <Border CornerRadius="3" Margin="2" MinWidth="400" BorderThickness="2"
                BorderBrush="{Binding Path=IssUrgency, Converter={StaticResource IntToRYGBBoarderBrushConverter}}">
            <StackPanel Orientation="Vertical">
                <TextBlock Text="{Binding Path=IssSubject}" Margin="3" FontWeight="Bold" FontSize="14"/>

                <!--DataTrigger will collapse following panel for simple view-->
                 <StackPanel Name="IssueDetailPanel" Visibility="Visible" Margin="3">
                    <StackPanel Width="Auto" Orientation="Horizontal">
                        <TextBlock Text="Due: " FontWeight="Bold"/>
                        <TextBlock Text="{Binding Path=IssDueDate}" FontStyle="Italic" HorizontalAlignment="Left"/>
                    </StackPanel>
                    <StackPanel Width="Auto" Orientation="Horizontal">
                        <TextBlock Text="Category: " FontWeight="Bold"/>
                        <TextBlock Text="{Binding Path=IssCategory}"/>
                    </StackPanel>
                </StackPanel>

            </StackPanel>
        </Border>

        // This is where I have the issue, ShowDetailListItems is in the base class, not the collection
        <DataTemplate.Triggers>
            <DataTrigger Binding="{Binding Path=ShowDetailListItems, Mode=TwoWay}" Value="False">
                <Setter TargetName="IssueDetailPanel" Property="Visibility" Value="Collapsed"/>
            </DataTrigger>
        </DataTemplate.Triggers>
    </DataTemplate>

I have learned a TON doing this but this current issue is driving me batty, no luck with google, MSDN, SO or a couple books
I thought I would add this note: I am learning this in order to build some apps for my business, I am a rank beginner in wpf and xaml so I relize this is probably somthing silly. I would really like to find a good tutorial on datacontexts as what I do find is a dozen different "How To's" that are all totally different. I know I have some big holes in my knowledge because I keep ending up with multiple instantiations of my viewmodel class when I try to create references to my datacontext in the codebehind, Window1.xaml and app.xaml files.

A: Have you tried one of these?
{Binding Path=ShowDetailListItems, ElementName=YourWindowName}

or
{Binding ShowDetailListItems, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}


text:
Q: Unable to pass the value of function on button click in Angular 6 I want to pass the value into function on button click . but when I am doing that I am getting the value as "Undefined"
please tell me a solution to pass the value into the function

.ts file

export class AppComponent  implements OnInit {
constructor() { }

    ngOnInit() {}

    togg(string name) {
        console.log(name);
        this.dropdowns[name] = !this.dropdowns[name];
    }
 }

.html file

<button (click)="togg('toggle_menu3');"> click </button>

A: Works fine for me here
https://stackblitz.com/edit/angular-em8xnv
Changed togg to be properly written like
togg(name: string) {
  console.log(name);
  // rest of code
}

and changed html to remove the semi colon (not actually needed)
<button (click)="togg('toggle_menu3')">test<button>


text:
Q: ScrollView or CollectionView? I have a collection view populated with data like:
[self.graniteImages addObject:[[NSMutableDictionary alloc]
                               initWithObjectsAndKeys:@"Angel Cream", @"name",
                               @"angel-cream.jpg", @"image", nil]];
[self.graniteImages addObject:[[NSMutableDictionary alloc]
                               initWithObjectsAndKeys:@"Angola Black", @"name" ,
                               @"angola_black1.jpg", @"image" , nil]];

and then have a segue to a detail view which is static.
I now want to add paging to the detail view so that I can swipe through the images that I have contained in my collection view in the same way that the iPhone photo gallery works.
I'm guessing either a scrollview or a second collectionview would be needed however I'm not sure where to start with this so any pointers, sample code or any other help you guys could give would be massively appreciated.
Thanks

A: If you already have a collection view that does what you want just turn on paging. self.collectionView.pagingEnabled = YES  You can also enable paging in IB by checking the paging box in the attributes inspector. Using a UICollectionView gives you the added benefit of reusable cells.
Edit
You could still use UICollectionView. Create an UICollectionViewCell subclass that contains your detail view. Then when you want to launch directly to a particular image you can use - (void)scrollToItemAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(UICollectionViewScrollPosition)scrollPosition animated:(BOOL)animated If you're loading a ton of images in this view the scrollview method will load all of your images at once rather than on demand like they would in a collectionview scenario.  You can always work around that in a scrollview but all that work's been done for you in UICollectionView.
Edit2
I started this in a comment but it was getting big...
In your view controller subclass you will need to register either your class or a nib that you created to lay out that cell.  I prefer the nib so I can lay everything out in Interface Builder.  If you go the nib route you will create an empty xib and drag a UICollectionViewCell out of the object library in the bottom right. Then select that cell and make sure the Class is set to the custom subclass you've created.
Now in your view controller subclass you'll call – registerNib:forCellWithReuseIdentifier: in the viewDidLoad method like this:
   [self.collectionView registerNib:[UINib nibWithNibName:@"WhateverYouNamedYourNib" bundle:nil] forCellWithReuseIdentifier:@"cell"];

Your view controller will conform to the UICollectionViewDataSource protocol and you will implement this method:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
  CustomCellClass *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath
  //Setup the cell with image and whatever else
  return cell;
}

A: You should simply use a UIScrollView with paging enabled. The following code should do the trick:
NSInteger numberOfImages = [self.graniteImages count];
    CGRect bounds = self.scrollView.bounds;
self.scrollView.contentSize = CGSizeMake(bounds.size.width * numberOfImages, bounds.size.height);
scrollView.pagingEnabled = YES;

CGFloat x = 0;
for (NSMutableDictionary *dict in images) {
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[dict valueForKey:@"image"]]];
    imageView.frame = CGRectMake(x, 0, bounds.size.width, bounds.size.height);
    [scrollView addSubview:imageView];
    x += self.view.bounds.size.width;
}

EDIT: This code would go in your detail view controller's ViewDidLoad method.
Your detail view controller should also have a property index of type NSUInteger and a graniteImages property of type NSMutableArray* that you can set in your collection view controller's prepareForSegue method just like:
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if( [segue.identifier isEqualToString:@"yourSegue"]){
    ((DetailViewController*)segue.destinationViewController).graniteImages = self.graniteImages;
    ((DetailViewController*)segue.destinationViewController).index = self.tappedImageIndex;
    }
}

and in your ViewDidLoad method you add:
[scrollView scrollRectToVisible:CGRectMake(bounds.size.width * self.index, 0, bounds.size.width, bounds.size.height) animated:NO];


text:
Q: Polymer on-click is double posting I'm wondering if anybody here has had a similar problem with Polymer double posting a form.  My code is very simple, as stated previously, each time I click the button the form is posted twice. I'm using Polymer 05.5
<polymer-element name="book-form">
    <template>
        Title:
        <input id="title" value="{{title}}" />
        Author:
        <input id="author" value="{{author}}" />
        Image:
        <input id="image" value="{{image}}" />
        <button on-click="{{fireAjax}}">Submit Form</button>
        <core-ajax id="ajax"
                   auto
                   url="http://localhost:45922/api/book"
                   handleAs="json"
                   method="POST"
                   >
        </core-ajax>
    </template>

</polymer-element>

A: Your fireAjax function changes the data of the core-ajax. Because auto is on, the ajax call is fired. Then you call this.$.ajax.go() so the call is fired again.
Try to remove the auto in the core-ajax element.

A: Okay I see what the problem is, the auto property on the form post anytime the url or the parameters change.  If one wants to control when the POST takes place they should remove the auto property from core-ajax.
<polymer-element name="book-form">
    <template>
        Title:
        <input id="title" value="{{title}}" />
        Author:
        <input id="author" value="{{author}}" />
        Image:
        <input id="image" value="{{image}}" />
        <button on-click="{{test}}">Submit Form</button>
        <core-ajax id="ajax"
                   url="http://localhost:45922/api/book"
                   handleAs="json"
                   method="POST"
                   >
        </core-ajax>
    </template>

</polymer-element>


text:
Q: missing some text when iterating xml elements in python I am running the following code in Python 2.7.3 on Mac OS X 10.6.8.
import StringIO
from lxml import etree
f = open('./foo', 'r')
doc = ""
while 1:
    line = f.readline()
    doc += line
    if line == "":
        break
tree = etree.parse(StringIO.StringIO(doc), etree.HTMLParser())
r = tree.xpath('//foo')
for i in r:
    for j in i.iter():
        print j.tag, j.text

And the file foo contains
<foo> AAA <bar> BBB </bar> XXX </foo>

The output is
foo AAA
bar BBB

Why am I not getting the text XXX?  How do I access it?
Thanks

A: Try this:
from lxml import etree

tree = etree.fromstring("<foo> AAA <bar> BBB </bar> XXX </foo>")
foos = tree.xpath('//foo')

for foo in foos:
    for j in foo.iter():
        print j.tag, j.text, j.tail

Output:
foo  AAA  None
bar  BBB   XXX

The tail attribute holds the text after the end tag of the element.
tail is a peculiarity of lxml and ElementTree compared to other XML models, such as DOM. See http://infohost.nmt.edu/tcc/help/pubs/pylxml/web/etree-view.html for more information.

A: You also have to take
node.tail

into account (or check for it).


text:
Q: picocli : redirect stdout and stderr to logger What is the correct/easiest way to redirect output (out/err) from .execute() or .parseArgs() to a logger (org.slf4j.Logger)?
(Production processes are often executed by a scheduler with output to application-specific log files. And stdout/err, if not redirected, gets dumped in the scheduler/server log - which is not appropriate. Hence this question.)
I have something like this:
Logger logger = LoggerFactory.getLogger(MyApp.class);
    // ...
    new CommandLine(new MyApp())
      .setOut(new LoggerWriter(logger, Level.INFO)
      .setErr(new LoggerWriter(logger, Level.ERROR)
      .execute(args);
    // ...

where the LoggerWriter class is inspired from here.


text:
Q: How to apply reduction of order to find a 2nd linearly independent solution? I have some questions about writing a general solution, $y$, for $y''-y=0$
when $y_1 = e^x$ is a known solution.
I do not understand the logic of the method of reduction of order. How do we apply this to find a second, linearly independent solution?

A: I recommend you read this article which explains the general procedure.
However, in your particular case, since you have one solution, $y_1=e^x$ the method says to look for a second one of the form $y_2=v(x)y_1(x)$. Then \begin{align}y_2'&=v'e^x+ve^x\\ y_2''&=e^x(v''+2v'+v)\end{align} and since it is assumed that $y_2$ is a solution of $y''-y=0$, we conclude $$y_2''-y_2=e^x(v''+2v')=0\implies v''+2v'=0.$$
The next step is where the name reduction of order comes from. Let $u=v'$ so that $u'=v''$. Then the $v$ equation (a second order equation) becomes $u'+2u=0$ (a first order equation) which has general solution $u(x)=Ce^{-2x}$, i.e., $v'(x)=Ce^{-2x}$. Integrating we get $v(x)=-{1\over 2}Ce^{-2x}+D$.
Since we are only interested in a second linearly independent solution $y_2$, we can take $C=-2$ and $D=0$ for simplicity. Then $$y_2(x)=v(x)y_1(x)=e^{-2x}\cdot e^x=e^{-x},$$ and so $$y(x)=c_1y_1(x)+c_2y_2(x)=c_1e^x+c_2e^{-x}.$$
To verify that $y_1$ and $y_2$ are in fact linearly independent on an interval $I$, simply evaluate the Wronskian of $y_1$ and $y_2$:
$$W(y_1,y_2)=\begin{vmatrix} y_1 & y_2\\ y_1' & y_2'\end{vmatrix}=\begin{vmatrix} e^x & e^{-x}\\ e^x & -e^{-x}\end{vmatrix}=e^x(-e^{-x})-e^{-x}(e^x)=-2\not=0,\quad \forall x\in I.$$

A: Related problem: (I), (II). It is a method used to find a second solution by knowing one solution. To find a second solution, assume that $y_2(x)=u(x)y_1(x)=u(x)e^{x}.$. Now substitute this in the differential equation and try to find $u(x)$ using the fact that $y''_1-y_1=0$.


text:
Q: Laravel Lighthouse Graphql multiple guards I am trying to make my custom guard to work against a GraphQL schema with Lighthouse but its not working.
The problem is that my custom guard is not reached by graphql query.
The schema.graphql: (removed some code for brevity)
extend type Query @guard(with: ["api", "partner"])
{
    GetHighscores(): [Highscore!]!
}

Note the @guard directive, it has api and partner. I want they run in that order (btw does it have order?).
Now the definition of the partner guard
AuthServiceProvider@boot
Config::set('auth.guards.partner', [
    'driver' => 'partner',
]);

Auth::viaRequest('partner', function (Request $request) {
    dd('MUST GET HERE');
});

When I run the query using an authenticated bearer token, the guard partner is not executed. But if I set the partner guard before api then it gets executed. What am I missing here?
edit
Using CURL, I have requested a protected laravel route and it works:
Route::middleware(['auth:api', 'auth:partner'])->get('/partners', function (Request $request) {
    print_r($request->user()->toArray());
});

it printed the dd() message, which is right.
So why Lighthouse could not reached my custom guard?

A: I solved my issue moving the check for the API guard inside the partner guard:
Auth::viaRequest('partner', function (Request $request) {
    $user = auth()->user();
    if ($user &&
        $user->partner()->exists() === true &&
        auth()->guard('api')->check() === true
    ) {
        return $user;
    }
});

in the graphql schema:
extend type Query @guard(with: "partner")
{
    GetHighscores(): [Highscore!]!
}

I still thinking that Lighthouse should be take care of multiple guards like it was an "AND"... anyways, its working now.

A: The lighthouse @guard directive behaves like a OR directive.
If the first guard passes, the second one is never checked.
What you could to is add the @guard directive twice. I think that should work.
extend type Query @guard(with: ["api"]) @guard(with: ["partner"])
{
    GetHighscores(): [Highscore!]!
}

This is the code from the directive:
/**
 * Determine if the user is logged in to any of the given guards.
 *
 * @param  array<string>  $guards
 *
 * @throws \Illuminate\Auth\AuthenticationException
 */
protected function authenticate(array $guards): void
{
    foreach ($guards as $guard) {
        if ($this->auth->guard($guard)->check()) {
            $this->auth->shouldUse($guard);

            return;
        }
    }

    $this->unauthenticated($guards);
}

A: My use case may be different as I wanted authorization not multiple kinds of authentication, I have users that should be allowed to authenticate but need to do some verification mutations and limited querying and be admitted to use the rest of the API by an administrator.
Was thinking to just copy the guard directive and make it work as an and?
But I ended up creating a FieldMiddleware directive as I did not want other checks to need to do a separate authentication or copy same auth guard everywhere as that could be subject to change, I just wanted to check some attributes from the model were okay for a user to continue to use that query or mutation.
Although it does seem like @can and policy or gate would be more appropriate if not authenticating but checking some role/permission/state, I just wanted something I could use that was clear cut as I haven't made policy for absolutely every model yet a lot of them are just querying any data, using Policy would also apply for my back-end system which has different checks for admin already.
sail artisan lighthouse:directive AllowedInApp --field
1 FieldMiddleware
So the field Middleware can wrap and do checks I need and throw if not allowed.
<?php

namespace App\GraphQL\Directives;

use App\Models\User;
use Closure;
use GraphQL\Type\Definition\ResolveInfo;
use Nuwave\Lighthouse\Exceptions\AuthorizationException;
use Nuwave\Lighthouse\Schema\Directives\BaseDirective;
use Nuwave\Lighthouse\Schema\Values\FieldValue;
use Nuwave\Lighthouse\Support\Contracts\FieldMiddleware;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;

final class AllowedInAppDirective extends BaseDirective implements FieldMiddleware
{
    public static function definition(): string
    {
        return /** @lang GraphQL */ <<<'GRAPHQL'
directive @allowedInApp on FIELD_DEFINITION
GRAPHQL;
    }

    /**
     * Wrap around the final field resolver.
     *
     * @param  \Nuwave\Lighthouse\Schema\Values\FieldValue  $fieldValue
     * @param  \Closure  $next
     * @return \Nuwave\Lighthouse\Schema\Values\FieldValue
     */
    public function handleField(FieldValue $fieldValue, Closure $next)
    {
        $previousResolver = $fieldValue->getResolver();

        $fieldValue->setResolver(function ($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) use ($previousResolver) {
            /***
             * @var User
             */
            $user = $context->user();

            if ($user->isVerifiedAndAdmitted === false) {
                throw new AuthorizationException(
                    "You are not authorized to access {$this->nodeName()}"
                );
            }

            return $previousResolver($root, $args, $context, $resolveInfo);
        });

        return $next($fieldValue);
    }
}

In my user model I added an attribute that did the check I wanted, only have users but it is possible to have multiple kinds of authenticatable model actually.
    /**
     * Get verified status returns true if both mobile and email are verified and the user is admitted.
     *
     * @return  \Illuminate\Database\Eloquent\Casts\Attribute
     */
    public function isVerifiedAndAdmitted(): Attribute
    {
        return Attribute::make(
            get: fn($value, $attributes) => isset($attributes['mobile_verified_at'])
                && isset($attributes['email_verified_at'])
                && $attributes['admitted_at'] !== null
                && now()->greaterThanOrEqualTo($attributes['admitted_at'])
        );
    }

From what I saw about the guard directive in lighthouse source.
The built in Guard Directive just returns when one defined guard or default guard succeeds.
src/Auth/GuardDirective.php
Untested, not sure its the right thing to use, maybe policy or gate is better.
    /**
     * Determine if the user is logged in to all of the given guards.
     *
     * @param  array<string|null>  $guards
     *
     * @throws \Illuminate\Auth\AuthenticationException
     */
    protected function authenticate(array $guards): void
    {
        $canPass = true;
        foreach ($guards as $guard) {
            if ($this->auth->guard($guard)->check()) {
                // @phpstan-ignore-next-line passing null works fine here
                $this->auth->shouldUse($guard);
            } else {
               $canPass = false;
               break;
            }
        }

        if ($canPass) {
            return;
        }

        $this->unauthenticated($guards);
    }
    ```


text:
Q: Django JSONWebTokenAuthentication not working for views I am using

rest_framework_jwt.authentication.JSONWebTokenAuthentication

for my REST APIs . This is working fine for authentication but for my Skill view , I am able to hit the REST endpoint even though I am not passing any authentication token .
How can i make my Skill API authenticated . Also I am new to Django so In the User view I do have a class , but for my Skill view i didnt found a correct example to have a class .
Please help me with this .
I have following view file :
from rest_framework.permissions import IsAuthenticated

@api_view(['GET'])
def skill_collection(request):
    if request.method == 'GET':
        skills = Skill.objects.all()
        serializer = SkillSerializer(skills, many=True)
        return Response(serializer.data)

@api_view(['GET'])
def skill_element(request, pk):
    try:
        skill = Skill.objects.get(pk=pk)
    except Skill.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == 'GET':
        serializer = SkillSerializer(skill)
        return Response(serializer.data)

Url file :
urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^rest-auth/', include('rest_auth.urls')),
    url(r'^rest-auth/registration/', include('rest_auth.registration.urls')),
    url(r'^rest-auth/login/', include('rest_auth.registration.urls')),
    url(r'^refresh-token/', refresh_jwt_token),
    url(r'^user/$', DetailsView.as_view(), name='rest_user_details'),
    url(r'^', include('api.urls')),
    url(r'^api/v1/skills/$', wantedly_app_views.skill_collection),
    url(r'^api/v1/skills/(?P<pk>[0-9]+)$', wantedly_app_views.skill_element)

]

A: I was able to add JWT authentication by adding following permission in settings.py
'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),

Please comment if this is right


text:
Q: How to make a start on this Erlang homework? Here is my challenge:

*

*Create a function exists that returns true or false when an item is in the list.
1> exists(2,[1,4,5,3,2]).
true
2> exists(2,[]).
false
3> exists(2,[4,5,6,7]).
false

*Create a function listLength that will return the length of a list. Using the native function length is not allowed.
1> listLength([1,2,3]).
3
2> listLength([]).
0

A: AS it looks like homework, I hope you will not get the solution here. I will give you some clues.
For the first one:

*

*there is one case when you know for sure that the term does not exist in the list: when the list is empty.

*When the list is not empty the only element of the list you can access is the head of the list, so you will have to use recursion to compare one by one every elements of the list to the input term.

Same thing for the second:

*

*you know the length of an empty list: 0

*you know that the length of a not empty list is 1 + length of the tail. Use recursion to count one by one all the elements.


text:
Q: What happens if I enable secure boot on a dual boot system? I recently installed Ubuntu 22.04 LTS on a laptop in a dual boot environment. To install wifi-card drivers, Ubuntu is asking me to enable dual boot with a password of some kind.
I get that this is to embed some keys to sign the driver in the firmware if I got it right?
So my question is really: What happens if I do this and what happens to the Windows part of the laptop?


text:
Q: Retrieve and update values in Google spreadsheet by row ID by using HTML form I was able to create a google spreadsheet (with ideas found on here) with these columns:
product | size | uid
where uid is random five number generated ID (=RANDBETWEEN(10000;99999)).
I then used the following apps script:
// original from: http://mashe.hawksey.info/2014/07/google-sheets-as-a-database-insert-with-apps-script-using-postget-methods-with-ajax-example/
// original gist: https://gist.github.com/willpatera/ee41ae374d3c9839c2d6

function doGet(e){
  return handleResponse(e);
}

//  Enter sheet name where data is to be written below
        var SHEET_NAME = "Sheet1";

var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service

function handleResponse(e) {
  // shortly after my original solution Google announced the LockService[1]
  // this prevents concurrent access overwritting data
  // [1] http://googleappsdeveloper.blogspot.co.uk/2011/10/concurrency-and-google-apps-script.html
  // we want a public lock, one that locks for all invocations
  var lock = LockService.getPublicLock();
  lock.waitLock(30000);  // wait 30 seconds before conceding defeat.

  try {
    // next set where we write the data - you could write to multiple/alternate destinations
    var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
    var sheet = doc.getSheetByName(SHEET_NAME);

    // we'll assume header is in row 1 but you can override with header_row in GET/POST data
    var headRow = e.parameter.header_row || 1;
    var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
    var nextRow = sheet.getLastRow()+1; // get next row
    var row = [];
    // loop through the header columns
    for (i in headers){
      if (headers[i] == "Timestamp"){ // special case if you include a 'Timestamp' column
        row.push(new Date());
      } else { // else use header name to get data
        row.push(e.parameter[headers[i]]);
      }
    }
    // more efficient to set values as [][] array than individually
    sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
    // return json success results
    return ContentService
          .createTextOutput(JSON.stringify({"result":"success", "row": nextRow}))
          .setMimeType(ContentService.MimeType.JSON);
  } catch(e){
    // if error return this
    return ContentService
          .createTextOutput(JSON.stringify({"result":"error", "error": e}))
          .setMimeType(ContentService.MimeType.JSON);
  } finally { //release lock
    lock.releaseLock();
  }
}

function setup() {
    var doc = SpreadsheetApp.getActiveSpreadsheet();
    SCRIPT_PROP.setProperty("key", doc.getId());
}

Then, I put together this php file:
<?php
if (isset($_GET['product'])) $product = $_GET['product'];
if (isset($_GET['size'])) $size = $_GET['size'];
if (isset($_GET['uid'])) $uid = $_GET['uid'];
?>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Submit rows</title>

Submit new row to google sheet.
<form id="test-form">

    product
    <input type="text" name="product" value="<?php echo $product; ?>"/>

    size
    <input type="text" name="size" value="<?php echo $size; ?>"/>

    UID
    <input type="text" name="uid" value="<?php echo $uid; ?>"/>

    <button type="submit" id="submit-form">Submit form</button>

</form>

Why like this? I have a QR code and when it is scanned, user is directed to url like this:
htttps://samplesite.com/index.php?product=Pants&size=large&uid=12345
So form fields are prepopulated by values from the qr code/link. Form is submitted, values are written into the google spreadsheet, all is fine.
But now to the question part! :)
There is another qr code on the product and when scanned, it opens url like this: htttps://samplesite.com/edit.php?uid=12345
I would like this to open another page with form that lists the row values of the same google spreadsheet where uid is 12345. With php, it could be something like select * from sheet_id where uid='12345' and then defining the column values, but obviously it is not that easy.
I did some searching and tabletop.js has been suggested, but they (https://github.com/jsoma/tabletop) don't recommend it anymore.

*

*How can I retrieve information from a google spreadsheet by unique row id and insert it as values in html form?
I plan to fill in the form with this data and then use drop downs to allow user to change the (size) value. Which leads us to the second part...

*How can I update the google spreadsheet by specific row id? I want this form to overwrite the values in same row with id 12345.

*And since we're here already: is excel's randbetween function good enough for this use? Or would you recommend a bigger number/letters? The outdated backend system unfortunately does not allow us to progress uid numbers by one, like in a regular database.

Thank you.

A: One way to do this would be to implement the HTML form directly in the doGet() and use google.script.run.withSuccessHandler(yourClientFunction).yourServerFunction(someParam) to push and pull data between the HTML form and the spreadsheet. This would handle authentication automatically. See the Web App demo.
Alternatively, use the Sheets API in your client code. You would not need a doGet() but would need to handle authentication.
You should not use randbetween() to create IDs, since there will eventually be collisions. If you allocate just five digits for the ID and never check for duplicates, the birthday problem virtually guarantees that there will be collisions after the first few hundred IDs. You should use an incrementing counter. If that is not possible, use Utilities.getUuid() or similar.


text:
Q: Create User without password I want to create a user in a repository without any password. I can see the UserManager API has methods to create a user with a password as below:
userManager.createUser("xxxxxx","xxxxxx")

But my use-case is to build the functionality like Subscribe Me, where the email will be enter to send the newsletters. I saw the docs, but here at the the time of submit, lead/user gets generated with some value of password.
My concern is that we have a sign-up section to store the user which can login to the site with password, but if with we implement the Subscribe Me functionality the user will be created with some password and somehow may be able to logged in to site, which should not be.
Any idea or suggestions would be appreciated.

A: There are multiple options, two that come into my mind are:

*

*create the users with randomly generated passwords, assign them to a group with very limmited access rights, e.g. read only on /content just like anonymous

*Store them in a custom node structure in JCR where you have full control and no ACL is applied OOTB.


text:
Q: How to use ffmpeg commnad in android with input and output file path? I want use ffmpeg command in android app.i am using this library to start with ffmpeg.
http://writingminds.github.io/ffmpeg-android-java/
i have developed a demo app and also run the command
ffmpeg -version
this command also giving exact ouput. but when i am giving any file path with name my command always fail for this i am using:
            String cmd[] = new String[]{"ffmpeg", "-i", "/storage/emulated/0/Videos/dheere.mp4", "-c:v", "libx264", "/storage/emulated/0/Videos/dheere2.3gp"};
            execute(cmd);

  private void execute(String cmd[]) {

    try {
        // to execute "ffmpeg -version" command you just need to pass "-version"
        FFMpegApp.getFfmpeg().execute(cmd, new ExecuteBinaryResponseHandler() {

            @Override
            public void onStart() {
                Log.e("gc", "Command Started");
            }

            @Override
            public void onProgress(String message) {
                Log.e("gc", "onProgress" + message);
            }

            @Override
            public void onFailure(String message) {
                Log.e("gc", "onFailure command" + message);
            }

            @Override
            public void onSuccess(String message) {
                Log.e("gc", "onSuccess command" + message);
            }

            @Override
            public void onFinish() {
                Log.e("gc", "onFinish command");
            }
        });
    } catch (FFmpegCommandAlreadyRunningException e) {
        // Handle if FFmpeg is already running
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

please give me any suggetion how to use command in android?
thanks in advance.

A: private void execute() {
String[] cmd = {"ffmpeg -i input_file_path.mp4 -ss 00:00:00.000 -pix_fmt rgb24 -r 10 -s 320x240 -t 00:00:10.000  output_file_path.gif"}

try {
    // to execute "ffmpeg -version" command you just need to pass "-version"
    FFMpegApp.getFfmpeg().execute(cmd, new ExecuteBinaryResponseHandler() {

        @Override
        public void onStart() {
            Log.e("gc", "Command Started");
        }

        @Override
        public void onProgress(String message) {
            Log.e("gc", "onProgress" + message);
        }

        @Override
        public void onFailure(String message) {
            Log.e("gc", "onFailure command" + message);
            // this will fail in case of wrong input or output path.
        }

        @Override
        public void onSuccess(String message) {
            Log.e("gc", "onSuccess command" + message);
        }

        @Override
        public void onFinish() {
            Log.e("gc", "onFinish command");
        }
    });
} catch (FFmpegCommandAlreadyRunningException e) {
    // Handle if FFmpeg is already running
    e.printStackTrace();
} catch (Exception e) {
    e.printStackTrace();
}


text:
Q: In Azure Logic App how to iterate over a dictionary I am having a Azure logic app where I want to iterate over a dictionary as shown below.
"test": {"text1":"qabdstw1234",
            "text2":"vhry46578"
            },

Here, in my Logic app I am able to iterate over a list of dictionary but here I want to iterate over a dictionary.
Does anybody knows how to do it?

A: Add a new action, search for Control and select the For each:

To process an array in your logic app, you can create a "Foreach" loop. This loop repeats one or more actions on each item in the array.

Source: Create loops that repeat workflow actions or process arrays in Azure Logic Apps

A: I have used parse JSON inorder to fetch test1 data from the JSON which you have provided and then used compose connector to get the same. Here is my Logic app :-

Here is the generated schema while using the sample JSON Payload which you have provided I'm using:-
{
    "type": "object",
    "properties": {
        "title": {
            "type": "string"
        },
        "text1": {
            "type": "array",
            "items": {
                "type": "string"
            }
        },
        "id": {
            "type": "string"
        },
        "status": {
            "type": "string"
        }
    }
}


text:
Q: ASP.NET - .aspx não recebe campos do form post cross domain Tenho um modelo de form que quero que o cliente use para colar em sua página.
O form aponta para uma página .aspx no meu servidor.
No evento Page_Load na minha .aspx eu quero pegar os campos preenchidos do form via post, no entanto, as quatro opções abaixo retornam array vazio (a primeira) ou nulo (as três seguintes):
    var a = HttpContext.Current.Request.Form;
    var b = Request.Form[Constantes.EngageFormParams.EnrollmentKey];
    var c = Request[Constantes.EngageFormParams.EnrollmentKey];
    var d = Request[Constantes.EngageFormParams.Login];

Se eu uso method='get' funciona. Como fazer funcionar o post?

A: Descobri o problema.
Páginas .aspx se baseiam no atributo "name" para pegar o valor do campo.
Então:
<input type="text" id="meucampo" value="oi"/>

Se eu der submit disso e na minha .aspx procurar por:
Request["meucampo"]

Vai retornar nulo.
No entanto, se eu colocar o atributo name, vai funcionar como esperado para qualquer uma das formas de ler os campos da request que eu coloquei na pergunta.
<input type="text" id="meucampo" name="meucampo" value="oi"/>


text:
Q: using post__in allow duplicate post id I have an array of ids in a specific order. I use post__in in my query to get posts from this array. I have some duplicate post IDs that I need to show twice in the page but the query seems to ignore them.
Let's say the array is as follows
array values  = 1,2,3,4,2,5

When I pass this array to post__in, it doesn't take value '2' twice as i specified in the array. Is there a workaround for this?

A: The situation
An array like array( 1,2,3,4,2,5 ) will be read like the following:
Array(
     0 => 1
    ,1 => 2
    ,2 => 3
    ,3 => 4
    ,4 => 2
    ,5 => 5
) [length = 6 ]

which seems ok. But when you look at the WP_Query object, you'll see the following part added to the query string:
" AND {$wpdb->posts}.ID IN ($post__in)"

This means that each post will be fetched once.
Conclusion
So unless you don't modify the query to include the post multiple times, you'll be left with only an option to do this on runtime.
Runtime configuration possibilities and x-raying the internals
Every basic loop looks like this:
if ( have_posts() )
{
    while( have_posts )
    {
        the_post();
        // do stuff
    }
}

Now the global $post refers to what gets setup via the_post(). It basically is a wrapper for $GLOBALS['wp_query']->the_post();. And when you take a look at the WP_Query::the_post() method, you'll find quite interesting things:
function the_post() {
    global $post;
    $this->in_the_loop = true;

    if ( $this->current_post == -1 ) // loop has just started
        do_action_ref_array('loop_start', array(&$this));

    $post = $this->next_post();
    setup_postdata($post);
}

There you see $this->next_post(); called. And this one looks from the inside like the following:
function next_post() {

    $this->current_post++;

    $this->post = $this->posts[$this->current_post];
    return $this->post;
}

Solution
So you see that the main thing the loop relies on, is the current_post counter. This one is as well accessible from the front end/a template. Simply use
$GLOBALS['wp_query']->current_post

to "jump" between posts. So if you need to repeat a post after post X, then just check against it, switch for one round and then skip back.

A: You can loop your ids and call get_post and setup_postdata :
global $post;
foreach ($ids as $id) :
    $post = get_post($id);
    setup_postdata( $post );
    the_title();
endforeach;


text:
Q: How to remove LineRenderer starting points ?(point 0, point 1, point 2) I created a line using LineRenderer and after a while I need to delete the starting points (point 0, point 1, point 2).I'm trying to get coroutia out of my way. But it starts to move away from the last half points and not from the initial
lineRenderer.positionCount = i+1;
Vector3 mPosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 15);
lineRenderer.SetPosition(i, Camera.main.ScreenToWorldPoint(mPosition));
i++;

public IEnumerator DeleteLine()
{
    int i = lineRenderer.positionCount;

    while (true)
    {

        if(i >= 0)
        {
            lineRenderer.positionCount = i;
        }
        else
        {
            lineRenderer.positionCount = 0;
            i = 0;
            StopCoroutine(_deletePosLine);
        }
        print(i);
        i--;

        yield return new WaitForSeconds(0.1f);

    }
}

A: *

*Get all points of your LineRenderer with GetPositions() or keep the list yourself.

*Remove the first item from the array. You can do this by allocating another array (minus one point) and copying with all items, starting from index 1. (not 0). Other alternatives exist by using Lists/Collections.

*Then set all positions again using SetPositions() with the correct positionCount first, of course.

Or: keep track of all your points in a Stack<Vector3> and Pop() the first item, convert that to an array using ToArray() and use that inSetPositions. That might work better.
For explanation of Stack see for example https://www.tutorialsteacher.com/csharp/csharp-stack.