Search Results

Search found 1544 results on 62 pages for 'weight'.

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

  • SQL to LINQ translating probem

    - by ognjenb
    I have problem with convertion this SQL statement to LINQ : SELECT a.Id, a.Name, a.ArtiklNumber, a.Notes, a.Weight, l.StartDate AS LastStartDate, l.LocationNameId, loc.Name AS CarrentLocation, a.Reserved FROM Accessories a LEFT OUTER JOIN Location l LEFT JOIN LocationName loc ON l.LocationNameId = loc.Id ON a.Id = (SELECT AccessoriesId FROM Location WHERE AccessoriesId = a.Id HAVING MAX(StartDate) = StartDate ) This is part of my translated code: testEntities6 accessoriesEntities = new testEntities6(); var max_StartDate = (from msd in accessoriesEntities.location from d in accessoriesEntities.device where msd.DeviceId == d.Id select msd.StartDate).Min(); var accessories_query = from accs in accessoriesEntities.accessories join l in accessoriesEntities.location on accs.Id equals l.AccessoriesId join loc in accessoriesEntities.locationname on l.LocationNameId equals loc.Id select new AccessoriesModel { //Accessories Id = accs.Id, Name = accs.Name, ArtiklNumber = accs.ArtiklNumber, Notes = accs.Notes, Weight = accs.Weight, Reserved = accs.Reserved, //Location LocationNameId = l.LocationNameId, StartDate = max_StartDate,//l.StartDate, //Locationname Loc_name = loc.Name };

    Read the article

  • JMS Step 4 - How to Create an 11g BPEL Process Which Writes a Message Based on an XML Schema to a JMS Queue

    - by John-Brown.Evans
    JMS Step 4 - How to Create an 11g BPEL Process Which Writes a Message Based on an XML Schema to a JMS Queue ol{margin:0;padding:0} .c11_4{vertical-align:top;width:129.8pt;border-style:solid;background-color:#f3f3f3;border-color:#000000;border-width:1pt;padding:5pt 5pt 5pt 5pt} .c9_4{vertical-align:top;width:207pt;border-style:solid;background-color:#f3f3f3;border-color:#000000;border-width:1pt;padding:5pt 5pt 5pt 5pt}.c14{vertical-align:top;width:207pt;border-style:solid;border-color:#000000;border-width:1pt;padding:5pt 5pt 5pt 5pt} .c17_4{vertical-align:top;width:129.8pt;border-style:solid;border-color:#000000;border-width:1pt;padding:5pt 5pt 5pt 5pt} .c7_4{vertical-align:top;width:130pt;border-style:solid;border-color:#000000;border-width:1pt;padding:0pt 5pt 0pt 5pt} .c19_4{vertical-align:top;width:468pt;border-style:solid;border-color:#000000;border-width:1pt;padding:5pt 5pt 5pt 5pt} .c22_4{background-color:#ffffff} .c20_4{list-style-type:disc;margin:0;padding:0} .c6_4{font-size:8pt;font-family:"Courier New"} .c24_4{color:inherit;text-decoration:inherit} .c23_4{color:#1155cc;text-decoration:underline} .c0_4{height:11pt;direction:ltr} .c10_4{font-size:10pt;font-family:"Courier New"} .c3_4{padding-left:0pt;margin-left:36pt} .c18_4{font-size:8pt} .c8_4{text-align:center} .c12_4{background-color:#ffff00} .c2_4{font-weight:bold} .c21_4{background-color:#00ff00} .c4_4{line-height:1.0} .c1_4{direction:ltr} .c15_4{background-color:#f3f3f3} .c13_4{font-family:"Courier New"} .c5_4{font-style:italic} .c16_4{border-collapse:collapse} .title{padding-top:24pt;line-height:1.15;text-align:left;color:#000000;font-size:36pt;font-family:"Arial";font-weight:bold;padding-bottom:6pt} .subtitle{padding-top:18pt;line-height:1.15;text-align:left;color:#666666;font-style:italic;font-size:24pt;font-family:"Georgia";padding-bottom:4pt} li{color:#000000;font-size:10pt;font-family:"Arial"} p{color:#000000;font-size:10pt;margin:0;font-family:"Arial"} h1{padding-top:0pt;line-height:1.15;text-align:left;color:#888;font-size:18pt;font-family:"Arial";font-weight:normal;padding-bottom:0pt} h2{padding-top:0pt;line-height:1.15;text-align:left;color:#888;font-size:18pt;font-family:"Arial";font-weight:bold;padding-bottom:0pt} h3{padding-top:0pt;line-height:1.15;text-align:left;color:#888;font-size:14pt;font-family:"Arial";font-weight:normal;padding-bottom:0pt} h4{padding-top:0pt;line-height:1.15;text-align:left;color:#888;font-style:italic;font-size:11pt;font-family:"Arial";padding-bottom:0pt} h5{padding-top:0pt;line-height:1.15;text-align:left;color:#888;font-size:10pt;font-family:"Arial";font-weight:normal;padding-bottom:0pt} h6{padding-top:0pt;line-height:1.15;text-align:left;color:#888;font-style:italic;font-size:10pt;font-family:"Arial";padding-bottom:0pt} This post continues the series of JMS articles which demonstrate how to use JMS queues in a SOA context. The previous posts were: JMS Step 1 - How to Create a Simple JMS Queue in Weblogic Server 11g JMS Step 2 - Using the QueueSend.java Sample Program to Send a Message to a JMS Queue JMS Step 3 - Using the QueueReceive.java Sample Program to Read a Message from a JMS Queue In this example we will create a BPEL process which will write (enqueue) a message to a JMS queue using a JMS adapter. The JMS adapter will enqueue the full XML payload to the queue. This sample will use the following WebLogic Server objects. The first two, the Connection Factory and JMS Queue, were created as part of the first blog post in this series, JMS Step 1 - How to Create a Simple JMS Queue in Weblogic Server 11g. If you haven't created those objects yet, please see that post for details on how to do so. The Connection Pool will be created as part of this example. Object Name Type JNDI Name TestConnectionFactory Connection Factory jms/TestConnectionFactory TestJMSQueue JMS Queue jms/TestJMSQueue eis/wls/TestQueue Connection Pool eis/wls/TestQueue 1. Verify Connection Factory and JMS Queue As mentioned above, this example uses a WLS Connection Factory called TestConnectionFactory and a JMS queue TestJMSQueue. As these are prerequisites for this example, let us verify they exist. Log in to the WebLogic Server Administration Console. Select Services > JMS Modules > TestJMSModule You should see the following objects: If not, or if the TestJMSModule is missing, please see the abovementioned article and create these objects before continuing. 2. Create a JMS Adapter Connection Pool in WebLogic Server The BPEL process we are about to create uses a JMS adapter to write to the JMS queue. The JMS adapter is deployed to the WebLogic server and needs to be configured to include a connection pool which references the connection factory associated with the JMS queue. In the WebLogic Server Console Go to Deployments > Next and select (click on) the JmsAdapter Select Configuration > Outbound Connection Pools and expand oracle.tip.adapter.jms.IJmsConnectionFactory. This will display the list of connections configured for this adapter. For example, eis/aqjms/Queue, eis/aqjms/Topic etc. These JNDI names are actually quite confusing. We are expecting to configure a connection pool here, but the names refer to queues and topics. One would expect these to be called *ConnectionPool or *_CF or similar, but to conform to this nomenclature, we will call our entry eis/wls/TestQueue . This JNDI name is also the name we will use later, when creating a BPEL process to access this JMS queue! Select New, check the oracle.tip.adapter.jms.IJmsConnectionFactory check box and Next. Enter JNDI Name: eis/wls/TestQueue for the connection instance, then press Finish. Expand oracle.tip.adapter.jms.IJmsConnectionFactory again and select (click on) eis/wls/TestQueue The ConnectionFactoryLocation must point to the JNDI name of the connection factory associated with the JMS queue you will be writing to. In our example, this is the connection factory called TestConnectionFactory, with the JNDI name jms/TestConnectionFactory.( As a reminder, this connection factory is contained in the JMS Module called TestJMSModule, under Services > Messaging > JMS Modules > TestJMSModule which we verified at the beginning of this document. )Enter jms/TestConnectionFactory  into the Property Value field for Connection Factory Location. After entering it, you must press Return/Enter then Save for the value to be accepted. If your WebLogic server is running in Development mode, you should see the message that the changes have been activated and the deployment plan successfully updated. If not, then you will manually need to activate the changes in the WebLogic server console. Although the changes have been activated, the JmsAdapter needs to be redeployed in order for the changes to become effective. This should be confirmed by the message Remember to update your deployment to reflect the new plan when you are finished with your changes as can be seen in the following screen shot: The next step is to redeploy the JmsAdapter.Navigate back to the Deployments screen, either by selecting it in the left-hand navigation tree or by selecting the “Summary of Deployments” link in the breadcrumbs list at the top of the screen. Then select the checkbox next to JmsAdapter and press the Update button On the Update Application Assistant page, select “Redeploy this application using the following deployment files” and press Finish. After a few seconds you should get the message that the selected deployments were updated. The JMS adapter configuration is complete and it can now be used to access the JMS queue. To summarize: we have created a JMS adapter connection pool connector with the JNDI name jms/TestConnectionFactory. This is the JNDI name to be accessed by a process such as a BPEL process, when using the JMS adapter to access the previously created JMS queue with the JNDI name jms/TestJMSQueue. In the following step, we will set up a BPEL process to use this JMS adapter to write to the JMS queue. 3. Create a BPEL Composite with a JMS Adapter Partner Link This step requires that you have a valid Application Server Connection defined in JDeveloper, pointing to the application server on which you created the JMS Queue and Connection Factory. You can create this connection in JDeveloper under the Application Server Navigator. Give it any name and be sure to test the connection before completing it. This sample will use the connection name jbevans-lx-PS5, as that is the name of the connection pointing to my SOA PS5 installation. When using a JMS adapter from within a BPEL process, there are various configuration options, such as the operation type (consume message, produce message etc.), delivery mode and message type. One of these options is the choice of the format of the JMS message payload. This can be structured around an existing XSD, in which case the full XML element and tags are passed, or it can be opaque, meaning that the payload is sent as-is to the JMS adapter. In the case of an XSD-based message, the payload can simply be copied to the input variable of the JMS adapter. In the case of an opaque message, the JMS adapter’s input variable is of type base64binary. So the payload needs to be converted to base64 binary first. I will go into this in more detail in a later blog entry. This sample will pass a simple message to the adapter, based on the following simple XSD file, which consists of a single string element: stringPayload.xsd <?xml version="1.0" encoding="windows-1252" ?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.example.org" targetNamespace="http://www.example.org" elementFormDefault="qualified" <xsd:element name="exampleElement" type="xsd:string"> </xsd:element> </xsd:schema> The following steps are all executed in JDeveloper. The SOA project will be created inside a JDeveloper Application. If you do not already have an application to contain the project, you can create a new one via File > New > General > Generic Application. Give the application any name, for example JMSTests and, when prompted for a project name and type, call the project JmsAdapterWriteWithXsd and select SOA as the project technology type. If you already have an application, continue below. Create a SOA Project Create a new project and choose SOA Tier > SOA Project as its type. Name it JmsAdapterWriteSchema. When prompted for the composite type, choose Composite With BPEL Process. When prompted for the BPEL Process, name it JmsAdapterWriteSchema too and choose Synchronous BPEL Process as the template. This will create a composite with a BPEL process and an exposed SOAP service. Double-click the BPEL process to open and begin editing it. You should see a simple BPEL process with a Receive and Reply activity. As we created a default process without an XML schema, the input and output variables are simple strings. Create an XSD File An XSD file is required later to define the message format to be passed to the JMS adapter. In this step, we create a simple XSD file, containing a string variable and add it to the project. First select the xsd item in the left-hand navigation tree to ensure that the XSD file is created under that item. Select File > New > General > XML and choose XML Schema. Call it stringPayload.xsd and when the editor opens, select the Source view. then replace the contents with the contents of the stringPayload.xsd example above and save the file. You should see it under the xsd item in the navigation tree. Create a JMS Adapter Partner Link We will create the JMS adapter as a service at the composite level. If it is not already open, double-click the composite.xml file in the navigator to open it. From the Component Palette, drag a JMS adapter over onto the right-hand swim lane, under External References. This will start the JMS Adapter Configuration Wizard. Use the following entries: Service Name: JmsAdapterWrite Oracle Enterprise Messaging Service (OEMS): Oracle Weblogic JMS AppServer Connection: Use an existing application server connection pointing to the WebLogic server on which the above JMS queue and connection factory were created. You can use the “+” button to create a connection directly from the wizard, if you do not already have one. This example uses a connection called jbevans-lx-PS5. Adapter Interface > Interface: Define from operation and schema (specified later) Operation Type: Produce Message Operation Name: Produce_message Destination Name: Press the Browse button, select Destination Type: Queues, then press Search. Wait for the list to populate, then select the entry for TestJMSQueue , which is the queue created earlier. JNDI Name: The JNDI name to use for the JMS connection. This is probably the most important step in this exercise and the most common source of error. This is the JNDI name of the JMS adapter’s connection pool created in the WebLogic Server and which points to the connection factory. JDeveloper does not verify the value entered here. If you enter a wrong value, the JMS adapter won’t find the queue and you will get an error message at runtime, which is very difficult to trace. In our example, this is the value eis/wls/TestQueue . (See the earlier step on how to create a JMS Adapter Connection Pool in WebLogic Server for details.) MessagesURL: We will use the XSD file we created earlier, stringPayload.xsd to define the message format for the JMS adapter. Press the magnifying glass icon to search for schema files. Expand Project Schema Files > stringPayload.xsd and select exampleElement: string. Press Next and Finish, which will complete the JMS Adapter configuration. Wire the BPEL Component to the JMS Adapter In this step, we link the BPEL process/component to the JMS adapter. From the composite.xml editor, drag the right-arrow icon from the BPEL process to the JMS adapter’s in-arrow. This completes the steps at the composite level. 4. Complete the BPEL Process Design Invoke the JMS Adapter Open the BPEL component by double-clicking it in the design view of the composite.xml, or open it from the project navigator by selecting the JmsAdapterWriteSchema.bpel file. This will display the BPEL process in the design view. You should see the JmsAdapterWrite partner link under one of the two swim lanes. We want it in the right-hand swim lane. If JDeveloper displays it in the left-hand lane, right-click it and choose Display > Move To Opposite Swim Lane. An Invoke activity is required in order to invoke the JMS adapter. Drag an Invoke activity between the Receive and Reply activities. Drag the right-hand arrow from the Invoke activity to the JMS adapter partner link. This will open the Invoke editor. The correct default values are entered automatically and are fine for our purposes. We only need to define the input variable to use for the JMS adapter. By pressing the green “+” symbol, a variable of the correct type can be auto-generated, for example with the name Invoke1_Produce_Message_InputVariable. Press OK after creating the variable. ( For some reason, while I was testing this, the JMS Adapter moved back to the left-hand swim lane again after this step. There is no harm in leaving it there, but I find it easier to follow if it is in the right-hand lane, because I kind-of think of the message coming in on the left and being routed through the right. But you can follow your personal preference here.) Assign Variables Drag an Assign activity between the Receive and Invoke activities. We will simply copy the input variable to the JMS adapter and, for completion, so the process has an output to print, again to the process’s output variable. Double-click the Assign activity and create two Copy rules: for the first, drag Variables > inputVariable > payload > client:process > client:input_string to Invoke1_Produce_Message_InputVariable > body > ns2:exampleElement for the second, drag the same input variable to outputVariable > payload > client:processResponse > client:result This will create two copy rules, similar to the following: Press OK. This completes the BPEL and Composite design. 5. Compile and Deploy the Composite We won’t go into too much detail on how to compile and deploy. In JDeveloper, compile the process by pressing the Make or Rebuild icons or by right-clicking the project name in the navigator and selecting Make... or Rebuild... If the compilation is successful, deploy it to the SOA server connection defined earlier. (Right-click the project name in the navigator, select Deploy to Application Server, choose the application server connection, choose the partition on the server (usually default) and press Finish. You should see the message ---- Deployment finished. ---- in the Deployment frame, if the deployment was successful. 6. Test the Composite This is the exciting part. Open two tabs in your browser and log in to the WebLogic Administration Console in one tab and the Enterprise Manager 11g Fusion Middleware Control (EM) for your SOA installation in the other. We will use the Console to monitor the messages being written to the queue and the EM to execute the composite. In the Console, go to Services > Messaging > JMS Modules > TestJMSModule > TestJMSQueue > Monitoring. Note the number of messages under Messages Current. In the EM, go to SOA > soa-infra (soa_server1) > default (or wherever you deployed your composite to) and click on JmsAdapterWriteSchema [1.0], then press the Test button. Under Input Arguments, enter any string into the text input field for the payload, for example Test Message then press Test Web Service. If the instance is successful you should see the same text in the Response message, “Test Message”. In the Console, refresh the Monitoring screen to confirm a new message has been written to the queue. Check the checkbox and press Show Messages. Click on the newest message and view its contents. They should include the full XML of the entered payload. 7. Troubleshooting If you get an exception similar to the following at runtime ... BINDING.JCA-12510 JCA Resource Adapter location error. Unable to locate the JCA Resource Adapter via .jca binding file element The JCA Binding Component is unable to startup the Resource Adapter specified in the element: location='eis/wls/QueueTest'. The reason for this is most likely that either 1) the Resource Adapters RAR file has not been deployed successfully to the WebLogic Application server or 2) the '' element in weblogic-ra.xml has not been set to eis/wls/QueueTest. In the last case you will have to add a new WebLogic JCA connection factory (deploy a RAR). Please correct this and then restart the Application Server at oracle.integration.platform.blocks.adapter.fw.AdapterBindingException. createJndiLookupException(AdapterBindingException.java:130) at oracle.integration.platform.blocks.adapter.fw.jca.cci. JCAConnectionManager$JCAConnectionPool.createJCAConnectionFactory (JCAConnectionManager.java:1387) at oracle.integration.platform.blocks.adapter.fw.jca.cci. JCAConnectionManager$JCAConnectionPool.newPoolObject (JCAConnectionManager.java:1285) ... then this is very likely due to an incorrect JNDI name entered for the JMS Connection in the JMS Adapter Wizard. Recheck those steps. The error message prints the name of the JNDI name used. In this example, it was incorrectly entered as eis/wls/QueueTest instead of eis/wls/TestQueue. This concludes this example. Best regards John-Brown Evans Oracle Technology Proactive Support Delivery

    Read the article

  • C# Neural Networks with Encog

    - by JoshReuben
    Neural Networks ·       I recently read a book Introduction to Neural Networks for C# , by Jeff Heaton. http://www.amazon.com/Introduction-Neural-Networks-C-2nd/dp/1604390093/ref=sr_1_2?ie=UTF8&s=books&qid=1296821004&sr=8-2-spell. Not the 1st ANN book I've perused, but a nice revision.   ·       Artificial Neural Networks (ANNs) are a mechanism of machine learning – see http://en.wikipedia.org/wiki/Artificial_neural_network , http://en.wikipedia.org/wiki/Category:Machine_learning ·       Problems Not Suited to a Neural Network Solution- Programs that are easily written out as flowcharts consisting of well-defined steps, program logic that is unlikely to change, problems in which you must know exactly how the solution was derived. ·       Problems Suited to a Neural Network – pattern recognition, classification, series prediction, and data mining. Pattern recognition - network attempts to determine if the input data matches a pattern that it has been trained to recognize. Classification - take input samples and classify them into fuzzy groups. ·       As far as machine learning approaches go, I thing SVMs are superior (see http://en.wikipedia.org/wiki/Support_vector_machine ) - a neural network has certain disadvantages in comparison: an ANN can be overtrained, different training sets can produce non-deterministic weights and it is not possible to discern the underlying decision function of an ANN from its weight matrix – they are black box. ·       In this post, I'm not going to go into internals (believe me I know them). An autoassociative network (e.g. a Hopfield network) will echo back a pattern if it is recognized. ·       Under the hood, there is very little maths. In a nutshell - Some simple matrix operations occur during training: the input array is processed (normalized into bipolar values of 1, -1) - transposed from input column vector into a row vector, these are subject to matrix multiplication and then subtraction of the identity matrix to get a contribution matrix. The dot product is taken against the weight matrix to yield a boolean match result. For backpropogation training, a derivative function is required. In learning, hill climbing mechanisms such as Genetic Algorithms and Simulated Annealing are used to escape local minima. For unsupervised training, such as found in Self Organizing Maps used for OCR, Hebbs rule is applied. ·       The purpose of this post is not to mire you in technical and conceptual details, but to show you how to leverage neural networks via an abstraction API - Encog   Encog ·       Encog is a neural network API ·       Links to Encog: http://www.encog.org , http://www.heatonresearch.com/encog, http://www.heatonresearch.com/forum ·       Encog requires .Net 3.5 or higher – there is also a Silverlight version. Third-Party Libraries – log4net and nunit. ·       Encog supports feedforward, recurrent, self-organizing maps, radial basis function and Hopfield neural networks. ·       Encog neural networks, and related data, can be stored in .EG XML files. ·       Encog Workbench allows you to edit, train and visualize neural networks. The Encog Workbench can generate code. Synapses and layers ·       the primary building blocks - Almost every neural network will have, at a minimum, an input and output layer. In some cases, the same layer will function as both input and output layer. ·       To adapt a problem to a neural network, you must determine how to feed the problem into the input layer of a neural network, and receive the solution through the output layer of a neural network. ·       The Input Layer - For each input neuron, one double value is stored. An array is passed as input to a layer. Encog uses the interface INeuralData to hold these arrays. The class BasicNeuralData implements the INeuralData interface. Once the neural network processes the input, an INeuralData based class will be returned from the neural network's output layer. ·       convert a double array into an INeuralData object : INeuralData data = new BasicNeuralData(= new double[10]); ·       the Output Layer- The neural network outputs an array of doubles, wraped in a class based on the INeuralData interface. ·        The real power of a neural network comes from its pattern recognition capabilities. The neural network should be able to produce the desired output even if the input has been slightly distorted. ·       Hidden Layers– optional. between the input and output layers. very much a “black box”. If the structure of the hidden layer is too simple it may not learn the problem. If the structure is too complex, it will learn the problem but will be very slow to train and execute. Some neural networks have no hidden layers. The input layer may be directly connected to the output layer. Further, some neural networks have only a single layer. A single layer neural network has the single layer self-connected. ·       connections, called synapses, contain individual weight matrixes. These values are changed as the neural network learns. Constructing a Neural Network ·       the XOR operator is a frequent “first example” -the “Hello World” application for neural networks. ·       The XOR Operator- only returns true when both inputs differ. 0 XOR 0 = 0 1 XOR 0 = 1 0 XOR 1 = 1 1 XOR 1 = 0 ·       Structuring a Neural Network for XOR  - two inputs to the XOR operator and one output. ·       input: 0.0,0.0 1.0,0.0 0.0,1.0 1.0,1.0 ·       Expected output: 0.0 1.0 1.0 0.0 ·       A Perceptron - a simple feedforward neural network to learn the XOR operator. ·       Because the XOR operator has two inputs and one output, the neural network will follow suit. Additionally, the neural network will have a single hidden layer, with two neurons to help process the data. The choice for 2 neurons in the hidden layer is arbitrary, and often comes down to trial and error. ·       Neuron Diagram for the XOR Network ·       ·       The Encog workbench displays neural networks on a layer-by-layer basis. ·       Encog Layer Diagram for the XOR Network:   ·       Create a BasicNetwork - Three layers are added to this network. the FinalizeStructure method must be called to inform the network that no more layers are to be added. The call to Reset randomizes the weights in the connections between these layers. var network = new BasicNetwork(); network.AddLayer(new BasicLayer(2)); network.AddLayer(new BasicLayer(2)); network.AddLayer(new BasicLayer(1)); network.Structure.FinalizeStructure(); network.Reset(); ·       Neural networks frequently start with a random weight matrix. This provides a starting point for the training methods. These random values will be tested and refined into an acceptable solution. However, sometimes the initial random values are too far off. Sometimes it may be necessary to reset the weights again, if training is ineffective. These weights make up the long-term memory of the neural network. Additionally, some layers have threshold values that also contribute to the long-term memory of the neural network. Some neural networks also contain context layers, which give the neural network a short-term memory as well. The neural network learns by modifying these weight and threshold values. ·       Now that the neural network has been created, it must be trained. Training a Neural Network ·       construct a INeuralDataSet object - contains the input array and the expected output array (of corresponding range). Even though there is only one output value, we must still use a two-dimensional array to represent the output. public static double[][] XOR_INPUT ={ new double[2] { 0.0, 0.0 }, new double[2] { 1.0, 0.0 }, new double[2] { 0.0, 1.0 }, new double[2] { 1.0, 1.0 } };   public static double[][] XOR_IDEAL = { new double[1] { 0.0 }, new double[1] { 1.0 }, new double[1] { 1.0 }, new double[1] { 0.0 } };   INeuralDataSet trainingSet = new BasicNeuralDataSet(XOR_INPUT, XOR_IDEAL); ·       Training is the process where the neural network's weights are adjusted to better produce the expected output. Training will continue for many iterations, until the error rate of the network is below an acceptable level. Encog supports many different types of training. Resilient Propagation (RPROP) - general-purpose training algorithm. All training classes implement the ITrain interface. The RPROP algorithm is implemented by the ResilientPropagation class. Training the neural network involves calling the Iteration method on the ITrain class until the error is below a specific value. The code loops through as many iterations, or epochs, as it takes to get the error rate for the neural network to be below 1%. Once the neural network has been trained, it is ready for use. ITrain train = new ResilientPropagation(network, trainingSet);   for (int epoch=0; epoch < 10000; epoch++) { train.Iteration(); Debug.Print("Epoch #" + epoch + " Error:" + train.Error); if (train.Error > 0.01) break; } Executing a Neural Network ·       Call the Compute method on the BasicNetwork class. Console.WriteLine("Neural Network Results:"); foreach (INeuralDataPair pair in trainingSet) { INeuralData output = network.Compute(pair.Input); Console.WriteLine(pair.Input[0] + "," + pair.Input[1] + ", actual=" + output[0] + ",ideal=" + pair.Ideal[0]); } ·       The Compute method accepts an INeuralData class and also returns a INeuralData object. Neural Network Results: 0.0,0.0, actual=0.002782538818034049,ideal=0.0 1.0,0.0, actual=0.9903741937121177,ideal=1.0 0.0,1.0, actual=0.9836807956566187,ideal=1.0 1.0,1.0, actual=0.0011646072586172778,ideal=0.0 ·       the network has not been trained to give the exact results. This is normal. Because the network was trained to 1% error, each of the results will also be within generally 1% of the expected value.

    Read the article

  • Determine arc-length of a Catmull-Rom spline

    - by Wouter
    I have a path that is defined by a concatenation of Catmull-Rom splines. I use the static method Vector2.CatmullRom in XNA that allows for interpolation between points with a value going from 0 to 1. Not every spline in this path has the same length. This causes speed differences if I let the weight go at a constant speed for every spline while proceeding along the path. I can remedy this by letting the speed of the weight be dependent on the length of the spline. How can I determine the length of such a spline? Should I just approximate by cutting the spline into 10 straight lines and sum their lengths? I'm using this for dynamic texture mapping on a generated mesh defined by splines.

    Read the article

  • How to speed up this simple mysql query?

    - by Jim Thio
    The query is simple: SELECT TB.ID, TB.Latitude, TB.Longitude, 111151.29341326*SQRT(pow(-6.185-TB.Latitude,2)+pow(106.773-TB.Longitude,2)*cos(-6.185*0.017453292519943)*cos(TB.Latitude*0.017453292519943)) AS Distance FROM `tablebusiness` AS TB WHERE -6.2767668133836 < TB.Latitude AND TB.Latitude < -6.0932331866164 AND FoursquarePeopleCount >5 AND 106.68123318662 < TB.Longitude AND TB.Longitude <106.86476681338 ORDER BY Distance See, we just look at all business within a rectangle. 1.6 million rows. Within that small rectangle there are only 67,565 businesses. The structure of the table is 1 ID varchar(250) utf8_unicode_ci No None Change Change Drop Drop More Show more actions 2 Email varchar(400) utf8_unicode_ci Yes NULL Change Change Drop Drop More Show more actions 3 InBuildingAddress varchar(400) utf8_unicode_ci Yes NULL Change Change Drop Drop More Show more actions 4 Price int(10) Yes NULL Change Change Drop Drop More Show more actions 5 Street varchar(400) utf8_unicode_ci Yes NULL Change Change Drop Drop More Show more actions 6 Title varchar(400) utf8_unicode_ci Yes NULL Change Change Drop Drop More Show more actions 7 Website varchar(400) utf8_unicode_ci Yes NULL Change Change Drop Drop More Show more actions 8 Zip varchar(400) utf8_unicode_ci Yes NULL Change Change Drop Drop More Show more actions 9 Rating Star double Yes NULL Change Change Drop Drop More Show more actions 10 Rating Weight double Yes NULL Change Change Drop Drop More Show more actions 11 Latitude double Yes NULL Change Change Drop Drop More Show more actions 12 Longitude double Yes NULL Change Change Drop Drop More Show more actions 13 Building varchar(200) utf8_unicode_ci Yes NULL Change Change Drop Drop More Show more actions 14 City varchar(100) utf8_unicode_ci No None Change Change Drop Drop More Show more actions 15 OpeningHour varchar(400) utf8_unicode_ci Yes NULL Change Change Drop Drop More Show more actions 16 TimeStamp timestamp on update CURRENT_TIMESTAMP No CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP Change Change Drop Drop More Show more actions 17 CountViews int(11) Yes NULL Change Change Drop Drop More Show more actions The indexes are: Edit Edit Drop Drop PRIMARY BTREE Yes No ID 1965990 A Edit Edit Drop Drop City BTREE No No City 131066 A Edit Edit Drop Drop Building BTREE No No Building 21 A YES Edit Edit Drop Drop OpeningHour BTREE No No OpeningHour (255) 21 A YES Edit Edit Drop Drop Email BTREE No No Email (255) 21 A YES Edit Edit Drop Drop InBuildingAddress BTREE No No InBuildingAddress (255) 21 A YES Edit Edit Drop Drop Price BTREE No No Price 21 A YES Edit Edit Drop Drop Street BTREE No No Street (255) 982995 A YES Edit Edit Drop Drop Title BTREE No No Title (255) 1965990 A YES Edit Edit Drop Drop Website BTREE No No Website (255) 491497 A YES Edit Edit Drop Drop Zip BTREE No No Zip (255) 178726 A YES Edit Edit Drop Drop Rating Star BTREE No No Rating Star 21 A YES Edit Edit Drop Drop Rating Weight BTREE No No Rating Weight 21 A YES Edit Edit Drop Drop Latitude BTREE No No Latitude 1965990 A YES Edit Edit Drop Drop Longitude BTREE No No Longitude 1965990 A YES The query took forever. I think there has to be something wrong there. Showing rows 0 - 29 ( 67,565 total, Query took 12.4767 sec)

    Read the article

  • are keywords in URLs good SEO or needlessly redundant?

    - by Blazemonger
    A coworker and I are locked in a debate over the value of SEO keywords in the URL of a page. She wants to change all the filenames of the HTML pages of a fencing company so they look like residential-home-chicago.html, contact-chicago-contractor.html, and so on. She is convinced that because Google highlights keywords in URLS in search results, that means that putting keywords here is more valuable. My position is that these do not improve SEO, since Google doesn't seem to give keywords in the URL any more weight than keywords in the body of the page, and might even give them less weight. In the meantime, they make it harder for me to find the pages I want when its time to edit them, and the site as a whole looks cheap and spammy. Google's own SEO guide suggests to me that yes, keywords in URLs are useful, but not superior, and that they are more useful for human readability than search engine rankings. I'm looking for authoritative sources that support either position, not blog articles from SEO optimization companies trying to promote themselves.

    Read the article

  • Weighted round robins via TTL - possible?

    - by Joe Hopfgartner
    I currently use DNS round robin for load balancing, which works great. The records look like this (I have a ttl of 120 seconds) ;; ANSWER SECTION: orion.2x.to. 116 IN A 80.237.201.41 orion.2x.to. 116 IN A 87.230.54.12 orion.2x.to. 116 IN A 87.230.100.10 orion.2x.to. 116 IN A 87.230.51.65 I learned that not every ISP / device treats such a response the same way. For example some DNS servers rotate the addresses randomly or always cycle them through. Some just propagate the first entry, others try to determine which is best (regionally near) by looking at the ip address. However if the userbase is big enough (spreads over multiple ISPs etc) it balances pretty well. The discrepancies from highest to lowest loaded server hardly every exceeds 15%. However now I have the problem that I am introducing more servers into the systems, that not all have the same capacities. I currently only have 1gbps servers, but I want to work with 100mbit and also 10gbps servers too. So what I want is I want to introduce a server with 10 GBps with a weight of 100, a 1 gbps server with a weight of 10 and a 100 mbit server with a weight of 1. I used to add servers twice to bring more traffic to them (which worked nice. the bandwidth doubled almost.) But adding a 10gbit server 100 times to DNS is a bit rediculous. So I thought about using the TTL. If I give server A 240 seconds ttl and server B only 120 seconds (which is about about the minimum to use for round robin, as a lot of dns servers set to 120 if a lower ttl is specified.. so i have heard) I think something like this should occour in an ideal scenario: first 120 seconds 50% of requests get server A -> keep it for 240 seconds. 50% of requests get server B -> keep it for 120 seconds second 120 seconds 50% of requests still have server A cached -> keep it for another 120 seconds. 25% of requests get server A -> keep it for 240 seconds 25% of requests get server B -> keep it for 120 seconds third 120 seconds 25% will get server A (from the 50% of Server A that now expired) -> cache 240 sec 25% will get server B (from the 50% of Server A that now expired) -> cache 120 sec 25% will have server A cached for another 120 seconds 12.5% will get server B (from the 25% of server B that now expired) -> cache 120sec 12.5% will get server A (from the 25% of server B that now expired) -> cache 240 sec fourth 120 seconds 25% will have server A cached -> cache for another 120 secs 12.5% will get server A (from the 25% of b that now expired) -> cache 240 secs 12.5% will get server B (from the 25% of b that now expired) -> cache 120 secs 12.5% will get server A (from the 25% of a that now expired) -> cache 240 secs 12.5% will get server B (from the 25% of a that now expired) -> cache 120 secs 6.25% will get server A (from the 12.5% of b that now expired) -> cache 240 secs 6.25% will get server B (from the 12.5% of b that now expired) -> cache 120 secs 12.5% will have server A cached -> cache another 120 secs ... i think i lost something at this point but i think you get the idea.... As you can see this gets pretty complicated to predict and it will for sure not work out like this in practice. But it should definitely have an effect on the distribution! I know that weighted round robin exists and is just controlled by the root server. It just cycles through dns records when responding and returns dns records with a set propability that corresponds to the weighting. My DNS server does not support this, and my requirements are not that precise. If it doesnt weight perfectly its okay, but it should go into the right direction. I think using the TTL field could be a more elegant and easier solution - and it deosnt require a dns server that controls this dynamically, which saves resources - which is in my opinion the whole point of dns load balancing vs hardware load balancers. My question now is... are there any best prectices / methos / rules of thumb to weight round robin distribution using the TTL attribute of DNS records? Edit: The system is a forward proxy server system. The amount of Bandwidth (not requests) exceeds what one single server with ethernet can handle. So I need a balancing solution that distributes the bandwidth to several servers. Are there any alternative methods than using DNS? Of course I can use a load balancer with fibre channel etc, but the costs are rediciulous and it also increases only the width of the bottleneck and does not eliminate it. The only thing i can think of are anycast (is it anycast or multicast?) ip addresses, but I don't have the means to set up such a system.

    Read the article

  • sorting dynamic table created by form inputs [migrated]

    - by mille
    i am having problems with sorting can someone help to sort this table not just by its form entry id but onclick with some other columns i tried a lot of plugins but cant get anything to work and i dont know what to do i am new at this i sorry for my english thanks. here is the js: var Animals ={ index: window.localStorage.getItem("Animals:index"), $table: document.getElementById("animals-table"), $form: document.getElementById("animals-form"), $button_save: document.getElementById("animals-save"), $button_discard: document.getElementById("animals-discard"), init: function() { if (!Animals.index) { window.localStorage.setItem("Animals:index", Animals.index = 1); } Animals.$form.reset(); Animals.$button_discard.addEventListener("click", function(event) { Animals.$form.reset(); Animals.$form.id_entry.value = 0; }, true); Animals.$form.addEventListener("submit", function(event) { var entry = { id: parseInt(this.id_entry.value), animal_id:this.animal_id.value, animal_name: this.animal_name.value, animal_type: this.animal_type.value, bday: this.bday.value, animal_sex: this.animal_sex.value, mother_name: this.mother_name.value, farm_name: this.farm_name.value, money: this.money.value, weight: this.weight.value, purchase_partner: this.purchase_partner.value }; if (entry.id === 0) { Animals.storeAdd(entry); Animals.tableAdd(entry); } else { // edit Animals.storeEdit(entry); Animals.tableEdit(entry); } this.reset(); this.id_entry.value = 0; event.preventDefault(); }, true); if (window.localStorage.length - 1) { var animals_list = [], i, key; for (i = 0; i < window.localStorage.length; i++) { key = window.localStorage.key(i); if (/Animals:\d+/.test(key)) { animals_list.push(JSON.parse(window.localStorage.getItem(key))); } } if (animals_list.length) { animals_list.sort(function(a, b) {return a.id < b.id ? -1 : (a.id > b.id ? 1 : 0);}) .forEach(Animals.tableAdd);} Animals.$table.addEventListener("click", function(event) { var op = event.target.getAttribute("data-op"); if (/edit|remove/.test(op)) { var entry = JSON.parse(window.localStorage.getItem("Animals:"+ event.target.getAttribute("data- id"))); if (op == "edit") { Animals.$form.id_entry.value = entry.id; Animals.$form.animal_id.value = entry.animal_id; Animals.$form.animal_name.value = entry.animal_name; Animals.$form.animal_type.value = entry.animal_type; Animals.$form.bday.value = entry.bday; Animals.$form.animal_sex.value = entry.animal_sex; Animals.$form.mother_name.value = entry.mother_name; Animals.$form.farm_name.value = entry.farm_name; Animals.$form.money.value = entry.money; Animals.$form.weight.value = entry.weight; Animals.$form.purchase_partner.value = entry.purchase_partner; } else if (op == "remove") { if (confirm('Are you sure you want to remove this animal from your list?' )) { Animals.storeRemove(entry); Animals.tableRemove(entry); } } event.preventDefault(); } }, true); }, storeAdd: function(entry) { entry.id = Animals.index; window.localStorage.setItem("Animals:index", ++Animals.index); window.localStorage.setItem("Animals:"+ entry.id, JSON.stringify(entry)); }, storeEdit: function(entry) { window.localStorage.setItem("Animals:"+ entry.id, JSON.stringify(entry)); }, storeRemove: function(entry) { window.localStorage.removeItem("Animals:"+ entry.id); }, tableAdd: function(entry) { var $tr = document.createElement("tr"), $td, key; for (key in entry) { if (entry.hasOwnProperty(key)) { $td = document.createElement("td"); $td.appendChild(document.createTextNode(entry[key])); $tr.appendChild($td); } } $td = document.createElement("td"); $td.innerHTML = '<a data-op="edit" data-id="'+ entry.id +'">Edit</a> | <a data-op="remove" data-id="'+ entry.id +'">Remove</a>'; $tr.appendChild($td); $tr.setAttribute("id", "entry-"+ entry.id); Animals.$table.appendChild($tr); }, tableEdit: function(entry) { var $tr = document.getElementById("entry-"+ entry.id), $td, key; $tr.innerHTML = ""; for (key in entry) { if (entry.hasOwnProperty(key)) { $td = document.createElement("td"); $td.appendChild(document.createTextNode(entry[key])); $tr.appendChild($td); } } $td = document.createElement("td"); $td.innerHTML = '<a data-op="edit" data-id="'+ entry.id +'">Edit</a> | <a data-op="remove" data-id="'+ entry.id +'">Remove</a>'; $tr.appendChild($td); }, tableRemove: function(entry) { Animals.$table.removeChild(document.getElementById("entry-"+ entry.id)); } }; Animals.init();

    Read the article

  • Ubuntu 14.04 Notification incorrectly displayed

    - by xenolyse
    I have a problem with my notifications on Ubuntu 14.04 x64. The notifications are just plain text with a colored background, and are also strangely placed in the top left corner. I have no idea on how it changed. After one reboot it was just there.. Here is a picture of the problem in question.: As you can see the notification appear over the unified menu. How can I restore the original state of the notification bubble? Here are the settings in ~/.notify-osd slot-allocation = fixed bubble-expire-timeout = 10sec bubble-vertical-gap = 5px bubble-horizontal-gap = 5px bubble-corner-radius = 37,5% bubble-icon-size = 30px bubble-gauge-size = 6px bubble-width = 240px bubble-background-color = 131313 bubble-background-opacity = 90% text-margin-size = 10px text-title-size = 100% text-title-weight = bold text-title-color = ffffff text-title-opacity = 100% text-body-size = 90% text-body-weight = normal text-body-color = eaeaea text-body-opacity = 100% text-shadow-opacity = 100% If I check the org.freedesktop.Notifications.service(/usr/share/dbus-1/servies) it appears to use the correct one. [D-BUS Service] Name=org.freedesktop.Notifications Exec=/usr/lib/x86_64-linux-gnu/notify-osd

    Read the article

  • How to read data from a large number of files in a folder? [closed]

    - by Gary Dhillon
    I seem to be having some trouble figuring out a solution for a problem. See the thing is, my code is supposed to read a lot of data from a bunch of files. I've been thinking of two different approaches: 1) the first one seems simpler, I ask the user if they would like to examine the next file or just quit out of the program.( I believe this is simpler and would take less time to run through.) 2)It reads through all the files and outputs the results for each of them, and then a shared result for all of them.( I think this would be better for what I've been asked to do and it saves the user some hassle.) If anyone can tell me how to code either of these in C++, I would be very grateful. Here is a sample of the file: 0 -- 19 weight 0 -- 20 weight I use this to determine density and possibly ignore the weights which is a number.

    Read the article

  • How can I estimate the entropy of a password?

    - by Wug
    Having read various resources about password strength I'm trying to create an algorithm that will provide a rough estimation of how much entropy a password has. I'm trying to create an algorithm that's as comprehensive as possible. At this point I only have pseudocode, but the algorithm covers the following: password length repeated characters patterns (logical) different character spaces (LC, UC, Numeric, Special, Extended) dictionary attacks It does NOT cover the following, and SHOULD cover it WELL (though not perfectly): ordering (passwords can be strictly ordered by output of this algorithm) patterns (spatial) Can anyone provide some insight on what this algorithm might be weak to? Specifically, can anyone think of situations where feeding a password to the algorithm would OVERESTIMATE its strength? Underestimations are less of an issue. The algorithm: // the password to test password = ? length = length(password) // unique character counts from password (duplicates discarded) uqlca = number of unique lowercase alphabetic characters in password uquca = number of uppercase alphabetic characters uqd = number of unique digits uqsp = number of unique special characters (anything with a key on the keyboard) uqxc = number of unique special special characters (alt codes, extended-ascii stuff) // algorithm parameters, total sizes of alphabet spaces Nlca = total possible number of lowercase letters (26) Nuca = total uppercase letters (26) Nd = total digits (10) Nsp = total special characters (32 or something) Nxc = total extended ascii characters that dont fit into other categorys (idk, 50?) // algorithm parameters, pw strength growth rates as percentages (per character) flca = entropy growth factor for lowercase letters (.25 is probably a good value) fuca = EGF for uppercase letters (.4 is probably good) fd = EGF for digits (.4 is probably good) fsp = EGF for special chars (.5 is probably good) fxc = EGF for extended ascii chars (.75 is probably good) // repetition factors. few unique letters == low factor, many unique == high rflca = (1 - (1 - flca) ^ uqlca) rfuca = (1 - (1 - fuca) ^ uquca) rfd = (1 - (1 - fd ) ^ uqd ) rfsp = (1 - (1 - fsp ) ^ uqsp ) rfxc = (1 - (1 - fxc ) ^ uqxc ) // digit strengths strength = ( rflca * Nlca + rfuca * Nuca + rfd * Nd + rfsp * Nsp + rfxc * Nxc ) ^ length entropybits = log_base_2(strength) A few inputs and their desired and actual entropy_bits outputs: INPUT DESIRED ACTUAL aaa very pathetic 8.1 aaaaaaaaa pathetic 24.7 abcdefghi weak 31.2 H0ley$Mol3y_ strong 72.2 s^fU¬5ü;y34G< wtf 88.9 [a^36]* pathetic 97.2 [a^20]A[a^15]* strong 146.8 xkcd1** medium 79.3 xkcd2** wtf 160.5 * these 2 passwords use shortened notation, where [a^N] expands to N a's. ** xkcd1 = "Tr0ub4dor&3", xkcd2 = "correct horse battery staple" The algorithm does realize (correctly) that increasing the alphabet size (even by one digit) vastly strengthens long passwords, as shown by the difference in entropy_bits for the 6th and 7th passwords, which both consist of 36 a's, but the second's 21st a is capitalized. However, they do not account for the fact that having a password of 36 a's is not a good idea, it's easily broken with a weak password cracker (and anyone who watches you type it will see it) and the algorithm doesn't reflect that. It does, however, reflect the fact that xkcd1 is a weak password compared to xkcd2, despite having greater complexity density (is this even a thing?). How can I improve this algorithm? Addendum 1 Dictionary attacks and pattern based attacks seem to be the big thing, so I'll take a stab at addressing those. I could perform a comprehensive search through the password for words from a word list and replace words with tokens unique to the words they represent. Word-tokens would then be treated as characters and have their own weight system, and would add their own weights to the password. I'd need a few new algorithm parameters (I'll call them lw, Nw ~= 2^11, fw ~= .5, and rfw) and I'd factor the weight into the password as I would any of the other weights. This word search could be specially modified to match both lowercase and uppercase letters as well as common character substitutions, like that of E with 3. If I didn't add extra weight to such matched words, the algorithm would underestimate their strength by a bit or two per word, which is OK. Otherwise, a general rule would be, for each non-perfect character match, give the word a bonus bit. I could then perform simple pattern checks, such as searches for runs of repeated characters and derivative tests (take the difference between each character), which would identify patterns such as 'aaaaa' and '12345', and replace each detected pattern with a pattern token, unique to the pattern and length. The algorithmic parameters (specifically, entropy per pattern) could be generated on the fly based on the pattern. At this point, I'd take the length of the password. Each word token and pattern token would count as one character; each token would replace the characters they symbolically represented. I made up some sort of pattern notation, but it includes the pattern length l, the pattern order o, and the base element b. This information could be used to compute some arbitrary weight for each pattern. I'd do something better in actual code. Modified Example: Password: 1234kitty$$$$$herpderp Tokenized: 1 2 3 4 k i t t y $ $ $ $ $ h e r p d e r p Words Filtered: 1 2 3 4 @W5783 $ $ $ $ $ @W9001 @W9002 Patterns Filtered: @P[l=4,o=1,b='1'] @W5783 @P[l=5,o=0,b='$'] @W9001 @W9002 Breakdown: 3 small, unique words and 2 patterns Entropy: about 45 bits, as per modified algorithm Password: correcthorsebatterystaple Tokenized: c o r r e c t h o r s e b a t t e r y s t a p l e Words Filtered: @W6783 @W7923 @W1535 @W2285 Breakdown: 4 small, unique words and no patterns Entropy: 43 bits, as per modified algorithm The exact semantics of how entropy is calculated from patterns is up for discussion. I was thinking something like: entropy(b) * l * (o + 1) // o will be either zero or one The modified algorithm would find flaws with and reduce the strength of each password in the original table, with the exception of s^fU¬5ü;y34G<, which contains no words or patterns.

    Read the article

  • Does anyone have a specific example of using the Flyweight Pattern?

    - by Jeremy E
    I have been studying design patterns and came accross the fly weight pattern. I have been trying to see opportunities to use the pattern in my applications but I am having trouble seeing how to use it. Also, what are some signs that a fly weight pattern is being used when I read other peoples code? According to the definition it says: Use sharing to support large numbers of fine-grained objects efficiently. If I read it right Dictionaries and Hashtables could be instances of fly weights is this correct? Thanks in advance.

    Read the article

  • Optimizing Python code with many attribute and dictionary lookups

    - by gotgenes
    I have written a program in Python which spends a large amount of time looking up attributes of objects and values from dictionary keys. I would like to know if there's any way I can optimize these lookup times, potentially with a C extension, to reduce the time of execution, or if I need to simply re-implement the program in a compiled language. The program implements some algorithms using a graph. It runs prohibitively slowly on our data sets, so I profiled the code with cProfile using a reduced data set that could actually complete. The vast majority of the time is being burned in one function, and specifically in two statements, generator expressions, within the function: The generator expression at line 202 is neighbors_in_selected_nodes = (neighbor for neighbor in node_neighbors if neighbor in selected_nodes) and the generator expression at line 204 is neighbor_z_scores = (interaction_graph.node[neighbor]['weight'] for neighbor in neighbors_in_selected_nodes) The source code for this function of context provided below. selected_nodes is a set of nodes in the interaction_graph, which is a NetworkX Graph instance. node_neighbors is an iterator from Graph.neighbors_iter(). Graph itself uses dictionaries for storing nodes and edges. Its Graph.node attribute is a dictionary which stores nodes and their attributes (e.g., 'weight') in dictionaries belonging to each node. Each of these lookups should be amortized constant time (i.e., O(1)), however, I am still paying a large penalty for the lookups. Is there some way which I can speed up these lookups (e.g., by writing parts of this as a C extension), or do I need to move the program to a compiled language? Below is the full source code for the function that provides the context; the vast majority of execution time is spent within this function. def calculate_node_z_prime( node, interaction_graph, selected_nodes ): """Calculates a z'-score for a given node. The z'-score is based on the z-scores (weights) of the neighbors of the given node, and proportional to the z-score (weight) of the given node. Specifically, we find the maximum z-score of all neighbors of the given node that are also members of the given set of selected nodes, multiply this z-score by the z-score of the given node, and return this value as the z'-score for the given node. If the given node has no neighbors in the interaction graph, the z'-score is defined as zero. Returns the z'-score as zero or a positive floating point value. :Parameters: - `node`: the node for which to compute the z-prime score - `interaction_graph`: graph containing the gene-gene or gene product-gene product interactions - `selected_nodes`: a `set` of nodes fitting some criterion of interest (e.g., annotated with a term of interest) """ node_neighbors = interaction_graph.neighbors_iter(node) neighbors_in_selected_nodes = (neighbor for neighbor in node_neighbors if neighbor in selected_nodes) neighbor_z_scores = (interaction_graph.node[neighbor]['weight'] for neighbor in neighbors_in_selected_nodes) try: max_z_score = max(neighbor_z_scores) # max() throws a ValueError if its argument has no elements; in this # case, we need to set the max_z_score to zero except ValueError, e: # Check to make certain max() raised this error if 'max()' in e.args[0]: max_z_score = 0 else: raise e z_prime = interaction_graph.node[node]['weight'] * max_z_score return z_prime Here are the top couple of calls according to cProfiler, sorted by time. ncalls tottime percall cumtime percall filename:lineno(function) 156067701 352.313 0.000 642.072 0.000 bpln_contextual.py:204(<genexpr>) 156067701 289.759 0.000 289.759 0.000 bpln_contextual.py:202(<genexpr>) 13963893 174.047 0.000 816.119 0.000 {max} 13963885 69.804 0.000 936.754 0.000 bpln_contextual.py:171(calculate_node_z_prime) 7116883 61.982 0.000 61.982 0.000 {method 'update' of 'set' objects}

    Read the article

  • Sending Javascript variables.

    - by shinjuo
    I have a page that allows a user to choose some things in a form and it will calculate the weight using javascript. It breaks it up into 5 variables that I need to send to another page. Originally I was just having it put the variable into a text box and then I was posting that text box. However I dont want to have 5 text boxes. So now I need to somehow send or post the five variables to another page. Here is my javascript function. I need to post weightBoxOne - weightBoxFive js function function getWeight(){ var weightBoxOne; var weightBoxTwo; var totalWeight; var box = .5; var quantity = document.dhform.quantity.value; var cardSize = document.dhform.cardSize.value; if(cardSize == 0.0141){ if(quantity <= 1000){ weightBoxOne = (quantity * cardSize) + box; totalWeight = weightBoxOne; }else if(quantity > 1000 && quantity <= 2000){ weightBoxOne = (1000 * cardSize) + box; weightBoxTwo = ((quantity - 1000) * cardSize) + box; totalWeight = weightBoxOne + weightBoxTwo; }else if(quantity > 2000 && quantity <= 3000){ weightBoxOne = (1000 * cardSize) + box; weightBoxTwo = (1000 * cardSize) + box; weightBoxThree = ((quantity - 2000) * cardSize) + box; totalWeight = weightBoxOne + weightBoxTwo + weightBoxThree; }else if(quantity > 3000 && quantity <= 4000){ weightBoxOne = (1000 * cardSize) + box; weightBoxTwo = (1000 * cardSize) + box; weightBoxThree = (1000 * cardSize) + box; weightBoxFour = ((quantity - 3000) * cardSize) + box; totalWeight = weightBoxOne + weightBoxTwo + weightBoxThree + weightBoxFour; }else{ weightBoxOne = (1000 * cardSize) + box; weightBoxTwo = (1000 * cardSize) + box; weightBoxThree = (1000 * cardSize) + box; weightBoxFour = (1000 * cardSize) + box; weightBoxFive = ((quantity - 4000) * cardSize) + box; totalWeight = weightBoxOne + weightBoxTwo + weightBoxThree + weightBoxFour + weightBoxFive; } }else if(cardSize == 0.00949){ if(quantity <= 4000){ weightBoxOne = (quantity * cardSize) + box; totalWeight = weightBoxOne; }else{ weightBoxOne = (4000 * cardSize) + box; weightBoxTwo = ((quantity - 4000) * cardSize) + box; totalWeight = weightBoxOne + weightBoxTwo; } } document.rates.weight.value = totalWeight; } //--> this is the form that was originally posting <form action="getRates.php" name="rates" method="post" onSubmit="popupform(this, 'join')"> <table style="width: 216px"> <tr> <td style="width: 115px; height: 49px;"><span class="style16">Weight</span><br/> <input type="text" id="weight" name="weight" size="10" maxlength="4"/> </td> <td align="right" style="width: 68px; height: 49px;" valign="top"><span class="style16">Zip Code</span><br/> <input type="text" id="zip" name="zip" size="10" maxlength="5"/> </td> </tr> <tr> <td style="width: 115px"> <input name="submit" type="submit" value="Get Rate Costs" style="width: 138px" />

    Read the article

  • Can anyone help me find why this C program work on VS2005 but not on DEV-C++

    - by user333771
    Hello to everybody..and greetings from Greece I have a C program for an exercise and it has a strange issue The program runs just fine on VS 2005 but it crashes on DEV-C++ and the problem that the problem is that the exercise is always evaluated against DEV-C++ The program is about inserting nodes to a BST and this is where the problem lies... Well i would really appreciate some help. enter code here #include <stdio.h> #include <stdlib.h> #include <malloc.h> typedef struct tree_node { int value; int weight; struct tree_node *left; struct tree_node *right; } TREE_NODE; /* The Following function creates a Binary Search Treed */ TREE_NODE *create_tree(int list[], int size); TREE_NODE *search_pos_to_insert(TREE_NODE *root, int value, int *left_or_right); /* this is the problematic function */ void inorder(TREE_NODE *root); /* Inorder Traversing */ TREE_NODE *temp; int main() { TREE_NODE *root; /* Pointer to the root of the BST */ int values[] = {10, 5, 3, 4, 1, 9, 6, 7, 8, 2}; /* Values for BST */ int size = 10, tree_weight; root = create_tree(values, 10); printf("\n"); inorder(root); /* Inorder BST*/ system("PAUSE"); } TREE_NODE *search_pos_to_insert(TREE_NODE *root, int value, int *left_or_right) { if(root !=NULL) { temp = root; if(value >root->value) { *left_or_right=1; *search_pos_to_insert(root->right, value, left_or_right); } else { *left_or_right=0; *search_pos_to_insert(root->left, value, left_or_right); } } else return temp;/* THIS IS THE PROBLEM (1) */ } TREE_NODE *create_tree(int list[], int size) { TREE_NODE *new_node_pntr, *insert_point, *root = NULL; int i, left_or_right; /* First Value of the Array is the root of the BST */ new_node_pntr = (TREE_NODE *) malloc(sizeof(TREE_NODE)); new_node_pntr->value = list[0]; /* ¸íèåóå ôçí ðñþôç ôéìÞ ôïõ ðßíáêá. */ new_node_pntr->weight = 0; new_node_pntr->left = NULL; new_node_pntr->right = NULL; root = new_node_pntr; /* Now the rest of the arrat. */ for (i = 1; i < size; i++) { insert_point = search_pos_to_insert(root, list[i], &left_or_right); /* THIS IS THE PROBLEM (2) */ /* insert_point just won't get the return from temp */ new_node_pntr = (TREE_NODE *) malloc(sizeof(TREE_NODE)); new_node_pntr->value = list[i]; new_node_pntr->weight = 0; new_node_pntr->left = NULL; new_node_pntr->right = NULL; if (left_or_right == 0) insert_point->left = new_node_pntr; else insert_point->right = new_node_pntr; } return(root); } void inorder(TREE_NODE *root) { if (root == NULL) return; inorder(root->left); printf("Value: %d, Weight: %d.\n", root->value, root->weight); inorder(root->right); }

    Read the article

  • Java: Object Array assignment in for loop

    - by Hackster
    I am trying to use Dijkstra's algorithm to find the shortest path from a specific vertex (v0) to the rest of them. That is solved and works well with this code from this link below: http://en.literateprograms.org/index.php?title=Special:DownloadCode/Dijkstra%27s_algorithm_(Java)&oldid=15444 I am having trouble with assigning the Edge array in a for loop from the user input, as opposed to hard-coding it like it is here. Any help assigning a new edge to Edge[] adjacencies from each vertex? Keeping in mind it could be 1 or multiple edges. class Vertex implements Comparable<Vertex> { public final String name; public Edge[] adjacencies; public double minDistance = Double.POSITIVE_INFINITY; public Vertex previous; public Vertex(String argName) { name = argName; } public String toString() { return name; } public int compareTo(Vertex other){ return Double.compare(minDistance, other.minDistance); } } class Edge{ public final Vertex target; public final double weight; public Edge(Vertex argTarget, double argWeight){ target = argTarget; weight = argWeight; } } public static void main(String[] args) { Vertex v[] = new Vertex[3]; Vertex v[0] = new Vertex("Harrisburg"); Vertex v[1] = new Vertex("Baltimore"); Vertex v[2] = new Vertex("Washington"); v0.adjacencies = new Edge[]{ new Edge(v[1], 1), new Edge(v[2], 3) }; v1.adjacencies = new Edge[]{ new Edge(v[0], 1), new Edge(v[2], 1),}; v2.adjacencies = new Edge[]{ new Edge(v[0], 3), new Edge(v[1], 1) }; Vertex[] vertices = { v0, v1, v2}; /*Three vertices with weight: V0 connects (V1,1),(V2,3) V1 connects (V0,1),(V2,1) V2 connects (V1,1),(V2,3) */ computePaths(v0); for (Vertex v : vertices){ System.out.println("Distance to " + v + ": " + v.minDistance); List<Vertex> path = getShortestPathTo(v); System.out.println("Path: " + path); } } } The above code works well in finding the shortest path from v0 to all the other vertices. The problem occurs when assigning the new edge[] to edge[] adjacencies. For example this does not produce the correct output: for (int i = 0; i < total_vertices; i++){ s = br.readLine(); char[] line = s.toCharArray(); for (int j = 0; j < line.length; j++){ if(j % 4 == 0 ){ //Input: vertex weight vertex weight: 1 1 2 3 int vert = Integer.parseInt(String.valueOf(line[j])); int w = Integer.parseInt(String.valueOf(line[j+2])); v[i].adjacencies = new Edge[] {new Edge(v[vert], w)}; } } } As opposed to this: v0.adjacencies = new Edge[]{ new Edge(v[1], 1), new Edge(v[2], 3) }; How can I take the user input and make an Edge[], to pass it to adjacencies? The problem is it could be 0 edges or many. Any help would be much appreciated Thanks!

    Read the article

  • SSL Handshake negotiation on Nginx terribly slow

    - by Paras Chopra
    I am using Nginx as a proxy to 4 apache instances. My problem is that SSL negotiation takes a lot of time (600 ms). See this as an example: http://www.webpagetest.org/result/101020_8JXS/1/details/ Here is my Nginx Conf: user www-data; worker_processes 4; events { worker_connections 2048; use epoll; } http { include /etc/nginx/mime.types; default_type application/octet-stream; access_log /var/log/nginx/access.log; sendfile on; keepalive_timeout 0; tcp_nodelay on; gzip on; gzip_proxied any; server_names_hash_bucket_size 128; } upstream abc { server 1.1.1.1 weight=1; server 1.1.1.2 weight=1; server 1.1.1.3 weight=1; } server { listen 443; server_name blah; keepalive_timeout 5; ssl on; ssl_certificate /blah.crt; ssl_certificate_key /blah.key; ssl_session_cache shared:SSL:10m; ssl_session_timeout 5m; ssl_protocols SSLv2 SSLv3 TLSv1; ssl_ciphers RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP; ssl_prefer_server_ciphers on; location / { proxy_pass http://abc; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } The machine is a VPS on Linode with 1 G of RAM. Can anyone please tell why SSL Hand shake is taking ages?

    Read the article

  • Dynamic Programming Algorithm?

    - by scardin
    I am confused about how best to design this algorithm. A ship has x pirates, where the age of the jth pirate is aj and the weight of the jth pirate is wj. I am thinking of a dynamic programming algorithm, which will find the oldest pirate whose weight is in between twenty-fifth and seventy-fifth percentile of all pirates. But I am clueless as to how to proceed.

    Read the article

  • creating objects from trivial graph format text file. java. dijkstra algorithm.

    - by user560084
    i want to create objects, vertex and edge, from trivial graph format txt file. one of programmers here suggested that i use trivial graph format to store data for dijkstra algorithm. the problem is that at the moment all the information, e.g., weight, links, is in the sourcecode. i want to have a separate text file for that and read it into the program. i thought about using a code for scanning through the text file by using scanner. but i am not quite sure how to create different objects from the same file. could i have some help please? the file is v0 Harrisburg v1 Baltimore v2 Washington v3 Philadelphia v4 Binghamton v5 Allentown v6 New York # v0 v1 79.83 v0 v5 81.15 v1 v0 79.75 v1 v2 39.42 v1 v3 103.00 v2 v1 38.65 v3 v1 102.53 v3 v5 61.44 v3 v6 96.79 v4 v5 133.04 v5 v0 81.77 v5 v3 62.05 v5 v4 134.47 v5 v6 91.63 v6 v3 97.24 v6 v5 87.94 and the dijkstra algorithm code is Downloaded from: http://en.literateprograms.org/Special:Downloadcode/Dijkstra%27s_algorithm_%28Java%29 */ import java.util.PriorityQueue; import java.util.List; import java.util.ArrayList; import java.util.Collections; class Vertex implements Comparable<Vertex> { public final String name; public Edge[] adjacencies; public double minDistance = Double.POSITIVE_INFINITY; public Vertex previous; public Vertex(String argName) { name = argName; } public String toString() { return name; } public int compareTo(Vertex other) { return Double.compare(minDistance, other.minDistance); } } class Edge { public final Vertex target; public final double weight; public Edge(Vertex argTarget, double argWeight) { target = argTarget; weight = argWeight; } } public class Dijkstra { public static void computePaths(Vertex source) { source.minDistance = 0.; PriorityQueue<Vertex> vertexQueue = new PriorityQueue<Vertex>(); vertexQueue.add(source); while (!vertexQueue.isEmpty()) { Vertex u = vertexQueue.poll(); // Visit each edge exiting u for (Edge e : u.adjacencies) { Vertex v = e.target; double weight = e.weight; double distanceThroughU = u.minDistance + weight; if (distanceThroughU < v.minDistance) { vertexQueue.remove(v); v.minDistance = distanceThroughU ; v.previous = u; vertexQueue.add(v); } } } } public static List<Vertex> getShortestPathTo(Vertex target) { List<Vertex> path = new ArrayList<Vertex>(); for (Vertex vertex = target; vertex != null; vertex = vertex.previous) path.add(vertex); Collections.reverse(path); return path; } public static void main(String[] args) { Vertex v0 = new Vertex("Nottinghill_Gate"); Vertex v1 = new Vertex("High_Street_kensignton"); Vertex v2 = new Vertex("Glouchester_Road"); Vertex v3 = new Vertex("South_Kensignton"); Vertex v4 = new Vertex("Sloane_Square"); Vertex v5 = new Vertex("Victoria"); Vertex v6 = new Vertex("Westminster"); v0.adjacencies = new Edge[]{new Edge(v1, 79.83), new Edge(v6, 97.24)}; v1.adjacencies = new Edge[]{new Edge(v2, 39.42), new Edge(v0, 79.83)}; v2.adjacencies = new Edge[]{new Edge(v3, 38.65), new Edge(v1, 39.42)}; v3.adjacencies = new Edge[]{new Edge(v4, 102.53), new Edge(v2, 38.65)}; v4.adjacencies = new Edge[]{new Edge(v5, 133.04), new Edge(v3, 102.53)}; v5.adjacencies = new Edge[]{new Edge(v6, 81.77), new Edge(v4, 133.04)}; v6.adjacencies = new Edge[]{new Edge(v0, 97.24), new Edge(v5, 81.77)}; Vertex[] vertices = { v0, v1, v2, v3, v4, v5, v6 }; computePaths(v0); for (Vertex v : vertices) { System.out.println("Distance to " + v + ": " + v.minDistance); List<Vertex> path = getShortestPathTo(v); System.out.println("Path: " + path); } } } and the code for scanning file is import java.util.Scanner; import java.io.File; import java.io.FileNotFoundException; public class DataScanner1 { //private int total = 0; //private int distance = 0; private String vector; private String stations; private double [] Edge = new double []; /*public int getTotal(){ return total; } */ /* public void getMenuInput(){ KeyboardInput in = new KeyboardInput; System.out.println("Enter the destination? "); String val = in.readString(); return val; } */ public void readFile(String fileName) { try { Scanner scanner = new Scanner(new File(fileName)); scanner.useDelimiter (System.getProperty("line.separator")); while (scanner.hasNext()) { parseLine(scanner.next()); } scanner.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } public void parseLine(String line) { Scanner lineScanner = new Scanner(line); lineScanner.useDelimiter("\\s*,\\s*"); vector = lineScanner.next(); stations = lineScanner.next(); System.out.println("The current station is " + vector + " and the destination to the next station is " + stations + "."); //total += distance; //System.out.println("The total distance is " + total); } public static void main(String[] args) { /* if (args.length != 1) { System.err.println("usage: java TextScanner2" + "file location"); System.exit(0); } */ DataScanner1 scanner = new DataScanner1(); scanner.readFile(args[0]); //int total =+ distance; //System.out.println(""); //System.out.println("The total distance is " + scanner.getTotal()); } }

    Read the article

  • Big datastructures in functional programming

    - by Denis Gorodetskiy
    I'm newbie in Functional Programming. I have a huge neural network with thousands of neurons and every connection between neurons has its weight. I have to update these weights very often, several thousand times per learning session. Is FP still applicable here? I mean in fp we can't modify variables and only able to return new variables not changing previous values. Does this mean I have to recreate whole network on every weight update?

    Read the article

  • Is there a compact or express SQL Server version that I can package with my WinForms app & is free?

    - by Greg
    Hi, Is there a light weight version of SQL Server I could use that has the characteristics of: Free (assuming my winforms app is semi-commercial) Can be seemlessly packaged for deployment as part of the winforms click-once application? (i.e. ease in installation for the user). Light weight for the user (ideally something that just runs when the winforms application that uses it is running - but better than using XML sererialization for persistance). Thanks

    Read the article

  • How to get this Qt state machine to work?

    - by Ton van den Heuvel
    I have two widgets that can be checked, and a numeric entry field that should contain a value greater than zero. Whenever both widgets have been checked, and the numeric entry field contains a value greater than zero, a button should be enabled. I am struggling with defining a proper state machine for this situation. So far I have the following: QStateMachine *machine = new QStateMachine(this); QState *buttonDisabled = new QState(QState::ParallelStates); buttonDisabled->assignProperty(ui_->button, "enabled", false); QState *a = new QState(buttonDisabled); QState *aUnchecked = new QState(a); QFinalState *aChecked = new QFinalState(a); aUnchecked->addTransition(wa, SIGNAL(checked()), aChecked); a->setInitialState(aUnchecked); QState *b = new QState(buttonDisabled); QState *bUnchecked = new QState(b); QFinalState *bChecked = new QFinalState(b); employeeUnchecked->addTransition(wb, SIGNAL(checked()), bChecked); b->setInitialState(bUnchecked); QState *weight = new QState(registerButtonDisabled); QState *weightZero = new QState(weight); QFinalState *weightGreaterThanZero = new QFinalState(weight); weightZero->addTransition(this, SIGNAL(validWeight()), weightGreaterThanZero); weight->setInitialState(weightZero); QState *buttonEnabled = new QState(); buttonEnabled->assignProperty(ui_->registerButton, "enabled", true); buttonDisabled->addTransition(buttonDisabled, SIGNAL(finished()), buttonEnabled); buttonEnabled->addTransition(this, SIGNAL(invalidWeight()), weightZero); machine->addState(registerButtonDisabled); machine->addState(registerButtonEnabled); machine->setInitialState(registerButtonDisabled); machine->start(); The problem here is that the following transition: buttonEnabled->addTransition(this, SIGNAL(invalidWeight()), weightZero); causes all the child states in the registerButtonDisabled state to be reverted to their initial state. This is unwanted behaviour, as I want the a and b states to remain in the same state. How do I prevent this?

    Read the article

  • PyYAML parse into arbitary object

    - by Philip Fourie
    I have the following Python 2.6 program and YAML definition (using PyYAML): import yaml x = yaml.load( """ product: name : 'Product X' sku : 123 features : - size : '10x30cm' weight : '10kg' """ ) print type(x) print x Which results in the following output: <type 'dict'> {'product': {'sku': 123, 'name': 'Product X', 'features': [{'weight': '10kg', 'size': '10x30cm'}]}} It is possible to create a strongly typed object from x? I would like to the following: print x.features(0).size I am aware that it is possible to create and instance from an existent class, but that is not what I want for this particular scenario.

    Read the article

  • Choose variable based on users choice from picklist.

    - by Kelbizzle
    I have this form. Basically what I want is to send a auto-response with a different URL based on what the user picks in the "attn" picklist. I've been thinking I could have a different variable for each drop down value. It will then pass this variable on to the mail script that will choose which URL to insert inside the auto response that is sent. It gives me a headache thinking about it sometimes. What's the easiest way to accomplish this? Am I making more work for myself? I really don't know because I'm no programmer. Thanks in advance! Here is the form: <form name="contact_form" method="post" action="sendemail_reports.php" onsubmit="return validate_form ( );"> <div id='zohoWebToLead' align=center> <table width="100%" border="0" align="center" cellpadding="0" cellspacing="0" class="txt_body"> <table border=0 cellspacing=0 cellpadding=5 width=480 style='border-bottom-color: #999999; border-top-color: #999999; border-bottom-style: none; border-top-style: none; border-bottom-width: 1px; border-top-width: 2px; background-color:transparent;'> <tr> <td width='75%'><table width=480 border=0 cellpadding=5 cellspacing=0 style='border-bottom-color: #999999; border-top-color: #999999; border-bottom-style: none; border-top-style: none; border-bottom-width: 1px; border-top-width: 2px; background-color:transparent;'> <input type="hidden" name="ip" value="'.$ipi.'" /> <input type="hidden" name="httpref" value="'.$httprefi.'" /> <input type="hidden" name="httpagent" value="'.$httpagenti.'" /> <tr></tr> <tr> <td colspan='2' align='left' style='border-bottom-color: #dadada; border-bottom-style: none; border-bottom-width: 2px; color:#000000; font-family:sans-serif; font-size:14px;'><strong>Send us an Email</strong></td> </tr> <tr> <td nowrap style='font-family:sans-serif;font-size:12px;font-weight:bold' align='right' width='25%'> First Name   : </td> <td width='75%'><input name='visitorf' type='text' size="48" maxlength='40' /></td> </tr> <tr> <td nowrap style='font-family:sans-serif;font-size:12px;font-weight:bold' align='right' width='25%'>Last Name   :</td> <td width='75%'><input name='visitorfl' type='text' size="48" maxlength='80' /></td> </tr> <tr> <td nowrap style= 'font-family:sans-serif;font-size:12px;font-weight:bold' align='right' width='25%'> Email Adress  : </td> <td width='75%'><input name='visitormail' type='text' size="48" maxlength='100' /></td> </tr> <tr> <td nowrap style='font-family:sans-serif;font-size:12px;font-weight:bold' align='right' width='25%'> Phone   : </td> <td width='75%'><input name='visitorphone' type='text' size="48" maxlength='30' /></td> </tr> <td nowrap style='font-family:sans-serif;font-size:12px;font-weight:bold' align='right' width='25%'> Subject   : </td> <td width='75%'><select name="attn" size="1"> <option value=" Investment Opportunities ">Investment Opportunities </option> <option value=" Vacation Rentals ">Vacation Rentals </option> <option value=" Real Estate Offerings ">Real Estate Offerings </option> <option value=" Gatherings ">Gatherings </option> <option value=" General ">General </option> </select></td> <tr> <td nowrap style= 'font-family:sans-serif;font-size:12px;font-weight:bold' align='right' width='25%'> Message   :<br /> <em>(max 5000 char)</em></td> <td width='75%'><textarea name='notes' maxlength='5000' cols="48" rows="3"></textarea></td> </tr> <tr> <td colspan=2 align=center style=''><input name='save' type='submit' class="boton" value=Send mail /> &nbsp; &nbsp; <input type='reset' name='reset' value=Reset class="boton" /></td> </tr> </table></td> </tr> </table> </div> </form> Here is the mail script: <?php //the 3 variables below were changed to use the SERVER variable $ip = $_SERVER['REMOTE_ADDR']; $httpref = $_SERVER['HTTP_REFERER']; $httpagent = $_SERVER['HTTP_USER_AGENT']; $visitorf = $_POST['visitorf']; $visitorl = $_POST['visitorl']; $visitormail = $_POST['visitormail']; $visitorphone = $_POST['visitorphone']; $notes = $_POST['notes']; $attn = $_POST['attn']; //additional headers $headers = 'From: Me <[email protected]>' . "\n" ; $headers = 'Bcc: [email protected]' . "\n"; if (eregi('http:', $notes)) { die ("Do NOT try that! ! "); } if(!$visitormail == "" && (!strstr($visitormail,"@") || !strstr($visitormail,"."))) { echo "<h2>Use Back - Enter valid e-mail</h2>\n"; $badinput = "<h2>Feedback was NOT submitted</h2>\n"; echo $badinput; die ("Go back! ! "); } if(empty($visitorf) || empty($visitormail) || empty($notes )) { echo "<h2>Use Back - fill in all fields</h2>\n"; die ("Use back! ! "); } $todayis = date("l, F j, Y, g:i a") ; $subject = "I want to download the report about $attn"; $notes = stripcslashes($notes); $message = "$todayis [EST] \nAttention: $attn \nMessage: $notes \nFrom: $visitorf $visitorl ($visitormail) \nTelephone Number: $visitorphone \nAdditional Info : IP = $ip \nBrowser Info: $httpagent \nReferral : $httpref\n"; //check if the function even exists if(function_exists("mail")) { //send the email mail($_SESSION['email'], $subject, $message, $headers) or die("could not send email"); } else { die("mail function not enabled"); } header( "Location: http://www.domain.com/thanks.php" ); ?>

    Read the article

  • How to align this div contents properly?

    - by Pandiya Chendur
    Here is my layout, I am using one div and many spans for getting the above view... Look at all the rows ther are not properly aligned... <div class="resultsdiv"><br /> <span style="width:200px;" class="resultName">' + employee.Emp_Name + '</span> <span class="resultfields" style="padding-left:100px;">Category&nbsp;:</span>&nbsp; <span class="resultfieldvalues">' + employee.Desig_Name + '</span><br /><br /> <span id="SalaryBasis" class="resultfields">Salary Basis&nbsp;:</span>&nbsp;<span class="resultfieldvalues">' + employee.SalaryBasis + '</span> <span class="resultfields" style="padding-left:25px;">Salary&nbsp;:</span>&nbsp;<span class="resultfieldvalues">' + employee.FixedSalary + '</span> <span style="font-size:110%;font-weight:bolder;padding-left:25px;">Address&nbsp;:</span>&nbsp; <span class="resultfieldvalues">' + employee.Address + '</span> </div> and my css are .resultsdiv { background-color: #FFF;border-top:solid 1px #ddd; height:50px; border-bottom:solid 1px #ddd; padding-bottom:15px; width:450px; } .resultseven { background-color: #EFF1f1; } .resultshover { background-color: #F4F2F2; cursor:pointer; } .resultName { font-size:125%;font-weight:bolder;color:#476275;font-family:Arial,Liberation Sans,DejaVu Sans,sans-serif; } .resultfields { font-size:110%;font-weight:bolder;font-family:Arial,Liberation Sans,DejaVu Sans,sans-serif; } .resultfieldvalues { color:#476275;font-size:110%;font-weight:bold;font-family:Arial,Liberation Sans,DejaVu Sans,sans-serif; } Any suggestion to get it aligned properly.... Should i use divs insted of spans to get this properly aligned...

    Read the article

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