Thursday, 8 August 2013

How to update an AngularJS directive when a scope variable is updated via ajax?

How to update an AngularJS directive when a scope variable is updated via
ajax?

I have the following directive:
MyApp.directive('myFilter', ['$filter','$rootScope',
function($filter, $rootScope)
{
var dir = {};
dir.restrict = 'E';
dir.templateUrl = 'views/myFilter.html';
dir.replace = true;
dir.scope =
{
name: '@',
model: '=',
};
dir.link = function(scope,el,attrs)
{
//stuff here
}
return dir;
}]);
Here's how I invoke it:
<my-filter model="someField" name="abcd" />
When the directive is first initalized, the someField is empty. Later on,
it is retrieved via ajax, and its value is filled in.
Question is, how can I watch for the value of someField to be updated?
When I do this:
scope.$watch(scope.model, function()
{
console.log( "changed, new val: ", scope.model );
}
This is only called once, when initalizing the directive, and the value
then is empty. When the value is retrieved via ajax (from $http.get), this
watch function is not called again. However, in other parts of the page
where I'm displaying {{someField}}, that value DOES update when ajax
request is fetched. So I don't think the problem has to do with doing
$scope.apply() after ajax request.

PHP Syntax Check please

PHP Syntax Check please

Is this the right syntax i am sure it is but i still get mysql said i have
an error in my syntax. By the way i'm running PHP 5.4.10. I have tried
using mysql instead of mysqli but it still does not work. Any help is
greatly appreciated.
<?php
$result = mysql_query("SELECT count(*) FROM User_info");
$row = mysql_fetch_row($result);
$num = $row[0];
echo $num;
?>
It says that the error in syntax is on the second line after PHP tag.

C-Linux-How to send C parameter value to awk script?

C-Linux-How to send C parameter value to awk script?

I'm quite new to Linux and not familiar with C. Here I have one question
about both.
I'm writing a C program to run in Linux. And I have a file names f.txt in
the same folder. With some fields like this:
Jason 12 Male
I want to compare the $2 of the txt file of each line with the value of
parameter a. If the second field of the line is greater than a, then print
the first field $1.
I tried codes like this but not work. Can anybody help? Thanks!
void main()
{ int a;
scanf("%d",&a);
char* comm="awk '{if($2>"+a+") print $1}' f.txt";
system(comm);
}

Parsing Solr status response XML with JAXB

Parsing Solr status response XML with JAXB

Solr returns status information in the following XML form (this is a
shortened version):
<?xml version="1.0" encoding="UTF-8"?>
<response>
<lst name="responseHeader">
<int name="status">0</int>
<int name="QTime">2</int>
</lst>
</response>
I'd like to pull this into my Java application. I created the following code:
@XmlRootElement(name="response")
@XmlAccessorType(XmlAccessType.FIELD)
public class Response {
@XmlElement(name="lst")
private ResponseHeader responseHeader;
public ResponseHeader getResponseHeader() {
return responseHeader;
}
public void setResponseHeader(ResponseHeader responseHeader) {
this.responseHeader = responseHeader;
}
public Response() {}
}
for the root element, and
@XmlAccessorType(XmlAccessType.FIELD)
public class ResponseHeader {
@XmlElement(name="int")
private IntegerElement status;
@XmlElement(name="int")
private IntegerElement QTime;
....
}
for the code inside. Finally, there's this for the int fields:
@XmlAccessorType(XmlAccessType.FIELD)
public class IntegerElement implements Serializable {
@XmlTransient
private static final long serialVersionUID = 1L;
@XmlAttribute
protected String name;
@XmlValue
private int value;
...
}
When I try to unmarshal the piece of xml above, only one of the int
elements is filled. The other doesn't get set (i.e. null). No errors
though. How should I go about annotating these classes better?

What design do I follow to convert my classic ASP pages to a Java Enterprise Web Application?

What design do I follow to convert my classic ASP pages to a Java
Enterprise Web Application?

There are so many Java technologies that it is difficult for me to know
where to start. I understand JSP and Servlets. I know what http servers to
use. Real basic stuff. What I don't understand is what I do after that?
I don't want to create a bunch of jsp and servlets. That's not very
different than what I have.
I need to query various databases. Some are direct hits. Some have
webservices I need to consume. I will have to create a login system that
hits active directly.
Aren't I supposed to do more to make a "big java" enterprise application?
I am hoping this does not fall into the immediate downvote category of
"what technology do I use?" If it does can someone kindly tell me where I
can ask things like this. I haven't had much luck on
programmers.stackexchange.com.

Json.net and JsontIgnore in Serializing

Json.net and JsontIgnore in Serializing

i have an object which have an attribute of Serializable, this class
inherit from abstract class which inherit from other class which also
Serializable which inherit from an interface
i have used
string included = JsonConvert.SerializeObject(msg,
Formatting.Indented,
new JsonSerializerSettings {
/*ContractResolver = new
NotificationPropertyResolver()*/
TypeNameHandling = TypeNameHandling.All});
as msg is the interface I want to send this object in SignalR and i see
that it dont ignore any member, i have decorated the interface and the
classes
is there solution for that? i have tried also to use resolver with my own
attributes - but still same results

Custom filter Gmail emails on receiving, mark as important if phrase is found, archive if not

Custom filter Gmail emails on receiving, mark as important if phrase is
found, archive if not

We subscribe to a request for information press service, were they send us
15 / 20 emails a day (each with 20 or so queries in them) which are all
request from reporters / journalists, asking for an opinion / quote for an
article they are working on.
99% of these queries are irrelevant to us, but we have to sift through
them to make sure.
We use gmail / google apps for business for our emails i was wandering is
there a way that i can set a custom filter to skim through the content in
these email, if the phrase/s we are looking for them are not found then
archive them but if the phrases are found then mark it as important.
ie. if phrases 'design, architecture, interior design, furniture' are in
the email mark it as important, if not archive email.

How to get the node number?

How to get the node number?

I am using the dom package to parse the XML file. How to get the line
number of the XML node while handling it? So for example some attributes
should be integers, but set as floating-point numbers, so error message
will be something like this:
error while parsing xml file(line 3): number must be integer
<Top>
<Name name='name' />
<Group number='1.56'> <---- error: number must be integer.
<Member name='name1' test='test1' l='100'/>
</Group>
</Top>

Wednesday, 7 August 2013

Pass form values to one php for checking and then to a second php for processing

Pass form values to one php for checking and then to a second php for
processing

The question says it all!
I have a form that needs to be validated with php (for javascript disabled
browsers). Then, once all errors (if any) are handled, the data needs to
be send to another php for processing. I found this post Same page
processing useful because it took care of validation on the same page as
the form - this saves me the need to pass back values to the original
form...etc. [Right now I am ignoring the issue of back button and page
refresh retaining the values - totally undesirable from my POV)
However, I noticed, in the same post, that it looks like all the form
processing should also be placed on the same page as the form. This (I
feel) will make the file ugly and a headache to maintain. So I was
wondering:
What if I have the completed (error checked) form processing in a
different php file? Is it possible to call that file (not by an include)
or send the appropriate data (from the validation code or some other way)
to the external processing file (similar to how we send POST data from the
actual form)?
The reason I ask is, I have a working system where a form submits data to
an external php file, that processes it and saves it to the database. Bad
practice, I know, but I only thought of adding the validation after all
this was done and working.
I guess it would be simple enough to copy all the code in the external php
into the php that validates the form input, but somehow, it doesn't seem
to be such a good idea! I would prefer to keep the 'saving to database'
part of the processing in a separate file.
Hence the question:
User fills in the form (form.php);
PHP on the same page checks for errors and reloads the form with the
entered data in case of errors (form.php).
In case it does not encounter any errors, it sends (?) the data as (maybe)
POST values to the processing file (process.php)
Is this possible? If it is please just give a hint - no code as I would
like to learn how to do this myself!

EF5: Can't Get StoreGeneratedPattern Property From Model

EF5: Can't Get StoreGeneratedPattern Property From Model

I've seen sample code for reading an EF EdmProperty's
StoreGeneratedPattern property (computed, identity, or none) in at least 2
places (here & here), but it doesn't work with my model. My context is an
ObjectContext, the version is EF5; maybe this code broke with EF5? When I
look at the properties for this property/column in the model, it shows
identity.
Here is my code:
using ( var context = new MyApplicationEntities() )
{
var entityType = ( (EntityConnection)context.Connection )
.GetMetadataWorkspace() // can't call
context.MetadataWorkspace - storage model will not be
present
.GetType( "MyEntityTypeWithIdentityColumn",
"MyApplicationModel.Store", DataSpace.SSpace ) as
EntityType;
EdmMember identityColumn =
entityType.Members["MyIdentityColumn"];
Facet item;
// All I get here for Facets is Nullable & DefaultValue
if ( identityColumn.TypeUsage.Facets.TryGetValue(
"StoreGeneratedPattern", false, out item ) )
{
var value = ( (StoreGeneratedPattern)item.Value ) ==
StoreGeneratedPattern.Computed;
}
}

Adapter pattern without the use of interfaces

Adapter pattern without the use of interfaces

this is my first question here so i'm sorry for any mistakes
i'm trying to understand if the Adapter pattern implementation is
dependent on interface realizations. from what i read, i should use
adapter when i need to Convert the interface of a class into another
interface clients expect.
i have been told the classic example of the 3 pronged plug using an
adapter to connect to a two pronged plug...
so, from what i understand, if some method in a class has a method with a
specific paramater signature, and i want to wrap it with logic that
require more (or less) paramaters, then i should implement the adapter
pattern.
from all the examples iv'e seen, the proper way to do this is to create an
adapter class that realizes an interface with the desired method
signature, and to hold the adoptee as a member in the adapter class. then,
i can call the adpotee method through the realized interface method and
input the logic.
the question is, if i only need to use one adoptee class, why use an
interface? is it not simpler to drop the interface bit and just hold the
adoptee as a member and implement the desired logic in a "stand alone"
method?
is it required to realize an interface method here for the adapter pattern
to be valid?
public class PostStatusAdapter
{
public interface IpostStatus
{
void Post(string i_Post, string i_Password);
}
public class UserAdapter : IpostStatus
{
User Adoptee = new User();
void IpostStatus.Post(string i_Post, string i_Password)
{
if (PasswordCorrect(i_Password))
{
Adoptee.PostStatus(i_Post);
}
}
private bool PasswordCorrect(string i_Password) { ... }
}
}

Filter specific child nodes along with the parent

Filter specific child nodes along with the parent

I need to retrieve the parent nodes along with only those child nodes
matching specific attribute values. The input XML is
<ErrorList>
<Table name="Table1" type="A">
<Error category="Minor">
<errorCode>100</errorCode>
<errorMessage>msg-100</errorMessage>
</Error>
<Error category="Major">
<errorCode>101</errorCode>
<errorMessage>msg-101</errorMessage>
</Error>
</Table>
<Table name="Table2" type="B">
<Error category="Fatal">
<errorCode>102</errorCode>
<errorMessage>msg-102</errorMessage>
</Error>
<Error category="Major">
<errorCode>105</errorCode>
<errorMessage>msg-101</errorMessage>
</Error>
</Table>
</ErrorList>
The XSL code below retrieves the Error nodes having category attribute
Fatal or Minor:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:output indent="yes" />
<xsl:template match="Error[@category = 'Fatal'] | Error[@category =
'Minor']">
<xsl:copy-of select="self::node()"/>
</xsl:template>
<xsl:template match="text()"/>
</xsl:stylesheet>
The output I get:
<Error category="Minor">
<errorCode>100</errorCode>
<errorMessage>msg-100</errorMessage>
</Error><Error category="Fatal">
<errorCode>102</errorCode>
<errorMessage>msg-102</errorMessage>
</Error>
The expected output is below (need to retrieve the parent table node for
the select child nodes):
<Table name="Table1" type="A">
<Error category="Minor">
<errorCode>100</errorCode>
<errorMessage>msg-100</errorMessage>
</Error>
</Table>
<Table name="Table2" type="B">
<Error category="Fatal">
<errorCode>102</errorCode>
<errorMessage>msg-102</errorMessage>
</Error>
</Table>
Can you please help me with the xsl to get the desired output.

