Use Kinect to create a digital catalog application - wpf

I am creating a WPF application to create digital catalog using kinect v1.8. I am trying to track only a single skeleton using following code:-
private void SensorSkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs skeletonFrameReadyEventArgs)
{
// Even though we un-register all our event handlers when the sensor
// changes, there may still be an event for the old sensor in the queue
// due to the way the KinectSensor delivers events. So check again here.
if (this.KinectSensor != sender)
{
return;
}
SkeletonFrame skeletonFrame = skeletonFrameReadyEventArgs.OpenSkeletonFrame();
if (skeletonFrame == null)
return;
Skeleton[] skeletons = new Skeleton[skeletonFrame.SkeletonArrayLength];
skeletonFrame.CopySkeletonDataTo(skeletons);
Skeleton skeleton = (from skl in skeletons
where skl.TrackingState == SkeletonTrackingState.Tracked
select skl).FirstOrDefault();
if (skeleton == null)
return;
Skeleton[] s = new Skeleton[1];
s[0] = skeleton;
if (SkeletonTrackingState.Tracked == s[0].TrackingState)
{
//s1.SkeletonStream.ChooseSkeletons(s[0].TrackingId);
var accelerometerReading = this.KinectSensor.AccelerometerGetCurrentReading();
this.interactionStream.ProcessSkeleton(s, accelerometerReading, skeletonFrame.Timestamp);
}
}
I am getting an exception when I run the code and skeleton gets detected as follows:-
on the line "this.interactionStream.ProcessSkeleton(s, accelerometerReading, skeletonFrame.Timestamp);"
I need to detect only one skeleton and use it for further processing like to access the digital catalog applications.
Thanks in advance.

I have Faced Same Problem By using below code I have track only one skeleton Which is closer to the sensor.and directly assign the closest skeleton to the main skeleton stream.
private void SensorSkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs skeletonFrameReadyEventArgs)
{
Skeleton[] skeletons = new Skeleton[0];
using (SkeletonFrame skeletonFrame = skeletonFrameReadyEventArgs.OpenSkeletonFrame())
{
if (skeletonFrame != null && this.skeletons != null)
{
//Console.WriteLine(skeletonFrame.SkeletonArrayLength);
skeletons = new Skeleton[skeletonFrame.SkeletonArrayLength];
// Set skeleton datas from skeletonFrame
skeletonFrame.CopySkeletonDataTo(this.skeletons);
TrackClosestSkeleton();
Skeleton[] singleSkeleton = new Skeleton[6];
Skeleton skl=(from mno in this.skeletons where mno.TrackingState==SkeletonTrackingState.Tracked && mno.TrackingId==globalClosestID select mno).FirstOrDefault();
if (skl == null)
return;
//Creating an empty skkeleton
Skeleton emptySkeleton = new Skeleton();
singleSkeleton[0] = skl; //Pass the Tracked skeleton with closestID
singleSkeleton[1] = emptySkeleton; //Passing Empty Skeleton
singleSkeleton[2] = emptySkeleton; //Passing Empty Skeleton
singleSkeleton[3] = emptySkeleton; //Passing Empty Skeleton
singleSkeleton[4] = emptySkeleton; //Passing Empty Skeleton
singleSkeleton[5] = emptySkeleton; //Passing Empty Skeleton
this.snew.SkeletonStream.ChooseSkeletons(globalClosestID);
var accelerometerReading = this.KinectSensor.AccelerometerGetCurrentReading();
this.interactionStream.ProcessSkeleton(singleSkeleton, accelerometerReading, skeletonFrame.Timestamp);
}
}
}
int globalClosestID = 0;
private void TrackClosestSkeleton()
{
if (this.snew != null && this.snew.SkeletonStream != null)
{
if (!this.snew.SkeletonStream.AppChoosesSkeletons)
{
this.snew.SkeletonStream.AppChoosesSkeletons = true; // Ensure AppChoosesSkeletons is set
}
float closestDistance = 10000f; // Start with a far enough distance
int closestID = 0;
foreach (Skeleton skeleton in this.skeletons.Where(s => s.TrackingState != SkeletonTrackingState.NotTracked))
{
if (skeleton.Position.Z < closestDistance)
{
closestID = skeleton.TrackingId;
closestDistance = skeleton.Position.Z;
}
}
if (closestID > 0)
{
this.snew.SkeletonStream.ChooseSkeletons(closestID); // Track this skeleton
globalClosestID = closestID;
}
}
}
check the above code it works for me.It may helpful to you.Here snew is the Kinectsensor.

