text:
Q: Insert image in Folder Show null value in Controller I want to insert an image on the client side. image URL inserted in the grid but when I click save button then image URL not pass to the controller and show result null value. But Image URL show in grid image column but not pass to the controller.
And Second Question: when I upload an image then only show Url of the image I want to display image view can you give me the idea how I display image in this code.
c#
 [HttpPost]
        public ActionResult mQuotationInsert(int Qt_ID, string EnteryDate, string Purpose, Quotation[] Quot, string AddNew)
        {
            string result = "Error! Order Is Not Complete!";
            try
            {
                objQuotation.QuotationInsert(Qt_ID, EnteryDate, Purpose, Quot, AddNew);
                ModelState.Clear();
                result = "Quotation Inserted Successfully!";
                return Json(result, JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {

                throw;
            }

        }

Javascript
// Add Multiple Record
    $("#addToList").click(function (e) {
            e.preventDefault();

            if ($.trim($("#PartyName").val()) == "" || $.trim($("#txtfile").val()) == "") return;

        var Srno = document.getElementById("detailsTable").rows.length,
            PartyName = $("#PartyName").val(),
            image = $("#txtfile").val(),
            IsMature = $("#chkNIsMature").is(":checked"),
            detailsTableBody = $("#detailsTable tbody");
            var Qt = '
' + Srno + '	' + PartyName + '	' + image + '	' + IsMature+ '	 Remove
';
            detailsTableBody.append(Qt);
            clearItem();
    });

  $("#saveQuotation").click(function (e) {
            e.preventDefault();
            var QuotationArr = [];
            QuotationArr.length = 0;

            $.each($("#detailsTable tbody tr"), function () {

                QuotationArr.push({
                    Srno: $(this).find('td:eq(0)').html(),
                    PartyName: $(this).find('td:eq(1)').html(),
                    image: $(this).find('td:eq(2)').html(),
                    IsMature: $(this).find('td:eq(3)').html()
                });
            });

            var data = JSON.stringify({
                Qt_ID: parseInt($("#txtQtID").val()),
                EnteryDate: $("#txtNEnteryDate").val(),
                Purpose: $("#txtNPurpose").val(),
                Quot: QuotationArr,
                AddNew: $("#AddNew").val()
            });

            $.when(saveQuotation(data)).then(function (response) {
                console.log(response);
            }).fail(function (err) {
                console.log(err);
            });
        });

HTML

Quotation Details

                                            Party Name
                                            <input type="text" id="PartyName" name="PartyName" placeholder="Party Name" class="form-control" ,Required=true />

                                        <form class="md-form">
                                            Image File

                                                    <input type="file" id="txtfile" name="file">

                                                    <input class="file-path validate" type="text" placeholder="Upload your file">

                                        </form>

                                            @Html.CheckBoxFor(m => m.IsMature, new { @class = "custom-control-input", @id = "chkNIsMature" })

                                            Mature

                                        Add To List

                                            SrNo.
                                            Party Name
                                            Image
                                            Mature


text:
Q: Simplest way to download and unzip files in Node.js cross-platform? Just looking for a simple solution to downloading and unzipping .zip or .tar.gz files in Node.js on any operating system.
Not sure if this is built in or I have to use a separate library.  Any ideas?  Looking for just a couple lines of code so when the next zip file comes that I want to download in node, it's a no brainer.  Feel like this should be easy and/or built in, but I can't find anything. Thanks!

A: I found success with the following, works with .zip
(Simplified here for posting: no error checking & just unzips all files to current folder)
function DownloadAndUnzip(URL){
    var unzip = require('unzip');
    var http = require('http');
    var request = http.get(URL, function(response) {
        response.pipe(unzip.Extract({path:'./'}))
    });
}

A: Checkout adm-zip.
ADM-ZIP is a pure JavaScript implementation for zip data compression for NodeJS.

The library allows you to:

*

*decompress zip files directly to disk or in-memory buffers

*compress files and store them to disk in .zip format or in compressed buffers

*update content of/add new/delete files from an existing .zip

A: Node has builtin support for gzip and deflate via the zlib module:
var zlib = require('zlib');

zlib.gunzip(gzipBuffer, function(err, result) {
    if(err) return console.error(err);

    console.log(result);
});

Edit: You can even pipe the data directly through e.g. Gunzip (using request):
var request = require('request'),
    zlib = require('zlib'),
    fs = require('fs'),
    out = fs.createWriteStream('out');

// Fetch http://example.com/foo.gz, gunzip it and store the results in 'out'
request('http://example.com/foo.gz').pipe(zlib.createGunzip()).pipe(out);

For tar archives, there is Isaacs' tar module, which is used by npm.
Edit 2: Updated answer as zlib doesn't support the zip format. This will only work for gzip.

A: I was looking forward this for a long time, and found no simple working example, but based on these answers I created the downloadAndUnzip() function.
The usage is quite simple:
downloadAndUnzip('http://your-domain.com/archive.zip', 'yourfile.xml')
    .then(function (data) {
        console.log(data); // unzipped content of yourfile.xml in root of archive.zip
    })
    .catch(function (err) {
        console.error(err);
    });

And here is the declaration:
var AdmZip = require('adm-zip');
var request = require('request');

var downloadAndUnzip = function (url, fileName) {

    /**
     * Download a file
     *
     * @param url
     */
    var download = function (url) {
        return new Promise(function (resolve, reject) {
            request({
                url: url,
                method: 'GET',
                encoding: null
            }, function (err, response, body) {
                if (err) {
                    return reject(err);
                }
                resolve(body);
            });
        });
    };

    /**
     * Unzip a Buffer
     *
     * @param buffer
     * @returns {Promise}
     */
    var unzip = function (buffer) {
        return new Promise(function (resolve, reject) {

            var resolved = false;

            var zip = new AdmZip(buffer);
            var zipEntries = zip.getEntries(); // an array of ZipEntry records

            zipEntries.forEach(function (zipEntry) {
                if (zipEntry.entryName == fileName) {
                    resolved = true;
                    resolve(zipEntry.getData().toString('utf8'));
                }
            });

            if (!resolved) {
                reject(new Error('No file found in archive: ' + fileName));
            }
        });
    };

    return download(url)
        .then(unzip);
};

A: I tried a few of the nodejs unzip libraries including adm-zip and unzip, then settled on extract-zip which is a wrapper around yauzl. Seemed the simplest to implement.
https://www.npmjs.com/package/extract-zip
var extract = require('extract-zip')
extract(zipfile, { dir: outputPath }, function (err) {
   // handle err
})

A: yauzl is a robust library for unzipping. Design principles:

*

*Follow the spec. Don't scan for local file headers. Read the central directory for file metadata.

*Don't block the JavaScript thread. Use and provide async APIs.

*Keep memory usage under control. Don't attempt to buffer entire files in RAM at once.

*Never crash (if used properly). Don't let malformed zip files bring down client applications who are trying to catch errors.

*Catch unsafe filenames entries. A zip file entry throws an error if its file name starts with "/" or /[A-Za-z]:// or if it contains ".." path segments or "\" (per the spec).

Currently has 97% test coverage.

A: It's 2017 (October 26th, to be exact).
For an ancient and pervasive technology such as unzip I would expect there to exist a fairly popular, mature node.js unzip library that is "stagnant" and "unmaintained" because it is "complete".
However, most libraries appear either to be completely terrible or to have commits recently as just a few months ago. This is quite concerning... so I've gone through several unzip libraries, read their docs, and tried their examples to try to figure out WTF. For example, I've tried these:

*

*thejoshwolfe/yauzl

*antelle/node-stream-zip

*ZJONSSON/node-unzipper

*EvanOxfeld/node-unzip

*Stuk/jszip

*kriskowal/zip
Update 2020: Haven't tried it yet, but there's also archiver
Top Recommendation: yauzl
Works great for completely downloaded file. Not as great for streaming.
Well documented. Works well. Makes sense.
2nd Pick: node-stream-zip
antelle's node-stream-zip seems to be the best
Install:
npm install --save node-stream-zip

Usage:
'use strict';

var fs = require('fs');
var StreamZip = require('node-stream-zip');

var zip = new StreamZip({
  file: './example.zip'
, storeEntries: true
});

zip.on('error', function (err) { console.error('[ERROR]', err); });

zip.on('ready', function () {
  console.log('All entries read: ' + zip.entriesCount);
  //console.log(zip.entries());
});

zip.on('entry', function (entry) {
  var pathname = path.resolve('./temp', entry.name);
  if (/\.\./.test(path.relative('./temp', pathname))) {
      console.warn("[zip warn]: ignoring maliciously crafted paths in zip file:", entry.name);
      return;
  }

  if ('/' === entry.name[entry.name.length - 1]) {
    console.log('[DIR]', entry.name);
    return;
  }

  console.log('[FILE]', entry.name);
  zip.stream(entry.name, function (err, stream) {
    if (err) { console.error('Error:', err.toString()); return; }

    stream.on('error', function (err) { console.log('[ERROR]', err); return; });

    // example: print contents to screen
    //stream.pipe(process.stdout);

    // example: save contents to file
    fs.mkdir(
      path.dirname(pathname),
      { recursive: true },
      function (err) {
        stream.pipe(fs.createWriteStream(pathname));
      }
    );
  });
});

Security Warning:
Not sure if this checks entry.name for maliciously crafted paths that would resolve incorrectly (such as ../../../foo or /etc/passwd).
You can easily check this yourself by comparing /\.\./.test(path.relative('./to/dir', path.resolve('./to/dir', entry.name))).
Pros: (Why do I think it's the best?)

*

*can unzip normal files (maybe not some crazy ones with weird extensions)

*can stream

*seems to not have to load the whole zip to read entries

*has examples in normal JavaScript (not compiled)

*doesn't include the kitchen sink (i.e. url loading, S3, or db layers)

*uses some existing code from a popular library

*doesn't have too much senseless hipster or ninja-foo in the code

Cons:

*

*Swallows errors like a hungry hippo

*Throws strings instead of errors (no stack traces)

*zip.extract() doesn't seem to work (hence I used zip.stream() in my example)

Runner up: node-unzipper
Install:
npm install --save unzipper

Usage:
'use strict';

var fs = require('fs');
var unzipper = require('unzipper');

fs.createReadStream('./example.zip')
  .pipe(unzipper.Parse())
  .on('entry', function (entry) {
    var fileName = entry.path;
    var type = entry.type; // 'Directory' or 'File'

    console.log();
    if (/\/$/.test(fileName)) {
      console.log('[DIR]', fileName, type);
      return;
    }

    console.log('[FILE]', fileName, type);

    // TODO: probably also needs the security check

    entry.pipe(process.stdout/*fs.createWriteStream('output/path')*/);
    // NOTE: To ignore use entry.autodrain() instead of entry.pipe()
  });

Pros:

*

*Seems to work in a similar manner to node-stream-zip, but less control

*A more functional fork of unzip

*Seems to run in serial rather than in parallel

Cons:

*

*Kitchen sink much? Just includes a ton of stuff that's not related to unzipping

*Reads the whole file (by chunk, which is fine), not just random seeks

A: Checkout gunzip-file
import gunzip from 'gunzip-file';

const unzipAll = async () => {
  try {
    const compFiles = fs.readdirSync('tmp')
    await Promise.all(compFiles.map( async file => {
      if(file.endsWith(".gz")){
        gunzip(`tmp/${file}`, `tmp/${file.slice(0, -3)}`)
      }
    }));
  }
  catch(err) {
    console.log(err)
  }
}

A: Download and extract for .tar.gz:
const https = require("https");
const tar = require("tar");

https.get("https://url.to/your.tar.gz", function(response) {
  response.pipe(
    tar.x({
      strip: 1,
      C: "some-dir"
    })
  );
});

A: You can simply extract the existing zip files also by using "unzip". It will work for any size files and you need to add it as a dependency from npm.

fs.createReadStream(filePath).pipe(unzip.Extract({path:moveIntoFolder})).on('close', function(){
        //To do after unzip
    callback();
  });

A: Another working example:
var zlib = require('zlib');
var tar = require('tar');
var ftp = require('ftp');

var files = [];

var conn = new ftp();
conn.on('connect', function(e)
{
    conn.auth(function(e)
    {
        if (e)
        {
            throw e;
        }
        conn.get('/tz/tzdata-latest.tar.gz', function(e, stream)
        {
            stream.on('success', function()
            {
                conn.end();

                console.log("Processing files ...");

                for (var name in files)
                {
                    var file = files[name];

                    console.log("filename: " + name);
                    console.log(file);
                }
                console.log("OK")
            });
            stream.on('error', function(e)
            {
                console.log('ERROR during get(): ' + e);
                conn.end();
            });

            console.log("Reading ...");

            stream
            .pipe(zlib.createGunzip())
            .pipe(tar.Parse())
            .on("entry", function (e)
            {
                var filename = e.props["path"];
                console.log("filename:" + filename);
                if( files[filename] == null )
                {
                    files[filename] = "";
                }
                e.on("data", function (c)
                {
                    files[filename] += c.toString();
                })
            });
        });
    });
})
.connect(21, "ftp.iana.org");

A: If you don't need to put multiple files into archive, but rather compress one file or just a string contents, then zlib.deflateRaw/zlib.inflateRaw can be used.
Here is an example how to compress in-memory string on macOS/iOS and decompress it in NodeJS.
// Swift, macOS/iOS
let data = "HelloZip!".data(using: .utf8)!
let compressedData = (data as NSData).compressed(using: .zlib) as Data
let compressedDataAsBase64EncodedString = compressedData.base64EncodedString()
print(compressedDataAsBase64EncodedString)
// Prints: 80jNycmPyixQBAA=

// JS, AWS Lambda.
import zlib from "zlib";

const compressedDataAsBase64EncodedString = "80jNycmPyixQBAA="
const compressedData = Buffer.from(compressedDataAsBase64EncodedString, "base64")
const data = zlib.inflateRawSync(compressedData)
console.log(data.toString())
// Prints: HelloZip!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pass date value from one session to another session in the same workflow I have two sessions i a workflow like below
workflow1->session1->session2
i have a join_date column in a table in Mapping1 , in session1
i want to pick this join_date value and pass to  mpping2/session2
If join date value changes in the table in session1 then the same value should pick and pass to session2
I will use this date value in a query in session2 .
Please tell me how to achieve this?
Thank you

A: You can do this using mapping and workflow variables.

*

*In mapping1 create a mapping variable say var1 and set its value to join_date.

*Create a workflow variable in the workflow, say var_wkf

*In session1, in Post-session on success variable assignment, assign var_wkf = var1

*In mapping2, create a mapping variable, say var2

*In session2, in Pre-session variable assignment, assign var2=var_wkf

*You can use the var2 variable in mapping2, it should have the value set in mapping1


text:
Q: Can I connect up LED strip lighting at alternate ends? I want to add some simple LED tape/strip lighting to my van. The 12V supply is close to one end of where I want the strip to start, and I have an earth block to chassis close to the other end. I know this sort of lighting normally has 12V and 0V connection done at the same end of the strip for convenience, but in my case it would be more convenient to connect at opposite ends. Although it will only be a short strip, I suppose it would also be of benefit in having uniform voltage drop at each LED done my way? Is there any reason I shouldn't connect at opposite ends?

A: The LED's are in parallel (for the most part), and thus the + and - nodes are the same at either end of the cable.
Below is a diagram representing a simple LED strip.

The strip "begins" on the left, and "ends" on the right. This is to say that if you lengthened the strip, you'd simply see the pattern repeat sideways.
Assuming the source is 12V, you can see that the cathode (+) end is 12V, both at the beginning of the strip (left side) and end of the strip (right side).
The same goes for the anode (-). It's 0V at the beginning, and 0V at the other end.
In this simplified example, there is theoretically no difference to grounding your strip at a different end.
Now let's go a bit deeper. First, the strips typically have several LEDs in series with a resistor, and that sequence is repeated in parallel. This method is cheaper and more compact, though perhaps less "accurate" in terms of current balancing. I didn't include that in the first example because it wasn't necessary for understanding the answer to the question.

Finally, realize that actual wires have a bit of resistance. Thus there is a difference to which end you connect the anode vs cathode. But you probably won't notice a difference. If you had a very long LED strip and the resistance added up considerably, you might notice that connecting the anode and cathode at the same end up the strip resulted in the LEDs gradually dimming as they progressed to the other end. This would be because the LEDs closest to that end have the least resistance. The LEDs at the far end would be behind much more wire, and thus have more more resistance. Connecting opposing ends should result in a more balanced brightness across all LEDs.
Below is a simulation that includes resistance between LED segments (exaggerated), and shows the current through each. There's a switch at the bottom that you can click on to switch the ground to either end.
[Link to simulation]

A: Beside the connectors perhaps not fitting together, you should be fine. LEDs will only pass current in one direction, so you won't blow them up. And since they're not digital/addressable, there is no danger of reverse biasing the controller ICs or miswiring inputs and outputs.


text:
Q: Where do I see the output for pre build event and post build event (VS2013)? I add these pre-build Events and post-build Events in the Visual Studio 2010.

*

*echo Hello for pre-build

*echo Byebye for post-build

Now if I build the project I will be able to see the following:
1>------ Build started: Project: HelloWorld, Configuration: Debug Win32 ------
1>Build started 2015-08-18 5:50:09 PM.
1>InitializeBuildStatus:
1>  Creating "Debug\HelloWorld.unsuccessfulbuild" because "AlwaysCreate" was specified.
1>PreBuildEvent:
1>  Hello
1>ClCompile:
1>  HelloWorld.cpp
1>  HelloWorld.vcxproj -> C:\Users\yuchen\Desktop\HelloWorld\Debug\HelloWorld.exe
1>PostBuildEvent:
1>  Byebye
1>FinalizeBuildStatus:
1>
1>Build succeeded.

I repeat the same process for Visual Studio 2013, for whatever reason, I am not sure whether the pre-build event and post-build event are actually running or not.
Is the output moved to a different window? Is there other settings to make the pre-build and post-build event working?
1>------ Rebuild All started: Project: HelloWorld2, Configuration: Debug Win32 ------
1>  stdafx.cpp
1>  HelloWorld2.cpp
1>  HelloWorld2.vcxproj -> C:\Users\yuchen\Desktop\Win32Project1\Debug\HelloWorld2.exe

A: Well, no, it isn't running.  If you want to make absolutely sure then just generate an intentional build error:
 exit /b 1

Do note that you are not using the same build settings, you've configured VS2010 to be more verbose.  Tools > Options > Projects and Solutions > Build and Run > MSBuild project build output verbosity.  You've got VS2010 set to "Normal" but VS2013 to "Minimal".  So you want to probably change it for VS2013 so you get what you were used to.
Just watch out for a very annoying bug in VS2013, I've lost countless minutes of my life on it.  When you use Project > Properties to change settings then it doesn't always present the settings for the configuration+platform you've got selected in the toolbar.  You are building Win32+Debug, make sure that the comboboxes at the top of the dialog are also selected to Debug and Win32.  And do keep in mind that you have edit pre/post-build events then you have to do so for all combinations of configuration and platform.


text:
Q: Mercurial: Tag the current revision with a name that is defined in a text file Normally in Mercurial if I want to tag the current revision i do this:
hg tag version12
This will tag my current revision to "version12"
Now suppose that the text "version12" is located in a file called buildNumbers.txt How can I issue a DOS command to tag it with the text contained within the buildNumbers.txt file?
What I already tried was piping the text file in.
hg tag < buildNumbers.txt
But that results in HG just giving me the help screen again.  That tells me it doesen't understand this command.
So does anyone know how to extract the version number from the text file and provide it as a parameter ?

A: Given buildNumbers.txt containing just one line with one tag (no whitepsace):
for /f %v in (buildNumbers.txt) do hg tag %v
If the structure of buildNumbers.txt is more compilcated (you didn't specify it), see the "options" to the for command.

A: You could use a PowerShell script if your buildNumbers.txt is a oneliner!
UrdaNumber.txt Contents:
1.0

UrdaHgTag.ps1:
$ver = cat .\UrdaNumber.Txt
hg tag $($ver)

This will tag the current revision to 1.0 if executed inside the repository.

A: Would this be what you need?
D:\code>md htagtest

D:\code>echo bla>tagfile

D:\code>hg init

D:\code>touch a b c

D:\code>hg add a b c

D:\code>hg commit -m first

D:\code>cat tagfile | xargs hg tag

D:\code>hg log
changeset:   1:2dce938a816a
tag:         tip
user:        Tempos
date:        Sat Sep 17 00:34:36 2011 +0300
summary:     Added tag bla for changeset 349e58fd49a1

changeset:   0:349e58fd49a1
tag:         bla
user:        Tempos
date:        Sat Sep 17 00:34:27 2011 +0300
summary:     first

D:\code>

A: Another powershell version, that does it in one line with pipes:
cat buildnumber.txt | %{hg tag $_}

note this uses a loop, so if you have more than one line in your file you will have to use Select-Object as well, unless you want multiple tags
cat buildnumber.txt | Select-Object -first 1 | %{hg tag $_}


text:
Q: find un-parseable xml strings using tsql (sql server 2005) Having a nvarchar column containing xml. Is there an easy way to find those rows where:
CONVERT(xml, XML, 2)

does not work? Thanks.

A: What would do the job is TRY_CONVERT, but that's new in SQL 2012.
So, pre 2012, the only other way I can think of is to create a SQLCLR function to try parsing the value into a XML blob.


text:
Q: Countdown timer Nan error coming out on safari Good Day.
I currently have a countdown timer running on my WordPress site. The timer represents 2 buying windows and auto rotates to the next buying window. We got the countdown working properly and rotating as it should displaying the proper countdown in Google Chrome but is returning a NaN error on safari.
Not sure what needs to be changed so it comes out working on all browsers. Any help is greatly appreciated! thanks in advance for you time helping me out with this matter
var date = new Date();
var d1 = date.toLocaleString("en-US", {timeZone: "America/Toronto"});
var d = new Date(d1);
var n = d.getDay();
var countDownDate = 0;

if ( n < 5 && n > 0) {
    d.setDate(d.getDate() + 4 - n);
    countDownDate = new Date(d.getFullYear() + "-" + (d.getMonth()+1 ) + "-" + (d.getDate()  ) + " 23:59:59").getTime();
    d.setDate(d.getDate() + 3);
//  jQuery(".ndate").html(d.getDate() + "/" + (d.getMonth() + 1) + "/" + d.getFullYear());
    jQuery(".ndate").html(d.getDate());
    jQuery(".nmonth").html( d.toLocaleString('default', { month: 'long' }));
    jQuery(".nday").html(d.toLocaleDateString('default', { weekday: 'long' }));
    document.getElementById('sun').style.display = 'flex';
    document.getElementById('wed').style.display = 'none';
} else {
    if ( n != 0) {
        d.setDate(d.getDate() + 7 - n);
    }
    countDownDate = new Date(d.getFullYear() + "-" + (d.getMonth() +1) + "-" + (d.getDate()  ) + " 23:59:59").getTime();
    d.setDate(d.getDate() + 3);
    //jQuery(".ndate").html(d.getDate() + "/" + (d.getMonth() + 1) + "/" + d.getFullYear());
    jQuery(".ndate").html(d.getDate());
    jQuery(".nmonth").html( d.toLocaleString('default', { month: 'long' }));
    jQuery(".nday").html(d.toLocaleDateString('default', { weekday: 'long' }));
    document.getElementById('sun').style.display = 'none';
    document.getElementById('wed').style.display = 'flex';
}

// Update the count down every 1 second
var x = setInterval(function() {
  // Get today's date and time
  var d2 = new Date().toLocaleString("en-US", {timeZone: "America/Toronto"});
  var now = new Date(d2).getTime();
  // Find the distance between now and the count down date
  var distance = countDownDate - now;
  // Time calculations for days, hours, minutes and seconds
  var days = Math.floor(distance / (1000 * 60 * 60 * 24));
  var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);

  // Output the result in an element with id="timeline"
document.getElementById("timeline").innerHTML = '

' + days
    + '	 : 	' + hours + '	 : 	'
    + minutes + '	 : 	' + seconds + '

DAYS	 	'
    + 'HOURS	 	' + 'MINUTES	 	' + 'SECONDS

';

    // If the count down is over, write some text
  if ( distance < 1) {

    //clearInterval(x);
    //document.getElementById("timeline").innerHTML = "EXPIRED";
    var date = new Date();
    var d1 = date.toLocaleString("en-US", {timeZone: "America/Toronto"});
    var d = new Date(d1);
    var n = d.getDay();
    if ( n < 5 && n > 0) {
        d.setDate(d.getDate() + 4 - n);
        //jQuery(".ndate").html(d.getDate() - 1);
        //jQuery(".nmonth").html( d.toLocaleString('default', { month: 'long' }));
        countDownDate = new Date(d.getFullYear() + "-" + (d.getMonth()+1 ) + "-" + (d.getDate()) + " 23:59:59").getTime();
        //document.getElementById('wed').style.display = 'flex';
        //document.getElementById('sun').style.display = 'none';

    }
      else {
        if ( n != 0) {
        d.setDate(d.getDate() + 7 - n);
        }
        //jQuery(".ndate").html(d.getDate() - 1);
        //jQuery(".nmonth").html( d.toLocaleString('default', { month: 'long' }));
        countDownDate = new Date(d.getFullYear() + "-" + (d.getMonth()+1 ) + "-" + (d.getDate()) + " 23:59:59").getTime();
        //document.getElementById('wed').style.display = 'none';
        //document.getElementById('sun').style.display = 'flex';
    }
    setInterval(1000);
  }

}, 1000);


text:
Q: iPhone - Add Core Data To existing Project? I am trying to add core data functionality to an existing project.
I added a data model file named "myProj.xcdatamodel"
My code crashes in the following when getting the managedObjectModel
What is the "momd" file? where can i get it or how can i create it?
When i read the path it returns null and crashes the app.
NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"myProj" ofType:@"momd"];
NSURL *modelURL = [NSURL fileURLWithPath:modelPath];

A: the "mom" or "momd" file is the compiled version of the .xcdatamodel file. Perhaps you didn't add the .xcdatamodel file to the target so it isn't getting compiled? Do Get Info on it and make sure it's building for your target.
Also check out the CoreDataBooks sample code.

A: The momd file is the versioned equivalent of the mom file. You have two options at this point:

*

*Add a version to your existing myProj.xcdatamodel model. In Xcode select the myProj.xcdatamodel file and select Design -> Data Model -> Add Model Version from the menu in Xcode.

*Only use the non versioned model file. Change your supplied code to:
NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"myProj" ofType:@"mom"]; NSURL *modelURL = [NSURL fileURLWithPath:modelPath];
If you create a Navigation-based application (Use Core Data for storage) from the default template in Xcode, you'll notice the model file is already versioned.
For further information see: Model Versions


text:
Q: urlconnection error en Android : NetworkOnMainThreadException Estoy intentado utilizar url connection en mi app android y me da el siguiente error:

FATAL EXCEPTION: main
                                                                   android.os.NetworkOnMainThreadException
                                                                       at
  android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1128)
                                                                       at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
                                                                       at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
                                                                       at java.net.InetAddress.getAllByName(InetAddress.java:214)
                                                                       at libcore.net.http.HttpConnection.(HttpConnection.java:70)
                                                                       at libcore.net.http.HttpConnection.(HttpConnection.java:50)
                                                                       at
  libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
                                                                       at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
                                                                       at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
                                                                       at
  libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:316)
                                                                       at libcore.net.http.HttpEngine.connect(HttpEngine.java:311)
                                                                       at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
                                                                       at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
                                                                       at
  libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:81)
                                                                       at Nuevo6.makeRequest(Nuevo6.java:86)
                                                                       at Nuevo6$1.onClick(Nuevo6.java:64)
                                                                       at android.view.View.performClick(View.java:4421)
                                                                       at android.view.View$PerformClick.run(View.java:18190)
                                                                       at android.os.Handler.handleCallback(Handler.java:725)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:92)
                                                                       at android.os.Looper.loop(Looper.java:175)
                                                                       at android.app.ActivityThread.main(ActivityThread.java:5279)
                                                                       at java.lang.reflect.Method.invokeNative(Native Method)
                                                                       at java.lang.reflect.Method.invoke(Method.java:511)
                                                                       at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
                                                                       at dalvik.system.NativeStart.main(Native Method)

