text:
Q: wxGrid row numbers don't sync with SQLite3 database I have a wx.Grid that is populated from a SQLite3 database. The user enters the data in text controls and then clicks the "Commit Values" button. The values are written to the database and then the function loads the database into the grid. The database has an index and it starts at '1'. The table looks like this:
CREATE TABLE Cycles (
    index INTEGER,
    First INTEGER,
    Second    TEXT,
    Third INTEGER,
    Fourth    INTEGER,
    Fifth INTEGER,
    Sixth INTEGER,
    Seventh   INTEGER,
    Eighth    INTEGER,
    PRIMARY KEY(index)
When the database loads, the column numbers jump and begin at '0' instead of '1' and the first row of values populate row '1'leaving row '0' blank. If I change the row number definition in onLoadTable() to 'rowNumb = row +1', then, when the "Commit Values" button is clicked, the rows begin at '1' but the values populate the second row leaving row '1' blank.
Here is fully functional, reproducible code:
import wx
import wx.lib.scrolledpanel as scrolled
import sqlite3 as sqlite
import wx.grid as gridlib

class MasterFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY,"",size=(900,400))

        panel = wx.Panel(self, -1)

        self.db = db
        self.c = self.db.conn.cursor()

        vbox = wx.BoxSizer(wx.VERTICAL)

        self.grid = wx.grid.Grid(panel)
        rowN = self.c.execute('SELECT Count(*) FROM Cycles')
        val = rowN.fetchone()
        rowNum = val[0] + 3
        self.grid.CreateGrid(rowNum,8)
        self.grid.Scroll(0,0)

        self.enterBtn = wx.Button(panel, -1, "Commit Values")
        self.Bind(wx.EVT_BUTTON, self.onEnter, self.enterBtn)

        vbox.Add(self.enterBtn)
        vbox.Add(self.grid)
        panel.SetSizer(vbox)
        panel.Fit()

    def onEnter(self, event):
        First = 1
        Second = 'mine'
        Third = 1
        Fourth = .5
        Fifth = 1
        Sixth = 20
        Seventh = 4
        Eighth = 10

        self.c.execute("INSERT INTO datatable VALUES (NULL,?,?,?,?,?,?,?,?);",(First,Second,Third,Fourth,Fifth,Sixth,Seventh,Eighth))
        self.db.conn.commit()
        self.onLoadTable()

    def onLoadTable(self):
        self.grid.ClearGrid()
        for row in range(12):
            rowNumb = row #+ 1
            self.grid.SetRowLabelValue(row, "%s" %rowNumb)

        meta = self.c.execute('SELECT * from datatable')
        labels = []
        for i in meta.description:
            labels.append(i[0])
        labels = labels[1:]
        for i in range(len(labels)):
            self.grid.SetColLabelValue(i, labels[i])

        all = self.c.execute('SELECT * from datatable')
        for row in all:
            row_num = row[0]
            cells = row[1:]
            for i in range(len(cells)):
                if cells[i] != None and cells[i] != "null":
                    self.grid.SetCellValue(row_num, i, str(cells[i]))
        self.db.conn.commit()

class GetDatabase():
    def __init__(self):
        self.conn = sqlite.connect("data4.db")

if __name__ == "__main__":
    db=GetDatabase()
    app = wx.App(False)
    frame = MasterFrame()
    frame.Show()
    app.MainLoop()

If I add  ...WHERE index=%d" %rowNumb  to the SELECT statements I get sqlite3.OperationalError: near "index": syntax error.

A: Grid starts at (0,0) so try subtracting 1 from row_num i.e.
self.grid.SetCellValue(row_num-1, i, str(cells[i]))


text:
Q: Call to undefined function curl_init() error I am on a Win 64 bit OS, php 5.6.8 using Eclipse PDT to develop PHP.
I have come across this  Call to undefined function curl_init() error.
I removed the ; preceeding extension=php_curl.dll in php.ini .Restarted the Apache server but still getting the same error.
Any hint where I am going wrong?

A: Just add php folder path in PATH environment variable..... ;)

A: Your issue is probably already solved. But for those still searching, please find my answer here.
It might be the the wrong Path being pointed at.
My answer in the Link ( Call to undefined function curl_init() even it is enabled in php7 ) says:
Your Filepath is probably incorrect
Check the Apache error log in
/var/log/apache2/error.log

if the called path or filename does match your real path in e.g.
/usr/lib/php/20151012/php_curl.so

In my case it's been the same path, but "the php_" was missing
/usr/lib/php/20151012/curl.so

So I changed the path / filename accordingly in
/etc/php/7.0/cli/conf.d/20-curl.ini

from
extension=php_curl.so

into
extension=curl.so

A: I had the same issue and after hours, I found a message here :
http://php.net/manual/curl.installation.php
which says, "Upgrading to php 5.6.9 on Windows 7 x64 cURL no longer is recognized. No errors on server start package just not available and didn't show in phpinfo.php. deplister.exe was ok
I fixed coping the following list files from php folder (in my case D:\xampp\php) libeay32.dll, libssh2.dll, ssleay32.dll to c:\xampp\apache\bin (or your apache\bin path), restart Apache and works fine, Apache's libraries were outdated."
It worked for me.
Not easy to find, right ? :-)

A: Have 2 steps:

*

*Go to php.ini and remove ; in line ;extension=curl (in window). With Linux you can find curl to un-comment it.

*I download internet 3 files: libeay32.dll, libssh2.dll, ssleay32.dll. And past to {Apache Folder}/bin. Then restart apache.

You can refer this link if need https://www.php.net/manual/en/curl.installation.php
It is OK now.

A: With PHP 7.2.4 and Apache 2.4.33 both installed on Windows 10x64 I got the same error: call to undefined function curl_init().
php.ini had extensions directory path and the php_curl extension defined and uncommented.
Tried suggestions from earlier answers, no go.
Fixed it by adding my PHP location to system PATH (as C:\php) and restarting httpd (Apache2.4 service in my case).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting MapServer to show raster? I am trying to use MapServer to display a raster image (png). That's it for now at least. However, I am having no luck. When I visit my map by using a link like:
*http://myurl.com/cgi-bin/mapserv?map=/path/to/file.map&layer=base&mode=map
I get the following error:

msLoadMap(): Regular expression error. MS_DEFAULT_MAPFILE_PATTERN validation failed. msEvalRegex(): Regular expression error. String failed expression test.

When I use shp2img:
shp2img -m file.map -o myimage.png -all_debug 5

I get no errors, but the image that's produced is completely gray except for the upper right quadrant which is white. This is nothing like my raster image.
My mapfile:
MAP
    SHAPEPATH     "/home/name/public_html/dir"
    IMAGETYPE     PNG
    EXTENT        -180 -90 180 90
    SIZE          800 600
    IMAGECOLOR    155 155 155
    UNITS         DD
    STATUS        ON
    DEBUG         ON

    LAYER
        NAME      "base"
        DATA      "/home/name/public_html/dir/image.png"
        STATUS    ON
        TYPE      RASTER
    END
END

What am I doing wrong?

A: Your map file is fine.
I've seen the Regular expression error. MS_DEFAULT_MAPFILE_PATTERN validation failed error when the extension to the map file in the URL is incorrect e.g.
.map Works: http://myurl.com/cgi-bin/mapserv?map=/path/to/file.map&layer=base&mode=map
.map2 fails with above error: http://myurl.com/cgi-bin/mapserv?map=/path/to/file.map2&layer=base&mode=map
In the MapServer source code you can see the regular expression used to check for a valid mapfile (.xml is also now allowed):
#define MS_DEFAULT_MAPFILE_PATTERN "\\.map$"

If your path and mapfile are correctly defined then it must be something in your URL request. Do you have any URL rewriters active? Maybe try and look at the web server logs to see the exact URL it receives.


text:
Q: Sort an html list with javascript I have a set of three list items that I would like to automatically display from high to low on page load. Ideally using jquery or javascript.

32

170

28

Each list item needs its own ID because they each have individual background images. The numbers must text nodes so that a user can edit them.

A: You can try this
var ul = $(".list:first");
var arr = $.makeArray(ul.children("li"));

arr.sort(function(a, b) {
    var textA = +$(a).text();
    var textB = +$(b).text();

    if (textA < textB) return -1;
    if (textA > textB) return 1;

    return 0;
});

ul.empty();

$.each(arr, function() {
    ul.append(this);
});

Live example : http://jsfiddle.net/B7hdx/1

A: There's also this small jQuery plugin. Which would make your sort nothing more than:
$('.list>li').tsort({attr:'id'});

A: you can use this lightweight jquery plugin List.js cause

*

*it's lightweight [only 3K script]

*easy to implement in your existing HTML table using class

*searchable, sortable and filterable

HTML

Luke

John

Javascript
var options = {
    valueNames: ['name']
};
var myList = new List('my-list', options);

A: This code will sort that list assuming there is only one .list item:
function sortList(selector) {
    var parent$ = $(selector);
    parent$.find("li").detach().sort(function(a, b) {
        return(Number(a.innerHTML) - Number(b.innerHTML));
    }).each(function(index, el) {
        parent$.append(el);
    });
}

sortList(".list");

You can see it work here: http://jsfiddle.net/jfriend00/FjuMB/
To explain how it works:

*

*It gets the .list parent object.

*It finds all the
 child objects.

*It removes all the
 child objects from the DOM, but preserves their data

*It sorts the li objects using a custom sort function

*The custom sort function gets the HTML in the li tag and converts it to a number

*Then, traversing the array in the newly sorted order, each li tag is appended back onto the original parent.

The result is that they are displayed in sorted order.
Edit:
This improved version will even sort multiple list objects at once:
function sortList(selector) {
    $(selector).find("li").sort(function(a, b) {
        return(Number(a.innerHTML) - Number(b.innerHTML));
    }).each(function(index, el) {
        $(el).parent().append(el);
    });
}

sortList(".list");

Demo: http://jsfiddle.net/jfriend00/RsLwX/

A: Non jquery version (vanilla javascript)
Benefits: the list is sorted in place, which doesn't destroy the LI's nor remove any events that may be associated with them. It just shuffles things around
Added an id to the UL:

32

170

28

and the vanilla javascript (no jquery)
// Grab a reference to the UL
var container = document.getElementById("myList");

// Gather all the LI's from the container
var contents = container.querySelectorAll("li");

// The querySelector doesn't return a traditional array
// that we can sort, so we'll need to convert the contents
// to a normal array.
var list = [];
for(var i=0; i<contents.length; i++){
    list.push(contents[i]);
}

// Sort based on innerHTML (sorts "in place")
list.sort(function(a, b){
    var aa = parseInt(a.innerHTML);
    var bb = parseInt(b.innerHTML);
    return aa < bb ? -1 : (aa > bb ? 1 : 0);
});

// We'll reverse the array because our shuffle runs backwards
list.reverse();

// Shuffle the order based on the order of our list array.
for(var i=0; i<list.length; i++){
    console.log(list[i].innerHTML);
    container.insertBefore(list[i], container.firstChild);
}

And the fiddle proof: https://jsfiddle.net/L27gpnh6/1/

A: This will probably be the fastest way to do it, since it doesn't use jQuery:
function sortList(ul){
    var new_ul = ul.cloneNode(false);

    // Add all lis to an array
    var lis = [];
    for(var i = ul.childNodes.length; i--;){
        if(ul.childNodes[i].nodeName === 'LI')
            lis.push(ul.childNodes[i]);
    }

    // Sort the lis in descending order
    lis.sort(function(a, b){
       return parseInt(b.childNodes[0].data , 10) -
              parseInt(a.childNodes[0].data , 10);
    });

    // Add them into the ul in order
    for(var i = 0; i < lis.length; i++)
        new_ul.appendChild(lis[i]);
    ul.parentNode.replaceChild(new_ul, ul);
}