You should try to track the closest skeleton using this method from MSDN
private void TrackClosestSkeleton()
{
if (this.kinect != null && this.kinect.SkeletonStream != null)
{
if (!this.kinect.SkeletonStream.AppChoosesSkeletons)
{
this.kinect.SkeletonStream.AppChoosesSkeletons = true; // Ensure AppChoosesSkeletons is set
}
float closestDistance = 10000f; // Start with a far enough distance
int closestID = 0;
foreach (Skeleton skeleton in this.skeletonData.Where(s => s.TrackingState != SkeletonTrackingState.NotTracked))
{
if (skeleton.Position.Z < closestDistance)
{
closestID = skeleton.TrackingId;
closestDistance = skeleton.Position.Z;
}
}
if (closestID > 0)
{
this.kinect.SkeletonStream.ChooseSkeletons(closestID); // Track this skeleton
}
}
}
And then in your SkeletonFrameReady
private void SkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs e)
{
Skeleton[] skeletons = new Skeleton[0];
using (SkeletonFrame skeletonFrame = e.OpenSkeletonFrame())
{
if (skeletonFrame != null && this.skeletonData != null)
{
skeletons = new Skeleton[skeletonFrame.SkeletonArrayLength];
// Set skeleton datas from skeletonFrame
skeletonFrame.CopySkeletonDataTo(this.skeletonData);
TrackClosestSkeleton();
}
}
//Do some stuff here
}

Related

For Unity, How to loop to check if different objects are null, or in my case not in the gameobject i attach the script to

I have multiple Images in one script and an array of sprites in another. I assign each image a specific sprite if a specific controller is connected. Then attach the script to a game object and assign the needed images. I only have some images on each gameobject, If I don't have every image on the script I attach on the game object, it gives me errors about object not in scene.
So im still learning unity and C#, and this is what I have now, and it works. Just wondering if there's a cleaner way to do this null check with a loop, which kind of loop and how?
Thanks in advance!
public GameManager gameManager;
public UIMananger uIMananger;
public Image[] moveImg;
public Image RunImg;
public Image jumpImg;
public Image mainAttackImg;
public Image secondAttackImg;
public Image PauseImg;
public Image SelectImg;
public Image recenterCameraImg;
public Image showUiImg;
public Image chaosTestImg;
public Image firstPersonCameraImg;
public Image EnterImg;
public Image BackImg;
void Update()
{
if (gameManager.UsingXboxController)
{
XboxMap();
}
}
public void XboxMap()
{
if (moveImg[0] != null)
{
moveImg[0].sprite = uIMananger.controllerButtons[10];
}
if (moveImg[1] != null)
{
moveImg[1].sprite = uIMananger.controllerButtons[11];
}
if (moveImg[2] != null)
{
moveImg[2].sprite = uIMananger.controllerButtons[12];
}
if (moveImg[3] != null)
{
moveImg[3].sprite = uIMananger.controllerButtons[13];
}
if (RunImg != null)
{
RunImg.sprite = uIMananger.controllerButtons[3];
}
if (jumpImg != null)
{
jumpImg.sprite = uIMananger.controllerButtons[0]; ;
}
if (mainAttackImg != null)
{
mainAttackImg.sprite = uIMananger.controllerButtons[2];
}
if (secondAttackImg != null)
{
secondAttackImg.sprite = uIMananger.controllerButtons[1];
}
if (PauseImg != null)
{
PauseImg.sprite = uIMananger.controllerButtons[22];
}
if (SelectImg != null)
{
SelectImg.sprite = uIMananger.controllerButtons[23];
}
if (recenterCameraImg != null)
{
recenterCameraImg.sprite = uIMananger.controllerButtons[6];
}
if (showUiImg != null)
{
showUiImg.sprite = uIMananger.controllerButtons[5];
}
if (chaosTestImg != null)
{
chaosTestImg.sprite = uIMananger.controllerButtons[18];
}
if (firstPersonCameraImg != null)
{
firstPersonCameraImg.sprite = uIMananger.controllerButtons[8];
}
if (EnterImg != null)
{
EnterImg.sprite = uIMananger.controllerButtons[0];
}
if (BackImg != null)
{
BackImg.sprite = uIMananger.controllerButtons[1];
}
}

Using ANTLR 4 to parse TSQL Joins in Views, Stored Procedures and Functions