os dejo el código del onCreate()
ImageView siguiente = (ImageView) findViewById(R.id.imageView2);
        siguiente.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Log.i("Vehiculos",vehiculos.getText().toString());

                miCC.setVehiclos(vehiculos.getText().toString());
                miCC.setAparcamiento(apar.getText().toString());
                miCC.setInfo(notas.getText().toString());

                Gson gson = new Gson();
                json = gson.toJson(miCC);

                Log.i("JSON",json);

                String result = makeRequest("urlWebService",json);

                Intent passIntent = new Intent();
                passIntent.setClass(Nuevo6.this,Menu.class);
                startActivity(passIntent);
            }
        });

Según veo en el log la codificación del JSON es correcta y la url del webService funciona bien pues si la meto en el navegador me isnerta en la BBDD un nuevo registro con los datos vacíos.
Y por último os dejo la funcion makeRequest que es la que da el problema en la sentencia: " urlConnection.connect();"
 public static String makeRequest(String uri, String json) {
        HttpURLConnection urlConnection;
        String url;
        String data = json;
        String result = null;
        try
        {
            urlConnection = (HttpURLConnection) ((new URL(uri).openConnection()));
            urlConnection.setDoOutput(true);
            urlConnection.setRequestProperty("Content-Type", "application/json");
            urlConnection.setRequestProperty("Accept", "application/json");
            urlConnection.setRequestMethod("POST");
            urlConnection.connect();

            OutputStream outputStream = urlConnection.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            writer.write(data);
            writer.close();
            outputStream.close();

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
            String line = null; StringBuilder sb = new StringBuilder();
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }
            bufferedReader.close();
            result = sb.toString();
        }
        catch (UnsupportedEncodingException e) {
            e.printStackTrace(); }
        catch (IOException e) {
            e.printStackTrace(); }
        return result;
    }