SQL statements and database connection within a java Program

SQL statements and database connection within a java Program

im having trouble with my sql statements that are supposed to be used
inside my java program to access and modify an access database. it throws
out a very large amount of errors and i cannot seem to find the way to fix
them. here is my code.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.CallableStatement;
import java.util.logging.Level;
import java.util.logging.Logger;
public class AccessDatabaseConnection {
private int wins = 0;
private String name = "";
private int losses = 0;
private int loss = 0;
private int win = 0;
Connection con;
private ultimate ult;
ResultSet rset;
Statement stmt;
public AccessDatabaseConnection(ultimate game) {
this.ult = game;
}
public Connection AccessDatabaseConnect() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String database = "jdbc:odbc:Driver={Microsoft Access
Driver(*.mdb,
*.accdb)};DBQ=C:\\Users\\McKenzieC\\Documents\\tictactoeRecords.accdb;";
con = DriverManager.getConnection(database, "", "");
stmt = con.createStatement();
} catch (Exception e) {
e.printStackTrace();
return con;
}
return con;
}
public void addData(String nameWin, String nameLose) {
if (getWins() == -1) {
win = getWins() + 2;
try {
rset = stmt.executeQuery("SELECT * FROM t_Records");
stmt.executeQuery("INSERT INTO t_Records (Name,Wins,Losses) "
+ "VALUES (" + nameWin.toUpperCase() + ","
+ Integer.toString(win) + "," + 0 + ")");
rset.close();
} catch (SQLException e) {
e.printStackTrace();
}
} else {
win = getWins() + 1;
try {
rset = stmt.executeQuery("SELECT * FROM t_Records");
stmt.executeQuery("UPDATE t_Records SET Wins="
+ Integer.toString(win) + " WHERE Name="
+ nameWin.toUpperCase());
rset.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (getLosses() == -1) {
loss = getLosses() + 2;
try {
rset = stmt.executeQuery("SELECT * FROM t_Records");
stmt.executeQuery("INSERT INTO t_Records (Name,Wins,Losses) "
+ "VALUES (" + nameLose.toUpperCase() + "," + 0 + ","
+ Integer.toString(loss) + ")");
rset.close();
} catch (SQLException e) {
e.printStackTrace();
}
} else {
loss = getLosses() + 1;
try {
rset = stmt.executeQuery("SELECT * FROM t_Records");
stmt.executeQuery("UPDATE t_Records SET Losses="
+ Integer.toString(loss) + " WHERE Name="
+ nameLose.toUpperCase());
rset.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// public String getName() {
// try {
// stmt = connect().createStatement();
// rset = stmt.executeQuery("SELECT * FROM t_Records");
// if (rset.next()) {
// name = rset.getString("Name");
// return name;
// }
// } catch (SQLException ex) {
// }
// return null;
// }
public int getWins() {
try {
rset = stmt.executeQuery("SELECT * FROM t_Records");
while (ult.getPlayerWin() != rset.getString("Name").toUpperCase()) {
if (ult.getPlayerWin() == rset.getString("Name").toUpperCase()) {
wins = rset.getInt("Wins");
rset.close();
return wins;
}
if (rset.next() == false) {
return -1;
} else {
rset.next();
}
}
wins = rset.getInt("Wins");
rset.close();
return wins;
} catch (SQLException e) {
e.printStackTrace();
return -1;
}
}
public int getLosses() {
try {
rset = stmt.executeQuery("SELECT * FROM t_Records");
while (ult.getPlayerLose().toUpperCase() != rset.getString("Name")
.toUpperCase()) {
if (ult.getPlayerLose().toUpperCase() == rset.getString("Name")
.toUpperCase()) {
losses = rset.getInt("Losses");
rset.close();
return losses;
}
if (rset.next() == false) {
return -1;
} else {
rset.next();
}
}
losses = rset.getInt("Losses");
rset.close();
return losses;
} catch (SQLException e) {
e.printStackTrace();
return -1;
}
}
}
the errors look like this.(there are a lot more so i cut these down a
little bit.)
java.sql.SQLException: [Microsoft][ODBC Driver Manager] Invalid cursor state
at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.SQLGetDataString(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcResultSet.getDataString(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcResultSet.getString(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcResultSet.getString(Unknown Source)
at AccessDatabaseConnection.getWins(AccessDatabaseConnection.java:109)
at AccessDatabaseConnection.addData(AccessDatabaseConnection.java:40)
at ultimate$ButtonHandler.checkGameWin(ultimate.java:1300)
at ultimate$ButtonHandler.actionPerformed(ultimate.java:149)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
java.sql.SQLException: [Microsoft][ODBC Driver Manager] Invalid
cursor state
at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.SQLGetDataString(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcResultSet.getDataString(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcResultSet.getString(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcResultSet.getString(Unknown Source)
at AccessDatabaseConnection.getWins(AccessDatabaseConnection.java:109)
at AccessDatabaseConnection.addData(AccessDatabaseConnection.java:41)
at ultimate$ButtonHandler.checkGameWin(ultimate.java:1300)
at ultimate$ButtonHandler.actionPerformed(ultimate.java:149)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)

Cannoto add QCheckBox to my window

Cannoto add QCheckBox to my window

For some reason this is giving me an error
#include <QtGui/QApplication>
#include <QWidget>
#include <QCheckBox>
QWidget window;
QCheckBox botonera = new QCheckBox(window);
The error seems to be about the window (should be a pointer to QWidget),
like QWidget * window;
But nothing seems to work, any idea??
Reg

Using a C++-function that is exported

Using a C++-function that is exported

I have been googling for days now, and I cant seem to wrap my head around
this problem.
I have a header, which exports some functions to a library. This file is
called test_extern.h, and the function looks like this:
__declspec(dllexport) int aFunction(int a, int b);
I have two other files, one .h and .cpp which calculates some things with
the help of the exported file. I have stripped down the versions to show
what I want to do.
A.h file:
// Include CBaseDILI_J1939 header file.
class A : public CBaseDILI_J1939
{
public:
int bFunction(int a, int b);
}
A.cpp file:
#include "test_extern.h"
#include "A.h"
int A::bFunction(int a, int b) {
return aFunction(a, b); // REturn the value of the exported function!
}
Now when I run this, I get "error LNK2019: unresolved external symbol
_imp_aFunction".
I have read and read all there is about exporting dll's, is there anyone
who knows what I might be doing wrong?

Could not start Tern server in Emacs

Could not start Tern server in Emacs

I have the latest version of Emacs and Tern but I have a problem with
using the plugin. When I use any Tern-related commands I get this command
from editor:
Wrong type argument: listp, "Could not start Tern server
env: node: No such file or directory.
"
As far as I know, Tern uses NodeJs to do it's job, I have the latest
version of NodeJs also but I don't know why I get this error.

MySQL join update: Updating join table row twice

MySQL join update: Updating join table row twice

To explain the problem I have just outlined an example situation below.
OrderRows
ID|OrderNumber|ProductNumber|Quantity|Done 1|10|100|1|no* 2|10|101|1|no
3|10|100|4|no* * Have the same product number
Stock ProductNumber|Quantity 100|5 101|1
UPDATE OrderRows INNER JOIN Stock ON
Stock.ProductNumber=OrderRows.ProductNumber SET Done='yes', Stock.
Quantity = Stock. Quantity -OrderRows. Quantity WHERE OrderNumber='100'
AND Done='no'
The result for the table Stock will be as below.
ProductNumber|Quantity 100|4 101|0
The Order Rows are updated correctly. But for Order Row three the Stock is
not adapted. This is because Order Row three has the same Product Number
as Order Row one. The question is, how can I fix this?

Tuesday, 6 August 2013

Multiple ManyToManyField usage and table not found

Multiple ManyToManyField usage and table not found

I have the following class decelerations in my models.py :-
enter code here
class Student(models.Model):
user = models.OneToOneField(User)
current_clubs = models.ManyToManyField('Club',related_name="current")
previous_clubs = models.ManyToManyField('Club',related_name="previous")
class Club(models.Model):
user = models.OneToOneField(User)
students = models.ManyToManyField('Student',related_name="stud")
When I try to view the student or club class from the admin page, (I am
able to create and register Student and Club logins but not view them as
an admin), I see the following error :- DatabaseError at
/admin/school/Club/1/ Django Version is 1.5.1 Exception Type is
DatabaseError Exception Value is no such table: school_club_students
I am unsure as to why such a table was not created by Django when I
created a Club object. If I try to use the admin interface to add a Club,
I run into the same error.
Thanks!

In Spring MVC, where to catch Database exceptions

In Spring MVC, where to catch Database exceptions


I am following the structure suggested above at (
http://viralpatel.net/blogs/spring3-mvc-hibernate-maven-tutorial-eclipse-example/
). I tried adding a duplicate entry, which resulted in the following
exception:
SEVERE: Servlet.service() for servlet [appServlet] in context with path
[/cct] threw exception [Request processing failed; nested exception is
org.springframework.dao.DataIntegrityViolationException: Duplicate entry
'a@b.com' for key 'PRIMARY'; SQL [n/a]; constraint [null]; nested
exception is org.hibernate.exception.ConstraintViolationException:
Duplicate entry 'a@b.com' for key 'PRIMARY'] with root cause
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:
Duplicate entry 'a@b.com' for key 'PRIMARY'
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at << removed for readability>>
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at com.sun.proxy.$Proxy26.addUser(Unknown Source)
at
com.bilitutor.cct.control.HomeController.signup(HomeController.java:56)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
<< removed for readability>>
I have the following questions:
Why is the exception being caught by the Controller (
userService.addUser(user) in com.bilitutor.cct.control.HomeController )
and not by the DAO ( sessionFactory.getCurrentSession().save(user); ) and
then bubbled up to the Controller?
I understand that I am getting a
org.springframework.dao.DataIntegrityViolationException because I am using
the @Repository annotation, which perhaps does exception translation
(correct me if I am wrong). In that case, when I catch the exception, how
do I find the error code for it?
As a best practice, on which layer (DAO, Service or Controller) is the
best spot to catch the exception?

Calculating blocks needed to access file's inode.

Calculating blocks needed to access file's inode.

A UNIX inode has 13 block pointers. Let the first ten be direct pointers
and the other three be single, double and triple indirect pointers
respectively. Furthermore, let disk blocks be 512 bytes in size and block
pointyers are 4 bytes. Suppose we need to read a file in subdirectory
/home/smith/cs123/. Only directory /home is in memory and everything else
is not in memory. Also supposed each directory can fit in one data block.
How many blocks are needed to access this file's inode? What are these
blocks?
After get this file's inode, how many blocks are needed to access to read
the first 10kb in this file.

Populating HTML input array with JQuery

Populating HTML input array with JQuery

I'm very much a newb when it comes to JQuery, and this arose out of an
attempt to learn how to use it.
I have a form defined in which I have a series of inputs like the following:
<input name="Name[]">
I have successfully set up JQuery to clone a variable number of these and
the submit works perfectly. When I submit this to PHP, I get the post data
I am expecting.
["Name"]=> array(6) { [0]=> string(0) "" [1]=> string(0) "" [2]=>
string(0) "" [3]=> string(0) "" [4]=> string(0) "" [5]=> string(0) "" }
The problem I'm running into, though, is attempting to populate these form
elements with the json data returned by my PHP. When I try to set the
values of these elements in the form using:
$('[name='+key+']', frm).val(value);
where (for instance) key = Name[0]
I haven't had much luck and get an error:
Uncaught Error: Syntax error, unrecognized expression: [name=Name[0]]
Apparently it doesn't like the brackets in there? Is there a way to access
elements in this manner?

Using ajax to recognize new html added to the folder structure and add it to a list

Using ajax to recognize new html added to the folder structure and add it
to a list

I am trying to build a mini-application that has a global header and a
content div. This content div will have different html-based demos that
are loaded into it, depending on the html-base demo selected from the
header. I will include an outline of what I am trying to accomplish, as
well as the code that I am currently using for the content-swapping. Would
love some input on how to proceed.
One note--this must be able to be downloadable and ran locally, with no
server/sb setup.
+++++++++++++++++++++++++++++++++++++++++++++
First off, the outline: 1. FOLDER STRUCTURE Main Demos Demo #1 index.html
js css Demo #2 index.html js css
When the folder is empty:
When the folder has one folder added to it:
Demo #1 main > demos > Demo #1 > index.html
When the folder has more than one folder added to it:
Demo #1 Demo #2 main > demos > Demo #1 > index.html
When Demo #2 is selected from the dropdown:
Demo #1 Demo #2 main > demos > Demo #2 > index.html
+++++++++++++++++++++++++++++++++++++++++++++
Lastly, here is the code that I am currently using for the content swap.
Would love some insight. Thanks all!
jQuery.ajaxSetup ({
cache: false
});
var ajax_load = "";
//load() functions
var loadUrl = "ajax/load.html";
var loadUrl2 = "ajax/load2.html";
jQuery("#load_demo_01").click(function(){
jQuery("#result").html(ajax_load).load(loadUrl);
});
jQuery("#load_demo_02").click(function(){
jQuery("#result").html(ajax_load).load(loadUrl2);
});

Lagrange multiplier problem

Lagrange multiplier problem

I am stuck with the following question: Use Lagrange multipliers to
determine the shortest distance from a point $x \in R $ to a plane
{$y¨Ob^T y=c$}. Please could someone help me step by step through the
problem as I am not even sure where to start with it.

How to indent input controls for a nested HTML list using CSS to a single column

How to indent input controls for a nested HTML list using CSS to a single
column

I have a nested html list, with each element having a set of associated
input controls. I want to indent all the input controls to a single
column. An example is given below
[b][b][c] • Element_1
[b][b][c] • Element_1.1
[b][b][c] • Element_1.1.1
[b][b][c] • Element_1.1.2
[b][b][c] • Element_1.2
[b][b][c] • Element_2
[b][b][c] • Element_3
Here [b] means a button and [c] means a checkbox and • means a bullet sign
for the list corresponding to the following element.

powerbuider datawindow update error

powerbuider datawindow update error

I am trying to insert a new record but sometimes datawindow not includes
all the column .
All colimns are selected in the update properties but i am not getting all
the columns in the insert statement.