I am using an SplHeap to hold graph nodes of a tree with directed edges that will be traversed from the leaves to the root. For this, I precalculate the "fan-in" of nodes and put them into the heap so that I can always retrieve the node with the smallest fan-in (0) from it.
After visiting a node, I reduce the fan-in of its successor by 1. Then obviously, the heap needs to be recalculated because the successor is now in the wrong place there. I have tried recoverFromCorruption(), but it doesn't do anything and keeps the heap in the wrong order (node with larger fanIn stays in front of smaller fanIn).
As a workaround, I'm now creating a new heap after each visit, amounting to a full O(N*log(N)) sort each time.
It should be possible, however, to make up-heap operations on the changed heap entry until it's in the right position in O(log(N)).
The API for SplHeap doesn't mention an up-heap (or deletion of an arbitrary element - it could then be re-added). Can I somehow derive a class from SplHeap to do this or do I have to create a pure PHP heap from scratch?
EDIT: Code example:
class VoteGraph {
private $nodes = array();
private function calculateFanIn() { /* ... */ }
// ...
private function calculateWeights() {
$this->calculateFanIn();
$fnodes = new GraphNodeHeap(); // heap by fan-in ascending (leaves are first)
foreach($this->nodes as $n) {
// omitted: filter loops
$fnodes->insert($n);
}
// traversal from leaves to root
while($fnodes->valid()) {
$node = $fnodes->extract(); // fetch a leaf from the heap
$successor = $this->nodes[$node->successor];
// omitted: actual job of traversal
$successor->fanIn--; // will need to fix heap (sift up successor) because of this
//$fnodes->recoverFromCorruption(); // doesn't work for what I want
// workaround: rebuild $fnodes from scratch
$fixedHeap = new GraphNodeHeap();
foreach($fnodes as $e)
$fixedHeap->insert($e);
$fnodes = $fixedHeap;
}
}
}
class GraphNodeHeap extends SplHeap {
public function compare($a, $b) {
if($a->fanIn === $b->fanIn)
return 0;
else
return $a->fanIn < $b->fanIn ? 1 : -1;
}
}
Hi All,
Could I get ideas on retrieving the dataset using lookup method. Basically, my scenario as I have source data needs to lookup for other source table and on matching column from source I need to get all the records from other source data.
its a one to many relations. I tried Lookup but gives only one record on matching condition, OLE DB command don't retrieve any data as it will do only Insert/Update operations.
Thanks
prav
Please note that there is no limitation of memory.
I need to insert int from 1 to 1000.
I can do the following operations in constant order of time:
push(), pop() and getMax()
Please suggest me appropriate datastructure.
Is it possible to restrict updating a column in SQL without using a trigger ? If so how ? (need the query)
PS:
I mean, I have a table
CREATE TABLE MYBUDGET.tbl_Income
(
[IncomeID] INT NOT NULL IDENTITY(1,1),
[IncomeCatID] INT NOT NULL,
[IncomeAmnt] MONEY NOT NULL,
[IncomeCurrencyID] INT NOT NULL,
[ExchangeRateID] INT NOT NULL,
[IncomeAmnt_LKR] MONEY NOT NULL,
[AddedOn] DATETIME NOT NULL,
[Remark] VARCHAR(250),
)
I need to allow users to update only [ExchangeRateID] and [IncomeAmnt_LKR] fields. All other fields can not be updated. only insert.
is there a proper way of setting up a 0/1-to-1 relationship? i want to be able to check if the related item exists without creating it:
if item.relationship is None:
item.relationship = item2()
but it creates the insert statements on the if statement
I have a function with this code:
foreach (PropertyInfo propertyInfo in typeof(T).GetProperties()){
//SOME CODE
if (propertyInfo.CanWrite)
propertyInfo.SetValue(myCopy, propertyInfo.GetValue(obj, null), null);
}
I would avoid to check "collection" properties; to do this now I have insert this control:
if (propertyInfo.PropertyType.Name.Contains("List")
|| propertyInfo.PropertyType.Name.Contains("Enumerable")
|| propertyInfo.PropertyType.Name.Contains("Collection"))
continue;
but, It don't like me!
Which is a better way to do it?
I am working on application that has multiple modules and sub modules. Here's what I need to do:
ModuleA has a sub module SubModuleA, SubModuleB, SubModuleC.
I want to export ModuleA, SubModuleA, SubModuleB, SubModuleC.
ModuleA can have multiple instances.
Whenever I import ModuleA inside the sub modules, I want to get the correct instance and also when I import SubModuleA,SubModuleB and SubModuleC inside other classes.
How can I manage that scenario using MEF? Do I really need to use MEF.
Updated:
Here's a quick example:
public class School
{
List<Classroom> classRooms { get; set; }
}
[Export]
public class Classroom
{
List<Teacher> teachers { get; set; }
}
public class Teacher
{
List<Student> students { get; set; }
}
public class Student
{
[Import]
Classroom classroom { get; set; }
}
As you can see, I want to export the classroom class because I need to import it in the Student class, let's just say that I really need the classroom class inside the student class. I want to skip the part where we pass the classroom to the teacher and from the teacher we'll pass it to the student. But when I import classroom, I want to have the correct instance where that class room contains the teacher of the student.
I'm implementing a interpreter-like project for which I need a strange little scheduling queue. Since I'd like to try and avoid wheel-reinvention I was hoping someone could give me references to a similar structure or existing work. I know I can simply instantiate multiple queues as I go along, I'm just looking for some perspective by other people who might have better ideas than me ;)
I envision that it might work something like this: The structure is a tree with a single root. You get a kind of "insert_iterator" to the root and then push elements onto it (e.g. a and b in the example below). However, at any point you can also split the iterator into multiple iterators, effectively creating branches. The branches cannot merge into a single queue again, but you can start popping elements from the front of the queue (again, using a kind of "visitor_iterator") until empty branches can be discarded (at your discretion).
x -> y -> z
a -> b -> { g -> h -> i -> j }
f -> b
Any ideas? Seems like a relatively simple structure to implement myself using a pool of circular buffers but I'm following the "think first, code later" strategy :)
Thanks
I am creating a core-data based Navigation iPhone app with multiple screens. Let's say it is a flash-card application. The data model is very simple, with only two entities: Language, and CardSet. There is a one-to-many relationship between the Language entity and the CardSet entities, so each Language may contain multiple CardSets. In other words, Language has a one-to-many relationship Language.cardSets which points to the list of CardSets, and CardSet has a relationship CardSet.language which points to the Language.
There are two screens: (1) An initial TableView screen, which displays the list of languages; and (2) a secondary TableView screen, which displays the list of CardSets in the Language.
In the initial screen, which lists the languages, I am using NSFetchedResultsController to keep the list of languages up-to-date. The screen passes the Language selected to the secondary screen.
On the secondary screen, I am trying to figure out whether I should again use an NSFetchedResultsController to maintain the list of CardSets, or if I should work through Language.cardSets to simply pull the list out of the object model. The latter makes the most sense programatically because I already have the Language - but then it would not automatically be updated on changes.
I have looked at the NSFetchedResultsController documentation, and it seems like I can easily create predicates based on attributes - but not relationships. I.e., I can create the following NSFetchedResultsController:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name LIKE[c] 'Chuck Norris'"];
How can I access my data through the direct relationship - Language.cardSets - and also have the table auto-update using NSFetchedResultsController? Is this possible?
I want to insert n elements into a map where n is known ahead of time. I do not want memory allocation at each insertion. I want all memory allocation at the beginning. Is there a way to do this? If so, how? Will writing some sort of memory allocator help?
I'm using cakephp 2.2.2 and I have a problem with the editing view
Models and relationships are:
Person hasMany OrganizationPerson
Organization hasMany OrganizationPerson
OrganizationPerson belongs to Person,Organization
A basic hasMany through relationship as found within cake documentation.
Tables are:
people (id,...)
organizations (id,...)
organization_people (id, person_id,organization_id,...)
In the person add and edit forms there is a select box allowing a user to select multiple organization. The problem I have is, when a user edits an existing person, the associated organizations aren't pre-selected.
Here is the code in the PeopleController:
$organizations = $this->Person->OrganizationPerson->Organization->find('list');
$this->set(compact('organizations'));
Related part of the code in the People/edit code looks like:
$this->Form->input('OrganizationPerson.organization_id', array('multiple' => true, 'empty' => false));
This will populate the select field, but it does not pre-select it with the Person's associated organizations.
Format and content of the $this-data:
Array (
[Person] => Array (
[id] => 1 ... )
[OrganizationPerson] => Array (
[0] => Array (
[id] => 1
[person_id] => 1
[organization_id] => 1 ... )
[1] => Array (
[id] => 2
[person_id] => 1
[organization_id] => 2 ... ) ) )
What I have to add/change in the code to get pre-selected organizations?
Thanks in advance!
I'm trying to insert/load javascript (e.g. prototype/jquery) into the iFrame generated by TinyMCE (tinymce.moxiecode.com) or YUI's text editor (http://developer.yahoo.com/yui/editor/) so as to better manipulate the objects/images/DIVs inside it.
Any thoughts?
I have this dtd : http://fast-code.sourceforge.net/template.dtd
But when I include in an xml I get the warning :
No grammar constraints (DTD or XML schema) detected for the document.
The xml is :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE templates PUBLIC "//UNKNOWN/" "http://fast-code.sourceforge.net/template.dtd">
<templates>
<template type="type">
<description>Some</description>
<variation></variation>
<variation-field></variation-field>
<allow-multiple-variation></allow-multiple-variation>
<class-pattern></class-pattern>
<getter-setter>setter</getter-setter>
<allowed-file-extensions>java</allowed-file-extensions>
<number-required-classes>1</number-required-classes>
<template-body>
<![CDATA[
Some Data
]]>
</template-body>
</template>
</templates>
Any clue?
I'm creating a digg-like site using Ruby on Rails that ranks the item (based on this algorithm). I'm using the will-paginate gem list the items in pages.
The problem is, will-paginate only allows me to insert ':order =' based on the table data. I would like to make will-paginate to sort by a number which is calculated using a function based on different fields on the table (e.g number of votes, age hours).
How can I do that?
Hello. I have the following php code that inserts data into XML and works correctly. However, I want to add an ID number like below
<CD id="xxxx">
My question is how can i add an ID into CD for this to work ? I use form to parse the id.
** the main code **
<?php
$CD = array(
'TITLE' => $_POST['title'],
'BAND' => $_POST['band'],
'YEAR' => $_POST['year'],
);
$doc = new DOMDocument();
$doc->load( 'insert.xml' );
$doc->formatOutput = true;
$r = $doc->getElementsByTagName("CATEGORIES")->item(0);
$b = $doc->createElement("CD");
$TITLE = $doc->createElement("TITLE");
$TITLE->appendChild(
$doc->createTextNode( $CD["TITLE"] )
);
$b->appendChild( $TITLE );
$BAND = $doc->createElement("BAND");
$BAND->appendChild(
$doc->createTextNode( $CD["BAND"] )
);
$b->appendChild( $BAND );
$YEAR = $doc->createElement("YEAR");
$YEAR->appendChild(
$doc->createTextNode( $CD["YEAR"] )
);
$b->appendChild( $YEAR );
$r->appendChild( $b );
$doc->save("insert.xml");
?>
the XML file
<?xml version="1.0" encoding="utf-8"?>
<MY_CD>
<CATEGORIES>
<CD>
<TITLE>NEVER MIND THE BOLLOCKS</TITLE>
<BAND>SEX PISTOLS</BAND>
<YEAR>1977</YEAR>
</CD>
<CD>
<TITLE>NEVERMIND</TITLE>
<BAND>NIRVANA</BAND>
<YEAR>1991</YEAR>
</CD>
</CATEGORIES>
</MY_CD>
I have add a custom plugin that insert custom tags into my tinyMCE editor of the format:
title
I want the custom tags to be rendered with some styles when viewed in the WYSIWYG view. I have seen one response to a similar question :
http://topsecretproject.finitestatemachine.com/2010/02/how-to-custom-tags-with-tinymce/
but this doesn't work - they tags are not stripped out but they are not styled either??
I have a s:List where I've defined my own itemRenderer, and would like to insert a horizontal line separating items, similar to the way the mx:LinkBar works. I don't want to have a line at the top or bottom of the list, so I can't just include an upper or lower border in the itemRenderer. I was hoping the itemRenderer could be made aware of its index in the list, but I don't see how. Is there a way to do this?
I have the following query (all tables are innoDB)
INSERT INTO busy_machines(machine)
SELECT machine FROM all_machines
WHERE machine NOT IN (SELECT machine FROM busy_machines)
and machine_name!='Main'
LIMIT 1
Which causes a deadlock when I run it in threads, obviously because of the inner select, right?
The error I get is:
(1213, 'Deadlock found when trying to get lock; try restarting transaction')
How can I avoid the deadlock? Is there a way to change to query to make it work, or do I need to do something else?
I am getting exception: "Specific cast is not valid", here is the code
con.Open();
string insertQuery = @"Insert into Tender (Name, Name1, Name2) values ('Val1','Val2','Val3');Select Scope_Identity();";
SqlCommand cmd = new SqlCommand(insertQuery, con);
cmd.ExecuteNonQuery();
tenderId = (int)cmd.ExecuteScalar();
i have this querystring that shall open up my page.
http://www.a1-one.com/[email protected]&stuid=123456
Now when this page loads, on page_load, I want to pick up email and stuid in two different variables. So I can use them to insert into my database (sql server)
how can this be done in vb.net
I have a table with a bunch of data already in it. I know how to create a partitioned table or alter an already existing partitioned table, but can I add partitions to a table after it has been created, has data in it, without losing the data?
The other option is to dump all the data, recreate the table with the partitions and then insert it all back it. Is that the only way?
Thanks.
Running XSD.exe on my xml to generate C# class. All works well except on this property
public DocumentATTRIBUTES[][] Document {
get {
return this.documentField;
}
set {
this.documentField = value;
}
}
I want to try and use CollectionBase, and this was my attempt
public DocumentATTRIBUTESCollection Document {
get {
return this.documentField;
}
set {
this.documentField = value;
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class DocumentATTRIBUTES
{
private string _author;
private string _maxVersions;
private string _summary;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string author
{
get
{ return _author; }
set { _author = value; }
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string max_versions
{
get { return _maxVersions; }
set { _maxVersions = value; }
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string summary
{
get { return _summary; }
set { _summary = value; }
}
}
public class DocumentAttributeCollection : System.Collections.CollectionBase
{
public DocumentAttributeCollection() : base() { }
public DocumentATTRIBUTES this[int index]
{
get
{
return (DocumentATTRIBUTES)this.InnerList[index];
}
}
public void Insert(int index, DocumentATTRIBUTES value)
{
this.InnerList.Insert(index, value);
}
public int Add(DocumentATTRIBUTES value)
{
return (this.InnerList.Add(value));
}
}
However when I try to serialize my object using
XmlSerializer serializer = new XmlSerializer(typeof(DocumentMetaData));
I get the error:
{"Unable to generate a temporary class (result=1).\r\nerror CS0030:
Cannot convert type 'DocumentATTRIBUTES' to 'DocumentAttributeCollection'\r\nerror CS1502: The best overloaded method match for 'DocumentAttributeCollection.Add(DocumentATTRIBUTES)' has some invalid arguments\r\nerror CS1503: Argument '1': cannot convert from 'DocumentAttributeCollection' to 'DocumentATTRIBUTES'\r\n"}
the XSD pertaining to this property is
<xs:complexType>
<xs:sequence>
<xs:element name="ATTRIBUTES" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="author" type="xs:string" minOccurs="0" />
<xs:element name="max_versions" type="xs:string" minOccurs="0" />
<xs:element name="summary" type="xs:string" minOccurs="0" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
hi
i am having a link like below
<a href="#" onclick="window.open('http://www.twitter.com/home?status=Reading+Facebook share, Yahoo Buzz and Tweet this buttons for Blogger blogs+http://www.didiknow.com');">Tweet this</a>
i want to insert a php variable value inside for the status thing
like
<a href="#" onclick="window.open('http://www.twitter.com/home?status=$markme_ddesc">Tweet this</a>
how to do so?? please help me..