Creo que mi error debe estar un poco más arriba en la sentencia  urlConnection = (HttpURLConnection) ((new URL(uri).openConnection())); ya que no estoy utilizando la variable string url, sino que he metido como uri la url (https://direcionDeMiWebService.php) y no sé si hay que hacer un casting o qué, creo que uri y url no es lo mismo y lo estoy pasando mal a la función.
Muchas gracias, un saludo

A: De acuerdo a tu LogCat el problema es NetworkOnMainThreadException

NetworkOnMainThreadException: se provoca cuando tratas de realizar
  operaciones en el hilo principal (Main thread), lo cual es incorrecto.

Error android.os.NetworkOnMainThreadException en usar HttpURLConnection de Android
Para solucionar esto como opción realiza  tu petición dentro de un Asynctask.
¿Como obtener el valor de un AsyncTask? Esperar hasta obtener el resultado
public class RequestTask extends AsyncTask <String,String,String> {

    @Override
    public String doInBackground(String... params) {

        String uri= params[0];
        String json = params[1];
        /*--------------------------------------------*/
        HttpURLConnection urlConnection;
        String url;
        String data = json;
        String result = null;
        try
        {
            urlConnection = (HttpURLConnection) ((new URL(uri).openConnection()));
            urlConnection.setDoOutput(true);
            urlConnection.setRequestProperty("Content-Type", "application/json");
            urlConnection.setRequestProperty("Accept", "application/json");
            urlConnection.setRequestMethod("POST");
            urlConnection.connect();

            OutputStream outputStream = urlConnection.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            writer.write(data);
            writer.close();
            outputStream.close();

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
            String line = null; StringBuilder sb = new StringBuilder();
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }
            bufferedReader.close();
            result = sb.toString();
        }
        catch (UnsupportedEncodingException e) {
            e.printStackTrace(); }
        catch (IOException e) {
            e.printStackTrace(); }
        return result;
        /*--------------------------------------------*/

    }

    @Override
    protected void onPreExecute() {
    }

    @Override
    public void onPostExecute(String result) {
        //result retorna valor obtenido por la petición.
    }

    @Override
    protected void onProgressUpdate(String... values) {
    }
}

