Search Results

Search found 10804 results on 433 pages for 'attribute keys'.

Page 146/433 | < Previous Page | 142 143 144 145 146 147 148 149 150 151 152 153  | Next Page >

  • Python class design - Splitting up big classes into multiple ones to group functionality

    - by Ivo Wetzel
    OK I've got 2 really big classes 1k lines each that I currently have split up into multiple ones. They then get recombined using multiple inheritance. Now I'm wondering, if there is any cleaner/better more pythonic way of doing this. Completely factoring them out would result in endless amounts of self.otherself.do_something calls, which I don't think is the way it should be done. To make things clear here's what it currently looks like: from gui_events import GUIEvents # event handlers from gui_helpers import GUIHelpers # helper methods that don't directly modify the GUI # GUI.py class GUI(gtk.Window, GUIEvents, GUIHelpers): # general stuff here stuff here One problem that is result of this is Pylint complaining giving me trillions of "init not called" / "undefined attribute" / "attribute accessed before definition" warnings.

    Read the article

  • Strange thing about .NET 4.0 filesystem enumeratation functionality

    - by codymanix
    I just read a page of "Whats new .NET Framework 4.0". I have trouble understanding the last paragraph: To remove open handles on enumerated directories or files Create a custom method (or function in Visual Basic) to contain your enumeration code. Apply the MethodImplAttribute attribute with the NoInlining option to the new method. For example: [MethodImplAttribute(MethodImplOptions.NoInlining)] Private void Enumerate() Include the following method calls, to run after your enumeration code: * The GC.Collect() method (no parameters). * The GC.WaitForPendingFinalizers() method. Why the attribute NoInlining? What harm would inlining do here? Why call the garbage collector manually, why not making the enumerator implement IDisposable in the first place? I suspect they use FindFirstFile()/FindNextFile() API calls for the imlementation, so FindClose() has to be called in any case if the enumeration is done.

    Read the article

  • insert and mofigy a record in an entity using Core Data

    - by aminfar
    I tried to find the answer of my question on the internet, but I could not. I have a simple entity in Core data that has a Value attribute (that is integer) and a Date attribute. I want to define two methods in my .m file. First method is the ADD method. It takes two arguments: an integer value (entered by user in UI) and a date (current date by default). and then insert a record into the entity based on the arguments. Second method is like an increment method. It uses the Date as a key to find a record and then increment the integer value of that record. I don't know how to write these methods. (assume that we have an Array Controller for the table in the xib file)

    Read the article

  • ASP.NET Session expires in no time?

    - by Galilyou
    Weired problem! ASP.NET Session expires instantly. In my web.config I have this session settings: <sessionState mode="InProc" timeout="10000" /> AFAIK the timeout attribute's value is in minutes and can't be greater than 525,600 minutes (1 year). I don't understand what I am doing wrong here. Why is the session expiring. Is it a server memory issue? I don't think so, the server is pretty descent and it has only one site which isn't doing much after all. Ideas? EDIT: After setting the cookiless attribute to true, and while noticing the session id on the url, I can see that the session id CHANGING. I assume that this means the session is expiring. The IIS Settings are correct AFAIK (the enable session state checkbox is checked, and the value of the time is 20). A Picture is worth 100 words:

    Read the article

  • Establish context with Watin

    - by Ian Quigley
    Feel free to tell me I'm doing this wrong but... I have the Watin attribute [Browser("IE")] and want to extend this attribute so that it will perform an action (login) to establish the context for the test (setup). I've created public class LoggedInBrowserAttribute : BrowserAttribute which takes URL, username, password and performs the login steps. However, if for some reason the username/password won't login to the system I don't want to perform the test. In the GetBrowser method I'm doing an Assert (is logged in) which seems wrong. What is the correct way to establish this context / abort the test? I don't want to return null from GetBrowser and then have if (browser == null) at the top of my test.

    Read the article

  • Decode sparse json array to php array

    - by Isaac Sutherland
    I can create a sparse php array (or map) using the command: $myarray = array(10=>'hi','test20'=>'howdy'); I want to serialize/deserialize this as JSON. I can serialize it using the command: $json = json_encode($myarray); which results in the string {"10":"hi","test20":"howdy"}. However, when I deserialize this and cast it to an array using the command: $mynewarray = (array)json_decode($json); I seem to lose any mappings with keys which were not valid php identifiers. That is, mynewarray has mapping 'test20'=>'howdy', but not 10=>'hi' nor '10'=>'hi'. Is there a way to preserve the numerical keys in a php map when converting to and back from json using the standard json_encode / json_decode functions?

    Read the article

  • ASP.NET MVC Validation - localisation of the error string

    - by gmang
    I followed the techique ASP.NET MVC 2: Model Validation from Scott Gu. (http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx). However I am building a localised web site. How can I localized the error string? I tried the following by replacing the following: [RegularExpression(@"\d{4}",ErrorMessage="Must be a 4 digit year")] public Nullable YearOfWork { get; set; } With the following: [RegularExpression(@"\d{4}",ErrorMessage=Resources.SharedStrings.search_error1)] public Nullable YearOfWork { get; set; } but I get a complilation error: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type Please help!

    Read the article

  • Effective thread Synchronization in C#

    - by n0vic3c0d3r
    I have a scenario where I need to search from many binary files (using keys) and combine the results (strings). Until now, I have been doing it in a for loop one file after the other. foreach (string file in FileSources.Keys) { aggregatedDefinitions.Append(DefinitionLookup(txtSearchWord.Text, file)); } Since this operation is very slow, I was thinking of using threads, so that I could do IO operations in parallel. Is threading the right way to go. If I use threading, how can I ensure that I get the results in the order I want. I haven't used Threading until now. It would be very helpful if you could suggest some materials/books that would help me solve my problem.

    Read the article

  • C# - Silverlight - CustomAttribute with Enum

    - by cmaduro
    I have the following class: [MetadataAttribute] [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] public class ModuleActivationButtonAttribute : ExportAttribute { public Enum TargetRegion { get; set; } public ModuleActivationButtonAttribute(Enum targetRegion) : base(typeof(IModuleActivationButton)) { TargetRegion = targetRegion; } } The class compiles fine, but when I decorate my property with it: [ModuleActivationButton(Regions.Tabs)] public IModuleActivationButton ModuleActivationButton { get { return new ModuleActivationButton() as IModuleActivationButton; } set { ModuleActivationButton = value; } } public enum Regions { Content, Tabs } The compiler spits out: Error 1 An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type C:\...\Manpower4U.Modules.Home\HomeModule.cs 28 33 Manpower4U.Modules.Home

    Read the article

  • jquery dataTables plugin: dynamically modify ajaxSource

    - by Anthony Koval'
    hello! on my page i have dataTable, which was initialized with, for example, sAjaxSource url like "/api/reports". when we're doing sorting, filtering it appends to url additional query-keys. I want do add keys "date_from" and "date_to" to sAjaxSource url (date intervals could be changed after table initialization). is there any entry-point function, before table reload, so i can do there smth like: var oSettings = rtbl.fnSettings(); oSettings.sAjaxSource = "/api/reports/?type=sites&date_from=" + $("#date_from").text() + "&date_to=" + $("#date_to").text(); thanks for your help!

    Read the article

  • Problem's running unittest test suite OO

    - by chrissygormley
    Hello, I have a test suite to perform smoke tests. I have all my script stored in various classes but when I try and run the test suite I can't seem to get it working if it is in a class. The code is below: (a class to call the tests) from alltests import SmokeTests class CallTests(SmokeTests): def integration(self): self.suite() if __name__ == '__main__': run = CallTests() run.integration() And the test suite: class SmokeTests(): def suite(self): #Function stores all the modules to be tested modules_to_test = ('external_sanity', 'internal_sanity') alltests = unittest.TestSuite() for module in map(__import__, modules_to_test): alltests.addTest(unittest.findTestCases(module)) return alltests unittest.main(defaultTest='suite') This output's an error: Attribute Error: 'module' object has no attribute 'suite' So I can see how to call a normal function defined but I'm finding it difficult calling in the suite. In one of the tests the suite is set up like so: class InternalSanityTestSuite(unittest.TestSuite): # Tests to be tested by test suite def makeInternalSanityTestSuite(): suite = unittest.TestSuite() suite.addTest(TestInternalSanity("BasicInternalSanity")) suite.addTest(TestInternalSanity("VerifyInternalSanityTestFail")) return suite def suite(): return unittest.makeSuite(TestInternalSanity) Can anyone help me with getting this running? Thanks for any help in advance.

    Read the article

  • inno setup - registry key vs. .ini files

    - by PPTim
    Hi, Dabbling with creating an installer with inno setup- but wondering: What are the pros and cons of using registry keys (windows program) vs. .ini files that sit within the program folder? If I store all my user settings in .ini files, the entire program can be removed by deleting the folder. With registry keys i'd have to create an uninstaller / remove the key manually. Why is it that most commercial applications use registry values? I know from brief use of Macs that most programs are drag and drop. Are one of the major reasons because of the lack of a registry key in mac OS?

    Read the article

  • design of orm tool

    - by ifree
    Hello , I want to design a orm tool for my daily work, but I'm always worry about the mapping of foreign key. Here's part of my code: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; namespace OrmTool { [AttributeUsage(AttributeTargets.Property)] public class ColumnAttribute:Attribute { public string Name { get; set; } public SqlDbType DataType { get; set; } public bool IsPk { get; set; } } [AttributeUsage(AttributeTargets.Class,AllowMultiple=false,Inherited=false)] public class TableAttribute:Attribute { public string TableName { get; set; } public string Description { get; set; } } [AttributeUsage(AttributeTargets.Property)] public class ReferencesAttribute : ColumnAttribut { public Type Host { get; set; } public string HostPkName{get;set;} } } I want to use Attribute to get the metadata of Entity ,then mapping them,but i think it's really hard to get it done; public class DbUtility { private static readonly string CONNSTR = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString; private static readonly Type TableType = typeof(TableAttribute); private static readonly Type ColumnType = typeof(ColumnAttribute); private static readonly Type ReferenceType = typeof(ReferencesAttribute); private static IList<TEntity> EntityListGenerator<TEntity>(string tableName,PropertyInfo[] props,params SqlParameter[] paras) { return null; } private static IList<TEntity> ResultList() { return null; } private static SqlCommand PrepareCommand(string sql,SqlConnection conn,params SqlParameter[] paras) { SqlCommand cmd = new SqlCommand(); cmd.CommandText = sql; cmd.Connection = conn; if (paras != null) cmd.Parameters.AddRange(paras); conn.Open(); return cmd; } } I don't know how to do the next step, if every Entity has it's own foreign key,how do I get the return result ? If the Entity like this: [Table(Name="ArtBook")] public class ArtBook{ [column(Name="id",IsPk=true,DataType=SqlDbType.Int)] public int Id{get;set;} [References(Name="ISBNId",DataType=SqlDataType.Int,Host=typeof(ISBN),HostPkName="Id")] public ISBN BookISBN{get;set;} public .....more properties. } public class ISBN{ public int Id{get;set;} public bool IsNative{get;set;} } If I read all ArtBooks from database and when I get a ReferencesAttribute how do I set the value of BookISBN?

    Read the article

  • django auth : strange error with authenticate()

    - by Rohit
    I am using authenticate() to authenticating users manually. Using admin interface I can see that there is no 'last_login' attribute for Users Debug traceback is : Environment: Request Method: GET Request URL: https://localhost/login/ Django Version: 1.1.1 Python Version: 2.6.5 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'mobius.polls'] Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware') Traceback: File "/usr/lib/pymodules/python2.6/django/core/handlers/base.py" in get_response 92. response = callback(request, *callback_args, **callback_kwargs) File "/usr/lib/pymodules/python2.6/django/contrib/auth/__init__.py" in login 55. user.last_login = datetime.datetime.now() Exception Type: AttributeError at /login/ Exception Value: 'unicode' object has no attribute 'last_login' I cant figure out, why is there this discrepancy. Any kind of help would be appreciated. Thanks in advance!

    Read the article

  • Implement a RSA algorithm in Java

    - by Robin Monjo
    Hello everyone. I want to implement a RSA algorithm to encrypt an image (byte[]). To generate my two keys I used this piece of code : KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA"); keygen.initialize(512); keyPair = keygen.generateKeyPair(); Once public and private key are generated, I would like to show them to the user so he can distribute the public key and use the private key to decode. How can I get back those key? Using keygen.getPrivateKey() and keygen.getPublicKey() give me all the information of the RSA algorithm, not only the keys I need. Thanks

    Read the article

  • public key email encryption

    - by anatak
    Who has their email fully encrypted ? I would like to encrypt my email but I am not sure how to start. If I use encrypted email and I send an email to someone who does not encrypt his email how can the receiver read the email ? What email client would you recommend to run on a windows systems for encrypted email ? I am using Thunderbird at the moment. As I understand you have to generate 2 keys (one public and one private) but how do you generate this key? I also think that you have to put your key somewhere to download but I don't understand how you can trust the downloaded keys. Any links to a good (not too complicated) guide about the working an implementing of email encryption would be very much appreciated. kind regards wim hendrix anatak

    Read the article

  • Conditional Validation with Paperclip difficult

    - by Michael Schmitz
    Hi, I have an "item", which goes through a multi-page creation process. Images are uploaded at step five, and I keep track of the steps by using the attribute "complete". When validating whether an image is attached with paperclip, I get problems using the code below: validates_attachment_presence :pic1, :if => Proc.new { |u| u.complete == "step5"} It seems that I can't access the "complete" attribute, as the active-record object seems to be the paperclip image. Is there a way for me to check at which point in the process I am and validate conditionally? Thanks, Michael

    Read the article

  • iPhone: Group by month - Core Data

    - by Shaun
    Hi I store dates in a core data entity attribute, I then display the date in the table cells. I want to group all the cells according to months and only display the relevant dates in the correct sections. I'm using sectionNameKeyPath of the NSFetchedResultsController, but I need to only use the month in the date to group. How can I achieve this? Would I need to create a new attribute and store just the month as a string or can I use NSPredicate? Please can anyone let me know if they have done this or give me some examples. Thanks

    Read the article

  • XSLT Document function returns empty result on Maven POM

    - by user328618
    Greetings! I want to extract some properties from different Maven POMs in a XSLT via the document function. The script itself works fine but the document function returns an empty result for the POM as long as I have the xmlns="http://maven.apache.org/POM/4.0.0" in the project tag. If I remove it, everything works fine. Any idea how the make this work while leaving the xmlns attribute where it belongs or why this doesn't work with the attribute in place? Here comes the relevant portion of my XSLT: <xsl:template match="abcs"> <xsl:variable name="artifactCoordinate" select="abc"/> <xsl:choose> <xsl:when test="document(concat($artifactCoordinate,'-pom.xml'))"> <abc> <ID><xsl:value-of select="$artifactCoordinate"/></ID> <xsl:copy-of select="document(concat($artifactCoordinate,'-pom.xml'))/project/properties"/> </abc> </xsl:when> <xsl:otherwise> <xsl:message terminate="yes"> Transformation failed: POM "<xsl:value-of select="concat($artifactCoordinate,'-pom.xml')"/>" doesn't exist. </xsl:message> </xsl:otherwise> </xsl:choose> And, for completeness, a POM extract with the "bad" attribute: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <!-- ... --> <properties> <proalpha.version>[5.2a]</proalpha.version> <proalpha.openedge.version>[10.1B]</proalpha.openedge.version> <proalpha.optimierer.version>[1.1]</proalpha.optimierer.version> <proalpha.sonic.version>[7.6.1]</proalpha.sonic.version> </properties> </project>

    Read the article

  • IDE underlining custom attributes

    - by runrunraygun
    I have a custom attribute... [System.AttributeUsage(System.AttributeTargets.All)] public class Refactor : System.Attribute { private string _message; public Refactor() { _message = string.Empty; } public Refactor(string message) { _message = message; } } Applied to [Refactor("this should be less rubbish")] public virtual void RubbishMethod() { … } Now when someone makes a call to RubbishMethod I'd like the IDE (vs2008) to underline that call in a deep brown colour, similar to if I mark as Obsolete you get a green wave line. Is this possible? I've been racking my brain and hitting the google but I can't find how and where to do this.

    Read the article

  • please explain NHibernate HiLo

    - by Ben
    I'm struggling to get my head round how the HiLo generator works in NHibernate. I've read the explanation here which made things a little clearer. My understanding is that each SessionFactory retrieves the high value from the database. This improves performance because we have access to IDs without hitting the database. The explanation from the above link also states: For instance, supposing you have a "high" sequence with a current value of 35, and the "low" number is in the range 0-1023. Then the client can increment the sequence to 36 (for other clients to be able to generate keys while it's using 35) and know that keys 35/0, 35/1, 35/2, 35/3... 35/1023 are all available. How does this work in a web application as don't I only have one SessionFactory and therefore one hi value. Does this mean that in a disconnected application you can end up with duplicate (low) ids in your entity table? In my tests I used these settings: <id name="Id" unsaved-value="0"> <generator class="hilo"/> </id> I ran a test to save 100 objects. The IDs in my table went from 32768 - 32868. The next hi value was incremented to 2. Then I ran my test again and the Ids were in the range 65536 - 65636. First off, why start at 32768 and not 1, and secondly why the jump from 32868 to 65536? Now I know that my surrogate keys shouldn't have any meaning but we do use them in our application. Why can't I just have them increment nicely like a SQL Server identity field would. Finally can someone give me an explanation of how the max_lo parameter works? Is this the maximum number of low values (entity ids in my head) that can be created against the high value? This is one topic in NHibernate that I have struggled to find documentation for. I read the entire NHibernate in action book and it still doesn't go into how this works in any detail. Thanks Ben

    Read the article

  • Somebody is storing credit card data - how are they doing it?

    - by pygorex1
    Storing credit card information securely and legally is very difficult and should not be attempted. I have no intention of storing credit card data but I'm dying to figure out the following: My credit card info is being stored on a server some where in he tworld. This data is (hopefully) not being stored on a merchant's server, but at some point it needs to be stored to verify and charge the account identified by merchant submitted data. My question is this: if you were tasked with storing credit card data what encryption strategy would you use to secure the data on-disk? From what I can tell submitted credit card info is being checked more or less in real time. I doubt that any encryption key used to secure the data is being entered manually, so decryption is being done on the fly, which implies that the keys themselves are being stored on-disk. How would you secure your data and your keys in an automated system like this?

    Read the article

  • Innodb setting in xampp doesn't seem locate my.cnf file....

    - by bala3569
    I created a new mysql database and i want to use foreign keys with it... I googled and found out this... InnoDB is one of MySQL storage engines, it supports transactions, row-level locking, and foreign-keys. However, by default, InnoDB is not enabled by XAMPP. To enable it, locate the my.cnf configuration file (normally in C:/xampp/mysql/bin directory) and search for the following lines: # Comment the following if you are using InnoDB tables But the path C:/xampp/mysql/bin directory in my system doesn't seem to have such a file... Look at this image http://img691.imageshack.us/img691/524/mysqln.jpg Where is my.cnf file? Any suggestion...

    Read the article

  • how to export bind and keyframe bone poses from blender to use in OpenGL

    - by SaldaVonSchwartz
    EDIT: I decided to reformulate the question in much simpler terms to see if someone can give me a hand with this. Basically, I'm exporting meshes, skeletons and actions from blender into an engine of sorts that I'm working on. But I'm getting the animations wrong. I can tell the basic motion paths are being followed but there's always an axis of translation or rotation which is wrong. I think the problem is most likely not in my engine code (OpenGL-based) but rather in either my misunderstanding of some part of the theory behind skeletal animation / skinning or the way I am exporting the appropriate joint matrices from blender in my exporter script. I'll explain the theory, the engine animation system and my blender export script, hoping someone might catch the error in either or all of these. The theory: (I'm using column-major ordering since that's what I use in the engine cause it's OpenGL-based) Assume I have a mesh made up of a single vertex v, along with a transformation matrix M which takes the vertex v from the mesh's local space to world space. That is, if I was to render the mesh without a skeleton, the final position would be gl_Position = ProjectionMatrix * M * v. Now assume I have a skeleton with a single joint j in bind / rest pose. j is actually another matrix. A transform from j's local space to its parent space which I'll denote Bj. if j was part of a joint hierarchy in the skeleton, Bj would take from j space to j-1 space (that is to its parent space). However, in this example j is the only joint, so Bj takes from j space to world space, like M does for v. Now further assume I have a a set of frames, each with a second transform Cj, which works the same as Bj only that for a different, arbitrary spatial configuration of join j. Cj still takes vertices from j space to world space but j is rotated and/or translated and/or scaled. Given the above, in order to skin vertex v at keyframe n. I need to: take v from world space to joint j space modify j (while v stays fixed in j space and is thus taken along in the transformation) take v back from the modified j space to world space So the mathematical implementation of the above would be: v' = Cj * Bj^-1 * v. Actually, I have one doubt here.. I said the mesh to which v belongs has a transform M which takes from model space to world space. And I've also read in a couple textbooks that it needs to be transformed from model space to joint space. But I also said in 1 that v needs to be transformed from world to joint space. So basically I'm not sure if I need to do v' = Cj * Bj^-1 * v or v' = Cj * Bj^-1 * M * v. Right now my implementation multiples v' by M and not v. But I've tried changing this and it just screws things up in a different way cause there's something else wrong. Finally, If we wanted to skin a vertex to a joint j1 which in turn is a child of a joint j0, Bj1 would be Bj0 * Bj1 and Cj1 would be Cj0 * Cj1. But Since skinning is defined as v' = Cj * Bj^-1 * v , Bj1^-1 would be the reverse concatenation of the inverses making up the original product. That is, v' = Cj0 * Cj1 * Bj1^-1 * Bj0^-1 * v Now on to the implementation (Blender side): Assume the following mesh made up of 1 cube, whose vertices are bound to a single joint in a single-joint skeleton: Assume also there's a 60-frame, 3-keyframe animation at 60 fps. The animation essentially is: keyframe 0: the joint is in bind / rest pose (the way you see it in the image). keyframe 30: the joint translates up (+z in blender) some amount and at the same time rotates pi/4 rad clockwise. keyframe 59: the joint goes back to the same configuration it was in keyframe 0. My first source of confusion on the blender side is its coordinate system (as opposed to OpenGL's default) and the different matrices accessible through the python api. Right now, this is what my export script does about translating blender's coordinate system to OpenGL's standard system: # World transform: Blender -> OpenGL worldTransform = Matrix().Identity(4) worldTransform *= Matrix.Scale(-1, 4, (0,0,1)) worldTransform *= Matrix.Rotation(radians(90), 4, "X") # Mesh (local) transform matrix file.write('Mesh Transform:\n') localTransform = mesh.matrix_local.copy() localTransform = worldTransform * localTransform for col in localTransform.col: file.write('{:9f} {:9f} {:9f} {:9f}\n'.format(col[0], col[1], col[2], col[3])) file.write('\n') So if you will, my "world" matrix is basically the act of changing blenders coordinate system to the default GL one with +y up, +x right and -z into the viewing volume. Then I also premultiply (in the sense that it's done by the time we reach the engine, not in the sense of post or pre in terms of matrix multiplication order) the mesh matrix M so that I don't need to multiply it again once per draw call in the engine. About the possible matrices to extract from Blender joints (bones in Blender parlance), I'm doing the following: For joint bind poses: def DFSJointTraversal(file, skeleton, jointList): for joint in jointList: bindPoseJoint = skeleton.data.bones[joint.name] bindPoseTransform = bindPoseJoint.matrix_local.inverted() file.write('Joint ' + joint.name + ' Transform {\n') translationV = bindPoseTransform.to_translation() rotationQ = bindPoseTransform.to_3x3().to_quaternion() scaleV = bindPoseTransform.to_scale() file.write('T {:9f} {:9f} {:9f}\n'.format(translationV[0], translationV[1], translationV[2])) file.write('Q {:9f} {:9f} {:9f} {:9f}\n'.format(rotationQ[1], rotationQ[2], rotationQ[3], rotationQ[0])) file.write('S {:9f} {:9f} {:9f}\n'.format(scaleV[0], scaleV[1], scaleV[2])) DFSJointTraversal(file, skeleton, joint.children) file.write('}\n') Note that I'm actually grabbing the inverse of what I think is the bind pose transform Bj. This is so I don't need to invert it in the engine. Also note I went for matrix_local, assuming this is Bj. The other option is plain "matrix", which as far as I can tell is the same only that not homogeneous. For joint current / keyframe poses: for kfIndex in keyframes: bpy.context.scene.frame_set(kfIndex) file.write('keyframe: {:d}\n'.format(int(kfIndex))) for i in range(0, len(skeleton.data.bones)): file.write('joint: {:d}\n'.format(i)) currentPoseJoint = skeleton.pose.bones[i] currentPoseTransform = currentPoseJoint.matrix translationV = currentPoseTransform.to_translation() rotationQ = currentPoseTransform.to_3x3().to_quaternion() scaleV = currentPoseTransform.to_scale() file.write('T {:9f} {:9f} {:9f}\n'.format(translationV[0], translationV[1], translationV[2])) file.write('Q {:9f} {:9f} {:9f} {:9f}\n'.format(rotationQ[1], rotationQ[2], rotationQ[3], rotationQ[0])) file.write('S {:9f} {:9f} {:9f}\n'.format(scaleV[0], scaleV[1], scaleV[2])) file.write('\n') Note that here I go for skeleton.pose.bones instead of data.bones and that I have a choice of 3 matrices: matrix, matrix_basis and matrix_channel. From the descriptions in the python API docs I'm not super clear which one I should choose, though I think it's the plain matrix. Also note I do not invert the matrix in this case. The implementation (Engine / OpenGL side): My animation subsystem does the following on each update (I'm omitting parts of the update loop where it's figured out which objects need update and time is hardcoded here for simplicity): static double time = 0; time = fmod((time + elapsedTime),1.); uint16_t LERPKeyframeNumber = 60 * time; uint16_t lkeyframeNumber = 0; uint16_t lkeyframeIndex = 0; uint16_t rkeyframeNumber = 0; uint16_t rkeyframeIndex = 0; for (int i = 0; i < aClip.keyframesCount; i++) { uint16_t keyframeNumber = aClip.keyframes[i].number; if (keyframeNumber <= LERPKeyframeNumber) { lkeyframeIndex = i; lkeyframeNumber = keyframeNumber; } else { rkeyframeIndex = i; rkeyframeNumber = keyframeNumber; break; } } double lTime = lkeyframeNumber / 60.; double rTime = rkeyframeNumber / 60.; double blendFactor = (time - lTime) / (rTime - lTime); GLKMatrix4 bindPosePalette[aSkeleton.jointsCount]; GLKMatrix4 currentPosePalette[aSkeleton.jointsCount]; for (int i = 0; i < aSkeleton.jointsCount; i++) { F3DETQSType& lPose = aClip.keyframes[lkeyframeIndex].skeletonPose.joints[i]; F3DETQSType& rPose = aClip.keyframes[rkeyframeIndex].skeletonPose.joints[i]; GLKVector3 LERPTranslation = GLKVector3Lerp(lPose.t, rPose.t, blendFactor); GLKQuaternion SLERPRotation = GLKQuaternionSlerp(lPose.q, rPose.q, blendFactor); GLKVector3 LERPScaling = GLKVector3Lerp(lPose.s, rPose.s, blendFactor); GLKMatrix4 currentTransform = GLKMatrix4MakeWithQuaternion(SLERPRotation); currentTransform = GLKMatrix4TranslateWithVector3(currentTransform, LERPTranslation); currentTransform = GLKMatrix4ScaleWithVector3(currentTransform, LERPScaling); GLKMatrix4 inverseBindTransform = GLKMatrix4MakeWithQuaternion(aSkeleton.joints[i].inverseBindTransform.q); inverseBindTransform = GLKMatrix4TranslateWithVector3(inverseBindTransform, aSkeleton.joints[i].inverseBindTransform.t); inverseBindTransform = GLKMatrix4ScaleWithVector3(inverseBindTransform, aSkeleton.joints[i].inverseBindTransform.s); if (aSkeleton.joints[i].parentIndex == -1) { bindPosePalette[i] = inverseBindTransform; currentPosePalette[i] = currentTransform; } else { bindPosePalette[i] = GLKMatrix4Multiply(inverseBindTransform, bindPosePalette[aSkeleton.joints[i].parentIndex]); currentPosePalette[i] = GLKMatrix4Multiply(currentPosePalette[aSkeleton.joints[i].parentIndex], currentTransform); } aSkeleton.skinningPalette[i] = GLKMatrix4Multiply(currentPosePalette[i], bindPosePalette[i]); } Finally, this is my vertex shader: #version 100 uniform mat4 modelMatrix; uniform mat3 normalMatrix; uniform mat4 projectionMatrix; uniform mat4 skinningPalette[6]; uniform lowp float skinningEnabled; attribute vec4 position; attribute vec3 normal; attribute vec2 tCoordinates; attribute vec4 jointsWeights; attribute vec4 jointsIndices; varying highp vec2 tCoordinatesVarying; varying highp float lIntensity; void main() { tCoordinatesVarying = tCoordinates; vec4 skinnedVertexPosition = vec4(0.); for (int i = 0; i < 4; i++) { skinnedVertexPosition += jointsWeights[i] * skinningPalette[int(jointsIndices[i])] * position; } vec4 skinnedNormal = vec4(0.); for (int i = 0; i < 4; i++) { skinnedNormal += jointsWeights[i] * skinningPalette[int(jointsIndices[i])] * vec4(normal, 0.); } vec4 finalPosition = mix(position, skinnedVertexPosition, skinningEnabled); vec4 finalNormal = mix(vec4(normal, 0.), skinnedNormal, skinningEnabled); vec3 eyeNormal = normalize(normalMatrix * finalNormal.xyz); vec3 lightPosition = vec3(0., 0., 2.); lIntensity = max(0.0, dot(eyeNormal, normalize(lightPosition))); gl_Position = projectionMatrix * modelMatrix * finalPosition; } The result is that the animation displays wrong in terms of orientation. That is, instead of bobbing up and down it bobs in and out (along what I think is the Z axis according to my transform in the export clip). And the rotation angle is counterclockwise instead of clockwise. If I try with a more than one joint, then it's almost as if the second joint rotates in it's own different coordinate space and does not follow 100% its parent's transform. Which I assume it should from my animation subsystem which I assume in turn follows the theory I explained for the case of more than one joint. Any thoughts?

    Read the article

  • Python hashable dicts

    - by TokenMacGuy
    As an exercise, and mostly for my own amusement, I'm implementing a backtracking packrat parser. The inspiration for this is i'd like to have a better idea about how hygenic macros would work in an algol-like language (as apposed to the syntax free lisp dialects you normally find them in). Because of this, different passes through the input might see different grammars, so cached parse results are invalid, unless I also store the current version of the grammar along with the cached parse results. (EDIT: a consequence of this use of key-value collections is that they should be immutable, but I don't intend to expose the interface to allow them to be changed, so either mutable or immutable collections are fine) The problem is that python dicts cannot appear as keys to other dicts. Even using a tuple (as I'd be doing anyways) doesn't help. >>> cache = {} >>> rule = {"foo":"bar"} >>> cache[(rule, "baz")] = "quux" Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'dict' >>> I guess it has to be tuples all the way down. Now the python standard library provides approximately what i'd need, collections.namedtuple has a very different syntax, but can be used as a key. continuing from above session: >>> from collections import namedtuple >>> Rule = namedtuple("Rule",rule.keys()) >>> cache[(Rule(**rule), "baz")] = "quux" >>> cache {(Rule(foo='bar'), 'baz'): 'quux'} Ok. But I have to make a class for each possible combination of keys in the rule I would want to use, which isn't so bad, because each parse rule knows exactly what parameters it uses, so that class can be defined at the same time as the function that parses the rule. But combining the rules together is much more dynamic. In particular, I'd like a simple way to have rules override other rules, but collections.namedtuple has no analogue to dict.update(). Edit: An additional problem with namedtuples is that they are strictly positional. Two tuples that look like they should be different can in fact be the same: >>> you = namedtuple("foo",["bar","baz"]) >>> me = namedtuple("foo",["bar","quux"]) >>> you(bar=1,baz=2) == me(bar=1,quux=2) True >>> bob = namedtuple("foo",["baz","bar"]) >>> you(bar=1,baz=2) == bob(bar=1,baz=2) False tl'dr: How do I get dicts that can be used as keys to other dicts? Having hacked a bit on the answers, here's the more complete solution I'm using. Note that this does a bit extra work to make the resulting dicts vaguely immutable for practical purposes. Of course it's still quite easy to hack around it by calling dict.__setitem__(instance, key, value) but we're all adults here. class hashdict(dict): """ hashable dict implementation, suitable for use as a key into other dicts. >>> h1 = hashdict({"apples": 1, "bananas":2}) >>> h2 = hashdict({"bananas": 3, "mangoes": 5}) >>> h1+h2 hashdict(apples=1, bananas=3, mangoes=5) >>> d1 = {} >>> d1[h1] = "salad" >>> d1[h1] 'salad' >>> d1[h2] Traceback (most recent call last): ... KeyError: hashdict(bananas=3, mangoes=5) based on answers from http://stackoverflow.com/questions/1151658/python-hashable-dicts """ def __key(self): return tuple(sorted(self.items())) def __repr__(self): return "{0}({1})".format(self.__class__.__name__, ", ".join("{0}={1}".format( str(i[0]),repr(i[1])) for i in self.__key())) def __hash__(self): return hash(self.__key()) def __setitem__(self, key, value): raise TypeError("{0} does not support item assignment" .format(self.__class__.__name__)) def __delitem__(self, key): raise TypeError("{0} does not support item assignment" .format(self.__class__.__name__)) def clear(self): raise TypeError("{0} does not support item assignment" .format(self.__class__.__name__)) def pop(self, *args, **kwargs): raise TypeError("{0} does not support item assignment" .format(self.__class__.__name__)) def popitem(self, *args, **kwargs): raise TypeError("{0} does not support item assignment" .format(self.__class__.__name__)) def setdefault(self, *args, **kwargs): raise TypeError("{0} does not support item assignment" .format(self.__class__.__name__)) def update(self, *args, **kwargs): raise TypeError("{0} does not support item assignment" .format(self.__class__.__name__)) def __add__(self, right): result = hashdict(self) dict.update(result, right) return result if __name__ == "__main__": import doctest doctest.testmod()

    Read the article

< Previous Page | 142 143 144 145 146 147 148 149 150 151 152 153  | Next Page >