Looking for some validation on the approach to using ANTLR 4 to parse SQL joins.
I have generated a lexer, parser and visitor from the following grammar.
https://github.com/antlr/grammars-v4/tree/master/tsql
I can then create a parse tree (in this example for a view) and I can kick off a walk of tree using a listener I have implemented.
ICharStream stream = CharStreams.fromstring(view);
ITokenSource lexer = new TSqlLexer(stream);
ITokenStream tokens = new CommonTokenStream(lexer);
TSqlParser parser = new TSqlParser(tokens);
parser.BuildParseTree = true;
IParseTree tree = parser.create_view();
TSqlListener listener = new TSqlListener();
ParseTreeWalker.Default.Walk(listener, tree);
My question is. Is my method of extracting the tokens for the joins the 'correct' and most efficient way of doing this.
My implementation is below and i based on listening for a walk of the tree at the join conditions. I need to capture table aliases and relate them to columns so I need to be in the same context when I'm walking the tree. Hence I'm manually descending in a single method.
public void EnterTable_sources([NotNull] TSqlParser.Table_sourcesContext context)
{
var table_sources = context.table_source().ToList();
foreach (var table_source in table_sources)
{
var item = table_source.table_source_item_joined();
if (item != null)
{
//first aliases
var source_item = item.table_source_item();
if (source_item != null)
{
TableAlias tableAlias = new TableAlias();
var table_name = source_item.table_name_with_hint();
if (table_name != null)
{
var fullTableName = table_name.GetText();
if (fullTableName.Contains('.'))
{
var nameParts = fullTableName.Split('.').ToList();
for (int i = 0; i <nameParts.Count; i++)
{
tableAlias.AddParts(nameParts);
}
}
else
{
tableAlias.AddParts(fullTableName);
}
}
var table_alias = source_item.as_table_alias();
if (table_alias != null)
{
tableAlias.Alias = table_alias.GetText();
}
JoinAnalysis.Aliases.Add(tableAlias);
}
var join_parts = item.join_part();
foreach (var join_part in join_parts)
{
var table_source_joins = join_part.table_source();
if (table_source_joins != null)
{
//The join table and alias
var table_source_item_joined = table_source_joins.table_source_item_joined();
if (table_source_item_joined != null)
{
var joinAlias = new TableAlias();
var table_source_item = table_source_item_joined.table_source_item();
var table_name = table_source_item.table_name_with_hint();
if (table_name != null)
{
var fullTableName = table_name.GetText();
if (fullTableName.Contains('.'))
{
var nameParts = fullTableName.Split('.').ToList();
joinAlias.AddParts(nameParts);
}
else
{
joinAlias.AddParts(fullTableName);
}
}
if (table_source_item != null)
{
var table_alias = table_source_item.as_table_alias();
if (table_alias != null)
{
joinAlias.Alias = table_alias.GetText();
}
}
if (joinAlias.Alias != null)
{
JoinAnalysis.Aliases.Add(joinAlias);
}
}
}
var search_condition = join_part.search_condition();
if (search_condition != null)
{
//The join conditions
var conditions = search_condition.search_condition_and();
if (conditions != null)
{
foreach (var condition in conditions)
{
if (condition != null)
{
foreach (var search_condition_not in condition.search_condition_not())
{
JoinCondition joinCondition = new JoinCondition();
joinCondition.LineNumber = search_condition_not.Start.Line;
var conditionText = search_condition_not.GetText();
joinCondition.JoinConditionText = conditionText;
var splitCondition = conditionText.Split("=");
if (splitCondition.Length == 2)
{
joinCondition.LeftPart = splitCondition[0];
joinCondition.RightPart = splitCondition[1];
}
JoinAnalysis.JoinConditions.Add(joinCondition);
}
}
}
}
}
}
}
}
}
Is there a better way to do this using all of the other listener methods that have been generated without manually descending into child nodes? I there some magic that I'm missing that holds context between nodes as they are walked?
Instead of manually drilling down to sub elements in a rule you can simply listen to the the enter/exit calls for these subrules. As an example: you listen to table_sources and descent to table_source_item_joined from there to table_name_with_hint. Instead you could simply override the EnterTable_name_with_hint method.
It is totally ok to write a listener, which only handles very specific parts of the language. Look at this (C++) code in MySQL Workbench, where I created several listeners, each just handling a subpart of a larger construct or individual objects. There are listeners for create table, alter table, column definitions, triggers and more.

RSSService item with the same key multiple times