para obtener el resultado de la petición se debe realizar de esta forma:
  //String result = makeRequest("urlWebService",json);
  String resultadoPeticion =  new RequestTask().execute(new String[]{"urlWebService",json}).get();

P.D. No uses esto en una aplicación de producción:
StrictMode.ThreadPolicy policy =
                    new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);

lo que realiza es desactivar la politica de no permitir operaciones en el hilo principal.

A: Eran dos problemas, por un lado que estaba poniendo un String en vez de una variable URL y por otro he tenido que añadir la sentencia :
if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy =
                    new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

Os dejo como queda la función makeRequest por si la podéis/queréis reutilizar:
public static String makeRequest(String json) {
        HttpURLConnection urlConnection;
        URL url;

        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy =
                    new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        try {
            url = new URL("http://www.miWebService.php");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        String data = json;
        String result = null;
        try
        {
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setDoOutput(true);
            urlConnection.setRequestProperty("Content-Type", "application/json");
            urlConnection.setRequestProperty("Accept", "application/json");
            urlConnection.setRequestMethod("POST");
            urlConnection.connect();

            OutputStream outputStream = urlConnection.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            writer.write(data);
            writer.close();
            outputStream.close();

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
            String line = null; StringBuilder sb = new StringBuilder();
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }
            bufferedReader.close();
            result = sb.toString();
        }
        catch (UnsupportedEncodingException e) {
            e.printStackTrace(); }
        catch (IOException e) {
            e.printStackTrace(); }
        return result;
    }

Ya si queréis ser un poco más "PRO" meterlo en un AsyncTask para que en caso de fallar no se bloquee el hilo principal y podéis mostrar un Toast de que falló la comunicación con el servidor!!!


text:
Q: Currently in American region when tried changing to SEA region a new profile was asked to be required To be able to add my friend in Starcraft 2 who is in SEA region I too have to be in SEA region I presume.
When I tried switching to SEA region it required me to enter my character name.
My question is if i enter my character name will I still me able to have my levels and acheivements still with me?

A: Achievements and experience are specific to your region, so when you (essentially) make a new account on SEA, the account will be empty.
The creation process on SEA will be as if you just bought the game and are entering your battlenet username for the first time.


text:
Q: Getting memory metrics in Apache Ignite using http request
I am using apache ignite 2.8.0.
  i need to get following information about ignite cache by using http request,
  1. reads per second
  2. writes per seconds
  3. hit per seconds
  4. miss per seconds
  5. average read time
  6. average write time
how can i get all the info by using http request (using http rest API)

A: You can get some of that using cmd=cache (and doing some math if you want "per second" measurements).
The remaining you may hope to have eventually via IEP-35, I don't see any REST support for it yet, you can file a ticket against Apache Ignite JIRA or start discussion on developers list.


text:
Q: Kafka-Storm integration We have been trying to integrate kafka-storm by referring the Learning Storm book. We have followed all the steps but on execution of the following command we are getting 'Build Failure'-
mvn clean compile exec:java
-Dmain.class=com.learningstorm.kafka.KafkaTopology
and the error is as follows-
[INFO] BUILD FAILURE
[INFO]------------------------------------------------------------------------
[INFO] Total time: 3.546s
[INFO] Finished at: Sat Jan 31 11:46:58 IST 2015
[INFO] Final Memory: 7M/111M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:java (default-cli) on project storm-example: The parameters 'mainClass' for goal org.codehaus.mojo:exec-maven-plugin:1.2.1:java are missing or invalid -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginParameterException

What should we do? Thanks in advance!

A: Add the dependency
<dependency>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.2.1</version>
</dependency>


text:
Q: How to keep 3 radio buttons in mvc 4? Hi i have one Field Called Address Type.
AddressType

i want to keep same as like which is mentioned in the below image
Address Type Radio Button

I keep this AddressType Field as DropDown . it contain totally 3 values and the data is fetch from AddressType Table. Now I want to change this dropdown to 3 radio buttons and depend upon selection in radio button i want to show div. How to do this in MVC4?
I have tried
@Html.RadioButtonFor(model =>model.AddressType,"Billing",true)
@Html.RadioButtonFor(model =>model.AddressType,"Tax",false)
@Html.RadioButtonFor(model =>model.AddressType,"Delivery",false)

Advance Thanks.

A: In your controller, get the address type from the database, where Id and AddressName are coloumn of the table AddressType, if you are using entity framework database first approach then see in the property names of the entity generated for table AddressType.
ViewBag.AddressType  = new SelectList(db.AddressType.ToList(), "Id", "AddressName");

In your view itrate each Address type with loop, make sure the name of the input field should be same when you gonna post it any controller action or use strongly type binding.
  @foreach (var item in (SelectList)ViewBag.AddressType)
    {
       @item.AddressName <input type="radio" name="AddressType" value="@item.Id" />
    }


text:
Q: actionscript 3.0 - .swf nested within a .swf? I know how to load in a .swf from an external file.
However, I don't know how to run one that's already in the library. Is it possible to have a .swf nested within a .swf? I want the final thing to be just one file.
Please help!

A: If you are using flex, the [Embed] tag works for .swfs too. If you are using Flash, I don't know.. but you can probably import the .swf into your library and make it into a symbol.

A: If you are trying to embed the contents of one SWF (B) into another (A), and you have access to the FLA for B, what you could do is recompile B as an SWC file (compiled Flash library).
First make sure that everything you need in B is being correctly exported for ActionScript.
Then, to export as an SWC:
File -> Publish Settings -> Flash -> Export SWC.
Once you have the SWC for B, add a reference to it in the FLA for A:
File -> Publish Settings -> Flash -> Settings -> Library path -> Click + button -> Type in the path to the SWC relative to your FLA (e.g. "./libs/mySWC.swc").
-
In A you'll now be able to reference through ActionScript any of the contents of B.

A: Swiffotron can combine SWF files together into one.


text:
Q: How to change query_cache_type to 2 in AWS RDS? I want to change my AWS RDS parameter query_cache_type value to 2 , I have done it in parameter group dashboard as in the given image.

I have also restarted my mySQL server with the changed parameter,
but when I am checking this by query I am getting a different response:-

How can I change this static parameter ?

A: Have you attached the parameter group to the RDS instance properly? I have just checked on my installation, and things are working as expected. (Note, I do have my cache size set to zero, as for our workload it is not beneficial to enable it)
Parameter Group Settings

MySQL Query Cache
mysql> show global variables like 'query_cache%';
+------------------------------+--------+
| Variable_name                | Value  |
+------------------------------+--------+
| query_cache_limit            | 0      |
| query_cache_min_res_unit     | 512    |
| query_cache_size             | 0      |
| query_cache_type             | DEMAND |
| query_cache_wlock_invalidate | OFF    |
+------------------------------+--------+
5 rows in set (0.01 sec)

Parameter Group Assigned to RDS Instance

Regards,
Dave


text:
Q: Unable to connect to Vagrant (ubuntu/trusty64) from host machine via port forwarding I have set up a Vagrant box with Ubuntu 14.04, node.js, npm, mongodb, forever, deployd and express. I forwarded the host port 8080 to guest port 80, and have a node server in the guest machine listening on port 80.
When I visit http://localhost:8080 in my browser, I expect to see the output from my node server ("Hello World") but instead I get no response from the browser.
From inside the guest machine, when I attempt to curl, I get curl: (7) Failed to connect to localhost port 80: Connection refused.
From the host machine, when I attempt to curl, I get curl: (52) Empty reply from server.
I have tried allowing all incoming web traffic by modifying the iptables using sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT, and have saved those settings and restarted the machine using vagrant reload. That did not resolve the issue.
My Vagrantfile looks like this:
Vagrant.configure("2") do |config|
  config.vm.box = "ubuntu/trusty64"
  config.vm.provision :shell, :path => "bootstrap.sh"
  config.vm.network "forwarded_port", guest: 80, host: 8080
end

My provisioning script looks like this:
#!/usr/bin/env bash

apt-get update
apt-get upgrade
apt-get install -y python-software-properties python g++ make
add-apt-repository ppa:chris-lea/node.js
apt-get update
apt-get install -y nodejs
export NODE_PATH=$NODE_PATH:/usr/lib/node_modules/
apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10
echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list
apt-get update
apt-get install -y mongodb-10gen
npm install forever -g
npm install deployd -g
npm install express -g
mkdir /data
mkdir /data/db
rm -rf /var/www
ln -fs /vagrant /var/www

I am running forever start server.js to start up this sample node server:
var http = require("http");

http.createServer(function(request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello World");
  response.end();
}).listen(80);

What am I missing here? Thanks in advance...

A: Check if your host is listening on port 8080:
$netstat -ntlp | grep 8080


text:
Q: JavaScript regex to extract text and number I am still new on regex (I should learn), I just need JS regex to extract string and number from a text like this: [number][string].
( /^(\d+).(\s+)/?)

Any help please?

A: I think you are looking for '/\d+[a-z]+/gi' :
var x = "123123K, 333D".match(/\d+[a-z]+/gi);
console.log(x);    //["123123K", "333D"]

UPDATE: x is array. You can iterate over it and extract number and text:
xitem.match(/\d+/)[0]      //number
xitem.match(/[a-z]+/i)[0]  //text

P.S.: About \s:

Matches a whitespace character, which in ASCII are tab, line feed,
  form feed, carriage return, and space; in Unicode, also matches
  no-break spaces, next line, and the variable-width spaces (amongst
  others).

http://en.wikipedia.org/wiki/Regular_expression#Examples

A: If the square brackets are in the line as well then do the following:
/^\[(\d+)\]\[(\s+)\]$/

If they are not
/^(\d+)(\s+)$/


text:
Q: Probability of a particle travelling a distance before decay I want to find the probability of a particle travelling a distance greater than 0.5mm before it decays. I know the mean lifetime of the particle at rest and it's momentum components.
I know how to calculate the average distance of the particle before decay but not how to calculate the probability of it travelling a specific distance. Do I have to manipulate the equation:
$$ P(t) = e^{-t/(\gamma \tau)}, $$
where $\gamma$ is the Lorentz factor and $\tau$ is the mean lifetime of the particle at rest?
Any hints would be appreciated, thanks!