Call the function like:
sortList(document.getElementsByClassName('list')[0]);

You can sort other lists the same way, and if you have other elements on the same page with the list class you should give your ul an id and pass it in using that instead.
Example JSFiddle
Edit
Since you mentioned that you want it to happen on pageLoad, I'm assuming you want it to happen ASAP after the ul is in the DOM which means you should add the function sortList to  the head of your page and use it immediately after your list like this:

    ...

    ...

32

170

28

    ...

A: One method could be to sort an array (well, a jQuery object) of the li elements and replace the contents (using the html method) of the ul with the sorted array of elements:
$(".list").html($(".list li").sort(function(a, b) {
     return parseInt($(b).text(), 10) - parseInt($(a).text(), 10);
}));

Here's a working example.

A: You can use this method:
var mylist = $('ul');
var listitems = mylist.children('li').get();
listitems.sort(function(a, b) {
   var compA = $(a).text().toUpperCase();
   var compB = $(b).text().toUpperCase();
   return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
})
$.each(listitems, function(idx, itm) { mylist.append(itm); });

Check the article here:
http://www.onemoretake.com/2009/02/25/sorting-elements-with-jquery/
Edit: There is a very cool jquery plugin that does that : http://tinysort.sjeiti.com/

A: Something like this should help:
var $parent = $(".list");

$(".list li").sort(function (a, b) {
    return window.parseInt($(a).text(), 10) - window.parseInt($(b).text(), 10);
}).remove().each(function () {
    $parent.append($(this));
});

A: using jQuery for help:
var sortFunction = function(a, b) {
    return (+($(b).text())) - (+($(a).text()));
}
var lis = $('ul.list li');
lis = Array.prototype.sort.call(lis, sortFunction);

for (var i = 0; i < lis.length; i++) {
    $('ul.list').append(lis[i]);
}

Fiddle Link

A: Sort jQuery collection as usual array and then append each element back in correct order.
$(".list li").sort(function(a, b) {
    return parseInt($(b).text(), 10) - parseInt($(a).text(), 10);
}).appendTo('.list');

http://jsfiddle.net/zMmWj/


text:
Q: Color Coding Shades of Hex Colors Criteria I am following this Jetpack Compose Codelab on Theming and I'm trying to grasp the logic used to name these shades of the Red Color but I am lost.

Here the Red700 is #DD0D3C but when I check with the Material Design Palette, Red700 corresponds to #D32F2F

When I Google the Hex Value for Red700 I am getting mixed results on the value. What I know is that the shades represent a different percentage of the Red Color but can't understand the logic in naming the shades.
Therefore my question is what is the criteria for naming shades of a color. I would also be interested to know if there is a tool online to generate uniformly named shades of a color.

A: I think I got a handle on this one.
The simple answer is that there is no uniform values for Shades of a color. From one color you can generate ten, twenty or more shades and it is up you to rename the shades depending on your scale.
In the process I learnt that a Color Shade is a hue or mixture of pure colors to which only black is added. It contains no white or gray. Shade darkens the color.
I also discovered this awesome Online Tool for Generating Color Shades.


text:
Q: jssh telnet fails even after installing the add-on on Linux I am working with ruby gem "firewatir (1.6.5)" and mozilla
    Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.9) Gecko/20100330 Fedora/3.5.9-1.fc11   Firefox/3.5.9.<\i>
I have installed the jssh.*.xpi extension for mozilla 3.5 for Linux and it works for sometime.
But the problem is that after running some scripts I get the error that "failed to telnet to localhost at port 9997".After this, sometimes re-installing the extension works, but sometimes it does not.
Is there any other way of ensuring that the jssh extension works?
Thanks and Regards,
Anjali C. G.

A: Did not play with Watir on Linux a lot, but the last time I have tried to drive Firefox with watir-webdriver, it worked just fine: http://zeljkofilipin.com/2010/01/12/watir-on-webdriver/


text:
Q: Зачем глубокое понимание HashMap Не имею какого-то большого опыта в разработке, всего несколько лет, поэтому задам неочевидный лично мне вопрос, который в обычной жизни озвучивать как-то страшновато) Зачем на собеседованиях настолько жестко гоняют по HashMap ? Со всем остальным прям понятно, но зачем нам глубокое понимание того как она работает? В какой конкретный момент программисту надо прям понимание как оно работает? Прям жизненно надо понимать как происходит в неё вставка? Есть какой-то момент, когда у нас сильно просядет перфоманс из-за непонимания? Есть какая-то причина держать всё это в голове? Какие кейсы в прикладном программировании когда нам надо как-то жестко использовать хэмапу или хэштейбл что бы всем знать эти нюансы? Просто есть ощущение, что упускаю какую-то гигантскую часть жизни и весь мир использует хэшмапы как не в себя, при том что я за последние три года использовал их максимум раз 10 наверное, без каких-либо сложных кейсов.
И ещё, раз уж начал глупые вопросы. Почему исходники  той же хэшмапы настолько блин тяжело читать? Почему те же исходники спринга всегда прекрасны и понятны, но тут прям какой-то ад. Так сделано, потому что процессору быстрее этот страшный код перемалывать?

A: Вообще, я бы сказал, так:

*

*Знание того как устроены кишки HashMap не является обязательной историей

*Однако знание почему HashMap важен - это часть обязательной программы

Исходники HashMap это сущий адъ - соглашусь, не в последнюю очередь это благодаря тому, что его несколько раз переписывали - в частности в Java 8 он реализован через бинарное дерево, а в старых версиях это просто через список/массив.
Начнине с версии для Java 7 - там код более читабельный.


text:
Q: How to find period of a vector in MATLAB? By the period I mean this :
Say I have a vector
v = [1,1,1 , 2,2,2 , 3,3,3];
period(v)

ans = 3

This vector should return 3 since the value changes in every 3rd item.
I can simply return the first index where the value changes, but I'm wondering if there is a built-in function, preferrably also working with non-uniform input. i.e. the last sequence could be smaller than 3.
The closest thing I could find is seqperiod but it returns 9 (the length) for this vector.
Thanks for any help!

A: If you know that the period remains constant for the entire array, you could use the diff() function and pull out the location of the first value like this:
>> diff_out = find(diff(v));
>> diff_out(1)

    ans =
    3

Alternatively, if the period varies, you could run an additional diff to get a vector that represents number of elements between changes like so:
>> diff([0,find(diff(v))])
   ans =

   3     3


text:
Q: Why does .fadeOut() not work, but .hide() works fine when hiding appended div in jquery? I want to show a div and remove it after few seconds. It's just that easy.
So in my html I've got:

And I've got this function:
function showWarning(text) {
            $('
'+text+'
').appendTo('#msg').hide().fadeIn('fast').delay(1000).queue(function() {
                $(this).fadeOut();
        });
    }

I can't find any way to make this work. fadeOut() is called but nothing happens on screen.
If I change fadeOut() to hide() it works fine. However... If I try hide(500) then it won't work.
I assume this is something trivial - beginner mistake - but I can't find it.
Thanks

A: The fadeIn() must not be finished running, use a callback function instead before doing your fadeOut.
$('
'+text+'
').appendTo('#msg').hide().fadeIn('fast', function () {
    $(this).fadeOut();
});

A: function showWarning(text) {
    $('
', {text: text}).fadeIn('fast', function() {
        $(this).delay(1000).fadeOut(600);
    }).appendTo('#msg');
}

FIDDLE

A: like so: http://jsfiddle.net/b7EV8/
function showWarning(text) {
    $('
' + text + '
').appendTo('#msg').hide().fadeIn('fast', function() {
        $('#msgtext').delay(1000).fadeOut();
    });
}

showWarning('hello')

A: function showWarning(text) {
  $('
').text(text).appendTo('#msg').hide().fadeTo(400,1,function(){
      $(this).delay(1000).fadeOut();
  });
}

demo


text:
Q: Intel Joule 570x Expansion Board;Ubuntu 16.04;mraa;SPI not working Platform
Board:Intel Joule 570X Expansion Board
OS: uname -a
Linux scout-570x-DVT3 4.4.0-1000-joule #0+joule12-Ubuntu SMP PREEMPT Fri Jan 6 04:28:41 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 16.04.1 LTS
Release:    16.04
Codename:   xenial
MRAA
mraa-gpio version
Version v1.7.0-11-g47c21e0 on INTEL JOULE EXPANSION
Question
Do I need to enable spidev for libmraa to work. If so how do I enable it?
Program:
Source
#include "mraa.h"
#include <unistd.h>
#include <stdint.h>
#include<iostream>

int main(int argc, char** argv)

{
    mraa_init();

    //! [Interesting]

    mraa_spi_context spi;

    spi = mraa_spi_init(0);

    printf("Hello, SPI initialised\n");

    std::cout<<"spi init"<<std::endl;

    uint8_t data[] = { 0x00, 0x32 };

    uint8_t* recv;

    std::cout<<"assigning  data"<<std::endl;

    int i=90;

    data[1] = i;

    std::cout<<"spi write coming up"<<std::endl;

    recv = mraa_spi_write_buf(spi, data, 2);

    if (recv==NULL)

        std::cout<<"error in writing"<<std::endl;

   printf("Writing -%i\n", i);

    //printf("RECIVED-%i-%i\n", recv[0], recv[1]);

    usleep(100000);

    //! [Interesting]

}