I have a RSSService with an item like the one show below
<item>
<title>Accessori per la cura della persona</title>
<link>http://www.myurl.it/accessori-per-la-cura-della-persona/</link>
<comments>http://www.myurl.it/accessori-per-la-cura-della-persona/#comments</comments>
<pubDate>Tue, 24 Oct 2017 09:29:44 +0000</pubDate>
<dc:creator><![CDATA[Farmacia Rizzo Davide]]></dc:creator>
<category><![CDATA[News]]></category>
<category><![CDATA[Offerte]]></category>
<category><![CDATA[Callifugo]]></category>
<category><![CDATA[Raspa piedi]]></category>
<category><![CDATA[Spazzola ceramica]]></category>
<category><![CDATA[Spazzola piatta]]></category>
<category><![CDATA[Spazzola tonda]]></category>
<category><![CDATA[Spazzole capelli]]></category>
<guid isPermaLink="false">http://www.myurl.it/?p=3982</guid>
<description>.....
To read all the content I use this:
List<Map> records;
...
records = rss.getResults();
...
for (Map m : records) {
Button b = new Button((String)m.get("title"));
if(((String)m.get("category")).equals(CATEGORY_OFFERTE)){
b.setIcon(iconStar);
} else {
b.setIcon(iconNews);
}
b.addActionListener((l)->{
Boolean can = Display.getInstance().canExecute((String)m.get("link"));
if(can != null && can) {
Display.getInstance().execute((String)m.get("link"));
} else {
ToastBar.Status status = ToastBar.getInstance().createStatus();
status.setMessage("Non riesco a connettermi");
status.setExpires(3000);
status.show();
}
});
recordsContainer.addComponent(b);
}
When I read the key "category" I always get the last entry (in this item "Spazzole capelli").
There is a way to read a key like an array? Something like that:
String[] mc = (String[]) m.get("category");
Thank's in advance for any help.
Davide.
This looks like a missing feature in RSSService that expects to find only one category entry and so it parses it into a hash map which effectively allows only one such entry.
I would suggest implementing your own RSS reading and go to the XML directly to get the full power of the protocol. You can use the existing class as a reference on how to do the RSS/ATOM parsing.
This is my idea
protected void textElement(String text) {
if(lastTag != null && current != null) {
// make "ATOM" seem like RSS
if("summary".equals(lastTag)) {
current.put("details", text);
} else {
if("content".equals(lastTag)) {
current.put("description", text);
} else {
if(current.get(lastTag) != null){
try {
List list = (List) current.get(lastTag);
list.add(text);
current.put(lastTag, list);
} catch (ClassCastException e){ // java.lang.String cannot be cast to java.util.List
List list = new ArrayList();
list.add((String)current.get(lastTag));
list.add(text);
current.put(lastTag, list);
}
} else {
current.put(lastTag, text);
}
}
}
}
}
Used in my Form like this:
for (Map m : records) {
Button b = new Button((String)m.get("title"));
try{
String category = (String)m.get("category");
if(category.equals(CATEGORY_OFFERTE)){
b.setIcon(iconStar);
} else {
b.setIcon(iconNews);
}
} catch (ClassCastException e){ // java.lang.String cannot be cast to java.util.List
b.setIcon(iconNews);
List list = (List) m.get("category");
for(int i=0; i < list.size(); i++){
if(((String)list.get(i)).equals(CATEGORY_OFFERTE)){
b.setIcon(iconStar);
}
}
}
b.addActionListener((l)->{
Boolean can = Display.getInstance().canExecute((String)m.get("link"));
if(can != null && can) {
Display.getInstance().execute((String)m.get("link"));
} else {
ToastBar.Status status = ToastBar.getInstance().createStatus();
status.setMessage("Non riesco a connettermi");
status.setExpires(3000);
status.show();
}
});
recordsContainer.addComponent(b);
}

textrange losing textpointer reference?

