text:
Q: Dynamic style listview I'm generating a list view from an ajax call to a web-service.
This is the code:
var ajax = {
parseJSONP:function(result){
    movieInfo.result = result.results;
    $.each(result.results, function(i, row) {

        console.log("Title" + row.title);

        $('#movie-list').append('
`<img src="http://d3gtl9l2a4fn1j.cloudfront.net/t/p/w185'+row.poster_path+'"/>`
' + row.title + '

' + row.vote_average + '/10

');
    });

    $('#movie-list').listview('refresh');
}

};
What I need, is to make to fill the background of the row element and increase the row height by 30%. The problem is that I can't figure a way to insert the css with the list view creation.
Is there a way to do this? I'm new to javascript and jQuery mobile 1.4.3.
Best Regards

A: A few things I notice:

*

*You are calling a jquery selector to get the element with the id of movie-list multiple times because the selector is in a loop. Rather than using jquery to look up the same element over and over again, you should set it into a variable and reuse it!

*You are creating html using string concatenation. While this is usually fine for small amounts of dynamic html, it can very quickly become difficult to maintain. I suggest creating the DOM elements and appending them to each other (without the use of jquery) instead of making a giant html string.

*You're building html in javascript! If at all possible, I would suggest adjusting your API to return the chunk of html that you need and build it server side rather than building it client side. If you build the html server side, then you can take advantage of whatever rendering framework you are using (PHP, Jade, JSF, etc...) and write the html as html.
With those things in mind, setting the background-image style property should work just fine. You may also need to use background-repeat and background-size to get the desired effect.
Here's what I came up with:
var ajax = {
    parseJSONP:function(response){
        var results = response.results;
        movieInfo.result = results;

        var $movieList = $("#movie-list");

        for(var i = 0; i < results.length; i++) {
            var row = results[i];

            console.log("Title: " + row.title);

            var listItem = document.createElement("li");
            var anchor = document.createElement("a");
            var header = document.createElement("h3");
            var paragraph = document.createElement("p");

            anchor.setAttribute("href", "");
            anchor.setAttribute("data-id", row.id);

            header.textContent = row.title;
            paragraph.textContent = row.vote_average + "/10";

            var backgroundImageUrl = "http://d3gtl9l2a4fn1j.cloudfront.net/t/p/w185" + row.poster_path;
            listItem.style.backgroundImage = "url('" + backgroundImageUrl + "')";
            listItem.style.backgroundRepeat = "no-repeat";
            listItem.style.backgroundSize = "cover";

            anchor.appendChild(header);
            anchor.appendChild(paragraph);
            listItem.appendChild(anchor);

            $movieList.append(listItem);
        }

        $movieList.listview('refresh');

        //increases the height of each list item by thirty percent
        $movieList.find("li").each(function(index, element) {
            var $element = $(element);
            $element.css("height", ($element.offset().height * 1.3) + "px");
        });
    }
};

A: Use html append like:
$('#movie-list').append('

' + row.title + '

' + row.vote_average + '/10

');


text:
Q: Delete broken link I need to delete all the content of a folder which may include broken links among others. The folder path is provided by a variable. Problem is that PowerShell fails to remove the broken links.
$folderPath = "C:\folder\"

Attempt 1:
Remove-Item -Force -Recurse -Path $folderPath

Fails with error:
Remove-Item : Could not find a part of the path 'C:\folder\brokenLink'.
At line:1 char:1
+ Remove-Item -Force -Recurse -Path $folderPath
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (C:\folder\brokenLink:String) [Remove-Item], DirectoryNot
   FoundException
    + FullyQualifiedErrorId : RemoveItemIOError,Microsoft.PowerShell.Commands.RemoveItemCommand

Attempt 2:
Start-Job { cmd /c rmdir $folderPath }

Fails because $folderPath gets passed as is instead of its value:
Start-Job { cmd /c rmdir $folderPath } | select command

Command
-------
 cmd /c rmdir $folderPath

Any suggestion besides using the .NET framework?
EDIT
By broken link I'm referring to a folder which points to a previously mounted partition, that doesn't exist anymore. The folder is still available but when attempting to navigate into it this error occurs because the destination doesn't exist anymore:
Error:

C:\folder\brokenLink refers to a location that is unavailable. It
  could be on a hard drive on this computer, or on a network. Check to
  make sure that the disk is properly inserted, or that you are
  connected to the Internet or your network, and then try again. If it
  still cannot be located, the information might have been moved to a
  different location.

A: This will work:
$folderPath = "C:\folderContaingBrokenSymlinks\";
$items = ls $folderPath -Recurse -ea 0;
foreach($item in $items){
    if($item.Attributes.ToString().contains("ReparsePoint")){
        cmd /c rmdir $item.PSPath.replace("Microsoft.PowerShell.Core\FileSystem::","");
    }
    else{
        rm -Force -Recurse $item;
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: When broadcasting in a wireless environment, does the packet spread through the AP? or directly from the device? When broadcasting in a wireless environment, does the packet spread  through the AP? or directly from the device?
I installed an AP that was not connected to the Internet and connected the devices to the AP. And one device sent a broadcast packet.
The broadcast packets were successfully transmitted.
By the way, when I connected the lan line directly to the AP and watched nic with wireshark, I could see that the above packets were caught.
If the device connected to the AP sends a broadcast message, will this message be spilled directly from the device's nic, or is it going through the AP and messaging the AP?

A: Suppose we have a WiFi network with one AP, and two clients (A and B).  If Client A wants to send a packet of any kind to Client B, that traffic goes through the AP first.
The AP is functionally equivalent to an Ethernet switch, where Client A and Client B are connected to different ports, even if they're located in the same room as each other.  The data must flow to the switch first.  There, the switch will inspect the destination MAC address and forward the packet on to whatever port(s) it should go to.
In the WiFi case, the client sends packets to the AP.  The AP inspects the packet and sees that its destined for the BSSID (functionally equivalent to the Ethernet MAC address) of another client.  So, the AP transmits that packet so that the other client can receive it.  If the packet is addressed to something on the connected Ethernet, then the packet goes out as an Ethernet packet.
In the case of a UDP broadcast, the target MAC/BSSID address is FF:FF:FF:FF:FF:FF.  It still goes through the AP though.  The AP receives this packet from Client A and then reransmits it to all clients while also sending it out any connected Ethernet.


text:
Q: How would I update complex object from a single endpoint using REST api? For example I have an object such as
{
    ID: 1000,
    Type: "Ticket",
    "Followers": [
    {
    "UserID": 1200
    },
    {
    "UserID": 1201
    },
    {
    "UserID": 1202
    }]
}

If I wanted to update this object using a new request, how would a list Followers be treated?
For example if a send this update request using PUT, would it mean that there are no changes in Followers, or that Followers is not empty?
{
    ID: 1000,
    Type: "Ticket",
    "Followers": []
}

A: I suppose you are designing the API and you are not referring to an existing API.
First I understood that you are talking about a RESTfull API?
Therefore most of the time you will have an endpoint dedicated to update a specific parameter.
For example to update the followers:
PUT/PATCH /api/ticket/1000/followers

Providing an empty array or null value to this request would then mean that you are removing your followers.
Or you can also implement DELETE HTTP method. The idea would then to use PUT only for an update logic - it will then returning an error if you provide and empty/null value.
In that case the only way to delete the followers will be to use the DELETE HTTP method:
DELETE /api/ticket/1000/followers

But once again it will depends of how you want to implement it and what seems the most usable and logical for you and the end users.
Edit:
Your question was related to the usage of the single endpoint /api/ticket/1000 without sub resources.
Therefore, sending the following object in PUT without providing "Followers" will not change/delete followers.
{
    ID: 1000,
    Type: "Ticket"
}

At the opposite, providing a key for "Followers" in your request will update the value of the followers. In that case it will delete them:
{
    ID: 1000,
    Type: "Ticket",
    "Followers": []
}


text:
Q: Creating a protobuf Enum with Especial characters I need to create an Enum in a proto3 file, and it needs to has the following strings as options:

"0,01_200", "200,01_500", "500,01_1.000", "1.000,01_3.000",
"3.000,01_10.000", 10.000,01_30.000, "30.000,01_100.000"

I tried something like this:
enum enumRangeTransactionCategory {
    0,01_200 = 0;
    200,01_500 = 1;
    500,01_1.000 = 2;
    1.000,01_3.000 = 3;
    3.000,01_10.000 = 4;
    10.000,01_30.000 = 5;
    30.000,01_100.000 = 6;
}

But did not work.
Could anyone help me?

A: Protobuf Enums map constants to (recommended) unsigned ints.
If I understand correctly, you want to be able to receive a float (?) value and map this onto an integer.
Your Protobuf Message should include a field of type float for the incoming value and your code (!) will need to map the ranges onto the integer values (buckets) that you want. Alternatively, your code will need to perform this mapping and use (perhaps) uint32 as the Protobuf Message field value.


text:
Q: HTML with event.preventDefault If the html document is disabled. (no scrolling...)
document.ontouchmove = function(event){ event.preventDefault(); }

Can I selectively enabled elements in the html document? such as a div, span
What javascript should I use to do that?

A: Here's a fairly hacky solution.
Change your touchmove handler as follows:
document.ontouchmove = function (event) {
    if (!event.elementIsEnabled) {
        event.preventDefault();
    }
};

Then for an element that you want to enable:
element.ontouchmove = function (event) {
    event.elementIsEnabled = true;
};

This works because:

*

*When a touchmove event is fired on the element, both of these event handlers handle the event in the bubbling phase. This means that the element touchmove handler fires first, because it is closest to the source of the event.

*When two event handlers handle the same event, they receive the same event object.

*You're allowed to set your own arbitrary properties on an event object.

So, the element touchmove handler just sets a custom property on the event object, and then the document touchmove handler checks for that custom property to determine whether the default action should be prevented.


text:
Q: check for a pre commit hook string , SVN I wanted to check if a string "XYZ" in present in SVN commit message in pre-commit hook. I have tried below code :
setlocal enabledelayedexpansion

set REPOS=%1
set TXN=%2

set SVNLOOK="%VISUALSVN_SERVER%\bin\svnlook.exe"

SET M=

REM Concatenate all the lines in the commit message
FOR /F "usebackq delims==" %%g IN (`%SVNLOOK% log -t %TXN% %REPOS%`) DO SET    M=!M!%%g

if [[ $M == * "XYZ"* ]] then
goto NORMAL_EXIT
else
:ERROR_TOO_SHORT
echo "Commit id missing .Please enter the commit id in the format [XYZ - number]";
goto ERROR_EXIT

:ERROR_EXIT
fi

REM All checks passed, so allow the commit.
:NORMAL_EXIT
exit 0

But when i commit in SVN i am getting $M was unexpected at this time. Where am i going wrong ?
EDIT: it works good for this code only ,
REM Make sure M is defined
SET M=0%M%

REM Here the 6 is the length we require
IF NOT "%M:~6,1%"=="" goto NORMAL_EXIT

:ERROR_TOO_SHORT
echo "Commit note must be at least 6 letters" >&2
goto ERROR_EXIT

:ERROR_EXIT
exit /b 1

If i try to modify this to check string using if..else then it breaks.


text:
Q: MySQL how to reverse where? I have a table like this

id
path

1
/

2
/a/

3
/a/b/

4
/a/b/c/

5
/a/b/c/d

When I use a path (e.g., path = '/a/b/c/') in the where clause, I would like to retrieve the children of this path.
e.g.:
id path

id
path

1
/

2
/a/

3
/a/b/

4
/a/b/c/

how can I achieve this?

A: You could use the instr function
SELECT *
FROM   mytable
WHERE  INSTR('/a/b/c', path) = 1

A: I think you can use LIKE for find child or parent in next way:
-- select childs of /a/b/

select *
from paths
where path like ('/a/b/%');

-- select parents of /a/b/

select *
from paths
where '/a/b/' like concat(path,'%');

Test SQL LIKE online


text:
Q: Can file system driver filters filter operations based on user id? follow up to: Windows Filesystem Minifilter Drivers: can I monitor and prevent FS operations using them?
I'm looking for a method to filter access to certain file system resources.
This includes removable media and non-ntfs file systems - so standard ACL won't work.
from what I read, a files system driver filter might be helpful - but I didn't find a way to get the user id of the initiating user.
Is this possible?
other recommendations \ references to existing tools are also welcome.

A: I am not sure what does "user id" mean. But this might be useful:

*

*When handling IRP_MJ_CREATE look at IrpSp->Parameters.Create.SecurityContext->AccessState.

*ACCESS_STATE contains SecurityDescriptor and SubjectSecurityContext.

*From SubjectSecurityContext you can retrieve PACCESS_TOKEN if you need it (call SeLockSubjectContext and SeQuerySubjectContextToken).

Have a nice day!

A: In most cases obtaining security information (token) of the user that initiated the call is possible, at least for operations such as file open and directory enumeration (and these are main points of filtering when you plan to prevent access of the user to the resource). And then you can cancel or modify request as you need. The only limitation I can think of is when the network redirector accesses the disk on behalf of the remote user impersonated as local system account. But these are border cases that you would need to investigate yourself in your particular task.


text:
Q: JS / Chrome Extension - EventListener & Mutation do not detect changed I am building a chrome extension and need to call a function once changes on the site have been detected. Preferably, I want to keep an eye on changes happening in an <iframe>, but since I cant get it to work I am already happy to fire the code whenever any change is detected.
this is the code in my inject.js file:
// run script when site changes are detected
chrome.storage.local.get("obj", function (res) {
    console.log("setting page data object from listener:");
    console.log(res);

    chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
        findKeyword();
        console.log("Listener onUpdate Executed");
    });

    chrome.tabs.onActivated.addListener(function(tabId, changeInfo, tab) {
        findKeyword();
        console.log("Listener onActivated Executed");
    });

    chrome.tabs.onCreated.addListener(function(tab) {
       findKeyword();
       console.log("Listener onCreated Executed");

    });

    // iFrame Listeners
    var iframe_id = res.obj.iframe_id;
    //var iframe = document.getElementById(res.obj.iframe_id);      // alternative

    $(iframe_id).find("body").on('mouseup', function(event) {
        findKeyword();
        console.log("iFrame Listener - MouseUp");
    });

    $('iframe#com.ihg.crm.web.hotel.Hotel').load(function() {
      findKeyword();
      alert("iFrame Listener - Load");
    });

    iframe_id.contentDocument.body.addEventListener('change', function() {
        findKeyword();
        console.log("iFrame Listener - body changes");
    });

    // MutationObservers
    var dom_observer = new MutationObserver(function(mutation) {
        findKeyword();
        console.log('Mutation observed');
    });

});

In addition, I am recently getting a Error handling response: TypeError: Cannot read property 'onUpdated' of undefined error, which is weird as I am firing the code from my background script, which AFAIK only loads once all content has loaded.
Appreciate any help, thanks.


text:
Q: Load operation failed for query x. the remote server returned an error: notfound I published a silverlight application with wcf ria service to my local host on windows 7 (IIS7).but when i run application in browser ,my silverlight application can not connect to wcf ria service and i receive the following error:

load operation failed for query x. the remote server returned an
  error: notfound

how can i fix this problem?!!!

A: I'd try attaching a debugger to the method you're calling in the service. There is probably some error happening which comes back as NotFound. Also, make sure you've enabled Silverlight debugging in the properties of the website project.

A: Please enter This URL in Browser
"http://Your Site Address/FolderName(s)/MyApp-Web-DishViewDomainService.svc
Service name is  full name of service replace dot with dash
for example if your domainclass is  mynamespace.mydomainclass
service address is mynamespace-mydomainclass.svc
the browser return error causes your problem
if error is not found check web.config setting
otherwise pls write  your problem

A: The 'Not Found' error returned by IIS is something of a misnomer.  Many times it masks over something else that happened and thus hides the true error.
One such instance of this is when the amount of information returned by the query exceeds IIS's limit of how much information it can return (the default for IIS 7 is something like 4 meg).  This will result in the 'Not Found' error.  To diagnose this condition, change your service so that it returns only a single record guaranteed to be less than 4 meg in size.  If this is the case, you can change the IIS default, or change your data load strategy (the latter is preferable).
Other conditions can be diagnosed similarly.

A: a problem is possible to be a number of record and change maxItemsInObjectGraph


text:
Q: how to add audio to the video created from set of images using jcodec I am able to create video with jcodec from set of images with the following but unable to add audio.
public void createVideo()
{
    SequenceEncoder se = null;
    try {
        File dir=new File(Environment.getExternalStorageDirectory()+ "/" + "DCIM/");
     //   if(!video.exists())
     //   {
            File video = File.createTempFile("jcodec_enc",".mp4",dir);
    //    }
        Log.e("Test ","File created");
        se = new SequenceEncoder(video);
        String directoryPath = Environment.getExternalStorageDirectory() /*+ "/" + "DCIM"*/ + "/Test/";
        File directory = new File(directoryPath);
        File[] files = directory.listFiles();

        for (int i = 0;i<files.length; i++) {
            if (!files[i].isDirectory()) {

                if (!files[i].exists())
                    break;
                Bitmap frame = BitmapFactory.decodeFile(files[i]
                        .getAbsolutePath());
                Log.e("Path ",files[i]
                        .getAbsolutePath());
                se.encodeNativeFrame(fromBitmap(Bitmap.createScaledBitmap(frame, 1300, 800, false)));
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        se.finish();
        Log.e("Test ","Finish");
    } catch (IOException e) {
        Log.e("TAG", "IO", e);
    }
}

and in build.gradle
 compile 'org.jcodec:jcodec-android:0.1.9'

what I have tried
private void createFinalVideo() {
    String TAG = "AUDIO_TRACK";
    String outputFile = "";

    try {

        File file = new File(Environment.getExternalStorageDirectory() + File.separator + "final.mp4");
        file.createNewFile();
        outputFile = file.getAbsolutePath();

        MediaExtractor videoExtractor = new MediaExtractor();

        videoExtractor.setDataSource(Environment.getExternalStorageDirectory()
                + File.separator + "testvideo.mp4");
      //  videoExtractor.setDataSource(affd.getFileDescriptor(), affd.getStartOffset(), affd.getLength());
        MediaExtractor audioExtractor = new MediaExtractor();
        final AssetFileDescriptor afd = this.getAssets().openFd("audio.m4a");
        audioExtractor.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
        final AssetFileDescriptor afdd = this.getAssets().openFd("audio.m4a");
      //  audioExtractor.setDataSource(Environment.getExternalStorageDirectory() + File.separator + "test_audio.ogg");

        Log.d(TAG, "Video Extractor Track Count " + videoExtractor.getTrackCount());
        Log.d(TAG, "Audio Extractor Track Count " + audioExtractor.getTrackCount());

        MediaMuxer muxer = new MediaMuxer(outputFile, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);

        videoExtractor.selectTrack(0);
        MediaFormat videoFormat = videoExtractor.getTrackFormat(0);
        int videoTrack = muxer.addTrack(videoFormat);

        audioExtractor.selectTrack(0);
        MediaFormat audioFormat = audioExtractor.getTrackFormat(0);
        int audioTrack = muxer.addTrack(audioFormat);

        Log.d(TAG, "Video Format " + videoFormat.toString());
        Log.d(TAG, "Audio Format " + audioFormat.toString());

        boolean sawEOS = false;
        int frameCount = 0;
        int offset = 100;
        int sampleSize = 256 * 1024;
        ByteBuffer videoBuf = ByteBuffer.allocate(sampleSize);
        ByteBuffer audioBuf = ByteBuffer.allocate(sampleSize);
        MediaCodec.BufferInfo videoBufferInfo = new MediaCodec.BufferInfo();
        MediaCodec.BufferInfo audioBufferInfo = new MediaCodec.BufferInfo();

        videoExtractor.seekTo(0, MediaExtractor.SEEK_TO_CLOSEST_SYNC);
        audioExtractor.seekTo(0, MediaExtractor.SEEK_TO_CLOSEST_SYNC);

        muxer.start();

        while (!sawEOS) {
            videoBufferInfo.offset = offset;
            audioBufferInfo.offset = offset;

            videoBufferInfo.size = videoExtractor.readSampleData(videoBuf, offset);
            audioBufferInfo.size = audioExtractor.readSampleData(audioBuf, offset);

            if (videoBufferInfo.size < 0 || audioBufferInfo.size < 0) {
                Log.d(TAG, "saw input EOS.");
                sawEOS = true;
                videoBufferInfo.size = 0;
                audioBufferInfo.size = 0;
            } else {
                videoBufferInfo.presentationTimeUs = videoExtractor.getSampleTime();
                videoBufferInfo.flags = videoExtractor.getSampleFlags();
                muxer.writeSampleData(videoTrack, videoBuf, videoBufferInfo);
                videoExtractor.advance();

                audioBufferInfo.presentationTimeUs = audioExtractor.getSampleTime();
                audioBufferInfo.flags = audioExtractor.getSampleFlags();
                muxer.writeSampleData(audioTrack, audioBuf, audioBufferInfo);
                audioExtractor.advance();

                frameCount++;

                Log.d(TAG, "Frame (" + frameCount + ") Video PresentationTimeUs:" + videoBufferInfo.presentationTimeUs + " Flags:" + videoBufferInfo.flags + " Size(KB) " + videoBufferInfo.size / 1024);
                Log.d(TAG, "Frame (" + frameCount + ") Audio PresentationTimeUs:" + audioBufferInfo.presentationTimeUs + " Flags:" + audioBufferInfo.flags + " Size(KB) " + audioBufferInfo.size / 1024);

            }
        }
        muxer.stop();
        muxer.release();

    } catch (IOException e) {
        Log.d(TAG, "Mixer Error 1 " + e.getMessage());
    } catch (Exception e) {
        Log.d(TAG, "Mixer Error 2 " + e.getMessage());
    }

    return;
}

With the above code output file is created but audio track was not added. help me to add background audio for the video. all suggestions will be appreciated.

A: Here is the code sample to mux video with audio
    private void muxing(String videopath, String output_path) {

    String outputFile = "";

    try {

        File file = new File(output_path);
        file.createNewFile();
        outputFile = file.getAbsolutePath();
        MediaExtractor videoExtractor = new MediaExtractor();
        //  AssetFileDescriptor afdd = getAssets().openFd("test.3gp");
        videoExtractor.setDataSource(videopath);
        MediaExtractor audioExtractor = new MediaExtractor();
        /*audioExtractor.setDataSource(Environment.getExternalStorageDirectory() + File.separator + "theme.aac");*/
        final AssetFileDescriptor afd = getActivity().getAssets().openFd("themes.aac");
        audioExtractor.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
        Log.d("test", "Video Extractor Track Count " + videoExtractor.getTrackCount());
        Log.d("test", "Audio Extractor Track Count " + audioExtractor.getTrackCount());

        MediaMuxer muxer = new MediaMuxer(outputFile, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);

        videoExtractor.selectTrack(0);
        MediaFormat videoFormat = videoExtractor.getTrackFormat(0);
        int videoTrack = muxer.addTrack(videoFormat);

        audioExtractor.selectTrack(0);
        MediaFormat audioFormat = audioExtractor.getTrackFormat(0);
        int audioTrack = muxer.addTrack(audioFormat);

        Log.d("test", "Video Format " + videoFormat.toString());
        Log.d("test", "Audio Format " + audioFormat.toString());

        boolean sawEOS = false;
        int frameCount = 0;
        int offset = 100;
        int sampleSize = 256 * 1024;
        ByteBuffer videoBuf = ByteBuffer.allocate(sampleSize);
        ByteBuffer audioBuf = ByteBuffer.allocate(sampleSize);
        MediaCodec.BufferInfo videoBufferInfo = new MediaCodec.BufferInfo();
        MediaCodec.BufferInfo audioBufferInfo = new MediaCodec.BufferInfo();

        videoExtractor.seekTo(0, MediaExtractor.SEEK_TO_CLOSEST_SYNC);
        audioExtractor.seekTo(0, MediaExtractor.SEEK_TO_CLOSEST_SYNC);

        muxer.start();

        while (!sawEOS) {
            videoBufferInfo.offset = offset;
            videoBufferInfo.size = videoExtractor.readSampleData(videoBuf, offset);

            if (videoBufferInfo.size < 0 || audioBufferInfo.size < 0) {
                Log.d("test", "saw input EOS.");
                sawEOS = true;
                videoBufferInfo.size = 0;

            } else {
                videoBufferInfo.presentationTimeUs = videoExtractor.getSampleTime();
                videoBufferInfo.flags = videoExtractor.getSampleFlags();
                //   videoBufferInfo.flags =MediaCodec.BUFFER_FLAG_SYNC_FRAME;
                muxer.writeSampleData(videoTrack, videoBuf, videoBufferInfo);
                videoExtractor.advance();

                frameCount++;
                Log.d("test", "Frame (" + frameCount + ") Video PresentationTimeUs:" + videoBufferInfo.presentationTimeUs + " Flags:" + videoBufferInfo.flags + " Size(KB) " + videoBufferInfo.size / 1024);
                Log.d("test", "Frame (" + frameCount + ") Audio PresentationTimeUs:" + audioBufferInfo.presentationTimeUs + " Flags:" + audioBufferInfo.flags + " Size(KB) " + audioBufferInfo.size / 1024);

            }
        }

        //     Toast.makeText(getApplicationContext(), "frame:" + frameCount, Toast.LENGTH_SHORT).show();

        boolean sawEOS2 = false;
        int frameCount2 = 0;
        while (!sawEOS2) {
            frameCount2++;

            audioBufferInfo.offset = offset;
            audioBufferInfo.size = audioExtractor.readSampleData(audioBuf, offset);

            if (videoBufferInfo.size < 0 || audioBufferInfo.size < 0) {
                Log.d("test", "saw input EOS.");
                sawEOS2 = true;
                audioBufferInfo.size = 0;
            } else {
              //  audioBufferInfo.presentationTimeUs = audioExtractor.getSampleTime();
                audioBufferInfo.presentationTimeUs = 30;
                audioBufferInfo.flags = audioExtractor.getSampleFlags();
                muxer.writeSampleData(audioTrack, audioBuf, audioBufferInfo);
                audioExtractor.advance();

                Log.d("test", "Frame (" + frameCount + ") Video PresentationTimeUs:" + videoBufferInfo.presentationTimeUs + " Flags:" + videoBufferInfo.flags + " Size(KB) " + videoBufferInfo.size / 1024);
                Log.d("test", "Frame (" + frameCount + ") Audio PresentationTimeUs:" + audioBufferInfo.presentationTimeUs + " Flags:" + audioBufferInfo.flags + " Size(KB) " + audioBufferInfo.size / 1024);

            }
        }

        //     Toast.makeText(getApplicationContext(), "frame:" + frameCount2, Toast.LENGTH_SHORT).show();

        muxer.stop();
        muxer.release();
        if (new File(videopath).exists()) {
            new File(videopath).delete();
        }

    } catch (IOException e) {
        Log.d("test", "Mixer Error 1 " + e.getMessage());
    } catch (Exception e) {
        Log.d("test", "Mixer Error 2 " + e.getMessage());
    }
}

A: this code is for converting series of images into video file.
    private void createVideoFromImages(final HashMap<String, String> paths) {
    final class ProcessTask extends AsyncTask<Void, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            cpb_ScanningMediaProgressBar.setVisibility(View.VISIBLE);
            rv_IndividualMediaView.setVisibility(View.GONE);
        }

        @Override
        protected String doInBackground(Void... params) {
            Calendar c = Calendar.getInstance();
            int seconds = c.get(Calendar.SECOND);
            String out_path = Environment.getExternalStorageDirectory() + File.separator + "DCIM/" + "SM_" + seconds + ".mp4";
            MySequenceEncoder se = null;
            DateFormat df = new SimpleDateFormat("MMMM d, yyyy HH:mm:ss aaa");
            String currentDateTimeString = df.format(new Date());
            ArrayList<MediaDetails> mediaDetailsList = new ArrayList<>();
            ArrayList<File> files = new ArrayList<>();
            File dir = new File(Environment.getExternalStorageDirectory() + "/" /*+ "Smart_Gallery/"*/);
            File video = null;
            try {

                video = File.createTempFile("temp", ".mp4", dir);

                Log.e("Test ", "File created");
                se = new MySequenceEncoder(video);
                for (Map.Entry<String, String> stringEntry : paths.entrySet()) {
                    File file_item = new File(stringEntry.getKey());
                    if (!file_item.isDirectory()) {
                        try {
                        if (!file_item.exists())
                            break;
                        Bitmap frame = BitmapFactory.decodeFile(file_item
                                .getAbsolutePath());
                         Log.e("Path ", file_item
                                .getAbsolutePath());
                        se.encodeNativeFrame(fromBitmap(Bitmap.createScaledBitmap(frame, 1300, 800, false)));
                        //   se.encodeNativeFrame(fromBitmap(Bitmap.createScaledBitmap(frame, frame.getWidth(), frame.getHeight(), false)));

                           // Thread.sleep(1000);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
                se.finish();
                if (video.exists()) {
                    muxing(video.getAbsolutePath(), out_path);
                }
                Log.e("Test ", "Finish");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return out_path;
        }

        protected void onPostExecute(String videopath) {
            cpb_ScanningMediaProgressBar.setVisibility(View.GONE);
            if (getActivity() != null) {
                ToastUtil.showToast(getActivity(), "Video saved in " + videopath);
                ((MainActivity) getActivity()).loadFragment(new TopTabsFragment(), "tabpager");
                ((MainActivity) getActivity()).makeDefaultPreference(2);
                ((MainActivity) getActivity()).refreshEntireGallery();
               /* if(videofile.exists()) {
                    Calendar c = Calendar.getInstance();
                    int seconds = c.get(Calendar.SECOND);
                    String out_path = Environment.getExternalStorageDirectory() + File.separator + "DCIM/" + "SM_" + seconds + ".mp4";
                    muxing(videofile.getAbsolutePath(), out_path);

                }
            }else
            {
                Log.e("Create Video","file doesnot exist");
            }*/
            }
        }
    }
    new ProcessTask().execute();

}


text:
Q: Div background color, to change onhover slowly I'm trying to make a div's background color change on mouse over. I wanna make background like this spnashot
and i am using this code on hover. I also wanna that when mouse over then color will change slowly

.header_col a:hover{
  background: -webkit-repeating-linear-gradient(#74ABDD, #74ABDD 49.9%, #498DCB 50.1%, #498DCB 100%);
  background: -o-repeating-linear-gradient(#74ABDD, #74ABDD 49.9%, #498DCB 50.1%, #498DCB 100%);
  background: -moz-repeating-linear-gradient(#74ABDD, #74ABDD 49.9%, #498DCB 50.1%, #498DCB 100%);
  background: repeating-linear-gradient(#74ABDD, #74ABDD 49.9%, #498DCB 50.1%, #498DCB 100%);
  color: white!important;
}

A: Hope this code will work

.header_col li {
  display:inline-block;
  transition: background 0.2s;
  transform: skew(20deg);  /* SKEW */

}
.header_col li a {
  display:block;
  text-decoration:none;
  color: black!important;
  transform: skew(-20deg); /* INVERSE SKEW */

}
.header_col li:hover{
  background: -webkit-repeating-linear-gradient(#74ABDD, #74ABDD 49.9%, #498DCB 50.1%, #498DCB 100%);
  background: -o-repeating-linear-gradient(#74ABDD, #74ABDD 49.9%, #498DCB 50.1%, #498DCB 100%);
  background: -moz-repeating-linear-gradient(#74ABDD, #74ABDD 49.9%, #498DCB 50.1%, #498DCB 100%);
  background: repeating-linear-gradient(#74ABDD, #74ABDD 49.9%, #498DCB 50.1%, #498DCB 100%);
  color: white!important;
}
.header_col li a:hover{
   color: white!important;
}

Page 1

Page 2

Page 3

Page 4

Page 5

A: You don't need gradients for that, check this example:
Edit: Now works with text.

    .button {
        position: relative;
        width: 100%;
        height: 100%;
        top: 0;
        z-index: -1;
        transform: skewX(30deg);
    }

    .button::after {
        content: "";
        position: absolute;
        bottom: 0;
        width: 100%;
        height: 50%;
        background-color: rgba(63, 142, 191,1);
    }

    .button::before {
        content: "";
        position: absolute;
        top: 0;
        width: 100%;
        height: 50%;
        background-color: rgba(63, 142, 191,1);
        transition: all .7s;
    }

    .wrapper:hover .button:before {
        background-color: rgba(63, 142, 191, .5);
    }

    a {
        text-align: center;
        width: 100%;
        left: 0;
        right: 0;
        height: 100%;
        width: 100%;
        position: absolute;
        margin: 0;
        display:flex;
        justify-content: center;
        align-items: center;

    }

    .wrapper {
        position: absolute;
        width: 200px;
        height: 80px;
        z-index: 9;
        left: 0;
        right: 0;
        margin: auto;
    }

    Text

A: To change the color on hover you may try like this
a{
    transition-duration: 0.8s;
    transition-delay: 0.5s;
    transition-property: color;
}

first, define these codes in "a" tag then give the hover effect
transition-property has defined the property you want to animate or move.


text:
Q: how to select the correct buttons in tic tac toe game I have a method which tries to determine a AI's move in tic tac toe. Currently I have a method where the computer selects a button randomly but I want it to be a little bit smarter. I have an idea on how to do this but need a little guidence in implementation.
Basically I want the computer to know that if there is either a posibility or win or lose then it will place their counter on the square which will help them win or prevent the player from winning. Here is an example using a grid of coordinates for a 3x3 tic tac toe board:
00 01 02
10 11 12  -- coordinates of all of the buttons in a tic tac toe board
20 21 22

if 00 is not empty and 01 is same as 00, then place 'O' on 02 -- helps win or prevent a win for 3 in a row
if 01 is not empty and 02 is same as 01, then place 'O' on 00 -- helps win or prevent a win for 3 in a row
if 01 is not empty and 21 is same as 01, then place 'O' on 11 -- helps win or prevent a win for 3 in a column
if 20 is not empty and 02 is same as 20, then place 'O' on 11 -- helps win or prevent a win for 3 in a diaganol

As you can tell there are many more scenarios but the main aim is if there is a chance to win or chance to prevent a win then the computer will need to place their 'O'. If the condition doesn't meet then basically select a random button.
So I know I need a bunch of else if but how can this be implemented to do what it needs to do?
Below is a skeleton of what I am trying to do to prevent win/win for 3 in a row for rows and selecting any random button if any of the above conditions do not match:
private void computerMove() {
    String[][] field = new String[3][3];
    Random random = new Random(); //you may want to declare this as a class field
    List<Button> emptyButtons = new ArrayList<>();

    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            field[i][j] = buttons[i][j].getText().toString();
            if (field[i][j].equals("")) {
                emptyButtons.add(buttons[i][j]);
            }
        }
    }

    Button selectButton;

    for (int i = 0; i < 3; i++) {
        if (field[i][0].equals(field[i][1])
                && field[i][2].equals("")){
            //prevent win/win on rows by selecting the correct button here
        }
        else if (field[i][0].equals(field[i][2])
                && field[i][1].equals("")){
             //prevent win/win on rows by selecting the correct button here
        }
        else if (field[i][1].equals(field[i][2])
                && field[i][0].equals("")){
            //prevent win/win on rows by selecting the correct button here
        }
        else {
            selectButton = emptyButtons.get(random.nextInt(emptyButtons.size()));
        }

    selectButton.setText("O");
    selectButton.setTextColor(playerO);
    turnsCount++;
    isGameOver();

}

A: To avoid long if-else statements you could represent the 'O's and 'X's using integers, so that the sum of any combination would be unique.
E.g., if '0' was 1 and 'X' was 10, given:
         | 11
         |----
X  X  .  | 20
O  X  O  | 12
O  O  .  | 2
---------|----
12 21  1 | 20

That is, the columns would sum to: 12, 21, 1,
and the rows would sum to: 20, 12, 2.
The diagonals sum to: 20, 11.
Using this summing method you can calculate if either player has a 1 move win.

*

*If sum == 20, 'X' can win by placing a piece on the zero-valued index of that row/column/diagonal.

*If sum == 2, O can win by placing a piece on the zero-valued index of that row/column/diagonal.
To get the diagonal sums, simply sum the indices where i==j.
Edit: i==j gives you one diagonal. In the general case, the other is given traversing the indices of the two loops (row vs column) in reverse order. Or for a 3x3 game, is just (1,3), (2,2), (3,1).

A: A tic tac toe game has 8 possible winning position (3 rows, 3 columns and 2 diagonals).
Store point for computer referring the row, column or diagonal

100 for 3 in row
10 for 2 in a row (with a empty cell)
1 for 1 in a row (with two empty cell)

now you have enough data to ensure next best possible move.

NOTE: You can also use Minimax with Alpha-beta Pruning Technique.


text:
Q: Shared memory multiprocesses I'm building an multi processes application and I need to save session ID, the sessions ID is 32 bit, and of course it can't be used twice in its lifetime, I'm currently using DB that saves all the ID in a table, and I do the following,
ID table is (int key, char used(1)) //1 is used, 0 is not
1. lock table
2. get one key for one sessions
3. update used field in it to used
4. unlock
After the session is finished the process use below to free key,
1. lock table
2. update used field in it to not used
4. unlock
I'm really wondering whether this is a good/fast implementation. and please note it's multi processes application.

A: Did you try memcached? It's fast, it has atomic updates, it does not have all the rest of database overhead. Not as fast as raw shared memory, but probably session registration is not your bottleneck anyway?

A: By definition database access is no the fastest repository. I need more details about the process to tell you something more useful, but keep in mind that using a database to do what you want is the simplest way but not the fastest. This link shows how Voltdb generates its unique transaction ID in a distributed environment : http://voltdb.com/company/blog/lifecycle-transaction.


text:
Q: How do you connect your application framework (Django/Rails, etc.) to a back-end written in some other language? If there are parts of my application which are very memory intensive and algorithmic, I would want to implement these in C or Java. What would be the best way to connect this code to my Django/(Rails, Merb etc.) web application?

A: Have you tried finding/writing a message/instruction queue processing interface for your C/Java code? That way you can pass jobs from your webapp to the message/instruction queue, where your C/Java code would pick up messages, and process them.
For Django, you have the option of using something like Celery.

A: For Python talking to C/C++, you can use:
Extending Python with C or C++
Boost
The idea in the above 2 solutions is that you will write your memory intensive code in C/C++ and then invoke them from within Python.

A: It depends on how you want to interact with it and what you are most comfortable with. I usually wrap the functionality up in a nice HTTP interface so I can access it from Python (or any other language). Pretty much every language has HTTP libraries and it's pretty easy to make a small REST API. Once it's available over HTTP, it also allows you to use standard HTTP tools for debugging, caching, and load-balancing. For heavier duty processing that can benefit from a queue, Celery/RabbitMQ are powerful and RabbitMQ can be interfaced with from quite a few languages. ZeroMQ can also be a very flexible and lightweight approach.
As an aside, if you the algorithmically intense parts of your application can be formulated into vector operations, check out NumPy. You may not have to leave Python


text:
Q: Program a system with C++ My question is simple because I am a beginner, so Can I program a full computer system with only using C++ language?
Thanks.

A: No you cannot.
You need low-level services which are not standardized within programming languages. For example, you need system port and DMA IO, that basically look different on all platforms. This is usually done by inline assembly code on the lowest level, though some C++ compilers will provide you with special keywords to access CPU features such as registers and special opcodes. For instance, in MS VC++ you have _EAX pseudo-variable to access the EAX CPU register.

A: Well ... Typically you will need at least some assembly at the very lowest levels, for machine-dependent initialization and so on.
So "no" strictly speaking, but that can really be a very small proportion, making the real answer "yes".
BeOS is an example of an operating system written in C++.

A: You will need some assembly. This is becaused there are some privileged instructions that are needed for operating system design that will not be generated by a C/C++ compiler.
One example is when userside code want to make use of an operating system service (like interprocess communication) it needs to switch from user mode into kernel mode. This is normally done by issuing a Software Interrupt (SWI). A C++ will never create the SWI instruction.
Similarly, when writing an arbitrary precision integer arithmatic library, one will need to find of the value of the Carry Bit. There is no C/C++ operator that can do this for you. You will have to use assembler.
Incidentation, writing directly to a device register can and often is done in C. the volatile keyword is placed into the language specifically for registers whose values can change unexpectedly

A: Yes. C++ is Turing Complete... So is Excel, which a clever dude discovered while implementing a realtime 3D engine.

A: Simply, yes you can.

A: You can write all possible programs in C++. In fact, you can write most programs in most languages, especially if you exclude performance concerns. This concept is known as "Turing completeness"

A: You may be interested in this book. It explains how computers work, going from the lowest hardware level to a code.
Cannot recommend it enough!
http://ecx.images-amazon.com/images/I/31VTerGLfML._BO2,204,203,200_PIsitb-sticker-arrow-click,TopRight,35,-76_AA240_SH20_OU01_.jpg

A: You could program a complete OS in C++ if you were so inclined (and had a decade or so to spare....) since it does compile to machine code.
It's probably not a 'beginner' task though, and to be honest, plain old C would be a better choice for system level stuff (both the Windows and Linux kernels use C).


text:
Q: Nginx appends html at the end of javascript taken from Tomcat I have a strange problem with a web application running in Tomcat as a deployable.
The html that user gets when finally being on https://my-url.com/admin
tried to fetch multiple resources from the application deployed to Tomcat.
Now if the FIRST request to Tomcat is made via Nginx, one of the Javascript files fetched will have a
<title>301 Moved Permanently</title>
301 Moved Permanently

nginx/1.12.2;

appended at the very end of the file. This breaks the whole page as we are quite reliant on Javascript. But if I would now restart Tomcat and make the first request straight against the application without going though Nginx, this line will not be appended. All requests afterwards will work as intended even though Nginx.
Here is the nginx conf:
user              nginx  nginx;

worker_processes  2;

pid        /var/run/nginx.pid;

worker_rlimit_nofile 1024;

events {
        worker_connections 512;
}

http {

        include /etc/nginx/mime.types;
        default_type application/octet-stream;
        sendfile "on";
        client_max_body_size 20m;
        client_body_timeout 300s;
        client_body_in_file_only clean;
        client_body_buffer_size 16K;
        client_body_temp_path /tmp/client_body_temp;
        log_format  main  '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"';
        keepalive_timeout  65;
        gzip  on;
        gzip_vary on;
        gzip_proxied any;
        gzip_comp_level 6;
        gzip_buffers 16 8k;
        gzip_http_version 1.1;
        gzip_min_length 256;
        gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;

        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;
}

server {
  listen 443 ssl;

  ssl_certificate      /etc/ssl/certs/name.crt;
  ssl_certificate_key  /etc/ssl/private/name.key;
  ssl_session_cache shared:SSL:1m;
  ssl_prefer_server_ciphers   on;

  server_name my-url.com;

  location / {
    return 301 https://$host/admin$request_uri;
  }

  location /admin {
    proxy_set_header    Host $host;
    proxy_set_header    X-Forwarded-Host $host;
    proxy_set_header    X-Forwarded-Server $host;
    proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header    X-Forwarded-Proto $http_x_forwarded_proto;
    proxy_pass          http://127.0.0.1:8080/admin/;
    proxy_redirect      http://127.0.0.1:8080/admin/ /admin/;
  }
}

server {
    listen 80;
    server_name my-url.com;
    access_log /dev/null;
    return 301 https://$host$request_uri;
}

Would anyone have some idea on what is going on here that causes such issue?


text:
Q: Proving the difference between upper and lower Darboux sums and the integral is less than the oscillation I have the following question, I'm stuck on:
Let $f$ be Riemann integradable on $[a,b]$ then prove that:
1. $|U(P,f) - \int_a^b{f(x)}dx|\leq\Omega(P,f)$
2. $|L(P,f) - \int_a^b{f(x)}dx|\leq\Omega(P,f)$
Where $U$,$L$ are the Darboux upper and lower sums, and $\Omega$ is the oscillation of $f$ relative to partition $P$
I would appreciate any hints or directions since I'm stuck.. Thank you.

A: Note that $U(f,P) - L(f,P) \le \Omega(f,P)$ and
$U(f,P) \ge \int f \ge L(f,P)$.


text:
Q: Посчитать статистику Есть таблицы articles(id, section_id) и sections(id) связанные соответственно связью один ко многим (одна секция имеет много статей). Я хочу узнать сколько минимально, в среднем и максимально статей во всех секциях. Не доводилось делать таких агрегирующих запросов с MIN, MAX, AVG... Помогите пожалуйста составить запрос!

A: В первую очередь придётся посчитать статьи:
SELECT COUNT(a.id)
FROM Articles a
GROUP BY a.section_id

Из этого можно получить агрегаты:
SELECT min(agg.cnt) mincnt, max(agg.cnt) maxcnt, avg(agg.cnt) avgcnt
FROM (
  SELECT COUNT(a.id) cnt
  FROM Articles a
  GROUP BY a.section_id
) agg


text:
Q: generate temporary filename with .ico extension on windows I wish to generate a temporary filename that ends with the extension .ico using the windows C API.
I have tried using GetTempFileName but then I cannot control the extension.

A: The only reasons why you'd want to use GetTempFileName is, because it guarantees to produce a unique file name. Appending an arbitrary extension breaks that invariant, so that is not a solution.
So you need a solution that produces a unique file name. Using the string representation of a GUID is a common way to get that:
std::wstring GetUniqueFileName( const std::wstring& extension = std::wstring() ) {
    GUID guid{ 0 };
    _com_util::CheckError( ::CoCreateGuid( &guid ) );
    wchar_t buffer[39];
    if ( !::StringFromGUID2( guid, buffer, sizeof( buffer ) / sizeof( *buffer ) ) ) {
        throw std::runtime_error( "StringFromGUID2() failed." );
    }
    std::wstring retVal{ buffer };
    retVal += extension;
    return retVal;
}


text:
Q: Find min value in 2d array with MPI Recently began to study MPI technology
The task is to find the minimum value in the matrix.
Search itself parallelize for faster work.
But I can't put my mind to how to make a parallel version from the sequential version of the program
I ask for help
#include <stdio.h>
#include "mpi.h"
#include <stdio.h>
#include <stdlib.h>
int main(int argc,char *argv[])
{
int rows, cols, min, value, n;
int done = 0, numprocs, rank, i, j;
srand(time(NULL));
double startwtime = 0.0, endwtime;
int namelen;
char processor_name[MPI_MAX_PROCESSOR_NAME];
MPI_Init(&argc,&argv);
MPI_Comm_size(MPI_COMM_WORLD,&numprocs);
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
MPI_Get_processor_name(processor_name,&namelen);
    while (!done) {
    if (rank == 0) {
        printf("Enter the height/width of the matrix\n");
        scanf("%d",&rows);
        scanf("%d",&cols);
        startwtime = MPI_Wtime();
    }
    if (rows == 0 || cols == 0) {
        done = 1;
    } else {
        int **arr = (int **) malloc(rows * sizeof(int*));    //creating 2d array
            for (i = 0; i < rows; i++) {
                arr[i] = (int *) malloc(cols * sizeof(int));
        }
        for (i = 0; i < rows; i++) {         //Array filling
            for (j = 0; j < cols; j++) {
                arr[i][j] = rand();
            }
        }
        for (i = 0; i < rows; i++) {      // output of the array to the screen for clarity
            for (j = 0; j < cols; j++) {
                printf("%d\n",arr[i][j]);
            }
        }
        min = arr[0][0];
        for (i = 0; i < rows; i++) {                              //find min value
            for (j = 0; j < cols; j++) {                          //
                if(min > arr[i][j]){min = arr[i][j];}         //need to parallize
            }
        }
        if (rank == 0) {
            endwtime = MPI_Wtime();
            printf("min = %d\n", min);
            printf("wall clock time = %f\n", endwtime-startwtime);
            fflush( stdout );
            for(i = 0; i < rows; i++) {
                    free(arr[i]);
            }
            free(arr);
        }
    }
}
MPI_Finalize();
return 0;
}

Sorry for my bad English
I am hope for your help
UPD: Added a similar function, but the program gives out garbage. It seems to me that this is due to the creation of an array based on pointers. And most likely I misused the functions
        MPI_Scatter (&arr[0][0], rows*cols/numprocs, MPI_INT, &arr[rows][cols], rows*cols/numprocs, MPI_INT, 0, MPI_COMM_WORLD);
        min = arr[0][0];
        for (i = 0; i < rows; i++) {
            for (j = 0; j < cols; j++) {
                min = arr[i][j];
            }
        }
        MPI_Reduce(&min, &value, rows*cols/numprocs, MPI_INT, MPI_MIN, 0, MPI_COMM_WORLD);


text:
Q: Wordpress Custom Query 'no database selected' after upgrading to 4.3.1 latest version
Upgraded word press version to latest version 4.3.1 and custom queries
  are not working into word press Upgrade. It's give message like "no
  database selected".

All the database details in wp-config.php are correct and working fine before up grade. following custom query which is gives message to me after upgrading to 4.3.1 latest version.

Please help to fixing it.
$sql = "select Country_Id, Country_Code,Country_Name from mopt_country where IsActive=1 order by Country_Name ASC";

$result = mysql_query($sql) or die(mysql_error());

A: Can you use mysqli which is safer and not deprecated like mysql function?
I had some connection problem when I used the mysql function. Dunno why honestly.
here is a sample code
    $mysqli = @new mysqli($DBServer, $DBUser, $DBPass, $DBName);
    if(!mysqli_connect_errno())
    {
        mysqli_set_charset($mysqli,"utf8");

        $sql = "
                SELECT param1,...,param9
                FROM Table
                ";

        if($stmt = $mysqli->prepare($sql))
            {
                $stmt->execute();
                $stmt->bind_result($param1,...,$param9);
                while ($stmt->fetch())
                {
                    //your code
                }
            }
        $mysqli->close();
    }
    else
    {
        echo 'Unable to connect';
        exit();
    }

Post your results after it.
Also, as I have already said in my comments, a no db problem is a no db problem. Double check your creditians (user, pass, dbname).
It seems logic after the upgrade, WP add any extra column or delete any column, but it doesn't logic to change your db name.
Edited:
Probably, this is the reason that you have that error:
check that link: Why shouldn't I use mysql_* functions in PHP?
As you can see, Quentin says that :

*

*The "new" password authentication method (on by default in MySQL 5.6;
  required in 5.7)

*All of the functionality in MySQL 5.1


text:
Q: Swift Error when calling selectRowAtIndexPath on tableview I am trying to programmatically select a cell in a tableview.  I get a SIGABORT error when hitting the selectRowAtIndexPath.  myIndex has a value of 1.  I am calling this from a viewController that has implemented the required tableview delegate and datasource methods.
override func viewDidAppear(animated: Bool) {
    if myIndex != nil {
        self.myTableView.selectRowAtIndexPath(NSIndexPath(index: myIndex), animated: false, scrollPosition: UITableViewScrollPosition.Middle)
    }
}

A: Pay attention to error messages in console - they are very helpful most of the times. When you run your code you'll see message:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid index path for
  use with UITableView.  Index paths passed to table view must contain
  exactly two indices specifying the section and row.  Please use the
  category on NSIndexPath in UITableView.h if possible.

Which describes both what the problem is and how to fix it - you should use different initializer for NSIndexPath
self.myTableView.selectRowAtIndexPath(NSIndexPath(forRow: 1, inSection: 0), animated: false, scrollPosition: .Middle)

A: selectRowAtIndexPath will want an indexPath with row and section. Not just an index.


text:
Q: Tortoise SVN - Can't connect to SVN "target machine activity refused it" I'm on a network at a major bank and I'm trying to connect to a SVN repository from my Windows 7 machine.  I'm using the latest version of Tortoise (as of yesterday) 64 bit client.
When I try and connect using repo-browser, I am able to log in with my credentials, but I then get the error, "No connection could be made because the target machine actively refused it."
Other people in my network are able to connect to the repository.  Someone else out out of the network was able to log on to the repository using my credentials.  I also tried to use superuser credentials to log on and got the same error.
I disabled my virus protection software and still got the same results.
I tried accessing from the command line and still got the same results.
I'm sure it's the way my machine or my network is configured, but I am not a network person, so I don't know how to troubleshoot this issue.

A: It was a proxy issue. I entered in the right proxy information and voila! I was granted access.

A: I know this question is old, but something for people to consider as well; make sure that whatever webserver you are running is actually running.  That may sound obvious, but I was using VisualSVN (which basically has its own Apache webserver built in) and it had stopped the service after a reboot.  Check this first before messing about with proxy settings.

A: Check The proxy definitions in the servers file located at C:\Users\XXX\AppData\Roaming\Subversion.
I removed the Proxy lines:
ssl-trust-default-ca  = no
http-proxy-host =
http-proxy-username =
http-proxy-password =

And it works!

A: If you are using Redmine, your URL for the repository is wrong. You will need to use the URL that can be found in the Project in Settings->Repositories. Here is the screenshot:

A: In my case when you copy URL from server repository it contains localhost path.
something like http://xxxx-xxx-xx-xx:portnumber/svn/MyRepository/
if you install SVN on server and try above path then it will show the required output, i.e. folder structure of your repository.
But when you try to access it form remote computer you need to replace all the things after http:// and before port number colon by your sever IP.
It will look like http://myserverip:myport/svn/MyRepository/
Also check windows firewall port is opened or not which you are accessing.

A: this fixed with relocating to the right branch
TortiseSVN >>relocate then put ur correct URL


text:
Q: Archiving MSSQL Database and Retrieving the archived data for reporting I am still an amateur when it comes to MS SQL Server.
I have been tasked with Archiving our Production Database which is growing daily.  Mainly I am looking at the transactions tables, simply because they are the ones that generate the most data (average of a million records per day).
I understand that the tables from which they pull data from might need to be archived as well for referential integrity purposes.
I also need a way to be able to query this archived data whenever needed as quickly as possible if there's a report needed. Any advice?

A: It sounds like whatever application is feeding this database is dumping tons of records in there if as you say there are 1 million transactions a day.  See if whatever is feeding this database has a retention feature.  If you have 1 million + records a day you are going to run out of space quickly.
There are a lot of factors involved in this type of process.  Size of the database, number of transactions, network speeds, storage space, etc...
If I were in your shoes at this moment I would restore a copy of your backup either to another instance or to the same instance if you have room.  I would truncate out all data that is not needed.  I would then create a SQL agent job that will insert the data into the new database tables with the GetDate() function and whatever offset time is needed and do it in a batch function of maybe 1000 per batch.
Here is a sample of one that I use.  It can be an insert or delete batch:
SET NOCOUNT ON;
DECLARE @r INT;
SET @r = 1;
WHILE @r > 0
    BEGIN
        BEGIN TRANSACTION;
        --This could be an INSERT or DELETE etc.
        DELETE TOP (1000)
        FROM dbo.application_log
        WHERE(DATEADD(MM, -6, GETDATE()) > date_created);
        SET @r = @@ROWCOUNT;
        COMMIT TRANSACTION;
    END;

After that is completed, then run a delete batch to remove the data from the primary database, which will purge the old data.
Keep in mind this is a very simplistic model of a data transfer and purge.  There are many ways to accomplish this, but require a greater knowledge of SQL and would take much longer to explain than we have time for here.
Hope that helps.


text:
Q: UbuntuOne syncing really slow I had my Documents folder synced in 11.10. I erased my harddisk before installing 12.04. I then set up U1 the same way and waited to get my files transferred to my hdd. It's really slow and I neither see some kind of progress bar or percentage shown nor do I know the exact speed of the download. I don't have a slow connection here. Is this normal?

A: You should follow this bug report:
https://bugs.launchpad.net/ubuntu/+source/ubuntuone-client/+bug/991250
In the list of the duplicates you can read one of them that is mine. In fact there is a problem with the overwhelming net's traffic in these days. Be patient.


text:
Q: How to verify a JWT with RS256 signature in Deno? I want to verify a signature from a Google JWT which uses RS256 as signature algorithm as of right now (Certs from Google: https://www.googleapis.com/oauth2/v3/certs), and the only libary which i could find for Deno handles HS256 (https://deno.land/x/djwt).
I am really not into the whole Cipher game, maybe anybody got an idea how i can verify the signature maybe there already is something with an example? I really don't know what i need to hash with SHA-256 or how i use RSA, when i try to look up how to implement this, I see a lot of technical explanation but no real examples on what to do with what.
I usually just used Googles Scriptpackage on Node see: https://developers.google.com/identity/sign-in/web/backend-auth
I have functions to hash with SHA-256 but nothing about RSA?

A: Support for RS256 is available since version 1.6 of djwt.
And since Deno version 1.12, RSA signatures can be verified with crypto.subtle, without the need to import external libraries.
First I show a short example with hardcoded values for the JWK and a token that I made up for this demonstration. The verification is done with the crypto.subtle functions:
import { decode } from "https://deno.land/std@0.95.0/encoding/base64url.ts"

const jwt = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IlctNjduZWt0WVRjOEpWWVBlV0g1c1dlN1JZVm5uMFN5NzQxZjhUT0pfQWMifQ.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImlhdCI6MTUxNjIzOTAyMn0.hiKxeC66LIyVKOXjiOk7iScFPy_5-ATw7hEfqGij8sBZmwXAeTPT5BRFYHitFKSXomGqmy_63LLvg4zbhcTTmNf8XIeDAuLsC32soO5woSByisswWHVf8BgxMkI_FPW_oEtEQ8Xv3FL_1rF9j9Oy3jIjgjqhFhXUtsSQWAeuGYH-OQljFwiuO5Bqexcw-H71OEWvQLQof_6KJ0viJyte8QEwEVridyO834-ppHzeaoW2sTvZ22ZNfxPCew0Ul2V_TxHTtO7ZuJCZ81EmeIV6dYJ2GrYh3UN1x1PHy4-tEn-PL4otlaO3PYOcXfCHxHa6xtPsquzPZJnB1Vq8zULLfQ"

// public key in JSON Web Key(JWK) format:
const pubJWK = {
    "kty": "RSA",
    "e": "AQAB",
    "use": "sig",
    "kid": "W-67nektYTc8JVYPeWH5sWe7RYVnn0Sy741f8TOJ_Ac",
    "alg": "RS256",
    "n": "kFpGoVmBmmKepvBQiwq3hU9lIAuGsAPda4AVk712d3Z_QoS-5veGp4yltnyEFYyX867GOKDpbH7OF2uIjDg4-FPZwbuhiMscbkZzh25SQmfRtCT5ocUloQiopBcNAE-sd1p-ayUJWjhPrFoBrBLZHYxVEjY4JrWevQDj7kSeX7eJpud_VuZ77TNoIzj7d_iUuJUUlqF1ZF540igHKoVJJ6ujQLHh4ob8_izUuxX2iDq4h0VN3-uer59GsWw6OHgkOt85TsjMwYbeN9iw_7cNfLEYpSiH-sVHBCyKYQw7f8bKaChLxDRhUUTIEUUjGT9Ub_A3gOXq9TIi8BmbzrzVKQ"
}

// import the JWK to RSA Key
const key = await crypto.subtle.importKey(
    "jwk",
    pubJWK,
    {name: "RSASSA-PKCS1-v1_5", hash: "SHA-256"},
    true,
    ["verify"],
  )

console.log(key)

// split the token into it's parts for verifcation
const [headerb64, payloadb64, signatureb64] = jwt.split(".")
const encoder = new TextEncoder()
const data = encoder.encode(headerb64 + '.' + payloadb64)
const signature = decode(signatureb64)

// verify the signature
const result = await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key, signature, data);
console.log(result)

you can directly run the code above and get the
result

true

for successful verification.
The second example loads the JWKS (JSON Web Key Set) from the google certs endpoint, tries to find the matching key and then verifies the token when a matching key was found. Here I use djwt to verify the token after the key was imported.
The token header contains a key Id ("kid"), which identifies the key that should be used for verification.
{
  "alg": "RS256",
  "typ": "JWT",
  "kid": "W-67nektYTc8JVYPeWH5sWe7RYVnn0Sy741f8TOJ_Ac"
}

import { verify, decode } from "https://deno.land/x/djwt@v2.4/mod.ts"

// the JWT that we want to verify
const jwt = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IlctNjduZWt0WVRjOEpWWVBlV0g1c1dlN1JZVm5uMFN5NzQxZjhUT0pfQWMifQ.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImlhdCI6MTUxNjIzOTAyMn0.hiKxeC66LIyVKOXjiOk7iScFPy_5-ATw7hEfqGij8sBZmwXAeTPT5BRFYHitFKSXomGqmy_63LLvg4zbhcTTmNf8XIeDAuLsC32soO5woSByisswWHVf8BgxMkI_FPW_oEtEQ8Xv3FL_1rF9j9Oy3jIjgjqhFhXUtsSQWAeuGYH-OQljFwiuO5Bqexcw-H71OEWvQLQof_6KJ0viJyte8QEwEVridyO834-ppHzeaoW2sTvZ22ZNfxPCew0Ul2V_TxHTtO7ZuJCZ81EmeIV6dYJ2GrYh3UN1x1PHy4-tEn-PL4otlaO3PYOcXfCHxHa6xtPsquzPZJnB1Vq8zULLfQ"

// get the JSON Web Key Set (JWKS) from google certs endpoint
const certs = fetch("https://www.googleapis.com/oauth2/v3/certs");
var jwks = await certs.then((response) => {
  return response.json()
})

// decode the JWT to get the key Id ('kid') from the header
// in Version 2.4 of djwt decode returns a 3 tuple instead of an object
const [ header, payload, signature  ] = decode(jwt)
var keyId = Object(header).kid

// find the matching JSON Web Key (JWK)
var pubJWK = findJWKByKeyId(String(keyId))

// parse the JWK to RSA Key
if (pubJWK) {
    // import the JWK to RSA Key
    const key = await crypto.subtle.importKey(
      "jwk",
      pubJWK,
      {name: "RSASSA-PKCS1-v1_5", hash: "SHA-256"},
      true,
      ["verify"],
    )

    // verify the signature based on the given public key
    try {
        console.log(await verify(jwt, key))
    }
    catch (error)
    {
        console.log(error)
    }

}
else
{
    console.log("key with kid (" + keyId +") not found")
}

// function to find a certain JWK by its Key Id (kid)
function findJWKByKeyId(kid:string) {
    return jwks.keys.find(
        function(x:string){ return Object(x).kid == kid }
    )
}

In the token header you see "alg": "RS256", but in crypto.subtle.importKey(), {name: "RSASSA-PKCS1-v1_5", hash: "SHA-256"}is used, which is the long form for the 'RS' in 'RS256', as Scott Brady explains.
As the given token (an example created on jwt.io) was not signed by Google, no matching key can be found and therefore it can't be verified. Use your own Google signed JWT to test the above code.
This post is a complete update of the original version, which was based on the now no longer maintained God Crypto library.

A: Let's try this code, more details visit this page jwt authentication in Deno
import { Context } from "https://deno.land/x/oak/mod.ts";
import users from "./users.ts";
import { makeJwt, setExpiration, Jose, Payload } from "https://deno.land/x/djwt/create.ts"
import key from './key.ts'

const header: Jose = {
  alg: "HS256",
  typ: "JWT",
}

export const login = async (ctx: Context) => {
  const {value} = await ctx.request.body();
  for (const user of users) {
    if (value.username === user.username && value.password === user.password) {
      const payload: Payload = {
        iss: user.username,
        exp: setExpiration(new Date().getTime() + 60000),
      }

      // Create JWT and send it to user
      const jwt = makeJwt({key, header, payload});
      if (jwt) {
        ctx.response.status = 200;
        ctx.response.body = {
          id: user.id,
          username: user.username,
          jwt,
        }
      } else {
        ctx.response.status = 500;
        ctx.response.body = {
          message: 'Internal server error'
        }
      }
      return;
    }
  }

  ctx.response.status = 422;
  ctx.response.body = {
    message: 'Invalid username or password'
  };
};

A: With the release of Deno v1.18 https://deno.land/x/jose is the most complete JWT/JWE/JWS/JWK module.
Verifying using a remote JWKSet is as simple as
import * as jose from 'https://deno.land/x/jose@v4.3.8/index.ts'

const JWKS = jose.createRemoteJWKSet(new URL('https://www.googleapis.com/oauth2/v3/certs'))

const { payload, protectedHeader } = await jose.jwtVerify(jwt, JWKS, {
  issuer: 'urn:example:issuer',
  audience: 'urn:example:audience'
})
console.log(protectedHeader)
console.log(payload)


text:
Q: CBCT GPU Reconstruction The below openCL code works pretty good and pretty fast, but I have the impression that I'm missing something in terms of openCL barrier and in therm of index mix; I know that is not very easy to understand, it is the kernel of a CBCT reconstruction I'm working on; the finale image (ReturnMatrice looks a little confused).
 __kernel void
                   ReconstructionGPU(
                                       __global          float* Matrice,
                                       __global          float* ReturnMatrice,
                                       __global          short* ReturnCheckImage,
                                       __constant        float* _dLocArraiAngoliSen,
                                       __constant        float* _dLocArraiAngoliCos,
                                       __constant        float* Cos_Tilt_in_Rad,
                                       __constant        float* Sin_Tilt_in_Rad,
                                       __constant        float* iTilt,
                                       __constant        float* _iOffsetU,
                                       __constant        float* _iOffsetV,
                                       __constant        int* iSizeX,
                                       __constant        int* iSizeY,
                                       __constant        int* iSizeZ,
                                       __constant        int* iSizeImgX,
                                       __constant        int* iSizeImgY,
                                       __constant        float* _fDSO,
                                       __constant        float* _fDSD,
                                       __constant        float* m_fSizeVoxelX,
                                       __constant        float* m_fSizeVoxelY,
                                       __constant        float* m_fPixelSensoreDim,
                                       __constant        int* Loop,
                                       __constant        int* Axial,
                                       __constant        int* Padding
                                   )
        {

        private int _iLocSizeX = iSizeX[0];                     // Detector X
        private int _iLocSizeY = iSizeY[0];                     // Detector Y
        private int _iLocSizeImage = _iLocSizeX * _iLocSizeY;   // Dimensione Immagine

        private int _iSizeMezziX;                               // EmiMatrix X
        _iSizeMezziX = (iSizeX[0] / 2 );

        private int _iSizeMezziY;
        _iSizeMezziY = (iSizeY[0] / 2 );                        // EmiMatrix Y

        private int _iSizeMezziDetX;                            // Emidetector X
        _iSizeMezziDetX = (iSizeImgX[0] / 2 );
        private int _iSizeMezziDetY;
        _iSizeMezziDetY = (iSizeImgY[0] / 2 );                  // Emidetector Y

        private float _iSizeMezziYQuadro = ((_iSizeMezziX - Padding[0]) * (_iSizeMezziY - Padding[0]));   //Border

        private float kySen = 0;
        private float kyCos = 0;

        private float CoordY_Piu_OffsetU = 0;

        private float CoordZ_Piu_OffsetV = 0;
        private float fDist_Y_inMmObj = 0;

        private float fDist_Z_inMmObj = 0;
        private float fDSDinMmY = 0;

        private float fDSDinMmZ = 0;

        private float fDSDinMmYPiu_AngoloTilt = 0;

        private float fDSDinMmZPiu_AngoloTilt = 0;

        private float _ValImage = 0;

        private int ValY = 0;

        private int ValZ = 0;

        private int _iTempx = 0;
        private int _iTempy = 0;

        private int _Index = 0;

        private int z = 0;

        private int zMenoAxial0 = 0;

        private float zPerIlockSizeImage = 0;

        private float TempYPerIlockSizeX = 0;

        private float zPiuTyLoc = 0;

        private float zMenoAxTyLoc = 0;

        private int m_y;
        private int m_x;
        private int y;
        private int x;

        private int m_z = get_global_id(2);

        z = m_z + Axial[0];

                                m_y = get_global_id(1);
                                m_x = get_global_id(0);

                                y = (m_y - _iSizeMezziY ) ;
                                x = (m_x - _iSizeMezziX) ;

                                CoordZ_Piu_OffsetV  = -_iSizeMezziX + z  +     _iOffsetV[0];
                                fDist_Z_inMmObj     = CoordZ_Piu_OffsetV * m_fSizeVoxelX[0];

                                zMenoAxial0        = (z - Axial[0] )   * _iLocSizeImage ;
                                zPerIlockSizeImage = z                 * _iLocSizeImage;

                                    kySen = (_dLocArraiAngoliSen[Loop[0]] * (y)) ;
                                    kyCos = (_dLocArraiAngoliCos[Loop[0]] * (y)) ;

                                    CoordY_Piu_OffsetU      = y  - _iOffsetU[0];

                                    fDist_Y_inMmObj     = (CoordY_Piu_OffsetU * m_fSizeVoxelY[0]);           // Distanza Y in millimetri del voxel in esame nel volume ricostruito

                                    fDSDinMmY                   = 0;

                                    fDSDinMmYPiu_AngoloTilt     = 0;

                                    ValY                        = 0;

                                    fDSDinMmZ                   = 0;

                                    fDSDinMmZPiu_AngoloTilt     = 0;

                                    ValZ                        = 0;

                                        _iTempx    =  ((_iSizeMezziX + (_dLocArraiAngoliCos[Loop[0]] * x)   - kySen));       // Calcolo coordinate X
                                        _iTempy    =  ((_iSizeMezziY + (_dLocArraiAngoliSen[Loop[0]] * x)   + kyCos));       // Calcolo coordinate Y

                                        // Calcoli salti per assegnazione matrice ricostruita

                                        TempYPerIlockSizeX =   _iTempy * iSizeX[0];

                                        zPiuTyLoc     = zPerIlockSizeImage + TempYPerIlockSizeX;

                                        zMenoAxTyLoc  = zMenoAxial0 + TempYPerIlockSizeX;

                                        if (_iTempy >= iSizeY - Padding[0] || _iTempx >= iSizeX - Padding[0] || _iTempy< 0 || _iTempx< 0  ||
                                          (((_iTempx - _iSizeMezziX) * (_iTempx - _iSizeMezziX)) + ((_iTempy - _iSizeMezziY) * (_iTempy - _iSizeMezziY))) > _iSizeMezziYQuadro)

                                        { }
                                        else
                                        {

                                            //float fKval = (_fDSO[0] - (x * m_fSizeVoxelX[0]));
                                            float fKval = (_fDSO[0] - (x * m_fPixelSensoreDim[0]));

                                            fDSDinMmY    = ((fDist_Y_inMmObj* _fDSD[0]) / fKval);         // Distanza Y del pixel in esame rapportata a DSD in millimetri
                                            fDSDinMmZ    = ((fDist_Z_inMmObj* _fDSD[0]) / fKval);         // Distanza DSD in millimetri

                                            if (iTilt != 0)
                                            {

                                                fDSDinMmYPiu_AngoloTilt = (fDSDinMmY * Cos_Tilt_in_Rad[0] +0.5f);                               // Calcolo della Coordinata che tiene conto anche dell'angolo di inclinazione del sensore

                                                ValY = (((fDSDinMmYPiu_AngoloTilt / m_fPixelSensoreDim[0] ) + _iSizeMezziDetX)+0.5f);   // Distanza in pixel del pixel in esame sul detector

                                                fDSDinMmZPiu_AngoloTilt = (fDSDinMmZ  + (fDSDinMmZ * Sin_Tilt_in_Rad[0])+0.5f);                 // Calcolo della Coordinata che tiene conto anche dell'angolo di inclinazione del sensore

                                                ValZ = (((fDSDinMmZPiu_AngoloTilt / m_fPixelSensoreDim[0]) + _iSizeMezziDetY)+0.5f);    // Distanza in pixel del pixel in esame sul detector

                                            }

                                            else
                                            {

                                                ValY = ((fDSDinMmY / m_fPixelSensoreDim[0]) + _iSizeMezziDetX+0.5f);                 // Distanza in pixel del pixel in esame sul detector

                                                ValZ = ((fDSDinMmZ / m_fPixelSensoreDim[0]) + _iSizeMezziDetY+0.5f);                 // Distanza in pixel del pixel in esame sul detector

                                            }

                                            if (ValY >= 0 && ValY < iSizeImgX[0] && ValZ >= 0 && ValZ < iSizeImgY[0])
                                                {

                                                _Index  = ((ValZ * iSizeImgX[0]) + ValY);

                                                _ValImage = (float)Matrice[_Index];//  Pixel dell'immagine con coordinate calcolate da ValX e ValY

                                                }
                                            else
                                                {

                                                 _ValImage = 0;     // Pixel dell'immagine con coordinate calcolate da ValX e ValY

                                                }

                                                   barrier(CLK_LOCAL_MEM_FENCE);

                                                            ReturnMatrice[(int)zMenoAxTyLoc + _iTempx] += _ValImage;   //ValImgPesato

                                                            _ValImage = 0;

                                                }

                }


text:
Q: Rsync only two dictionaries I want to work localy on some programm, which I want to test and run on a remote server. The only files I am editing are the *.hpp and *.cpp in the src and the include directory.
For that I tried this rsync command, to only upload the necessarry source files:
rsync --dry-run -av --exclude '*' --include 'src/*.cpp' --include 'include/*.hpp' Programm/ user@remote:/home/user/Programm
But for some reason no files are commited to the server after some local changes.
Any hints appreciated!
Thank you

A: Here's excerpt from the rsync man page, which tackles your exact problem.

Note that, when using the --recursive (-r) option (which is implied by
  -a), every subdir component of every path is visited left to right, with each directory having a chance for exclusion before its content.
  In this way include/exclude patterns are applied recursively to the
  pathname of each node in the filesystem's tree (those inside the
  transfer). The exclude patterns short-circuit the directory traversal
  stage as rsync finds the files to send.
For instance, to include "/foo/bar/baz", the directories "/foo" and
  "/foo/bar" must not be excluded. Excluding one of those parent
  directories prevents the examination of its content, cutting off
  rsync's recursion into those paths and rendering the include for
  "/foo/bar/baz" ineffectual (since rsync can't match something it never
  sees in the cut-off section of the directory hierarchy).
The concept path exclusion is particularly important when using a
  trailing '*' rule. For instance, this won't work:
+ /some/path/this-file-will-not-be-found
  + /file-is-included
  - *
This fails because the parent directory "some" is excluded by the '*' rule, so rsync never visits any of the files in the "some" or
  "some/path" directories. One solution is to ask for all directories in
  the hierarchy to be included by using a single rule: "+ */" (put it
  somewhere before the "- *" rule), and perhaps use the
  --prune-empty-dirs option. Another solution is to add specific include rules for all the parent dirs that need to be visited. For instance,
  this set of rules works fine:
+ /some/
  + /some/path/
  + /some/path/this-file-is-found
  + /file-also-included
  - *


text:
Q: how to split a string and store the first half in a array in apps script I have a column in my spreadsheet like below
Login 11:30,
Login 11:30,
Logout 11:30,
Login 11:30,
Logout 09:30,
Login 09:30

I want to split (Login/Logout and Time) and I want to store the first half (i.e Login/Logout) in an array
function cabList(cabID, column1) {
    var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Input1');
    var data = ss.getDataRange().getValues();
    var length = data.length,
        count1 = 0,
        count2 = 0,
        outputArray = [],
        shiftData = [],
        temp = [];
    var shift = ss.getRange(3, 11, ss.getLastRow(), 1).getValues();

    for (i = 0; i < length; i++) {
        var tt = shift[i].split(" ");
        shiftData[i] = tt[0];
        if (data[i][column1] === cabID && shiftData[i] === 'Login') {
            count1 += 1;
        } else if (data[i][column1] === cabID && shiftData[i] === 'Logout') {
            count2 += 1;
        }
    }
    temp[0] = cabID;
    temp[1] = count1;
    temp[2] = count2;
    outputArray.push(temp);
}

I'm trying this code but i'm getting an error called

TypeError: Cannot find function split in object Login 11:30

A: var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var finalarray = {};

for(var i=1; i<=sheet.getRange("a1:a6").getValues().length; i++){
  var testcol = sheet.getRange("a"+i).getValue();
  var tt=testcol.split(" ");
  finalarray[i-1] = tt[0];
}
Logger.log(finalarray);

====================================================
function cabList(cabID, column1) {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Input1');
var data = ss.getDataRange().getValues();
var length = data.length,
count1 = 0,
count2 = 0,
outputArray = [],
shiftData = [],
temp = [];

for(var i = 3; i<=ss.getLastRow(); i++){
  for(var j = 11; j>=1; j--){
    var shift = sheet.getRange(i, j, i, 1).getValue();
    var tt = shift.split(" ");
    shiftData[k] = tt[0];
    k++;
    if (data[i][column1] === cabID && shiftData[i] === 'Login') {
        count1 += 1;
    } else if (data[i][column1] === cabID && shiftData[i] === 'Logout') {
        count2 += 1;
    }
  }
}
temp[0] = cabID;
temp[1] = count1;
temp[2] = count2;
outputArray.push(temp);
}

Hope this will help you.
Thanks.


text:
Q: Making requests from Flash for URLs with + signs in them I am hosting images on Amazon S3 and using them in my Flash application. My application receives signed S3 urls that point to the images in S3. The URL looks something like this (line breaks added for clarity):
http://s3.amazonaws.com/my-bucket/my-image.jpg?
  AWSAccessKeyId=AKIAI7PSLIMJFIA2JRQG&
  Expires=1313812683&
  Signature=yhnSe47GRjReUQlfG/S/A+JJTdo=

The problem here is with the + sign that can occur in the Signature. If I send the + sign as-is, then the browser thinks that it's a space, as it should according to the URL specs. Really, S3 shouldn't use + signs for this reason, but it seems to be something they overlooked.
Normally this isn't a problem since you just replace the + sign with a %2B. However, Flash has some default behavior that makes this difficult.
From what I can see, the URLRequest object is setup to always encode URLs as if it was passed through the encodeURI function. I don't see any way to turn this off. Unfortunately, encodeURI doesn't encode + signs, but it does encode % signs.
This means that if I leave the + sign in there then Flash leaves it alone and S3 thinks I have a space in my URL. If I use %2B then Flash turns it into %252B, due to encoding the %. Doh!
Does anybody see a way around this that I'm missing?

A: I don't think it is automatically changes the url submitted to it. Adobe's documentation even tells you to take care and escape unusual characters.
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/URLRequest.html?filter_flash=cs5&filter_flashplayer=10.2&filter_air=2.6


text:
Q: Nginx - Magento multiple websites I have a Magento installation with multiple websites, which is running in Apache web server.
Now I want to move these to Nginx web server; how can I achieve this with Nginx configuration?
Below is the htaccess code which is redirecting websites:
SetEnvIf HOST 44\.55\.222\.101\:8080 MAGE_RUN_CODE=website_new
SetEnvIf HOST 44\.55\.222\.101\:8080 MAGE_RUN_TYPE=website

Please help.

A: To run 2 Magento websites on the same server with different ports you bave to use 2 different nginx configuration files for each port under /etc/nginx/conf.d/.
From the example provided it seems like you are running the websites on ports 80 and 8080. The Magento has provided the default nginx configuration here at http://www.magentocommerce.com/wiki/1_-_installation_and_configuration/configuring_nginx_for_magento
Use this for port 80 and for 8080 use the below code:
server {
    listen 8080 default;
    server_name 44.55.222.101;
    root /var/www/html;
    location / {
        index index.php index.html index.htm;
        try_files $uri $uri/ @handler;
        expires 30d;
    }
    location ^~ /app/ { deny all; }
    location ^~ /includes/           { deny all; }
    location ^~ /lib/                { deny all; }
    location ^~ /media/downloadable/ { deny all; }
    location ^~ /pkginfo/            { deny all; }
    location ^~ /report/config.xml   { deny all; }
    location ^~ /var/                { deny all; }
    location /var/export/ {
        auth_basic           "Restricted";
        auth_basic_user_file htpasswd;
        autoindex            on;
    }
    location  /. {
        return 404;
    }
    location @handler {
        rewrite / /index.php;
    }
    location ~ .php/ {
        rewrite ^(.*.php)/ $1 last;
    }
    location ~ .php$ {
        if (!-e $request_filename) { rewrite / /index.php last; }
        expires        off;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_param  HTTPS $fastcgi_https;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        fastcgi_param  MAGE_RUN_CODE website_new;
        fastcgi_param  MAGE_RUN_TYPE website;
        include        fastcgi_params;
    }
}

A: Store code is defined in Administration > Configuration > Manage Stores
fastcgi_param  MAGE_RUN_CODE default;
fastcgi_param  MAGE_RUN_TYPE store;

A: .htaccess and SetEnvIf is for Apache web server. For Nginx you can use fastcgi_param (if you are running nginx with fastcgi).
You can find more details here:
http://www.magentocommerce.com/wiki/1_-_installation_and_configuration/configuring_nginx_for_magento


text:
Q: How do I create an iterator of lines from a file that have been split into pieces? I have a file that I need to read line-by-line and break into two sentences separated by a "=". I am trying to use iterators, but I can't find how to use it properly within split. The documentation says that std::str::Split implements the trait, but I'm still clueless how to use it.
use std::{
    fs::File,
    io::{prelude::*, BufReader},
};

fn example(path: &str) {
    for line in BufReader::new(File::open(path).expect("Failed at opening file.")).lines() {
        let words = line.unwrap().split("="); //need to make this an iterable
    }
}

How can I use a trait I know is already implemented into something like split?

A: As @Mateen commented, split already returns an iterable. To fix the lifetime problems, save the value returned by unwrap() into a variable before calling split.
I'll try to explain the lifetime issue here.
First it really helps to look at the function signatures.
pub fn unwrap(self) -> T

pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P>

unwrap is pretty simple, it takes ownership of itself and returns the inner value.
split looks scary, but it's not too difficult, 'a is just a name for the lifetime, and it just states how long the return value can be used for. In this case it means that both the input arguments must live at least as long as the return value.
//                   Takes by reference, no ownership change
//                               v
pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P>
//           ^              ^      ^                         ^
//           |              |--|---|                         |
// This just declares a name.  |                             |
//                             |                             |
//           Both of these values must last longer than -----|

This is because split doesn't copy any of the string, it just points to the position on the original string where the split takes place. If the original string for some reason was dropped, the Split will not point to invalid data.
A variable's lifetime (unless the ownership is passed to something else) lasts till it is out of scope, this is either at the closing } if it is named (e.g. with let) or it is at the end of line / ;
That's why there is a lifetime problem in your code:
for line in std::io::BufReader::new(std::fs::File::open(path).expect("Failed at opening file.")).lines() {
    let words = line
        .unwrap() // <--- Unwrap consumes `line`, `line` can not be used after calling unwrap(),
        .split("=") // Passed unwrap()'s output to split as a reference
        ; //<-- end of line, unwrap()'s output is dropped due to it not being saved to a variable, the result of split now points to nothing, so the compiler complains.
}

Solutions
Saving the return value of unwrap()
for line in std::io::BufReader::new(std::fs::File::open("abc").expect("Failed at opening file.")).lines() {
    let words = line.unwrap();
    let words_split = words.split("=");
} // <--- `word`'s lifetime ends here, but there is no lifetime issues since `words_split` also ends here.

You can rename words_split to words to shadow the original variable to not clutter variable names if you want, this also doesn't cause an issue since shadowed variables are not dropped immediately, but at the end of its original scope.
Or
Rather than having a iterator of type str, all of which are just fancy pointers to the original string, you can copy each slice out to it's own string, removing the reliance on keeping the original string in scope.
There is almost certainly no reason to do this in your case, since copying each slice takes more processing power and more memory, but rust gives you this control.
let words = line
    .unwrap()
    .split("=")
    .map(|piece|
        piece.to_owned() // <--- This copies all the characters in the str into it's own String.
    ).collect::<Vec<String>>()
    ; // <--- unwrap()'s output dropped here, but it doesn't matter since the pieces no longer points to the original line string.

let words_iterator = words.iter();

collect gives you the error cannot infer type because you didn't state what you wanted to collect into, either use the turbofish syntax above, or state it on words i.e. let words: Vec<String> = ...
You have to call collect because map doesn't do anything unless you use it, but that's out of the scope of this answer.


text:
Q: Download file from server folder I have files uploaded on server folder and its path is saved in database. sample view of table is:
id  name    resume
1    N1   resume/abc.doc
2    N2   resume/def.pdf

On a click of a button i wish to download the files (format of file would mostly be docx, pdf) from the server to the system. The code that i have written downloads a file but it is either empty or corrupted. Can anyone please tell how to download files from server
<a href="download.php?candidateid=<? echo $candidateid ?>">Download

download.php
$candidateid=$_GET['candidateid'];

$filename = "Filename.docx";
header("Content-Disposition: attachment; filename=\"$filename\"");
$flag = false;
$sql = "SELECT resume FROM candidates where id='".$candidateid."' ";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0)
    {
        while($row = mysqli_fetch_assoc($result))
            {
                if (!$flag)
                    {
                        // display field/column names as first row
                        echo implode("\t", array_keys($row)) . "\r\n";
                        $flag = true;
                    }
                echo implode("\t", array_values($row)) . "\r\n";
            }
    }

A: Using the candidateid you can fetch the file name from your table and then store in a variable and then write the code
$file = '/path/to/your/dir/'.$file;

if(!$file){ // file does not exist
    die('file not found');
} else {
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment; filename=$file");
    header("Content-Type: application/zip");
    header("Content-Transfer-Encoding: binary");

    // read the file from disk
    readfile($file);
}


text:
Q: RuntimeWarning: divide by zero encountered in log10 in pandas align.py, prob from `query`-- cause/solution? Getting the following error, and don't know what it means / how to avoid / whether I should worry:
C:\Users\Nick\Anaconda3\lib\site-packages\pandas\computation\align.py:98:
  ordm = np.log10(abs(reindexer_size - term_axis_size))

while running query().
dtypes:
CGI            int64
SITEID         int32
LONGITUDE    float64
LATITUDE     float32
dtype: object

Query:
towerData = towerData.query('CGI != 0')

Pandas 0.16.2


text: Q: Read local file with known path in chunks with Javascript I'm trying to read file from known path with javascript. At the moment I'm using XMLHttpRequest to get local files but the problem is it loads whole file into memory. This presents a problem when you're trying to read huge files so I want to read files in chunks. This answer on SO deals with it, but it uses FileReader api and File object. Since I already have file path, it seems unnecessary to ask user again to choose file by hand. Is there any way to read file in chunks just by knowing it's path?


text:
Q: Testlink login error I have installed and configured testlink 1.9.16 on centos7 server using following link
https://sysadmin.compxtreme.ro/how-to-install-testlink-on-centos-6-3/
I made some changes according to my Centos7
after completing all procedure, when i open IP_of_my_server/login.php
i get following error message
==============================================================================
 DB Access Error - debug_print_backtrace() OUTPUT START
 ATTENTION: Enabling more debug info will produce path disclosure weakness (CWE-200)
            Having this additional Information could be useful for reporting
            issue to development TEAM.
 ==============================================================================
my log entry is
ERROR ON exec_query() - database.class.php  -  - /* Class:tlEvent -  Method: writeToDB */ INSERT INTO events
(transaction_id,log_level,description,source,fired_at,object_id,object_type,activity) VALUES (0,2,'','',1503033721,0,NULL,'')THE MESSAGE : /* Class:tlEvent - Method: writeToDB */ INSERT INTO events (transaction_id,log_level,description,source,fired_at,object_id,object_type,activity) VALUES (0,2,'','',1503033721,0,NULL,'')
Query failed: errorcode[]
        errormsg:
My mysql version is mysql  Ver 5.6.37 for Linux on x86_64
and my PHP version is PHP 5.6.31 (cli)
can anyone help me ?

A: Faced with the same problem. Looks like installer problem. Just set password for testlink database user. Something like:

grant all privileges on testlink.* to 'testlink'@'localhost' identified by 'your_password';

The password must be the same as in the file config.inc.php in your testlink directory. 'DB_PASS' option.


text:
Q: Change Yii2 assets directory to AWS S3 This is my current assets setting.
class AppAsset extends AssetBundle
{

    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $css = [
    //...

I also have an account on AWS S3. I could upload/download files to S3 successful.
Because I'm using heroku.com to run my website, all assets files will be removed when heroku's dynno is stopped restart. So I want to change assets directory to other server like S3.
How to change yii2 assets directory to AWS S3 ?
Thanks!

A: It is easy.  Just change your sourcePath to the alias that you need. Here is example.
First create alias in you config/web.php
$config = [
    'id' => 'basic',
    'aliases'=>[
        '@test'=> 'https://s3.amazonaws.com'//change it to your amazon s3 path
    ],
    //other config

Then just add it to you AppAssets class or create another Asset.
class AppAsset extends AssetBundle
{

    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $sourcePath = '@test';
    public $css = [
    //...

Thats all.