Q: MediaCodec encoding - dequeueInputBuffer returns INFO_TRY_AGAIN_LATER? I'm working on a project where I'm using the AudioRecord class to record audio and MediaMuxer to write the encoded data to an output file. Everything seems to be working fine once I start recording but after a few calls to the writeRecordingAudioFileSampleData method below, the dequeueInputBuffer method continuously returns INFO_TRY_AGAIN_LATER (-1).
I tried flushing the encoder every time I call the method and the issue no longer occurs. But then the app crashes when I call the stop method on the the media muxer (it says "Failed to stop the muxer"). I shouldn't have to call flush the MediaCodec but without it, I keep getting INFO_TRY_AGAIN_LATER.
Here is the method that starts the recording process. For brevity, I have not included the methods that get the presentation time or the methods that initialize the AudioRecord instance, the MediaMuxer, and the MediaCodec encoder. I don't believe the issue has to do with them but if they may be helpful, let me know and I'll post them.
    public ActionResponse startRecording()
    {
        ActionResponse response = new ActionResponse();
        try
        {
            File recordDir = new File(RECORD_TEMP_DIR);
            if(!recordDir.exists())
            {
                if(!recordDir.mkdirs())
                    throw new IOException("Could not create file");
            }

            String fileName = generateRecordingName();
            String path = RECORD_TEMP_DIR + "/" + fileName + "." + recordingOutputOptions.recordAudioFormat.name;
            currentTrack = new AudioFile();
            currentTrack.setName(fileName);
            currentTrack.setPath(path);
            currentTrack.setFormat(recordingOutputOptions.recordAudioFormat);

            this.initializeAudioRecord();
            if(audioRecord.getState() != AudioRecord.STATE_INITIALIZED)
                throw new IOException("Could not initialize audio record instance");

            this.initializeRecordingAudioEncoder();
            this.initializeRecordingMediaMuxer();

            encoder.start();

            audioRecord.startRecording();

            recordReadThread = new Thread(readAudioRecordRunnable);
            recordReadThread.start();

            recorderState = MEDIA_RECORDER_STATE.RECORDING;
            response.setStatus(ActionResponse.ResponseStatus.SUCCESS);
        }
        catch (IOException e)
        {
            response.setStatus(ActionResponse.ResponseStatus.FAILURE);
            response.setError(e);
        }

        return response;
    }

And here is the runnable where I'm reading data from the AudioRecord instance:
        private Runnable readAudioRecordRunnable = new Runnable()
    {
        @Override
        public void run()
        {
            ActionResponse response = new ActionResponse(ActionResponse.ResponseStatus.SUCCESS);
            File outFile = new File(currentTrack.path);
            try
            {
                if(outFile.exists())
                    outFile.delete();

                // Parent directory should have already been created before we started recording
                if(!outFile.createNewFile())
                {
                    response.setStatusMessage("Could not create file");
                    response.setStatus(ActionResponse.ResponseStatus.FAILURE);
                }
                else
                {
                    ByteBuffer buffer = ByteBuffer.allocateDirect(recordingOutputOptions.bufferSize);
                    int numReads = 0;
                    while (recorderState == MEDIA_RECORDER_STATE.RECORDING)
                    {
                        int result = audioRecord.read(buffer, recordingOutputOptions.bufferSize);

                        if (result >= 0)
                        {
                            audioAbsolutePtsUs = (System.nanoTime()) / 1000L;
                            int samplesPerBuffer = recordingOutputOptions.bufferSize / recordingOutputOptions.bytesPerSample;
                            long presentationTime = getPresentationTimeUs(audioAbsolutePtsUs,samplesPerBuffer);

                            Log.e("TAG","Writing " + result + " bytes of recorded data with presentation time: " + String.valueOf(presentationTime));
                            ActionResponse encodeResponse = writeRecordingAudioFileSampleData(buffer,false,presentationTime);
                            if(!encodeResponse.isSuccess())
                            {
                                response = encodeResponse;
                                break;
                            }

                            buffer.clear();
                            numReads++;
                            //encoder.flush();
                        }
                        else
                        {
                            response.setStatus(ActionResponse.ResponseStatus.FAILURE);
                            response.setStatusMessage("Audio record return result: " + result);
                            break;
                        }
                    }
                }

                if(response.isSuccess())
                    writeRecordingAudioFileSampleData(null,true,0);
            }
            catch (Exception e)
            {
                response.setStatus(ActionResponse.ResponseStatus.FAILURE);
                response.setStatusMessage("Error occurred while recording");
                response.setError(e);
            }
            finally
            {
                try
                {
                    encoder.stop();
                    encoder.release();
                    encoder = null;

                    muxer.stop();
                    muxer.release();
                    muxer = null;
                    isMuxerStarted = false;
                }
                catch (Exception ex)
                {
                    Log.e("Recording Error","Error stopping and cleaning up encoder and muxer",ex);
                }
            }

            if(!response.isSuccess())
            {
                stopRecording();

                outFile.delete();

                Log.e("Recording Error",response.statusMessage,response.error);
                if(recordEventHandler!=null)
                    recordEventHandler.onRecordError(response);
            }
        }
    };

