Monday, 30 September 2013

Transparently redirecting http traffic to local proxy in bridge mode

Transparently redirecting http traffic to local proxy in bridge mode

Router - LinuxBridge - Backbone -- 10.0.0.0/8 , 10.20.0.0/16 test net
|
|
|(eth1)
--------> Management Interface 10.101.101.10
# brctl show br0
bridge name bridge id STP enabled interfaces
br0 0000.00900b2a6f44 no eth16
eth17
br0 Link encap:Ethernet HWaddr 00:90:0B:2A:6F:44
--
eth1 Link encap:Ethernet HWaddr 00:90:0B:2C:80:A2
inet addr:10.101.101.10 Bcast:10.101.101.255 Mask:255.255.255.0
--
eth16 Link encap:Ethernet HWaddr 00:90:0B:2A:6F:44
--
eth17 Link encap:Ethernet HWaddr 00:90:0B:2A:6F:45
br0 is formed with eth16 and eth17. eth16, eth17 and br0 has ifconfig
"0.0.0.0 up". That is no IP set.
# route -n
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
0.0.0.0 10.101.101.1 0.0.0.0 UG 0 0 0 eth1
10.101.101.0 0.0.0.0 255.255.255.0 U 0 0 0 eth1
There are lots of clients within subnets other then 10.101.101.0
management subnet behind backbone.
I am trying to transparently cache http traffic.
# iptables -t nat -I PREROUTING -p tcp -s 10.20.0.0/16 --dport 80 -j DNAT
--to-destination 10.101.101.10:3128
Alternatively,
# ebtables -t broute -A BROUTING -p IPv4 --ip-protocol 6 --ip-source
10.20.0.0/16 --ip-destination-port 80 -j redirect --redirect-target ACCEPT
# iptables -t nat -A PREROUTING -i br0 -p tcp -s 10.20.0.0/16 --dport 80
-j REDIRECT --to-port 3127
I see packet counters increasing in iptables stats. However squid can not
reply back to the clients. Internet stops for clients.
I have tried with rp_filter=0,1 and accept_local=0,1; Result were the same.
Is it possible to transparently redirect traffic in such as topology? What
do you suggest to make it work?
Best Regards,

Running 12.04 LTS with Windows , Ubuntu doesn't boot. Have tried to re-load sw but Windows seems to block it

Running 12.04 LTS with Windows , Ubuntu doesn't boot. Have tried to
re-load sw but Windows seems to block it

Running 12.04 LTS with Windows happily for years, Ubuntu doesn't boot now.
Have tried to re-load sw but Windows seems to block CD disc. I'm only a
simple user with no programming skills. Have loved Ubuntu but now can't
get my machine past appalling Windows. Help? Bootloader doesn't work
either.

GSON Not an Object Error

GSON Not an Object Error

I have the following json object:
cNGJSON = {
"one": graph1.graphNode, "two": graph2.graphNode, "three":
graph3.graphNode, "four": graph4.graphNode, "five":
graph5.graphNode,"six": graph6.graphNode,
"seven": graph7.graphNode,"eight": graph8.graphNode, "nine":
graph9.graphNode,"ten": graph10.graphNode, "eleven":
graph11.graphNode, "twelve": graph12.graphNode,
"thirteen": graph13.graphNode,"fourteen":
graph14.graphNode,"fifteen": graph15.graphNode,"sixteen":
graph16.graphNode, "seventeen": graph17.graphNode, "eighteen":
graph18.graphNode,
"nineteen": graph19.graphNode
};
where graph1.graphNode is an integer array.
[1,2,3,4]
I send this to the server with jQuery:
$.ajax({
url: 'validate',
type: 'post',
dataType: 'json',
success: function (data) {
console.log("Success!!");
},
data: cNGJSON
});
However I get a
Expected BEGIN_OBJECT but was STRING at line 1 column 1
Error every time I try.
I tried with setting the cNGJSON to:
cNGJSON = {
"one": "Number one", "two": "Number two"
};
Still I get the same error.

Optimize search by hash in MySQL

Optimize search by hash in MySQL

I have an InnoDB table with a lot of fields, one of them is a unique hash
of 32 bytes (typical md5 result).
I have to do a lot of queries searching by that hash, but my table starts
to be big (500.000 records), and this search takes a lot of time:
SELECT id FROM table WHERE key='Bj8DzS7RmCG41nLdgOp0kEhNtrfPo3KF' This
took about 0.7s
I could create an index of this "hash" 32-bytes varchar column, but this
table grows a lot and if I have to optimize table (to re-index), it takes
a lot of time to do it (about 10 minutes in my case), locking all the
other live queries.
So, what is the best way to optimize a query where you have to search by a
32-bytes varchar field ?

Sunday, 29 September 2013

Getting a form post checkbox variable outside a while loop on another page

Getting a form post checkbox variable outside a while loop on another page

I have read through this post, which looks to be the most similar, but it
has not solved my problem.
I have the below while loop working to display results from my database.
The specific line of question in the while loop is this (note: it is
within a form):
while($row = mysqli_fetch_array($result)){
<input type='checkbox' name='booking_to_delete[]'
value='".$row['BookingNo']."'>
}
The rest of the form data passes through fine except for the checkboxes.
In the following php page, I have this:
function delete_booking_from_database($num){
$sql="SELECT * FROM bookings WHERE BookingNo=".$num;
$result=mysqli_query($sql);
if (!result){
echo "Record not found.";
}
else{
$sql="DELETE FROM bookings WHERE BookingNo=".num;
$result=mysqli_query($sql);
}
}
if (isset($_POST['booking_to_delete']) &&
count($_POST['booking_to_delete'])>0){
foreach($_POST['booking_to_delete'] as $bookingid){
delete_booking_from_database($bookingid);
}
echo "Record successfully deleted";
header("refresh:2;url=index.php");
}
The page shows "Record successfully deleted" and forwards me back to
index.php so I know that's working fine, however no data is deleted from
the database.

Adding elements to JPanel

Adding elements to JPanel

Why does "drawing" not appear here? I am adding it to a different JPanel
then adding everything to another JPanel and returning that. However, all
i see is the TrackBall
public class Draw extends JFrame
{
private JSplitPane itemPane;
private Point position = null;
public Draw()
{
// Set the layout to a grid
setLayout ( new BorderLayout (5,5));
// Set the properties of the window
setTitle ("Emulator");
setSize ( 900, 700);
setDefaultCloseOperation (EXIT_ON_CLOSE);
setBackground ( new Color (15, 255, 10));
// Add the components
addComponents ();
}
public static void startWindowsGui()
{
// We are in the static main, set the form to invoke later
SwingUtilities.invokeLater ( new Runnable()
{
public void run()
{
// Create a new instance of server and set it to visible
Draw gui = new Draw();
gui.setVisible (true);
}
} );
}
private void addComponents()
{
// Create the main and an itemPane
JSplitPane mainPane = new JSplitPane (
JSplitPane.HORIZONTAL_SPLIT );
setItemPane(new JSplitPane ( JSplitPane.VERTICAL_SPLIT ));
mainPane.add ( createPane ( ), JSplitPane.LEFT );
mainPane.add ( getItemPane(), JSplitPane.RIGHT );
mainPane.setOneTouchExpandable ( true );
getItemPane().setOpaque(true);
getItemPane().setBackground(new Color(0xffffffc0));
JPanel p = new JPanel();
this.getItemPane().add(p);
add ( mainPane, BorderLayout.CENTER );
}
public static void main(final String[] args)
{
Runnable gui = new Runnable()
{
@Override
public void run()
{
new Draw().setVisible(true);
}
};
SwingUtilities.invokeLater(gui);
}
private class Drawing extends JPanel {
private static final long serialVersionUID = 1L;
private final Point position;
public Drawing(Point position) {
this.position = position;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(Color.RED);
g2.fillOval(160 + position.x, 160 - position.y, 15, 15);
}
}
private JPanel createPane()
{
// Create the feedPanel
JPanel panel = new JPanel ( );
JPanel panel2 = new JPanel ( );
JPanel panel3 = new JPanel ( );
this.position = new Point();
TrackBall myJoystick = new TrackBall(150, position, 100);
panel.add(myJoystick, BorderLayout.PAGE_END);
Drawing drawing = new Drawing(position);
panel2.add(drawing, BorderLayout.PAGE_START);
panel3.add(panel2);
panel3.add(panel);
return panel3;
}
public JSplitPane getItemPane() {return itemPane;}
public void setItemPane(JSplitPane itemPane) {this.itemPane =
itemPane;}
}

db Connection not able to display table on webpage

db Connection not able to display table on webpage