Output
Hello, SPI initialised
spi init
assigning  data
spi write coming up
error in writing
Writing -90
Debug
journalctl -t libmraa
-- Logs begin at Thu 2017-04-13 12:04:32 EDT, end at Thu 2017-06-01 18:28:10 EDT. --
Jun 01 18:18:37 scout-570x-DVT3 libmraa[2837]: libmraa version v1.7.0-11-g47c21e0 initialised by user 'scout' with EUID 1001
Jun 01 18:18:37 scout-570x-DVT3 libmraa[2837]: Adding i2c bus found on i2c-4 on adapter i2c_designware.0
Jun 01 18:18:37 scout-570x-DVT3 libmraa[2837]: Adding i2c bus found on i2c-9 on adapter i2c_designware.5
Jun 01 18:18:37 scout-570x-DVT3 libmraa[2837]: Adding i2c bus found on i2c-10 on adapter i2c_designware.6
Jun 01 18:18:37 scout-570x-DVT3 libmraa[2837]: Adding i2c bus found on i2c-5 on adapter i2c_designware.1
Jun 01 18:18:37 scout-570x-DVT3 libmraa[2837]: Adding i2c bus found on i2c-6 on adapter i2c_designware.2
Jun 01 18:18:37 scout-570x-DVT3 libmraa[2837]: libmraa initialised for platform 'INTEL JOULE EXPANSION' of type 13
Jun 01 18:18:37 scout-570x-DVT3 libmraa[2837]: spi: Failed opening SPI Device. bus:/dev/spidev32765.0. Error 2 No such file or directory
Jun 01 18:18:37 scout-570x-DVT3 libmraa[2837]: spi: write_buf: context is invalid
Jun 01 18:24:50 scout-570x-DVT3 libmraa[3049]: libmraa version v1.7.0-11-g47c21e0 initialised by user 'scout' with EUID 1001
Jun 01 18:24:50 scout-570x-DVT3 libmraa[3049]: Adding i2c bus found on i2c-4 on adapter i2c_designware.0
Jun 01 18:24:50 scout-570x-DVT3 libmraa[3049]: Adding i2c bus found on i2c-9 on adapter i2c_designware.5
Jun 01 18:24:50 scout-570x-DVT3 libmraa[3049]: Adding i2c bus found on i2c-10 on adapter i2c_designware.6
Jun 01 18:24:50 scout-570x-DVT3 libmraa[3049]: Adding i2c bus found on i2c-5 on adapter i2c_designware.1
Jun 01 18:24:50 scout-570x-DVT3 libmraa[3049]: Adding i2c bus found on i2c-6 on adapter i2c_designware.2
Jun 01 18:24:50 scout-570x-DVT3 libmraa[3049]: libmraa initialised for platform 'INTEL JOULE EXPANSION' of type 13
Jun 01 18:28:04 scout-570x-DVT3 libmraa[3115]: libmraa version v1.7.0-11-g47c21e0 initialised by user 'scout' with EUID 1001
Jun 01 18:28:04 scout-570x-DVT3 libmraa[3115]: Adding i2c bus found on i2c-4 on adapter i2c_designware.0
Jun 01 18:28:04 scout-570x-DVT3 libmraa[3115]: Adding i2c bus found on i2c-9 on adapter i2c_designware.5
Jun 01 18:28:04 scout-570x-DVT3 libmraa[3115]: Adding i2c bus found on i2c-10 on adapter i2c_designware.6
Jun 01 18:28:04 scout-570x-DVT3 libmraa[3115]: Adding i2c bus found on i2c-5 on adapter i2c_designware.1
Jun 01 18:28:04 scout-570x-DVT3 libmraa[3115]: Adding i2c bus found on i2c-6 on adapter i2c_designware.2
Jun 01 18:28:04 scout-570x-DVT3 libmraa[3115]: libmraa initialised for platform 'INTEL JOULE EXPANSION' of type 13
Jun 01 18:28:10 scout-570x-DVT3 libmraa[3116]: libmraa version v1.7.0-11-g47c21e0 initialised by user 'scout' with EUID 1001
Jun 01 18:28:10 scout-570x-DVT3 libmraa[3116]: Adding i2c bus found on i2c-4 on adapter i2c_designware.0
Jun 01 18:28:10 scout-570x-DVT3 libmraa[3116]: Adding i2c bus found on i2c-9 on adapter i2c_designware.5
Jun 01 18:28:10 scout-570x-DVT3 libmraa[3116]: Adding i2c bus found on i2c-10 on adapter i2c_designware.6
Jun 01 18:28:10 scout-570x-DVT3 libmraa[3116]: Adding i2c bus found on i2c-5 on adapter i2c_designware.1
Jun 01 18:28:10 scout-570x-DVT3 libmraa[3116]: Adding i2c bus found on i2c-6 on adapter i2c_designware.2
Jun 01 18:28:10 scout-570x-DVT3 libmraa[3116]: libmraa initialised for platform 'INTEL JOULE EXPANSION' of type 13
Question
Do I need to enable spidev for libmraa to work. If so how do I enable it?


text:
Q: SQLite library variant only for dump I am developing application which reads (only reads!) data from SQLite database file; but size of result binary is limited. I've tried to make SQLite smaller (by specifying SQLITE_OMIT_* preprocessor definitions), but size of result EXE is 490kb, which is enormous for my purpose. Is there a small SQLite library specified only for reading all stored data? No requests, no optimizations, just reading all tables data from database file.
I use Microsoft Visual Studio 2010.


text:
Q: result in tuple for conditional expression using Python I'm trying see how I can use a tuple in conditional statement like this:
(False_condition, True_Condition)[conditional expression]

Assign example values:
x, y = 4, 7

Conditional:
("x is greater than y", "x is less than y") [x < y]

Output:
'x is less than y'

Problem: What if x == y?
Assign value:
x,y = 5,5

Conditional:
("x is greater than y", "x is less than y", "x is equal to y") [x < y]

Output:
"x is greater than y"

Question: In this method, can you NOT have a third option?

A: You can get to what you want with this:
print(( "x is less than y", "x is equal to y", "x is greater than y")[ [x<y,x==y,x>y].index(True)])

A: Here's what you want
("x is greater than y", "x is less than y", "x is equal to y")[(x < y) or (x==y)*2]

Looks weird, ha?
That's because in the square brackets after a tuple python expects a number.
And the thing is, conditional false evaluates to 0 and conditional true evaluates to 1 with implicit type coercion.
So to make this work you would have to figure out a oneliner with conditionals, that will evaluate as follows:

*

*0 if x > y

*1 if x < y