And here is the writeRecordingAudioFileSampleData method:
        public ActionResponse writeRecordingAudioFileSampleData(final ByteBuffer data,boolean isEndOfStream, long presentationTime)
    {
        ActionResponse response = new ActionResponse(ActionResponse.ResponseStatus.SUCCESS);
        try
        {
            boolean doneSubmittingInput = false;
            int index;
            int numBytesSubmitted = 0;
            int numBytesEncoded = 0;
            int numRetriesDequeueOutputBuffer = 0;
            ByteBuffer[] inputBuffers = encoder.getInputBuffers();
            ByteBuffer[] outputBuffers = encoder.getOutputBuffers();

            while (true)
            {
                if (!doneSubmittingInput)
                {
                    index = encoder.dequeueInputBuffer(ENCODER_BUFFER_TIMEOUT_US);
                    if (index != MediaCodec.INFO_TRY_AGAIN_LATER)
                    {
                        Log.e("TAG","Dequeued input buffer: " + index);
                        if(isEndOfStream)
                        {
                            doneSubmittingInput = true;
                            encoder.queueInputBuffer(index, 0, 0, 0, BUFFER_FLAG_END_OF_STREAM);
                        }
                        else
                        {
                            int dataSize = data.capacity();
                            if (numBytesSubmitted >= dataSize)
                            {
                                doneSubmittingInput = true;
                            }
                            else
                            {
                                ByteBuffer buffer = inputBuffers[index];
                                buffer.clear();
                                buffer.put(data);
                                encoder.queueInputBuffer(index, 0, buffer.remaining(), presentationTime, 0);
                                Log.e("TAG","Queued input buffer: " + index);
                                numBytesSubmitted += buffer.remaining();
                            }
                        }
                    }
                    else
                    {                            response.setStatus(ActionResponse.ResponseStatus.FAILURE);
                        response.setStatusMessage("Dequeue input buffer returned: " + index);
                        break;
                    }
                }

                MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
                index = encoder.dequeueOutputBuffer(info, ENCODER_BUFFER_TIMEOUT_US);

                if (index == MediaCodec.INFO_TRY_AGAIN_LATER)
                {
                    Log.e("TAG","No output buffer available");

                    if (++numRetriesDequeueOutputBuffer > MAX_NUM_RETRIES_DEQUEUE_OUTPUT_BUFFER)
                    {
                        if(!isEndOfStream)
                        {
                            // All data encoded
                            Log.e("TAG","Max Retries Exceeded. All data has been encoded.");
                            break;
                        }
                        else
                        {
                            Log.e("TAG","Max Retries Exceeded. End of stream input has been queued.");
                            // EOS Input Queued, Continue Loop to Receive output
                        }
                    }
                }
                else if (index == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED)
                {
                    // should only happen once before receiving buffers
                    if (isMuxerStarted)
                    {
                        // should not occur
                        response.setStatus(ActionResponse.ResponseStatus.FAILURE);
                        response.setStatusMessage("Output format changed after muxer started");
                        break;
                    }

                    MediaFormat newFormat = encoder.getOutputFormat();
                    muxerTrackIndex = muxer.addTrack(newFormat);
                    muxer.start();
                    isMuxerStarted = true;
                    Log.e("TAG","Started Muxer");
                }
                else if (index == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED)
                {
                    // should not occur
                    Log.e("TAG","Output buffers changed");
                    outputBuffers = encoder.getOutputBuffers();
                }
                else if (index < 0)
                {
                    Log.e("TAG","Unexpected index " + index + " received from dequeueOutputBuffer");
                    // Unexpected result - should not occur. Ignore it
                }
                else
                {
                    Log.e("TAG","Dequeued output buffer: " + index);
                    ByteBuffer encodedData = outputBuffers[index];
                    if ((info.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0)
                    {
                        // The codec config data was pulled out and fed to the muxer when we got
                        // the INFO_OUTPUT_FORMAT_CHANGED status.  Ignore it.
                        Log.e("TAG","Ignoring codec config data");
                        info.size = 0;
                    }

                    if (info.size != 0)
                    {
                        if (!isMuxerStarted)
                        {
                            // should not occur
                            response.setStatus(ActionResponse.ResponseStatus.FAILURE);
                            response.setStatusMessage("Attempting to write data but muxer was not started");
                            break;
                        }

                        info.presentationTimeUs = presentationTime;
                        muxer.writeSampleData(muxerTrackIndex,encodedData,info);
                        Log.e("TAG","Wrote " + info.size + " bytes to muxer");
                        numBytesEncoded += info.size;
                    }

                    encoder.releaseOutputBuffer(index, false);
                    Log.e("TAG","Releasing output buffer: " + index);

                    if ((info.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0)
                    {
                        // EOS Submitted
                        if(!isEndOfStream)
                        {
                            // Unexpected EOS
                            response.setStatus(ActionResponse.ResponseStatus.FAILURE);
                            response.setStatusMessage("Unexpected buffer end of stream flag");
                        }
                        else
                            Log.e("TAG","Dequeued end of stream reached. All data has been encoded.");

                        break;
                    }
                }
            }
        }
        catch (Exception exc)
        {
            response.setStatus(ActionResponse.ResponseStatus.FAILURE);
            response.setStatusMessage(exc.getMessage());
            response.setError(exc);
        }
        finally
        {

        }

        return response;
    }

Finally, here is a sample of the output I get when running the app, which shows where the recording stops:
W/ExtendedACodec: Failed to get extension for extradata parameter
E/TAG: Writing 28288 bytes of recorded data with presentation time: 41035517230
E/TAG: Dequeued input buffer: 0
E/TAG: Queued input buffer: 0
I/MPEG4Writer: limits: 4294967295/0 bytes/us, bit rate: -1 bps and the estimated moov size 3195 bytes
D/MPEG4Writer: Audio track starting
E/TAG: Started Muxer
E/TAG: Dequeued input buffer: 1
E/TAG: Dequeued output buffer: 0
       Ignoring codec config data
E/TAG: Releasing output buffer: 0
E/TAG: Dequeued output buffer: 1
I/MPEG4Writer: setStartTimestampUs: 41035517230
               Earliest track starting time: 41035517230
E/TAG: Wrote 371 bytes to muxer
       Releasing output buffer: 1
E/TAG: Dequeued output buffer: 2
E/TAG: Wrote 372 bytes to muxer
E/TAG: Releasing output buffer: 2
E/TAG: Dequeued output buffer: 3
W/MPEG4Writer: 0-duration samples found: 1
E/TAG: Wrote 520 bytes to muxer
       Releasing output buffer: 3
E/TAG: No output buffer available
E/TAG: No output buffer available
I/chatty: uid=10286(com.bandindustries.musicjournal) Thread-4 identical 3 lines
E/TAG: No output buffer available
E/TAG: Max Retries Exceeded. All data has been encoded.
       Writing 28288 bytes of recorded data with presentation time: 41035677592
       Dequeued input buffer: 2
E/TAG: Queued input buffer: 2
E/TAG: Dequeued output buffer: 0
W/MPEG4Writer: 0-duration samples found: 1
E/TAG: Wrote 513 bytes to muxer
E/TAG: Releasing output buffer: 0
E/TAG: Dequeued input buffer: 3
E/TAG: Dequeued output buffer: 1
       Wrote 462 bytes to muxer
E/TAG: Releasing output buffer: 1
E/TAG: Dequeued output buffer: 2
       Wrote 433 bytes to muxer
E/TAG: Releasing output buffer: 2
E/TAG: No output buffer available
I/chatty: uid=10286(com.bandindustries.musicjournal) Thread-4 identical 4 lines
E/TAG: No output buffer available
       Max Retries Exceeded. All data has been encoded.
E/TAG: Writing 28288 bytes of recorded data with presentation time: 41035837955
E/TAG: Dequeued input buffer: 0
E/TAG: Queued input buffer: 0
E/TAG: Dequeued output buffer: 3
W/MPEG4Writer: 0-duration samples found: 2
E/TAG: Wrote 407 bytes to muxer
E/TAG: Releasing output buffer: 3
E/TAG: Dequeued input buffer: 2
E/TAG: Dequeued output buffer: 0
       Wrote 408 bytes to muxer
E/TAG: Releasing output buffer: 0
E/TAG: Dequeued output buffer: 1
E/TAG: Wrote 392 bytes to muxer
E/TAG: Releasing output buffer: 1
E/TAG: Dequeued output buffer: 2
E/TAG: Wrote 390 bytes to muxer
E/TAG: Releasing output buffer: 2
E/TAG: No output buffer available
I/chatty: uid=10286(com.bandindustries.musicjournal) Thread-4 identical 4 lines
E/TAG: No output buffer available
E/TAG: Max Retries Exceeded. All data has been encoded.
E/TAG: Writing 28288 bytes of recorded data with presentation time: 41035998318
E/TAG: Dequeued input buffer: 0
E/TAG: Queued input buffer: 0
E/TAG: Dequeued output buffer: 3
W/MPEG4Writer: 0-duration samples found: 3
E/TAG: Wrote 356 bytes to muxer
E/TAG: Releasing output buffer: 3
I/zygote64: Do partial code cache collection, code=27KB, data=29KB
            After code cache collection, code=27KB, data=29KB
            Increasing code cache capacity to 128KB
D/MPEG4Writer: Audio track stopping. Stop source
               Audio track source stopping
               Audio track source stopped
I/MPEG4Writer: Received total/0-length (11/0) buffers and encoded 11 frames. - Audio
               Audio track drift time: 0 us
D/MPEG4Writer: Audio track stopped. Stop source
               Audio track stopped. Stop source
               Stopping writer thread
D/MPEG4Writer: 0 chunks are written in the last batch
D/MPEG4Writer: Writer thread stopped
I/MPEG4Writer: Ajust the moov start time from 41035517230 us -> 41035517230 us
D/MPEG4Writer: Audio track stopping. Stop source
E/Recording Error: Dequeue input buffer returned: -1

Has anyone ever experienced this before? This is my first time working with low-level media classes in Android and I couldn't find many good examples online or in the documentation. I appreciate any help. Thank you.
UPDATE: The issue where the app crashes when stopping the media muxer was due to sending 0 as the presentation time stamp for the last call, which is the end of stream. But I'm getting an empty file as output for some reason.


Q: Load single column of CSV into MySQL I have a csv file that is formated as follows:
Rank, URL
1, www.google.com
2, www.facebook.com
etc...

I have a table with structure
url, source, date_added

Where each csv file has a different source ID.
I am using the following query to load my data
load data local infile 'this.csv'
into table seeds.seed
fields terminated by ',';

Which doesn't quite do what I want but it's my starting point.
What I want to do is select column 2 to be inserted as my URL field, and set the source to 0 for each entry. So I am thinking something like this...
load data local infile 'this.csv'
into table seeds.seed(url, source)
select col1, '0'
fields terminated by ',';

What is the correct notation for col1? And am I missing any other key parts to the query?

A: LOAD DATA INFILE 'this.csv'
  INTO TABLE seed
  (col1) SET source = 0;
FIELDS TERMINATED BY ',' ENCLOSED BY '"' ESCAPED BY '"'
LINES TERMINATED BY '\r\n';

Have a look into SO answer.
This is the reference

A: Query that ended up working
load data local infile 'this.csv' into table seeds.seed
fields terminated by ',' lines terminated by '\n'
(@col1,@col2) set url=@col2, source='0';

A: it's quite tricky using load data infile. I spent all last week trying to work it out with so many numerous errors. I'll give you my insights.
I can't see your create table statement so I don't know what datatypes you are using.
If you have integer fields then you have to put at least a 0 in each field in your csv file even if it is wrong. you remove it later post import.
If your integer field is a auto_increment like a primary key then you can omit the field alltogether. don't make my mistake and just leave the field there with no values. Delete it completely otherwise your csv will start with a field terminator character and cause no end of issues.
load data infile 'file.csv'
into table mytablename
fields terminated by ','
lines terminated by '\r\n' - ( for windows)
ignore 1 lines (field1, field2, field4 etc.) - you list your fields in your csv there. If you have fields with no data then you can delete them from your csv and omit them from the list here too.
ignore 1 lines - ignores the first line of the csv which contains your field list.
set id=null,
field3=null;
I set my auto_increment id field to null as its not in the csv file and the mysql knows it exists and what to do with it.
Also set field3 to null because that had no values and was deleted from the csv file as an example.


Q: Angular 2 how to put object array in to another object array So I have 2 Arrays (Always equal index) :
A: [
{name: Jhon1}
{name: Jhon2}
{name: Jhon3}
]

B: [
{lastName: Pom1}
{lastName: Pom2}
{lastName: Pom3}
]

Expected Result after merge  :
A: [
   {name: Jhon1, lastName: Pom1}
   {name: Jhon2, lastName: Pom2}
   {name: Jhon3, lastName: Pom3}
]

Concat method just merges the whole array in to one like this :
  A: [
    {name: Jhon1}
    {name: Jhon2}
    {name: Jhon3}
    {lastName: Pom1}
    {lastName: Pom2}
    {lastName: Pom3}
    ]

My own function that I am trying. Below there is two arrays: this.prices and this.search.favoriteItems, I want to merge then the same way as I described before :
showProducts(){
   for(let i of this.localStorageArray){
    let id = localStorage.getItem(i);
    this.search.getProductsById(id).subscribe
    ((data: any) => {
     this.prices.push(data.lowestPrices.Amazon);
     this.search.favoriteItems.push(data);
   //something here to merge this.prices and this.search
    });

  }
  }

A: You can use .map() with Object destrcuturing:

let arr1 = [{name: 'Jhon1'}, {name: 'Jhon2'}, {name: 'Jhon3'}],
    arr2 = [{lastName: 'Pom1'}, {lastName: 'Pom2'}, {lastName: 'Pom3'}];

let zip = (a1, a2) => a1.map((o, i) => ({...o, ...a2[i]}));

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


Q: Cannot initialize non-const reference from convertible type I cannot initialize a non-const reference to type T1 from a convertible type T2. However, I can with a const reference.
long l;
const long long &const_ref = l; // fine
long long &ref = l;             // error: invalid initialization of reference of
                                // type 'long long int&' from expression of type
                                // 'long int'

Most problems I encountered were related to r-values that cannot be assigned to a non-const reference. This is not the case here -- can someone explain? Thanks.

A: An integer promotion results in an rvalue. long can be promoted to a long long, and then it gets bound to a const reference. Just as if you had done:
typedef long long type;
const type& x = type(l); // temporary!

Contrarily an rvalue, as you know, cannot be bound to a non-const reference. (After all, there is no actual long long to refer to.)

A: long long is not necessarily sized equal to long and may even use an entire different internal representation. Therefor you cannot bind a non-const reference to long to an object of type long long or the other way around. The Standard forbids it, and your compiler is correct to not allow it.
You can wonder the same way about the following code snippet:
long a = 0;
long long b = 0;

a = b; // works!

long *pa = 0;
long long *pb = pa;

The last initialization won't work. Just because a type is convertible to another one, doesn't mean another type that compounds one of them is convertible to a third type that compounds the other one. Likewise, for the following case
struct A { long i; };
struct B { long long i; };

A a;
B b = a; // fail!

In this case A and B each compound the type long and long long respectively, much like long& and long long& compound these types. However they won't be convertible into each other just because of that fact. Other rules happen to apply.
If the reference is to const, a temporary object is created that has the correct type, and the reference is then bound to that object.

A: I'm not a standards lawyer, but I think this is because long long is wider than long.  A const reference is permitted because you won't be changing the value of l.  A regular reference might lead to an assignment that's too big for l, so the compiler won't allow it.

A: Let's assume that it's possible :
 long long &ref = l;

It means that later in the code you can change the value referenced by ref to the value that is bigger then long type can hold but ok for long long. Practically, it means that you overwrite extra bytes of memory which can be used by different variable with unpredictable results.


Q: Python Module Import Error "ImportError: No module named mrjob.job" System: Mac OSX 10.6.5, Python 2.6
I try to run the python script below:
from mrjob.job import MRJob

 class MRWordCounter(MRJob):
  def mapper(self, key, line):
      for word in line.split():
          yield word, 1

  def reducer(self, word, occurrences):
      yield word, sum(occurrences)

if __name__ == '__main__':
    MRWordCounter.run()

I get the following error:
:~ vskarich$ python mrjob_test.py < words
Traceback (most recent call last):
  File "mrjob_test.py", line 1, in <module>
   from mrjob.job import MRJob
  ImportError: No module named mrjob.job

I had used easy_install like so:
sudo easy_install mrjob
This command downloaded the needed .egg file, and my site-packages directory for python looks like this:
:~ vskarich$ cd /Library/Python/2.6/site-packages

:site-packages vskarich$ ls

PyYAML-3.09-py2.6-macosx-10.6-universal.egg
easy-install.pth
README
mrjob-0.2.0-py2.6.egg
boto-2.0b3-py2.6.egg
simplejson-2.1.2-py2.6-macosx-10.6-universal.egg

I am not sure what to do here as I am somewhat new to python; any help would be much appreciated. Thank you!

A: Two suggestions:

*

*Make sure you don't have any file or directory permissions problems for the installed eggs and files in the site-packages directory.

*If you have installed another instance of Python 2.6 (besides the Apple-supplied one in /usr/bin/python2.6), make sure you have installed a separate version of easy_install for it.  As is, your output indicates it was almost certainly installed using the Apple-supplied easy_install in /usr/bin which is for the Apple-supplied Python.  The easiest way to do that is to install the Distribute package using the new Python.

A: I had the same problem, I tried pip install mrjob, sudo easy_install mrjob. It looked like it installed successfully, but when I ran a simple example script, I got the import error.
I got it to work by following the instructions at: http://pythonhosted.org//mrjob/guides/quickstart.html#installation.
In a nutshell, I cloned the source code from github and ran python setup.py install. My problem might be different from yours, though. There was nothing in my site-packages directory for mrjob after running pip-install and easy_install.

A: mrjob package can be installed by running following command:
pip install mrjob
After installation, the error will be solved.
It worked in my case.


Q: Android - DatabaseUtils.sqlEscapeString() does not work I want to insert "women's cloth" in the database, so I use
String name = DatabaseUtils.sqlEscapeString("women's cloth");

but it gives out put like
"'Women''s Clothing'"

and while inserting app crashes and gives
E/SQLiteLog: (1) near ",": syntax error

--------- beginning of crash -----------------
07-12 12:42:19.628 22387-22521/com.i4ustores E/AndroidRuntime: FATAL EXCEPTION: Thread-8634
android.database.sqlite.SQLiteException: near ",": syntax error (code 1):

A: From your simple code, I guess you create SQL statement manually.
Try using String.format:
String query = String.format("SELECT * FROM %s WHERE %s = ?",
                      TABLE_NAME, SEARCH_KEY);

Read more at: Local Databases with SQLiteOpenHelper
Or try using PreparedStatement like below:
PreparedStatement pstmt = con.prepareStatement("UPDATE EMPLOYEES
                                     SET SALARY = ? WHERE ID = ?");
pstmt.setBigDecimal(1, 153833.00)
pstmt.setInt(2, 110592)

Please be aware that the parameterIndex (i.e 1 and 2 in above code) start from 1.


Q: Folder changes monitor made in Visual Basic 2010 does not write changes correctly I've made a program in Visual Basic 2010, that monitors and write down changes in a folder eg. when a file deletes, when a file renames, when a file creates and which files, but it's a problem. I've writed the code to make a new line when another change is made, when a change is made, it writes it down to a file named log.txt, but the log only looks like "File log.txt has been modified" because the program, when it write changes to the log, it changes the log.txt to write down the log, but the strange is, it deletes everything in the document and writes "File log..txt has been modified" even if I have writed in the code to make a new line before writing. Can someone help me with this problem? Here's the code:
Imports System.IO
Imports System.Diagnostics
Public Class Form1
Public watchfolder As FileSystemWatcher

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

    watchfolder = New System.IO.FileSystemWatcher()

    'this is the path we want to monitor
    watchfolder.Path = TextBox1.Text

    'Add a list of Filter we want to specify
    'make sure you use OR for each Filter as we need to
    'all of those

    watchfolder.NotifyFilter = IO.NotifyFilters.DirectoryName
    watchfolder.NotifyFilter = watchfolder.NotifyFilter Or _
                               IO.NotifyFilters.FileName
    watchfolder.NotifyFilter = watchfolder.NotifyFilter Or _
                               IO.NotifyFilters.Attributes

    ' add the handler to each event
    AddHandler watchfolder.Changed, AddressOf logchange
    AddHandler watchfolder.Created, AddressOf logchange
    AddHandler watchfolder.Deleted, AddressOf logchange

    ' add the rename handler as the signature is different
    AddHandler watchfolder.Renamed, AddressOf logrename

    'Set this property to true to start watching
    watchfolder.EnableRaisingEvents = True

    Button1.Enabled = False
    Button2.Enabled = True

    'End of code for btn_start_click
End Sub
Private Sub logchange(ByVal source As Object, ByVal e As  _
                    System.IO.FileSystemEventArgs)
    If e.ChangeType = IO.WatcherChangeTypes.Changed Then
        Dim writer As New IO.StreamWriter("log.txt")
        writer.WriteLine(Chr(13) & "File" + " " + e.FullPath + " " + "has been modified")
        writer.Close()
    End If
    If e.ChangeType = IO.WatcherChangeTypes.Created Then
        Dim writer As New IO.StreamWriter("log.txt")
        writer.WriteLine(Chr(13) & "File" + " " + e.FullPath + " " + "has been created")
        writer.Close()
    End If
    If e.ChangeType = IO.WatcherChangeTypes.Deleted Then
        Dim writer As New IO.StreamWriter("log.txt")
        writer.WriteLine(Chr(13) & "Filde" + " " + e.FullPath + " " + "has been deleted")
        writer.Close()
    End If
End Sub
Public Sub logrename(ByVal source As Object, ByVal e As  _
                        System.IO.RenamedEventArgs)
    Dim writer As New IO.StreamWriter("log.txt")
    writer.WriteLine(Chr(13) & "File" + " " + e.FullPath + "has been renamed to" + " " + e.Name)
    writer.Close()
End Sub

Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
    ' Stop watching the folder
    watchfolder.EnableRaisingEvents = False
    Button1.Enabled = True
    Button2.Enabled = False
End Sub

End Class

A: When you open your streamwriter, you are not telling it to append, so it overwrites:
Dim writer As New IO.StreamWriter("log.txt", True)

Also, you dont need a new stream for each activity:
Dim msg as string= Environment.NewLine & "File " & e.FullPath & " "
Select case e.ChangeType
      case IO.WatcherChangeTypes.Created
         msg &= "has been created"

      case IO.WatcherChangeTypes.Deleted
         msg &= "has been deleted"
      ...etc
 End Select

 Dim writer As New IO.StreamWriter("log.txt", True)
 writer.WriteLine(msg)
 writer.Close()

..you could also leave the stream open until the watcher ends
You probably should exempt logging changes to log.txt, so test e.FullPath:
 If System.Io.Path.GetFileName(e.FullPath).ToLower = "log.text" Then Exit Sub

A: Now the program in working! Thank you MPelletier and Plutonix for the amazing help! Here is the complete code:
 Imports System.IO
 Imports System.Diagnostics
 Public Class Form1

Public watchfolder As FileSystemWatcher

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

    watchfolder = New System.IO.FileSystemWatcher()
    watchfolder.IncludeSubdirectories = True

    watchfolder.Path = TextBox1.Text

    watchfolder.NotifyFilter = IO.NotifyFilters.DirectoryName
    watchfolder.NotifyFilter = watchfolder.NotifyFilter Or _
                               IO.NotifyFilters.FileName
    watchfolder.NotifyFilter = watchfolder.NotifyFilter Or _
                               IO.NotifyFilters.Attributes

    AddHandler watchfolder.Changed, AddressOf logchange
    AddHandler watchfolder.Created, AddressOf logchange
    AddHandler watchfolder.Deleted, AddressOf logchange

    AddHandler watchfolder.Renamed, AddressOf logrename

    watchfolder.EnableRaisingEvents = True

    Button1.Enabled = False
    Button2.Enabled = True

End Sub
Private Sub logchange(ByVal source As Object, ByVal e As  _
                    System.IO.FileSystemEventArgs)
    If System.IO.Path.GetFileName(e.FullPath).ToLower = "log.txt" Then Exit Sub
    Dim msg As String = Environment.NewLine & "File " & e.FullPath & " "

    Select Case e.ChangeType
        Case IO.WatcherChangeTypes.Created
            msg &= "has been created" + "  " + "Time:" + " " + Format(TimeOfDay)

        Case IO.WatcherChangeTypes.Deleted
            msg &= "has been deleted" + "  " + "Time:" + " " + Format(TimeOfDay)

        Case IO.WatcherChangeTypes.Changed
            msg &= "has been modified" + "  " + "Time:" + " " + Format(TimeOfDay)

    End Select

    Dim writer As New IO.StreamWriter("log.txt", True)
    writer.WriteLine(msg)
    writer.Close()
End Sub
Public Sub logrename(ByVal source As Object, ByVal e As  _
                        System.IO.RenamedEventArgs)
    Select e.ChangeType
        Case IO.WatcherChangeTypes.Created
            Exit Sub
        Case IO.WatcherChangeTypes.Changed
            Exit Sub
        Case IO.WatcherChangeTypes.Deleted
            Exit Sub
        Case Else
            Dim msgrn As String = Environment.NewLine & "File " + e.OldName + " "
            msgrn &= "has been renamed to" + " " + e.Name + "  " + "Time:" + " " + Format(TimeOfDay)
            Dim writer As New IO.StreamWriter("log.txt", True)
            writer.WriteLine(msgrn)
            writer.Close()
    End Select

End Sub

Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click

    watchfolder.EnableRaisingEvents = False
    Button1.Enabled = True
    Button2.Enabled = False
End Sub

Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
    Me.Hide()
    MsgBox("To close it later, don't open the program again, press CTRL+ALT+DELETE and press Start Task Manager or something like that, and go to processes and kill FolderMonitor.exe or what you have named the file", 0 + 64, "FolderMonitor")
End Sub
End Class


Q: TypeError: coercing to Unicode: need string or buffer, file found in python(writing data from existing files into single file) I am supposed to write the data from three existing files to a single file in python. I faced the error "TypeError: coercing to Unicode: need string or buffer", file found. My three existing files are e, g and m and I made a file named results for writing my data from those three mentioned existing files. I really appreciate for any help
filenames= [e,g,m]
    with open(results, "w") as outfile:
        for file in filenames:
            with open(file) as infile:
                for line in infile:
                    outfile.write(line)

A: Your filename should be a string.
Filename e, m, g should be "e", "m", "g", result should be "result".
Refer to code below:
#!/usr/bin/python
# -*- coding: utf-8 -*-

filenames= ["e","g","m"]

with open("results", "w") as outfile:
    for file in filenames:
        with open(file) as infile:
            for line in infile:
                outfile.write(line)


Q: p Values for FUN="coef" in bootstrapLavaan Suppose I have a lavaan model:
fit='
    #Structural model
    var1=~item1+item2+item3
    var2=~item1+item2+item3
    var3=~item1+item2+item3

    #Path model
    var3~var2
    var2~var1
    '

I then use sem to calculate:
    example=lavaan::sem(fit, data)

Now I want to apply bootstrapLavaan as such:
    boot.example=bootstrapLavaan(example, FUN="coef")

When I analyse the object using...
    summary(boot.example)

... I am only given values for the coefficients such as the means, medians, min, max, etc. Is there some way to get p values for these coefficients?


Q: Unable to upload attachments to testresult using TFS API I am trying to upload attachments using TFS API
Following is the code snippet :
    result.State = TestResultState.Completed;
    result.RunBy = identity;

    var attachment = result.CreateAttachment(logFilePath);
    run.Attachments.Add(attachment);

The code doesn't throw any error. Also i see that IAttachmentOwner.AttachmentUploadCompleted Event has been raised indicating it is completed.
Yet I am not able to see the uploaded attachments on my TFSWebPortal.
Am I missing something here ?
P.S : First question here. Please feel free to correct me.

A: You can get it works with the following code:
TfsTeamProjectCollection tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri("http://tfsservername:8080/tfs/DefaultCollection"));
        ITestManagementTeamProject project = tfs.GetService<ITestManagementService>().GetTeamProject("projectName");

        foreach (ITestPlan p in project.TestPlans.Query("Select * From TestPlan"))
        {
            ITestRun testRun = p.CreateTestRun(false);
            var testPoints = p.QueryTestPoints("SELECT * from TestPoint");
            foreach (ITestPoint testPoint in testPoints)
            {
                testRun.AddTestPoint(testPoint, null);
            }
            testRun.Save();

            ITestCaseResultCollection results = testRun.QueryResults();

            foreach (ITestCaseResult result in results)
            {
                result.Attachments.Add(result.CreateAttachment(@"C:\Users\visong\Pictures\000.jpg"));
                result.Outcome = TestOutcome.Warning;
                result.State = TestResultState.Completed;
                results.Save(true);
            }

            testRun.Save();
            testRun.Refresh();
        }

Then you should be able to find the attachement in the test result you're working with in MTM.


Q: I can't find Generate local resource from tools menu in visual studio 2013 When I'm in design view(markup) of a web page, I can't find the Generate Local Resource from my tools menu. Can anyone tell me how to enable this tool?


Q: Level Order Traversal: Deleting a Subtree #include <iostream>

using namespace std;

struct node {
    int item;
    node* l;
    node* r;
    node (int x) {
        item = x;
        l = 0;
        r = 0;
    }
    node(int x, node* l, node* r) {
        item = x;
        this->l = l;
        this->r = r;
    }
};

typedef node* link;

class QUEUE {
private:
    link* q;
    int N;
    int head;
    int tail;
public:
    QUEUE(int maxN) {
        q = new link[maxN + 1];
        N = maxN + 1;
        head = N;
        tail = 0;
    }
    int empty() const {
        return head % N == tail;
    }
    void put(link item) {
        q[tail++] = item;
        tail = tail % N;
    }

    link get() {
        head = head % N;
        return q[head++];
    }
};

link head = 0; // Initial head of the tree

link find(int x) {
    if (head == 0) {
        cout << "\nEmpty Tree\n";
        return 0;
    }
    link temp = head;
    // To find the node with the value x and return its link
    QUEUE q(100);
    q.put(temp);
    while (!q.empty()) {
        temp = q.get();
        if (temp->item == x) {
            return temp;
        }
        if (temp->l != 0) q.put(temp->l);
        if (temp->r != 0) q.put(temp->r);
    }
    return 0;
}

void print(link temp) {
    QUEUE q(100);
    q.put(temp);
    while (!q.empty()) {
        temp = q.get();
        cout << temp->item << ", ";
        if (temp->l != 0) q.put(temp->l);
        if (temp->r != 0) q.put(temp->r);
    }
}

void deleteAll(link h) {
    // This deletes the entire binary tree
    QUEUE q(100);
    q.put(h);
    while (!q.empty()) {
        h = q.get();
        if (h->l != 0) q.put(h->l);
        if (h->r != 0) q.put(h->r);
        delete h;
    }
}

int main() {
    link temp = 0;
    char c;
    int n1, n2;
    cout << "\n\nPlease enter the input instructions (X to exit program) : \n\n";
    do {
        cin >> c;
        switch (c) {
            case 'C':   cin >> n1;
                        if (head == 0) {
                            head = new node(n1);
                            cout << "\nRoot node with item " << n1 << " has been created\n\n";
                        } else {
                            cout << "\nError: Tree is not empty\n\n";
                        }
                        break;

            case 'L':   cin >> n1 >> n2;
                        temp = find(n1);
                        if (temp != 0) {
                            if (temp->l == 0) {
                                temp->l = new node(n2);
                                cout << "\nNode with item " << n2 << " has been added\n\n";
                            }
                            else {
                                cout << "\nError: The specified node already has a left child\n\n";
                            }
                        }
                        else {
                            cout << "\nError: The specified node doesn't exist\n\n";
                        }
                        break;

            case 'R':   cin >> n1 >> n2;
                        temp = find(n1);
                        if (temp != 0) {
                            if (temp->r == 0) {
                                temp->r = new node(n2);
                                cout << "\nNode with item " << n2 << " has been added\n\n";
                            }
                            else {
                                cout << "\nError: The specified node already has a right child\n\n";
                            }
                        }
                        else {
                            cout << "\nError: The specified node doesn't exist\n\n";
                        }
                        break;

            case 'P':   cin >> n1;
                        temp = find(n1);
                        if (head != 0) {
                            cout << "\nLevel-order traversal of the entire tree: ";
                            print(temp);
                        }
                        else {
                            cout << "\nError: No elements to print\n\n";
                        }
                        break;

            case 'D':   cin >> n1;
                        temp = find(n1);
                        deleteAll(temp);
                        temp = 0;
                        break;

            case 'X':   cout << "\nExiting Program\n\n";
                        break;

            default:    cout << "\nInvalid input entered. Try again.\n\n";

        }
    } while (c != 'X');
    system("pause");
    return 0;
}

Sample Input:
C 9
L 9 8
R 9 6
L 8 3
R 8 5
R 6 2
L 3 4
L 4 10
L 5 1
R 5 11
L 1 12
R 1 7

It all works fine until I delete a subtree and print when it prints garbage value before crashing. Please help me figure out the bug because I've been trying in vain for hours now.
It all works fine until I delete a subtree and print when it prints garbage value before crashing. Please help me figure out the bug because I've been trying in vain for hours now.

A: When you delete a node, you call deleteAll(temp) which deletes temp, but it doesn't remove the pointer value from the l or r of temp's parent node.
This leaves you with a invalid pointer, causing garbage printing and crashing.
Unfortunately, the way your find works currently, you don't know what the current temp node's parent is when you get around to checking its value.
One way to fix it is to have a different type of find (called something like remove) that looks in l and r at each iteration for the value and sets l or r to NULL before returning the pointer. You might have to have a special case for when the value is found in the root.
Edit (sample code added):
I am assuming you are not using recursion for some reason, so my code uses your existing queue based code. I only changed enough to get it working.
findAndUnlink find the node with the value given and "unlinks" it from the tree. It returns the node found, giving you a completely separate tree. Note: it is up to the caller to free up the returned tree, otherwise you will leak memory.
This is a drop in replacement for find in your existing code, as your existing code then calls deleteAll on the returned node.
link findAndUnlink(int x) {
    if (head == 0) {
        cout << "\nEmpty Tree\n";
        return 0;
    }
    link temp = head;
    if (temp->item == x) {
        // remove whole tree
        head = NULL;
        return temp;
    }
    // To find the node with the value x and remove it from the tree and return its link
    QUEUE q(100);
    q.put(temp);
    while (!q.empty()) {
        temp = q.get();
        if (temp->l != NULL) {
            if (temp->l->item == x) {
                link returnLink = temp->l;
                temp->l = NULL;
                return returnLink;
            }
            q.put(temp->l);
        }
        if (temp->r != NULL) {
            if (temp->r->item == x) {
                link returnLink = temp->r;
                temp->r = NULL;
                return returnLink;
            }
            q.put(temp->r);
        }
    }
    return 0;
}

A: Try the recursive function:
void Delete(link h)
{
  if(h)
  {
    if(h->l) Delete(h->l);
    if(h->r) Delete(h->r);
    delete(h);
  }
}


Q: Dotnetnuke 6 Ribbonbar Admin and dropdown gone
Above is the ribbonbar after I have logged in as a super user. The Admin option next to Host is completely gone
The site is running DNN6, the skin is only in the site portal folder, and it seems that all admin modules and options have gone away. Even the header, which I set in Site Settings (under Admin), went away!
Has anyone else had their admin options completely disappear on them? Is it possible that the skin is messing it up (all other sites use the same _default menu files and they work fine)?
Thanks for any replies.

A: We've recently had this exact situation occur in one of our DNN sites. It turn out that one of the site's administrators had accidentally renamed the Admin page from within the "Page Management" section (it's easy to see how that could happen). The fix was to go directly to /Admin/Pages.aspx and change the "Page Name" back to "Admin" ... and it will show up in the ribbon bar again.
As a suggestion to DNN developers, I would recommend making the Admin page and its subpages impossible to rename....

A: Can you check the database to see if those pages exist? What if you try to navigate to http://website/admin.aspx do you see the admin page and all the child pages there?


Q: Is it possible to deploy a background Function "myBgFunctionInProjectB" in "project-b" and triggered by my topic "my-topic-project-a" from "project-a" It's possible to create a topic "my-topic-project-a" in project "project-a" so that it can be publicly visible (this is done by setting the role "pub/sub subscriber" to "allUsers" on it).
Then from project "project-b" I can create a subscription to "my-topic-project-a"  and read the events from "my-topic-project-a". This is done using the following gcloud commands:
(these commands are executed on project "project-b")
gcloud pubsub subscriptions create subscription-to-my-topic-project-a --topic projects/project-a/topics/my-topic-project-a
gcloud pubsub subscriptions pull subscription-to-my-topic-project-a --auto-ack

So ok this is possible when creating a subscription in "project-b" linked to "my-topic-project-a" in "project-a".
In my use case I would like to be able to deploy a background function "myBgFunctionInProjectB" in "project-b" and triggered by my topic "my-topic-project-a" from "project-a"
But ... this doesn't seem to be possible since gcloud CLI is not happy when you provide the full topic name while deploying the cloud function:
gcloud beta functions deploy myBgFunctionInProjectB --runtime nodejs8 --trigger-topic projects/project-a/topics/my-topic-project-a --trigger-event google.pubsub.topic.publish

ERROR: (gcloud.beta.functions.deploy) argument --trigger-topic: Invalid value 'projects/project-a/topics/my-topic-project-a': Topic must contain only Latin letters (lower- or upper-case), digits and the characters - + . _ ~ %. It must start with a letter and be from 3 to 255 characters long.

is there a way to achieve that or this is actually not possible?
Thanks

A: So, it seems that is not actually possible to do this. I have found it by checking it in 2 different ways:

*

*If you try to create a function through the API explorer, you will need to fill the location where you want to run this, for example, projects/PROJECT_FOR_FUNCTION/locations/PREFERRED-LOCATION, and then, provide a request body, like this one:

{
"eventTrigger": {
"resource": "projects/PROJECT_FOR_TOPIC/topics/YOUR_TOPIC",
"eventType": "google.pubsub.topic.publish"
},
"name":
  "projects/PROJECT_FOR_FUNCTION/locations/PREFERRED-LOCATION/functions/NAME_FOR_FUNTION
}

This will result in a 400 error code, with a message saying:

{
"field": "event_trigger.resource",
"description": "Topic must be in the same project as function."
}

It will also say that you missed the source code, but, nonetheless, the API already shows that this is not possible.

*

*There is an already open issue in the Public Issue Tracker for this very same issue. Bear in mind that there is no ETA for it.

I also tried to do this from gcloud, as you tried. I obviously had the same result. I then tried to remove the projects/project-a/topics/ bit from my command, but this creates a new topic in the same project that you create the function, so, it's not what you want.


Q: where can i find metadata of all the amazon cloud services? I searching for what are the metadata that AWS uses for each and every service. For AWS instance it uses ami-id, ami_launch-index, hostname, instance-action and many more as the metadata like wise where i can find metadata for all the services like EBS, VPN....
Reference
Information obtained from Amazon Elastic Compute Cloud User Guide for Microsoft Windows Instances pdf pg no : 232 – 242

A: I believe you are interested in knowing the properties of the each AWS Resource / Service and not the meta-data. I don't think there is a straight answer. The work around what I can recommend is using the AWS CloudFormation's Syntax definition of each AWS Resource.
For Example :
EC2 Instance is represented by the following syntax. Not all of them are mandatory. http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html
Look at the KEYS of the Key:Value pair provided below [ "AvailabilityZone" : String ]
{
   "Type" : "AWS::EC2::Instance",
   "Properties" : {
      "AvailabilityZone" : String,
      "BlockDeviceMappings" : [ EC2 Block Device Mapping, ... ],
      "DisableApiTermination" : Boolean,
      "EbsOptimized" : Boolean,
      "IamInstanceProfile" : String,
      "ImageId" : String,
      "InstanceInitiatedShutdownBehavior" : String,
      "InstanceType" : String,
      "KernelId" : String,
      "KeyName" : String,
      "Monitoring" : Boolean,
      "NetworkInterfaces" : [ EC2 Network Interface, ... ],
      "PlacementGroupName" : String,
      "PrivateIpAddress" : String,
      "RamdiskId" : String,
      "SecurityGroupIds" : [ String, ... ],
      "SecurityGroups" : [ String, ... ],
      "SourceDestCheck" : Boolean,
      "SsmAssociations" : [ SSMAssociation, ... ]
      "SubnetId" : String,
      "Tags" : [ Resource Tag, ... ],
      "Tenancy" : String,
      "UserData" : String,
      "Volumes" : [ EC2 MountPoint, ... ],
      "AdditionalInfo" : String
   }
}

For VPC [http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc.html]
{
   "Type" : "AWS::EC2::VPC",
   "Properties" : {
      "CidrBlock" : String,
      "EnableDnsSupport" : Boolean,
      "EnableDnsHostnames" : Boolean,
      "InstanceTenancy" : String,
      "Tags" : [ Resource Tag, ... ]
   }
}

For EBS Volume [http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html]
{
   "Type":"AWS::EC2::Volume",
   "Properties" : {
      "AutoEnableIO" : Boolean,
      "AvailabilityZone" : String,
      "Encrypted" : Boolean,
      "Iops" : Number,
      "KmsKeyId" : String,
      "Size" : String,
      "SnapshotId" : String,
      "Tags" : [ Resource Tag, ... ],
      "VolumeType" : String
   }
}

The CloudFormation Resource Page has details for most of the items [http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html]. Below is the current list as of today [7 Jan 2016]

*

*AWS::AutoScaling::AutoScalingGroup

*AWS::AutoScaling::LaunchConfiguration

*AWS::AutoScaling::LifecycleHook

*AWS::AutoScaling::ScalingPolicy

*AWS::AutoScaling::ScheduledAction

*AWS::CloudFormation::Authentication

*AWS::CloudFormation::CustomResource

*AWS::CloudFormation::Init

*AWS::CloudFormation::Interface

*AWS::CloudFormation::Stack

*AWS::CloudFormation::WaitCondition

*AWS::CloudFormation::WaitConditionHandle

*AWS::CloudFront::Distribution

*AWS::CloudTrail::Trail

*AWS::CloudWatch::Alarm

*AWS::CodeDeploy::Application

*AWS::CodeDeploy::DeploymentConfig

*AWS::CodeDeploy::DeploymentGroup

*AWS::CodePipeline::CustomActionType

*AWS::CodePipeline::Pipeline

*AWS::Config::ConfigRule

*AWS::Config::ConfigurationRecorder

*AWS::Config::DeliveryChannel

*AWS::DataPipeline::Pipeline

*AWS::DirectoryService::MicrosoftAD

*AWS::DirectoryService::SimpleAD

*AWS::DynamoDB::Table

*AWS::EC2::CustomerGateway

*AWS::EC2::DHCPOptions

*AWS::EC2::EIP

*AWS::EC2::EIPAssociation

*AWS::EC2::Instance

*AWS::EC2::InternetGateway

*AWS::EC2::NetworkAcl

*AWS::EC2::NetworkAclEntry

*AWS::EC2::NetworkInterface

*AWS::EC2::NetworkInterfaceAttachment

*AWS::EC2::PlacementGroup

*AWS::EC2::Route

*AWS::EC2::RouteTable

*AWS::EC2::SecurityGroup

*AWS::EC2::SecurityGroupEgress

*AWS::EC2::SecurityGroupIngress

*AWS::EC2::SpotFleet

*AWS::EC2::Subnet

*AWS::EC2::SubnetNetworkAclAssociation

*AWS::EC2::SubnetRouteTableAssociation

*AWS::EC2::Volume

*AWS::EC2::VolumeAttachment

*AWS::EC2::VPC

*AWS::EC2::VPCDHCPOptionsAssociation

*AWS::EC2::VPCEndpoint

*AWS::EC2::VPCGatewayAttachment

*AWS::EC2::VPCPeeringConnection

*AWS::EC2::VPNConnection

*AWS::EC2::VPNConnectionRoute

*AWS::EC2::VPNGateway

*AWS::EC2::VPNGatewayRoutePropagation

*AWS::ECS::Cluster

*AWS::ECS::Service

*AWS::ECS::TaskDefinition

*AWS::EFS::FileSystem

*AWS::EFS::MountTarget

*AWS::ElastiCache::CacheCluster

*AWS::ElastiCache::ParameterGroup

*AWS::ElastiCache::ReplicationGroup

*AWS::ElastiCache::SecurityGroup

*AWS::ElastiCache::SecurityGroupIngress

*AWS::ElastiCache::SubnetGroup

*AWS::ElasticBeanstalk::Application

*AWS::ElasticBeanstalk::ApplicationVersion

*AWS::ElasticBeanstalk::ConfigurationTemplate

*AWS::ElasticBeanstalk::Environment

*AWS::ElasticLoadBalancing::LoadBalancer

*AWS::IAM::AccessKey

*AWS::IAM::Group

*AWS::IAM::InstanceProfile

*AWS::IAM::ManagedPolicy

*AWS::IAM::Policy

*AWS::IAM::Role

*AWS::IAM::User

*AWS::IAM::UserToGroupAddition

*AWS::Kinesis::Stream

*AWS::KMS::Key

*AWS::Lambda::EventSourceMapping

*AWS::Lambda::Function

*AWS::Lambda::Permission

*AWS::Logs::Destination

*AWS::Logs::LogGroup

*AWS::Logs::LogStream

*AWS::Logs::MetricFilter

*AWS::Logs::SubscriptionFilter

*AWS::OpsWorks::App

*AWS::OpsWorks::ElasticLoadBalancerAttachment

*AWS::OpsWorks::Instance

*AWS::OpsWorks::Layer

*AWS::OpsWorks::Stack

*AWS::RDS::DBCluster

*AWS::RDS::DBClusterParameterGroup

*AWS::RDS::DBInstance

*AWS::RDS::DBParameterGroup

*AWS::RDS::DBSecurityGroup

*AWS::RDS::DBSecurityGroupIngress

*AWS::RDS::DBSubnetGroup

*AWS::RDS::EventSubscription

*AWS::RDS::OptionGroup

*AWS::Redshift::Cluster

*AWS::Redshift::ClusterParameterGroup

*AWS::Redshift::ClusterSecurityGroup

*AWS::Redshift::ClusterSecurityGroupIngress

*AWS::Redshift::ClusterSubnetGroup

*AWS::Route53::HealthCheck

*AWS::Route53::HostedZone

*AWS::Route53::RecordSet

*AWS::Route53::RecordSetGroup

*AWS::S3::Bucket

*AWS::S3::BucketPolicy

*AWS::SDB::Domain

A: Try using AWS CLI.
You can execute the describe commands of the various services to see and understand the metadata


Q: Dot/point in datagridview when updating data So, I have a datagridview (datagridview1) and it's connected to SQL Server. datagridview in column 3 (adhb) can be update by pressing a button and just edit in the specific column. The problem is when I try to update a decimal number (e.g 100.25) it's just change to 10025. How can it be able to update decimal value?
The database (tbl_tahunan), and column 3 (adhb) is set to decimal(18,2)
query for update data
query = "UPDATE tbl_tahunan SET adhb = " + datagridview1.Rows[0].Cells[2].Value + " WHERE id_coicop = 1";

cmd = new SqlCommand(query, conn);

cmd.ExecuteNonQuery();

A: Editing databases with data grids is ridiculously easy if you make life easy. Try doing this:

*

*Make a brand new project, so you don't disturb existing code

*Add a new file of type DataSet

*Open it by double clicking

*Right click anywhere on the surface, choose Add.. TableAdapter

*Fill in the connection details of the db

*Choose "SELECT that produces rows"

*Put a query of SELECT * FROM tbl_tahunan

*Finish the wizard

*Switch to the form

*Open the Data Sources tool panel (View menu, Other Windows submenu)

*Expand the nodes in the name of your dataset

*Drag the tbl_tahunan one onto the form

*Run the program

Yes, that's it, not a single line of code written by you; VS has done it all (and made a better job of it too) and this simple app will download, display, edit and save rows. And I bet it won't have any decimal problems either..
You can look at how it works by reading the code in .Designer.cs files: the datagridview is connected to a datatable (tbl_tahunandatatable) through a bindingSource. When you fill the table with data, you will see the grid show the data automatically. You do not need to interact with the datagridview cells collection. All programmatic editing of data should be done to the datatable. This is a concept called MVC (model- the datatable, view - the datagridview, controller - sometimes the datagridview in editing mode, other times something else) - keeping M separate from VC usually helps build a sensible program structure
You can build on this simple app you've created by e.g.:

*

*opening dataset,

*right clicking on the TableAdapter,

*adding another query,

*add a query with some relevant where clause (llike SELECT * FROM tbl_tahunan WHERE adhb BETWEEN @from AND @to)

*call it a good name, like FillByAdhbBetween

*putting some text boxes in the UI

*putting a button on the ui that calls it:

tbl_tahunanTableAdapter.FillByAdhbBetween(somedatasetname.tbl_tahunan, Convert.ToDecimal(adhbfromTextbox.Text), Convert.ToDecimal(adhbtoTextbox.Text))

Now the grid will only fill with some rows instead of all
Personally I always make the first query in a table adapter have a WHERE clause, that selects by primary key. It is handy for loading related data. We almost never want to select all rows from a db into our program


Q: How do I import a sprite sheet with its JSON file into my phaser game? I am creating a game using the phaser game engine. I created a sprite sheet and downloaded it. It came with the 256 × 384 .png file with my frames and a JSON file which I assume contains information about how to split up the frames. I don't know how to import the sprite sheet with the JSON file into my preload() function. I tried using the following code but it is not working. Any help would be greatly appreciated.
var game = new Phaser.Game(1200, 750, Phaser.AUTO, '', { preload:   preload, create: create, update: update });
function preload(){
    game.load.image('background', 'assets2/background.png');
    game.load.json('robot', 'assets2/VillainSpriteSheet_json.json');
    game.load.spritesheet('robot', 'assets2/VillainSpriteSheet.png');
}

var villain;

function create(){

var villainjson = game.cache.getJSON('robot');

//enable physics
game.physics.startSystem(Phaser.Physics.ARCADE);

//create background
var background = game.add.sprite(0, 0, 'background');

//villain
villain = game.add.sprite(50, 50, 'robot');

//enable phsyics
game.physics.arcade.enable(villain);
villain.body.bounce.y = .2;
villain.body.gravity.y = 300;
villain.body.collideWorldBounds = true;

}

A: I think you are confusing two frameworks, jQuery and Phaser. For loading and displaying sprites you don't need jQuery, just Phaser will do.
The load.spritesheet expects a spritesheet where all sprites have a fixed width and height, so with all sprites in a grid layout.
What you have sounds like a spriteatlas, the difference being that in a spriteatlas each sprite can have a different width and height, and all these widths and heights per sprite are described in the accompanying .JSON file.
So I think you are looking for the load.atlasJSONHash function, something like this:
function preload(){
    //..
    game.load.atlasJSONHash('robot', 'assets2/VillainSpriteSheet.png', 'assets2/VillainSpriteSheet_json.json');

// and then load a sprite like so
// Note: 'myframename1' should be some framename from the .json file
var villain = game.add.sprite(50, 50, 'robot', 'myframename1');

And btw just to clarify, the load.json in Phaser can be used to just load a .json file, for example with for your own customised data like level layouts, dialog/multilanguage texts, highscore data, enemy patterns etc.

A: You don't want jQuery's getJSON(). You want the Phaser one.
It would be something like
p = new Phaser.Game(...);
p.cache.getJSON('foo');
p.load.image(...);


Q: how to sum up minutes and seconds ?in oracle I have a column called duration_d which is varchar2 and the data in that table looks like below
duration_d
-----------
12:25
01:35
12:10
04:21
12:18
12:24

I tried below query
SELECT SUM( to_date( duration_d, 'mi:ss' ))
  FROM table
 GROUP BY calling_number;

When I execute it following error is coming
ORA-00933: SQL command not properly ended
00933. 00000 -  "SQL command not properly ended"

can any one tell me how to make sum it?

A: To get the total as fractions of a day you can use:
SELECT SUM( TO_DATE( duration_d, 'MI:SS' ) - TO_DATE( '00:00', 'MI:SS' ) ) AS total
FROM   your_table

Which gives the result:
TOTAL
------------------------------------------
0.0383449074074074074074074074074074074074

To convert this to an interval data type you can use NUMTODSINTERVAL:
SELECT NUMTODSINTERVAL(
         SUM( TO_DATE( duration_d, 'MI:SS' ) - TO_DATE( '00:00', 'MI:SS' ) ),
         'DAY'
       ) AS total
FROM   your_table

Which gives the result:
TOTAL
-------------------
+00 00:55:13.000000

A: Please try below:
with x as
(select sum((regexp_substr(YOUR_COLUMN, '[0-9]+', 1, 1)*60) +
             regexp_substr(id, '[0-9]+', 1, 2)) seconds
from YOUR_TABLE)
SELECT
    TO_CHAR(TRUNC(seconds/3600),'FM9900') || ':' ||
    TO_CHAR(TRUNC(MOD(seconds,3600)/60),'FM00') || ':' ||
    TO_CHAR(MOD(seconds,60),'FM00')
FROM x

Will work only if the duration is always [MI:SS].
Also you can add the group by as per your requirement.
Converting Seconds to the required duration format Reference.
Group By
with x as
(select calling_number,sum((regexp_substr(YOUR_COLUMN, '[0-9]+', 1, 1)*60) +
             regexp_substr(id, '[0-9]+', 1, 2)) seconds
from YOUR_TABLE
group by calling_number)
SELECT calling_number,
    TO_CHAR(TRUNC(seconds/3600),'FM9900') || ':' ||
    TO_CHAR(TRUNC(MOD(seconds,3600)/60),'FM00') || ':' ||
    TO_CHAR(MOD(seconds,60),'FM00')
FROM x

A: Use a combination of SUBSTR, to_char, to_date, NVL, INSTR, reverse and SUM.
SELECT "calling_number",
to_char(to_date(SUM(NVL(SUBSTR("duration_d", 0, INSTR("duration_d", ':')-1), "duration_d"))*60 +
SUM(substr("duration_d", - instr(reverse("duration_d"), ':') + 1)),'sssss'),'hh24:mi:ss') AS SUM_DURATION_D
FROM yourtable
GROUP BY "calling_number"

Output
calling_number  SUM_DURATION_D
1               00:26:10
2               00:29:03

SQL Fiddle: http://sqlfiddle.com/#!4/9b0a81/33/0

A: Correct spelling as below
SELECT SUM( TO_DATE( duration_d, 'mi:ss' ) )
 FROM YOURTABLE Group By calling_number


Q: PHP:checked attribute in array of checkboxes I have an array like this
$current_asset = [
    ['name'=>'Land,'id'=>1],
    ['name'=>'Building ,'id'=>2],
    ['name'=>'Machinery','id'=>3],
];

<?php
 foreach($current_asset as $key=>$value){ ?>
 <input type="checkbox" name="current_asset[]" value="<?php echo $value['id'] ?>">

 <?php } ?>

My question how can I add checked attribute in if one of the value is checked when the form populated with the POST data
I am getting the checkbox array like this on form submit
Here are the current checkboxes on form submit (ie values of current_asset)
Array(
    0=>1
    1=>1
   )

A: You would need to do some kind of check before printing
$html=‘’;
foreach($current_asset as $asset) {
 if($asset[‘hasBeenCheckedBefore’]) {
  $checked = ‘checked’;
 } else {
  $checked = ‘’;
 }
 $html .= “$asset[‘name’] <input type=‘checkbox’ name=‘current_asset[]’ value=‘$asset[“id”]’ $checked />”;
}

A: Here is an example of one way to do it.  I have changed your data structure to be easier to use. I was confused initially because you didn't mention any way to store data.  So this is only good for the one page view.
<?php

// initialize data

/**
 * Data structure can make the job easy or hard...
 *
 * This is doable with array_search() and array_column(),
 * but your indexes might get all wonky.
 */
$current_asset = [
    ['name'=>'Land','id'=>1],
    ['name'=>'Building' ,'id'=>2],
    ['name'=>'Machinery','id'=>3],
];

/**
 * Could use the key as the ID.  Note that it is being
 * assigned as a string to make it associative.
 */
$current_asset = [
    '1'=>'Land',
    '2'=>'Building',
    '3'=>'Machinery',
];

/**
 * If you have more information, you could include it
 * as an array.  I am using this setup.
 */
$current_asset = [
    '1'=> ['name' => 'Land',      'checked'=>false],
    '2'=> ['name' => 'Building',  'checked'=>false],
    '3'=> ['name' => 'Machinery', 'checked'=>false],
];

// test for post submission, set checked as appropriate
if(array_key_exists('current_asset', $_POST)) {
  foreach($_POST['current_asset'] as $key => $value) {
    if(array_key_exists($key,$current_asset)) {
      $current_asset[$key]['checked'] = true;
    }
  }
}

// begin HTML output
?>
<html>
  <head>
    <title></title>
  </head>
  <body>

    <!-- content .... -->

    <form method="post">
    <?php foreach($current_asset as $key=>$value): ?>
      <?php $checked = $value['checked'] ? ' checked' : ''; ?>
      <label>
        <input type="checkbox" name="current_asset[<?= $key ?>]" value="<?= $key ?>"<?= $checked ?>>
        <?= htmlentities($value['name']) ?>
      </label>
    <?php endforeach; ?>
    </form>

  <body>
</html>


Q: Vbox Parent, Pane Child overlapping other components javafx Hey all I am new to java and javafx trying to learn them. I am currently trying to do a problem where the user inputs values for two circles (the center and radius of circle). It is supposed to then show the circles, and display what they are doing, such as they are equal, one is contained in the other, etc.
To do this I used a vbox, and I am attempting to draw the circles using a pane, and implementing the pane into the vbox.  Here is my code:
 public class Shapes extends Application {

  @Override
  public void start(Stage stage) {

  createTextField();
  VBox root = new VBox();
  root.setSpacing(10);
  Pane pane = new Pane();
  Color blue = new Color(1,0,0,1);
  Color red = new Color(0,0,1,1);
  Circle circle1 = createCircle(50, 50, 50, red);
  Circle circle2 = createCircle(50, 50, 200, blue);
  pane.getChildren().addAll(circle1, circle2);
  root.getChildren().addAll(label0, label1, label2, tField, label3, label4, pane);
  Scene scene = new Scene(root, 1000 , 1000);
  stage.setTitle("Spatial Relations Demo by");
  stage.setScene(scene);
  stage.show();
  }

  public static void main(String[] args) {
  Application.launch(args);
  }

  Label label0, label1, label2, label3, label4;
  TextField tField;

  public void createTextField()
  {
   label0 = new Label();
   label0.setText("Spatial Relations Demo");

   label1 = new Label();
   label1.setText("                              ");
   label1.setTextAlignment(TextAlignment.CENTER);

   label2 = new Label();
   label2.setText("Input Circles: x1 y1 r1 x2 y2 r2 ");
   label2.setTextAlignment(TextAlignment.CENTER);

   label3 = new Label();
   label3.setTextAlignment(TextAlignment.CENTER);

   label4 = new Label();
   label4.setTextAlignment(TextAlignment.CENTER);

  tField = new TextField();
  tField.setOnAction(new TextFieldHandler());
 }

  public class TextFieldHandler implements EventHandler<ActionEvent> {
  public void handle( ActionEvent e)
  {
  String str = tField.getText();
  int x1, y1, r1, x2, y2, r2;

  Scanner scanner = new Scanner(str);
  x1 = scanner.nextInt();
  y1 = scanner.nextInt();
  r1 = scanner.nextInt();

  x2 = scanner.nextInt();
  y2 = scanner.nextInt();
  r2 = scanner.nextInt();

  tField.setText( "" );
  String str1 = str.format("Input is: " + x1 + " " + y1 + " " + r1 + " " + x2 + " " + y2 + " " + r2);
  label3.setText(str1);

 double d = sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));

 if ((x1==x2) & (y1==y2) & (r1==r2))
   label4.setText( " The circles are equal.");
 else if (d >= (r1+r2))
   label4.setText( " The circle interiors are disjoint.");
 else if (d <= (r2-r1))
   label4.setText( " Circle1 is inside Circle2.");
 else if (d <= (r1-r2))
   label4.setText( " Circle2 is inside Circle1.");
 else
   label4.setText( " The circles overlap.");
}
}

 public Circle createCircle(int x, int y, int r, Color color)
  {
    Circle circle = new Circle();
    circle.setRadius(r);
    circle.setCenterX(x);
    circle.setCenterY(y);
    circle.setStroke(color);
    circle.setFill(null);

    return circle;
  }

}

As of right now I just have implemented some test numbers to draw the circles, but I am still trying to figure out how to get the user inputted numbers as my circle parameters. I was not sure how to get the pane to work properly. Any tips or advice would be greatly appreciated thanks! I tried to post an image to show my output but I guess I dont have enough reputation for it. My circles are overlapping everything instead of staying below the labels and textfield. I cant seem to figure out how to keep them below those items in the vbox.

A: Your red circle (the one with the color you called blue ;) ) has bounds that extend into negative coordinate ranges in both x- and y-directions (it has center (50, 50) and radius 200). Hence it extends beyond the bounds of the pane.
If you want to make sure the pane doesn't paint outside of its bounds, you can set a clip that is bound to its size:
    Rectangle clip = new Rectangle(0, 0, 0, 0);
    clip.widthProperty().bind(pane.widthProperty());
    clip.heightProperty().bind(pane.heightProperty());
    pane.setClip(clip);

To update the circles, you just have to make them instance variables instead of local to the start method, and update their centers and radii:
import java.util.Scanner;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.text.TextAlignment;
import javafx.stage.Stage;

public class Shapes extends Application {

    private Label label0, label1, label2, label3, label4;
    private TextField tField;

    private Circle circle1 ;
    private Circle circle2 ;

    @Override
    public void start(Stage stage) {

        createTextField();
        VBox root = new VBox();
        root.setSpacing(10);
        Pane pane = new Pane();
        Color blue = new Color(1, 0, 0, 1);
        Color red = new Color(0, 0, 1, 1);
        circle1 = createCircle(50, 50, 50, red);
        circle2 = createCircle(50, 50, 200, blue);
        pane.getChildren().addAll(circle1, circle2);

        // If desired:

        // Rectangle clip = new Rectangle(0, 0, 0, 0);
        // clip.widthProperty().bind(pane.widthProperty());
        // clip.heightProperty().bind(pane.heightProperty());
        // pane.setClip(clip);

        root.getChildren().addAll(label0, label1, label2, tField, label3,
                label4, pane);
        Scene scene = new Scene(root, 1000, 1000);
        stage.setTitle("Spatial Relations Demo by");
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        Application.launch(args);
    }

    public void createTextField() {
        label0 = new Label();
        label0.setText("Spatial Relations Demo");

        label1 = new Label();
        label1.setText("                              ");
        label1.setTextAlignment(TextAlignment.CENTER);

        label2 = new Label();
        label2.setText("Input Circles: x1 y1 r1 x2 y2 r2 ");
        label2.setTextAlignment(TextAlignment.CENTER);

        label3 = new Label();
        label3.setTextAlignment(TextAlignment.CENTER);

        label4 = new Label();
        label4.setTextAlignment(TextAlignment.CENTER);

        tField = new TextField();
        tField.setOnAction(new TextFieldHandler());
    }

    public class TextFieldHandler implements EventHandler<ActionEvent> {
        @Override
        public void handle(ActionEvent e) {
            String str = tField.getText();
            int x1, y1, r1, x2, y2, r2;

            Scanner scanner = new Scanner(str);
            x1 = scanner.nextInt();
            y1 = scanner.nextInt();
            r1 = scanner.nextInt();

            x2 = scanner.nextInt();
            y2 = scanner.nextInt();
            r2 = scanner.nextInt();

            circle1.setCenterX(x1);
            circle1.setCenterY(y1);
            circle1.setRadius(r1);
            circle2.setCenterX(x2);
            circle2.setCenterY(y2);
            circle2.setRadius(r2);

            tField.setText("");
            String str1 = String.format("Input is: " + x1 + " " + y1 + " " + r1
                    + " " + x2 + " " + y2 + " " + r2);
            label3.setText(str1);

            double d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));

            if ((x1 == x2) & (y1 == y2) & (r1 == r2))
                label4.setText(" The circles are equal.");
            else if (d >= (r1 + r2))
                label4.setText(" The circle interiors are disjoint.");
            else if (d <= (r2 - r1))
                label4.setText(" Circle1 is inside Circle2.");
            else if (d <= (r1 - r2))
                label4.setText(" Circle2 is inside Circle1.");
            else
                label4.setText(" The circles overlap.");

            scanner.close();
        }
    }

    public Circle createCircle(int x, int y, int r, Color color) {
        Circle circle = new Circle();
        circle.setRadius(r);
        circle.setCenterX(x);
        circle.setCenterY(y);
        circle.setStroke(color);
        circle.setFill(null);

        return circle;
    }

}


Q: Getting ongoing recording data segments from AVAudioRecorder My problem is as follows:
I need to capture every 320 bytes of raw audio data.
I do this by using an NSTimer that fires a method every 0.02 seconds - that is because i need to record 8000Hz and 16bit mono audio, and i've calculated that it should be 50x a second (8000 * 16 / 320 / 8).
So, knowing that the AVAudioRecorder saves to a file, i can get every 320 bytes from that file by [[NSData dataWithContentsOfURL:[audioRecorder url]] subdataWithRange:NSMakeRange(bytesUsed, 320)], but the thing that has confused me, is that the moment i start the recording, the data files size is 4096 bytes and then after 0.5 seconds, it's 9424 bytes and increases by around 5,3k bytes every half a second.
So i'm confused if i'm getting the right data and thinking that the settings might be wrong.
Current settings for AVAudioRecorder are:
[NSNumber numberWithInt:kAudioFormatLinearPCM], AVFormatIDKey,
[NSNumber numberWithInt:16], AVLinearPCMBitDepthKey,
[NSNumber numberWithInt:AVAudioQualityMin], AVEncoderAudioQualityKey,
[NSNumber numberWithInt:16], AVEncoderBitRateKey,
[NSNumber numberWithInt: 1], AVNumberOfChannelsKey,
[NSNumber numberWithFloat:8000.0], AVSampleRateKey,

So the main problem is:
What settings should i use?
Is this the right way to go about getting segments from an ongoing audio recording?
I apologize for the bad explanation, do ask questions to help me make it more understandable.


Q: Finding an HTTP bottleneck I'm developing a custom Blog application in Ruby on Rails, having load speed as a primary measure of success.
I'm caching (with Redis) both views and models to shorten up queries and rendering of raw HTML. Finally I succeeded loading a single post in under 15ms. Time to deploy.
I bought a Linode 20$/month machine with 2gb ram, 2 cores, ssd storage, 40gbit in, 250mbit out. The machine is hosted in London. I installed Ubuntu 15.04.
I set up Cloudflare free plan for more aggressive caching and minification of assets. I enabled the Full SSL functionality.
I installed nginx as a proxy to the Rails application running on Unicorn. Rails, Redis, PostgreSQL and nginx run on the same server.
I am in Rome, Italy. The nearest Cloudflare datacenter is in Milan, while the origin Linode server is in London. The average request time (as reported by the chrome network panel) is 230ms. Whops...
So first of all I checked out the Rails logs, and the log reported times (and the X-Runtime header) where consistent with my development data (< 20ms).
I edited nginx configuration to add an X-Time header:
add_header X-Time $request_time;

And that shows just a few ms over the Rails timings.
Then I enabled direct access to the server (disabled Cloudflare) and disabled SSL to remove the handshake overhead.
So I finally found that with or without Cloudflare, with or without SSL, load times where always quite random in the range [180-350]ms, with no apparent explaination.
Here's a shot of the Chrome timing panel, without both Cloudflare and SSL. Just a raw HTTP connection directly on port 80 of the nginx server.

Why am I seeing such high times on a blazing fast application? What should I check next? Is the Linode server my bottleneck?
Thanks
Edit
It looks like gzip compression as enabled by default by nginx was slowing the whole thing down by a 30%. I have now disabled it since Cloudflare will gzip it anyway in a second step. Now request times are between 120 and 200ms but I still feel like it could be improved.


Q: Way to slice a string using 2 variable? I m new to programming and came across a question If I have a string where I have 2 variables indexed.. and need the value from the middle.
for example, my string is HeyEveryoneImtryingtolearnpythonandihavequestion
where I have variables
V1 = 'Imtrying'
V2 = 'andihave'

what can I do to get the "learnpython" substring? or is it not valid?

A: You can use index and slicing:
s = 'HeyEveryoneImtryingtolearnpythonandihavequestion'

v1 = 'Imtrying'
v2 = 'andihave'

start = s.index(v1) + len(v1)
end = s.index(v2, start)

output = s[start:end]
print(output) # tolearnpython

A: You can also use regex:
import re

s = "HeyEveryoneImtryingtolearnpythonandihavequestion"
V1 = 'Imtryingto'
V2 = 'andihave'

a = re.search(f"{re.escape(V1)}(.*?){re.escape(V2)}", s).group(1) # 'learnpython'


Q: Symfony: Overriding Symfony service ( compiler pass ) I'm on symfony 2.7 and need to override Symfony\Component\Asset\UrlPackage
I've looked at http://symfony.com/doc/current/cookbook/bundles/override.html
and http://symfony.com/doc/current/cookbook/service_container/compiler_passes.html
but can't get it working.
I have made a file in my bundle MyApp\CoreBundle\Overrides\UrlPackage;
I registered UrlPackage as a service and added a function:
public function process(ContainerBuilder $container)
{
    $definition = $container->getDefinition('assets.url_package');
    $definition->setClass('MyApp\CoreBundle\Overrides\UrlPackage');
}

The weird thing is, if I call $this->has('assets.url_package') in any controller, it returns false.
I did grab it from the services file under Symfony:
<service id="assets.url_package" class="Symfony\Component\Asset\UrlPackage" abstract="true">
        <argument /> <!-- base URLs -->
        <argument type="service" /> <!-- version strategy -->
        <argument type="service" id="assets.context" />
    </service>

If I run php app/console debug:container, the UrlPackage from symfony isn't in there, but, if I change something inside the vendor/*/UrlPackge file, it does work
Can someone point me in the right direction?

A: Decorating the service is the thing you're looking for:
bar:
    public: false
    class: stdClass
    decorates: foo
    arguments: ["@bar.inner"]

You can inject the original service in your own service, and implement the original interface to make them compatible.
http://symfony.com/doc/2.7/service_container/service_decoration.html

A: Symfony 5.1+
Symfony 5.1+ provide a simpler service decoration:

In previous Symfony versions you needed to use the syntax decorating
service ID + .inner to refer to that service. This quickly becomes
cumbersome in YAML/XML when using PHP classes as service IDs. That's
why in Symfony 5.1 we've simplified this feature to always use .inner
to refer to the original service.
@source: https://symfony.com/blog/new-in-symfony-5-1-simpler-service-decoration

# config/services.yaml

services:
    App\MyService: ~

    # Before
    App\SpecialMyService:
        decorates: App\MyService
        arguments: ['@App\SpecialMyService.inner']

    # After
    App\SpecialMyService:
        decorates: App\MyService
        arguments: ['@.inner'] # <--- the service ID is no longer needed


Q: C++ - Are there ways to get current class type with invariant syntax? I want to write a macro which, when expanded within a class, uses that class type (specifically, as template argument). Within class method, I can use this:
#define METHOD_MACRO int sample_method(void)const {\
    return template_struct<this_type<decltype(this)>::type>::index;}