How to display a table from database(mysql) on webpage (PHP) i am not able
to display..
$con=mysqli_connect("localhost", "ABC", "PW","DBN");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
DONE Connection now what to write??
Query:
( SELECT "username" AS SourceTable, username FROM user_info WHERE id =
'$u_id' ) UNION ( SELECT "exam1" AS SourceTable,score FROM exam1 WHERE id
= '$u_id' ) UNION ( SELECT "exam2" AS SourceTable,score FROM exam2 WHERE
id = '$u_id' ) UNION ( SELECT "exam3" AS SourceTable,score FROM exam3
WHERE id = '$u_id' ) UNION ( SELECT "exam4" AS SourceTable,score FROM
exam4 WHERE id = '$u_id' ) UNION ( SELECT "exam5" AS SourceTable,score
FROM exam5 WHERE id = '$u_id' ) UNION ( SELECT "exam6" AS
SourceTable,score FROM exam6 WHERE id = '$u_id' ) UNION ( SELECT "exam7"
AS SourceTable,score FROM exam7 WHERE id = '$u_id' ) UNION ( SELECT
"exam8" AS SourceTable,score FROM exam8 WHERE id = '$u_id' ) UNION (
SELECT "exam9" AS SourceTable,score FROM exam9 WHERE id = '$u_id' ) UNION
( SELECT "exam10" AS SourceTable,score FROM exam10 WHERE id = '$u_id' )
UNION ( SELECT "exam11" AS SourceTable,score FROM exam11 WHERE id =
'$u_id' ) UNION ( SELECT "exam12" AS SourceTable,score FROM exam12 WHERE
id = '$u_id' ) UNION ( SELECT "exam13" AS SourceTable,score FROM exam13
WHERE id = '$u_id' ) UNION ( SELECT "exam14" AS SourceTable,score FROM
exam14 WHERE id = '$u_id' ) UNION ( SELECT "exam15" AS SourceTable,score
FROM exam15 WHERE id = '$u_id' ) UNION ( SELECT "exam16" AS
SourceTable,score FROM exam16 WHERE id = '$u_id' ) UNION ( SELECT "exam17"
AS SourceTable,score FROM exam17 WHERE id = '$u_id' ) UNION ( SELECT
"exam18" AS SourceTable,score FROM exam18 WHERE id = '$u_id' ) UNION (
SELECT "exam19" AS SourceTable,score FROM exam19 WHERE id = '$u_id' )
UNION ( SELECT "exam20" AS SourceTable,score FROM exam20 WHERE id =
'$u_id' )
How to display a table from database(mysql) on webpage (PHP) i am not able
to display..

Error with child process & wait `C`

Error with child process & wait `C`

In the below code, if there is a problem creating a child process or
something happens to the child process what happens to wait(&status)?
pid_t pid;
int status;
if(pid=fork()>0){
printf("Parent Process\n");
wait(&status);
} else... child process here

Saturday, 28 September 2013

Prawn doesn't draw a horizontal rule

Prawn doesn't draw a horizontal rule

I want to draw a simple horizontal rule. What I'm doing is:
move_down 30
horizontal_rule
and Gemfile
gem 'prawn', :git => "https://github.com/prawnpdf/prawn.git", branch:
'master'
It doesn't draw anything.

Two classes inside a superclass for use with Entity Framework

Two classes inside a superclass for use with Entity Framework

