Daily Archives

Articles indexed Thursday July 5 2012

Page 11/17 | < Previous Page | 7 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • Ember.js CollectionView order

    - by ilia choly
    I have an ArrayController which is periodically updated. It has a sorted computed property which keeps things in order. I'm trying to use a CollectionView with it's content property bound to the sorted property, but it's not rendering them in the correct order. demo I've obviously made the false assumption that order is maintained between the content and childViews property. What is the correct way to do this?

    Read the article

  • SQL Server race condition issue with range lock

    - by Freek
    I'm implementing a queue in SQL Server (please no discussions about this) and am running into a race condition issue. The T-SQL of interest is the following: set transaction isolation level serializable begin tran declare @RecordId int declare @CurrentTS datetime2 set @CurrentTS=CURRENT_TIMESTAMP select top 1 @RecordId=Id from QueuedImportJobs with (updlock) where Status=@Status and (LeaseTimeout is null or @CurrentTS>LeaseTimeout) order by Id asc if @@ROWCOUNT> 0 begin update QueuedImportJobs set LeaseTimeout = DATEADD(mi,5,@CurrentTS), LeaseTicket=newid() where Id=@RecordId select * from QueuedImportJobs where Id = @RecordId end commit tran RecordId is the PK and there is also an index on Status,LeaseTimeout. What I'm basically doing is select a record of which the lease happens to be expired, while simultaneously updating the lease time with 5 minutes and setting a new lease ticket. So the problem is that I'm getting deadlocks when I run this code in parallel using a couple of threads. I've debugged it up to the point where I found out that the update statement sometimes gets executing twice for the same record. Now, I was under the impression that the with (updlock) should prevent this (it also happens with xlock btw, not with tablockx). So it actually look like there is a RangeS-U and a RangeX-X lock on the same range of records, which ought to be impossible. So what am I missing? I'm thinking it might have something to do with the top 1 clause or that SQL Server does not know that where Id=@RecordId is actually in the locked range? Deadlock graph: Table schema (simplified):

    Read the article

  • Does Apache allow to authorize an HTTP request based on a result of a subrequest?

    - by Jan Wrobel
    I'm looking for an equivalent of nginx http auth request module but for Apache. For each incoming HTTP requests, the module sends a subrequests to authentication/authorization back-end. Th auth request carries a path and all headers of the original request. Based on the result of the auth request, the original requests is allowed (HTTP code 200), denied (HTTP code 403) or login is requested (HTTP code 401). Such a generic mechanism allows to build really flexible authentication and authorization schemes. Is something like this possible in Apache (likely with a help of some third party module)?

    Read the article

  • Androids ExpandableListView - where to put the button listener for buttons that are children

    - by CommonKnowledge
    I have been playing around a lot with the ExpandableListView and I cannot figure out where to add the button listeners for the button that will be the children in the view. I did manage to get a button listener working that uses getChildView() below, but it seems to be the same listener for all the buttons. The best case scenario is that I would be able to implement the button listeners in the class that instantiates the ExpandableListAdapter class, and not have to put the listeners in the actual ExpandableListAdapter class. At this point I don't even know if that is possible I have been experimenting with this tutorial/code: HERE getChildView() @Override public View getChildView(int set_new, int child_position, boolean view, View view1, ViewGroup view_group1) { ChildHolder childHolder; if (view1 == null) { view1 = LayoutInflater.from(info_context).inflate(R.layout.list_group_item_lv, null); childHolder = new ChildHolder(); childHolder.section_btn = (Button)view1.findViewById(R.id.item_title); view1.setTag(childHolder); childHolder.section_btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(info_context, "button pushed", Toast.LENGTH_SHORT).show(); } }); }else { childHolder = (ChildHolder) view1.getTag(); } childHolder.section_btn.setText(children_collection.get(set_new).GroupItemCollection.get(child_position).section); Typeface tf = Typeface.createFromAsset(info_context.getAssets(), "fonts/AGENCYR.TTF"); childHolder.section_btn.setTypeface(tf); return view1; } Any help would be much appreciated. Thank you and I will be standing by.

    Read the article

  • use proxy from a list

    - by user1505181
    I am trying to write a program which neeeds to use a proxy 3 times then move onto the next proxy in a list and so on. the user will enter their proxy list into a list/textfile and the program will use the first in the list and then carry on through the list until it gets to the end. How do i get the proxy details from the list and use them using httpwebrequest? i have no problem using a proxy if i set it within the code but dont know how to get it to work through the list basically it is like this: user enters a list of proxies into a text file program uses first proxy in list 3 times then moves onto next. this repeats until finished.

    Read the article

  • PHP Convert C# Hex Blob Hexadecimal String back to Byte Array prior to decryption

    - by PolishHurricane
    I have a piece of data that I am receiving in hexadecimal string format, example: "65E0C8DEB69EA114567954". It was made this way in C# by converting a byte array to a hexadecimal string. However, I am using PHP to read this string and need to temporarily convert this back to the byte array. If it matters, I will be decrypting this byte array, then reconverting it to unencrypted hexadecimal and or plaintext, but I will figure that out later. So the question is, how do I convert a string like the above back to an encoded byte array/ blob in PHP? Thanks!

    Read the article

  • How can I create/update an XML node that may or may not exist?

    - by ScottBai
    Is there a method available (i.e. without me creating my own recursive method), for a given xpath (or other method of identifying the hierarchical position) to create/update an XML node, where the node would be created if it does not exist? This would need to create the parent node if it does not exist as well. I do have an XSD which includes all possible nodes. i.e. Before: <employee> <name>John Smith</name> </employee> Would like to call something like this: CoolXmlUpdateMethod("/employee/address/city", "Los Angeles"); After: <employee> <name>John Smith</name> <address> <city>Los Angeles</city> </address> </employee> Or even a method to create a node, given an xpath, wherein it will recursively create the parent node(s) if they do not exist? As far as the application (if it matters), this is taking an existing XML doc that contains only populated nodes, and adding data to it from another system. The new data may or may not already have values populated in the source XML. Surely this is not an uncommon scenario?

    Read the article

  • AIDL based two way communication

    - by sshasan
    I have two apps between which I want some data exchanged. As they are running in different processes, so, I am using AIDL to communicate between them. Now, everything is happening really great in one direction (say my apps are A and B) i.e. data is being sent from A to B but, now I need to send some data from B to A. I noticed that we need to include the app with the AIDL in the build path of app where the AIDL method will be called. So in my case A includes B in its build path. For B to be able to send something to A, by that logic, B would need A in its build path. This would create a cycle. I am stuck at this point. And I cannot think of a work around this loop. Any help would be greatly appreciated :) . Thanks! ----EDIT---- So, I following the advice mentioned in one of the comments below, I have the following code In the IPCAIDL project the AIDL file resides, its contents are package ipc.android.aidl; interface Iaidl{ boolean pushBoolean(boolean flag); } This project is being used as a library in both the IPCServer and the IPC Client. The IPCServer Project has the service which defines what happens with the AIDL method. The file is booleanService.java package ipc.android.server; import ipc.android.aidl.Iaidl; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; public class booleanService extends Service { @Override public IBinder onBind(Intent intent) { return new Iaidl.Stub() { @Override public boolean pushBoolean(boolean arg0) throws RemoteException { Log.i("SERVER(IPC AIDL)", "Truth Value:"+arg0); return arg0; } }; } } The IPCClient file which calls this method is package ipc.android.client2; import ipc.android.aidl.Iaidl; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.os.RemoteException; import android.view.View; import android.widget.Button; public class IPCClient2Activity extends Activity { Button b1; Iaidl iAIDL; boolean k = false; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); bindService(new Intent("ipc.android.server.booleanService"), conn, Context.BIND_AUTO_CREATE); startService(new Intent("ipc.android.server.booleanService")); b1 = (Button) findViewById(R.id.button1); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(k){ k = false; } else{ k = true; } try { iAIDL.pushBoolean(k); } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); } private ServiceConnection conn = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { // TODO Auto-generated method stub } @Override public void onServiceConnected(ComponentName name, IBinder service) { iAIDL = Iaidl.Stub.asInterface(service); } }; } The manifest file for IPCServer includes the declaration of the service.

    Read the article

  • Cannot import resource > "app/config/security.yml" from "/app/config/config.yml"

    - by tirengarfio
    Im getting this error: FileLoaderLoadException: Cannot import resource "app/config/security.yml" from "/app/config/config.yml". The file security.yml is on the right path. This is my security.yml file: jms_sapp/confiapp/config/security.yml secure_all_services: false exprapp/confiapp/config/security.yml security: encoders: Symfony\Component\Security\Core\User\User: plaintext role_hierarchy: ROLE_ADMIN: ROLE_USER ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH] providers: in_memory: memory: users: user: { password: userpass, roles: [ 'ROLE_USER' ] } admin: { password: adminpass, roles: [ 'ROLE_ADMIN' ] } firewalls: dev: pattern: ^/(_(profiler|wdt)|css|images|js)/ security: false login: pattern: ^/demo/secured/login$ security: false secured_area: pattern: ^/demo/secured/ form_login: check_path: /demo/secured/login_check login_path: /demo/secured/login logout: path: /demo/secured/logout target: /demo/ #anonymous: ~ #http_basic: # realm: "Secured Demo Area" access_control: #- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY, requires_channel: https } #- { path: ^/_internal/secure, roles: IS_AUTHENTICATED_ANONYMOUSLY, ip: 127.0.0.1 }

    Read the article

  • How to redirect a URL with GET variables in routes.rb without Rails stripping out the variable first?

    - by Michael Hopkins
    I am building a website in Rails to replace an existing website. In routes.rb I am trying to redirect some of the old URLs to their new equivalents (some of the URL slugs are changing so a dynamic solution is not possible.) My routes.rb looks like this: match "/index.php?page=contact-us" => redirect("/contact-us") match "/index.php?page=about-us" => redirect("/about-us") match "/index.php?page=committees" => redirect("/teams") When I visit /index.php?page=contact-us I am not redirected to /contact-us. I have determined this is because Rails is removing the get variables and only trying to match /index.php. For example, If I pass /index.php?page=contact-us into the below routes I will be redirected to /foobar: match "/index.php?page=contact-us" => redirect("/contact-us") match "/index.php?page=about-us" => redirect("/about-us") match "/index.php?page=committees" => redirect("/teams") match "/index.php" => redirect("/foobar") How can I keep the GET variables in the string and redirect the old URLs the way I'd like? Does Rails have an intended mechanism for this?

    Read the article

  • PHP APC - Why is loading cached array op codes slow?

    - by Aaron Kreider
    I'm using APC to reduce my loading time for my PHP files. My files load very fast, except for one file where I define more than 100 arrays. This 270 kb file takes 200 ms to load. The rest of the files are full of objects, methods, and functions. I'm wondering: does OP code caching not work as well for arrays? My APC cache should be big enough to handle all of my classes. Currently 40% of my cache is free. My hit rate is 99%. apc.shm_size=32 M apc.max_file_size = 1M apc.shm_segments= 1 APC 3.1.6 I'm using PHP 5.2, Apache 2, and Windows Vista.

    Read the article

  • Node.js running under IIS Express Keeps Crashing

    - by PazoozaTest Pazman
    I recently resinstalled Windows 7 on my machine and went back to downloading and installing the tools to help me continue developing node.js windows azure web applications. I followed the instructions given on the node.js azure site: http://www.windowsazure.com/en-us/develop/nodejs/ and using web installer 4.0 it says I have successfully installed these tools: Windows Azure Powershell Windows Azure SDK for Node.js - June 2012 Windows Azure SDK for .Net (VS 2012 RC) - June 2012 IIS Recommend Configuration The problem I am experiencing is that when I run the site using powershell e.g: start-azureemulator -launch it goes ahead and runs IIS Express, and after several minutes IIS Express crashes with the following information: Problem signature: Problem Event Name: APPCRASH Application Name: iisexpress.exe Application Version: 8.0.8298.0 Application Timestamp: 4f620349 Fault Module Name: iiscore.dll Fault Module Version: 8.0.8298.0 Fault Module Timestamp: 4f63b65c Exception Code: c0000005 Exception Offset: 00021767 OS Version: 6.1.7601.2.1.0.256.28 Locale ID: 1033 Additional Information 1: f66d Additional Information 2: f66d807b515d6b2dc6f28f66db769a01 Additional Information 3: 7b2f Additional Information 4: 7b2f6797d07ebc2c23f2b227e779722e I am running 2 instances each time, and both of them crash one after the other. Is anyone experiencing something similar and fix this issue ? Is their an upgrade I need to do ? I've run windows update but it says I've got all the latest updates etc. Can I tell the powershell cmdlet to use IIS 7 instead of IIS Express? I'm guessing its something to do with IIS Express on my machine. I did some hunting around and found this person here who experienced a similar problem: https://github.com/tjanczuk/iisnode/issues/149 I've got a cron job running every 1 second, to check if any website totals need to be updated. Could this be causing IIS Express to crash? Cheers

    Read the article

  • Accessing PerSession service simultaneously in WCF using C#

    - by krishna555
    1.) I have a main method Processing, which takes string as an arguments and that string contains some x number of tasks. 2.) I have another method Status, which keeps track of first method by using two variables TotalTests and CurrentTest. which will be modified every time with in a loop in first method(Processing). 3.) When more than one client makes a call parallely to my web service to call the Processing method by passing a string, which has different tasks will take more time to process. so in the mean while clients will be using a second thread to call the Status method in the webservice to get the status of the first method. 4.) when point number 3 is being done all the clients are supposed to get the variables(TotalTests,CurrentTest) parallely with out being mixed up with other client requests. 5.) The code that i have provided below is getting mixed up variables results for all the clients when i make them as static. If i remove static for the variables then clients are just getting all 0's for these 2 variables and i am unable to fix it. Please take a look at the below code. [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)] public class Service1 : IService1 { public int TotalTests = 0; public int CurrentTest = 0; public string Processing(string OriginalXmlString) { XmlDocument XmlDoc = new XmlDocument(); XmlDoc.LoadXml(OriginalXmlString); this.TotalTests = XmlDoc.GetElementsByTagName("TestScenario").Count; //finding the count of total test scenarios in the given xml string this.CurrentTest = 0; while(i<10) { ++this.CurrentTest; i++; } } public string Status() { return (this.TotalTests + ";" + this.CurrentTest); } } server configuration <wsHttpBinding> <binding name="WSHttpBinding_IService1" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288" maxReceivedMessageSize="2147483647" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false"> <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" /> <reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="true" /> <security mode="Message"> <transport clientCredentialType="Windows" proxyCredentialType="None" realm="" /> <message clientCredentialType="Windows" negotiateServiceCredential="true" algorithmSuite="Default" establishSecurityContext="true" /> </security> </binding> </wsHttpBinding> client configuration <wsHttpBinding> <binding name="WSHttpBinding_IService1" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288" maxReceivedMessageSize="2147483647" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false"> <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" /> <reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="true" /> <security mode="Message"> <transport clientCredentialType="Windows" proxyCredentialType="None" realm="" /> <message clientCredentialType="Windows" negotiateServiceCredential="true" algorithmSuite="Default" establishSecurityContext="true" /> </security> </binding> </wsHttpBinding> Below mentioned is my client code class Program { static void Main(string[] args) { Program prog = new Program(); Thread JavaClientCallThread = new Thread(new ThreadStart(prog.ClientCallThreadRun)); Thread JavaStatusCallThread = new Thread(new ThreadStart(prog.StatusCallThreadRun)); JavaClientCallThread.Start(); JavaStatusCallThread.Start(); } public void ClientCallThreadRun() { XmlDocument doc = new XmlDocument(); doc.Load(@"D:\t72CalculateReasonableWithdrawal_Input.xml"); bool error = false; Service1Client Client = new Service1Client(); string temp = Client.Processing(doc.OuterXml, ref error); } public void StatusCallThreadRun() { int i = 0; Service1Client Client = new Service1Client(); string temp; while (i < 10) { temp = Client.Status(); Thread.Sleep(1500); Console.WriteLine("TotalTestScenarios;CurrentTestCase = {0}", temp); i++; } } } Can any one please help.

    Read the article

  • what kind of relationship is there between a common wall and the rooms that located next to it?

    - by siamak
    I want to know whats the Relationship between a common wall (that are located In an adjoining room ) and the rooms. As i know the relationship between a room and its walls is Composition not Aggregation (am i right ?) And according to the definition of Composition the contained object can't be shared between two containers, whereas in aggregation it is possible. now i am confused that whats the best modeling approach to represent the relationship between a common wall and the rooms located next to it ? It would be highly Appreciated if you could provide your advices with some code. |--------|--------| Approch1: (wall class ---- room class) /Composition Approach2: wall class ----- room class /Aggregation Approch3: we have a wall class and a Common wall class , Common wall class inherits from wall class adjoining room class ---- (1) Common wall class /Aggregation adjoining room class ---- (6) wall class / composition Approach4: I am a developer not a designer :) so this is my idea : class Room { private wall _firstwall ; private wall _secondtwall; private wall _thirdwall ; private wall _commonwall ; public Room( CommonWall commonwall) { _firstwall=new Wall(); _secondtwall=new Wall(); _thirdwall=new Wall(); _commonwall=commonwall; } } Class CommonWall:Wall { //... } // in somewher : static void main() { Wall _commonWall=new Wall(); Room room1=new Room(_commonWall); Room room2=new Room(_commonWall); Room [] adjacentRoom =new Room[2]{room1,room2}; } Edit 1: I think this is a clear question but just for more clarification : The point of the question is to find out whats the best pattern or approach to model a relationship for an object that is a component of two other objects in the same time. and about my example : waht i mean by a "room" ?,surely i mean an enclosed square room with 4 walls and one door.but in this case one of these walls is a common wall and is shared between two adjacent rooms.

    Read the article

  • Applescript from Mac App says "Expected end of line but found \U201c\"\U201d."

    - by Rasmus Styrk
    I am trying to perform a copy/paste for my to the the last active app, here's my code: NSString *appleScriptSource = [NSString stringWithFormat:@"\ntell application \"%@\" to activate\ntell application \"System Events\" to tell process \"%@\"\nkeystroke \"v\" using command down\nend tell", [lastApp localizedName], [lastApp localizedName]]; NSDictionary *error; NSAppleScript *aScript = [[NSAppleScript alloc] initWithSource:appleScriptSource]; NSAppleEventDescriptor *aDescriptor = [aScript executeAndReturnError:&error]; The problem is that on some computers it works just fine, but on others it fails. My error output from error that is returned by executeAndReturnError is: 2012-06-13 17:43:19.875 Mini Translator[1206:303] (null) (error: { NSAppleScriptErrorBriefMessage = "Expected end of line but found \U201c\"\U201d."; NSAppleScriptErrorMessage = "Expected end of line but found \U201c\"\U201d."; NSAppleScriptErrorNumber = "-2741"; NSAppleScriptErrorRange = "NSRange: {95, 1}"; }) I can't seem to figure out what it means or why it happens. We tried copying the generated apple-script code into the Apple Script editor, and here it works just fine. My App is sandboxed - i have added the bundle identifiers for the key "com.apple.security.temporary-exception.apple-events" for the apps i want to support. Any suggestions?

    Read the article

  • Understanding and Implementing a Force based graph layout algorithm

    - by zcourts
    I'm trying to implement a force base graph layout algorithm, based on http://en.wikipedia.org/wiki/Force-based_algorithms_(graph_drawing) My first attempt didn't work so I looked at http://blog.ivank.net/force-based-graph-drawing-in-javascript.html and https://github.com/dhotson/springy I changed my implementation based on what I thought I understood from those two but I haven't managed to get it right and I'm hoping someone can help? JavaScript isn't my strong point so be gentle... If you're wondering why write my own. In reality I have no real reason to write my own I'm just trying to understand how the algorithm is implemented. Especially in my first link, that demo is brilliant. This is what I've come up with //support function.bind - https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind#Compatibility if (!Function.prototype.bind) { Function.prototype.bind = function (oThis) { if (typeof this !== "function") { // closest thing possible to the ECMAScript 5 internal IsCallable function throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable"); } var aArgs = Array.prototype.slice.call(arguments, 1), fToBind = this, fNOP = function () {}, fBound = function () { return fToBind.apply(this instanceof fNOP ? this : oThis || window, aArgs.concat(Array.prototype.slice.call(arguments))); }; fNOP.prototype = this.prototype; fBound.prototype = new fNOP(); return fBound; }; } (function() { var lastTime = 0; var vendors = ['ms', 'moz', 'webkit', 'o']; for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame']; window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame']; } if (!window.requestAnimationFrame) window.requestAnimationFrame = function(callback, element) { var currTime = new Date().getTime(); var timeToCall = Math.max(0, 16 - (currTime - lastTime)); var id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; if (!window.cancelAnimationFrame) window.cancelAnimationFrame = function(id) { clearTimeout(id); }; }()); function Graph(o){ this.options=o; this.vertices={}; this.edges={};//form {vertexID:{edgeID:edge}} } /** *Adds an edge to the graph. If the verticies in this edge are not already in the *graph then they are added */ Graph.prototype.addEdge=function(e){ //if vertex1 and vertex2 doesn't exist in this.vertices add them if(typeof(this.vertices[e.vertex1])==='undefined') this.vertices[e.vertex1]=new Vertex(e.vertex1); if(typeof(this.vertices[e.vertex2])==='undefined') this.vertices[e.vertex2]=new Vertex(e.vertex2); //add the edge if(typeof(this.edges[e.vertex1])==='undefined') this.edges[e.vertex1]={}; this.edges[e.vertex1][e.id]=e; } /** * Add a vertex to the graph. If a vertex with the same ID already exists then * the existing vertex's .data property is replaced with the @param v.data */ Graph.prototype.addVertex=function(v){ if(typeof(this.vertices[v.id])==='undefined') this.vertices[v.id]=v; else this.vertices[v.id].data=v.data; } function Vertex(id,data){ this.id=id; this.data=data?data:{}; //initialize to data.[x|y|z] or generate random number for each this.x = this.data.x?this.data.x:-100 + Math.random()*200; this.y = this.data.y?this.data.y:-100 + Math.random()*200; this.z = this.data.y?this.data.y:-100 + Math.random()*200; //set initial velocity to 0 this.velocity = new Point(0, 0, 0); this.mass=this.data.mass?this.data.mass:Math.random(); this.force=new Point(0,0,0); } function Edge(vertex1ID,vertex2ID){ vertex1ID=vertex1ID?vertex1ID:Math.random() vertex2ID=vertex2ID?vertex2ID:Math.random() this.id=vertex1ID+"->"+vertex2ID; this.vertex1=vertex1ID; this.vertex2=vertex2ID; } function Point(x, y, z) { this.x = x; this.y = y; this.z = z; } Point.prototype.plus=function(p){ this.x +=p.x this.y +=p.y this.z +=p.z } function ForceLayout(o){ this.repulsion = o.repulsion?o.repulsion:200; this.attraction = o.attraction?o.attraction:0.06; this.damping = o.damping?o.damping:0.9; this.graph = o.graph?o.graph:new Graph(); this.total_kinetic_energy =0; this.animationID=-1; } ForceLayout.prototype.draw=function(){ //vertex velocities initialized to (0,0,0) when a vertex is created //vertex positions initialized to random position when created cc=0; do{ this.total_kinetic_energy =0; //for each vertex for(var i in this.graph.vertices){ var thisNode=this.graph.vertices[i]; // running sum of total force on this particular node var netForce=new Point(0,0,0) //for each other node for(var j in this.graph.vertices){ if(thisNode!=this.graph.vertices[j]){ //net-force := net-force + Coulomb_repulsion( this_node, other_node ) netForce.plus(this.CoulombRepulsion( thisNode,this.graph.vertices[j])) } } //for each spring connected to this node for(var k in this.graph.edges[thisNode.id]){ //(this node, node its connected to) //pass id of this node and the node its connected to so hookesattraction //can update the force on both vertices and return that force to be //added to the net force this.HookesAttraction(thisNode.id, this.graph.edges[thisNode.id][k].vertex2 ) } // without damping, it moves forever // this_node.velocity := (this_node.velocity + timestep * net-force) * damping thisNode.velocity.x=(thisNode.velocity.x+thisNode.force.x)*this.damping; thisNode.velocity.y=(thisNode.velocity.y+thisNode.force.y)*this.damping; thisNode.velocity.z=(thisNode.velocity.z+thisNode.force.z)*this.damping; //this_node.position := this_node.position + timestep * this_node.velocity thisNode.x=thisNode.velocity.x; thisNode.y=thisNode.velocity.y; thisNode.z=thisNode.velocity.z; //normalize x,y,z??? //total_kinetic_energy := total_kinetic_energy + this_node.mass * (this_node.velocity)^2 this.total_kinetic_energy +=thisNode.mass*((thisNode.velocity.x+thisNode.velocity.y+thisNode.velocity.z)* (thisNode.velocity.x+thisNode.velocity.y+thisNode.velocity.z)) } cc+=1; }while(this.total_kinetic_energy >0.5) console.log(cc,this.total_kinetic_energy,this.graph) this.cancelAnimation(); } ForceLayout.prototype.HookesAttraction=function(v1ID,v2ID){ var a=this.graph.vertices[v1ID] var b=this.graph.vertices[v2ID] var force=new Point(this.attraction*(b.x - a.x),this.attraction*(b.y - a.y),this.attraction*(b.z - a.z)) // hook's attraction a.force.x += force.x; a.force.y += force.y; a.force.z += force.z; b.force.x += this.attraction*(a.x - b.x); b.force.y += this.attraction*(a.y - b.y); b.force.z += this.attraction*(a.z - b.z); return force; } ForceLayout.prototype.CoulombRepulsion=function(vertex1,vertex2){ //http://en.wikipedia.org/wiki/Coulomb's_law // distance squared = ((x1-x2)*(x1-x2)) + ((y1-y2)*(y1-y2)) + ((z1-z2)*(z1-z2)) var distanceSquared = ( (vertex1.x-vertex2.x)*(vertex1.x-vertex2.x)+ (vertex1.y-vertex2.y)*(vertex1.y-vertex2.y)+ (vertex1.z-vertex2.z)*(vertex1.z-vertex2.z) ); if(distanceSquared==0) distanceSquared = 0.001; var coul = this.repulsion / distanceSquared; return new Point(coul * (vertex1.x-vertex2.x),coul * (vertex1.y-vertex2.y), coul * (vertex1.z-vertex2.z)); } ForceLayout.prototype.animate=function(){ if(this.animating) this.animationID=requestAnimationFrame(this.animate.bind(this)); this.draw(); } ForceLayout.prototype.cancelAnimation=function(){ cancelAnimationFrame(this.animationID); this.animating=false; } ForceLayout.prototype.redraw=function(){ this.animating=true; this.animate(); } $(document).ready(function(){ var g= new Graph(); for(var i=0;i<=100;i++){ var v1=new Vertex(Math.random(), {}) var v2=new Vertex(Math.random(), {}) var e1= new Edge(v1.id,v2.id); g.addEdge(e1); } console.log(g); var l=new ForceLayout({ graph:g }); l.redraw(); });

    Read the article

  • Force save files all browsers - not open in browser window

    - by Joshc
    I'm after a simple solution to work in all browsers. For specific file types, or targeted links via a class: how can I get them to simply force download in all major browsers. I thought I found the perfect solution for apachce server - by adding this into the .htaccess. http://css-tricks.com/snippets/htaccess/force-files-to-download-not-open-in-browser/ AddType application/octet-stream .csv AddType application/octet-stream .xls AddType application/octet-stream .doc AddType application/octet-stream .avi AddType application/octet-stream .mpg AddType application/octet-stream .mov AddType application/octet-stream .pdf Seems to work in Firefox and Safari, but not chrome or IE (have not tested anything else) Can any one please help me with a solution on how to make links to force download the file, instead of opening in the browser, for ALL browsers. I can't seem to find a full browser proof solution. Is it not possible? Any links to tutorial or snippets would be awesome. My website if PHP based so can make it work with PHP if posible. Thanks

    Read the article

  • Google Data Api returning an invalid access token

    - by kingdavies
    I'm trying to pull a list of contacts from a google account. But Google returns a 401. The url used for requesting an authorization code: String codeUrl = 'https://accounts.google.com/o/oauth2/auth' + '?' + 'client_id=' + EncodingUtil.urlEncode(CLIENT_ID, 'UTF-8') + '&redirect_uri=' + EncodingUtil.urlEncode(MY_URL, 'UTF-8') + '&scope=' + EncodingUtil.urlEncode('https://www.google.com/m8/feeds/', 'UTF-8') + '&access_type=' + 'offline' + '&response_type=' + EncodingUtil.urlEncode('code', 'UTF-8') + '&approval_prompt=' + EncodingUtil.urlEncode('force', 'UTF-8'); Exchanging the returned authorization code for an access token (and refresh token): String params = 'code=' + EncodingUtil.urlEncode(authCode, 'UTF-8') + '&client_id=' + EncodingUtil.urlEncode(CLIENT_ID, 'UTF-8') + '&client_secret=' + EncodingUtil.urlEncode(CLIENT_SECRET, 'UTF-8') + '&redirect_uri=' + EncodingUtil.urlEncode(MY_URL, 'UTF-8') + '&grant_type=' + EncodingUtil.urlEncode('authorization_code', 'UTF-8'); Http con = new Http(); Httprequest req = new Httprequest(); req.setEndpoint('https://accounts.google.com/o/oauth2/token'); req.setHeader('Content-Type', 'application/x-www-form-urlencoded'); req.setBody(params); req.setMethod('POST'); Httpresponse reply = con.send(req); Which returns a JSON array with what looks like a valid access token: { "access_token" : "{access_token}", "token_type" : "Bearer", "expires_in" : 3600, "refresh_token" : "{refresh_token}" } However when I try and use the access token (either in code or curl) Google returns a 401: curl -H "Authorization: Bearer {access_token}" https://www.google.com/m8/feeds/contacts/default/full/ Incidentally the same curl command but with an access token acquired via https://code.google.com/oauthplayground/ works. Which leads me to believe there is something wrong with the exchanging authorization code for access token request as the returned access token does not work. I should add this is all within the expires_in time frame so its not that the access_token has expired

    Read the article

  • php file force download

    - by droidus
    When I use this code to download this image (only used for testing purposes), I open the downloaded image, and all it gives me is an error. i tried it in chrome. opening it with windows photo viewer, it says that it can't display the picture because it is empty??? here is the code: <?PHP // Define the path to file $file = 'http://www.media.lonelyplanet.com/lpi/12553/12553-11/469x264.jpg'; if(!file) { // File doesn't exist, output error die('file not found'); } else { header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename='.basename($file)); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Content-Length: ' . filesize($file)); ob_clean(); flush(); readfile($file); exit; } ?>

    Read the article

  • Delay after pressing a button

    - by KrLx_roller
    After I press a button, Android parse a JSON file and pick the info it needs. Until yesterday, I was using an external library created by a user and it worked perfectly. But now, I don't want to depend on him, so I've searching info about Google's GSON. I've implemented this library with no problem, but now, after pressing the button that opens a new activity there's a delay. This delay is due to the connection and parsing that are done before the activity shows. How can I force the app to wait the Internet connection until de Activity is shown? It's a lil bit uncomfortable because after pressing the button, it seems that the app has frozen, but after all data is loaded, the new activity appears. Thank you in advance!

    Read the article

  • .htaccess mod force extra characters

    - by user1090809
    I need to be able to write/post links on the web that look like 'mysite.com/?d=foo', and take the user to filepath '/foo.php'. Here is my htaccess: RewriteEngine on RewriteBase / RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}\.php -f RewriteRule ^([^/]+)/$ $1.php [L] RewriteRule ^([^/]+(/[^/]+)*)/$ /$1.php [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$ RewriteRule ^([^.]+[^/.])$ /$1/ [R=301,L,NC] Baically I need to "force" '/?d=' before the filename, kinda like I've already modded my htaccess to force a trailing slash. How do I need to reconstruct my htaccess to make that possible?

    Read the article

  • Force an indent in Python code for organizational purposes

    - by Vine
    Is there a way to force an indent in Python? I kind of want it for the sake of making the code look organized. As an example: # How it looks now class Bro: def __init__(self): self.head = 1 self.head.eye = 2 self.head.nose = 1 self.head.mouth = 1 self.neck = 1 self.torso = 1 # How it'd look ideally (indenting sub-variables of 'head') class Bro: def __init__(self): self.head = 1 self.head.eye = 2 self.head.nose = 1 self.head.mouth = 1 self.neck = 1 self.torso = 1 I imagine this is possible with some sort of workaround, yeah?

    Read the article

  • VB.NET: Force user to use the topmost form

    - by SiliconCelery
    I'm programming a Minesweeper clone in Visual Studio 2010, with VB.NET, as a Windows Form Application, and I'm having trouble with the Game Won and Game Lost forms. When I show those forms, I want the game form to still be visible, so that the player can see where the mines were, but I don't want the game form to be enabled until the Game Won or Game Lost form is closed. Exactly like Windows Minesweeper does when you win or lose. There aren't any obvious properties for this, as far as I can see, and I've had no luck Googling, I don't know what terms to search. Any help is appreciated, thanks.

    Read the article

  • Force Download Files Broken Headers wrong?

    - by Sinan
    if($_POST['mode']=="save") { $root = $_SERVER['DOCUMENT_ROOT']; $path = "/mcboeking/"; $path = $root.$path; $file_path = $_POST['path']; $file = $path.$file_path; if(!file_exists($file)) { die('file not found'); } else { header("Cache-Control: public"); header("Content-Description: File Transfer"); header('Content-Type: application/force-download'); header("Content-Disposition: attachment; filename=\"".basename($file)."\";" ); header("Content-Length: ".filesize($file)); readfile($file);}} As soon as i download the file and open it i get an error message. When i try to open a .doc i get the message : file structure is invalid. And when i try to open a jpg : This file can not be opened. It may be corrupt or a file format that Preview does not recognize. But when i download PDF files, they open without any problem. Can someone help me? P.s. i tried different headers including : header('Content-Type: application/octet-stream');

    Read the article

  • Using SocialCounter.NET with ASP.NET MVC

    - by DigiMortal
    I found small library called SocialCounter.NET that is able to display some data from popular social sites. Although it is possible to use widgets offered by social networks there are also scenarios when you don’t want or can’t use these JavaScript based widgets. In this posting I will show you how to use SocialCounter.NET. Start with downloading SocialCounter.NET. You can also use NuGet package manager to download SocialCounter.NET. Using SocialCounter.NET is very easy as you can see from this example view: @using SocialCounter.NET; @{      ViewBag.Title = "Home Page"; } <h2>Social</h2> <p>     Twitter followers: @Counter.GetTwitterFollowersCount("gpeipman")<br />     Facebook friends: @Counter.GetFacebookFriendsCount("gpeipman")<br />     Facebook likes: @Counter.GetFacebookLikes("http://www.eindhovenmetalmeeting.nl/")<br />     Delicious saves count: @Counter.GetDeliciousSaveCount("http://youreffectiveleadership.com/")<br /> </p> And the result is shown on image on right. You can use SocialCounter.NET by example on user profile pages and on your content pages where you want to show how many people have saved current page as bookmark. SocialCounter.NET supports also LinkedIn, RSS-feeds and Google Plus accounts. In future – I hope – they will add support for more social networks to their library.

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14 15 16 17  | Next Page >