(this_type is my struct, here it's equivalent to remove_pointer<remove_const<T>>)
But when I need class type outside of method (for typedef for class member pointer), this keyword isn't available; I've tried to use auto for some trick with deducing type, but no luck here.
Classes in question are inherited from my class, if this can be of any help. I would like to avoid anyone using my macro having to write obligatory typdedef.
Any ideas?

A: You can use the following trick:
#define SELF \
    static auto helper() -> std::remove_reference<decltype(*this)>::type; \
    typedef decltype(helper()) self

struct A {
    SELF;
};

I declare a helper function using the auto return type, which allows me to use decltype(*this) as a return type, not knowing what is the class name. Then I can use decltype(helper()) to use the class type in the code. Note that the function has to be static, otherwise you can not use it in decltype. Also the function is just declared, not defined; this should not be a problem as you are not going to call it anyway. (You can add an empty body to it, but it will raise a warning that a function has no return. Still you may change the return type to be decltype(this) and return nullptr.)
You may then use the self typedef for further declarations, or just alter the macros to typedef not the class itself, but what you need to. Adjust it to suit your particular need.
UPD: This seems to be a non-standard behavior of GCC. For example, ICC does not allow this in static functions even in trailing return type.


Q: add icon to wpform submit button hi i want to make the form button same like in the image.
the link of the form is this
http://ministerievanlicht.com/contact/
the code is this that will get the button same to same but it not worked.

.button {
  margin: 0 auto;
  text-decoration:none;
  text-align:center;
  display: flex;
  background: #333333;
  color: white;
  justify-content: space-between;
  align-items: center;
  pointer-events:none;
  max-width:660px;
  border-bottom:solid gray 1px
    font-family: DIN pro;
    font-weight: bold;
}
.button .fa {
  padding:1em;
  pointer-events:auto;
  width:1.5em;
}
.button::before {
  content: '';
  padding: 1em
}

and here is the custom css is this
i want to add icon at the end of the button
div.wpforms-container-full .wpforms-form input[type=date], div.wpforms-container-full .wpforms-form input[type=datetime], div.wpforms-container-full .wpforms-form input[type=datetime-local], div.wpforms-container-full .wpforms-form input[type=email], div.wpforms-container-full .wpforms-form input[type=month], div.wpforms-container-full .wpforms-form input[type=number], div.wpforms-container-full .wpforms-form input[type=password], div.wpforms-container-full .wpforms-form input[type=range], div.wpforms-container-full .wpforms-form input[type=search], div.wpforms-container-full .wpforms-form input[type=tel], div.wpforms-container-full .wpforms-form input[type=text], div.wpforms-container-full .wpforms-form input[type=time], div.wpforms-container-full .wpforms-form input[type=url], div.wpforms-container-full .wpforms-form input[type=week], div.wpforms-container-full .wpforms-form select, div.wpforms-container-full .wpforms-form textarea {
    padding: 18px 0px 18px 26px;
}
div.wpforms-container-full .wpforms-form .wpforms-field-label {
    font-family: 'DIN PRO';
    font-style: normal;
    font-weight: normal;
    font-size: 12px;
    line-height: 24px;
    color: #333333;
    opacity: 1.0;
}
div.wpforms-container div.wpforms-uploader {
    width: 330px;
    height: 193px;
}
div.wpforms-container-full .wpforms-form input[type=checkbox], div.wpforms-container-full .wpforms-form input[type=radio] {
    width: 21px;
    height: 21px;
}
div.wpforms-container-full .wpforms-form input[type=submit], div.wpforms-container-full .wpforms-form button[type=submit], div.wpforms-container-full .wpforms-form .wpforms-page-button {
    background-color: #eee;
    border: 1px solid #ddd;
    color: #333;
    font-size: 1em;
    padding: 10px 330px;
    text-decoration: none;
    text-align: center;
    display: flex;
    background: #333333;
    color: white;
    justify-content: space-between;
    align-items: center;
    pointer-events: none;
        width: 660px;
    height: 55px;
    border-bottom: solid gray 1px; font-family: DIN pro;
    font-weight: bold;
}

A: I have prepared two icon buttons for you. One works with a hover and the other without a hover.

.btn {
  background-color: #333333;
  border: none;
  color: white;
  padding: 12px 16px;
  font-size: 16px;
  cursor: pointer;
  height: 60px;
  margin: 10px;
  position: relative;
  width: 660px;
  border-bottom: solid gray 1px
}

/* Darker background on mouse-over */

.btn:hover {
  background-color: #444444;
}

.btn .ic-line {
  width: 1px;
  height: 60px;
  background: #ddd;
  float: right;
  position: absolute;
  right: 60px;
  top: 0;
}

.fa-custom {
  float: right;
  position: absolute;
  right: 20px;
  top: 22px;
  font-size: 1.1rem;
  color: #fff;
}

.btn .ic-line1 {
  width: 1px;
  height: 60px;
  background: #ddd;
  float: right;
  position: absolute;
  right: 60px;
  top: 0;
  visibility: hidden;
}

.fa-custom1 {
  float: right;
  position: absolute;
  right: 20px;
  top: 22px;
  font-size: 1.1rem;
  visibility: hidden;
  color: #fff;
}

.btn:hover .ic-line1 {
  visibility: visible;
}

.btn:hover .fa-custom1 {
  visibility: visible;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

Icon Buttons

Icon buttons:

<button class="btn">Send</button>

Icon Buttons When hover

Icon buttons:

<button class="btn">Send</button>


Q: How to add my output from a "FOR" Loop and sum together I am a beginner, so I want to ask that how to sum my "FOR" loop value from my input form? and the GrandTotal is used to change it "readonly" textbox in my form.
let grandTotal = 0;
for(let i = 1; i <= 5; ++i) {
  grandTotal += parseInt(document.getElementById("Total" + i).value);
}
grandTotal = document.getElementById("GrandTotal").value;

This is one part of my HTML\

  1
  <input type="text" id="BookTitle" name="BookTitle" size="30" >
  <input type="text" id="Author" name="Author" size="10">
  <select id="Category" name="Category">
    <option value="Please choose the categoty...">Please choose the Category...</option>
    <option value="Business">Business</option>
    <option value="Fiction">Fiction</option>
    <option value="Mathematics">Mathematics</option>
    <option value="Technology">Technology</option>
    </select>
  <input type="text" class="UnitPrice" id="UnitPrice1" name="Unit Price" step="0.01" value="0.00" placeholder="0.00" onkeypress="return forNumberOnly(event)">
  <input type="text" class="Quantity" id="Quantity1" name="Quantity" value="0" min="0" onkeypress="return forNumberOnly(event)">
  <input type="text" id="Total1" name="Total" value="0.00"  readonly>

A: Have a look at this - I use the selector [name=Total] because it makes more sense than [id^=Total]
I delegate the change to the tbody:

document.getElementById("tb").addEventListener("change", function(e) {
  const tgt = e.target;
  const parent = tgt.closest("tr");
  const up  = +parent.querySelector(".UnitPrice").value || 0
  const qty = +parent.querySelector(".Quantity").value || 0
  parent.querySelector("[name=Total]").value = (up * qty).toFixed(2);

  const grandTotal = [...document.querySelectorAll("[name=Total]")] // all total
    .map(ele => +ele.value) // get each value and convert to number
    .reduce((a, b) => a + b); // sum them
  document.getElementById("GrandTotal").value = grandTotal; // assign to a field
})

      1
      <input type="text" id="BookTitle" name="BookTitle" size="30">
      <input type="text" id="Author" name="Author" size="10">

        <select id="Category" name="Category">
          <option value="Please choose the categoty...">Please choose the Category...</option>
          <option value="Business">Business</option>
          <option value="Fiction">Fiction</option>
          <option value="Mathematics">Mathematics</option>
          <option value="Technology">Technology</option>
        </select>

      <input type="text" class="UnitPrice" id="UnitPrice1" name="Unit Price" step="0.01" value="0.00" placeholder="0.00">
      <input type="text" class="Quantity" id="Quantity1" name="Quantity" value="0" min="0">
      <input type="text" id="Total1" name="Total" value="0.00" readonly>

      1
      <input type="text" id="BookTitle" name="BookTitle" size="30">
      <input type="text" id="Author" name="Author" size="10">

        <select id="Category" name="Category">
          <option value="Please choose the categoty...">Please choose the Category...</option>
          <option value="Business">Business</option>
          <option value="Fiction">Fiction</option>
          <option value="Mathematics">Mathematics</option>
          <option value="Technology">Technology</option>
        </select>

      <input type="text" class="UnitPrice" id="UnitPrice2" name="Unit Price" step="0.01" value="0.00" placeholder="0.00" onkeypress="return forNumberOnly(event)">
      <input type="text" class="Quantity" id="Quantity2" name="Quantity" value="0" min="0" onkeypress="return forNumberOnly(event)">
      <input type="text" id="Total2" name="Total" value="0.00" readonly>

<input type="text" readonly id="GrandTotal" />


Q: What should I type in python to open a file located on my desktop when using a Mac? When I opened a .txt file located in a folder called scripts on my h-drive using Windows I typed this:
F = open('h:\\scripts\\data.txt')

I copied the file to a USB drive (n:) and now I want to access this file by using Python on a macbook. I typed this:
P = open('n:\\data.txt')

But I keep getting the following error:
IOError: [Errno 2] No such file or directory: 'data.txt'

So I guess I need to use a different way of specifying pathways to folders when using Python on a Macbook?
Thank you for the replies, sorry for asking the original question without explaining it properly, but as you can tell I am completely new to coding.

A: If by open you mean that you want to get a file() object back, then:
import os
filename = "Your_file.something"
username = os.environ["USER"]
f = open(os.path.join("/Users", username, "Desktop", filename), <mode>)

But there should be a $HOME variable present which will give you the real home folder even if it is not named as the user:
f = open(os.path.join(os.environ["HOME"], "Desktop/Your_file.something"), <mode>)

That is if shell alias for home folder won't work:
f = open("~/Desktop/Your_file.something", <mode>)

BTW, <mode> is of course the mode you wish to open your file in ("r", "w", "rb", "wb", "a", "ab", etc.)


Q: Writing tab spaced words to a file in Python I have a set of words in a file. I want to add a new character separated by tab to all these words and write to a new file.
The code I wrote is
#file to read is opened as ff and file to write is opened as fw.
count = "X"
x = ff.readlines()
for word in x:
     fw.write('%s\t%s'% (word, count))
     fw.write("\n")

The problem is the new word 'X' is not alignment with the existing words. The sample output i am getting is
 A.
      O
 Mahesh
      O
 Anand
      O
 Anton
      O
 Plot

The output I want is:
Original File
word
word2

New File
word    X
word2    X

I want it to be aligned properly

A: readlines() includes the end of line characters:
In [6]: ff.readlines()
Out[6]: ['word1\n', 'word2']

You need to strip them off:
word = word.rstrip()

count = "X"
with open('data', 'r') as ff, open('/tmp/out', 'w') as fw:
    for word in ff:
        word = word.rstrip()  # strip only trailing whitespace
        fw.write("{}\t{}\n".format(word, count))

A: use str.rstrip() as to remove end of line \n.
use context manager with statement to open the file,
and use str.formate to write in file.
with open('out_file.txt') as ff, open('in_file.txt', 'w+') as r:
    for line in ff:
        r.write('{}\t{!r}\n'.format(line.rstrip(), 'X'))
    r.seek(0)
    print r.read()

>>>
   word1    'X'
   word2    'X'
   word3    'X'
   word4    'X'

A: you should remove '\n':
count = "X"
with open('data', 'r') as ff, open('/tmp/out', 'w') as fw:
    for word in ff.readlines():
        print >> fw, '%s\t%s' % (word.rstrip(), count)


Q: Column name checking null still giving null error I want to insert values in a table. So I have written the below code for that.
create or replace PROCEDURE NEIQC_DATA_DUMP_MST AS
BEGIN

execute immediate 'truncate table TBL_NEIQC_WF_SITE_MST_NEW';

INSERT INTO TBL_NEIQC_WF_SITE_MST_NEW

(
    OBJECTID,
    SAP_ID,
    NETWORK_ENTITY_ID    ,
    SITE_NAME            ,
    SITE_ADDRESS         ,
    MAINTENANCEZONE_CODE ,
    INVENTORY_TYPE       ,
    TYPE_NAME            ,
    SITE_STATUS_CODE     ,
    NE_MODIFIED_DATE     ,
    NE_MODIFIED_BY       ,
    --SERVICE_CODE,
    CREATED_DATE         ,
    CREATED_BY           ,
    STRUCTURE_NAME       ,
    RJ_CITY_CODE         ,
    RJ_R4G_STATE_CODE    ,
    RJ_DISTRICT_CODE     ,
    RJ_TALUK_CODE        ,
    RJ_JC_CODE           ,
    RJ_JIOPOINT_SAPCODE  ,
    RJ_COMPANY_CODE_1    ,
    RJ_COMPANY_CODE_2    ,
    PLACEMENT_DATE,
    SITE_TYPE
)

SELECT

    OBJECTID                      ,
    RJ_SAPID ,
    RJ_NETWORK_ENTITY_ID          ,
    RJ_SITE_NAME                  ,
    RJ_SITE_ADDRESS               ,
    RJ_MAINTENANCE_ZONE_CODE      ,
    CASE when RJ_SAPID LIKE '%ENB%' THEN 'SITE' ELSE 'OTHERS' end as INVENTORY_TYPE,
    TYPE_NAME                     ,
    4,
    RJ_LAST_MODIFIED_DATE,
    RJ_LAST_MODIFIED_BY ,
    --APP_FIBERINV.FUNC_SC(RJ_SAPID),
    SYSDATE,
    'SCHEDULER',
    STRUCTURE_NAME                ,
    RJ_CITY_CODE                  ,
    RJ_R4G_STATE_CODE             ,
    RJ_DISTRICT_CODE              ,
    RJ_TALUK_CODE                 ,
    RJ_JC_CODE                    ,
    RJ_JIOPOINT_SAPCODE           ,
    RJ_COMPANY_CODE_1             ,
    RJ_COMPANY_CODE_2          ,
    PLACEMENT_DATE,
    REGEXP_SUBSTR(TO_CHAR(RJ_SAPID),'[^-]+', 1, 4) AS SITE_TYPE

 from APP_FTTX.ne_structures WHERE RJ_SAPID IS NOT NULL OR RJ_SAPID <> 'NA' AND OBJECTID IS NOT NULL;

COMMIT;

END NEIQC_DATA_DUMP_MST;

But the issue is, even after checking the null condition for OBJECTID I am still getting error as

ORA-01400: cannot insert NULL into ("APP_FIBERINV"."TBL_NEIQC_WF_SITE_MST_NEW"."OBJECTID")

Please suggest what may be wrong here.

A: This is probably down to operator precedence; AND has higher precedence than OR. So your condition:
WHERE RJ_SAPID IS NOT NULL OR RJ_SAPID <> 'NA' AND OBJECTID IS NOT NULL

is interpreted as
WHERE RJ_SAPID IS NOT NULL OR (RJ_SAPID <> 'NA' AND OBJECTID IS NOT NULL)

If you have a source row where OBJECTID is null then it will still pass than condition, and fail on insertion, if RJ_SAPID is anything except 'NA', including if that is null.
I believe you want:
WHERE (RJ_SAPID IS NOT NULL OR RJ_SAPID <> 'NA') AND OBJECTID IS NOT NULL

so you need to include those parentheses in your statement.

A: i think your where condition should be improved. add '()' around your or condition
WHERE (RJ_SAPID IS NOT NULL OR RJ_SAPID <> 'NA') AND OBJECTID IS NOT NULL;