A: I presume you also have the rest mass of the particle. So, you can calculate its $v\gamma$ from $|p|$, and thence using the trigonometric relationship between $v/c$ and $\gamma$ (if $v/c=\sin\theta$ then $\gamma=\sec\theta$) you can determine $v$ and $\gamma$ separately.
And then you can work out how much time (in its rest frame) it takes to cover the given distance. And from there you should be able to figure out the probability of it lasting for that amount of time before decaying.


text:
Q: $match aggregate not working with date range in node This is the query condition。visitedDate :type of date
const s = new Date('2017/3/1')

const e = new Date('2017/3/2')
const filter = [
    {
        $match: {
            dataSource: 0,
            visitedDate: {
                $gte: s,
                $lt: e
            }
        }
    },
    {
        $limit: 10
    }
]

I using the mongoose aggregate in node, return "[]".
code:

model.aggregate(filter, (err, data) => {
    if (err) {
        return reject(err)
    }
    return resolve(data)
})

Why, what should i do?


text:
Q: What is the proper name for compositions like (f∘g)(x) Addition, subtraction, multiplication, and division of functions, $(f+g)(x)$, $(f-g)(x)$, $(f×g)(x)$, $(f÷g)(x)$, are fairly common. Is there an established name for such operations on functions using any operator to compose $f$ and $g$, similar to how $(f∘g)(x)$ is called function composition?
In other words, how do we call $(f*h)(x)$ where $*$ denotes a binary operation?
The mathematician Kenneth E. Iverson called this a fork (full APL documentation), but this terminology clearly wasn't accepted (unlike other mathematical terms he invented), because fork doesn't find me anything on Wikipedia or MathWorld.

A: Wikipedia calls this action lifting an operation pointwise, thereby forming a pointwise operation.
From the Wikipedia article "Pointwise":

A binary operation $o: Y × Y → Y$ on a set $Y$ can be lifted pointwise to an operation $O: (X→Y) × (X→Y) → (X→Y)$ on the set $X→Y$ of all functions from $X$ to $Y$ as follows: Given two functions $f_1: X → Y$ and $f_2: X → Y$, define the function $O(f_1,f_2): X → Y$ by
$$(O(f_1,f_2))(x) = o(f_1(x),f_2(x)) \text{ for all } x∈X.$$
Commonly, $o$ and $O$ are denoted by the same symbol. A similar definition is used for unary operations $o$, and for operations of other arity.

A: I do not think that it has its own name (at least one that is widely accepted). I would just "multiply" the functions and specify which "multiplication" is being used. That is mostly based on the fact that one often uses the word "multiplication" for the binary operation of a semigroup/monoid/group etc. So I guess that is just the way to go.


text:
Q: Read the Div Class value in Javascript How can I read this
Mumbai, Maharashtra, India
 by using JavaScript
Thanks

A: You can use loop in javascript:
var data = document.getElementsByClassName("aigjdd");
for (var i = 0; i < priceEls.length; i++) {
  var FinalData = data[i].innerText;
  alert(FinalData);
}

A: just select your data using javascript selector  then use it or show it as you want

var data = document.getElementsByClassName('aigjdd')[0].innerHTML;
alert(data );

Mumbai, Maharashtra, India

A: You can use querySelector, which will return only one Element
console.log(document.querySelector("aigjdd").innerText);


text:
Q: How to access a uitablviews selected item from the appdelegate? If I have a uitableview within a uitableview (yes the cells of the toplevel tableview are tableviews, but never mind that) on a tabbar tab and the user selects a row how can I get access to the selected item from my appdelegate and from the tabbar tabs
Mainly the question I have is if you have a var somewhere deep in your view heirachry how can a tabbar viewcontroller or the appdelegate get hold of it?

A: I usually use specific class to hold such variables. The source looks something like this:
static UIView *__someView = nil;
@implementation VariableContainer
+ (void)setSomeView:(UIView *)someView {
    __someView = someView;
}
+ (UIView *)someView {
    return __someView;
}
@end

When you create some object you want to access from some distant object you just call [VariableContainer setSomeView:] and when you need to access it [VariableContainer someView].
This is just one of many ways you can achieve this same result. A few tips about this one:

*

*for every custom object (such as your app delegate) put in header "@class objectName"

*try importing this container only into source files (no headers)

*do not use retain, only have weak links

*you can put as many objects as you wish so have only 1 container

I hope this helps a bit.


text:
Q: How to check equality of two FStar.Set's How can you check whether two sets are equal in FStar? The following expression is of type Type0 not Tot Prims.bool so I'm not sure how to use it to determine if the sets are equal (for example in a conditional). Is there a different function that should be used instead of Set.equal?
Set.equal (Set.as_set [1; 2; 3]) Set.empty

A: The sets defined in FStar.Set are using functions as representation.
Therefore, a set s of integers for instance, is nothing else than a function mapping integers to booleans.
For instance, the set {1, 2} is represented as the following function:
// {1, 2}
fun x -> if x = 1 then true
         else (
            if x = 2 then true
            else false
         )

You can add/remove value (that is, crafting a new lambda), or asks for a value being a member (that is, applying the function).
However, when it comes to comparing two sets of type T, you're out of luck : for s1 and s2 two sets, s1 = s2 means that for any value x : T, s1 x = s2 x. When the set of T's inhabitants is inifinite, this is not computable.
Solution The function representation is not suitable for you. You should have a representation whose comparaison is computable. FStar.OrdSet.fst defines sets as lists: you should use that one instead.
Note that this OrdSet module requires a total order on the values held in the set. (If you want have set of non-ordered values, I implemented that a while ago, but it's a bit hacky...)


text:
Q: Change hostname bash script I'm trying to change my hostname at startup of an image to the /24 - /32 IPv4 address. I've come up with the following script, but HNAME remains NULL:
#!/bin/sh
echo "Changing hostname to IP-related"
HNAME=ifconfig | grep 'inet addr:' | grep -v '127.0.0.1' | cut -d. -f4 | awk '{ print $1 }'
echo "Proposed hostname is: $HNAME"
echo

hostname=$HNAME
echo "The new hostname is $HOST_NAME"
echo

A: I found a solution. Thanks to @anubhava - also fixed a few inconsistencies in my original example:
#!/bin/sh
echo "Changing hostname to IP-related"
HNAME=ifconfig | grep 'inet addr:' | grep -v '127.0.0.1' | cut -d. -f4 | awk '{ print $1 }'
echo "Proposed hostname is: $HNAME"
echo

hostname $HNAME
echo "The new hostname is $HNAME"
echo


text:
Q: Erro ao validar dígito do usuário em jogo da forca No meu código Java para jogo da forca, surge um erro no momento que testa se o usuário digitou uma das letras da palavra secreta.
erro:

Exception in thread "AWT-EventQueue-0"
java.lang.NumberFormatException: For input string: ""

Código que testa a letra:
if (jtChute.getText().isEmpty()) {
            JOptionPane.showMessageDialog(null, "Preencha o campo: 'Chute uma letra' ");
        jtChute.requestFocus();

    } else {
        char[] pal = jlRevela.getText().toUpperCase().toCharArray();
        String armazenada = jlSegredo.getText();

        StringBuilder acertou = new StringBuilder(armazenada); //modifica a string

        char l = jtChute.getText().toUpperCase().charAt(0); //pega a primeira letra

        boolean correto = false;

        for (int i = 0; i < pal.length; i++) { //percorre todas as letras da palavra
            if (pal[i] == l) {
                acertou.setCharAt(i, l);
                JOptionPane.showMessageDialog(null, "Parabéns!");

                jlSegredo.setText(armazenada);
                correto = true;
            }
        }
        int vidas = Integer.parseInt(jlResta.getText());
        if (correto == false);
        vidas--;
        jlResta.setText(Integer.toString(vidas));
        JOptionPane.showMessageDialog(null, "Você errou!");
        if (vidas == 0) {
            JOptionPane.showMessageDialog(null, "VOCÊ PERDEU");
            jlSegredo.setText("");
            jlRevela.setText("REVELADOR");
            jlResta.setText("");
            JOptionPane.showMessageDialog(null, "Jogue novamente.");
        }
        if (jlSegredo.getText().equals(jlRevela.getText())) {
            JOptionPane.showMessageDialog(null, "Você descobriu a palavra. Parabéns!");
            jlSegredo.setText("");
            jlRevela.setText("REVELADOR");
            jlResta.setText("");
        }
    }
    jtChute.setText("");
    jtChute.requestFocus();
}

A: O erro está ocorrendo nesta linha provavelmente:
int vidas = Integer.parseInt(jlResta.getText());

supondo que esta seja o único uso do parseXXX no seu código. Pela mensagem, você está tentando converter uma string vazia em número.
Se este campo é de entrada de usuário, você precisa validar também se o valor recebido é convertível em um inteiro. Um jeito simples de validar isso é justamente capturar a exceção que esse método lança, a NumberFormatException
int vidas;

try{

vidas = Integer.parseInt(jlResta.getText());

} catch(NumberFormatException ex) {
//aqui você faz algo quando o valor não for um número
}

Se esse campo não for uma entrada de usuário, você deve garantir que ele sempre tenha um valor numérico antes de fazer a conversão.
Pelo que pude perceber, trata-se de um campo de texto para exibir o número de tentativas restantes, se for essa a única finalidade, recomendo usar um JLabel, já que a finalidade, pelo que parece, é apenas mostrar ao player quantas tentativas ele ainda tem.


text:
Q: UI framework vs Styled-components to make UI from scratch in React? I jumped into React recently, so I'm very confused about many things. One of them is about how most of people design UI in React.
Before jumping in, I used Bootstrap to design UI of my website by using pre-made components such as buttons, modal views, navigations, and so on. But, figured out I can't use it anymore in React, but I can use React-Bootstrap instead. Is React-Bootstrap still the most popular UI framework in React as well? I'm asking that because I found some other UI frameworks such as Semantic UI or Material UI for React.
Also, I found styled-components. However, styled-components makes me feel like I need to make every component by myself to use which sounds like taking too long time.
As a very beginner, I'm curious about how people usually work on UI in React?

A: Firstly, There is no clear answer for the problem. In general purpose of styled-components not mean don't use another ui framework. And the companies solve the problems which is spesific with their Engineering Team. They have their own architecture though. But the alone programmers are choose some open source solutions.
Well, Some people use together or alone. It's totally about your project or your style of architecture. But still i would say some stuffs for giving point of view.
In the other hand; the UI Frameworks are solve modular problems. An example: You cannot create a modal with only css even styled-components. you know, you need JavaScript for that.
To use both:

*

*You can use on Elements Semantic-UI(ReactJS or direct element with the className),

*You can use styled-components instead of css file for spesific part of your project. As e.g: Main, Aside, Article, Post, TopNavigation etc.