*2 if x == y
We can utilize a so-called short-circuiting properties (see: https://stackoverflow.com/a/14892812).

*this guy x < y makes for the first 2 cases. We can separate it out with parenthesis: (x < y).

*with (x < y) or whatever, it will produce true (1) with the first statement if x < y and stop there, but if x < y happens to be false (0), then the or statement will proceed on evaluating the statement on the right, and return whatever, whatever it will be.

*so with (x < y) or (x==y)*2, if x < y then it will return true (1) right away, but if not: it will return (x==y)*2, which is either false (0) or true (1) multiplied by 2, so either 0 or 2.

Thus we have:

*

*0, if both x < y and x == y are false (i.e. x > y)

*1, if x < y returns true (1)

*2, if x < y is false, and x==y is true (1)

In fact, if we utilize short-circuiting properties of and statement, (x==y)*2 may be substituted to (x==y) and 2, yielding the same results, but running with a bit less CPU time. This approach may be used to refactor numbers of nested if statements that is intended to run a big number of times (usually > 1'000'000 times), and is called branchless programming.
P.S. You may want not to put everything in one line.

A: You can use lambdas they are more efficient because in lambda   only one expression will be evaluated unlike in tuple and Dictionary :
(lambda x,y:"x:{} is greater than y:{}".format(x,y), lambda x,y: "x:{} is less than y:{}".format(x,y) if x<y else "x:{} equal to y:{}".format(x,y))[x<=y](x,y)

A: What I usually use:
>>> for x, y in (1, 2), (2, 2), (2, 1):
        print('=<>'[(x < y) - (x > y)])

<
=
>

Although kukuster is right, or is faster. I might switch.
>>> for x, y in (1, 2), (2, 2), (2, 1):
        print('=<>'[(x < y) or -(x > y)])

<
=
>


text:
Q: Reducing memory size to ensure backgrounding in iOS When developing an app that uses Bluetooth Low Energy, there comes a time when the iOS device loses connection to the peripheral. (Sometimes for hours.)
In order to reconnect to an existing peripheral, the app must constantly scan in the background at a specific rate throughout the day(s), even when the app is backgrounded.
The problem is, iOS will not guarantee that your app will not get killed, due to memory constraints, etc.
Information found in the iPhone OS Programming guide states that:

Apps that work with Bluetooth peripherals can ask to be woken up if
  the peripheral delivers an update when the app is suspended. This
  support is important for Bluetooth-le accessories that deliver data at
  regular intervals, such as a Bluetooth heart rate belt. When an app
  includes the UIBackgroundModes key with the bluetooth-central value in
  its Info.plist file, the Core Bluetooth framework keeps open any
  active sessions for the corresponding peripheral. In addition, new
  data arriving from the peripheral causes the system to wake up the app
  so that it can process the data. The system also wakes up the app to
  process accessory connection and disconnection notifications.

The problem does not arise when the phone is connected to a device and the application is background.  It does happen, however, when the device is disconnected and the app is backgrounded.  In this specific case, the phone is no longer connected to the peripheral, and therefore no longer getting notifications.
Many people have discussed this before, either on Stack Overflow or the Apple forums, and I believe one of the Apple developers has responded saying:

We're aware of this issue and are trying to come up with a solution.
  Currently, there is no workaround."

My question is, is there a way to at least improve your chances of not getting killed by iOS due to memory constraints?
For example, an instant messaging app (IMO) seems to run quite nicely in the background. After days and days of not being used, the app will wake up and display a gChat message.
I'm questioning things such as

*

*Strong pointers

*Overall memory size

*Reducing memory size when app is backgrounded or minimized

*Reducing frequency of background operation

*Etc.

A: Why do you need background execution even when the bluetooth hardware is disconnected?
I don't think that you need to "rescan continuously" to reconnect again, if the hardware is "paired" with the iPhone/iPad, it will reconnect itself. Like a bluetooth headset. Or not?
AFAIK you have no chances to accomplish what you are asking for.
A normal App is always suspended when the user go back to home. The app has approx. 5 secs of background time to stop timers, save state ecc ecc.
There are special background modes that allows you to have more background time, and each of this mode (explained in the page you linked) has a different behavior.
About the bluetooth mode:
The descripted behavior is not an issue, but it's by design:

*

*the app is suspended

*when the app is suspended, it can be killed by the OS to free ram (and there are no tricks to avoid this), but the system will wake up if needed.

*the app is then awaken every time a notification is received (awaken from suspended state or lauched from "previously-killed" state)

*the app has 10 seconds to do tasks (save informations, ecc ecc). Moreover, can request +10 mins. of background time for a particular task

*after the 10 secs (or 10 min) the app is suspended again
The example you wrote about the chat app is incorrect: chat apps usually doesn't use any background mode, simply they forward you messages using push notifications. When you open the app, the app connect to a server that stores all your messages and download it.
You can get "more uptime" using location background mode (routing app can work in background), or using a combination of significative location changes (the app is awaken) and the 10 minutes background time, but I think that Apple will reject an app that "abuse" this.
Shortly, you have to design your app to support this behavior.

A: I found this in some more Apple documentation:

Memory Usage for Background Apps
Every app should free up as much memory as is practical upon entering
  the background. The system tries to keep as many apps in memory at the
  same time as it can, but when memory runs low it terminates suspended
  apps to reclaim that memory. Apps that consume large amounts of memory
  while in the background are the first apps to be terminated.
Practically speaking, your app should remove strong references to
  objects as soon as they are no longer needed. Removing strong
  references gives the compiler the ability to release the objects right
  away so that the corresponding memory can be reclaimed. However, if
  you want to cache some objects to improve performance, you can wait
  until the app transitions to the background before removing references
  to them.
Some examples of objects that you should remove strong references to
  as soon as possible include:
Image objects
Large media or data files that you can load again from disk Any other
  objects that your app does not need and can recreate easily later To
  help reduce your app's memory footprint, the system automatically
  purges some data allocated on behalf of your app when your app moves
  to the background.
The system purges the backing store for all Core Animation layers.
  This effort does not remove your app's layer objects from memory, nor
  does it change the current layer properties. It simply prevents the
  contents of those layers from appearing onscreen, which given that the
  app is in the background should not happen anyway. It removes any
  system references to cached images. (If your app does not have a
  strong reference to the images, they are subsequently removed from
  memory.) It removes strong references to some other system-managed
  data caches.

A: From the apple documentation i have always assumed the following:
connectPeripheral:options:
Establish a connection to the peripheral.

- (void)connectPeripheral:(CBPeripheral *)peripheral options:(NSDictionary *)options;
Parameters
peripheral
The peripheral to connect to.

options
A dictionary to customize the behavior of the connection. See CBConnectPeripheralOptionNotifyOnDisconnectionKey.

Discussion
**This never times out**. Use cancelPeripheralConnection: to cancel a pending connection.'

With the important part being on the fact that this never times out. I would assume this would hand off to the system so that it will connect automatically to the peripheral when it comes into range, thus removing the need for full backgrounding. Someone correct me if im wrong though!


text:
Q: Webview not loading url in android I have this  code.
@SuppressLint("SetJavaScriptEnabled")
@Composable
fun WebPageScreen(urlToRender: String) {
  AndroidView(factory = {
    WebView(it).apply {
      layoutParams = ViewGroup.LayoutParams(
          ViewGroup.LayoutParams.MATCH_PARENT,
          ViewGroup.LayoutParams.MATCH_PARENT
      )
      webViewClient = WebViewClient()
      loadUrl("https:....") //Url to be loaded
    }
  }, update = {
    it.loadUrl("https:...") //Url to be loaded
  })
}

Im trying to loading this url
When i load this page it is redirecting but showing error what is the problem and how to solve this?

A: Create this file
res/xml/network_security_config.xml
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">URL</domain>
    </domain-config>
</network-security-config>

add this line in manifest, inside application
android:networkSecurityConfig="@xml/network_security_config"

or
you can use this line in manifest
android:usesCleartextTraffic="true"

if your website is not using SSL yet, you can use certbot for free SSL

A: The webview is not working for particular url because the authorizer of that website have secured it in such a way. To Access that url in webview we need to get client certificate from the authority.


text:
Q: Does JavaScript have both a compiler and an interpreter? I've heard these terms used in different blogs and was curious if there was a difference.

A: A COMPILER converts source code (the code you've written) into machine code for the computer to understand.
An INTERPRETER directly executes your code without previously compiling it into machine code.

A: Javascript can be run with just an interpreter, the program that parses the script and executes the code.
However, some environments (like Chrome's V8 Javascript engine), will use a compiler to convert some of the Javascript code into a lower level language, which it can execute faster.  It's a big part of why Javascript can be executed at near-native speeds now.


text:
Q: Carousel in Bot Framework - continuously updating from database - upon scrolling it? Is it possible that carousel in Bot Framework (where it is allowed - like Messenger, Bot Emulator etc.) updates continuously (according to a database from which it reads data) after it was initially rendered and sent as a message to the user - without rerendering the whole carousel and resending it to the user?
Something like - .onFlipHandRightOnCarousel or .onFlipHandLeftOnCarousel - delete void HeroCards (where in database they are flagged as 'inactive') from already rendered carousel and rerender this new carousel without resending a new session.send(msg) to the user?

A: Modifying messages that have already been sent means modifying the chat history. This functionality will be highly channel-specific as it depends on how the client handles the history and what the client allows users to do to the history. Many channels do not support this functionality but some do. Generally speaking, if you as a user can go back and delete or edit messages in the chat history then a bot can too. If you as a user cannot then you should not expect a bot to be able to do it. But if you're working with a channel that does allow history edits then I imagine you should be able to edit the carousels if those are also supported.


text:
Q: Using closest_level to change titles while using transition_levels from the package gganimate in R I'm using transition_layers from gganimate to create an animated plot with a title that updates at each layer. Here is a simple reproducible example with two layers.
library(gganimate)

## data
df = data.frame(x=c(0,1),
                y=c(0,1))

## static plot
g = ggplot(data=df, aes(x=x, y=y))+
  geom_point()+
  geom_line()+
  labs(title = '{closest_layer}')
g

## animated plot
gg = g +
  transition_layers(layer_names=c('Layer 1: Points',
                                  'Layer 2: Line')) +
  enter_fade()
a = animate(gg, nframes = 50, end_pause = 20)
a

It works as expected to start, but then at the end of the animation, the title changes back to 'Layer 1: Points' too soon (while still showing the second layer, and before the animation restarts). How can I make the title stay on "Layer 2" while the second layer is showing?

A: I figured this out.  Using next_layer instead of closest_layer does the trick.
library(gganimate)

## data
df = data.frame(x=c(0,1),
                y=c(0,1))

## static plot
g = ggplot(data=df, aes(x=x, y=y))+
  geom_point()+
  geom_line()+
  labs(title = '{closest_layer}')
g

## animated plot
gg = g +
  transition_layers(layer_names=c('Layer 1: Points',
                                  'Layer 2: Line')) +
  enter_fade()
a = animate(gg, nframes = 50, end_pause = 20)
a


text:
Q: how to do an self invoked AJAX post? i am a bit confused about the self invoked function, i have done an http.get function to get the data from a json in this way (and work):
var Callmodule = (function(){
var urljsonEntrata= "modello.json";

function getmodules(){
    var req = $.ajax({
        url: urljsonEntrata,
        dataType: 'json',
        type: 'GET'
    });

    req.done(function(data){
        console.log('ajax to '+urljsonEntrata+' DONE');
        console.log(data);
        console.log('-----------------------------');
    });

    req.fail(function( jqXHR, textStatus, errorThrown ) {
        console.log('ajax to '+urljsonEntrata+' FAIL');
        console.log(jqXHR);
        console.log(textStatus);
        console.log(errorThrown);
        console.log('-----------------------------');
    });
    return req;
}
return {
    callGetmodules : getmodules(),
}
})();

i have done this because i want to use it in vue.js application, and i have invoked it in this way:
  methods:{
getModuleData : function(){
    var req = Callmodule.callGetmodules;
    var self = this;
    req.done(function(data){
        self.modello=data;
        self.isLoading=false;
    });
    req.fail(function(jqXHR,textStatus,errorThrown){
        console.log('richiesta andata a male')
    });
}

now i have tried in the same way for the http.POST , but simply it doesn't work
var PostModule = (function(datadapostare){
var PostUscita= "http://www.website.com/filephp.php";
var datapost = datadapostare
function postquote(){
    var req = $.ajax({
        type: 'POST',
        url: PostUscita,
        data: datapost,
        dataType: 'json',
    });

    req.done(function(data){
        console.log('ajax to '+PostUscita+' DONE');
        console.log(data);
        console.log('-----------------------------');
    });

    req.fail(function( jqXHR, textStatus, errorThrown ) {
        console.log('ajax to '+PostUscita+' FAIL');
        console.log(jqXHR);
        console.log(textStatus);
        console.log(errorThrown);
        console.log('-----------------------------');
    });
    return req;
}
return {
    Postmodules : postquote(),
}
})();

and here the way in which i post it (consider it wrapped inside vuejs methods):
postData : function(){
var req = Postmodule.Postmodules;
var self = this;
req.done(function(data){
    self.modello=data;
    self.isLoading=false;
});
req.fail(function(jqXHR,textStatus,errorThrown){
    console.log('richiesta andata a male')
});

}
why it does not go in done? and in which way i must pass the data object to post?
thank you in advance

A: I would recommend using vue-resource or axios to handle http requests, it has a much simpler API as opposed to using the jQuery library


text:
Q: SSPI negotiation failed with WtrustChannelFactory This one has me for a while now, I am trying to build a console app that can call a .net web/wcf service  SP, the first leg is to get a token from the idP (ADFS4.0) the pasted code was working fine for a whole day, at some point it stopped working with the following error:
SOAP security negotiation with 'https://adfs.domain.in/adfs/services/trust/13/windowsmixed' for target 'https://adfs.domain.in/adfs/services/trust/13/windowsmixed' failed. See inner exception for more details.
The inner error is:
The Security Support Provider Interface (SSPI) negotiation failed.
NativeErrorCode:   0x80090350  -> SEC_E_DOWNGRADE_DETECTED
I have tried /13/windows and /windowstransport as well as the endpoint.
private static GenericXmlSecurityToken RequestSecurityToken()
{
    // set up the ws-trust channel factory
    var factory = new Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannelFactory(new WindowsWSTrustBinding(
                SecurityMode.TransportWithMessageCredential), new EndpointAddress(new Uri("https://adfs.domain.in/adfs/services/trust/13/windowsmixed"), EndpointIdentity.CreateSpnIdentity("adfs@domain.in")));
    factory.TrustVersion = TrustVersion.WSTrust13;
    var rst = new RequestSecurityToken
    {
        RequestType = RequestTypes.Issue,
        KeyType = KeyTypes.Bearer,
        AppliesTo = new System.ServiceModel.EndpointAddress(endpoint_address)
    };
    // request token and return
    return factory.CreateChannel().Issue(rst) as GenericXmlSecurityToken;
}


text:
Q: Grouping by 'equal sums' I'm trying to take a list of numbers, and put them into >=N groups such that the sums of each groups are approximately (but not necessarily exactly) equal, and 'outliers' can be in a group of their own.
So for a target of 3 groups and an input of something like:
[3, 2, 1, 4, 2, 5]

The output might be:
[[5,1], [4,2], [3,2]]

The respective sums of each group being
6, 6, 5

I think I've got the methodology down, as pseudocode it looks something like this:
let target = Ceil(Sum(Series) / NumberOfTargetGroups) //The ideal size of each group

while (count(UnpickedNumbers) > 0)
    let CurrentGroup = new group
    while (sum(CurrentGroup) < target)
        for each Unpicked in sortDesc(UnpickedNumbers)
            if (sum(CurrentGroup) + Unpicked)
                Add Unpicked to current group
                Remove unpicked from available numbers

What I can't figure out is how to turn that logic into a GroupBy(n => ...) - the reason for wanting to do this being that the list of numbers is actually coming from a property of a series of objects that I want to group in this manner.

A: Partition is NP-complete problem.
I've preapred snippet:
public IEnumerable<IEnumerable<TObject>> Algo<TObject>(IEnumerable<TObject> source, int groups,
                                                       Func<TObject, int> intSelector)
{
    if (source == null)
    {
        throw new ArgumentNullException("source");
    }

    source = source.OrderByDescending(intSelector);
    var evaluated = source as IList<TObject> ?? source.ToList();
    if (groups > evaluated.Count())
    {
        throw new ArgumentException("Invalid group count.");
    }

    var result = new List<List<TObject>>();
    for (var i = 0; i < groups; i++)
    {
        result.Add(new List<TObject> { evaluated[i] });
    }

    for (var i = groups; i < evaluated.Count(); i++)
    {
        var bestIndex = 0;
        var bestSum = result[bestIndex].Sum(intSelector);
        for (var j = 1; j < result.Count; j++)
        {
            var sum = result[j].Sum(intSelector);
            if (sum < bestSum)
            {
                bestSum = sum;
                bestIndex = j;
            }
        }

        result[bestIndex].Add(evaluated[i]);
    }

    return result;
}

It is not efficient (there are many ways to optimize it) and the result is not always optimial. But hope that it will be base for your algorithm (maybe approx. is enough for you - test it!).
EDIT:
I've modified snippet for you - you don't have to use GroupBy. Usage:
var widgets = new List<Widget>  { W1, W2, etc. };
var result = Algo(widgets, groups: 3, intSelector: widget => widget.Height);


text:
Q: Convert string in php I have one string:
"Hello\u00c2\u00a0World"

I would like convert in:
"Hello World"

I try :
str_replace("\u00c2\u00a0"," ","Hello\u00c2\u00a0World");

or
str_replace("\\u00c2\\u00a0"," ","Hello\u00c2\u00a0World");

but not work!

A: Resolve!
str_replace(chr(194).chr(160)," ","Hello\u00c2\u00a0World");

A: If you would like to remove \u.... like patterns then you can use this for example:
$string = preg_replace('/(\\\u....)+/',' ',$input);

A: You are most of the way there.
$stuff = "Hello\u00c2\u00a0World";
$newstuff = str_replace("\u00c2\u00a0"," ",$stuff);

you need to put the return from str_replace into a variable in order to do something with it later.

A: This should work
$str="Hello\u00c2\u00a0World";
echo str_replace("\u00c2\u00a0"," ",$str);

A: You may try this, taken from this answer
function replaceUnicode($str) {
    return preg_replace_callback("/\\\\u00([0-9a-f]{2})/", function($m){ return chr(hexdec($m[1])); }, $str);
}
echo replaceUnicode("Hello\u00c2\u00a0World");


text:
Q: Create table using HTML in Powershell i want to know services stopped and which are set to automatic and output file goes to HTML page. In that HTML output i want to create table for stopped services on top of that table server name. Can someone tell me..
$ServerListFile = "C:\Dv\Server_List.txt"
$ServerList = Get-Content $ServerListFile -ErrorAction SilentlyContinue
foreach ($Computername in $ServerList) {
Write-Host "Automatic Services Stopped :" $Computername
Get-wmiobject win32_service -computername $Computername  -Filter  "startmode
= 'auto'  AND state != 'running'" | Select DisplayName,Name,State,startmode
|  Format-Table  -auto | Out-File C:\Dv\Report.html
}

A: Something like this should work.
Single table
Get-Content "C:\Dv\Server_List.txt" -ErrorAction SilentlyContinue | ForEach-Object {
    Write-Host "Automatic Services Stopped :" $_
    Get-WmiObject Win32_Service -ComputerName $_ -Filter  "startmode = 'auto' AND state != 'running'"
} |
    Select-Object DisplayName, Name, State, StartMode |
    ConvertTo-Html |
    Out-File C:\Dv\Report.html

Multiple tables
This version creates a sequence of tables using ConvertTo-Html -Fragment. Each table is preceded by a HTML header (h2 in the example) with the computer name. The individual tables are concatenated and merged into a single HTML document at the end using a bare (no input) call to ConvertTo-Html.
# Generate the content which should be inserted as a set of HTML tables
$preContent = Get-Content "C:\Dv\Server_List.txt" -ErrorAction SilentlyContinue | ForEach-Object {
    $ComputerName = $_

    Write-Host "Automatic Services Stopped :" $ComputerName

    # A table (and heading) will only be generated for $ComputerName if there are services matching the filter.
    Get-WmiObject Win32_Service -ComputerName $ComputerName -Filter  "startmode = 'auto' AND state != 'running'" |
        Select-Object DisplayName, Name, State, StartMode |
        ConvertTo-Html -PreContent "
$ComputerName
" -Fragment
}

# Generate the document which holds all of the individual tables.
$htmlDocument = ConvertTo-Html -Head $htmlHead -PreContent $preContent | Out-String
# Because the document has no input object it will have an empty table (

), this should be removed.
$htmlDocument -replace '
\r?\n
' | Out-File C:\Dv\Report.html

Styling
You'll find the HTML generated by these to be pretty raw. One of the better ways to tackle that is to use CSS, here's a fragment of mine that makes HTML tables look prettier:
$HtmlHead = ''

# Use the Head parameter when calling ConvertTo-Html
... | ConvertTo-Html -Head $HtmlHead | ...

Note: The Head only applies when the Fragment parameter is not supplied with ConvertTo-Html.


text:
Q: Removing underline partially from a link I have the following 'link-box' in my footer:

This is the HTML:

 - <spawn class="red">Zegmaar</spawn><spawn class="blue">Bas</spawn>.nl

I want the first part of the text, " - " / "-" to not be underlined, like this:

I think text-decoration-skip: spaces; would be the easiest way to accomplish this, however, almost no browsers support it (yet).
How could I get the desired result?
The more simple and elegant your solution, the better. I want to use only CSS and HTML.

A: The cleanest option would be to use a custom class for this link
.headerLink {text-decoration:none;}

And then another class for the parts that should be underlined:
.headerLinkAction {text-decoration: underline;}

You may want to update the hover class as well.

A: You can took off underline fom the anchor tag, then use underline to those part of word like this,

 - <spawn class="red">Zegmaar</spawn><spawn class="blue" style="text-
 decoration: underline;">Bas</spawn>.nl

If you want to show the underline only on hover, then use class for hover with text-decoration:none;.

A:

Try this:
( Removed underline )

 - <spawn class="red">Zegmaar</spawn><spawn class="blue">Bas</spawn>.nl


text:
Q: conditional expectation as direct sum Let $(\Omega, \mathcal{F}, P)$ be a probability measure space and $\mathcal{L}^1(\mathcal{G})$ =$\{$X $\mathcal{G}$-measurebale , $\int XdP<\infty$ $\}$  for  $\mathcal{G}\subset\mathcal{F}$ an abritrary sub $\sigma$-Algebra.
$\circ$ Is $\mathcal{L}^1(\mathcal{G})$ modulo Nullsets with $|| \cdot ||_1$ a closed subset of $\mathcal{L}^1(\mathcal{F})$  / a Banach space?
$\circ$ Is there some other Subspace $\mathcal{S}$ such that $\mathcal{L}^1(\mathcal{G}) \oplus \mathcal{S}  =\mathcal{L}^1(\mathcal{F})$ or even a $\mathcal{H}\subset \mathcal{F}$ with $\mathcal{L}^1(\mathcal{G}) \oplus  \mathcal{L}^1(\mathcal{H}) =\mathcal{L}^1(\mathcal{F})$?


text:
Q: C - format specifier for scanf? float lat, lon;
char info[50];

scanf("%f, %f, %49[^\n]", &lat, &lon, info);

In the above snippet, what kind of format specifier is %49[^\n].
I do understand that it is the format specifier for the character array which is going to accept input upto 49 characters (+ the sentinal \0), and [^\n] looks like its a regex (although I had read somewhere that scanf doesn't support regex) OR a character set which is to expand to "any other character" that is NOT "newline" \n. Am I correct?
Also, why is there no s in the format specifier for writing into array info?
The program this snippet is from works. But is this good C style?

A: My apologies, I incorrectly answered below.  If you can skip to the end, I'll give you the correct answer.
*** Incorrect Answer Begins ***
It would not be a proper format specifier, as there is no type.
%[parameter][flags][width][.precision][length]type

are the rules for a format statement.  As youc an see, the type is non-optional.  The author of this format item is thinking they can combine regex with printf, when the two have entirely different processing rules (and printf doesn't follow regex's patterns)
*** Correct Answer Begins ***
scanf uses different format string rules than printf  Within scanf's man page is this addition to printf's rules

[
Matches a nonempty sequence of characters from the specified set
of accepted characters; the next pointer must be a pointer to char,
and there must be enough room for all the characters in the string,
plus a terminating null byte. The usual skip of leading white space is
suppressed. The string is to be made up of characters in (or not in) a
particular set; the set is defined by the characters between the open
bracket [ character and a close bracket ] character. The set excludes
those characters if the first character after the open bracket is a
circumflex (^). To include a close bracket in the set, make it the
first character after the open bracket or the circumflex; any other
position will end the set. The hyphen character - is also special;
when placed between two other characters, it adds all intervening
characters to the set. To include a hyphen, make it the last character
before the final close bracket. For instance, [^]0-9-] means the set
"everything except close bracket, zero through nine, and hyphen". The
string ends with the appearance of a character not in the (or, with a
circumflex, in) set or when the field width runs out.

Which basically means that scanf can scan with a subset of regex's rules (the character set subset) but not all of regex's rules

A: The specifier %[ is a different conversion specifier from %s, even if it also must be paired with an argument of type char * (or wchar_t *). See e.g. the table here

[set]         matches a non-empty sequence of character from set of characters.
If the first character of the set is ^, then all characters not in the set are matched. If the set begins with ] or ^] then the ] character is also included into the set. It is implementation-defined whether the character - in the non-initial position in the scanset may be indicating a range, as in [0-9]. If width specifier is used, matches only up to width. Always stores a null character in addition to the characters matched (so the argument array must have room for at least width+1 characters)


text:
Q: picasso is not able to load image in android i am using android api level 17 as minimum and have included internet permissions in manifest file.
But i am not able to get image. I want to fetch images from my server , the link i am using is proper. check my code :
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;

import com.squareup.picasso.Picasso;

public class MainActivity extends AppCompatActivity {
ImageView im;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        im=(ImageView)findViewById(R.id.iv);

        Picasso.with(getApplicationContext()).load("example.com").into(im);
    }
}

A: Change your Context to your Activity instead:
 Picasso.with(this).load("example.com").into(im);


text:
Q: Scroll to Top on mm-subopen click Using mmenu and I'd like to scroll to top of the page whenever someone clicks on the "arrow" for the subpages; the a href class is named "mm-subopen".
It doesn't have an ID, so I have to go with the class.
How do I accomplish this?  I've tried the following, but it doesn't work.
Thanks..
$(function() {
  $("a.mm-subopen").scrollToTop(100);
});

A: I believe you have forgotten to bind the click event to your selector. You will need to tell jQuery which event, when triggered from the element of interest, triggers the scrolling to top function. It is also advisable to disable the default function of the <a> element, by using .preventDefault().
$(function() {
    $("a.mm-subopen").click(function(e) {
        e.preventDefault();
        $(window).scrollTop(100);
    });
});

Also, we are scrolling the viewport, so we bind the .scrollTop() method to the $(window) object. See proof-of-concept demo here: http://jsfiddle.net/teddyrised/c1jvzvz7/
p/s: You have specified the viewport to scroll to the 100px position from the top. If you want to scroll to the true top, use scrollTop(0) instead.


text:
Q: Unexpected error in Apache Velocity template file I have an xml containing the description of the classes I want to generate with velocity, in this form:
<Class name="name">
  <Attribute name="name" type="typeName"/>
  ...
  <Method name="name" type="typeName"/>
</Class>

the template's code is:
public class $class.Name implements NodeIface {

#foreach($att in $class.Attributes)
  private $att.Type $att.name;

  public $att.Type get$utility.firstToUpperCase($att.Name)() {
    return this.$att.Name;
  }

  public void set$utility.firstToUpperCase($att.Name)($att.Type $att.Name) {
    this.$att.Name = $att.Name;
  }
#end

#foreach($mtd in $class.Methods)
  if($class.Name == "name") {
    public $mtd.Name() {
      this.$att.Name = new $att.Type(Constants.SERVER_PORT, classNameHandler.class); //here lies the error
    }

    @Override
       public $mtd.Type $mtd.Name() throws TException {
         TSocket $att.Name = new TSocket("localhost", Constants.SERVER_PORT);
         TBinaryProtocol $att.Name = new TBinaryProtocol($att.Name);
         managementClient = new ManagementService.Client($att.Name);
         this.setDispatcher(new OperationDispatcher($att.Name));
         arithmeticServerTransport.open();
         $att.Name.start();
                $att.Name = new $att.Type($att.Name);
        PortNegotiator negotiator = new PortNegotiator($att.Name);
        negotiator.negotiate($att.Type, $att.Name);
    }

    @Override
    public $mtd.Type $mtd.Name() {
        $att.Name.stop();
    }
  }
  else if ($class.Name == "GreetingsNode") {
    public $mtd.Name();
        this.$att.Name = new $att.Type((Constants.SERVER_PORT, GreetingsServiceHandler.class));
    }

    #Override
    public $mtd.Type $mtd.Name() throws TException {
        TSocket $att.Name = new TSocekt("localhost", Constants.SERVER_PORT);
        TBinaryProtocol $att.Name = new TBinaryProtocol($att.Name);
        $att.Name = new ManagementService.Client($att.Name);
        this.SetUser(new User($att.Name);
        this.setMessenger(new MessageDispatcher($att.Name));
        $att.Name.open()

        $att.Name = new $att.Type($att.Name);
        PortNegotiator negotiator = new PortNegotiator($att.Name);
        negotiator.negotiate($att.Type, $att.Name);
    }

    @Override
    public $mtd.Type $mtd.Name() {
      $att.Name.stop();
    }

#End

Eclipse's velocity text editor tells me that there is an error with this message: "Encountered ");\r\n\t\t}\r\n\t\t\r\n\t\t@Override\r\n\t\tpublic " at Class.vm[line 23, column 86]
Was expecting one of:
    "[" ...
    "," ...
    ")" ...
     ..."
What does this mean?

A: It's a case where you need to use the formal reference notation:
      this.$att.Name = new ${att.Type}(Constants.SERVER_PORT, classNameHandler.class);

otherwise the Velocity parser will think that you are trying to call a method on the $att.Type object.


text:
Q: выбрать корректную ветку для push работаю над проектом на github, в самом проекте есть 2 ветки, бета и альфа, обычно работал в ветке альфа alpha-branch если я проверяю в git git branch то отображается только 1 ветка alpha-branch. сейчас возникла ситуация что нужно пролить в бету, но в списке branch только альфа. как можно запушить в таком случае на beta-branch?
после комментария проверил git branch -r, и правда отображается ряд удаленных веток..подскажите как запушить на нее в таком случае?

A: команда (показан и примерный её вывод)
$ git branch -r
origin/ветка1
origin/ветка2
repo2/ветка3
repo3/ветка4

покажет все ветки всех подключенных к вашему локальному репозиторию удалённых репозиториев.
репозитории фигурируют под теми (произвольными) именами, под которыми они подключены. в данном случае: origin, repo2 и repo3.
имя origin — по умолчанию присваивается удалённому репозиторию, например, при выполнении git clone.
в принципе, чтобы отправить изменения из текущей ветки в любую из веток любого из подключенных репозиториев, можно выполнить:
$ git push имя-репозитория имя-ветки

для приведённого выше примера отправить изменения в, например, origin/ветка2, можно так:
$ git push origin ветка2

но отправить изменения из произвольной локальной ветки в произвольную удалённую, скорее всего, не выйдет и вы можете получить ошибку вида:

error: src refspec ветка2 does not match any

это говорит о том, что надо явно указать источник. это может быть имя локальной ветки, хэш конкретного коммита или метка (в том числе «специальная» — HEAD, которая указывает на текущий коммит, куда переключена ваша рабочая копия репозитория). примерно так:
$ git push имя-репозитория источник:ветка

но и это ещё не «победа». скорее всего, вы можете получить в ответ ошибку вида:

To url-репозитория
   ! [rejected]        источник -> ветка (non-fast-forward)
  error: failed to push some refs to 'url-репозитория'
  hint: Updates were rejected because a pushed branch tip is behind its remote
  hint: counterpart. Check out this branch and merge the remote changes
  hint: (e.g. 'git pull') before pushing again.
  hint: See the 'Note about fast-forwards' in 'git push --help' for details.

это значит что ваш текущий коммит невозможно связать цепочкой коммитов с коммитом, на который указывает удалённая ветка (напомню, что ветка в git — это лишь «плавающий» указатель на коммит).
и действовать вам надо было несколько иначе.
например, так:

*

*создать локальную ветку, основанную на удалённой, и переключиться на неё:
$ git checkout -b ветка2 origin/ветка2

*внести необходимые изменения, сделать необходимые коммиты.

*отправить эти изменения в удалённый репозиторий:
$ git push


text:
Q: How to submit a external signal to my computer in a simple way? I have an electrical wire that have two states: 1/0. `1' means there is current while `0' means there is no current. How can I put these two states into a file of my computer in a simple way?
I know that I can use an advanced ammeter/voltmeter and use GPIB lines to realize this. But is there a really simple way to satisfy this really simple need? Besides, I use Linux/Windows. Do you have any idea?

A: Simplest I can think of would be the audio port, because it's sitting there unused on most systems waiting for you to connect some leads to it.
Not sure how to connect your line voltage to that port?  Build the circuit described at the bottom of the page here:
xoscope.sourceforge.net
testing this circuit should involve the application there 'xoscope' (i.e. hook up your new circuit to a source and watch the line dance as you change voltage)
Another idea might be to hook up an arduino (or some other 8bit dev board) and use one of the example sketches that deal with digital IO?

A: Arduino or its .NET counterpart, NetDuino, is a hardware platform that will let you do this inexpensively.
http://arduino.cc/


text:
Q: Trigger to apex class I want to transfer a trigger code into apex class, and the trigger code happens to have trigger.isinsert and trigger.new attributes. Can you suggest me how to do it?

A: These variables are accesssible in the Trigger's Context.
You can refer below links, which explains using a handler along with a Apex Trigger.
https://developer.salesforce.com/forums/?id=906F000000093cKIAQ
http://www.infallibletechie.com/2014/05/trigger-handler-controller-in-salesforce.html


text:
Q: Parameterizing complex search methods Is there a best practice on how to handle DAL methods with complex search logic? I'm talking about the business requirements like
"List customers who's companies are active or in sleep status, have more than 1000$ of orders in the last quarter, customer must not be deleted, company must have office in London or New York and Paris..."
These requirements quickly make your CustomerDAL.GetCustomers(...) have over 9000 parameters, not to mention that it changes all the time which can be a pain if you have lots of layers, interfaces, webservices etc.
Are there other good ways to clean up methods like that, besides creating a CustomerSearchParameters struct which you create and set up before calling the method itself?

A: Well you could build an expression within the method calling GetCustomers() and then pass in that expression into the query, e.g.
GetCustomer(string where)

However this makes validating the where clause difficult. A better approach might be to use a expression structure to capture the constraints, this would also make it easier to validate the expression prior to executing the query:
class Expression {
  string PropertyName
  object value
}

GetCustome(Expression[] constraints)

A: Maybe you should have a look at the JPA Criteria API. Even if you are not using JPA a model like this where you can add Criteria to your query dynamically might do what you need. I would recommend to make sure, that you create a transparent API (your DAL or DAO methods e.g. shouldn't rely on the JPA Criteria API directly).


text:
Q: Converting total irradiance forecast from cloud cover forecast using pvlib in python I am trying to calculate total irradiance in python using pvlib. In older versions the irradiation module included a method implementing Liu-Jordan model and it was possible to convert cloud cover forecast to irradiation forecast.
Would it be possible to perform this conversion in the latest version (0.3.3)?

A: An early prototype of the pvlib python forecasting feature conflated the Liu Jordan model with a cloud cover to transmittance model. This was on a github branch, but it was not part of an official pvlib python release.
pvlib python 0.4 includes the irradiance.liujordan function, but you'll need to first convert cloud cover to transmittance. The ForecastModel class has a simple method for doing so.
For the pvlib python 0.4.x series, the essential code is
model = pvlib.forecast.ForecastModel()  # or any subclass of ForecastModel
irrads = model.cloud_cover_to_irradiance_liujordan(cloud_cover)

The pvlib python documentation also describes how to do this, though you'll have to look past the unrelated documentation errors on readthedocs (or build the documentation locally):
http://pvlib-python.readthedocs.io/en/latest/forecasts.html#cloud-cover-and-radiation
The API may change in 0.5.


text:
Q: Simple A/B randomization script with PHP I have two ad options in my theme, Adsense and "Custom". If the user enters code into the "Custom" field, it trumps whatever they have in the "Adsense" code field, so the theme places their custom ad atop the content area. If they have adsense enabled, and nothing in the custom ad spot, the theme places their adsense code there.
I'd like to add an option to allow the user to opt to have my theme automatically rotate ads between adsense and their custom ads. The custom ads may be Ebay, Amazon, ClickBank, etc.
How would you set up a PHP script that will randomly choose between two options?
Alternately, I'd like to be able to give the user the option to choose a percentage value so that the adsense ads are rotated based on their chosen percentage.
Just looking for some suggested approaches. Thanks in advance.

A: <?php

   $option[0] = 'html option 1';
   $option[1] = 'html option 2';

   echo $option[rand()%count($option)];
?>

A: 1) I think mt_rand(); it's better than rand(); (source:http://php.net/manual/en/function.mt-rand.php)
2)
   $option[0] = 'html option 1';
   $option[1] = 'html option 1';
   $option[2] = 'html option 1';
   $option[3] = 'html option 2';
echo $option[rand()%count($option)];

It's not a better solution, but it works :)


text:
Q: how to set a secondary axis to a data series in PHPEXCEL? how to set a secondary axis for this series?
    $series = new PHPExcel_Chart_DataSeries(
        PHPExcel_Chart_DataSeries::TYPE_LINECHART,      // plotType
        PHPExcel_Chart_DataSeries::GROUPING_CLUSTERED,  // plotGrouping
        $chartOrder,                                    // plotOrder
        $chartLables,                                   // plotLabel
        $chartCategories,                               // plotCategory
        $chartValues                                    // plotValues
    );
    $series->setPlotDirection(PHPExcel_Chart_DataSeries::DIRECTION_COL);
    $plotarea = new PHPExcel_Chart_PlotArea(null, array($series));
    $legend = new PHPExcel_Chart_Legend(PHPExcel_Chart_Legend::POSITION_BOTTOM, null, false);

    $chart = new PHPExcel_Chart(
        "chart_$topRow_$leftColumn",                    // name
        null,                                           // title
        $legend,                                        // legend
        $plotarea,                                      // plotArea
        true,                                           // plotVisibleOnly
        0,                                              // displayBlanksAs
        null,                                           // xAxisLabel
        null                                            // yAxisLabel
    );
    $chart->setTopLeftPosition('A1');
    $chart->setBottomRightPosition(K12');
    $objWorksheet->addChart($chart);

A: You can't, secondary Y-axes are not yet supported.... remember that charting is still considered experimental, and chart functionality is still being built


text:
Q: remove index.php from URL in codeigniter in windows azure I am experimenting to develop websites on windows azure platform.
I want to remove index.php from URL in my codeigniter project.
I found 1 solution here:
Solution
But, I don't know where is web.config file in azure management panel?
Can anyone tell me exact location ? Can I change that file from their website?
Thanks.

A: This web.config should work with codeigniter.
Just create a file called web.config and upload it to your wwwroot folder on Azure (The folder where your index.php is)
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="Rule" stopProcessing="true">
                    <match url="^(.*)$" ignoreCase="false" />
                        <conditions>
                            <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
                            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
                            <add input="{URL}" pattern="^/favicon.ico$" ignoreCase="false" negate="true" />
                        </conditions>
                        <action type="Rewrite" url="index.php/{R:1}" appendQueryString="true" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>

Let me know how you get on!
Thanks


text:
Q: Issues with tree based learners for Boosting Machines or RFs I'm wondering if tree based methods are capable of making predictions that are larger in magnitude than the largest training observations? Given my understanding of decision trees and partitioning feature space, I would guess it's not possible for predictions from GBMs or Random Forests to exceed the largest values found in training data.
Assuming the above is true, how do modelers deal with these tree-based limitations. If tree based algorithm predictions are bounded by what's observed in training data, I would imagine this would result in prediction problems for applications where unprecedented values are feasible. Other than employ a different algorithm, is there a different way to handle this boundedness of predictions?


text:
Q: Refresh_token using oauth.io Hi I am student of Computer Science and doing some experiments on oauth.io. but i am facing problem to get refresh_token after getting code successfully. After getting the code i am writing the follwing line of code but its giving me Internal server error..
The code is
$.ajax("https://oauth.io/auth/access_token", {
    type: "post",
    data: {
        code: result.code,
        key: '5WeOrrR3tP6RyShR1',
        secret: '2_q3tb_D_qgDwSGpt' },
    success: function (data) {
        console.log("result", data);
    }
});

Which url used to get refresh_token? please someone help me.
thanks

A: there was a bug recently in the js sdk when you set the response type server-side (to get the code & refresh_token), so you may have to redownload oauth.js if you use a static version.
I guess your jquery code is server side (because of the nodejs tag and the use of a code), but i had an error "no transport" that i fixed with a new XMLHttpRequest. Here is my full test:
var jsdom = require('jsdom').jsdom;
var win = jsdom().createWindow();
var $ = require('jquery')(win);
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;

$.support.cors = true;
$.ajaxSettings.xhr = function () {
    return new XMLHttpRequest;
}

$.ajax("https://oauth.io/auth/access_token", {
    type: "post",
    data: {
        code: process.argv[2],
        key: 'xxxxxxxxxxxx',
        secret: 'yyyyyyyyyyyy' },
    success: function (data) {
        console.log("result", data);
    },
    error: function() {
        console.error(arguments);
    }
});

and my result looks like:
{ access_token: 'xxxxxxxxxxx',
  request:
   { url: '{{instance_url}}',
     required: [ 'instance_url' ],
     headers: { Authorization: 'Bearer {{token}}' } },
  refresh_token: 'yyyyyyyyyyyyy',
  id: 'https://login.salesforce.com/id/00Db0000000ZbGGEA0/005b0000000SSGXAA4',
  instance_url: 'https://eu2.salesforce.com',
  signature: 'zzzzzzzzzzzzz',
  state: 'random_string',
  provider: 'salesforce' }


text:
Q: Jenkins : withCredentials does not mask passwords in Groovy Script I am using Credentials and CredentialBinding to mask credentials passed to "bat" to be used in "net use" to connect to a share via a groovy script. Unfortunately the password is exposed in console log :
    withCredentials([
        usernamePassword(
            credentialsId: credentialsId,
            passwordVariable: 'PASSWORD',
            usernameVariable: 'USER'
        )
    ]) {
        def user = this.env['USER'];
        def password = this.env['PASSWORD'];
        bat "net use \\\\$server $PASSWORD /user:$user /persistent:yes"
        bat "net use"
    }

I tried using %PASSWORD% in single quotes as well , but strings are not getting interpolated in "net use".
Please let me know if something is amiss.

A: Can you share your log that you get (obviously with the password removed)
As withCredentials should mask automatically if you have a reasonably recent version even when passing to other processes
e.g.
    steps {
            withCredentials([
                usernamePassword(
                    credentialsId: "MY_CREDENTIALS",
                    passwordVariable: 'PASSWORD',
                    usernameVariable: 'USER'
                )
            ]) {
                sh "echo $PASSWORD"
                echo USER
            }
        }

will still mask the password
[Pipeline] withCredentials
Masking supported pattern matches of $USER or $PASSWORD
[Pipeline] {
[Pipeline] sh
Warning: A secret was passed to "sh" using Groovy String interpolation, which is insecure.
     Affected argument(s) used the following variable(s): [PASSWORD]
     See https://jenkins.io/redirect/groovy-string-interpolation for details.
+ echo ****
****
[Pipeline] echo
****
[Pipeline] }
[Pipeline] // withCredentials

Also what are these lines for when you can just use $PASSWORD and $USER directly
def user = this.env['USER'];
def password = this.env['PASSWORD'];


text:
Q: Laravel 4.1 - $user->roles()->detach() issue in testing environment I have tables 'users', 'roles', and 'users_roles'. When I $user->roles()->attach() and detach() it works fine in my local environment with MySQL. But when I try to do the same in my testing environment (memory / Sqlite) $user->roles()-detach() does not work. No errors are thrown, it just doesn't remove the entries from the pivot table. It's like it's not firing or something.
I'm using PHPUnit 3.7
$this->roles()->attach(1);
$count = $this->roles->count();
$this->roles()->detach();

I've also tried $this->roles()->detach(1) with no luck. Any ideas?
--- Update ---
Something I forgot to mention is that I am running a
$count1 = $user->roles->count();

between the attach() and detach() and this is what seems to be causing the issue. Why would running a count() between  an attach() and detach() cause detach to not fire? I updated the code above to reflect my new findings.

A: I figured out a solution. Instead of running $user->roles->count() I switched that to be         $count1 = count(User::find($user->id)->roles->toArray());
Seems to be working fine although I don't know if there are any repercussions of that.


text:
Q: Errno::ENOENT: No such file or director config/settings.yml (heroku deploy) I am trying to deploy to heroku and getting the following error, which is below. I would appreciate any tips or help on solving that please.
Preparing app for Rails asset pipeline
   Running: rake assets:precompile
   rake aborted!
   Errno::ENOENT: No such file or directory - /tmp/build_c6574b00-1f27-48f0-a3ea-4413871d028e/config/settings.yml
   /tmp/build_c6574b00-1f27-48f0-a3ea-4413871d028e/vendor/bundle/ruby/2.0.0/gems/settingslogic-2.0.9/lib/settingslogic.rb:102:in `initialize'
   /tmp/build_c6574b00-1f27-48f0-a3ea-4413871d028e/vendor/bundle/ruby/2.0.0/gems/settingslogic-2.0.9/lib/settingslogic.rb:60:in `new'
   /tmp/build_c6574b00-1f27-48f0-a3ea-4413871d028e/vendor/bundle/ruby/2.0.0/gems/settingslogic-2.0.9/lib/settingslogic.rb:60:in `instance'
   /tmp/build_c6574b00-1f27-48f0-a3ea-4413871d028e/vendor/bundle/ruby/2.0.0/gems/settingslogic-2.0.9/lib/settingslogic.rb:48:in `load!'
   /tmp/build_c6574b00-1f27-48f0-a3ea-4413871d028e/app/models/settings.rb:4:in `<class:Settings>'
   /tmp/build_c6574b00-1f27-48f0-a3ea-4413871d028e/app/models/settings.rb:1:in `<top (required)>'
   /tmp/build_c6574b00-1f27-48f0-a3ea-4413871d028e/vendor/bundle/ruby/2.0.0/gems/activesupport-4.1.4/lib/active_support/dependencies.rb:247:in `require'
   /tmp/build_c6574b00-1f27-48f0-a3ea-4413871d028e/vendor/bundle/ruby/2.0.0/gems/activesupport-4.1.4/lib/active_support/dependencies.rb:247:in `block in require'
   /tmp/build_c6574b00-1f27-48f0-a3ea-4413871d028e/vendor/bundle/ruby/2.0.0/gems/activesupport-4.1.4/lib/active_support/dependencies.rb:232:in `load_dependency'
   /tmp/build_c6574b00-1f27-48f0-a3ea-4413871d028e/vendor/bundle/ruby/2.0.0/gems/activesupport-4.1.4/lib/active_support/dependencies.rb:247:in `require'
   /tmp/build_c6574b00-1f27-48f0-a3ea-4413871d028e/vendor/bundle/ruby/2.0.0/gems/activesupport-4.1.4/lib/active_support/dependencies.rb:348:in `require_or_load'
   /tmp/build_c6574b00-1f27-48f0-a3ea-4413871d028e/vendor/bundle/ruby/2.0.0/gems/activesupport-4.1.4/lib/active_support/dependencies.rb:480:in `load_missing_constant'
   /tmp/build_c6574b00-1f27-48f0-a3ea-4413871d028e/vendor/bundle/ruby/2.0.0/gems/activesupport-4.1.4/lib/active_support/dependencies.rb:180:in `const_missing'
   /tmp/build_c6574b00-1f27-48f0-a3ea-4413871d028e/config/initializers/action_mailer.rb:5:in `<top (required)>'
   /tmp/build_c6574b00-1f27-48f0-a3ea-4413871d028e/vendor/bundle/ruby/2.0.0/gems/activesupport-4.1.4/lib/active_support/dependencies.rb:241:in `load'
   /tmp/build_c6574b00-1f27-48f0-a3ea-4413871d028e/vendor/bundle/ruby/2.0.0/gems/activesupport-4.1.4/lib/active_support/dependencies.rb:241:in `block in load'
   /tmp/build_c6574b00-1f27-48f0-a3ea-4413871d028e/vendor/bundle/ruby/2.0.0/gems/activesupport-4.1.4/lib/active_support/dependencies.rb:232:in `load_dependency'
   /tmp/build_c6574b00-1f27-48f0-a3ea-4413871d028e/vendor/bundle/ruby/2.0.0/gems/activesupport-4.1.4/lib/active_support/dependencies.rb:241:in `load'
   /tmp/build_c6574b00-1f27-48f0-a3ea-4413871d028e/vendor/bundle/ruby/2.0.0/gems/railties-4.1.4/lib/rails/engine.rb:648:in `block in load_config_initializer'
   /tmp/build_c6574b00-1f27-48f0-a3ea-4413871d028e/vendor/bundle/ruby/2.0.0/gems/activesupport-4.1.4/lib/active_support/notifications.rb:161:in `instrument'
   /tmp/build_c6574b00-1f27-48f0-a3ea-4413871d028e/vendor/bundle/ruby/2.0.0/gems/railties-4.1.4/lib/rails/engine.rb:647:in `load_config_initializer'
   /tmp/build_c6574b00-1f27-48f0-a3ea-4413871d028e/vendor/bundle/ruby/2.0.0/gems/railties-4.1.4/lib/rails/engine.rb:612:in `block (2 levels) in <class:Engine>'
   /tmp/build_c6574b00-1f27-48f0-a3ea-4413871d028e/vendor/bundle/ruby/2.0.0/gems/railties-4.1.4/lib/rails/engine.rb:611:in `each'
   /tmp/build_c6574b00-1f27-48f0-a3ea-4413871d028e/vendor/bundle/ruby/2.0.0/gems/railties-4.1.4/lib/rails/engine.rb:611:in `block in <class:Engine>'
   /tmp/build_c6574b00-1f27-48f0-a3ea-4413871d028e/vendor/bundle/ruby/2.0.0/gems/railties-4.1.4/lib/rails/initializable.rb:30:in `instance_exec'
   /tmp/build_c6574b00-1f27-48f0-a3ea-4413871d028e/vendor/bundle/ruby/2.0.0/gems/railties-4.1.4/lib/rails/initializable.rb:30:in `run'
   /tmp/build_c6574b00-1f27-48f0-a3ea-4413871d028e/vendor/bundle/ruby/2.0.0/gems/railties-4.1.4/lib/rails/initializable.rb:55:in `block in run_initializers'
   /tmp/build_c6574b00-1f27-48f0-a3ea-4413871d028e/vendor/bundle/ruby/2.0.0/gems/railties-4.1.4/lib/rails/initializable.rb:44:in `each'
   /tmp/build_c6574b00-1f27-48f0-a3ea-4413871d028e/vendor/bundle/ruby/2.0.0/gems/railties-4.1.4/lib/rails/initializable.rb:44:in `tsort_each_child'
   /tmp/build_c6574b00-1f27-48f0-a3ea-4413871d028e/vendor/bundle/ruby/2.0.0/gems/railties-4.1.4/lib/rails/initializable.rb:54:in `run_initializers'
   /tmp/build_c6574b00-1f27-48f0-a3ea-4413871d028e/vendor/bundle/ruby/2.0.0/gems/railties-4.1.4/lib/rails/application.rb:300:in `initialize!'
   /tmp/build_c6574b00-1f27-48f0-a3ea-4413871d028e/vendor/bundle/ruby/2.0.0/gems/railties-4.1.4/lib/rails/railtie.rb:194:in `public_send'
   /tmp/build_c6574b00-1f27-48f0-a3ea-4413871d028e/vendor/bundle/ruby/2.0.0/gems/railties-4.1.4/lib/rails/railtie.rb:194:in `method_missing'
   /tmp/build_c6574b00-1f27-48f0-a3ea-4413871d028e/config/environment.rb:5:in `<top (required)>'
   /tmp/build_c6574b00-1f27-48f0-a3ea-4413871d028e/vendor/bundle/ruby/2.0.0/gems/activesupport-4.1.4/lib/active_support/dependencies.rb:247:in `require'
   /tmp/build_c6574b00-1f27-48f0-a3ea-4413871d028e/vendor/bundle/ruby/2.0.0/gems/activesupport-4.1.4/lib/active_support/dependencies.rb:247:in `block in require'
   /tmp/build_c6574b00-1f27-48f0-a3ea-4413871d028e/vendor/bundle/ruby/2.0.0/gems/activesupport-4.1.4/lib/active_support/dependencies.rb:232:in `load_dependency'
   /tmp/build_c6574b00-1f27-48f0-a3ea-4413871d028e/vendor/bundle/ruby/2.0.0/gems/activesupport-4.1.4/lib/active_support/dependencies.rb:247:in `require'
   /tmp/build_c6574b00-1f27-48f0-a3ea-4413871d028e/vendor/bundle/ruby/2.0.0/gems/railties-4.1.4/lib/rails/application.rb:276:in `require_environment!'
   /tmp/build_c6574b00-1f27-48f0-a3ea-4413871d028e/vendor/bundle/ruby/2.0.0/gems/railties-4.1.4/lib/rails/application.rb:379:in `block in run_tasks_blocks'
   /tmp/build_c6574b00-1f27-48f0-a3ea-4413871d028e/vendor/bundle/ruby/2.0.0/gems/sprockets-rails-2.0.1/lib/sprockets/rails/task.rb:54:in `block (2 levels) in define'
   Tasks: TOP => environment
   (See full trace by running task with --trace)

config/settings.yml is as below ///////////////////////////////
defaults: &defaults
core:
name: My_app
smtp:
  default_from:
  host:
  port:
  domain:
  username:
  password:
  authentication:
  start_tls:

development:
<<: *defaults
web:
host: localhost:3000

test:
 <<: *defaults
web:
host: localhost:3000

A: I think that your file is not included in your git repository. Try
git add config/settings.yml
git commit -m 'adding settings'
git push heroku master

It should work
and make sure to change config.assets.version

*

*config.assets.version = '1.0'

*config.assets.version = '1.1'

A: the following post helped
Precompilation breaking on heroku, works locally
Just change config.assets.version

*

*config.assets.version = '1.0'

*config.assets.version = '1.1'


text:
Q: Проблема со скрытием Navigation Bar Мне нужно скрыть панель Navigation Bar от пользователя, для этого в методе onCreate и так же в методе onTouchEvent я использовал простой код скрытия:
    decorView = getWindow().getDecorView();
    int uiOptions =View. SYSTEM_UI_FLAG_HIDE_NAVIGATION;
    decorView.setSystemUiVisibility(uiOptions);

Но моя проблема в том что, хоть при открытии он и скрыт, но при прикосновении 1 раз к экрану он появляется, после при 2 нажатии он опять скрывается. Как мне можно добиться результата что бы он вовсе не появлялся?

A: Вообще это странный подход. Если навигационная панель не хардверная, то как юзер закроет приложение? Поясните, чего вы хотите добиться этим.
А попробовать можно вот это из офиц. доков:
View decorView = getWindow().getDecorView();
decorView.setOnSystemUiVisibilityChangeListener
    (new View.OnSystemUiVisibilityChangeListener() {
@Override
    public void onSystemUiVisibilityChange(int visibility) {
    // Note that system bars will only be "visible" if none of the
    // LOW_PROFILE, HIDE_NAVIGATION, or FULLSCREEN flags are set.
    if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
        //системные панели открыты, их можно тут опять закрыть
    } else {
        //системные панели зарыты, их можно тут опять открыть
    }
}

});
В теории так можно предупредить появление нав. панели в момент, когда она хочет открыться.


text:
Q: Excel macro to email tables and graphs via Outlook I am trying to send Automate mail from Excel via Outlook mail to users. Within that i have requirement to send some Excel tables and graphs to certain users. The excel table should be placed after some text provided/written by sender and should retain the same table format in the email.
I am not able to get this functionality automate (sending excel table and graph in the email body) and require your help in sorting this out.
PS: I am using excel/Outlook 2010 (win)
Below is my overall code written as of now:
Sub Mail_to_MgmtTeam()

Dim OutApp As Object
Dim OutMail As Object
Dim strbody As String

Dim rng As Range

Dim x As Integer, y As Integer
Dim total_Resource As Integer

Application.ScreenUpdating = False

' Delete the Temp sheets, if any (just precautionary step)
Application.DisplayAlerts = False
On Error Resume Next
Sheets("Temp").Delete
Application.DisplayAlerts = True
Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = "Temp"

Sheets("Mail Details").Select
Range("A5").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets("Temp").Select
Range("A5").Select
ActiveSheet.Paste
Application.CutCopyMode = False

Columns("J:J").EntireColumn.Delete
Columns("A:A").EntireColumn.Delete
Range("A5").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select

'' Below code not getting executed successfully
'Selection.Select
'Set rng = Sheets("Temp").Selection.SpecialCells(xlCellTypeVisible)
'rng.Copy

' NEED HELP Here : TO send this selected TABLE within the email BODY to someone...

' code for sending the mails form Excel
Sheets("Mail Details").Select
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)

strbody = "Dear " & Cells(x + 5, 3).Value & ", " & _
       vbNewLine & vbNewLine & _
       "Below Table provides the overall statue of Pending Lists." & _
         vbNewLine & vbNewLine & vbNewLine & _
      "Thank You " & vbNewLine & "XYZ..."

On Error Resume Next
With OutMail
    .To = Sheets("Mail Details").Range("D6").Value
    .CC = ""
    .BCC = ""
    .Subject = "Excel Table Attached"
    .Body = strbody
    .Send
End With

On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing

MsgBox "Mails have been sent", vbDefaultButton1, "Mail Sent!!!"

End Sub

Thanks in advance
Kunal...

A: I was able to complete the task for which i had posted. I am posting the final code below for anyone who may need help in future on the similar line...
PS:

*

*I have segmented into different sets for easy of use. Please copy each code and paste it in in 'module' back to back

*The sheet name should be "RawData" and "ReportData"

*The Table should be placed in sheet "RawData"  and Column header should be in Row 5

*In sheet "RawData", in K Column, Mail ID is mentioned

Macro #1
Option Explicit
Dim folder_path As String
Dim chart_no As Integer
Dim file_path As String

Sub mail_2_IBUhead()

Dim OutApp As Object
Dim OutMail As Object
Dim strbody As String
Dim rng As Range
Dim x As Integer, y As Integer
Dim total_Resource As Integer

Application.ScreenUpdating = False

Sheets("RawData").Select

Call export_chart

Call Send_Automate_Mail

Sheets("RawData").Select
Range("A1").Select

'Delete the htm file we used in this function
Kill file_path & "Chart_1.png"

MsgBox "Draft Mails have been generated", vbDefaultButton1, "Mail Drafted!!!"

End Sub

Macro #2:
Private Sub Send_Automate_Mail()
' This macro would only send the mail...

Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object
Dim strbody_1 As String, strbody_2 As String, strbody_3 As String
Dim Start_row As Integer, Start_column As Integer, End_row As Integer, End_Column As Integer

' selecting the entire table range in the sheet
Sheets("RawData").Select
Range("A5").Select
Start_row = Selection.Row
Start_column = Selection.Column
Selection.End(xlToRight).Select
End_Column = Selection.Column
Range("A5").End(xlDown).Select
End_row = Selection.Row

Range(Cells(Start_row, 1), Cells(End_row, End_Column)).Select

Set rng = Selection.SpecialCells(xlCellTypeVisible)

If rng Is Nothing Then
    MsgBox "The selection is not a range or the sheet is protected. " & _
           vbNewLine & "Please correct and try again.", vbOKOnly
    Exit Sub
End If

With Application
    .EnableEvents = False
    .ScreenUpdating = False
End With

Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)

strbody_1 = "Dear User,
" & _
            " Below is the Graph....
  "

strbody_2 = "" & _
            " Below is the Table...
  "

strbody_3 = " This is an Automated mail. Please do not respond.

 " & _
            " Regards,
 Sender  "

file_path = folder_path & "\"

With OutMail
    .To = Sheets("RawData").Range("k6").Value
    .CC = ""
    .BCC = ""
    .Subject = "BE. RawData"
    .Attachments.Add file_path & "Chart_1.png"
    .htmlbody = strbody_1 & "
" & "
" & _
                "" & "
" & "
" & _
                strbody_2 & "
" & _
                RangetoHTML(rng) & "
" & _
                strbody_3
    .Importance = 2
    ' display the e-mail message, change it to ".send" to send the mail on running the macro
    .Display
End With
On Error GoTo 0

With Application
    .EnableEvents = True
    .ScreenUpdating = True
End With

Set OutMail = Nothing
Set OutApp = Nothing

End Sub

Macro #3:
Function RangetoHTML(rng As Range)
' this function is used in code "Send_Automate_Mail"
' do not change the code if you are new to coding :)
Dim fso As Object
Dim ts As Object
Dim TempFile As String
Dim TempWB As Workbook

TempFile = Environ$("temp") & "/" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"

'Copy the range and create a new workbook to past the data in
rng.Copy
Set TempWB = Workbooks.Add(1)
With TempWB.Sheets(1)
    .Cells(1).PasteSpecial Paste:=8
    .Cells(1).PasteSpecial xlPasteValues, , False, False
    .Cells(1).PasteSpecial xlPasteFormats, , False, False
    .Cells(1).Select
    Application.CutCopyMode = False
    On Error Resume Next
    .DrawingObjects.Visible = True
    .DrawingObjects.Delete
    On Error GoTo 0
End With

'Publish the sheet to a htm file
With TempWB.PublishObjects.Add( _
     SourceType:=xlSourceRange, _
     Filename:=TempFile, _
     Sheet:=TempWB.Sheets(1).Name, _
     Source:=TempWB.Sheets(1).UsedRange.Address, _
     HtmlType:=xlHtmlStatic)
    .Publish (True)
End With

'Read all data from the htm file into RangetoHTML
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
RangetoHTML = ts.ReadAll
ts.Close
RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", "align=left x:publishsource=")

TempWB.Close savechanges:=False
Kill TempFile

Set ts = Nothing
Set fso = Nothing
Set TempWB = Nothing

End Function

Macro #4:
Private Sub export_chart()
' this code will export all the graphs present in the sheet

Dim objCht As ChartObject
Dim x As Integer

folder_path = Application.ActiveWorkbook.Path

' for each graph present in the sheet, it will get exported
Sheets("ReportData").Select
x = 1
For Each objCht In ActiveSheet.ChartObjects
    objCht.Chart.Export folder_path & "\Chart_" & x & ".png", "PNG"
    x = x + 1
Next objCht

End Sub

Thanks,
Kunal...


text:
Q: os.system not running inside for loop data= pd.read_csv("ztf1.csv",usecols=[5],header=0)
#print(data)
names=data.columns

data1= pd.DataFrame(data,columns=names)
#print(data1)

for columnData in data1:
  os.system('wget --auth-no-challenge --user=xxxx@gmail.com --password=xxxx -O ztf.csv "https://irsa.ipac.caltech.edu/cgi-bin/ZTF/nph_light_curves?ID={0}&FORMAT=CSV"'.format('oid'))

This is my code.It dosent even give any errors.Just no output.


text:
Q: Difference in number of lines in Editpad Lite and Windows notepad I have a text file which when opened in Editpad Lite show the number of lines as 2754813 and when it is opened in Windows Notepad showing the number of lines as 2713520. When I read it with a C# programme, it shows the number of lines contained in the text file as 2713520 i.e. the same as in notepad. Wordwrap is turned off in both cases This prevents me from matching the lines with Editpad text file. Would anyone please offer their valuable comment.

A: int b = 0;
using (StreamWriter Writer = new StreamWriter(path_to_textfile.txt"))
{
  using (StreamReader Reader = new StreamReader(lisfile))
  {
    while ((line = Reader.ReadLine()) != null)
    {
      Match match = Regex.Match(line, @"");//line break symbol between quotes.
      if (match.Success)
      {
        b++;
        if (b == 100000) //I got the count of lines correctly.
        {
          Writer.WriteLine(line);
        }
      }
      else
      {
        //Writer.WriteLine(line);
      }

    }
  }
}