I've been using some code I found here, to try and change the case of text in a flow document. It changes the text properly however all the formatting is lost (bold, italics, etc) and when I save the document to a XML file all the text ends up in the first Run of the document and all the other Run's are empty.
private void ChangeCase()
{
TextPointer start = mergedDocument.ContentStart;
TextPointer end = mergedDocument.ContentEnd;
List<TextRange> textToChange = SplitToTextRanges(start, end);
ChangeCaseToAllRanges(textToChange);
}
private List<TextRange> SplitToTextRanges(TextPointer start, TextPointer end)
{
List<TextRange> textToChange = new List<TextRange>();
var previousPointer = start;
for (var pointer = start; (pointer != null && pointer.CompareTo(end) <= 0); pointer = pointer.GetPositionAtOffset(1, LogicalDirection.Forward))
{
var contextAfter = pointer.GetPointerContext(LogicalDirection.Forward);
var contextBefore = pointer.GetPointerContext(LogicalDirection.Backward);
if (contextBefore != TextPointerContext.Text && contextAfter == TextPointerContext.Text)
{
previousPointer = pointer;
}
if (contextBefore == TextPointerContext.Text && contextAfter != TextPointerContext.Text && previousPointer != pointer)
{
textToChange.Add(new TextRange(previousPointer, pointer));
previousPointer = null;
}
}
textToChange.Add(new TextRange(previousPointer ?? end, end));
return textToChange;
}
private void ChangeCaseToAllRanges(List<TextRange> textToChange)
{
Func<string, string> caseChanger;
ComboBoxItem cbi = cb_Case.SelectedItem as ComboBoxItem;
var textInfo = CultureInfo.CurrentUICulture.TextInfo;
if (cbi == null || (string)cbi.Tag == "none")
{
return;
}
else if((string)cbi.Tag == "title")
{
caseChanger = (text) => textInfo.ToTitleCase(text);
}
else if ((string)cbi.Tag == "upper")
{
caseChanger = (text) => textInfo.ToUpper(text);
}
else if ((string)cbi.Tag == "lower")
{
caseChanger = (text) => textInfo.ToLower(text);
}
else
return;
foreach (var range in textToChange)
{
if (!range.IsEmpty && !string.IsNullOrWhiteSpace(range.Text))
{
System.Diagnostics.Debug.WriteLine("Casing: " + range.Text);
System.Diagnostics.Debug.WriteLine("\tat: " +
range.Start.GetOffsetToPosition(mergedDocument.ContentStart) +
" ," +
range.End.GetOffsetToPosition(mergedDocument.ContentStart));
range.Text = caseChanger(range.Text);
}
}
}
I can't see any reason why this code isn't working properly. It looks like the textpointers in the textrange object are being redirected to the beginning of the document.
When setting TextRange.Text, it first deletes the selection by telling the TextContainer (the FlowDocument) to delete that content. If that content happened to be an entire Inline with your styling dependency properties then goodbye! So, not only does it get unstyled text, but it sets it
Since you want to keep your existing inline objects you can iterate through the entire FlowDocument to find them and set their text property.
Here is a helper method that only supports Paragraphs and finds all inlines in the entire selection (this logic is a lot simpler if you are always doing Document.ContentStart and Document.ContentEnd). You can expand this to include the inlines inside of Lists, ListItems, and Hyperlinks if you need to (by following a similar pattern).
You should then be able to set the Text property on each of these inlines.
List<Inline> GetInlines(TextRange selection)
{
var inlines = new List<Inline>();
foreach (var block in Document.Blocks.Where(x => selection.Start.CompareTo(x.ContentEnd) < 0 && selection.End.CompareTo(x.ContentStart) > 0))
{
var paragraph = block as Paragraph;
if (paragraph != null)
{
inlines.AddRange(paragraph.Inlines.Where(x => selection.Start.CompareTo(x.ContentEnd) < 0 && selection.End.CompareTo(x.ContentStart) > 0));
}
}
return inlines;
Edit: You will want to cast these to Run or Span to access the text property. You can even just remove Inline and get these types (probably just Run).

Context Menu on a Group Row in RadGridView

I found one old solution Here.
But GridViewExpander is obsolete in 2009. Proof Here.
How can i implement it (Context Menu on a Group Row in RadGridView) in another way?
No answers... =(
But i found solution.
The are two ways to solve it:
1) If you need custom style for your GridViewGroupRow - read about Templates Structure
2) If not, then just use somthing like this:
<TelerikNavigation:RadContextMenu.ContextMenu>
<TelerikNavigation:RadContextMenu Opened="RadContextMenuOpened" ItemClick="ContextMenuItemClick" x:Name="contextMenu">
</TelerikNavigation:RadContextMenu>
private void RadContextMenuOpened(object sender, RoutedEventArgs e)
{
var menu = (RadContextMenu)sender;
if (menu == null)
return;
var cell = menu.GetClickedElement<GridViewCell>();
var row = menu.GetClickedElement<GridViewRow>();
var groupRow = menu.GetClickedElement<GridViewGroupRow>();
if (cell != null && row != null)
{
if (!cell.DataColumn.IsFrozen)
{
//Code for current cell
}
}
if (groupRow != null)
{
//Code for groupRow
}
}
private void ContextMenuItemClick(object sender, RadRoutedEventArgs e)
{
if (_currentCell != null)
{
//Code for current cell
}
if (_currentGroupRow != null)
{
var menu = (RadContextMenu)sender;
var clickedItem = e.OriginalSource as RadMenuItem;
if (clickedItem != null)
{
foreach (var gridViewRow in _currentGroupRow.ChildrenOfType<GridViewRow>())
{
foreach (var gridViewCellBase in gridViewRow.Cells)
{
if (gridViewCellBase.Column.UniqueName == "PlanObject")
{
var val = gridViewCellBase.DataContext as YourObjectName;
if (val != null)
{
//.....
}
}
}
}
//....
}
}
}

Resources