*If you prefer to use the styled-components, also you can use same components in React Native. (There is no css file support for React Native. You'll need inline CSS)

*To use only div instead of the spesific component, you'll confused after project being bigger. I would recommended you to create for each meaningful Element.

*You can combine the open source community UI parts with your own CSS.

*You won't need a CSS(Less, Sass) file when you use styled-components. That's mean, you'll work only on your JS files instead CSS files, so you can do dynamic things in your components. styled-components supports almost all CSS features.

To use standalone Semantic-UI:

I prefer Semantic-UI-React instead of ReactJS bootstrap frameworks.

*

*You cannot use the CSS of Semantic-UI-React in React Native. You should choose which is another solution or actually make your own your components architecture.

*You are ready to go with every project with Semantic-UI-React for web/mobile site.

*You have to learn basics of less-lang.

*You can change everything from your theme files which variables.

Lastly,

*

*If you have big project or goal though; nevertheless, i think you should use a UI Framework in learning and adaptive process.

*If you are still not sure what you should do you then, you have to try all of them to find your own architecture.

*I think in learning process, you have to concern about ReactJS needs(Redux, Router etc.) before CSS.

It's my first answer at Stackoverflow. Hopefully, the answer will help you for your concern.


text:
Q: How to loop through axis for subplots in a while loop? How can i use my while loop conditions to loop through axis of subplots. I am very new to python. I have written a code where i plot the data based on some conditions in a while loop. The code works fine for plotting individual plots but when i have to plot all in one plot like subplots, i don't know how can i index that every time one round of plotting is finished the axis index should change and the next plotting is done on different index. As in the image it can be seen, the first row is plotted and rest everything is plotted all over again as the loop has no condition to go for axis indexing. How can i achieve is that every time the value of i,j.l,m in the code is incremented, the plots should move to next row in subplot figure.[]
import matplotlib.pyplot as plt
import xarray as xr
file="/home/arjun2516/hlrn/JOBS/cy_topo_ref4hr2/OUTPUT/cy_topo_ref4hr2_av_3d.002.nc"
Data=xr.open_dataset(file)

l=150
m=300
i = 75
j = 175
while i and j < 700 and l and m < 800 :
    fig,axs = plt.subplots(ncols=3, nrows=3,figsize=(20,20))
    Data.zusi[i:j,75:175].plot.contourf(ax=axs[0,0])
    print(i,j)
    # plt.show()
    Data.zusi[l:m,250:400].plot.contourf(ax=axs[0,1])
    #  plt.show()
    Data.zusi[l:m,450:600].plot.contourf(ax=axs[0,2])
    # plt.show()
    i += 200
    j += 200
    l += 200
    m += 200
    print(i,j)
print('ok')

I tried to introduce a for loop inside the while loop but it was also producing same results.

A: There is several problems in your code:

*

*You are creating a new figure object (containing the grid of subplots) in every loop iteration, so the plots from different iterations will end up in different figures. Move the plt.subplots command before the loop.

*In order to plot onto the axis of a different row in each loop iteration, you need an axis index that starts at zero (that is, indexing the first row) and is incremented in each iteration.

With these changes, your code becomes:
l=150
m=300
i = 75
j = 175

fig,axs = plt.subplots(ncols=3, nrows=3,figsize=(20,20))
ax_idx = 0

while i and j < 700 and l and m < 800 :
    # Select axis based on the axis index
    Data.zusi[i:j,75:175].plot.contourf(ax=axs[ax_idx,0])
    print(i,j)
    # plt.show()
    Data.zusi[l:m,250:400].plot.contourf(ax=axs[ax_idx,1])
    #  plt.show()
    Data.zusi[l:m,450:600].plot.contourf(ax=axs[ax_idx,2])
    # plt.show()
    i += 200
    j += 200
    l += 200
    m += 200
    # Increase the axis index
    ax_idx += 1
    print(i,j)

Note that you could also simplify your code by using a for loop. I would also highly recommend using xarray's capabilities for label-based indexing, in this case isel. It makes the code a little bit more verbose, but much more understandable.
n_rows = 3
fig,axs = plt.subplots(ncols=3, nrows=n_rows, figsize=(20,20))
ax_idx = 0

for ax_idx in range(n_rows):
    # Compute the index values
    l = 150 + ax_idx * 200
    m = 300 + ax_idx * 200
    i = 75 + ax_idx * 200
    j = 175 + ax_idx * 200
    # Index array based on named dimensions and plot it
    Data.zusi.isel(x=slice(i, j), y=slice(75, 175)).plot.contourf(ax=axs[ax_idx, 0])
    Data.zusi.isel(x=slice(l, m), y=slice(250, 400)).plot.contourf(ax=axs[ax_idx, 1])
    Data.zusi.isel(x=slice(l, m), y=slice(450, 600)).plot.contourf(ax=axs[ax_idx, 2])
    print(i,j)


text:
Q: State the midpoint rule State the Midpoint rule for:
$$\int_c^dg(t)dt$$ with $m$ subintervals
Is this how you state it?
$$M_n=\frac{d-c}{m}[g(t_m)]$$
or
$$M_n=\frac{d-c}{m}[g(t_1)+g(t_2)...g(t_m)]$$

A: Let us explore a little bit. I believe that you have an exam soon and I wanted to give you more of an intuistic approach to this problem.

Let us take your definite integral of $$\int_c^dg(t)dt.$$
We want to divide the interval $[c,d]$ into $m-$subintervals of equal width such that $$\triangle{t}=\frac{d-c}{m}$$
where we define the subintervals as $[t_0,t_1],[t_1,t_2],\cdots,[t_{m-1},t_m] \ (t_0=c \ \text{and} \ t_m=d)$.
Here is a visual sketch:

Let $g(t^*_i)$ be the height of the midpoint at midpoint $t^*_i$. Therefore we receive a notion that $$\int_c^dg(t)dt=\triangle{t}g(t^*_1)+\triangle{t}g(t^*_2)+\cdots+\triangle{t}g(t^*_m).$$
By factorization, we get the final result of the midpoint rule to be
$$\int_c^dg(t)dt=\boxed{\triangle{t} \ [g(t^*_1)+g(t^*_2)+\cdots+g(t^*_m)]}=\boxed{\triangle{t} \ [\sum[g(t^*_m)]}.$$

I just wanted to give you a bit more insight on this rule about why "it is." All in all, your first equation
$$M_n=\frac{d-c}{m}[g(t_m)]$$
is wrong because you need to account for all heights from $c$ to $d$ in order to receive the correct definite integral. On the other hand, the you equation proceeding the first
$$M_n=\frac{d-c}{m}[g(t_1)+g(t_2)...g(t_m)]$$
is correct only if you refer to the $t_i$ as the midpoints of each subinterval and $g(t_i)$ as the height at each midpoint.
Hope this was helpful!


text:
Q: Pine Script Strategy Stoploss and Takeprofit problem I tried to code a strategy with Stoploss and Takeprofit. After the signal bar, the entry (blue Line), stoploss (red line) and takeprofit (green line) are declared.
Problem 1: When a position is entered, the stoploss is triggered. Even if the red line is not touched by the price. What am i doing wrong? (compare Imagelink) 1

Problem 2: When a position is closed, a new position is entered at the next bar. Even if the price is higher than the entry price (blue line). These buys should not happen. (compare Imagelink) 2

Here my Code:
//Stoploss + Take profit
SL = input.float(0.5, step=0.1)
TP = input.float(2.5, step=0.1)

buyprice = BB_high
longstop = BB_high - (BB_high - BB_low)*SL
longprofit = BB_high + (BB_high - BB_low)/2 * TP

plot (longstop, color=color.red, linewidth=2)
plot (longprofit, color=color.green, linewidth=2)

//Position entry + exit (stoploss or takeprofit)
strategy.entry("Buy", strategy.long, stop=buyprice)

if strategy.position_size >0
    strategy.exit (id="Long SL", from_entry="Buy", limit=longstop)
    strategy.exit (id="Long TP", from_entry="Buy", stop=longprofit)

A: Use limit for take profit and stop for stop loss. You got those mixed up.
strategy.exit (id="Long SL", from_entry="Buy", stop=longstop)
strategy.exit (id="Long TP", from_entry="Buy", limit=longprofit)


text:
Q: When the train start to go / move / something else? While talking about a bus or a train, what's the correct way to refer to his leaving the main train station? Is there a specific term like departure for airplane.
I thought about "When the train goes / moves to Cardiff" something else? But I'm not sure if it's natural.

A: Pulls away is usually used for trains. To add more context, one might say:

The train pulls away from the station.

In the context above this doesn't really fit though. The following may suffice:

When the train travels to Cardiff.

Or

When the train leaves for Cardiff.

It depends on the context you're using it in though

A: You could say

When the train leaves for Cardiff

to leave for means:

*To set out for some destination.
What time do you leave for the airport in the morning?
  They're leaving for New York next week, so I'm having a going-away party for them this Saturday.

(source: The Free Dictionary - I've left out the sentence which is erroneously duplicated from definition 3)


text:
Q: finding an element recursively (c++) int searching(string arr [],int sizee,string element) {
    static int location;
    if(arr[sizee-1]==element) {
        location = sizee;
        return location;
    }
    else location = searching(arr, sizee-1, element);
}

I have used this function to search for element.
It works for array of size 2 but more than that it gives me wrong place.
Also I want to know how to make it return -1 if it couldn't find the element.

A: There are a few things wrong/not needed with your code.  The biggest issue is you do not have a stop condition for when the element does not exist in the array.  Currently you just go negative and accessing the array with a negative index is undefined behavior.
Another issue is location.  It is not needed.  Once you find the element you just return the position directly.  No need to set a variable and then return that variable.  So making those changes gives you a function that looks like
int searching(string arr [],int sizee,string element) {
    if (sizee <= 0)
        return -1; // we did not find the element in the array or the caller gave us a negative size
    if(arr[sizee-1]==element)
        return sizee-1; // just return the index you used
    // no else needed here.  Just return the result of calling the function recursively
    return searching(arr, sizee-1, element);
}

A: first, you must ensure, sizee greater than zero, or you will over flow.second, the third function parameter element's data type should be char, no string.


text:
Q: How to set width of the dropdown of search view to match the width of search text area in android I want to implement searchview with suggestions-list.
Normally,suggestions-list dropdown width appears as same as the searchview text area.But when I set the following property in AndroidManifest.xml
android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" to application tag, I see that suggestions-list width appears greater than the searchview text area.
I tried setting dropdownwidth with autoCompleteTextView.setDropdownWidth(int)to some value, did not work.

A: You can do something like this, here I needed to fill the screen width with dropdown:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // inflate our menu
    getMenuInflater().inflate(R.menu.search_menu, menu);

    // find MenuItem and get SearchView from it
    MenuItem searchMenuItem = menu.findItem(R.id.search);
    SearchView searchView = (SearchView) searchMenuItem.getActionView();

final AutoCompleteTextView searchTextView = (AutoCompleteTextView) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);

    // get AutoCompleteTextView from SearchView
    final AutoCompleteTextView searchEditText = (AutoCompleteTextView) searchView.findViewById(searchEditTextId);
    final View dropDownAnchor = findViewById(searchTextView.getDropDownAnchor());
    if (dropDownAnchor != null) {
        dropDownAnchor.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom,
                                       int oldLeft, int oldTop, int oldRight, int oldBottom) {

                // calculate width of DropdownView

                int point[] = new int[2];
                dropDownAnchor.getLocationOnScreen(point);
                // x coordinate of DropDownView
                int dropDownPadding = point[0] + searchTextView.getDropDownHorizontalOffset();

                Rect screenSize = new Rect();
                getWindowManager().getDefaultDisplay().getRectSize(screenSize);
                // screen width
                int screenWidth = screenSize.width();

                // set DropDownView width
                searchTextView.setDropDownWidth(screenWidth - dropDownPadding * 2);
            }
        });
    }

    return super.onCreateOptionsMenu(menu);
}

