text:
Q: Writing own MenuBar in Dojo I'm trying to tidy up my code a bit, therefore one step I wanted to do is to transform my declarative markup from my navigation menubar into a programmatic one. I simply wanted to extend the class of dijit/MenuBar and add my functions in there. This is what it looks like so far:
define([ "util/debugger", "dojo/_base/declare", "dojo/_base/lang", "dojo/on",
    "dojo/ready", "dijit/MenuBar", "dijit/PopupMenuBarItem",
    "dijit/MenuItem", "dijit/DropDownMenu" ], function(debug, declare,
    lang, on, ready, MenuBar, PopupMenuBarItem, MenuItem, DropDownMenu) {
return declare("navMenu", [ MenuBar ], {

    constructor : function(kwArgs) {
        debug.log("constructor called", "navMenu.constructor()", 1);
        lang.mixin(this, kwArgs);
        /* Ansicht */
        var subMenuAnsicht = new DropDownMenu({});
        var item_showFilterBar = new MenuItem({
            label : "Filterleiste anzeigen"
        });
        subMenuAnsicht.addChild(item_showFilterBar);
        // [...]
        var test = new PopupMenuBarItem({
            label : "Ansicht",
            popup : subMenuAnsicht
        });
//---------
        this.addChild(test); // <==== this is where dojo says "c is null"
//---------
        /* Hilfe */
        var subMenuHelp = new DropDownMenu({});
        var item_showVersion = new MenuItem({
            label : "Versionsinfo"
        });
        on(item_showVersion, "click", clickVersionInfo);
        subMenuHelp.addChild(item_showVersion);
        // [...]
        this.addChild(new PopupMenuBarItem({
            label : "Hilfe",
            popup : subMenuHelp
        }));
        /* Meine Einstellungen */
        var subMenuMySettings = new DropDownMenu({});
        var item_showMySettings = new MenuItem({
            label : "Meine Einstellungen"
        });
        subMenuMySettings.addChild(item_showMySettings);
        // [...]
        this.addChild(new PopupMenuBarItem({
            label : "Meine Einstellungen",
            popup : subMenuMySettings
        }));
        /* Administration */
        // if (sessionHandler.getPermission == "admin") {
        var subMenuAdmin = new DropDownMenu({});
        var item_showUserManager = new MenuItem({
            label : "Userverwaltung"
        });
        subMenuAdmin.addChild(item_showUserManager);
        // [...]
        this.addChild(new PopupMenuBarItem({
            label : "Administration",
            popup : subMenuAdmin
        }));
        // }
        this.placeAt("navMenu");
        this.startup();
    } // [...]
})});

Unfortunately I get an error message "c is null". I guess there might be a problem with the this-function-call on the inherited addChild-method.
Anybody an idea?
Thanks in advance!

A: why dont you try dojo.extend and just provide the defination of those functions which you want to overrid or provide new functions
view that dojo.extend

A: The logic to add child widgets should be done in the postCreate method.  The following link will provide you a better understanding of the widget lifecycle.
http://dojotoolkit.org/documentation/tutorials/1.6/understanding_widget/
postCreate: function() {
  this.inherited(arguments);

  /* Ansicht */
  ...

  /* Hilfe */
  ...

  etc
}


text:
Q: Merge array lists into one array list I spent more time on this issue than I am willing to admit.
I have a function called:
def array_funct(filename):
...
 data = np.array((array))
 return data

which reads in .txt files from a folder and returns a numpy array.
The first row is a list of x coordinates and second row are the cooresponding y coordinates. Hence I use:
array_funct(filename)[:,0]
array_funct(filename)[:,1]

to access the x and y coordinates.
Now all I want to do is to create a for loop which would read in more than 1 file and store them in following way
for i in range(0,number_of_files):

    array_funct(file[i])[:,0]
    array_funct(file[i])[:,1]

Let's look at the x-lists which I get:
print(array_funct(file[0])[:,0])
[1,2,3,4]
print(array_funct(file[1])[:,0])
[2,4,6,8]

All I want is to take these two numpy like lists and create:
x_tot = [[1,2,3,4], [2,4,6,8]]

such that I can access the single lists element wise like:
x_tot[0] = [1,2,3,4]

Is that so hard? Should I stop using numpy array ? I would like to stay in numpy if possbile.
Also keep in mind that I made this example for just 2 files but it could be more. I just want to create a x_tot and y_tot for a variable amount of files I would read in. Such that:
x_tot = [[1,2,3],[2,3,4],[..],..]
x_tot = [[2,4,6],[4,6,8],[..],..]

A: Given the following array_funct function and filenames list:
def array_funct(filename):
    # Fake random data, replace with data read from file
    data_read = [[1,2,3,4], [5,6,7,8]] # [random.sample(range(1, 10), 7), random.sample(range(1, 10), 7)]
    data = np.array(data_read)
    return data

filenames = ['file1.txt', 'file2.txt']

Try this code:
lx = [list(array_funct(file)[0]) for file in filenames]
ly = [list(array_funct(file)[1]) for file in filenames]

Or more efficiently by reading and scrolling the file once:
all_data = [(list(arr[0]),list(arr[1])) for arr in [array_funct(f) for f in filenames]]
lx, ly = list(map(list, zip(*all_data)))

In both cases, the output is as follows:
# lx = [[1, 2, 3, 4], [1, 2, 3, 4]]
# ly = [[5, 6, 7, 8], [5, 6, 7, 8]]

A: Something like:
x_tot = np.array([array_funct(file[i])[:,0] for i in range(0,number_of_files)])

should work.

redpajama_set_name: RedPajamaStackExchange


text:
Q: I can't change Jenkins ListenAddress problem from 127.0.0.1 on MacOS I installed Jenkins via homebrew on macOS and used it well, then I updated macOS yesterday.
After restarting Jenkins today, I can't access it from other PCs.
Jenkins changed to listen on localhost:8080
I checked that the httpListenAddress is 0.0.0.0 in the homebrew.mxcl.jenkins-lts.plist .
Looking at Jenkins systemInfo, the following line looks strange.

sun.java.command /usr/local/opt/jenkins-lts/libexec/jenkins.war --httpListenAddress=127.0.0.1 --httpPort=8080

I am wondering where this httpListenAddress parameter came from.

A: After updating Jenkins via brew to 2.375.1 on macos 12.6 I could not access Jenkins on any machine in the same network other that the machine its installed in.
The cause, I believe, is the --httpListenAddress parameter being set to 127.0.0.1 instead of 0.0.0.0 that leads Jenkins to listen to requests from all available interfaces.
This post lead me to edit both the /usr/local/Homebrew/Library/Taps/homebrew/homebrew-core/Formula/jenkins-lts.rb and /Users//Library/LaunchAgents/homebrew.mxcl.jenkins-lts.plist, but the latter was always deleted when the brew service was stopped and recreated when it started, having --httpListenAddress the value of 127.0.0.1 again. A while later I found this answer and after doing as it instructs, the mentioned files were created as expected.


text:
Q: Expand div to specific height depending on amount of text I have set the height of a div to a specific value I.E 60px. I want the height of the div to expand to 80px and 100px depending on the amount of text in the div. I have tried to do this a few ways but as of yet haven't found a solution.
Here is my code.
  HTML

Text goes here, Text goes here, Text goes here,

