I am trying to reverse a stack using an empty stack and a variable v. But I am not getting the answer which I should Get. Can anyone please help me with this ?
void Reverse()
{
S.push(1);
S.push(2);
S.push(3);
int v;
for(int i=1;i<S.size();i++)
{
v=S.top();
S.pop();
for(int j=0;j<S.size()-i;j++ )
{
T.push(S.top());
S.pop();
}
S.push(v);
while(!T.empty())
{
S.push(T.top());
T.pop();
}
}
}
Stack is last-in-first-out (LIFO) non-generic collection of objects (see http://msdn.microsoft.com/en-us/library/system.collections.stack.aspx ). Thus, the simplest way to reverse the stack content is to create another stack, then pop entries from the original and push it to a new one, like in the following example (pertinent to .NET/C# implementation):
Stack _stackOriginal = new Stack();
_stackOriginal.Push(1);
_stackOriginal.Push(2);
_stackOriginal.Push(3);
Stack _stackReverse = new Stack();
while (_stackOriginal.Count>0)
{
_stackReverse.Push(_stackOriginal.Pop());
}
There is another solution found on this site (Does Stack<> constructor reverse the stack when being initialized from other one?), like the following:
Stack<int> _stackReverse = new Stack<int>(new Stack<int>(_stackOriginal));
Rgds,
Related
this question is basically the same question I asked a few weeks ago... how to tap into mappingcontext.processAnonType... I marked the question as answered by mistake and since then have not been able to get any follow up.
Basically what I am trying to figure out is a location within the breeze pipeline that i can set a non entity object's prototype when the object is materialized from server results... when breeze processes results from the servers that are not entities, it ends up calling the method below of the helper MappingContext class... this method is as follows:
function processAnonType(mc, node) {
// node is guaranteed to be an object by this point, i.e. not a scalar
var keyFn = mc.metadataStore.namingConvention.serverPropertyNameToClient;
var result = {};
__objectForEach(node, function (key, value) {
var newKey = keyFn(key);
var nodeContext = { nodeType: "anonProp", propertyName: newKey };
visitNode(value, mc, nodeContext, result, newKey);
});
return result;
}
up above the value of "results" is what the client ends up receiving from breeze... this is a perfect place that I could do what it is i want to do just because i have access to the final object ("results") AND the node.$type property... i basically want to parse the node.$type property in order to figure out the prototype of the non entity object... unfortunately it does not appear processAnonType is an interception point within the pipeline... in the previous question i asked, i was directed to look at a custom jsonresultsadapter... i did that but i don't think it will work simply because the jsonresultsadapter does not ever appear to be in the position of changing the value of "results" (the final object returned)... so even if i implement a custom jsonresulsadapter and return new nodes, the value of "results" up above continues to be the same... can anyone please clue me in? thank you
EDIT #1: I already tried using a custom jsonresultsadapter… but this does NOT work for what I am SPECIFICALLY trying to do, UNLESS I am using a very old version of breeze (unlikely) or am missing something really obvious (more likely)... down below I have provided two snippets of breeze code that will hopefully help me explain my conclusion... the first snippet is the “visitandmerge” method of the mappingcontext… towards the bottom of that method you’ll see a call made to “jra.visitnode”… that’s great… it calls my custom jra implementation which returns a “node” property in the result such that the following line will use that node rather than the original one… so far so good… then at the end you’ll see that a call is made to “processmeta” that passes in my custom node… ok fine… but then if you look the “processmeta” code in my case the last “else” block ends up being invoked and a call is made to “processanontype”… this is where the problem is… at this point my custom node is discarded for purposes of creating/instantiating the final object returned to the client… I understand my custom node will be used to create properties for the final object but that's not what I am after... instead I need to manipulate the final object myself by setting its prototype… as I mentioned previously, if you look at the “processanontype” method it creates a new object (var result = {};) and that object is returned to the client, NOT my custom node, which is inline with what the documentation says… please see all the comments I left in the previous post... do you understand what my problem is? I am probably missing something here really obvious… can you please clue me in? thanks again
proto.visitAndMerge = function (nodes, nodeContext) {
var query = this.query;
var jra = this.jsonResultsAdapter;
nodeContext = nodeContext || {};
var that = this;
return __map(nodes, function (node) {
if (query == null && node.entityAspect) {
// don't bother merging a result from a save that was not returned from the server.
if (node.entityAspect.entityState.isDeleted()) {
that.entityManager.detachEntity(node);
} else {
node.entityAspect.acceptChanges();
}
return node;
}
var meta = jra.visitNode(node, that, nodeContext) || {};
node = meta.node || node;
if (query && nodeContext.nodeType === "root" && !meta.entityType) {
meta.entityType = query._getToEntityType && query._getToEntityType(that.metadataStore);
}
return processMeta(that, node, meta);
});
};
function processMeta(mc, node, meta, assignFn) {
// == is deliberate here instead of ===
if (meta.ignore || node == null) {
return null;
} else if (meta.nodeRefId) {
var refValue = resolveEntityRef(mc, meta.nodeRefId);
if (typeof refValue === "function" && assignFn != null) {
mc.deferredFns.push(function () {
assignFn(refValue);
});
return undefined; // deferred and will be set later;
}
return refValue;
} else if (meta.entityType) {
var entityType = meta.entityType;
if (mc.mergeOptions.noTracking) {
node = processNoMerge(mc, entityType, node);
if (entityType.noTrackingFn) {
node = entityType.noTrackingFn(node, entityType);
}
if (meta.nodeId) {
mc.refMap[meta.nodeId] = node;
}
return node;
} else {
if (entityType.isComplexType) {
// because we still need to do serverName to client name processing
return processNoMerge(mc, entityType, node);
} else {
return mergeEntity(mc, node, meta);
}
}
} else {
if (typeof node === 'object' && !__isDate(node)) {
node = processAnonType(mc, node);
}
// updating the refMap for entities is handled by updateEntityRef for entities.
if (meta.nodeId) {
mc.refMap[meta.nodeId] = node;
}
return node;
}
}
You should NOT need to modify the processAnonType method.
The parameters to the visitNode method in the jsonResultsAdapter have all of the information regarding the node being visited that you say you need. (See the link at the bottom of this post). The result from the visitNode is an object with the following properties:
entityType: you should return null for an anonymous type
nodeId and nodeRefId: ( probably not needed for an anonymous objects unless you plan to return multiple refs to the same object)
ignore: boolean - (if you want to completely ignore the node).
node: This is where you can take the incoming node ( the first parameter in the visitNode parameter list) and modify it, or return a completely new node object that represents your anonType instance. This object will be returned to the client unchanged, so you can create an new instance of your object with whatever prototype you want. If you don't set this property then the original incoming node will be used.
passThru: (avail in breeze versions > v 1.5.4) boolean - you should return true to return the node (above) intact without ANY further processing.
So your visitNode will look something like this:
visitNode: function(node, mappingContext, nodeContext) {
// 'isAnonType' is your method that determines if this is an anon type
var isAnon = isAnonType(node.$type);
if (isAnonType) {
// 'createCustomAnonNode' is your method where you create a copy of the node with whatever prototype you want.
// prototype you want.
var newNode = createCustomAnonNode(node);
return {
return { passThru: true, node: newNode };
}
} else {
// assuming that you kept track of the default JsonResultsAdapter;
return defaultAdapter.visitNode(node, mappingContext, nodeContext);
}
}
For more detail, see:
http://www.getbreezenow.com/documentation/jsonresultsadapters
I've read several related posts and even posted and answer here but it seems like I was not able to solve the problem.
I have 3 Activities:
Act1 (main)
Act2
Act3
When going back and forth Act1->Act2 and Act2->Act1 I get no issues
When going Act2->Act3 I get no issues
When going Act3->Act2 I get occasional crashes with the following error: java.lang.IllegalStateException: trying to requery an already closed cursor android.database.sqlite.SQLiteCursor#.... This is a ListView cursor.
What I tried:
1. Adding stopManagingCursor(currentCursor);to the onPause() of Act2 so I stop managing the cursor when leaving Act2 to Act3
protected void onPause()
{
Log.i(getClass().getName() + ".onPause", "Hi!");
super.onPause();
saveState();
//Make sure you get rid of the cursor when leaving to another Activity
//Prevents: ...Unable to resume activity... trying to requery an already closed cursor
Cursor currentCursor = ((SimpleCursorAdapter)getListAdapter()).getCursor();
stopManagingCursor(currentCursor);
}
When returning back from Act3 to Act2 I do the following:
private void populateCompetitorsListView()
{
ListAdapter currentListAdapter = getListAdapter();
Cursor currentCursor = null;
Cursor tournamentStocksCursor = null;
if(currentListAdapter != null)
{
currentCursor = ((SimpleCursorAdapter)currentListAdapter).getCursor();
if(currentCursor != null)
{
//might be redundant, not sure
stopManagingCursor(currentCursor);
// Get all of the stocks from the database and create the item list
tournamentStocksCursor = mDbHelper.retrieveTrounamentStocks(mTournamentRowId);
((SimpleCursorAdapter)currentListAdapter).changeCursor(tournamentStocksCursor);
}
else
{
tournamentStocksCursor = mDbHelper.retrieveTrounamentStocks(mTournamentRowId);
}
}
else
{
tournamentStocksCursor = mDbHelper.retrieveTrounamentStocks(mTournamentRowId);
}
startManagingCursor(tournamentStocksCursor);
//Create an array to specify the fields we want to display in the list (only name)
String[] from = new String[] {StournamentConstants.TblStocks.COLUMN_NAME, StournamentConstants.TblTournamentsStocks.COLUMN_SCORE};
// and an array of the fields we want to bind those fields to (in this case just name)
int[] to = new int[]{R.id.competitor_name, R.id.competitor_score};
// Now create an array adapter and set it to display using our row
SimpleCursorAdapter tournamentStocks = new SimpleCursorAdapter(this, R.layout.competitor_row, tournamentStocksCursor, from, to);
//tournamentStocks.convertToString(tournamentStocksCursor);
setListAdapter(tournamentStocks);
}
So I make sure I invalidate the cursor and use a different one. I found out that when I go Act3->Act2 the system will sometimes use the same cursor for the List View and sometimes it will have a different one.
This is hard to debug and I was never able to catch a crashing system while debugging. I suspect this has to do with the time it takes to debug (long) and the time it takes to run the app (much shorter, no pause due to breakpoints).
In Act2 I use the following Intent and expect no result:
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
Intent intent = new Intent(this, ActivityCompetitorDetails.class);
intent.putExtra(StournamentConstants.App.competitorId, id);
intent.putExtra(StournamentConstants.App.tournamentId, mTournamentRowId);
startActivity(intent);
}
Moving Act1->Act2 Act2->Act1 never gives me trouble. There I use startActivityForResult(intent, ACTIVITY_EDIT); and I am not sure - could this be the source of my trouble?
I would be grateful if anyone could shed some light on this subject. I am interested in learning some more about this subject.
Thanks,D.
I call this a 2 dimensional problem: two things were responsible for this crash:
1. I used startManagingCursor(mItemCursor); where I shouldn't have.
2. I forgot to initCursorAdapter() (for autocomplete) on onResume()
//#SuppressWarnings("deprecation")
private void initCursorAdapter()
{
mItemCursor = mDbHelper.getCompetitorsCursor("");
startManagingCursor(mItemCursor); //<= this is bad!
mCursorAdapter = new CompetitorAdapter(getApplicationContext(), mItemCursor);
initItemFilter();
}
Now it seems to work fine. I hope so...
Put this it may work for you:
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
orderCursor.requery();
}
This also works
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
startManagingCursor(Cursor);
}
Does anyone happen to know how
umbraco.cms.businesslogic.template.Template Import(System.Xml.XmlNode n, umbraco.BusinessLogic.User u)
in the Umbraco API works? More specifically what the XMLNode you're supposed to pass in looks like (is supposed to be)? I've been searching for a reference on this method for a while now, can't seem to find anything. The API reference on the Umbraco wiki isn't helping much either.
To answer my own question, here is the source code for the function:
public static Template Import(XmlNode n, User u)
{
string alias = xmlHelper.GetNodeValue(n.SelectSingleNode("Alias"));
Template t = Template.GetByAlias(alias);
if (t == null)
{
t = MakeNew(xmlHelper.GetNodeValue(n.SelectSingleNode("Name")), u);
}
t.Alias = alias;
t.ImportDesign(xmlHelper.GetNodeValue(n.SelectSingleNode("Design")));
return t;
}
One question I have yet to find an answer on is this. How do I keep track of active Sitemap nodes on multiple levels?
For example :
node 1
node 2 "active"
Child node 1
Child node 2 "active"
node 3
How do I keep track of a childnode being active as well as the parent it belongs to being marked as active.
I know there is something called IsDescendant but I always get exceptions when using it due to null values.
Is there some screencast/tutorial on doing more advanced custom navigation in mvc.net(or asp.net for that matter). Most seem to deal with simple one level navigation.
I would prefer examples in C# if possible, thank you.
Ok ,,, I've suffered from the same issue and I came up with a work around, check my answer in this question :
Hierarchical menu in view based on parent child class
I've been meaning to come up with a more generic elegant way of doing it since I've faced the problem but I've been busy ever since. I'm hoping I'll find some time in the next weeks to come up with something ,,,
Note : for simplicity in my solution in the above question in the methods DisplayMenu and ConvertToItem particularity, I've removed the parts where it should check for the currentMenuID and the currentMenuItemID fields and add the current css class to the li element (or active class in your case).
Since this is all what's your question is about, I've provided the full methods below.
public static string DisplayMenu(this HtmlHelper helper, NavigationModel navigationMenu)
{
string classOfCurrentMenu;
String result = "<ul id='main-nav'>\n";
foreach(Menu menu in navigationMenu.Menus)
{
classOfCurrentMenu = "";
if (menu.ID == navigationMenu.currentMenuID)
{
classOfCurrentMenu = "current";
}
result += "<li>\n";
result += string.Format("<a href='#' class='{0}'> {1} </a>\n", helper.AttributeEncode(classOfCurrentMenu),helper.AttributeEncode(menu.Name));
result += "<ul>\n";
foreach(MenuItem item in menu.MenuItems)
{
result += NavigationHelper.ConvertToItem(helper, item, navigationMenu.currentMenuID, navigationMenu.currentMenuItemID);
}
result += "</ul>\n";
result += "</li>\n";
}
result += "</ul>\n";
return result;
}
private static string ConvertToItem(this HtmlHelper helper,MenuItem item, int currentMenuID, int currentMenuItemID)
{
if (item.Show)
{
string classOfCurrentItem = "";
if (item.ID == currentMenuItemID && item.MenuID == currentMenuID)
classOfCurrentItem = "current";
return string.Format("<li><a href='{0}' class='{1}'>{2}</a></li>\n", helper.AttributeEncode(item.Link), helper.AttributeEncode(classOfCurrentItem), helper.AttributeEncode(item.Label));
}
else { return ""; }
}
I don't consider this as a perfect solution to the problem, I hate writing HTML in C# code, I will try my best to come up with a more generic (multi level) cleaner solution for the problem, and of course make use of the TagBuilder class in the framework.
I'm having a little trouble with a method in which I use yield return this doesn't work...
public IEnumerable<MyClass> SomeMethod(int aParam)
{
foreach(DataRow row in GetClassesFromDB(aParam).Rows)
{
yield return new MyClass((int)row["Id"], (string)row["SomeString"]);
}
}
The above code never runs, when the call is made to this method it just steps over it.
However if I change to...
public IEnumerable<MyClass> SomeMethod(int aParam)
{
IList<MyClass> classes = new List<MyClass>();
foreach(DataRow row in GetClassesFromDB(aParam).Rows)
{
classes.Add(new MyClass((int)rows["Id"], (string)row["SomeString"]);
}
return classes;
}
It works just fine.
I don't understand why the first method never runs, could you help me in understanding what is happening here?
The "yield" version is only "run" when the caller actually starts to enumerate the returned collection.
If, for instance, you only get the collection:
var results = SomeObject.SomeMethod (5);
and don't do anything with it, the SomeMethod will not execute.
Only when you start enumerating the results collection, it will hit.
foreach (MyClass c in results)
{
/* Now it strikes */
}
yield return methods are actually converted into state machine classes that retrieve information lazily - only when you actually ask for it. That means that in order to actually pull data, you have to iterate over the result of your method.
// Gives you an iterator object that hasn't done anything yet
IEnumerable<MyClass> list = SomeMethod();
// Enumerate over the object
foreach (var item in list ) {
// Only here will the data be retrieved.
// The method will stop on yield return every time the foreach loops.
}
The reason it runs in the second case is because there's no yield block, and thus the entire method runs in one go.
In this specific case, it's unlikely that you'll have any advantage to use an iterator block over a regular one because your GetClassesFromDb() isn't one either. This means that it will retrieve all the data at the same time first time it runs. Iterator blocks are best used when you can access items one at a time, because that way you can stop if you don't need them anymore.
I had to learn in a near disastrous way how cool/dangerous yield is when I decided to make our company's parser read incoming data lazily. Fortunately only one of the handful of our implementing functions actually used the yield keyword. Took a few days to realize it was quietly not doing any work at all.
The yield keyword it will be as lazy as it possibly can, including skipping over the method altogether if you don't put it to work with something like .ToList() or .FirstOrDefault() or .Any()
Below are two variations, one using the keyword and one returning a straight-up list. One won't even bother to execute, while the other will, even though they seem the same.
public class WhatDoesYieldDo
{
public List<string> YieldTestResults;
public List<string> ListTestResults;
[TestMethod]
public void TestMethod1()
{
ListTest();
Assert.IsTrue(ListTestResults.Any());
YieldTest();
Assert.IsTrue(YieldTestResults.Any());
}
public IEnumerable<string> YieldTest()
{
YieldTestResults = new List<string>();
for (var i = 0; i < 10; i++)
{
YieldTestResults.Add(i.ToString(CultureInfo.InvariantCulture));
yield return i.ToString(CultureInfo.InvariantCulture);
}
}
public IEnumerable<string> ListTest()
{
ListTestResults = new List<string>();
for (var i = 0; i < 10; i++)
{
ListTestResults.Add(i.ToString(CultureInfo.InvariantCulture));
}
return ListTestResults;
}
}
Moral of the story: Make sure that if have a method that returns IEnumerable and you use yield in that method, you have something that will iterate over the results, or the method won't execute at all.