Original answer:
https://stackoverflow.com/a/26344053/1959110


text:
Q: When onLost event triggered in Nearby Message API I am working on Nearby Message API to start a service in my App in he background whenever Eddystone beacon detected nearby.
It works fine but what I observed is that it trigger its onFound event every time I restart Bluetooth.
But I want to trigger onFound event every time I(android device) comes in the range of a beacon(Bluetooth would always be in On Mode).
After debugging, I found that this happens because onLost event not triggered when I go out the range of my beacon, instead, onLost only triggered when I turn-off Bluetooth.
So my Question is, what is the expected behavior of onLost event, and is it possible what I am thinking?
Thanks in advance for your views.

A: From: https://developers.google.com/android/reference/com/google/android/gms/nearby/messages/MessageListener
public void onLost (Message message)

Called when a message is no longer detectable nearby.
Note: This callback currently works best for messages attached to BLE beacons. For other messages, it may not be called in a timely fashion, or at all.
This method will not be called repeatedly (unless the message is found again between lost calls).
you should try to move away from (or turn off) the beacon and this should trigger "onLost", like turning off Bluetooth

A: The onLost callback is triggered when Nearby scan cannot detect beacon for at least 10 seconds (timeout based on experience, I did not find any official value).
The situation is easy in case of foreground scanning. The scanning is active all the time and Nearby is able to detect "missing" beacon after 10 seconds.
The situation gets complicated in case of background scanning. The scan is performed only on screen-on events so the onLost can be triggered much much later.
I think switching Bluetooth off triggers Nearby and previously found beacons become lost. That's the reason why you get onLost when you switch off Bluetooth. If you are using background scanning, you will get updates when other application makes scan. So if you get out of beacon's range, wait 10 secs and then perform scan by other app, you should get onLost callback.
The same applies to onFound.
I guess it does not solve your problem but hopefully it answers your question...


text:
Q: Canvas se limpia automaticamente pues estoy haciendo una aplicación en Android Studio, en esta aplicación utilizo Canvas como lienzo de escritura pues mi meta es imprimir en el canvas una ecuación matemática, el problema está que cuando ingreso los datos desde un Custom Dialog con un EditText y presiono sobre botón aceptar para que el canvas se pinte, efectivamente pasa pero el canvas se limpia automáticamente cuando el teclado virtual se cierra, he notado que solo pasa con el teclado virtual porque he probado con un teclado físico y todo va perfecto!
Cabe destacar que no es el mismo problema que causa por ejemplo cuando se pasa de landscape a portraint o viceversa. El contenido de las variables no se pierde, el problema es solo el canvas que se limpia.
el canvas está en una clase diferente al MainActivity
Agradecería mucho cualquier ayuda o recomendación para poder investigar, gracias!


text:
Q: What am I missing out on from Visual Studio if I'm using Visual Studio Code? In very concrete terms, what are examples of things that I could do in Visual Studio that I can't do with Visual Studio Code?
Background:
I've used vim for all my code editing for decades, but recently started using Visual Studio Code and I'm very thoroughly enjoying it. Given that history, I considered Visual Studio Code to be an IDE.
Curious about the difference between Visual Studio and Visual Studio Code, I've found several explanations pointing out that VSCode is a code editor while Visual Studio is an IDE. I'm so confused by this. VSCode certainly feels like an IDE to me, so I really wonder what I'm missing out on.
I'm on Linux, so it's entirely hypothetical, but now that I'm leveling up my development environment, I can't help but be curious what might be in store for me at the next level(s) and looking at the documentation, I'm struggling to find anything that stands out.

A: There some Microsoft features integrated into Visual Studio, which you can't do in Code like the Windows Forms Apps.
Another key difference is, that in Visual Studio there are a lot of features already baked in, while Code is more modular. For example, you can individually install debuggers and syntax highlighting for different languages. By saying is VSCode is a code editor, people refer to it as missing some features in the vanilla configuration. But I do agree Code feels very much like an IDE.


text:
Q: 2D arrays in JSON getting converted into a 1D array of objects I've looked around but haven't found an answer so I figured i would give it an ask myself.
I've noticed that a round trip to JSON converts a 2-D array into a 1D array of Objects.
Is there any way around this or should I just try to work with objects from the beginning (e.g. $test->1->4 ? see example below
    $test = array();
    $test[0][0] = "0-0";
    $test[0][2] = "0-2";
    $test[1][1] = "1-1";
    $test[1][2] = "1-2";
    var_dump($test);
    $encoded = json_encode($test);
    var_dump($encoded);
    $recreated = json_decode($encoded);
    var_dump($recreated);

outputs
array(2) {
  [0]=>
  array(2) {
    [0]=>
    string(3) "0-0"
    [2]=>
    string(3) "0-2"
  }
  [1]=>
  array(2) {
    [1]=>
    string(3) "1-1"
    [2]=>
    string(3) "1-2"
  }
}
string(45) "[{"0":"0-0","2":"0-2"},{"1":"1-1","2":"1-2"}]"
array(2) {
  [0]=>
  object(stdClass)#19 (2) {
    ["0"]=>
    string(3) "0-0"
    ["2"]=>
    string(3) "0-2"
  }
  [1]=>
  object(stdClass)#20 (2) {
    ["1"]=>
    string(3) "1-1"
    ["2"]=>
    string(3) "1-2"
  }
}

A: This is because you don't have ongoing indexes in your array:
$test = array();
$test[0][0] = "0-0";
$test[0][2] = "0-2";

In this case json_encode() HAS to create an object because there is a numeric key (1) missing.
You can decode it back to an array with json_decode($txt, true), but this is only a work around, not a fix.

A: By default json_decode will convert the json into objects. You code needs to look like:
$recreated = json_decode($encoded, true);

A: You can decode as arrays:
$recreated = json_decode($encoded, true);


text:
Q: Syntax error when using sequelize postgres sequelize: 1.7.0
pg: 2.11.1
posgreSql: 9.3 (pg server on my pc)

I have app that is using following config:
db: 'mysql://user:pass@localhost/dbname'

And it works with sequelize and mysql dialect.
When I change it to:
db: 'postgres://user:pass@localhost/dbname'

and dialect to postgres and try to sequelize.sync() I get following error:
{
   "message":"syntax error at or near \"(\"",
   "name":"error",
   "stack":"error: syntax error at or near \"(\"\n    at Connection.parseE (/Users/me/Desktop/node/myapp/node_modules/pg/lib/connection.js:561:11)\n    at Connection.parseMessage (/Users/me/Desktop/node/myapp/node_modules/pg/lib/connection.js:390:17)\n    at [object Object].<anonymous> (/Users/me/Desktop/node/myapp/node_modules/pg/lib/connection.js:92:20)\n    at EventEmitter.emit (events.js:95:17)\n    at Socket.<anonymous> (_stream_readable.js:746:14)\n    at EventEmitter.emit (events.js:92:17)\n    at emitReadable_ (_stream_readable.js:408:10)\n    at emitReadable (_stream_readable.js:404:5)\n---------------------------------------------\n    at module.exports.CustomEventEmitter.failure.CustomEventEmitter.fail.CustomEventEmitter.error (/Users/me/Desktop/node/myapp/node_modules/sequelize/lib/emitters/custom-event-emitter.js:93:10)\n    at exec (/Users/me/Desktop/node/myapp/node_modules/sequelize/lib/query-chainer.js:92:14)\n    at onError (/Users/me/Desktop/node/myapp/node_modules/sequelize/lib/query-chainer.js:72:11)\n    at EventEmitter.emit (events.js:95:17)\n    at module.exports.CustomEventEmitter.emit (/Users/me/Desktop/node/myapp/node_modules/sequelize/lib/emitters/custom-event-emitter.js:61:33)\n    at [object Object].<anonymous> (/Users/me/Desktop/node/myapp/node_modules/sequelize/lib/emitters/custom-event-emitter.js:131:17)\n---------------------------------------------\n    at module.exports.CustomEventEmitter.failure.CustomEventEmitter.fail.CustomEventEmitter.error (/Users/me/Desktop/node/myapp/node_modules/sequelize/lib/emitters/custom-event-emitter.js:93:10)\n    at exec (/Users/me/Desktop/node/myapp/node_modules/sequelize/lib/query-chainer.js:92:14)\n    at onError (/Users/me/Desktop/node/myapp/node_modules/sequelize/lib/query-chainer.js:72:11)\n    at EventEmitter.emit (events.js:95:17)\n    at module.exports.CustomEventEmitter.emit (/Users/me/Desktop/node/myapp/node_modules/sequelize/lib/emitters/custom-event-emitter.js:61:33)\n    at [object Object].<anonymous> (/Users/me/Desktop/node/myapp/node_modules/sequelize/lib/emitters/custom-event-emitter.js:131:17)",
   "code":"42601"
},
"msg":"uncaughtException",
"time":"2014-03-31T14:17:29.496Z",
"v":0
}

What I am doing wrong?
Before I created dbname database in pg there was error missing database so I guess sequelize is connected to pg but it generates some syntax errors in pgsql code??

the problem was that in model schema I had Sequelize.INTEGER(11) - and postgres does not allow to pass 11 as a size of INTEGER - this will be solved in 2.x.x version of Sequelize (You can find issue corresponding to this problem on sequelize github repo).