First off, I know that dropdownlists should each be separate in their own
ViewModel, preferably emitted in a partial view.
However, if you could help me with the below problem, this will inform me
why I'm having trouble getting this to compile at design time with the two
classes inside my superclass (since I need them in the same View.
If I have a superclass described as below:
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
using YeagerTechModel.DropDownLists;
namespace YeagerTechModel.ViewModels
{
[DataContract]
[Serializable]
public partial class CustomerProjectDDL
{
[DataMember]
public Customer Customer = new Customer();
[DataMember]
public ProjectName ProjectName = new ProjectName();
}
}
and the definitions of the ProjectName class is as follows:
namespace YeagerTechModel.DropDownLists
{
[DataContract]
[Serializable]
public partial class ProjectName
{
[DataMember]
public Int16 ProjectID { get; set; }
[DataMember]
public String Name { get; set; }
}
}
I'm getting the design time compile error below in my method when I try
and use the above: The left curly brace right after the new statement:
"Cannot initialize type 'YeagertechModel.ViewModels.CustomerProjectDDL'
with a collection initializer because it does not implement IENumerable."
public List<CustomerProjectDDL> GetProjectNameDropDownListVM()
{
try
{
using (YeagerTechEntities DbContext = new
YeagerTechEntities())
{
DbContext.Configuration.ProxyCreationEnabled = false;
DbContext.Database.Connection.Open();
var project = DbContext.Projects.Where(w =>
w.ProjectID > 0).Select(s =>
new CustomerProjectDDL()
{
ProjectName.ProjectID = s.ProjectID,
ProjectName.Name = s.Name
});
List<CustomerProjectDDL> myProjects = new
List<CustomerProjectDDL>();
myProjects = project.ToList();
return myProjects;
}
}
catch (Exception ex)
{
throw ex;
}
}

C# winmm.dll mp3 player Fast Forward method?

C# winmm.dll mp3 player Fast Forward method?

I am using winmm.dll to make a basic mp3 player. I have a little problem
with my FFW method... basically nothing happens when I activate it.
You can probably figure what I am trying to do....
the first 6 comment out lines, hold a working sample code, when running my
loop it doesnt work for me, What have I done wrong ?
public void FFW()
{
//string cmd1 = "set MyMp3 time format ms";
//mciSendString(cmd1, null, 0, 0);
//cmd1 = "seek MyMp3 to 8000";
//mciSendString(cmd1, null, 0, 0);
//cmd = "play MyMp3";
//mciSendString(cmd, null, 0, 0);
int ffw5sec = 5000;
while (isPlaying == true)
{
string cmd = "set MyMp3 time format ms";
mciSendString(cmd, null, 0, 0);
cmd = "seek MyMp3 to " + ffw5sec.ToString();
mciSendString(cmd, null, 0, 0);
cmd = "play MyMp3";
mciSendString(cmd, null, 0, 0);
ffw5sec += 5000;
}
}

Friday, 27 September 2013

How to Return variables from a List in java and entry into mysqldatabase?

How to Return variables from a List in java and entry into mysqldatabase?

I want to return all the arraylist but only one is getting returned, do
not understand why such thing is happening?Spent the whole day trying to
understand the reason for such error.
Code : -
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import au.com.bytecode.opencsv.CSVReader;
public class CSVFileReader {
public List<String> main() {
String startFile = "/Users/sample.csv";
List<List<String>> build = new ArrayList<List<String>>();
List<String> tempArr = null;
try {
CSVReader reader = new CSVReader(new FileReader(startFile));
String[] line = null;
String[] headers = reader.readNext();
// generate headers
for(String header : headers){
tempArr = new ArrayList<String>();
// tempArr.add(header);
build.add(tempArr);
}
// generate content
while((line = reader.readNext())!=null){
for (int i = 0; i < build.size(); i++) {
tempArr = build.get(i);
String val = line[i];
tempArr.add(val);
//System.out.println("the value of the array variable is
:"+val);
build.set(i, tempArr);
}
}
for(List<String> string:build){
System.out.println("The value of the array and their
variables are :"+string);
}
for (int i=0; i<build.size();){
System.out.println("Element :"+build.get(i));
return build.get(i);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String[] args){
CSVFileReader csvfilereader = new CSVFileReader();
System.out.println("the returned variable is :"+csvfilereader.main());
}
}
The CSV file is like:(Could Be A file of any size and any number of columns)
Keyword,AlternateKeyword,PrintValue
ego kit1,silicone baby dolls for sale,samsung
ego kit2,ego ce4,samsung
ego kit3,venus,samsung,
ego kit4,zz cream,samsung
ego kit5,samsung galaxy 7.7 case,samsung
ego kit6,apple,samsung
And the Output is :
The value of the array and their variables are :[ego kit, ego kit, ego
kit, ego kit, ego kit, ego kit]
The value of the array and their variables are :[silicone baby dolls for
sale, ego ce4, venus, zz cream, samsung galaxy 7.7 case, apple]
The value of the array and their variables are :[Samsung, Samsung,
Samsung, Samsung, Samsung, Samsung]
Element :[ego kit1, ego kit2, ego kit3, ego kit4, ego kit5, ego kit6]
the returned variable is :[ego kit, ego kit, ego kit, ego kit, ego kit,
ego kit]
I want return all the ArrayList.
Also I want to group together the elements of the first column with the
elements of second and third column row-wise for entry into a
mysqldatabase, based on the value of the first column elements.Here the
first column is the primary id, based on which we have to enter the
values, like for ego kit1-->silicone dolls for sale,samsung and likewise.
I do not want the steps for mysql entry just want to create the Sql
statement based on the elements above.
New to Java, stuck at this point, please help.

implement in Clojure integer? in scheme

implement in Clojure integer? in scheme

I'm new to Clojure, and can't find an equivalent of integer? in scheme,
mainly for test cases as below:
(integer? 39.0) => #t
The function I've come up so far is:
(defn actual-integer? [x] (or (= 0.0 (- x (int x))) (integer? x)))
Does it work when x is arbitrary number types or is there a better solution?
Thanks.

Iterate through the double linked list of ifaddr

Iterate through the double linked list of ifaddr

struct ifaddrs {
struct ifaddrs *ifa_next;
char *ifa_name;
unsigned int ifa_flags;
struct sockaddr *ifa_addr;
struct sockaddr *ifa_netmask;
struct sockaddr *ifa_dstaddr;
void *ifa_data;
};
struct ifaddrs *addrs,*tmp;
if(getifaddrs(&addrs) != 0) {
perror("getifaddrs");
return 1;
}
for(tmp = addrs; tmp ; tmp = tmp->ifa_next) {
}
I have seen this code of getifaddrs getting the results in ifaddrs. But
the Iteration
for loop is lopping through all the interfaces it can find.
for(tmp = addrs; tmp ; tmp = tmp->ifa_next) {
}
The question is I don't see how tmp->ifa_next pointer incremented or going
to the next link.

Can't add VSS 6.0 database in Visual Studio 2008

Can't add VSS 6.0 database in Visual Studio 2008

I am using VSS 6.0 along with Visual Studio 2008. If I launch VSS
separately, I can add a Database by clicking "Browse" -> "Browse" -> click
on a "srcsafe.ini" file. I can then choose a name for the database, and it
will be added to the list of available databases.
However, if I am running Visual Studio, and I try to add my solution to
source control, it will prompt me to connect to a VSS database, for which
I follow the exactly same procedure described as above. Instead of adding
the database to the list of database, it will do nothing. No screen
freeze, no error, no nothing.
Has anyone encountered the same problem? If yes, did you solve it and how
did you solve it? Any help would be much appreciated.

The meaning of "a" in an awk command?

The meaning of "a" in an awk command?

I have an awk command in a script I am trying to make work, and I don't
understand the meaning of 'a':
awk 'FNR==NR{ a[$1]=$0;next } ($2 in a)' FILELIST.TXT FILEIN.* > FILEOUT.*
I'm quite new to using command line, so I'm just trying to figure things
out, thanks.

JSF TinyMCE Composite Component not working?

JSF TinyMCE Composite Component not working?

I have created a TinyMCE Composite Component Steps which i did 1- Added
tinymce folder provided by TinyMCE in resource directory of the project.
2- Then created another folder editors in resource directory and created
two file one is js file tinymce_init.js and code is
tinyMCE.init({
mode : "specific_textareas",
theme : "simple",
debug : true,
editor_selector : "tinymce"
});
and another file tinymce.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<ui:component xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:composite="http://java.sun.com/jsf/composite"
xmlns:pe="http://primefaces.org/ui/extensions">
<composite:interface>
<composite:attribute name="value" />
</composite:interface>
<composite:implementation>
<h:outputScript library="tinymce" name="tinymce.js" target="head" />
<h:outputScript library="editors" name="tinymce_init.js"
target="head" />
<h:inputTextarea rows="5" cols="80" />
</composite:implementation>
</ui:component>
3- Now access this composite component into my xhtml file something like this
<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:editors="http://java.sun.com/jsf/composite/editors">
<h:head>
<title>test</title>
</h:head>
<h:body>
<editors:tinymce />
</h:body>
</html>
But when i access this file i saw a input box without any toolbar , what i
am doing wrong and JS is loaded properly without any error in browser
console.

Thursday, 26 September 2013

500 Internal Server Error when querying index

500 Internal Server Error when querying index

I am trying to get started with Neo4j and the Neo4jClient; the first thing
I'm trying to attempt is to insert a series of nodes with a
publication_number property. Before inserting each node, I want to check
to ensure another node with the same publication number does not exist. To
this end I created an index for publication_number, which I then query.
This is the code I have so far. (Obviously all the logic above has not
been implemented, but I can't even get this to work.)
class Program
{
static void Main(string[] args)
{
var client = new GraphClient(new
Uri("http://192.168.12.31:7474/db/data"));
client.Connect();
// create index
client.CreateIndex("publication_number_idx", new IndexConfiguration
{
Provider = IndexProvider.lucene,
Type = IndexType.exact
},
IndexFor.Node);
// create record
Record record1 = new Record { publication_number = "1" };
Record record2 = new Record { publication_number = "2" };
// add record1 to graph and index
var record1Ref = client.Create(record1);
client.ReIndex(record1Ref, new[] { new IndexEntry
("publication_number_idx") { { "publication_number",
record1.publication_number } } });
Console.WriteLine("Added record1 at {0}", record1Ref.Id);
// add record2 to graph and index
var record2Ref = client.Create( record2,
new[] { new Cites(record1Ref) {
Direction =
RelationshipDirection.Outgoing }
},
new[] { new
IndexEntry("publication_number_idx")
{ {"publication_number",
record2.publication_number } } });
Console.WriteLine("Added record2 at {0}", record2Ref.Id);
// 500 error here
client.QueryIndex<Record>("publication_number_idx", IndexFor.Node,
@"START n=node:publication_number_idx(publication_number = ""2"")
RETURN n;");
}
}
public class Cites : Relationship,
IRelationshipAllowingSourceNode<Record>,
IRelationshipAllowingTargetNode<Record>
{
public Cites(NodeReference targetNode)
: base(targetNode)
{
}
public const string TypeKey = "CITES";
public override string RelationshipTypeKey
{
get { return TypeKey; }
}
}
I appear to be successful in adding the notes and updating the index. I am
able to query the index using Cypher in the Console; however, when I use
the same Cypher query with the Neo4J Client I get a 500 Internal Server
Error on the query.
Unhandled Exception: System.ApplicationException: Received an unexpected
HTTP status when executing the request.
The response status was: 500 Internal Server Error
The response from Neo4j (which might include useful detail!) was: {
"exception" : "NullPointerException", "fullname" :
"java.lang.NullPointerException", "stacktrace" : [
"org.apache.lucene.util.SimpleStringInterner.intern(SimpleStringInterner.java:54)",
"org.apache.lucen e.util.StringHelper.intern(StringHelper.java:39)",
"org.apache.lucene.index.Term.(Term.java:38)", "org.apache.luce
ne.queryParser.QueryParser.getFieldQuery(QueryParser.java:643)",
"org.apache.lucene.queryParser.QueryParser.Term(QueryPa rser.java:1436)",
"org.apache.lucene.queryParser.QueryParser.Clause(QueryParser.java:1319)",
"org.apache.lucene.queryPar ser.QueryParser.Query(QueryParser.java:1245)",
"org.apache.lucene.queryParser.QueryParser.TopLevelQuery(QueryParser.java
:1234)",
"org.apache.lucene.queryParser.QueryParser.parse(QueryParser.java:206)",
"org.neo4j.index.impl.lucene.IndexType .query(IndexType.java:300)",
"org.neo4j.index.impl.lucene.LuceneIndex.query(LuceneIndex.java:227)",
"org.neo4j.server.re
st.web.DatabaseActions.getIndexedNodesByQuery(DatabaseActions.java:889)",
"org.neo4j.server.rest.web.DatabaseActions.get
IndexedNodesByQuery(DatabaseActions.java:872)",
"org.neo4j.server.rest.web.RestfulGraphDatabase.getIndexedNodesByQuery(R
estfulGraphDatabase.java:707)",
"java.lang.reflect.Method.invoke(Method.java:606)",
"org.neo4j.server.rest.security.Secu
rityFilter.doFilter(SecurityFilter.java:112)" ] } at
Neo4jClient.GraphClient.SendHttpRequest(HttpRequestMessage request, String
commandDescription, HttpStatusCode[] ex pectedStatusCodes) in
c:\TeamCity\buildAgent\work\f1c4cf3efbf1b05e\Neo4jClient\GraphClient.cs:line
137 at Neo4jClient.GraphClient.QueryIndex[TNode](String indexName,
IndexFor indexFor, String query) in c:\TeamCity\buildA
gent\work\f1c4cf3efbf1b05e\Neo4jClient\GraphClient.cs:line 1168 at
Antares.Program.Main(String[] args) in c:\Users\Yellick
Chris\Documents\Visual Studio 2012\Projects\Antares\Antare
s\Program.cs:line 41

Wednesday, 25 September 2013

How To Create Multiple Hover Code

How To Create Multiple Hover Code

In Order To Understand This Question Go To This Picture
https://www.dropbox.com/s/obgvpejrzndttqb/9-25-2013%2010-16-50%20PM.png
Hey So This Is My First Time Asking A Question On {SO} So Im Hoping To Get
A Lot Of Feedback! I Was Wondering How To Code Up A Multiple Highlight
Hover Only Using Html Css And Well Of Course A php While Loop.
So In The Picture You Can See The Boxes(Friends Photos) And There Names On
The Right Sort Of Like a Year Book So the Way i Wanna Output This Is By
Fetching There Info From The Database And Using A While Loop To Out Put
The 2 Links the box(friendphotos) and name. But The Box Has To Be Inside A
Div On The Left And The Names On another Div On The Right.
Alright So This Is What I Wanna Know How Can I create Something Like The
Image So When I Hover Over There Name It Highlights There name and
Produces A Box Shadow on the box(photo) And Vice Versa. To Be More
Specific How Can I Create A Code Like This Using HTML And Css Inside a
While Loop Where The Box(friends PHoto) stays On The Left Side And The
Names Stay On The Right Side.
How Can I Create a Html Css Code That Does Multiple highlight On Hover
When I Hover The Name It Highlights The Name At The same Time The Box Gets
A shadow and Vice Versa.
How Can I Create A Code That Will Create Something Like The Image
How Can I Add That Code To A While Loop Where The Box(friendsPhoto) Will
Stay On the Left and Name On The Right without messing the layout .
Thanks In Advance I Will Really Appreciate A Good Answer Thanks Again.

Thursday, 19 September 2013

Finding if a number is equal to sum of 2 nodes in tree

Finding if a number is equal to sum of 2 nodes in tree

Here is my code that for this. I am traversing the whole tree and then
doing a find on each node. find() takes O(log n) and so the whole program
takes O(n log n) time.
Is there a better way to implement this program? I am not just talking of
better in terms of time complexity but in general as well. How best to
implement this?
public boolean searchNum(BinTreeNode node, int num) {
//validate the input
if(node == null) {
return false;
}
// terminal case for recursion
int result = num - node.item;
//I have a separate find() which finds if the key is in the tree
if(find(result)) {
return true;
}
return seachNum(node.leftChild, num) || searchNum(node.rightChilde, num);
}
public boolean find(int key) {
BinTreeNode node = findHelper(key, root);
if (node == null) {
return false;
} else {
return true;
}
}
private BinTreeNode findHelper(int key, BinTreeNode node) {
if (node == null) {
return null;
}
if(key == node.item) {
return node;
}
else if(key < node.item) {
return findHelper(key,node.leftChild);
}
else {
return findHelper(key,node.rightChild);
}
}

Entity Framework Many-to-Many relastionship update with detached entities

Entity Framework Many-to-Many relastionship update with detached entities

I'm trying to update a detached entity's relationship. Say, I've got
CarTypes table and Salesmen table. A salesmen can sell more then one type
of car and one type of car can be sold by more then one salesman. DB has a
linking table between CarTypes and Salesmen but EF generated only two
Entities. I'm trying to update some CarType properties as well as the
relationship to the Salesmen entity to redefine who can sell this car
type. A Salesman entity should stay unchanged. My CarType is defined
something like this
class CarType
{
Id {get;set;}
Name {get;set;}
.....
ICollection<Salesman> Salesmen {get;set;}
}
I attach the object like this:
db.CarTypes.Attch(carTypeToUpdate);
Mark each relevant property of carTypeToUpdate as modified like this:
db.Entry(carTypesToUpdte).Property("propertyName").IsModified = true;
and finally do
db.SaveChanges();
Everything is OK with normal properties. However, I can't figure out how
to update the relationships. I've tried to attach the Salesman object and
then do
db.Entry(carTypeToUpdate).Collection("Salesmen").CurrentValue =
myUpdatedList;
However, then objects defined in the list are added to the relationship,
but the old once are not removed. I was hoping then when you set
CurrentValue, it will override all entries. No such luck!
Please help!...

Unable to save a float value to a bitfield structure

Unable to save a float value to a bitfield structure

I have a structure
struct {
u32 var1 :7;
u32 var2 :4;
u32 var3 :4;
u32 var4 :1;
u32 var5 :4;
u32 var6 :7;
u32 var7 :4;
u32 var8 :1;
} my_struct;
my_struct struct1[10];
for(int i=0;i<10; i++)
{
// left some portion
struct1[i].var5= x;// where x is a float value retrieved from a
database with sqlapi++ asDouble()
cout<<"Value of x from db is:\t"<<x; // prints 0.1 if it is stored,
prints 2.4 if 2.4 is fed
cout<<"Value of x stored in struct1 is:\t"<<struct1[i].var5; //
prints 0 instead of 0.1, prints 2 instead of 2.4
}
I want to store floating point values like 0.1, 3.4, 0.8 in var5. But i am
unable to do so. Can somebody help me how could i fix this problem?

ldap search filter is not working

ldap search filter is not working

I want to get all members of a group.
$filter = "member=*";
$result = ldap_search($ldap_connection, GROUP_USER_ADMINS.",".BASE_DS,
$filter);
The base_dn is the complete dn of the group.
With this Filter, I get an array with much more informations, what I
hadn't planned.
I can use the
$entries = ldap_get_entries($ldap_connection, $result);
print_r($entries[0][members]);
to print the result with only all the members. But why the filter is not
working? I want only the members an not all informations about the group
like whencreated or the samaccounttype of the group.
Why the filter is not working?

To ::close() or to ::fclose()?

To ::close() or to ::fclose()?

We see a strange issue sometimes when we call boost::filesystem::copy() to
copy a file from a normal local partition to one hosted on Lustre.
Normally if we do cp of files we notice that the destination file exists
correctly and is available immediately after cp returns, however with the
boost operation, when it returns, the file may be all there or not (at the
destination.)
Looking through the boost code, I see:
if ( ::close( infile) < 0 ) sz_read = -1;
if ( ::close( outfile) < 0 ) sz_read = -1;
I'm wondering if this is correct, will this correctly flush the file to
the destination, or should this call ::fclose() to explicitly flush and
then close the file? I don't see any explicit ::fflush() calls preceding
the close, so not sure if the file really is flushed to the destination
correctly...

Symfony2 can't connect to remote database

Symfony2 can't connect to remote database

My web application (on ip 10.0.0.240) should connect to a remote database
(10.0.0.245)
parameters:
database_driver: pdo_mysql
database_host: 10.0.0.245
database_port: null
database_name: apps
database_user: apps
database_password: ******
I double check in config file i have :
doctrine:
dbal:
driver: %database_driver%
host: %database_host%
port: %database_port%
dbname: %database_name%
user: %database_user%
password: %database_password%
charset: UTF8
I took this settings from a existing application of mine working just
fine... but here I have constant error :
SQLSTATE[28000] [1045] Access denied for user 'apps'@'10.0.0.240' (using
password: YES)
If I try to connect from my local machine it works... I'v deploy my
project using capifony I'v check on current/app/confif/parameters.yml and
share/app/config/parameters.yml they are the same and they are good ...
Thanks

Wednesday, 18 September 2013

Search in datagrid using combo box

Search in datagrid using combo box

i have to search data from the text box in datagrid using c# My code is
private void button_Search_Click(object sender, EventArgs e)
{
sqlcon.Open();
//DataSet ds15 = new DataSet();
DataTable dt= new DataTable();
SqlDataAdapter adpt = new SqlDataAdapter("Select ColumName from TableName
where Field like '%{0}%'", comboBox_Search.Text);
adpt.Fill(dt);//datatable to catch the fields from the database
dataGridView1.DataSource = dt;
Getting error Arguement exception was unhandled
I want to search through combo box

Random asp.net Session Timeouts

Random asp.net Session Timeouts

Need some ideas on random asp.net Session Timeouts. Environment: - ASP.NET
3.5 Intranet Web App using Windows Authentication. - 1 Web Server - Web
Garden Configuration (multiple worker processes). There are multiple
automatic recycles done throughout the day based on memory limits set in
IIS for the app pool.
- Session State Mode : StateServer (using the asp.net State Service
running on the web server). THIS IS OUT OF PROCESS. - Session Timeout set
to 480 minutes in web.config. Out of 400+ users, there's seems to be a
small % that will frequently lose their session due to timeout. This
happens randomly throughout the day.
I'm pretty sure it's not due to the recycling. I can do an IISReset and
still keep working with the same session since the session state is kept
in the stateServer. As long as I don't restart that service, the session
sticks around.
One thing that came to mind is maybe the session cookie is not making it
to the web server, but not sure what would cause that scenario.
Been racking my brains on this. The configuration I have should allow
active sessions for 8 hours.
thanks in advance

Programming in C, Switch Case problems

Programming in C, Switch Case problems

#include <stdio.h>
int main(void)
{
char ch;
//character = ch
printf("Please type a character [A-Z or a-z] ('x'to exit):");
scanf("%c", &ch);
switch(ch) //switch statement
{
case 'a':
printf("%c is a vowel.\n", ch);
break;
case 'e':
printf("%c is a vowel.\n", ch);
break;
case 'i':
printf("%c is a vowel.\n", ch);
break;
case 'o':
printf("%c is a vowel.\n", ch);
break;
case 'u':
printf("%c is a vowel.\n", ch);
break;
case 'A':
printf("%c is a vowel.\n", ch);
break;
case 'E':
printf("%c is a vowel.\n", ch);
break;
case 'I':
printf("%c is a vowel.\n", ch);
break;
case 'O':
printf("%c is a vowel.\n", ch);
break;
case 'U':
printf("%c is a vowel.\n", ch);
break;
default:
if(ch != 'x'){
printf("%c is a consonant.\n", ch);
break; }
else if(ch == 'x'){
printf("%c is a consonant.\n", ch);
break; }
}
I have been having much trouble with this code. I have it perfect however
it needs to keep repeating until 'x' is entered. Tried a while loop,
couldn't have any luck, just recently tried the if statement in the
default, that doesnt work either. I'm so close if anyone could give me a
little insight!

JSON Object Casting Error with Facebook C# SDK for ASP.NET 3.5

JSON Object Casting Error with Facebook C# SDK for ASP.NET 3.5

I am using the Facebook C# SDK using ASP.NET 3.5 and I am getting a weird
error message for one of the calls from a sample code base provided here:
http://www.thepcwizard.in/2013/07/sample-app-using-facebook-c-sharp-sdk.html.
This example is an excellent walk-through of the basics using the Facebook
C# SDK for FB login code but I have this one issue that I can't seem to
figure out.
The error message is below:
Server Error in '/' Application.
Unable to cast object of type 'Facebook.JsonArray' to type
'System.Collections.Generic.IDictionary`2[System.String,System.Object]'.
Description: An unhandled exception occurred during the execution of the
current web request. Please review the stack trace for more information
about the error and where it originated in the code.
Exception Details: System.InvalidCastException: Unable to cast object of
type 'Facebook.JsonArray' to type
'System.Collections.Generic.IDictionary`2[System.String,System.Object]'.
Source Error:
**Line 271: var athletes = (IDictionary<string,
object>)me["favorite_athletes"];**
Line 272:
Line 273: foreach (var athlete in (JsonArray)athletes)
I have compiled the FB C# SDK version 3.5 as instructed and mostly
everything is working fine. I had to replace the dynamic types to var
types and cast them to IDictionary collections because ASP.NET 3.5 does
not support dynamic types. All good. Everything works great including the
friends list generation and display and all of my personal data being
called but the favorite athletes call is causing the error (code is
below). I think the issue lies in that fact that there is a "data"
variable called for the friends lists and this "data" variable is not
called for the athletes list. This is the only difference in how the JSON
object is returned from what I can see. The code sample seems to recognize
this by removing the "data" variable when the data is retrieved but still
no luck on the error.
The favorite athletes JSON data as it comes back from Facebook is below:
{
"favorite_athletes": [
{
"id": "14185406833",
"name": "Serena Williams"
},
{
"id": "61801828075",
"name": "Venus Williams"
},
{
"id": "386180624733248",
"name": "Robert Griffin III"
},
{
"id": "164825930120",
"name": "Tiger Woods"
},
{
"id": "363865183112",
"name": "Floyd Mayweather"
},
{
"id": "142603419139653",
"name": "Michael Vick"
},
{
"id": "64637653943",
"name": "LeBron James"
}
],
"id": "8723497347"
}
The friends list data as it is returned from Facebook is below (fake user
info for the purposes of this question because I do have far more than 4
friends :) ):
{
"id": "8723497347",
"friends": {
"data": [
{
"name": "Friend 1",
"id": "1234567"
},
{
"name": "Friend 2",
"id": "567965"
},
{
"name": "Friend 3",
"id": "9847634"
},
{
"name": "Friend 4",
"id": "100005000106091"
}
],
"paging": {
"next":
"https://graph.facebook.com/8723497347/friends?limit=5000&offset=5000&__after_id=100005000106091"
}
}
}
The code block that is throwing the error is below:
private void GetUserData(string accessToken)
{
var fb = new FacebookClient(accessToken);
var me = (IDictionary<string,
object>)fb.Get("me?fields=friends,name,email,favorite_athletes");
string id = (string)me["id"]; // Store in database
string email = (string)me["email"]; // Store in database
string FBName = (string)me["name"]; // Store in database
NameText.Visible = true;
NameText.Text = FBName;
ViewState["FBName"] = FBName; // Storing User's Name in ViewState
var friends = (IDictionary<string, object>)me["friends"];
foreach (var friend in (JsonArray)friends["data"])
{
ListItem item = new
ListItem((string)(((JsonObject)friend)["name"]),
(string)(((JsonObject)friend)["id"]));
FriendList.Items.Add(item);
}
var athletes = (IDictionary<string, object>)me["favorite_athletes"];
foreach (var athlete in (JsonArray)athletes)
{
SportsPersonList.Items.Add((string)(((JsonObject)athlete)["name"]));
}
Login.Text = "Log Out";
}
Any advice on this would be appreciated! Thanks in advance for your time.

Complete auto-correct upon pressing send

Complete auto-correct upon pressing send

I have a textview that I want to autocorrect the last word when a user
presses send. (similar to the message.app) Currently I am calling resign
firstResponder then immediately calling become firstResponder, in my
didTouchOnSend action.
[composeTextView resignFirstResponder];
[composeTextView becomeFirstResponder];
This method works, but only when I press the send button on the keyboard.
How can I get it to work on the send UIButton I created programmatically?

Returning pointer from a function in c

Returning pointer from a function in c

What's the problem with the following code
#include<stdio.h>
int main()
{
int *a=pointer_return();
}
int* pointer_return()
{
int a=10;
return &a;
}

Display twitter bootstrap progress bar in HTML email

Display twitter bootstrap progress bar in HTML email

We have a requirement of displaying progress bar in the HTML email sent as
a part of user notification. We use .NET. Is there any way to do this
through standard .NET code? Or is there any 3rd party component that can
be used to display progress bar in email clients(outlook/gmail etc.)?
Thanks JJ

Listbox datatemplate not working

Listbox datatemplate not working

I know i have made some silly mistake. But won't able to solve.
This is the xaml code:
<Border BorderBrush="Red" BorderThickness="3" Grid.Column="0" Grid.Row="0">
<toolKit:ListBoxDragDropTarget AllowDrop="True" >
<ListBox Height="85" Width="120">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="12233"
Foreground="AliceBlue"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</toolKit:ListBoxDragDropTarget>
</Border>
And the screen shot is :

Tuesday, 17 September 2013

Changing lables on x-axis like from Monday to show M as per window size in HighCharts

Changing lables on x-axis like from Monday to show M as per window size in
HighCharts

I am using highcharts library to draw chart and I need to display Weekdays
as labels on x-axis and also to auto reset it like from Monday to M if all
weekdays can't fit on screen.
It should be dynamic means no flickering should appear when changing label
text on x-axis.
Any suggestion..
Thanks in advance.

C#: Being thrown an IndexOutOfRangeException for an unknown reason

C#: Being thrown an IndexOutOfRangeException for an unknown reason

I'm fairly new to C#, and for some reason I'm being thrown an
IndexOutOfRangeException for a substring with the bounds of 0 and 0. I
don't think it's an issue with my scope as I've tested to make sure
everything is defined where it is used.
I'm trying to make a very simple anagram generator:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
string[] d = { "Apple", "Bass", "Cat", "Dog", "Ear", "Flamingo",
"Gear", "Hat", "Infidel", "Jackrabbit", "Kangaroo", "Lathargic",
"Monkey", "Nude", "Ozzymandis", "Python", "Queen", "Rat",
"Sarcastic", "Tungston", "Urine", "Virginia", "Wool", "Xylophone",
"Yo-yo", "Zebra", " "};
string var;
int len = 0;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var = textBox2.Text;
//textBox1.Text = d[2];
for (int y = 0; y <= var.Length; y++)
{
for (int x = 0; x <= d.Length; x++)
{
if (d[x].Substring(0, 0).ToUpper() ==
var.Substring(len, len).ToUpper())
{
textBox1.Text = textBox1.Text + "\n" + d[x];
len = len + 1;
}
}
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
}
}

Confusion with Constructors, Classes, and separate files

Confusion with Constructors, Classes, and separate files

I'm supposed to write a main program that prompts the user for a name and
initial balance. Your program should create two objects, one using the
default constructor and another using the constructor that allows the
user-entered name and balance to be used to initialize its object. Then
prompt the user for one amount to be credited to an account and one amount
to be debited. Use creditAccount to credit money to the object created
with the parameterized constructor and debitAccount to subtract the debit
amount from the object created with the default constructor. Use
displayBalance to display the balance in both objects. Repeat the cycle
above until the user enters an option to exit the program. I just don't
understand where to go from here to have it actually build and use the
class.
//My Account Program
//9/17/2013
#include <iostream>
#include <sstream>
#include <string>
#include "Account.h"
using namespace std;
int main()
{
float balance;
string CustomerName;
cout << "Your Account Machine" << endl;
cout << "Please enter your last name." << endl << endl;
cin >> CustomerName;
cout << "Please enter your account balance." << endl;
cin >> balance;
Account balance();
char exitchar; //Exit's the program.
cout << "\nPress any key and <enter> to exit the program.\n";
cin >> exitchar;
return 0;
}
Account.h
using namespace std;
class Account {
public:
Account();
float InitialBalance;
Account::Account(float balance)
{
SetInitialBalance(balance);
}
void SetInitialBalance(float balance)
{
if(balance >= 0)
InitialBalance = balance;
else
cout << "Error! Initial Balance cannot be less than 0." << endl;
}
float CreditAccount(float& balance)
{
float CreditInput;
cout << "Would you like to credit the account? Enter the amount
you would like to credit." << endl;
cin >> CreditInput;
balance = (CreditInput + balance);
}
float DebitAccount(float& balance)
{
float DebitInput;
cout << "Would you like to debit the account? Enter the amount you
would like to debit." << endl;
cin >> DebitInput;
balance = (balance - DebitInput);
if( balance < 0)
cout << "Debit amount exceeds account balance." << endl;
}
float DisplayBalance(float balance)
{
string CustomerName;
cout << "Customer Name: " << CustomerName << endl;
cout << "Account Balance: " << balance << endl;
}
};

neo4j batch-import node count

neo4j batch-import node count

i have a csv file with 1845554 lines, each representing a node, but using
the batch-import ( https://github.com/jexp/batch-import/ ) the result is
.........
Importing 924693 Nodes took 1270 seconds
Importing 3014 Relationships took 0 seconds
........
Total import time: 1286 seconds
[WARNING]
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:297)
at java.lang.Thread.run(Thread.java:724)
Caused by: org.neo4j.graphdb.NotFoundException: id=927736
all subsequent import fails due to the importer not finding all nodes...
any hints why ?
thank you.

Can not change font color of all elements within rows and columns in table tags

Can not change font color of all elements within rows and columns in table
tags

I am trying to change font color of different web elements in different
areas. Mostly it works fine while I am using I am using like this:
<font color='BLUE'>
<DIV>
<SPAN style="WHITE-SPACE: normal; TEXT-TRANSFORM: none; WORD-SPACING: 0px;
FLOAT: none; : rgb(34,34,34); FONT: 13px Calibri;
-webkit-text-size-adjust: auto">
</SPAN>
</DIV>
<DIV>
<SPAN style="BORDER-TOP- : ; WHITE-SPACE: normal; TEXT-TRANSFORM:
none; WORD-SPACING: 0px; FLOAT: none; : rgb(0,0,0); FONT: large
arial, sans-serif; -webkit-text-size-adjust: auto">abc
</SPAN>
</DIV>
</font>
or just
<font color='BLUE'>
<P>abc
</P>
</font>
BUT when I am trying to change font color and formation of some text
elements which are under tags, it dorsn't work!
<font color='white'>
<DIV>
<TABLE style="WIDTH: 165pt; BORDER-COLLAPSE: collapse; border=0
cellSpacing=0 cellPadding=0 width=219>
<COLGROUP>
<COL style="WIDTH: 21pt; mso-width-source: userset; mso-width-alt:
1024" width=28>
<COL style="WIDTH: 92pt; mso-width-source: userset; mso-width-alt:
4498" width=123>
<TBODY>
<TR style="HEIGHT: 66pt; mso-height-source: userset" height=88>
<TD style="BORDER-BOTTOM: #ece9d8; BORDER-LEFT: #ece9d8;
- : transparent; WIDTH: 165pt; HEIGHT: 66pt; BORDER-TOP:
#ece9d8; BORDER-RIGHT: #ece9d8" class=xl65 height=88 width=219
colSpan=4><FONT size=2 face=Calibri>Students, if you are looking
for opportunities to earn community service hours, please check
out the guidance board located at the south entrance of the high
school hallway.</FONT>
</TD></TR>
<TR style="HEIGHT: 107.25pt; mso-height-source: userset" height=143>
<TD style="BORDER-BOTTOM: #ece9d8; BORDER-LEFT: #ece9d8;
- : transparent; WIDTH: 165pt; HEIGHT: 107.25pt; BORDER-TOP:
#ece9d8; BORDER-RIGHT: #ece9d8" class=xl65 height=143 width=219
colSpan=4>
<FONT size=2 face=Calibri>There will be sign up meetings for
winter sports in the gym during break next week. <BR>All students
interested in playing soccer, please sign-up in the gym during
break tomorrow.<BR>Students wanting to play basketball, please
sign-up on Thursday, 9/19.
<SPAN style="mso-spacerun: yes">&nbsp;
</SPAN><BR><BR></FONT></TD></TR>
</TBODY>
</TABLE>
</DIV>
</font>
Please suggest me what should I do if I want to keep generic rule to
change font colors for all sort of formats.

Sunday, 15 September 2013

What is the Entity Key for in the Datastore Viewer?

What is the Entity Key for in the Datastore Viewer?

I am new to Google App Engine, Python and NoSQL.
While browsing the Datastore Viewer I noticed that there is a key labelled
"Key" in the list view, and "Entity Key" in the single entity edit view,
which is generated automatically.
What is it for? Should I use this to identify my entities? Or should I
just ignore it? Is it an internal key used by App Engine?
Any light shed on this would be much appreciated!
Thanks

Submitting using check box

Submitting using check box

Hi I have following check box and a button. I want to check the box and
than call a function when the button is clicked using jquery.
<form id="rollUpForm" >
<table id="testing" class="" border="1" cellpadding="0"
cellspacing="0">
<tr>
<td>
<td> <label class="" for="_person" >Person</label></td>
<td> <input type="checkbox" class="_person"
id="rollUPForm_vendor" name="person"/></td>
<td><input type="button" id="personList" class=""
value="Search" /></td>
</tr>
</table>
</form>
$(document).ready(function () {
$("#vendorList").click(function () {
if ($("input:checkbox:checked").val() = "vendor") {
fnloadlist();
}
});
});
When I run using firebug. It gives error "ReferenceError: invalid
assignment left-hand side" at if statement. I tried few different things
but nothing seem to work. Please help as I am new to jquery. Thanks

Resizing custom user control according to data in the webBrowser control docked in it

Resizing custom user control according to data in the webBrowser control
docked in it

I have a webBrowser control named webBrowser1 that is added and docked as
DockStyle.Full on a custom user control. The web-browser accepts some HTML
text dynamically and displays it. I disabled the scroll bars of the
webBrowser control. My problem is that whenever the content is somewhat
lengthy, the webBrowser hides it from below. But the requirement of my
project objective is that the webBrowser must not show either scroll bars
or it should not hide some of the content. The content must be completely
shown as it is without scrolling. That means the user control on which the
webBrowser is docked must resize iteself according to webBrowser's
content. So, can anyone please suggest me how to achieve this? I searched
all over the internet and SO but found nothing.

MySQLi speed: multiple queries or one

MySQLi speed: multiple queries or one

I want to get data from a database which looks like this:
id - brand - type
1 Airbus plane
2 Boeing plane
3 Fokker plane
4 Toyota car
5 Mustang car
6 Peugeot car
7 Sparta bike
Now I want to e.g. output an <hr/> whenever the type is different. I can
do this two ways:
One prepared statement and set a variable $current_type and check its
value with the one from the database
Three prepared statements (for each type since they don't differ from
plane, car, bike)
Which is the fastest? I would say the first but the second makes my code
look so much better. Can I neglect the speed difference?

Drag and drop object with text field in Android

Drag and drop object with text field in Android

I am working on a project that enables a user to create a UML Class
diagram (for database design) and outputs a MySQL script in android. I
can't seem to find a way to implement a draggable text area in a generic
View only. My plan is to create an object that contains two textfields (1
for the class name and the other for the attributes)everytime the user
cicks on the New button. Your thoughts? Thank you.

Get a dropbox url from the command line not working on windows

Get a dropbox url from the command line not working on windows

I have was researching how to get share link of any dropbox folder
installed on my machine. I do not want to write code with AppKey and
Secret key. I want to make use of existing dropbox APIs. I have found one
thread where questioner is able to get share link.
Get a dropbox url from the command line
When I tried the same command, I am getting error as ""Dropbox Daemon is
not installed!".
I am using Windows 7 64 bit.
Please help.
Thanks!

var m=" setVisibility ( ' " + objID +" ' , false ) ";

var m=" setVisibility ( ' " + objID +" ' , false ) ";

pls, help me... I am new in javascript, so I can not understand the
meaning of ' " + objID +" ' then comes this.
timer[objID]=setTimeout(m,150);
Here is all the code. If needed you could copy/paste it in your editor to
see the result. Thanks
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>TEXT</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css"> **/*the css */**
html, body { margin: 0px; padding: 0px; }
h1 { margin-top: 30px }
#menu a, .subMenu a {
display: block;
font-family: Arial, sans-serif;
font-size: 10pt;
font-weight: bold;
text-decoration: none;
color: black;
border: 1px solid #ddd;
}
#menu a:hover, #menu a:active, .subMenu a:hover, .subMenu
a:active {
background-color: #eee;
border-color: #999;
}
#menu {
background-color: #ddd;
position: absolute;
top: 0px;
left: 0px;
width: 100%;
}
#menu a {
width: 100px;
float: left;
margin-left: 5px;
padding: 2px;
}
.subMenu {
width: 150px;
top: 26px;
background-color: #ddd;
border: 1px solid black;
position: absolute;
visibility: hidden;
}
.subMenu a {
display: block;
width: 90%;
margin: 0px;
padding: 4px;
}
#subMenu1 { left: 5px }
#subMenu2 { left: 125px }
#subMenu3 { left: 230px }
</style> **/*the css ends*/**
<script type="text/javascript">
var timer= new Object();
**/* this func. sets the visibility
of hidden menus which appear by
"onmouseover"*/**
function setVisibility(objID, visible){
var obj=document.getElementById(objID);
if(obj.style.visibility=visible){
obj.style.visibility="visible";
}
else{obj.style.visibility="";}
}
**/* this one calls the func. above
if needed to show the hidden
menu*/**
function showMenu(objID)
{ setVisibility(objID,true);
clearTimeout(timer[objID]);
}
**/*this one hides by onmouseout putting false boolean in func.
setVisibility "visible" parameter*/**
function hideMenu(objID)
{
var m="setVisibility('"+objID+"',false)";
timer[objID]=setTimeout(m,150);
}
</script>
</head>
<body>
<h1>Text</h1>
<div id="menu">
<a href="#"
onmouseover="showMenu('subMenu1')"
onmouseout="hideMenu('subMenu1')">Module 1</a>
<a href="#"
onmouseover="showMenu('subMenu2')"
onmouseout="hideMenu('subMenu2')">Module 2</a>
<a href="#"
onmouseover="showMenu('subMenu3')"
onmouseout="hideMenu('subMenu3')">Module 3</a>
</div>
<div id="subMenu1" class="subMenu"
onmouseover="showMenu('subMenu1')"
onmouseout="hideMenu('subMenu1')">
<a href="../module1/statements/for-1.html">Text</a>
<a href="../module1/statements/if-1.html">Text</a>
<a href="../module1/statements/switch.html">Text</a>
</div>
<div id="subMenu2" class="subMenu"
onmouseover="showMenu('subMenu2')"
onmouseout="hideMenu('subMenu2')">
<a href="../module2/objects/build-in/array.html">Text</a>
<a href="../module2/objects/build-in/boolean.html">Text</a>
<a href="../module2/objects/build-in/date.html">Text</a>
<a href="../module2/objects/build-in/global-object.html">Text</a>
<a href="../module2/objects/build-in/math.html">Text</a>
<a href="../module2/objects/build-in/number.html">Text</a>
</div>
<div id="subMenu3" class="subMenu"
onmouseover="showMenu('subMenu3')"
onmouseout="hideMenu('subMenu3')">
<a href="../module3/document.html">Text</a>
<a href="../module3/history.html">Text</a>
<a href="../module3/location.html">Text</a>
<a href="../module3/navigator.html">Text</a>
</div>
</body>
</html>

Saturday, 14 September 2013

change css rule by input range

change css rule by input range

Can I change elem's css rule by input range without js? Like this:
<input type="range" min="0" max="100">
<span>Some text</span>
input[vlaue="0"]+span {background:red;}
input[vlaue="50"]+span {background:green;}

Iframe Communication Checkbox Values

Iframe Communication Checkbox Values

On the parent page, I have a series of checkboxes like below:
<input type="checkbox" class="parlay" value=1>
<input type="checkbox" class="parlay" value=2>
<input type="checkbox" class="parlay" value=3>
On a certain event I pop an iframe, and need to get the values for all the
checkboxes which are "checked" on the parent page. Can someone point me to
a jQuery or Javascript approach for this problem?
Thanks much

Exclude Context Item from Sitecore Lucene Search Results

Exclude Context Item from Sitecore Lucene Search Results

The Problem:
I'm trying to build a related items functionality but I'm picking up the
context item in my results as well.
The Implementation:
I'm trying to use a FieldSearchParam to exclude a list of items from results:
var fieldParam = new FieldSearchParam()
{
Condition = QueryOccurance.MustNot,
FieldName = BuiltinFields.ID,
FieldValue = item.ID.ToString().Replace("{", "").Replace("}",
"").Replace("-", "").ToLower() + "~",
};
Believe me, I'm aware how nasty that FieldValue is, but the index doesn't
hold the standard Sitecore Item GUID format.
The Question:
First of all, is there a better way to format the item guid for lucene
comparison? This implementation wouldn't even cover different languages.
Secondly, why aren't my items getting excluded?

Create a user-defined gap between two Bootstrap columns

Create a user-defined gap between two Bootstrap columns

I want to create little panels/dashboard for my interface. In my case I
want to have two panels like so
+-------------------------------+ +-------------------------------+
| | | |
| | | |
+-------------------------------+ +-------------------------------+
Generally it is easy with Bootstrap 3.
<div class="row">
<div class="col-md-5">
</div>
<div class="col-md-5 pull-right">
</div>
</div>
The problem is, the gap of col-md-2, as it is the case here, is way too
big. I cannot use a col-md-1 gap, because then both sides do not have an
equal size.
I also tried to add padding right and left, but that had not effect, too.
What can I do here?

Using GIT to deploy website

Using GIT to deploy website

I have followed this excellent write up
http://toroid.org/ams/git-website-howto to deploy code to my server using
Git's post-hooks strategy.
I have a post-update file that looks like this:
GIT_WORK_TREE=/home/rajat/webapps/<project name> git checkout -f
Everytime I push code to master branch, it gets auto deployed. What I want
to do now is to make this support multiple branches, so that:
git push origin master -----> deploys code to production
(/home/rajat/webapps/production)
git push origin staging ----> deploys code to staging
(/home/rajat/webapps/staging)
git push origin test ----> deploys code to test (/home/rajat/webapps/test)
For this, the post-update hook needs to understand which branch got
updated. Is this possible ?

jquery form plugin in wordpress to upload an image file does not work as expected

jquery form plugin in wordpress to upload an image file does not work as
expected

Trying to use the jquery form plugin in a worpress site .
HTML:
<form id="imageform" method="post" action="<?php
bloginfo('template_directory')?>/ajaximage.php "
enctype="multipart/form-data" accept-charset="utf-8" >
Upload image:
<input type="file" name="photoimg" id="photoimg" value="" />
</form>
<button value="&nbsp;Upload&nbsp;"
class="btn_upload">&nbsp;Upload&nbsp;</button>
<div id='preview'></div><!-- end of id preview-->
JS:
$(document).ready(function(){
$(".btn_upload").click(function(){
$("#preview").html('');
$(".result_upload").html('<img src="'+loc+'/images/ajax-loader.gif"
alt="wait.."/>');
$("#imageform").ajaxForm({
target: '#preview'
}).submit();
});
});
ajaximage.php has
$photoimg = trim($_POST['photoimg']);
echo 'got it';
If I do not select any file , I get the result as expected. But if I
select an image file then the error message says - "Undefined index:
photoimg in line ...."
How to make it work correctly?

iPhone - How to convert .caf audio files into .aac?

iPhone - How to convert .caf audio files into .aac?

I am working on audio recording. I am able to record my audio in caf (Core
audio format). Now I want to record sound in aac.I'm developing an iphone
app that records audio, right now it records caf files, I need to convert
these files to aac... any idea how to do this?

Rails 4, ActiveRecord. Join table and select by different records of one model of joined table

Rails 4, ActiveRecord. Join table and select by different records of one
model of joined table

Models:
class Option < ActiveRecord::Base
belongs_to :estate
belongs_to :metric
...
end
class Estate < ActiveRecord::Base
belongs_to :category
has_many :options, :dependent=>:destroy
...
end
class Category < ActiveRecord::Base
has_many :estates, :dependent=>:destroy
has_many :metrics, :dependent=>:destroy
...
end
class Metric < ActiveRecord::Base
belongs_to :category
has_many :options, :dependent=>:destroy
...
end
I can find Estate with given params of option by:
Estate.where(bla: 'bla-bla').joins(:options).where('options.metric_id=?
and options.field1=?', 1,'bla-bla')
But each Estate has many Options, how can i select Estate with one value
of one option and second value of another option by sql or ActiveRecord,
like:
Estate.where(bla: 'bla-bla').to_a.
select{|x| x.options.exists?(metric_id: 1, field1: 'value1')
&& x.options.exists?(metric_id: 2, field1: 'value2')}

Friday, 13 September 2013

MediaPlayer streaming mp3, get jibberish

MediaPlayer streaming mp3, get jibberish

I was thinking of a shortcut to get Chinese TTS working. I'm using
MediaPlayer to stream Google Translate Text-to-Speech generated mp3's.
When I use to englishToSpeech method, the audio plays back perfectly.
However, when I use my hanziToSpeech(Chinese) method, the audio plays back
with jibberish Chinese. I suspect the jibberish occurs due to the time it
takes Google Translate to generate an mp3.
For example,
http://translate.google.com/translate_tts?tl=zh-cn&q=%E4%B8%89%E5%8F%B7%E6%80%8E%E4%B9%88%E6%90%9E%E7%9A%84
Google generates a mp3 in Chinese. It takes a little bit. I suspect that
the MediaPlayer is buffering the audio before its actually done being
generated. It works perfectly fine with English, probably because
generating English mp3s is quick.
It also got some errors which I posted.
public static void hanziToSpeech(String input)
{
String translateURL =
"http://translate.google.com/translate_tts?tl=zh-cn&q=" + input;
Sound.playURL(translateURL);
}
public static void englishToSpeech(String input)
{
String translateURL =
"http://translate.google.com/translate_tts?tl=en&q=" + input;
Sound.playURL(translateURL);
}
public static void playURL(String url)
{
MediaPlayer mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mp.setDataSource(url);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
mp.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mp.start();
}
TextToSpeech.englishToSpeech(english);
TextToSpeech.hanziToSpeech(chinese);

09-13 23:50:31.049: V/ChromiumHTTPDataSource(39): connect on behalf of uid
10044 09-13 23:50:31.049: I/ChromiumHTTPDataSource(39): connect to
http://translate.google.com/translate_tts?tl=zh-cn&q=http://translate.google.com/translate_tts?tl=zh-cn&q=ÈýºÅÔõô¸ãµÄ£¬°ÑÇòÈÃÈ˼ҶӸøÇÀ×ßÁË¡£
@0 09-13 23:50:31.389: E/WVMExtractor(39): Failed to open libwvm.so 09-13
23:50:31.400: I/NuCachedSource2(39): ERROR_END_OF_STREAM 09-13
23:50:32.440: D/AudioSink(39): bufferCount (4) is too small and increased
to 12

Xcode 4.6.3 Storyboard Class and Subclass Reference

Xcode 4.6.3 Storyboard Class and Subclass Reference

I this this following stuff:

And I have create a new Objective-C category


And after all on Identify inspector I have defined the Custom Class as
MyScrollView

And when app start on iOS Simulator I received this message:
Unknown class MyScrollView in Interface Builder file.
This approach can be used to implement ViewController, but is not working
to nested classes. Have any solution for this case?

cut a sprite sheet on cocos2d for animation

cut a sprite sheet on cocos2d for animation

Hi I want to cut a sprite in 6 equivalent part just with one image, a .png
file wich I find on the web, no with texturepacker, (the image below by
example)
I can take other way but I want to know if I can do that. any one haves idea?

How to add url link in css file?

How to add url link in css file?

Is it possible to add url link inside of css code? I searched all
websites, but I couldn't find correct answer, I'm looking for something
like this following example:
<style type="text/css">
.example a:link {
text-decoration: none;
href="http://www.yourdomain.com/";
}
</style>
and html code something like this:
<div class="example"> Text for url hyperlink </div>
Is it possible like this? cause I can't use usual html code in my page,
cause of some reason of codes, I have to use another way to insert url to
texts and images files.
I mean, I can't use like this following way, I need another way.
<a href="http://www.yourdomain.com/">Text</a>
Thanks in advance.

How to changed Country Label

How to changed Country Label

I want to ask how can i changed the country label. I want to display
bharat instead of india to the users.
I want to changed label only....when users select country from dropdown
list then bharat will display instead of india.

Thursday, 12 September 2013

JQuery API Doc generator for typescript custom Widget?

JQuery API Doc generator for typescript custom Widget?

I have some custom typescript Widget have to create a API doc for that. I
have searched a lot but i didn't find anything useful. Is there is any
tool for generate a API doc like Jquery API
Note: I have used Natural Docs for my jquery custom widget, but i can't
use it in typescript custom widget. Is there any way to use that for
typescript.
Any suggestions should be appreciated....

Why can't I expand this event object in the chrome console?

Why can't I expand this event object in the chrome console?

Simplified, what I'm doing is running this in the console:
window.onbeforeunload = function (e) {
var e = e || window.event;
if (e) {
console.log(e);
}
}
But in the console, when the event fires (by trying to "leave page" in the
middle of writing an SO question) what I see is this:
Event {clipboardData: undefined, cancelBubble: false, returnValue: true,
srcElement: document, defaultPrevented: false…}
With a little "i" graphic next to it. When I click the arrow next to it to
expand the object in the console, nothing happens. The arrow turns to
indicate that it has expanded, but it doesn't expand.
What am I missing here??

Id jump urls behaving weirdly

Id jump urls behaving weirdly

I have an id jump (is there a better word for it?) to
http://brianjblair.com/music/compositions/#j2
I have noticed that sometimes it doesn't go down to the id (stays at top
of page). I have never seen it work when going from an a tag. It works
sometimes when typed directly into the url box. Reload will not change the
position.
I think it has to do with me changing positions of things before the page
completely loads, with setTimeout.
How do I make it work reliably?

Using a function from Matlab with Excel

Using a function from Matlab with Excel

Im having a little problem trying to run a function from Matlab in
EXcel... I have tried the solution I found in another post using some kind
of sub but it doesnt work everytime...
I would like to try a shell, but I cant find proper information about how
to use it (im a little bit of a dummy...)
So please, could anybody explain me how to use it?
Thanks!

How to permit running two copies of one postgresql pl/sql function

How to permit running two copies of one postgresql pl/sql function

I have heavy pl/sql postgres function. How to permit starting another copy
of this function.

ArgumentError (wrong number of arguments (3 for 0..1)):

ArgumentError (wrong number of arguments (3 for 0..1)):

This is my model:
class User < ActiveRecord::Base
has_many :appointments
has_many :doctors, :through => :appointments
end
class Doctor < ActiveRecord::Base
has_many :appointments
has_many :users, :through => :appointments
end
class Appointment < ActiveRecord::Base
belongs_to :doctor
belongs_to :user
end
Code to call controller action:
$.ajax({
type: "POST",
url: "/create",
data: {
appointment_date: date,
hairdresser_id: "1",
user_id: "1"
}
// Etc. });
Action:
def create
@appointment = Appointment.new(:appointment_date, :doctor_id, :user_id)
if @appointment.save
flash[:success] = "Welcome to the Baxter!"
redirect_to @user
else
alert("failure!")
end
And I got this error:
ArgumentError (wrong number of arguments (3 for 0..1)):
How to handle this error? Any advice? Thanks.

GWT:make text limit on RichTextArea and stop user enter more characters

GWT:make text limit on RichTextArea and stop user enter more characters

I am using GWT RixhText Area and want to put a limit on 100 characters in
the richText Area .
right now i am doing this .
description.addKeyDownHandler(new KeyDownHandler(){
@Override
public void onKeyDown(KeyDownEvent event) {
if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER ||
event.getNativeKeyCode() == KeyCodes.KEY_UP ||
event.getNativeKeyCode() == KeyCodes.KEY_LEFT||
event.getNativeKeyCode() == KeyCodes.KEY_DOWN ||
event.getNativeKeyCode() == KeyCodes.KEY_BACKSPACE||
event.getNativeKeyCode() == KeyCodes.KEY_SHIFT) {
}else{
if(description.getText().trim().length()>100){
Window.alert("You have reached your maximum limit");
}
}
}});
Now when 100 characters reached it works fine, give me the alert but how
can i stop user from entering more characters , it shows the alert but
also takes the input .. how to stop this ..
Secondly I am using this css below to move to the next line itself when
area ends.. it works fine .. but if a user just hold down the key on
keyboard and don't release this css doesn't works , not taking to next
line and goes on .. is there a solution for this
CSS:
break-word {
white-space: pre-wrap; /* css-3 */
white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
word-wrap: break-word; /* Internet Explorer 5.5+ */
}
thanks

Wednesday, 11 September 2013

async and await return type confusion

async and await return type confusion

Hello friends i wanted to know the affects of return type of some async
method on its behavior like i have one method called methodasync1() like
private async void methodasync1(filename)
{
await getfileaysnc(filename);
}
and other function methodasync2() like
private async Task methodasync2(filename)
{
await getfileasync(filename);
}
are both functions work in same way or there is any difference. and also
any concept i should know plz tell me any idea and help is appreciated

how a positive value becomes negative after casting?

how a positive value becomes negative after casting?

public class Test1 {
public static void main(String[] args) {
byte b1=40;
byte b=(byte) 128;
System.out.println(b1);
System.out.println(b);
}
}
the output is
40 -128
the first output is 40 I understood but the second output -128 How it is
possible ? is it possible due to it exceeds its range ? if yes how it
works after byte casting...help me

Bash script trouble with comparing strings

Bash script trouble with comparing strings

I'm trying to compare strings. I get "command not found" error. How do I
compare the strings?
Code:
#!/bin/bash
STR="Hello World"
if [$STR="Hello World"]; then
echo "passed test"
else
echo "didn't pass test"
fi
Output:
test.sh: line 4: [Hello: command not found
didn't pass test

How to have an href process in an iframe (colorbox) after running a php script?

How to have an href process in an iframe (colorbox) after running a php
script?

What I am trying to figure out is how to have a link open in an iframe
(using colorbox) after a php script has been fully processed. The reason I
need to have the link load after the php script is that in php script I
generate a png image from a canvas element on the page. This image is then
used as the image on the subsequent page.
The issue I have been having is that if the link opens prior to the
completion of imagesave script the link will not function correctly (ie
the image will not appear (first time clicked) or the last image saved
will appear rather then the intended image).
I am using Jquery and Colorbox on the page. The javascript passes the
variables to the php which stores them in a session.
My HTML on the main page is as follows:
<script>
$(document).ready(function(){
$(".share").colorbox({iframe:true, width:"80%", height:"80%"});
});
</script>
<canvas id="YourYogaMatCanvas" width="888" height="288" >Your browser
does not support the HTML5 canvas tag.</canvas><br/>
<a href="featureshare" class="share" id="sharing"
onclick="savetoserver();">Share Your Creation Now</a><br/><br/>
JavaScript:
function savetoserver() {
canvas = document.getElementById('YourYogaMatCanvas');
var dataURL = canvas.toDataURL();
var dataURL2 = canvas.toDataURL();
do {
dataURL = canvas.toDataURL();
dataURL2 = canvas.toDataURL();
$.ajax({
type: "POST",
url: "featureimagesave.php",
data: {
imgBase64: dataURL,
yogatextcolor: txtcolorsel,
yogamatcolor: selmatcolor,
prefile: prefile,
name: matname,
price: priceCalc
},
});
}while (dataURL != dataURL2);
}
PHP featureimagesave:
<?php
session_start();
// requires php5
define('UPLOAD_DIR', 'images/users/');
$img = $_POST['imgBase64'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$filename = uniqid();
$file = UPLOAD_DIR . $filename . '.png';
$success = file_put_contents($file, $data);
$_SESSION['file'] = $filename;
$_SESSION['textcolor'] = $_POST['yogatextcolor'];
$_SESSION['matcolor'] = $_POST['yogamatcolor'];
$_SESSION['featurefile'] = $_POST['prefile'];
$_SESSION['name'] = $_POST['name'];
$_SESSION['price'] = $_POST['price'];
?>
HTML on featureshare page the $Session variable file is used to reference
the image as follows:
<?php
echo '<div id="uimage"><img id="userimage"
src="images/users/'.$_SESSION['file'].'.png"> </div>';
?>
Any help or an idea of how to make this work would be greatly appreciated.
I do have session start on every page prior to the HTML tag.

ArgumentError: odd number of arguments for Hash when trying to connect to redis

ArgumentError: odd number of arguments for Hash when trying to connect to
redis

I'm trying to get rails connect to redis by following this tutorial. But
I'm getting the following error when I try $redis = Redis.new(:host =>
'localhost', :port => 6379) or even just Redis.new. I've tried the new
notation as well (host: 'localhost',port: 6379). Redis works (ping-PONG
test via redis-cli passes).
ArgumentError: odd number of arguments for Hash
from /var/lib/gems/1.9.1/gems/redis-2.1.1/lib/redis.rb:65:in `[]'
from /var/lib/gems/1.9.1/gems/redis-2.1.1/lib/redis.rb:65:in `info'
from /var/lib/gems/1.9.1/gems/redis-2.1.1/lib/redis.rb:606:in `inspect'
from
/var/lib/gems/1.9.1/gems/railties-4.0.0/lib/rails/commands/console.rb:90:in
`start'
from
/var/lib/gems/1.9.1/gems/railties-4.0.0/lib/rails/commands/console.rb:9:in
`start'
from
/var/lib/gems/1.9.1/gems/railties-4.0.0/lib/rails/commands.rb:64:in
`<top (required)>'
from bin/rails:4:in `require'
from bin/rails:4:in `<main>'
What am I doing wrong?
Config Details:
$ ruby -v
ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-linux]
$ rails -v
Rails 4.0.0

CSS Gradient Diagonal Striped Background Misalignment

CSS Gradient Diagonal Striped Background Misalignment

I have created a SCSS mixin based on the Bootstrap LESS mixin that will
create a diagonally striped background. However, no matter how big I make
the "tile" for the stripe, there always seems to be a 1px mis-alignment.
I'm guessing that it has something to do with sub-pixel calculations, but
I'm wondering if someone can point me in the right direction.
http://codepen.io/allicarn/pen/ncHod
Another goal would be to modify the angle and have it work, but that's
just bonus points ;)

Why does Chrome sometimes logs only the preflight request (and not the actual GET) when using CORS?

Why does Chrome sometimes logs only the preflight request (and not the
actual GET) when using CORS?

The GET request completes successfully but I cannot inspect the response.
This occurs randomly in some of the endpoints of my api.
Firefox always logs the response.

How to use LINQ with dynamic collections

How to use LINQ with dynamic collections

Is there a way to convert dynamic object to IEnumerable Type to filter
collection with property.
dynamic data = JsonConvert.DeserializeObject(response.Content);
I need to access something like this
var a = data.Where(p => p.verified == true)
Any Ideas?