supporting text

        CSS
        #header {
        height: 60px;
        width: 100%;
        background-color: #f4f6f8;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0px 20px;

    }

    Javascript

    function increase() {
        var text = parseInt(document.getElementById("header").style.height);
        if (text < 80) {
            document.getElementById("header").style.height = "60px";
        } else if (text == 80) {
            document.getElementById("header").style.height = "80px";
        } else if (text > 80){
            document.getElementById("header").style.height = "100px";
    }

    increase();

A:

variables and value are just placeholders, you can change it.

A:
parseInt(document.getElementById("header").style.height)

The style height of your element will be exactly whatever you set it to. For example "60px".
If you want to find the actual height of the div, instead of .style.height use .clientHeight.
If the text goes beyond the height of the div, you can use .scrollHeight to get the full height of the content.


text:
Q: Angular $sce.trustAsHtml on textarea with html identical to ng-model I have a textarea marked up and augmented with angular like the HTML below:
<textarea
  ng-model="message.reply"
  ng-bind-html="message.reply"
</textarea>

In my controller, I'm setting $scope.message.reply equal to a string with HTML on a response from an HTTP request.
In the success function on the HTTP request, I'm concatenating onto the message.reply string with HTML links.  However, in the textarea, these are appearing as text and not HTML.
In the success function my code looks something like this:
$scope.message.reply += $sce.trustAsHtml('' + res.data.file.link + '');
It's concatenating properly, but it's not trusting as HTML.  I have ngSanitize included in my project and it works elsewhere, but isn't working in this textarea.
What's the problem?

A: A textarea can not render HTML inside.


text:
Q: Display text given a counters current count At present I have a very basic Javascript counter-style function:

    <button type="button" onClick="onClick()">Add One To Chain</button>

Chain: 0

However now I wish to present the user with different text prompts at different points whilst counting.
For example if the counter reaches 10 I would like it to say hello, and if it reaches 20 it would say something like keep going, and at 30 STOP! and so on.
Any help would be much appreciated!

A: You could use a switch statement like so:
switch (clicks) {
    case 10:
        text = 'Hello';
        break;
    case 20:
        text = 'Keep going';
        break;
    case 30:
        text = 'STOP';
        break;
    default:
        text = clicks;
        break;
}
document.getElementById("clicks").textContent = text;

A: This is a dynamic approach. It will alert as many prompts as you fill in the prompts array.
var clicks = 0,
    prompts = ['Hello', 'Keep going', 'STOP'];

function onClick()
{
    clicks += 1;

    var promptKey = clicks / 10 - 1;

    if (clicks % 10 == 0 && prompts[promptKey] !== undefined) {
        alert(prompts[promptKey]);
    }

    document.getElementById("clicks").innerHTML = clicks;
};

A: You can use if else in Javascript for this to work.
Here is working example.

var clicks = 0;

function onClick1() {

  clicks += 1;

  if (clicks == 10) {
    alert("Hello");
  } else if (clicks == 20) {
    document.getElementById("clicks").style.color = "green";
    document.getElementById("clicks").innerHTML = clicks + " Keep Going";
  } else if (clicks == 30) {
    document.getElementById("clicks").style.color = "red";
    document.getElementById("clicks").innerHTML = clicks + "Stop !!";
  } else {
    document.getElementById("clicks").innerHTML = clicks;
  }
}
<button type="button" onClick="onClick1()">Add One To Chain</button>

Chain: 0

A: The easiest way to do it would be like this. I've included comments to help you understand what's up.

  <button type="button" onClick="onClick()">Add One To Chain</button>

Chain: 0

Hope that's helpful!

A: [Edited]:
The following will be more maintable : Steps and messages are stored in an object rather than hardcoded in a switch case loop.
var clicks = 0;
var messages = {"10": "hello", "20": "keep going", "30": "stop"};
function onClick() {
  clicks++;
  document.getElementById("clicks").innerHTML = (messages.hasOwnProperty(clicks.toString())) ? messages[clicks.toString()] : clicks;
  return;
};

see the following fiddle


text:
Q: xrdp fails from Windows 11 to CentOS Stream 9 I am trying to take a remote desktop connection from Windows 11 to CentOS Stream 9 running on Hyper V.
Below is the error msg:

Link to view xrdp.ini
Thanks!


text:
Q: Cypress: How to test HTML5 built in validation popup? How can we catch an HTML5 built in popup validation error when testing an App with Cypress? It does not seem to be showing up in the DOM so I have no clue about how to catch it with a cy command (I'm using testing-library).

A: You can refer the cypress FAQ for this.
cy.get('locator').then(($input) => {
  expect($input[0].validationMessage).to.eq('Your error message')
})


text:
Q: How to get the document object of a website? I have spent the last hour looking for a solution to this but couldn't figure it out. I am working on a chrome extension project and trying to use the mozilla/readability library which requires a document object as a parameter, but no matter what I try I get:
Error: First argument to Readability constructor should be a document object.

I have tried so many different things I have no idea:
window.document.documentElement.innerHTML (and outerHTML and just documentElement)
document.documentElement (and .innerHTML, outerHTML)
document

EDIT This is how I get my document from the content script (since I am working with Chrome extensions)
Pupup.js
const bgPage = chrome.extension.getBackgroundPage();
const dom = bgPage.dom;
console.log(dom);
let curArticle = new Readability(dom).parse();
console.log(curArticle);
setArticle(curArticle);

background.js
chrome.runtime.onMessage.addListener(receiver);

function receiver(request, sender, sendResponse) {
console.log(request);
dom = request.dom;
}

content.js
const message = {
type: "content",
dom: document,
};
chrome.runtime.sendMessage(message);


text:
Q: How to add timestamps to Java Applet console I need to time the Applet plugin startup time, and also the startup time of a specific Applet.
I have enabled debugging and tracing in the Java preferences, but the log and trace have no timestamps.
How can I enable them?
EDIT: I didn't develop this Applet, nor do I have access to the source code.


text:
Q: How to include static library into Swift project? I have a swift base project iPhone app. I would like to use Zoiper SDK within it.
What I got from them are static libraries (.a files):
- libcrypto.a
- libsipwrapper.a
- libssl.a

written probably in Objective-C.
And also external header files
- wrapper_defs.h,
- wrapper_cbk.h,
- wrapper.h

written in Objective-C.
I tried to add bridging header like this:
#ifndef ZoiperTest_Bridging_Header_h
#define ZoiperTest_Bridging_Header_h

#import "include/wrapper_defs.h"
#import "include/wrapper_cbk.h"
#import "include/wrapper.h"

#endif /* ZoiperTest_Bridging_Header_h */

But that returned lots of errors (types used in wrapper.h not being recognized)
Do I have to include also library .a files into bridging header?
What would be exact syntax for that?
I've tried adding #import   into bridge header but that gives me file not found error.

A: I could integrate zoiper SDK on a swift project. The easy way for me was create an Static Library on Objetive-C with the libs and integrate this on my swift project. -> https://github.com/depazsierra/zoiperExample
On the static library, i reused the ZSDKLibControl that came with zoiper example.
Any question, just let me know.

A: What you can do is the following and it worked for me. Create a static library from scratch. Add the .h (wrappers), including the LibController from the demo. Then once you finish follow this link: How can I use an .a static library in swift?
I was able to use the methods and all but not fully tested yet.


text:
Q: Return IEnumerable of DTOs including many-to-many mapping in single SQL SELECT I am using Automapper to project from an EF Core 2 entity to a DTO. My query returns an IEnumerable of DTO instances. One of the properties on my DTO is an IEnumerable that is populated via a many-to-many relationship off of the source entity. The solution laid out below works, however it results in many individual SQL SELECT queries.
Is there a way to map the many-to-many where EF can compile a single SELECT query rather than n queries?
TSource:
public class FilterList
{
    public int Id { get; set; }
    public ICollection<FilterListLanguage> FilterListLanguages { get; set; }
    public string Name { get; set; }
    public string ViewUrl { get; set; }
    ...
}

TDestination:
public class FilterListSummaryDto
{
    public int Id { get; set; }
    public IEnumerable<string> Languages { get; set; }
    public string Name { get; set; }
    public string ViewUrl { get; set; }
}

Mapping Profile:
CreateMap<FilterList, FilterListSummaryDto>()
    .ForMember(dto => dto.Languages,
        conf => conf.MapFrom(list => list.FilterListLanguages.Select(x => x.Language.Name)));

Query:
public async Task<IEnumerable<FilterListSummaryDto>> GetAllSummariesAsync()
{
    return await filterListsDbContext.FilterLists
                                     .AsNoTracking()
                                     .OrderBy(x => x.Name)
                                     .ProjectTo<FilterListSummaryDto>()
                                     .ToListAsync();
}

Example SQL Queries Executed:
...
SELECT `x.Language`.`Name`
FROM `filterlists_languages` AS `x0`
INNER JOIN `languages` AS `x.Language` ON `x0`.`LanguageId` = `x.Language`.`Id`
WHERE @_outer_Id = `x0`.`FilterListId`
Microsoft.EntityFrameworkCore.Database.Command:Information: Executed DbCommand (1ms) [Parameters=[@_outer_Id='82' (DbType = UInt16)], CommandType='Text', CommandTimeout='30']
SELECT `x.Language`.`Name`
FROM `filterlists_languages` AS `x0`
INNER JOIN `languages` AS `x.Language` ON `x0`.`LanguageId` = `x.Language`.`Id`
WHERE @_outer_Id = `x0`.`FilterListId`
Microsoft.EntityFrameworkCore.Database.Command:Information: Executed DbCommand (1ms) [Parameters=[@_outer_Id='86' (DbType = UInt16)], CommandType='Text', CommandTimeout='30']
SELECT `x.Language`.`Name`
FROM `filterlists_languages` AS `x0`
INNER JOIN `languages` AS `x.Language` ON `x0`.`LanguageId` = `x.Language`.`Id`
WHERE @_outer_Id = `x0`.`FilterListId`
Microsoft.EntityFrameworkCore.Database.Command:Information: Executed DbCommand (0ms) [Parameters=[@_outer_Id='85' (DbType = UInt16)], CommandType='Text', CommandTimeout='30']
...


text:
Q: Samsung Galaxy S camera crash unexpectedly My app crash without a stacktrace like what was asked here. I am also using Samsung Galaxy S. It works fine with my HTC desire. The solution is by "removing the preview view and re-instantiating it"
However, my surfaceview created is done this way
camera = (SurfaceView) findViewById(R.id.cameraview);

How can I solve this problem or how can i reinstantiate this SurfaceView?
02-21 15:57:20.305: ERROR/SecCamera(2357): startPreview: get the first frame of the preview
02-21 15:57:20.305: ERROR/CameraHardwareSec(2357): startPreview : return startPreview 0
02-21 15:57:20.305: DEBUG/CameraHardwareSec(2357): MemoryHeapBase(fd(33), size(3686464), width(640), height(480))
02-21 15:57:20.305: ERROR/CameraHardwareSec(2357): CameraHardwareSec: mPostViewWidth = 640 mPostViewHeight = 480 mPostViewSize = 614400
02-21 15:57:20.305: ERROR/CameraHardwareSec(2357): CameraHardwareSec: mRawHeap : MemoryHeapBase(previewHeapSize(614408))
02-21 15:57:20.305: WARN/CameraService(2357): width(640), height(480), format:yuv420sp
02-21 15:57:20.328: ERROR/SecCamera(2357): fimc_v4l2_streamoff()
02-21 15:57:20.336: ERROR/SecCamera(2357): ERR(fimc_v4l2_streamoff):VIDIOC_STREAMOFF failed
02-21 15:57:20.336: ERROR/SecCamera(2357): int android::SecCamera::stopRecord()::1494 fail. errno: No such device
02-21 15:57:20.336: ERROR/CameraHardwareSec(2357): ERR(previewThread):Fail on mSecCamera->stopRecord()
02-21 15:57:20.363: WARN/CameraService(2357): startRecording (pid 2357)
02-21 15:57:20.367: WARN/CameraService(2357): startCameraMode(1) (pid 2357)
02-21 15:57:20.367: WARN/CameraService(2357): startRecordingMode (pid 2357)
02-21 15:57:20.367: DEBUG/SecCamera(2357): passed fmt = 842094164 found pixel format[8]: YUV 4:2:0 planar, Y/CbCr, Tiled
02-21 15:57:20.367: ERROR/SecCamera(2357): startRecord: m_recording_width = 320, m_recording_height = 240

A: I think there should be some problem with setting preview parameters.
Try below.
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {

if (isPreviewRunning) {
    camera.stopPreview();
}
try{
Camera.Parameters p = camera.getParameters();
if(p!=null){
List<Size> sizes = p.getSupportedPreviewSizes();
Size optimalSize = getOptimalPreviewSize(sizes, w, h);
p.setPreviewSize(optimalSize.width, optimalSize.height);
camera.setParameters(p);

camera.setPreviewDisplay(holder);;
camera.startPreview();

}
} catch (IOException e) {
    // TODO Auto-generated catch block

    e.printStackTrace();
}

isPreviewRunning = true;
}
private Size getOptimalPreviewSize(List<Size> sizes, int w, int h) {
// TODO Auto-generated method stub
final double ASPECT_TOLERANCE = 0.05;
double targetRatio = (double) w / h;
if (sizes == null) return null;

Size optimalSize = null;
double minDiff = Double.MAX_VALUE;

int targetHeight = h;

// Try to find an size match aspect ratio and size
for (Size size : sizes) {
double ratio = (double) size.width / size.height;
if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}

// Cannot find the one match the aspect ratio, ignore the requirement
if (optimalSize == null) {
minDiff = Double.MAX_VALUE;
for (Size size : sizes) {
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
}
return optimalSize;
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {

if (isPreviewRunning) {
    camera.stopPreview();
}
try{
Camera.Parameters p = camera.getParameters();
if(p!=null){
List<Size> sizes = p.getSupportedPreviewSizes();
Size optimalSize = getOptimalPreviewSize(sizes, w, h);
p.setPreviewSize(optimalSize.width, optimalSize.height);
camera.setParameters(p);

camera.setPreviewDisplay(holder);;
camera.startPreview();

}
} catch (IOException e) {
    // TODO Auto-generated catch block

    e.printStackTrace();
}

isPreviewRunning = true;
}

private Size getOptimalPreviewSize(List sizes, int w, int h) {
// TODO Auto-generated method stub
final double ASPECT_TOLERANCE = 0.05;
double targetRatio = (double) w / h;
if (sizes == null) return null;

Size optimalSize = null;
double minDiff = Double.MAX_VALUE;

int targetHeight = h;

// Try to find an size match aspect ratio and size
for (Size size : sizes) {
double ratio = (double) size.width / size.height;
if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}

// Cannot find the one match the aspect ratio, ignore the requirement
if (optimalSize == null) {
minDiff = Double.MAX_VALUE;
for (Size size : sizes) {
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
}
return optimalSize;

}
Put this code in your surfaceChanged(). getOptimalPreviewSize() is used to set preview parameters according to device resolution.

A: Well, I upgraded the firmware to 2.3.3 and it is working now.


text:
Q: Function doesn't display data from JSON In my webapp I have a page where I use getJSON to get data from server. Firebug shows that it get's JSON from server just the way it is supposed to, but no data is shown. What could be the problem? Here is what my code looks like:
 $('#detailsPage').live('pageshow', function(event) {
    var id = getUrlVars()["id"];
    $.getJSON(serviceURL + 'getemployee.php?id='+id+'&callback=?', displayEmployee);
});

function displayEmployee(data) {
    var employee = data.item;
    $('#employeePic').attr('src', 'pics/' + employee.PIC);
    $('#fullName').text(employee.NAME);
    $('#employeeTitle').text(employee.TITLE);
    $('#lisatieto').text(employee.INFO);

    if (employee.puhelin_nro) {
        $('#actionList').append('

Soita puhelimeen

');
        $('#actionList').append('

SMS

');
    }
    $('#actionList').listview('refresh');

}

Console shows
employee is undefined
[Break On This Error]

$('#employeePic').attr('src', 'pics/' + employee.PIC);

This is the JSON response:
jQuery164008509381752724021_1336981793995({
    "key": [
        {
            "PIC": "Tuntematon",
            "NAME": "0",
            "TITLE": "0",
            "INFO": "0"
        }
    ]
})

A: You need to use this
var employee = data.key[0];


text:
Q: See if there is a leasing in a selected period of time I need help again. I am vurrently working on a sample project. And there I have a listBox with cars that are available for the selected period of time. This period of time is selected through DateTime-Control in Windows Forms.
So I've got a loop (foreach) where I delete all of the list entries which are not available for the selected time period.
it looks like this
int recordsRemoved = availableCars.RemoveAll(f =>f.ObjectID == v.Car &&  dtStartDate.Value >= v.StartDate | dtEndDate.Value <= v.EndDate);

dtStartDate is the Windows Forms Control and v.StartDate is the StartDate from the rent in my DataBase.
I hope it is understandable so far...
As you can probably tell, my "if" doesn't work the way I want to. What I need is an option where it deletes every car which is already rent from (for example) 10.05.2016 to 17.05.2016.
When I select 10.05.2016 to 17.05.2016 I don't want any car to be in the list which would be (for example) rent from 12.05.2016 to 23.05.2016.
Well, once again, I hope I could explain it so that you can understand it.
Many thanks in advance

A: Try Where like below:
int recordsRemoved = availableCars.RemoveAll(availableCars.Where(f =>f.ObjectID == v.Car &&  dtStartDate.Value >= v.StartDate && dtEndDate.Value <= v.EndDate));


text:
Q: nodejs/mongodb, remove entire collection I'm trying to remove all items in a collection.
db.collection('sessions', function(err, collection) {
    collection.remove();
});

This is the error I get:
node.js:134
        throw e; // process.nextTick error, or 'error' event on first tick
        ^
TypeError: Cannot call method 'getRequestId' of null
    at [object Object].executeCommand (/srv/www/www.cidev.com/nodejs/node_modules/mongodb/lib/mongodb/db.js:778:48)
    at Collection.remove (/srv/www/www.cidev.com/nodejs/node_modules/mongodb/lib/mongodb/collection.js:199:26)
    at /srv/www/www.cidev.com/nodejs/session/memory/index.js:15:20
    at [object Object].collection (/srv/www/www.cidev.com/nodejs/node_modules/mongodb/lib/mongodb/db.js:197:12)
    at new <anonymous> (/srv/www/www.cidev.com/nodejs/session/memory/index.js:14:11)
    at Object.<anonymous> (/srv/www/www.cidev.com/nodejs/session/memory/index.js:157:16)
    at Module._compile (module.js:411:26)
    at Object..js (module.js:417:10)
    at Module.load (module.js:343:31)
    at Function._load (module.js:302:12)

However, I can do this via mongodb fine:
db.sessions.remove();

What's the best way to achieve what I want via node?
Thanks

A: Going back to this... just to update the question.
store.collection('sessions',function(err, collection){
    collection.remove({},function(err, removed){
    });
});

A: I know this is a little late to the party and much has changed, but to remove a collection in node, you do this:
db.collection('someCollection').drop();

From the mongo terminal you do this:
db.someCollection.drop();

It's that simple.

A: Providing a more recent answer, based on API changes and trying the previous answers myself.
The following example represents a block of code as we use it in our integration tests:
const mongoUrl = 'mongodb://localhost:27017/test-database';
const mongoClient = await MongoClient.connect(mongoUrl, {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

const database = mongoClient.db();
if (database) {
  const collections = await database.listCollections();
  await collections.forEach(async collection => {
    console.log(`Dropping ${collection.name}`);
    await database.collection(collection.name).drop();
  });
}

Note, while you could use the following, it will fail if you don't have full permissions over the database, such as in Mongo Cloud:
await database.dropDatabase();

For context, I was using mongodb package 3.5.9 and node 14.15.1.

A: I'm not sure whether you were able to figure this out, but your code did not work for me...perhaps because of changes in the API? Anyway I was able to remove an entire collection's contents using the following code:
db.CollectionName.remove().exec(function(error) {
    if(error) {
        console.log('Uh oh: ' + error);
    }
    else {
        console.log('    [Existing Collection Deleted]');
    }
 });


text:
Q: Como plotar um gráfico de linha com cores diferentes dependendo do valor? Suponha os seguintes dados:
set.seed(1)
y<-rnorm(101)
x<-seq(from=0, to=100,by=1)

Quero fazer um plot com uma linha que tenha cor diferente para valores negativos.
Para fazer um gráfico de pontos basta o comando abaixo:
plot(x,y,col=ifelse(y>0,"blue","red"))

No entanto, se altero para um gráfico de linha não funciona.
plot(x,y,col=ifelse(y>0,"blue","red"),type="l")

Se tento fazer com o ggplot2 também não está dando certo. Ele atribui ao segmento da linha a cor do ponto anterior.
library(ggplot2)
df<-data.frame(x,y)
df$cat<-y>0
ggplot(df,aes(x,y,color=cat)) + geom_path(aes(group=1))

Como fazer para o R atribuir corretamente a cor vermelha para valores negativos e cor azul para valores positivos no plot de linha?

A: Uma "solução" parcial seria gerar um spline com muitos pontos (uns 100 por exemplo) que aí as cores teriam menor probabilidade de ficarem em lugar errado.  Mas essa solução pode gastar muita memória se sua base de dados for grande e vai suavizar o gráfico. Ex:
df2 <- data.frame(spline(df$x, df$y, n = 100*nrow(df)))
df2$cat <- df2$y>0
ggplot(data = df, aes(x, y))+ geom_line(data=df2, aes(color=cat, group=1))


text:
Q: illegal-attempt-to-map-a-non-collection-as-a-onetomany-manytomany-or-collectionofelements in Spring I want to send a JSON as POST Request to insert into the database. Following is the JSON
{
    "url": "https://www.tec.com",
    "status":"Regular",
     "Student":
     {
         "id": 1,
         "name": "John Doe",
         "age": 12
    }
}

where I have the main class
Data.java
@ToString
@Setter
@Getter
@Entity
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "data")
public class Data implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public int id;
    private String url;
    private String status;

    @ElementCollection
    private Student student;
}

Student.java

@ToString
@Setter
@Getter
@AllArgsConstructor
@Entity
@NoArgsConstructor
@Table(name = "Student")
public class Student implements Serializable {
    @Id
    private int id;
    private String name;
    private int age;
}

Please tell me how to resolve this .So that the data should save in the database when I send the JSON on the above-specified format.

A: You are getting this error message because you placed the @ElementCollection annotation on student.
This annotation is meant for collections. It is meant to be placed on entity members which are collections such as a Set, List, etc.
You should remove this annotation from student and replace it with @OneToOne
public class Data implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public int id;
    private String url;
    private String status;

    @OneToOne(cascade=CascadeType.ALL)
    private Student student;
}

@OneToOne means there is one Student for every one Data
(cascade=CascadeType.ALL) means if you save Data, its student will also be saved.
Another option is to replace the single student with a collection of students.


text:
Q: Zeroizing IBuffer? I am currently building a Windows Store App that uses cryptography. This means extensive use of the CryptographicBuffer class. The app is very security-sensitive, so I would like to make sure to Zeroize any Buffer's immediately after use. I am doing the same thing with byte[]'s when I use them.
To Zeroize them, currently we'd like to:

*

*Write all 1's.

*Write a pattern. Currently using 0,1,2,...254,255,0,1...

*Write all 0's.

The solution I have come up with is to create an extension method for each of IBuffer and byte[] which will do this for me. For byte[] I believe it's pretty straightforward:
public static void Zeroize(this byte[] bytes)
{
    for (int i = 0; i < bytes.Length; i++)
    {
         bytes[i] = 255;
    }
    for (int i = 0; i < bytes.Length; i++)
    {
        bytes[i] = (byte)(i % 255);
    }

    for (int i = 0; i < bytes.Length; i++)
    {
        bytes[i] = 0;
    }
}

For IBuffer, it's a little bit more difficult, in that you don't seem to get direct access to the Buffer. Through System.Runtime.InteropServices.WindowsRuntime; you do seem to get a few useful methods, such as IBuffer.CopyTo and IBuffer.AsStream, which give you direct access to the Buffer or underlying Stream. The solution I have come up with is this:
public static void Zeroize(this IBuffer buffer)
{
    var capacity = buffer.Capacity;
    byte[] toWrite = new byte[capacity];
    for (int i = 0; i < capacity; i++)
    {
        toWrite[i] = 255;
    }

    toWrite.AsBuffer().CopyTo(buffer);

    for (int i = 0; i < capacity; i++)
    {
        toWrite[i] = (byte)(i % 255);
    }

    toWrite.AsBuffer().CopyTo(buffer);

    for (int i = 0; i < capacity; i++)
    {
            toWrite[i] = 0;
    }

    toWrite.AsBuffer().CopyTo(buffer);
}

My questions are thus: Is there a better way to be doing this? Is there any other hidden methods (InteropServices isn't really advertised all that well) that would make this a bit easier/more efficient/more secure?
Note: I realize the Zeroization process may be overkill, but it is requested by the Owner.


text:
Q: How to transactionally poll Kafka from Camel? I'm currently working on message bus based on kafka and managed by camel and Spring. I have a XML route definition to poll events and retrieve the corresponding complete business objects from an external API that looks like that :
`
<route id="station-event-enrich-route" autoStartup="true" >
        <from
            uri="kafka:{{kafka.cluster.url}}?brokers={{kafka.cluster.url}}&topic={{events.topic.name}}&autoCommitEnable=false&allowManualCommit=true&maxPollRecords={{station.brocker.bulk.limit}}&groupId={{kafka.groupId}}" />

        <!-- SNIP logic to aggregate several events -->

        <pollEnrich strategyRef="keepHeadersAggregationStrategy">
            <simple>{{api.url}}?view=full&id=$simple{in.headers.BUSINESS_ID}</simple>
        </pollEnrich>

        <!-- SNIP logic to split the retrieved events according to their ids -->

        <to uri="velocity:velocity/resource-object.vm"/>

        <removeHeaders pattern="*" excludePattern="MANUAL_COMMIT"/>

        <to uri="kafka:{{kafka.cluster.url}}?brokers={{kafka.cluster.url}}&topic={{objects.topic.name}}&groupId={{kafka.groupId}}&requestRequiredAcks=all" />

        <transform>
            <simple>${headers.MANUAL_COMMIT.commitSync()}</simple>
        </transform>
</route>

`
My problem is the following : when the kafka event topic is polled, and if the api.url in my pollEnrich is not available, no business object is retrieved and the event is lost. So I need to implement a transactional logic to be able to rollback on the initial kafka polling in my route so that the same event could be polled several times till the api.url send me the awaited business object.
I tried several approaches, starting from updating my version of org.apache.camel:camel-kafka to 2.22.0 to be able to play with the manual commit. Then, I tried to implement a basic error handler (configured with maximumRedeliveries=-1 to have infinite retries) so that when the pollEnrich triggers a onException, I can set a header to avoid doing the final manual commit. It works, apparently, but my event is never repolled again.
I also tried to use the transacted tag with a org.springframework.kafka.transaction.KafkaTransactionManager instance from spring-kafka, but it's not the good approach as only the producers are transactional.
What I am missing, and what is the correct approach ?
I use Java 8, Camel 2.22.0 and Spring 4.3.18.RELEASE (not recommended but it should work).

A: It looks like a relatively new feature in Camel to support Kafka manual commits. And the documentation wasn't particularly clear. I'm using Camel 2.22.1.
From the description of your problem, you are looking for "at least once" semantics. That is you want to be able to re-process a message when there was an issue. Of course the result of this approach is that no other messages in the partition w/ a failing message can be processed (or seen) until the application can successfully process it. In the case of a failing service, this would likely result in all partitions for a given topic being blocked until the service is back up.
The Kafka uri to get this to work would look like this:
kafka:TestLog?brokers=localhost:9092&groupId=kafkaGroup&maxPollRecords=3&consumersCount=1&autoOffsetReset=earliest&autoCommitEnable=false&allowManualCommit=true&breakOnFirstError=true
Breaking that down a bit:

*

*kafka:TestLog : specifies the Kafka topic to consume from

*brokers=localhost:9092 : specifies the bootstrap servers for Kafka cluster

*groupId=kafkaGroup : specifies the Kafka consumer group

*consumersCount=1 : specifies the number of Kafka consumers for that Camel route

The last two configuration settings are important when consuming from a Kafka topic with a number of partitions. They need to be tuned/configured so that they are taking into account the number of Camel instances you are planning to run.
The more interesting configuration to get to "at least once" semantics:

*

*autoCommitEnable=false : turn off auto committing of offsets so we can use manual commits.

*allowManualCommit=true : turn on manual commits, giving us access to the KafkaManualCommit capability (see code below).

*breakOnFirstError=true : when this is true, the route will stop processing the rest of the messages in the batch received on last poll of the topic.

*maxPollRecords=3 : specifies the number of messages consumed during a single poll of the Kafka topic.It is probably is a good idea to keep this set to a low number, since issues w/ a message in the batch would cause all of the messages in the batch to be re-processed.

*autoOffsetReset=earliest : will cause the consumer to read from the earliest offset when there is a difference between the current offset and the offset marking the end of the partition (more on that in a bit).

The Camel route would look something like this:
      from(kafkaUrl)
        .routeId("consumeFromKafka")
        .process(exchange -> {
            LOGGER.info(this.dumpKafkaDetails(exchange));
        })
        .process(exchange -> {
            // do something
        })
        .process(exchange -> {
            // do something else
        })
        .process(exchange -> {
            exchange.setProperty(Exchange.FILE_NAME, UUID.randomUUID().toString() + ".txt");
        })
        .to("file://files")
        // at the end of the route
        // manage the manual commit
        .process(exchange -> {
            // manually commit offset if it is last message in batch
            Boolean lastOne = exchange.getIn().getHeader(KafkaConstants.LAST_RECORD_BEFORE_COMMIT, Boolean.class);

            if (lastOne) {
                KafkaManualCommit manual =
                        exchange.getIn().getHeader(KafkaConstants.MANUAL_COMMIT, KafkaManualCommit.class);
                if (manual != null) {
                    LOGGER.info("manually committing the offset for batch");
                    manual.commitSync();
                }
            } else {
                LOGGER.info("NOT time to commit the offset yet");
            }
        });

After running this route and getting an error you can see the state of the consumer group with this command:
./bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --group kafkaGroup --describe

that might yield this result:

   TOPIC     PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG
   TestLog   0          92              95              3

This is where the autoOffsetReset setting comes into play. The current offset is where the consumer group wants to consume from. If that offset (92) is the error message, then the group will fall behind as more messages (in this case two more) are added. The route (using the given settings) will cause Camel to continually process the message at offset 92 until it succeeds. If the Camel route is stopped and started, the application would pick up consuming from the earliest offset (the 92) and not the latest which would be 95 based on autoOffsetReset. Using latest would result in "lost" messages, because a restart of Camel would start processing using latest offset.
A sample application is available here

A: If you are getting null value from this exchange.getIn().getHeader(KafkaConstants.MANUAL_COMMIT, KafkaManualCommit.class)
You need to set allowManualCommit=true in kafka uri


text:
Q: Is looking for Wi-Fi access points purely passive? Say I carry a Wi-Fi enabled phone or laptop through an area where there are WAPs.  Assuming that I don't actively try to connect to them or otherwise interact with them, is it possible for the owner of that WAP to know that I was there?
I'm asking this in the context of my earlier question:  Looking for MACs on the network
I was talking with a friend about my newfound ability to detect phones (and other devices with MAC addresses) on the network, and he pointed out that it might be useful to detect unknown phones on the network; I could use that data to track down anyone who was in my house and brought a Wi-Fi phone with them.
So, if I set up a logging fake WAP with no security or encryption, can I glean any useful information about the devices that come into the house?  Assuming that the thief doesn't actively try to connect...

A: No, looking for 802.11 APs is primarily active. When you bring up a list of visible APs in the area, your 802.11 client most likely does what's known as an "active scan", where it tunes its radio to each supported channel in turn, transmits a Probe Request frame, and waits perhaps 20-40ms to gather Probe Response frames from any APs on that channel before moving on to the next channel. This allows it to scan all the channels much faster than a "passive scan".
A "passive scan" is possible, but isn't used very often because it takes longer. To do a passive scan, the client tunes to each channel in turn, and waits a typical Beacon Interval (usually about 100ms, but could be more) to gather Beacons.
Some channels in 5GHz in some regulatory regions require that you scan passively first, until you know that the channel is not in use by nearby radar installations. But most clients, as soon as they see a Beacon on a passive-scan channel, will switch to an active scan to speed up the process.
If your client device is on, and hasn't given up looking for your recently-joined/preferred/remembered networks, it will almost certainly be broadcasting Probe Requests which give away not only your wireless MAC address and some of the capabilities of your card, but often also the name the network it's looking for. This is necessary in case the network is a "hidden" (a.k.a. "non-broadcast SSID", a.k.a. "closed") network.
It's pretty trivial to learn people's wireless client MAC addresses and also the names of their home and work networks just by hanging out at the office or a coffee shop or airport terminal with an 802.11 monitor mode packet sniffer, recording Probe Requests.

A: This recent paper presented at the Internet Measurement Conference 2013 might be interesting to you:
Signals from the Crowd: Uncovering Social Relationships through Smartphone Probes
Abstract:

The ever increasing ubiquitousness of WiFi access points, coupled
  with the diffusion of smartphones, suggest that Internet every time
  and everywhere will soon (if not already has) become a reality. Even
  in presence of 3G connectivity, our devices are built to switch
  automatically to WiFi networks so to improve user ex-perience. Most of
  the times, this is achieved by recurrently broadcasting automatic
  connectivity requests (known as Probe Requests) to known access points
  (APs), like, e.g., "Home WiFi", "Campus WiFi", and so on. In a large
  gathering of people, the number of these probes can be very high. This
  scenario rises a natural question: "Can significant information on
  the social structure of a large crowd and on its socioeconomic status
  be inferred by looking at smartphone probes?".
In this work we give a
  positive answer to this question. We organized a 3-months long
  campaign, through which we collected around 11M probes sent by more
  than 160K different devices. During the campaign we targeted national
  and international events that attracted large crowds as well as other
  gatherings of people. Then, we present a simple and automatic
  methodology to build the underlying social graph of the smartphone
  users, starting from their probes. We do so for each of our target
  events, and find that they all feature social-network properties. In
  addition, we show that, by looking at the probes in an event, we can
  learn important sociological aspects of its participants language,
  vendor adoption, and so on

A: There is a system called Jasager that detects WiFi probes that most clients shout out ("Hello, is linksys there", etc), pretends to be it, lets them automatically connect as if they are 'at home', with that lovely 'public' networking option Windows now has.
Lo and behold, all their public fileshares, web traffic (and there are extensions for it that let you MITM attack SSL sessions) and anything else you can think of.
Enjoy and don't get caught.

A: I recommend you get hold of Backtrack and try running airodump-ng (or else install aircrack if on Linux). That'll show you what's going on with the devices and whether they are visible / probing for network addresses. You can use airbase-ng to act as an access point.
Note there may be legal issues around doing this depending on what country you live in.

A: Unless you have a hotspot server or some other server running. A wireless antenna turned on merely passively listens for SSIDs that are broadcasting. But if you have a hidden network that you connect to, there are some emissions you are transmitting and perhaps that could be exploited.
Hypothetically, say someone knows you automatically connect to an SSID that is hidden, and they know the credentials (perhaps they saw this on your computer). That is enough now to make a connection. From there the possibilities are endless.


text:
Q: Getting "Cannot read property 'nodeType' of null" when calling ko.applyBindings I have this knockout code:
function Task(data) {
    this.title = ko.observable(data.title);
    this.isDone = ko.observable(data.isDone);
}

function TaskListViewModel() {
    // Data
    var self = this;
    self.tasks = ko.observableArray([]);
    self.newTaskText = ko.observable();
    self.incompleteTasks = ko.computed(function() {
        return ko.utils.arrayFilter(self.tasks(), function(task) { return !task.isDone() });
    });

    // Operations
    self.addTask = function() {
        self.tasks.push(new Task({ title: this.newTaskText() }));
        self.newTaskText("");
    };
    self.removeTask = function(task) { self.tasks.remove(task) };
}

ko.applyBindings(new TaskListViewModel());

This html:

Tasks

    <form data-bind="submit: addTask">
        Add task: <input data-bind="value: newTaskText" placeholder="What needs to be done?" />
        <button type="submit">Add</button>
    </form>

 0">

            <input type="checkbox" data-bind="checked: isDone" />
            <input data-bind="value: title, disable: isDone" />
            Delete

    You have   incomplete task(s)
     - it's beer time!

The example is the same as the one found on the Knockout website, but when I run it, it returns this message on Chrome Fire Bug:

Uncaught TypeError: Cannot read property 'nodeType' of null

This one is related to the knockout file and to this line of my script:
ko.applyBindings(new TaskListViewModel());

And this error is pointing to this line (1766) on knockout:
var isElement = (nodeVerified.nodeType == 1);

What am I doing wrong?

A: You have a simple spelling mistake:
self.addTask = fuction() {

Should be:
self.addTask = function() { //Notice the added 'n' in 'function'

A: You might want to consider using the jquery ready handler for this
$(function() {
   function TaskListViewModel() {
   ...
   ko.applyBindings(new TaskListViewModel());
});

Then you achieve two things:

*

*Avoid polluting the global namespace

*Knockout binding occurs AFTER the DOM is created.  You can place your javascript wherever it is suited for organization.

See http://api.jquery.com/ready/

A: if you have jQuery put apply binding inside onload so that knockout looks for the DOM when DOM is ready.
$(document).ready(function(){
    ko.applyBindings(new TaskListViewModel());
});

A: This problem was happening because I was trying to bind an HTML element before it was created.
My script was loaded on top of the HTML (in the head) but it needed to be loaded at the bottom of my HTML code (just before the closing body tag).
Thanks for your attention James Allardice.
A possible workaround is using defer="defer"

Use this if the script is not going to generate any document content. This will tell the browser that it can wait for the content to be loaded before loading the script.
Further reading.
Hope it helps.


text: Q: How to skip a click in a web-page? Sometime, In some web pages, you always know the first click will pop-up ads. Is there a way to skip this click in a web page? I want the browser to click but not fetch the data of that click.


text:
Q: WPF ContextMenu woes: How do I set the DataContext of the ContextMenu? I am having some trouble figuring out how to set the correct DataContext on a ContextMenu.
I have a collection of view models who are the source of an ItemsControl.  Each view model has a collection of items which are also the source of another ItemsControl.  Each item is used to draw image which has a ContextMenu.  The MenuItems in that ContextMenu need to bind to a command on the view model, but the PlacementTarget of the ContextMenu is pointing to the individual item.
My Xaml looks something like this:
<ItemsControl ItemsSource="{Binding Markers"}>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <ItemsControl ItemsSource="{Binding Items}">
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <Image>
                            <Image.ContextMenu>
                                <ContextMenu>
                                     <MenuItem Header="Edit" Command="{Binding EditCommand}" />
                                </ContextMenu>
                            </Image.ContextMenu>
                        </Image>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

How can I set the DataContext of the ContextMenu to the item's corresponding parent view model?

A: The ContextMenu is outside of the visual tree.  Below is the xaml that should get you the datacontext:
<ItemsControl ItemsSource="{Binding Markers}" Tag="{Binding ElementName=outerControl, Path=DataContext}">
   ...
   <ContextMenu DataContext="{Binding Path=PlacementTarget.Tag, RelativeSource={RelativeSource Self}}">
      <MenuItem Header="Edit"
                Command="{Binding EditCommand}" />
   </ContextMenu>
   ...
</ItemsControl>

This post explains how this works.

A: I don't like use Tag. I prefer attached property.
You need add attached property:
public static readonly DependencyProperty DataContextExProperty =
   DependencyProperty.RegisterAttached("DataContextEx",
                                       typeof(Object),
                                       typeof(DependencyObjectAttached));

public static Object GetDataContextEx(DependencyObject element)
{
    return element.GetValue(DataContextExProperty);
}

public static void SetDataContextEx(DependencyObject element, Object value)
{
    element.SetValue(DataContextExProperty, value);
}

In XAML:
<Button attached:DependencyObjectAttached.DataContextEx="{Binding ElementName=MyDataContextElement, Path=DataContext}">
    <Button.ContextMenu>
        <ContextMenu DataContext="{Binding RelativeSource={RelativeSource Self}, Path=PlacementTarget.(attached:DependencyObjectAttached.DataContextEx)}">
        </ContextMenu>
    </Button.ContextMenu>
</Button>

A: You can use a markupextension:
using System;
using System.Windows.Controls;
using System.Windows.Markup;
using System.Xaml;

[MarkupExtensionReturnType(typeof(ContentControl))]
public class RootObject : MarkupExtension
{
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        var rootObjectProvider = (IRootObjectProvider)serviceProvider.GetService(typeof(IRootObjectProvider));
        return rootObjectProvider?.RootObject;
    }
}

It lets you do:
<ItemsControl ItemsSource="{Binding Markers}">
   ...
   <ContextMenu DataContext="{Binding DataContext, Source={local:RootObject}}">
      <MenuItem Header="Edit"
                Command="{Binding EditCommand}" />
   </ContextMenu>
   ...
</ItemsControl>

A: This code allows you to use both the global and local DataContext (of entire userControl and of current TreeViewItem):
<TreeView Grid.Row="0" ItemsSource="{Binding Path=SelectableEnterprises}">
<TreeView.ItemTemplate>
    <HierarchicalDataTemplate ItemsSource="{Binding Children}">
        <Grid Height="20" Tag="{Binding DataContext, ElementName=userControl}">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="25"/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
            <Grid.ContextMenu>
                <ContextMenu DataContext="{Binding PlacementTarget, RelativeSource={RelativeSource Self}}" >
                    <ContextMenu.Visibility>
                        <MultiBinding Converter="{converters:SurveyReportVisibilityConverter}">
                            <Binding Path="DataContext"/> <!--local DataContext-->
                            <Binding Path="Tag.SelectedSurvey"/> <!--global DataContext-->
                        </MultiBinding>
                    </ContextMenu.Visibility>

                    <MenuItem Header="Show HTML-report" Command ="{Binding Tag.OpenHTMLReportCommand}"
                              CommandParameter="{Binding DataContext}" />
                </ContextMenu>
            </Grid.ContextMenu>


text:
Q: Two doubts about proof of Doob's Martingale Inequalities Theorem on Jacod-Protter I quote Jacod-Protter.

Theorem Let $M=(M_n)_{n\geq0}$ be a martingale and define $M_n^*=\sup_{j\leq n}|M_j|$. Let $1 < p < \infty$. There exists a constant $c$ depending only on $p$ such that
  \begin{equation}
\mathbb{E}\{(M_n^*)^p\} \leq c\mathbb{E}\{|M_n|^p\}
\end{equation}

The proof of the above theorem ends in the following manner:
\begin{equation}
\mathbb{E}\{(M_n^*)^p\}\leq\int_0^{\infty}p2p\lambda^{p-2}\mathbb{E}\{|M_n|\mathbb{1}_{\{|M_n|>\frac{\lambda}{2}\}}\}d\lambda = \mathbb{E}\{\int_0^{2|M_n|}2p\lambda^{p-2}d\lambda|M_n|\}=\frac{2^{p}p}{p-1}\mathbb{E}\{|M_n|^{p}\}
\end{equation}
At this point, the theorem is considered as proven and it is stated that

we showed in the proof of above theorem that the constant $c\leq \frac{2^p p}{p-1}$. With more work one can show that $c^{\frac{1}{p}}=\frac{p}{p-1}$

As to the last line above, I would have two doubts and, as a consequence, two observations:
FIRST:
Considering the way in which the theorem is stated, I think it would be correct to state that the constant $c\geq\frac{2^p p}{p-1}$ (that is, $c$ is at least equal to $\frac{2^p p}{p-1}$ for the above theorem inequality to hold true) and NOT the constant $c\leq\frac{2^p p}{p-1}$ (that is, $c$ is at most equal to $\frac{2^p p}{p-1}$ for the above theorem inequality to hold true)
SECOND:
I would say that $c^{\frac{1}{p}}=\frac{2(p)^{\frac{1}{p}}}{{(p-1)}^{\frac{1}{p}}}=2(\frac{p}{p-1})^{\frac{1}{p}}$ and NOT that $c^{\frac{1}{p}}=\frac{p}{p-1}$
Are my observations correct?

A: For the first doubt :

we showed in the proof of above theorem that the constant $c\leq \frac{2^p p}{p-1}$.

I think that the meaning of this sentence is basically as follows :
"(We want to find $c$ such that $\mathbb{E}\{(M_n^*)^p\} \leq c\mathbb{E}\{|M_n|^p\}$.) We showed in the proof of above theorem that such $c$ can be found at least in $c\leq \frac{2^p p}{p-1}$."
You are correctly claiming that $\mathbb{E}\{(M_n^*)^p\} \leq c\mathbb{E}\{|M_n|^p\}$ holds for every $c$ satisfying $c\color{red}{\ge} \frac{2^p p}{p-1}$, but I don't think that this is what the sentence is trying to say.

For the second doubt :

With more work one can show that $c^{\frac{1}{p}}=\frac{p}{p-1}$

I think that the meaning of this sentence is basically as follows :
"There is another way to show that $\mathbb{E}\{(M_n^*)^p\} \leq (\frac{p}{p-1})^{p}\mathbb{E}\{|M_n|^p\}$ holds (where $(\frac{p}{p-1})^{p}$ is smaller than $\frac{2^pp}{p-1}$)."
I don't think that the sentence means that $c^{\frac 1p}=\frac{p}{p-1}$ follows from $c=\frac{2^pp}{p-1}$.


text:
Q: Reading a file. How do i put the strings into character arrays? I am reading a file and placing the info into arrays for later use.
I have to open and then read and close.
I got the first 3 things done and it works good. But i am stumped on how to go forward with the next part. Also how would i know when i reach the end of the file. I know how long this one is because i made it. But if i was to run a unknown file i wouldn't know how many are in it.
My main problem right now is i have a string for the last file that i need to read. It will do that but it is returning the last one it pulls from the file. would a 2d array be good to use for the string and how would i do this.
int main(void)
{
    FILE * pFile;
    char buf[40];
    int x[80];
    float y[80];
    int z[80];
    char str[40];

    pFile = fopen("testint.dat", "r");
    if (pFile != NULL)
    {
        int i = 0;
        for ( i = 0; i < 5; i++)
        {
            fgets(buf, 40, pFile);
            x[i] = atoi(buf);

            fgets(buf, 40, pFile);
            y[i] = atof(buf);

            fgets(buf, 40, pFile);
            z[i] = buf[0];

            fgets(str, 40, pFile);
            str[strlen(str) - 1] = '\0';

            printf("\n %s \n", str);

            printf("\n %i \n", x[i]);
            printf("\n %f \n", y[i]);
            printf("\n %c \n", z[i]);
        }

    }

    printf("\n\n %s \n", str);
    printf(" %i \n", x[0]);
    printf(" %f \n", y[1]);
    printf(" %c \n", z[2]);
    system("pause");

}

also here is the file info:
1
1.1
a
aaaa
2
2.2
b
bbbb
3
3.3
c
cccc
4
4.4
d
dddd
5
5.5
e
eeee

Note: so far the code isn't returning errors. It is more the question of how i can proceed. (also anyone that can help me i owe you a beer)

A:
But if i was to run a unknown file i wouldn't know how many are in it.

Replace
int i = 0;
for ( i = 0; i < 5; i++)
{
    fgets(buf, 40, pFile);
    x[i] = atoi(buf);

    fgets(buf, 40, pFile);
    y[i] = atof(buf);

    fgets(buf, 40, pFile);
    z[i] = buf[0];

    fgets(str, 40, pFile);
    str[strlen(str) - 1] = '\0';

    printf("\n %s \n", str);

    printf("\n %i \n", x[i]);
    printf("\n %f \n", y[i]);
    printf("\n %c \n", z[i]);
}

with
int i = 0;
while (fgets(buf, 40, pFile))
{
    x[i] = atoi(buf);

    fgets(buf, 40, pFile);
    y[i] = atof(buf);

    fgets(buf, 40, pFile);
    z[i] = buf[0];

    fgets(str, 40, pFile);
    str[strlen(str) - 1] = '\0';

    printf("\n %s \n", str);

    printf("\n %i \n", x[i]);
    printf("\n %f \n", y[i]);
    printf("\n %c \n", z[i]);
    i++;
}

Avoid the use of magic numbers like 40, use sizeof(buf)

A: Your question about when you reach the end of file, there is a function for it naming 'end of file' in short EOF heres a good example:
Eof example


text: Q: Lipschitzian extension of mapping between Alexandrov spaces Let $X$ be an $n-$dim (compact, if needed) Alexandrov space with curvature $\geq -k$, with $k\geq0$, and let $Y$ be an Alexandrov space with curvature $\leq0$ globally. Given any bounded nonempty $E\subset X$ and $f:E\mapsto Y$ Lipschitzian. Can we extend $f$ to the whole $X$, with $lip(f\big|_X)\leq C(n,k,Y)\cdot lip(f\big|_E)$, for some constant $C(n,k,Y)$? Here $lip(f\big|_E):=\sup_{x,y\in E}\frac{d_Y(f(x),f(y))}{d_X(x,y)}$. Thank you !


text:
Q: How to automatically set hspace to inline 2nd column? I'm new to latex and i wonder how to create a table-like look, because now i have to set the hspace manually to get my expected result.
How can i line up a "second column" on top of each other?
How i actually do it manually:
Elongation: \hspace{24pt} $y(t) = r * \sin(\omega*t+\phi_0)$\\
Geschwindigkeit: \hspace{1pt} $v(t) = r * \omega * \sin(\omega*t+\phi_0) = y'(t)$\\
Beschleunigung: \hspace{5pt} $a(t) = r * \omega^2 * -\sin(\omega*t+\phi_0) = v'(t) = y''(t)$\\\\

Should look like this:
Elongation:       y(t) = r∗sin(ω∗t + φ0)
Geschwindigkeit:  v(t) = r∗ω∗sin(ω∗t + φ0) = y0(t)
Beschleunigung:   a(t) = r∗ω2 ∗−sin(ω∗t + φ0) = v0(t) = y00(t)

A: You can obtain this with a description environment, using convenient parameters:
\documentclass{book}
\usepackage{enumitem}
\setlength\parindent{1em}
\newlength{\descrwidth}

\begin{document}

{\settowidth{\descrwidth}{Geschwindigkeit:\quad}
\begin{description}[font=\normalfont, noitemsep, labelwidth=\dimexpr\descrwidth, leftmargin =\descrwidth, labelsep=0pt]
\item[Elongation:]$y(t) = r * \sin(\omega*t+\phi_0)$ Text text text. Text text text. Text text text. Text text text. \\
\item[Geschwindigkeit:] $v(t) = r * \omega * \sin(\omega*t+\phi_0) = y'(t)$\\
\item[Beschleunigung:] $a(t) = r * \omega^2 * -\sin(\omega*t+\phi_0) = v'(t) = y''(t)$\\\\
\end{description}}

\end{document}

A: Table-like? Why not just the traditional tabular?
\documentclass{article}
\usepackage{parskip,array}
\begin{document}
\renewcommand\arraystretch{1.5}\tabcolsep0pt
\begin{tabular}{p{3cm}l}
Elongation:      & $y(t) = r * \sin(\omega*t+\phi_0)$\\
Geschwindigkeit: & $v(t) = r * \omega * \sin(\omega*t+\phi_0) = y'(t)$\\
Beschleunigung:  & $a(t) = r * \omega^2 * -\sin(\omega*t+\phi_0) = v'(t) = y''(t)$\\
\end{tabular}
\end{document}

For long formulas, just use a table with two  p{<width>} columns  (or environments like tabular*, tabularx or tabulary).
OK, ok, ... without tabular, just simpler with tabto:
\documentclass{article}
\usepackage{tabto,parskip}
\NumTabs{4}
\begin{document}
Elongation:     \tab $y(t) = r * \sin(\omega*t+\phi_0)$\par
Geschwindigkeit:\tab $v(t) = r * \omega * \sin(\omega*t+\phi_0) = y'(t)$\par
Beschleunigung: \tab $a(t) = r * \omega^2 * -\sin(\omega*t+\phi_0) = v'(t) = y''(t)$
\end{document}

For long formulas, you can use some like  \tab\parbox[t]{.7\linewidth}{$...$}. If you need custom Tab positions, use some like
\TabPositions{0pt, 0.3\linewidth} instead of  \NumTabs.


text:
Q: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'float java.lang.Float.floatValue()' on a null object reference When I launch my app this problem shows. This is my Java code:
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(layout.activity_main);
    ImageView imageView = new ImageView(this);

    imageView.setBackgroundColor(Color.WHITE);

    SVG svg = SVGParser.getSVGFromResource(getResources(), raw.canel);`

    imageView.setImageDrawable(svg.createPictureDrawable());
   setContentView(imageView);
}

A: This is the line where the exception is thrown:
SVG svg = SVGParser.getSVGFromResource(getResources(), raw.canel);

There are two possibilities: either SVGParser is null and therefore has no getSVGFromResource, or raw is null and has no canel member.
If your error is that SVGParser is null, then the problem is that you did not import SVGParser. In this case the solution is to import the package which contains SVGParser, since it is a class and it was not imported, therefore the compiler thinks it is a variable and has not been initialized.
If your error is that raw is null, then the solution is to initialize it. In this case you have missed the part where the variable is being initialized. It is quite possible that you initialize it correctly, but after onCreate is being called, therefore the member is not initialized yet when you try to use it.
We need more information about the problem to give you a more specific solution.


text:
Q: Lower and upper index in a sorted vector I have a vector with timestamps as following:
1521753105.031429052352905
1521753105.081429004669189
1521753105.131428956985474
1521753105.181428909301758
1521753105.231429100036621
1521753105.281429052352905
1521753105.331429004669189
1521753105.381428956985474
1521753105.431428909301758
1521753105.481429100036621
1521753105.531429052352905
1521753105.581429004669189

The current time is:
1521753105.231428861618042

which is in between the 4th and 5th values.

How to determine the lower and upper index to the current time?

A: Similar to Ander's solution:
find first greater timestamp than your current timestamp. Find last smaller timestamp by subtracting one.
bracket = find(A>v,1) + [-1, 0];

A: One liner trick!
A=%[your numbers]
v=%the value to find its position

braket=find(sort([A,v])==v)+[-1 0]

Assumes that A was sorted originally, of course


text:
Q: Drawing Individual Pixels in OpenGL I'm trying to highlight ("color #00FFFF") specific individual pixels in an image (already displayed in the background) using OpenGL/C++.  The pixel coordinates and the image exist in exact 2D space, but all the OpenGL code I'm seeing in the project so far - glTranslatef(), glScalef() - is 3D and float-based, and the positioning of the object appears to happen separately from the time it's drawn.
I'm used to Java's Graphics2D package, where I can call something to the effect of
width = 1; height = 1;
buffer.drawRect(width, height, xPosition, yPosition);

and it'll fill in a pixel at the specified location.  Is there anything similar to that syntax - where I can set size, set position, and draw all in one line - in OpenGL?  If not, how would I go about adapting my 2D+pixel input to OpenGL's float and 3D structure?
I currently have this:
glPushMatrix();
glTranslatef(0.0f, 0.0f, -5.0f);
glColor3f(0, 1, 1);
glPointSize(5.0f);
glBegin(GL_POINTS);
glVertex3f(1.0f, 1.0f, 1.0f);
glPopMatrix();

which I pieced together from some Google searches and other parts of my code, but I don't see anything being draw.  I have no idea as to the units for the translate, vertex, or pointsize commands.  It'd be awesome if I could replace all of that with something like the Java command up above.  If not, is there some way I can guarantee whatever I draw here will be "on top" of everything else, but still not behind the camera.

A:
Is there anything similar to that syntax - where I can set size, set position, and draw all in one line - in OpenGL?

glRect():
#include <GL/glut.h>

void display()
{
    glEnable( GL_CULL_FACE );
    glEnable( GL_BLEND );
    glBlendFunc( GL_SRC_ALPHA, GL_ONE );

    double w = glutGet( GLUT_WINDOW_WIDTH );
    double h = glutGet( GLUT_WINDOW_HEIGHT );

    glDepthMask( GL_TRUE );
    glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

    // draw teapot
    glEnable( GL_DEPTH_TEST );
    glDepthMask( GL_TRUE );

    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    gluPerspective( 60, w / h, 1, 100 );

    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();
    glTranslatef( 0, 0, -5 );

    glColor4ub( 255, 0, 0, 255 );
    glPushMatrix();
    float angle = 60.0f * ( glutGet(GLUT_ELAPSED_TIME) / 1000.0f );
    glRotatef( angle, 0.1, 0.95, 0.05 );
    glutSolidTeapot( 1.0 );
    glPopMatrix();

    // draw rectangle
    glDisable( GL_DEPTH_TEST );
    glDepthMask( GL_FALSE );

    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    glOrtho( 0, w, 0, h, -1, 1);

    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();

    glColor4ub( 0, 255, 0, 128 );
    glRecti( 0 + 50, 0 + 50, w - 50, h - 50 );

    glutSwapBuffers();
}

void timer( int extra )
{
    glutPostRedisplay();
    glutTimerFunc( 16, timer, 0 );
}

int main( int argc, char **argv )
{
    glutInit( &argc, argv );
    glutInitDisplayMode( GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE );
    glutInitWindowSize( 640, 480 );
    glutCreateWindow( "Rect" );
    glutDisplayFunc( display );
    glutTimerFunc( 0, timer, 0 );
    glutMainLoop();
    return 0;
}


text:
Q: Resume video using Jquery(Html5 video element) I am using video html5 element to get the duration property to find the last time
where the video stops playing either when user closes browser or user pauses, to send it to the database so that later it will resume from where it stops.
Currently what I googled and check on stack overflow is something like this
    <script type="text/javascript">

    $("#video").on("durationchange", function() {
         alert("Current duration is: " + this.duration);
     });

  </script>

 <video id="video" poster="image.jpg" controls>
      <source src="video_path.mp4" type="video/mp4" />
  </video>

I also want to seek to the video to the duration where the user stops after login
to my app. I tried it but is not correct way of doing
       $(window).load(function() {
       .ajax({
            type: "GET",
            url: "/api/videoResume/",
            data: param = "",
            contentType: "application/json; charset=utf-8",
            dataType: "json"
        })
        .done(function(result){
           //update the video element duration
           //seeking video to the duration
        })
   });

A: Another way to do it just add an event listener, so that when a video is paused, you can capture the current time and you then instead of sending an alert like in the example below, you could send that information to your database etc. The code would look like this:
Javascript:
var video1 = document.getElementById('video1');

function videoPausePlayHandler(e) {
    if (e.type == 'pause') {
   alert(video1.currentTime);
    }
}

video1.addEventListener('pause', videoPausePlayHandler, false);

HTML:
<video id="video1" poster="image_path.jpg" controls>
<source src="video_path.mp4" type="video/mp4" />
</video>

Working sample: https://jsfiddle.net/l33tstealth/qr72bvxb/1/


text:
Q: Instant RSpec Test-Driven Development How-to Strong parameters error I have been working my way through this book but the 'Writing ActiveRecord Specifications' required changes with the Rails 4 strong parameters requirement.
I added a location_controller.rb to overcome the strong parameters error
app/controllers/location_controller.rb
class LocationController < ActionController::Base

  params = ActionController::Parameters.new(latitude: lat, longitude: long)

end

app/models/location.rb
require 'active_record'

class Location < ActiveRecord::Base

  #attr_protected :latitude, :longitude

  validates :latitude, :longitude,:presence => true,:numericality => true

  R = 3_959 # Earth's radius in miles, approx
  def near?(lat, long, mile_radius)
    raise ArgumentError unless mile_radius >= 0

    #loc = Location.new(:latitude => lat,:longitude => long)

    loc = location.new(params)

    R * haversine_distance(loc) <= mile_radius
  end

  private
  def to_radians(degrees)
    degrees * Math::PI / 180
  end

  def haversine_distance(loc)
    dist_lat = to_radians(loc.latitude - self.latitude)
    dist_long = to_radians(loc.longitude - self.longitude)
    lat1 = to_radians(self.latitude)
    lat2 = to_radians(loc.latitude)
    a = Math.sin(dist_lat/2) * Math.sin(dist_lat/2) +
        Math.sin(dist_long/2) * Math.sin(dist_long/2) *
            Math.cos(lat1) * Math.cos(lat2)
    2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a))
  end

end

spec/models/location_spec.rb
require "spec_helper"
require "rspec/its"
require "/home/conor/geo_pictures/app/models/location"

describe Location do

  let (:latitude) { 38.911268 }

  let (:longitude) { -77.444243 }

  let (:air_space) { Location.new(:latitude => 38.911268, :longitude => -77.444243) }

  describe "#initialize" do

    subject { air_space }

    its(:latitude) { should == latitude }

    its(:longitude) { should == longitude }

  end

  describe "#near?" do
    context "when within the specified radius" do
      subject { air_space }
      it { should be_near(latitude, longitude, 1) }
    end
    context "when outside the specified radius" do
      subject { air_space }
      it { should_not be_near(latitude * 10, longitude * 10, 1) }
    end

  end

  context "when a negative radius is used" do

    it "raising an error" do

      expect { air_space.near?(latitude, longitude, -1) }.to raise_error ArgumentError

    end

  end

end

Gemfile
source 'https://rubygems.org'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.0.3'

# Use sqlite3 as the database for Active Record
gem 'sqlite3'

# Use SCSS for stylesheets
gem 'sass-rails', '~> 4.0.0'

# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'

# Use CoffeeScript for .js.coffee assets and views
gem 'coffee-rails', '~> 4.0.0'

# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'

# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'

# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 1.2'

group :doc do
  # bundle exec rake doc:rails generates the API under doc/api.
  gem 'sdoc', require: false
end

gem 'rspec-rails', :group => [:test, :development]

gem 'rspec-its', :group => [:test, :development]

# Use ActiveModel has_secure_password
# gem 'bcrypt-ruby', '~> 3.1.2'

# Use unicorn as the app server
# gem 'unicorn'

# Use Capistrano for deployment
# gem 'capistrano', group: :development

# Use debugger
# gem 'debugger', group: [:development, :test]

the error message I receive is
Failures:
1) Location#initialize latitude
     Failure/Error: let (:air_space) { Location.new(:latitude => 38.911268, :longitude => -77.444243) }
     ActiveRecord::ConnectionNotEstablished:
       ActiveRecord::ConnectionNotEstablished
     # ./spec/models/location_spec.rb:11:in block (2 levels) in <top (required)>'
     # ./spec/models/location_spec.rb:15:inblock (3 levels) in '
     # ./spec/models/location_spec.rb:17:in `block (3 levels) in '
2) Location#initialize longitude
     Failure/Error: let (:air_space) { Location.new(:latitude => 38.911268, :longitude => -77.444243) }
     ActiveRecord::ConnectionNotEstablished:
       ActiveRecord::ConnectionNotEstablished
     # ./spec/models/location_spec.rb:11:in block (2 levels) in <top (required)>'
     # ./spec/models/location_spec.rb:15:inblock (3 levels) in '
     # ./spec/models/location_spec.rb:19:in `block (3 levels) in '
3) Location#near? when within the specified radius
     Failure/Error: let (:air_space) { Location.new(:latitude => 38.911268, :longitude => -77.444243) }
     ActiveRecord::ConnectionNotEstablished:
       ActiveRecord::ConnectionNotEstablished
     # ./spec/models/location_spec.rb:11:in block (2 levels) in <top (required)>'
     # ./spec/models/location_spec.rb:25:inblock (4 levels) in '
     # ./spec/models/location_spec.rb:26:in `block (4 levels) in '
4) Location#near? when outside the specified radius
     Failure/Error: let (:air_space) { Location.new(:latitude => 38.911268, :longitude => -77.444243) }
     ActiveRecord::ConnectionNotEstablished:
       ActiveRecord::ConnectionNotEstablished
     # ./spec/models/location_spec.rb:11:in block (2 levels) in <top (required)>'
     # ./spec/models/location_spec.rb:29:inblock (4 levels) in '
     # ./spec/models/location_spec.rb:30:in `block (4 levels) in '
5) Location when a negative radius is used raising an error
     Failure/Error: expect { air_space.near?(latitude, longitude, -1) }.to raise_error ArgumentError
       expected ArgumentError, got # with backtrace:
         # ./spec/models/location_spec.rb:11:in block (2 levels) in <top (required)>'
         # ./spec/models/location_spec.rb:39:inblock (4 levels) in '
         # ./spec/models/location_spec.rb:39:in block (3 levels) in <top (required)>'
     # ./spec/models/location_spec.rb:39:inblock (3 levels) in '
Finished in 0.01039 seconds (files took 0.80876 seconds to load)
5 examples, 5 failures
Failed examples:
rspec ./spec/models/location_spec.rb:17 # Location#initialize latitude
rspec ./spec/models/location_spec.rb:19 # Location#initialize longitude
rspec ./spec/models/location_spec.rb:26 # Location#near? when within the specified radius
rspec ./spec/models/location_spec.rb:30 # Location#near? when outside the specified radius
rspec ./spec/models/location_spec.rb:37 # Location when a negative radius is used raising an error
Adding this to spec/spec_helper.rb
ActiveRecord::Base.establish_connection(:adapter => "sqlite3",
                                       :database => ":memory:")

changes the error to
/home/conor/geo_pictures/spec/spec_helper.rb:1:in `': uninitialized constant ActiveRecord (NameError)

A: The first error you should fix is: ActiveRecord::ConnectionNotEstablished.  You need to configure a test database in config/database.yml.
In your spec (spec/models/location_spec.rb), you only need to have require 'spec_helper'.  The other classes will be autoloaded by Rails.
Finally, strong parameters are not usually specified in that format.
You would specify them like this:
 params.require(:location).permit(:latitude, :longititude)
Refer to the documentation here.


text:
Q: Non-Deterministic behaviour of svm{e1071} I noticed that SVM when fed with decision.values=T  (plus sigmoid to get probabilities ) produces non-deterministic result when I permute data frame under analysis. Does anyone has any idea why? Please try the code yourself
install.packages("e1071")
library(e1071)
A <- cbind(rnorm(20,1,1),rnorm(20,1,1),rep(1,20))
B <- cbind(rnorm(20,9,1),rnorm(20,9,1),rep(0,20))

dataframe <- as.data.frame(rbind(A,B))

predc <- rep(0,length(dataframe[,1]))
K <- length(dataframe[1,])
permutator <- sample(nrow(dataframe))

dataframe$V3 <- factor(dataframe$V3)
dataframe <- dataframe[permutator, ]
for(i in 1:length(dataframe[,1])) {

  frm <- as.formula(object=paste("V",as.character(K), " ~ .",sep=""))
  r <- svm(formula=frm, data=(dataframe[-i,]))
  predicted <- predict(r,newdata=dataframe[i,],decision.values=TRUE)
  predc[i] <- sigmoid(attr(predicted,'decision.values')[1])
}

plot(sort(predc))

[edited: code]


text:
Q: SOAUP UI- Assertion is getting failed My API Response is below. I am trying put an assertion on id field:
[
{
"id": "10008709",
"label": "signal"
},
{
"id": "10014720",
"label": "Application"
},
{
"id": "10014721",
"label": "erver"
},
{
"id": "10014724",
"label": "Mandora"
}
]
My assertion is .id[0] should be equal to 10008709 but assertion is getting failed with below message :ASSERTION FAILED -> Comparison failed for path [.id[0]], expecting [10008709], actual was [[]].
Please could you help. Thanks in advance
Just to add if it helps. when I tried .id  it returns me [[10008709, 10014720, 10014721, 10014724]]

A: You're referencing the wrong thing.  id[0] is the entry you want, but by using the square brackets, you're saying id is an array and you want the first id in the array.  You don't.  You want the id from the first entry....
import groovy.json.JsonSlurper

// I had to use JSON Slurper purely to create a demo JSON object to use as an example.
def slurper = new groovy.json.JsonSlurper();
def jsonString = '[ { "id": "10008709", "label": "signal" }, { "id": "10014720",     "label": "Application" }, { "id": "10014721", "label": "erver" }, { "id": "10014724", "label": "Mandora" } ]';
def result = slurper.parseText(jsonString);

// Let's get the first entry.
log.info(result[0]);

//Let's get the id for the first entry
log.info(result[0].id);

// Let's try an assertion.
assert "10008709" == result[0].id;


text:
Q: Convert list of nested tuples to list of tuples I have a list of strings but some of the strings have one or two tuples in them such as
["('753.00', '97.00', '863.74', '179.00'), ('123.00', '37.00', '813.74', '139.00')", "('829.37', '381.62', '1022.00', '491.63')"]

I need this to be a list of single tuples instead like
[('829.37', '381.62', '1022.00', '491.63'), ('123.00', '37.00', '813.74', '139.00'), ('753.00', '97.00', '863.74', '179.00')]

Problem is that I have not been able to separate the following because it is enclosed in the same quote.
"('753.00', '97.00', '863.74', '179.00'), ('123.00', '37.00', '813.74', '139.00')" into ('753.00', '97.00', '863.74', '179.00'), ('123.00', '37.00', '813.74', '139.00')

I tried list(map(ast.literal_eval, lst)) but that does work as from a previous post that someone marked duplicate.

A: This seems like an issue with the data pipeline upstream. Whatever is generating this should probably be where it should be fixed.
That said, the following should do what you need:
import ast

entries = [
    "('753.00', '97.00', '863.74', '179.00'), ('123.00', '37.00', '813.74', '139.00')",
    "('829.37', '381.62', '1022.00', '491.63')"
]

output_entries = list()
for entry in entries:
    obj = ast.literal_eval(entry)
    if obj and isinstance(obj[0], tuple):
        output_entries.extend(obj)
    else:
        output_entries.append(obj)
print(output_entries)

This prints:
[('753.00', '97.00', '863.74', '179.00'), ('123.00', '37.00', '813.74', '139.00'), ('829.37', '381.62', '1022.00', '491.63')]

Or, do what @Samwise suggests in the comments, but with ast.literal_eval(...):
import ast
output_entries = list(ast.literal_eval(','.join(entries)))

Because using ast.literal_eval(...)is safer: https://stackoverflow.com/a/15197698/604048

ast.literal_eval raises an exception if the input isn't a valid Python datatype, so the code won't be executed if it's not.


text:
Q: Android Camera intent with Uri not saving the images on Camera folder I am using Camera Intent with following code
    public void clickPicturesThroughCamera() {
    try {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        initImageUri();
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, RETURN_FROM_CAMERA);
    } catch (Exception e) {
        showToast(getString(R.string.error_opening_camera));
    }
 }

    public void initImageUri() {
    ContentValues cv = new ContentValues();
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat,
            Locale.ENGLISH);
    String name =simpleDateFormat.format(Calendar.getInstance().getTime())
            + "_" + new Random().nextInt(100) + ".jpg";
    cv.put(MediaStore.Images.Media.TITLE, name);
    imageUri = getContentResolver().insert(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, cv);

}

The images captured will be stored on  /storage/sdcard0/DCIM/Camera/imagename.jpg. But when I click images through default Camera app it will be stored on storage/extSdCard/DCIM/Camera/imagename.jpg as I have used external sdcard to store the the captured images by default.
So my main requirment is that the app I am developing should store the captured images on the default location i.e. storage/extSdCard/DCIM/Camera/imagename.jpg instead of /storage/sdcard0/DCIM/Camera/imagename.jpg. For that what should I do in the above code, so that it will always save the images on default Camera folder.
Thanks

A: The path can vary among devices. By using MediaStore.Images.Media.EXTERNAL_CONTENT_URI you are asking the device for the correct path.
http://developer.android.com/reference/android/provider/MediaStore.Images.Media.html


text:
Q: Webcam Streaming from C++ to Android Apps I am trying to create a system that could live stream my laptop's webcam to Android apps. Currently, I having a C++ system that processes some object detection algorithm, and what I am trying to achieve is that when a particular object was detected, on the Android apps side user will receive a notification and able to live stream the camera(currently working on webcam) to have a view of the object.
So, the main concern is that I would like to have some guidances/suggestions on how to stream by webcam's view from a C++ system to Android apps.
Thank you.


text:
Q: Why more than two android flavor dimensions don't work properly? Here is a problem, for example, I need the next three dimensions for my app: "brand", "environment", "market". The configuration will look like this:
flavorDimensions "brand", "environment", "market"

productFlavors {
    // brand
    nike{
        dimension "brand"
        applicationId "com.android.nike"
    }
    adidas{
        dimension "brand"
        applicationId "com.android.adidas"
    }

    // environment
    test{
        dimension "environment"
        applicationIdSuffix ".test"
    }
    prod {
        dimension "environment"
    }

    // market
    google {
        dimension "market"
    }
    amazon {
        dimension "market"
    }
}

As a result, I can build the next 8 applications (I ignoring build types in this example):
nikeTestGoogle
nikeTestAmazon
nikeProdGoogle
nikeProdAmazon
adidasTestGoogle
adidasTestAmazon
adidasProdGoogle
adidasProdAmazon

As I understand documentation about flavor dimensions (https://developer.android.com/studio/build/build-variants#flavor-dimensions), application nikeTestGoogle use files from the next folders: main, nike, test, google, nikeTest, nikeTestGoogle. But it doesn't work, Android studio sees only files in main, nike, test, google, and nikeTestGoogle. Files in nikeTest ignored and even doesn't mark as currently active.
Does anyone know why it happened?


text:
Q: Additional props on abstract field are ignored I expect to see an error from TS when I add props to a type, when those props are not part of their interface.
This works OK if you deal with the interface directly but seems to only work for required fields when type is coming from an abstract class.
Why is this? And how can I get the validation to work as expected?
interface IProps {
  foo: string;
  bar: number;
}

abstract class AbstractClass {
  protected abstract props: IProps;
}

class ConcreteClass extends AbstractClass {
  constructor() {
    super();
  }

  protected props = {
    foo: "hello",
    bar: 2,
    baz: true // <--- Why am I not getting 'baz' does not exist in type 'IProps'?
  };
}

Playground Link

A: Because the inferred type of props in ConcreteClass is a subinterface of IProps that includes baz. You can assign subinterface instances (and subclass instances) to variables declared with supertypes, just not the other way around (because the other way around, they're missing properties).
To prevent that, you need to use the type name again:
class ConcreteClass extends AbstractClass {
  constructor() {
    super();
  }
  protected props: IProps = {
  // *** Here -----^
      foo: "hello",
      bar: 2,
      baz: true // Error: Type '{ foo: string; bar: number; baz: boolean; }' is not assignable to type 'IProps'.
  };
}

Playground Link
It's different from doing this:
let props: IProps;
// ...
props = {
    foo: "hello",
    bar: 2,
    baz: true // Error: Type '{ foo: string; bar: number; baz: boolean; }' is not assignable to type 'IProps'.
};

...because ConcreteClass is declaring props, not assigning to something that already exists.
Alternately, you could define props as non-abstract. It's a bit of a pain because you have to initialize it with appropriate defaults. You could declare it as IProps|undefined to avoid that:
abstract class AbstractClass {
  protected props: IProps|undefined = undefined;
}

class ConcreteClass extends AbstractClass {
  constructor() {
    super();
    this.props = {
        foo: "hello",
        bar: 2,
        baz: true // Error: Type '{ foo: string; bar: number; baz: boolean; }' is not assignable to type 'IProps'.
    };
  }
}

Playground Link
...or of course just initialize it with appropriate defaults and then overwrite them if/as necessary:
abstract class AbstractClass {
  protected props: IProps = {
      foo: "",
      bar: 42
  }
}

class ConcreteClass extends AbstractClass {
  constructor() {
    super();
    this.props.foo = "hello";
    this.props.bar = 2;
  }
}

Playground Link


text:
Q: Cross Field Validation with inline messaging in JSF with JSR 303 What's the best way to invoke class level JSR-303 constraints that do cross field validation from JSF and have the resulting messages get translated to a FacesMessage and be tied to a particular JSF component based on the PropertyPath in the ConstraintViolation?
rich:graphValidator is close, but it doesn't make use of the PropertyPath.  Perhaps MyFaces extval could get me close, but there seems to be a whole extra layer of framework on time of bean-validation, so I avoided it.
Here's a simple example:
public enum Type {
    ROAD, RACE;
}

public class Driver {
    private String name;
    private Type licenseType;
    ...
}

@CarConstraint
public class Car {
    @Valid
    private Driver driver;
    private Type carType;
    private String make;
    private String model;
    ...
}

public class CarConstraintValidator implements ConstraintValidator<CarConstraint, Car> {
    @Override
    public void initialize(CarConstraint constraintAnnotation) {}

    @Override
    public boolean isValid(Car value, ConstraintValidatorContext context) {
        if (value == null) { return true; }

        if (Type.RACE.equals(value.getCarType())
            && !Type.RACE.equals(value.getDriver().getLicenseType())) {

            context.buildConstraintViolationWithTemplate("Driver of this car must have a racing license")
                .addNode("driver")
                .addNode("licenseType")
                .addConstraintViolation();

            return false;
        }

        return true;
    }
}

Picture a form where the information about the car and the driver are input. If the Driver had a license type of ROAD and the Car had a car type of RACE, it'd be ideal to see a resulting validation message be translated into a FacesMessage which is connected to the input for license type, since the message was added to that node using the fluent API of Bean Validation.

A: Our team had the same problem.  You may have a look OmniFaces. I used code from the validators as a blueprint to build a prototype that used reflection to call the class level validators.


text:
Q: Loading data from Firebase with React I have a firebase location with a list of patients
I am trying to reference this location and save it in the state of my react component to later pass to a drop down. I am pretty new to REACT, so i am not sure if this is this best way to this.
import * as firebase from "firebase";

class App extends Component {
  constructor() {
    super();
    this.state = {
      patient: []
    };
  }

  componentDidMount() {
    let patientList = "";
    var rootRef = firebase
      .database()
      .ref()
      .child("patient");
    rootRef.on("child_added", snap => {
      this.setState({
        patient: snap.val().label
      });
    });
  }

  render() {
    return (
      <React.Fragment>
        <li>{this.state.patient}</li>
      </React.Fragment>
    );
  }
}

However this code is returning only the last label in the firebase location. Please help.

A: Try this one
rootRef.on("child_added", snap => {

    // Store all the labels in array
    var patients = [];
    snapshot.forEach(function(snap){
        var row = snap.val();
        patients.push(row.label);
    });

    // Store label array into state
    this.setState({
        patient: patients
    });
});

A: I think this will help your case to implement the real time patient list.
rootRef.on("child_added", snap => {

    var patients = this.state.patient || [];
    snapshot.forEach(snap => {
        var row = snap.val();
        patients.push(row.label);
    });

    this.setState({
        patient: patients
    });

I hope it helps. Thanks!!


text:
Q: Restricting IdentityServer3 ClientCredentials access by IP address I'm implementing an identity server using IdentityServer3, and want to restrict a particular ClientCredentials client to a set of IP addresses.
I've tried a few things:

*

*I see an AllowedCorsOrigins property on the Client object, and if I enable this I see IdentityServer logging warnings, but it doesn't prevent access.

*Injected OwinEnvironmentService into my UserService's constructor - UserService doesn't seem to be used by the ClientCredentials flow.

Is this possible, or am I misunderstanding how to use ClientCredentials?

A: This is not easily possible with the client credentials flow. But you could implement a customized m grant type instead.
https://identityserver.github.io/Documentation/docsv2/advanced/customGrantTypes.html


text:
Q: How can I Get FB Event Venue Struct values using FQL How can I Get FB Event Venue Struct values using FQL in the same Event Query :
Based on Event FB Documentation .. venue is a struct property but i can't access its members like street,city,state,country,zip,latitude,longitude,id
FB Event Documentation
By Using the query below i can't access venue values ..
SELECT name,description, start_time,end_time, venue.street,venue.city,venue.country,venue.zip, venue.latitude,venue.longitude, venue.id, venue.name, venue.located_in
FROM event WHERE eid =296244733844027

FQL Query Example
so any suggestions about how to get Venue Values in FB Event Query using FQL

A: It's returned in the json ... as follows for example ...
{
  "data":
   [
     {
      "name": "Outdoor Movie Night & BBQ @ the Chambers!",
      "description": "Party!!!",
      "start_time": "2013-06-22T19:00:00-0700",
      "end_time": null,
      "venue": {
        "name": "000 0th Ave W, Seattle"
      }
    }
  ]
}


text:
Q: REPL for ocamldebug? One of the things that I miss from GHC (Haskell) when using OCaml is that there is no unified debugger/REPL. The debugger and the REPL are completely separate, which is crazy! You can't think of a random function call and execute it in the running process, like you can in ghci.
Any tips, workarounds for this?

A: There is a REPL for Ocaml which is not debuggable, it is the ocaml command.
You might also use ocamldebug on ocaml, but I'm not sure it would help you.
The ocamldebug debugger is mostly used (on your application compiled with ocamlc) as you would use gdb for C.


text:
Q: Getting "double precision not supported on this device" error when trying to run a program using OpenCL in ubuntu 18.04 I am trying to run a C++ program on my laptop with ubuntu 18.04, it compiles but I get an error when I try to run it in the terminal.
The program uses OpenCL because I am trying to learn how to use it. I installed OpenCl using the following:
sudo apt install ocl-icd-libopencl1
sudo apt install opencl-headers
sudo apt install clinfo
sudo apt install ocl-icd-opencl-dev
sudo apt install beignet

When I try to run a sample code I got this error:
ASSERTION FAILED: Double precision not supported on this device (if this is a literal, use '1.0f' not '1.0')
  at file /build/beignet-Bevceu/beignet-1.3.2/backend/src/backend/gen_insn_selection.cpp, function void gbe::ConvertInstructionPattern::convertBetweenFloatDouble(gbe::Selection::Opaque&, const gbe::ir::ConvertInstruction&, bool&) const, line 6227
Trace/breakpoint trap (core dumped)

This is a sample code my professor wrote last semester when we were learning how to use OpenCL on the school computers we were given. The code worked there now I am trying to get it to work on my computer but I get this error.
My laptop doesn't have a GPU but has integrated graphics with an Intel® Core™ i5-3210M Processor.
Any help with what this error means or how I can fix it would be great.


text:
Q: How to combine multiple object properties in select ng-options angular I want to display both the text and number in my select options. JSON has different properties for text and number and I need to combine them and display in select options value by default.
Expected Output:
000.000.0001 - Chicago
HTML:
<!doctype html>

  <meta charset="utf-8">
  <title>AngularJS Plunker</title>
  <link rel="stylesheet" href="style.css">

  <select ng-model="model.selected" ng-options="item.ID as item.Title for item in items"></select>

Selected: {{model.selected}}

JS:
var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.items = [
       {ID: '000.000.0001', Title: 'Chicago'},
       {ID: '000.000.0002', Title: 'New York'},
       {ID: '000.000.0003', Title: 'Washington'}
    ];
});

A: you can assign multiple values using this approach
  <select ng-model="model.selected" ng-options="item.ID  as item.ID + '-' + item.Title for item in items"></select>

Selected: {{model.selected}}

angular.module("app",[])
.controller("ctrl",function($scope){

  $scope.model = {
    selected : '000.000.0001'
  }
 $scope.items = [
       {ID: '000.000.0001', Title: 'Chicago'},
       {ID: '000.000.0002', Title: 'New York'},
       {ID: '000.000.0003', Title: 'Washington'}
    ];
})

<select ng-model="model.selected" ng-options="item.ID  as item.ID + '-' + item.Title for item in items"></select>

Selected: {{model.selected}}


text:
Q: Is there anyway to use variable in search function of Regex? I wonder if there is any way to use a special variable in regex and mix it with regex code??
this is a function that takes type and folder and searches all files and folders in it to find all files with that type. and the error occurred in line 10 when I tried to combine them.
def explore(extension,path):
    import os
    import re
    d = dict()
    for dirpath, dirs, files in os.walk(path):
        count = 0
        for filename in files:
            fname = os.path.join(dirpath,filename)
            fname = fname.lower()
            j = ".\"+extension+"$"
            if re.search(j,fname) != None:
                if fname.endswith(extension):
                    count+=1
                    d[dirpath]=count
    print(d)

A: Error here is missing one ". When you do ", then it means that quote sign is just a character. It doesn't end your string. To get rid of this error, you can do it in two ways:
First - use r before string. It treats characters in string as regular characters:
        j = r".\"+extension+"$"

Second - use double slash. Double slash will result in one, regular character slash.
j = ".\\"+extension+"$"

As an addition. It's better to use for example fstrings rather than concatenating strings. Try syntax below :)
print(f"Hello. My name is {your_variable}!")