A: Sequelize and postgres work well for me. Did you set dialect, protocol, port correctly in config.js like this
{
  "development":{
    "username":"name",
    "password":"pass",
    "database":"db",
    "dialect":"postgres",
    "protocol":"postgres",
    "host":"127.0.0.1",
    "port":"5432"
  },
...


text:
Q: My CSS animation does not work I have some animation pull down that supposed to work on all browsers but it is not working on any.
Any help is much appreciated.
Thanks.
HTML:

CSS:
 .scroll-indicator-wrapper {
    display: block;
    position: absolute;
    left: calc(50% - 45px/2);
    height: 45px;
    width: 45px;
    -webkit-transition: all .3s ease-in-out;
    -moz-transition: all .3s ease-in-out;
    transition: all .3s ease-in-out;
}
.scroll-indicator {
    cursor: pointer;
    height: 45px;
    width: 45px;
    background: // some background
    background-size: 22px 14px;
    border-radius: 100%;
    z-index: 9999;
    opacity: 0.6;
    -webkit-transition: all .3s ease-in-out;
    -moz-transition: all .3s ease-in-out;
    transition: all .3s ease-in-out;
    -webkit-animation: pulseDown 3s ease-in-out infinite;
    -moz-animation: pulseDown 3s ease-in-out infinite;
    animation: pulseDown 3s ease-in-out infinite;
    -webkit-animation-delay: 1.5s;
    -moz-animation-delay: 1.5s;
    animation-delay: 1.5s;
}


text:
Q: Problem with ground between two batteries and a battery level notificator I'm trying to make an inverter (DC to AC), for a university class project.
The DC source is powered from  two DC batteries 12V each, then this provides energy to a SPWM generator which then goes to an H-bridge, then a transformer, and finally to a lowpass filter.
My problem begins with Proteus. When I try to make a battery level indicator, it has to be one for each battery. Besides that, ground must be connected between the (-) terminal of the first battery and the (+) terminal of the second one.
In picture 1 and 2 are the circuits working for each battery, but when I try to connect both with the two batteries connected and the ground, it goes all to 0V as seen in picture 3.
What do I need to do to solve this, but meeting the requirements -ground  between the two batteries and a battery level indicator system for each battery. The LEDs are supposed to turn on when the battery level is less than 11V.

A: You are choosing a dual Op Amp comparator correctly but not choosing a differential input to bias -Vbat  as a a differential amp with positive bias to reach Vin >=0 for common mode.  The voltage divider must be biased to +Vcc and not 0V for -Vbat to be compared.  then output on both LEDs is >0V so you do not connect Anode to 0V but rather and comparator switches to 0V not -Vee.  This a common design flaw.


text:
Q: C++ Code Stability between different g++ versions We've been trying to track down some strange behavior in our large legacy app for the past few months. It suffers from random and occasional memory corruption, vtable corruption (??), and other strange and random behavior like infinite loops in std::rbl_tree, std::map, and even std::string s = "abcd".
The target machine is 32-bit Centos 6 so we started with the built-in g++ 4.4 but address sanitizer wasn't available, so moved to 4.8 in devtoolset-2 and now have compiled gcc 4.9 from source.
Valgrind (v3.8.1) doesn't work with any of them - it gives unhandled instruction bytes: 0xC5 0xF9 0x6E 0xC5
AddressSanitizer reports different errors between gcc 4.8 and 4.9, and often reports bogus global-buffer-overflow errors like

Error reading 0x080e3ad4 where 0x080e3ad4 is located 0 bytes to the
  right of global variable 'x'

Except that 0x080e3ad4 is the address of x!
Worse yet, the erroneous behavior is different between gcc versions.
I've read a lot of posts comparing the speed advantages of gcc v5, 6, 7, but nothing about stability of the code they produce.
Since it takes a lot of effort to build a new gcc and reconfigure our large app to build with it, and test & package the distribution for customers, here's the question:

*

*What improvement in stability come with a newer gcc?

*How has AddressSanitizer been improved?

*Can we expect Valgrind to not barf out on illegal op codes?

All suggestions appreciated.  Its been months on this problem.
EDIT
To be clear, I'd like to get instrumentation that works (eg AddressSanitizer, Valgrind or others) so we can fix the underlying behavior.  Those debug tools working or not is tied to the compiler environment rather than our C++ program.  (eg. There is no assembler in the program so Valgrind should understand the instructions from the compiler and/or the compiler should emit opcodes that are understood by Valgrind, as one example.
EDIT II
G++ compiler flags (for debug compile)
/usr/local/gcc-4.9.4/bin/c++4.9 -c -std=c++98  -m32 -g -ggdb -O0
-Wall -Wextra -Wno-sign-compare -Wcast-align -fdiagnostics-color=auto
-ftemplate-depth=32 -march=native -fPIC -o xx.o xx.cpp

Target hardware: i5-6500


text:
Q: Ways to say "My phone ran out of power" What are some other ways to say "My phone ran out of power", meaning my battery got depleted. What is the level of formality of each one?

A: Some other ways (including some provided in the comments):
Formal

*

*My phone's battery is completely discharged - @Canadian_Yankee

*My phone's battery is drained.

Informal

*

*My phone ran out of juice - @Canadian_Yankee

*My phone is out of juice

*My phone ran out of battery

*My phone is out of battery

*My phone died - @TypelA

*My phone went out


text:
Q: Infinitely many intermediate fields between F and L Let $k = F_p$, the finite field of $p$ elements and $F = k(t, u)$ where $t$ and
$u$ are independent variables. Let $α$ and $β$ be roots of $x^p − t$ and $x^p − u$ respectively. Let $L = F(α, β)$. Consider the intermediate fields $F ⊂
F(α+λβ) ⊂ L$ as $λ$ varies over all elements of $F$. I want to show there are infinitely many intermediate fields between F and L in the following way.
So let's say $λ ≠ µ$ are two elements of $F$ such that $F(α + λβ) = F(α + µβ)$, how to show that $α, β ∈ F(α + λβ)$? If I can do this then I can conclude that $F(α + λβ) = F(α, β)$ which is not possible right? :O

A: Assume that $F(\alpha + \lambda\beta) = F(\alpha + \mu\beta)$ for some $\lambda, \mu \in F$. Then we have that $\alpha + \mu\beta \in F(\alpha + \lambda\beta)$ and so:
$$(\mu - \lambda)\beta = \alpha + \mu\beta - (\alpha + \lambda\beta) \in F(\alpha + \lambda\beta)$$
This implies that $\beta \in F(\alpha + \lambda\beta)$, as $(\mu - \lambda)$ is an element of $F$. From here it's not hard to conclude that $\alpha = \alpha + \lambda\beta - \lambda\beta \in F(\alpha + \lambda\beta)$. Therefore as you've noted we get that $F(\alpha + \lambda\beta) = F(\alpha, \beta)$.
To see that this equality is impossible, note that:
$$(\alpha + \lambda\beta)^p = \alpha^p + \lambda^p\beta^p = t + \lambda^pu \in F$$
This means that $[F(\alpha + \lambda\beta):F] = p$, while $[F(\alpha,\beta):F]=p^2$, which is a contadiction.


text:
Q: How many crypto currencies support in bitpay? I am using following coins lite coin, doge coin, aurora coin, world coin, max coin, prime coin, peer coin and feather coin. In those coins are supported in bit pay online payment gateway.

A: No, Bitpay does not support altcoins. I dont think that they ever will! (http://www.reddit.com/r/litecoin/comments/1rq4pf/bitpay_will_not_support_litecoin_and_other/)


text:
Q: Optimize live elements' selectors in jQuery I read a lot about optimization in jQuery in some links below:

*

*jQuery Website , Performance

*jQuery Best Practices - Greg Franko

*jQuery Coding Standards and Best Practices

*14 Helpful jQuery Tricks, Notes, and Best Practices
and more ...
But none of them mentioned for .on() caching selectors. I don't know if there is any way to use cached elements in these kind of selectors.
for example I have a lot of these selectors in my script.js file.
$(document).on('click', '.menu li.remove', function(e){ ... });
$(document).on('click', '.menu li.edit', function(e){ ... });
$(document).on('click', '.menu li.action', function(e){ ... });
$(document).on('click', '.menu li.anotherAction', function(e){ ... });

and much more. .menu is a menu and can be anywhere in document, so I can't use specific id container to select it. like this:
$('#sidebar').on('click', '.menu li.action', function(e){ ... });

is there any way to optimize these selectors. Checking for existence maybe, caching .menu if it is possible.

A: When you need to eek out every last bit of performance, you probably need to ditch abstractions.
If you do your own delegation, you'll certainly see a performance improvement.
Because in the example you gave, all the delegation is identical except for the class name, I'd bind a single handler, put the code in separate functions, and then examine the e.target and its ancestors manually looking for the .menu li. If that's found, then check the class of the li, and invoke the correct handler.
var handlers = {
    remove: function() {/*your code*/},
    edit: function() {/*your code*/},
    action: function() {/*your code*/},
    anotherAction: function() {/*your code*/}
};

var targets = Object.keys(handlers);

document.onclick = function(e) {
    e = e || window.event;
    var li;
    var node = e.target || e.srcElement;
    var targetClass;

    do {
        if (!li) {
            if (node.nodeName === "LI") {
                li = node;
            }
        } else if (node.className.indexOf("menu") > -1) {
            targetClass = li.className
            break;
        }
    } while(node = node.parentNode);

    if (!targetClass)
        return;

    for (var i = 0; i < targets.length; i++) {
        if (targetClass.indexOf(targets[i]) > -1) {
            handlers[targets[i]].call(li, e);
        }
    }
}

In the code above, as we traverse up from the e.target, we first check to see if we're on an li. If so, grab it and continue one.
As we continue, we no longer need to check for li elements, but we now need to check for an element with the menu class. If we find one, we grab the class name of the li we previously found and then halt the loop.
We now know we have our menu li.someClass element. So then we can use the class that we found on the li to look up the proper function to invoke from our list of functions we made above.

You should note that my .indexOf() class testing is ad hoc, and could result in false positives. You should improve it. Also, the code needs more tweaking since we're caching the li without knowing if it actually has a class that we're interested in. That should be fixed as well.
I'll leave it to you to add the necessary tweaks if you desire. :-)

A: I personally think you are worrying about speed where speed is not an issue.
If the menus are not loaded dynamically, there is nothing stopping you from combining delegated event handlers with normal jQuery selectors to target more of the closer elements (e.g. your .menu class):
e.g.
$('.menu').on('click', 'li.remove', function(e){ ... })
 .on('click', 'li.edit', function(e){ ... })
 .on('click', 'li.action', function(e){ ... })
 .on('click', 'li.anotherAction', function(e){ ... });

This will create a handler on each menu (so closer to the elements).
If your menus are dynamically loaded, then your existing code is perfectly fine, as my understanding is that delegated event handlers only apply the selector argument to the elements in the bubble chain. If that is the case, delegated events will be pretty darn fast anyway. Certainly faster than you can click your mouse! I have never had speed issue with delegated event handlers and I probably overuse them in my plugins (I always assume dynamic content in those).