Saturday, 31 August 2013

CSS header with div to left which fills screen

CSS header with div to left which fills screen

Ok so I am trying to make a header div that is centered on the based that
the site
content div is 980px; width
But what I want is that if the screen is bigger on the left there is a Div
that is linked to the header that take the background color of the header
and pulls it to the left side of the users screen while keeping the header
in the center of the page.
my code
html,body{
margin:0;
padding:0;
}
#content,.content{
margin:0 auto;
width: 980 !important;
}
#header-nav{
width:100% !important;
height:60px !important;
padding:0;
margin:20px 0;
}
.nav-left{
height: 55px;
position: absolute;
top: 30px;
z-index: 6;
margin: 0;
padding: 0;
right: 60%;
width: 5000px;
background: #cb0f32;
border: none;
-webkit-box-shadow: 1px 1px 2px rgba(0, 0, 0, 0.3);
-moz-box-shadow: 1px 1px 2px rgba(0, 0, 0, 0.3);
box-shadow: 1px 1px 2px rgba(0, 0, 0, 0.3);
filter: none;
}
.content{
position:absolute;
top:30px;
left:25%;
z-index: 7;
margin:0 auto;
width:980px !important;
background:#000;
}
HTML Code
<body>
<div id="header-nav">
<div class="nav-left">
</div>
<div id="content" class="content">
<div id="nav-bar">
<p>My Site Title</p>
</div>
</div>
</div>
I know this should be easy but I can't get it to work could anyone please
point me in the right direction
demo of code http://russellharrower.com/home?preview=1

c# If else statement with case insensative

c# If else statement with case insensative

I have this if else statement which is assigned to compare results from a
text box to a list of context. I am wondering how do i make it such that
it is case insensitive ?
value = textbox1.Text;
if (article.contains(value))
{
label = qwerty;
}
else
{
break;
{

Getting Screen Positions of D3 Nodes After Transform

Getting Screen Positions of D3 Nodes After Transform

I'm trying to get the screen position of a node after the layout has been
transformed by d3.behavior.zoom() but I'm not having much luck. How might
I go about getting a node's actual position in the window after
translating and scaling the layout?
mouseOver = function(node) {
screenX = magic(node.x); // Need a magic function to transform node
screenY = magic(node.y); // positions into screen coordinates.
};
Any guidance would be appreciated.

summary table with total whilst controlling for value on one variable?

summary table with total whilst controlling for value on one variable?

I've used function summary(data[data$var1==5,]) to get a summary of
observations while the variable of interest equals 5 (or whatever).
However, I also need a total for a particular var2 as well, and I'm unsure
how to go about coding that in here whilst keeping the variable that I
want controlled at 5 (or whatever).
I'm quite happy writing a second line looking for the total of var2 whilst
controlling var1. Any help would be appreciated, thanks.

how to display elements of json array returned from php within a loop in ajax(jquery)

how to display elements of json array returned from php within a loop in
ajax(jquery)

Below ajax code is receiving a json array from php. Rest details i have
written as comments:
$.ajax({
type: "POST",
url: "dbtryout2_2.php",
data:datastr,
cache: false,
//dataType: 'json',
success: function(arrayphp)
{
//"arrayphp" is receiving the json array from
php.
//below code is working where iam displaying
the array directly
//This code displays the array in raw format.
$(".searchby .searchlist").append(arrayphp);
}
});
But when iam trying to display the elements of the array seperately using
below code ,then it is not working:
$.ajax({
type: "POST",
url: "dbtryout2_2.php",
data:datastr,
dataType: "json",
cache: false,
contentType: "application/json",
success: function(arrayphp)
{
//nothing is getting displayed with this code
$.each(arrayphp,function(i,v){
alert(i+"--"+v);
});
}
});
WOULD ANYBODY FIGURE OUT WAT THE PROBLEM IS WITH MY CODE?

Libgdx Make Lights Ignore Bodies

Libgdx Make Lights Ignore Bodies

I have a libgdx game in the works with Box2d and Box2d Lights.
My questions is how do I get Bodys / Bodydefs to ignore the light source
from a Box2d Light and not cast shadows?
Thanks.

Simple bit setting and cleaning

Simple bit setting and cleaning

I'm coding an exercise from a book. This program should set a "bitmapped
graphics device" bits, and then check for any of them if they are 1 or 0.
The setting function was already written so I only wrote the test_bit
function, but it doesn't work. In the main() I set the first byte's first
bit to 1, so the byte is 10000000, then I want to test it: 1000000 &
10000000 == 10000000, so not null, but I still get false when I want to
print it out. What's wrong?
#include <iostream>
const int X_SIZE = 32;
const int Y_SIZE = 24;
char graphics[X_SIZE / 8][Y_SIZE];
inline void set_bit(const int x, const int y)
{
graphics[(x)/8][y] |= (0x80 >> ((x)%8));
}
inline bool test_bit(const int x, const int y)
{
if(graphics[x/8][y] & (0.80 >> ((x)%8)) != 0)
return true;
else return false;
}
void print_graphics(void) //this function simulate the bitmapped graphics
device
{
int x;
int y;
int bit;
for(y=0; y < Y_SIZE; y++)
{
for(x = 0; x < X_SIZE / 8; x++)
{
for(bit = 0x80;bit > 0; bit = (bit >> 1))
{
if((graphics[x][y] & bit) != 0)
std::cout << 'X';
else
std::cout << '.';
}
}
std::cout << '\n';
}
}
main()
{
int loc;
for (loc = 0; loc < X_SIZE; loc++)
{
set_bit(loc,loc);
}
print_graphics();
std::cout << "Bit(0,0): " << test_bit(0,0) << std::endl;
return 0;
}

What is the best cloud hosting solution for nodejs and mongodb application?

What is the best cloud hosting solution for nodejs and mongodb application?

I am working on a new application which uses nodejs and mongodb. I am new
to both of these. I have earlier worked on AWS and simple unix servers.
But I need a solution like heroku which can be scaled with least efforts.
Please give some feedback regarding that.
I have googled a bit and I liked https://modulus.io/ . Its scalable and
cheap.
Heroku + Mongolab seems costly.
Also I am not aware of what issues I am going to face.
Pardon me if you find this question unsuitable for stackoverflow.

Friday, 30 August 2013

(2, 'No such file or directory') when trying to open a csv file on Django

(2, 'No such file or directory') when trying to open a csv file on Django

I cannot for the life in me figure out why I keep getting this error. So I
have a django module that is running the following code
c = open('file.csv', 'rb')
reader = csv.reader(c)
rows = []
rownum = 0
for row in reader:
# Skip header
if rownum != 0:
rows.append(row)
rownum += 1
c.close()
return rows
A few things to keep in mind. file.csv is in the same directory as the
python file calling this function. I run this SAME code in the python
interpreter, outside of the django environment and it works beautifully. I
have tried rb and r, both don't work. I don't know why it doesn't work.
Is there something I am missing?
I am using python2.6

Thursday, 29 August 2013

ACTION_VIEW Intent to show image not working on 2.3

ACTION_VIEW Intent to show image not working on 2.3

I'm using the following code to display an image that I have saved on the
device. This works fine in Android 4.2, but when I use it on 2.3 , the
gallery opens but shows a black screen (never loads the image). I don't
see any errors being thrown either.
I can confirm the file exists, and the path created is correct (as I said
it works in 4.2)
private void viewPicture(File file, Context context){
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "image/*");
context.startActivity(intent);
}

Wednesday, 28 August 2013

Issue with printing arrays in ember.js

Issue with printing arrays in ember.js

I'm seeing something weird when I try to include the ember.js library
(ember-1.0.0-rc.7.js).
The javacode I have just prints out a javascript array:
<script type="application/javascript">
var songs = [ 'a','b','c'];
console.debug(songs.toString());
for(key in songs)
{
console.debug(songs[key]);
}
</script>
When I don't include the library, it'll print out a , b, c in the console.
However, when i do include it, it start printing out a, b, c, but as well
as all the functions to...
Example: function (idx) { return this.objectAt(idx); } function
superWrapper() { var ret, sup = this._super; this._super = superFunc || K;
ret = func.apply(this, arguments); this._super = sup; return ret; }
function (key) { return this.mapProperty(key); }
Any reason why this occurs with the ember.js library, and how do I resolve
this issue?
Any advice appreciated, Thanks, D

Is there Phonegap plugin for modules purchase?

Is there Phonegap plugin for modules purchase?

I want to make free application based on Phonegap with the possibility to
by premium module on Play Market for Android & App Store for IOS. How can
I do this? Maybe there is a special plugin for Phonegap?

How to collect records in crystal report using record selection formula to concatenate records

How to collect records in crystal report using record selection formula to
concatenate records

What i want is to collect records using record selection formula on the
basis of criteria selection.
If i have 2 criteria's then i have 4 combinations using criteria
selection. e.g.
if(cri1 <> 'ALL' and cri2 <> 'ALL') then record fetched
else if(cri1 = 'ALL' and cri2 <> 'ALL') then record fetched
else if(cri <> 'ALL' and cri = 'ALL') then record fetched
else if(cri = 'ALL' ; cri = 'ALL') then record fetched

(cri1 and cri2 are parameter fields used in crystal report)
In the same way for 3 criteria's, i will have 8 combinations. That is, for
n criteria's i will be having '2' to the power of 'n' combinations That
means for 10 criteria's i will be having 2 to the power of 10 combinations
(i.e. 1024) combinations.
Well i want to know whether is there any way to collect data in much
simpler way for n number of criteria's. Because for more than 3 criteria's
it will be very confusing to collect the records.
** Please help on this..**

Why always hello world?

Why always hello world?

Whatever I am writing in the printf bracket, it is always displaying
"hello world" only. Why is that?
#include <stdio.h>
int main(void)
{
printf("..... world\rhello\n");
return 0;
}

Tuesday, 27 August 2013

FTP upload from iPad not executing

FTP upload from iPad not executing

I am using the FTPManger from the link below. I have included the .h and
.m files and the frameworks into my ios application.
https://github.com/nkreipke/FTPManager
The code that i use in my viewController is as bellow. The action starts
the begining of the upload. But when i press the button it goes thru all
those methods but nothing happens and no errors show.
-(IBAction)uploadImage:(id)sender
{
[self upload:@"Default.png" ftpUrl:@"ftp://xxx.xxx.x.xxx" ftpUsr:@"ip100"
ftpPass:@"ftp100100"];
}
//uploading
-(void)startUploading {
man = [[FTPManager alloc] init];
succeeded = [man uploadFile:[NSURL URLWithString:filePath] toServer:server];
[self performSelectorOnMainThread:@selector(uploadFinished) withObject:nil
waitUntilDone:NO];
}
//
-(void)uploadFinished
{
NSLog(@"uploadFinished");
[progTimer invalidate];
progTimer = nil;
filePath = nil;
server = nil;
man = nil;
//test whether succeeded == YES
}
//
-(void)upload:(NSString*)file ftpUrl:(NSString*)url ftpUsr:(NSString*)user
ftpPass:(NSString*)pass {
NSLog(@"Upload");
server = [FMServer serverWithDestination:url username:user password:pass];
filePath = file;
progTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self
selector:@selector(changeProgress) userInfo:nil repeats:YES];
[self performSelectorInBackground:@selector(startUploading) withObject:nil];
}
//
-(void)changeProgress {
NSLog(@"changeProgress");
if (!man) {
return;
}
}

javascript get date from ntp server

javascript get date from ntp server

i need get date and time from ntp server .
I want add time.
Format date like this 31/12/2013 03:32:02 PM
<script language="JavaScript">
var someDate = new Date();
var numberOfDaysToAdd = $(session-time-left-secs)/60/60/24;
someDate.setDate(someDate.getDate() + numberOfDaysToAdd);
var dd = someDate.getDate();
var mm = someDate.getMonth() + 1;
var y = someDate.getFullYear();
var someFormattedDate = dd + '/'+ mm + '/'+ y;
document.write(someFormattedDate);
</script>

BroadcastReceiver and wifiState

BroadcastReceiver and wifiState

I'm writing an application that needs to receive wifi state modification.
To do it I've wrote a class, TestReceiver, that extends BroadcastReceiver
and, now, write on Log.i. The receiver has been registrated via
AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.lazooo.wifi_finder_service">
<uses-sdk android:minSdkVersion="14"/>
<application android:icon="@drawable/icon" android:label="@string/app_name">
<user-permission
android:name="android.permission.ACCESS_NETWORK_STATE" />
<user-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<receiver android:name=".TestReceiver">
<intent-filter>
<action android:name="android.net.wifi.WIFI_STATE_CHANGED"/>
<action android:name="android.net.wifi.STATE_CHANGE"/>
</intent-filter>
</receiver>
</application>
The matter is that it doesn't work, when I turn on/off wifi it doesn't do
nothing. What am I missing?

Continuous Integration build succeeds, Manual build fails

Continuous Integration build succeeds, Manual build fails

My Team Project consists of a Web Forms application and WCF Services, in
two separate solutions (the WCF services are hosted on a server within the
domain, the web app is in the DMZ). I have two build definitions for my
Team Project: a CI build and a manual build Yesterday I merged a branch
back into my trunk to prepare for a deployment. When I checked in my merge
the CI build kicked off...and succeeded. So then I queued the manual build
(the manual build is what ends up on prod server). The manual build
failed. It fails everytime I run it now, however the CI build succeeds
every time. The error from the build log is pasted below. I don't know how
I broke this build, and I'm confused as to why the CI build succeeds but
the manual build fails (same build definition except the drop location is
different and the trigger is different).
Error:
Exception Message: Access to the path 'C:\Builds\1\My Web App\My Web
App\Sources\MyAppWcfServices\Services\Messages' is denied. (type
UnauthorizedAccessException) Exception Stack Trace: at
System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at
System.IO.FileSystemEnumerableIterator1.CommonInit() at
System.IO.FileSystemEnumerableIterator1..ctor(String path, String
originalUserPath, String searchPattern, SearchOption searchOption,
SearchResultHandler`1 resultHandler, Boolean checkHost) at
System.IO.Directory.InternalGetFileDirectoryNames(String path, String
userPathOriginal, String searchPattern, Boolean includeFiles, Boolean
includeDirs, SearchOption searchOption, Boolean checkHost) at
System.IO.Directory.InternalGetDirectories(String path, String
searchPattern, SearchOption searchOption) at
Microsoft.TeamFoundation.Common.FileSpec.DeleteDirectoryInternal(String
path) at
Microsoft.TeamFoundation.Common.FileSpec.DeleteDirectoryInternal(String
path) at
Microsoft.TeamFoundation.Common.FileSpec.DeleteDirectoryInternal(String
path) at
Microsoft.TeamFoundation.Common.FileSpec.DeleteDirectoryInternal(String
path) at Microsoft.TeamFoundation.Common.FileSpec.DeleteDirectory(String
path, Boolean recursive) at
Microsoft.TeamFoundation.Build.Workflow.Activities.DeleteDirectory.Execute(CodeActivityContext
context) at
System.Activities.CodeActivity.InternalExecute(ActivityInstance instance,
ActivityExecutor executor, BookmarkManager bookmarkManager) at
System.Activities.Runtime.ActivityExecutor.ExecuteActivityWorkItem.ExecuteBody(ActivityExecutor
executor, BookmarkManager bookmarkManager, Location resultLocation)
Things I've read/tried:
TFS 2012 Build "Access to Path Denied"
Tool to find duplicate copies in a build (I didn't run the tool, couldn't
find a log file named like the example...confused)
I do not have my obj or bin directories in version control. This build
definition has been working great for months, up until yesterday. I'm not
sure what happened when I merged that would've caused this. There were no
conflicts in my merge, it was easy peasy....until I tried to build.

c# webclient returns 404 on working page

c# webclient returns 404 on working page

im trying to create some piece of code that will check webpage and collect
some data, that i need to work on. I already got the code, and it worked
pretty good for a while, but this time something is wrong - it returns 404
error code for 90% of visited pages, and im sure that those pages exist. i
already added headers to my webclient, and sleep thread to slow down a
bit, but nothing seems to help. could anyone check it out and ultimately
give some advice, why this works in such way?
public static string Download(string uri)
{
WebClient client = new WebClient();
client.Headers.Add("user-agent", "Mozilla/4.0 (compatible;
MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
string s = client.DownloadString(uri);
return s;
}
private void button1_Click(object sender, EventArgs e)
{
foreach (string[] dataRow in data)
{
symbol = dataRow[0];
urlId = symbol.Remove(symbol.Length - 3);
try
{
System.Threading.Thread.Sleep(2000);
String grohedownloaded =
Download(@"http://www.hansgrohe.pl/productdetail.html?model="
+ urlId + "XXX&lang=pl_PL");
foreach (Match match in Regex.Matches(grohedownloaded,
"href=\"(.*?)\" class=\"cloud-zoom\""))
{
string a = match.Groups[1].Value; //+
match.Groups[2].Value;
MessageBox.Show(symbol + " " + a);
}
MessageBox.Show("test");
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError &&
ex.Response != null)
{
var resp = (HttpWebResponse)ex.Response;
if (resp.StatusCode == HttpStatusCode.NotFound)
{
MessageBox.Show("error 404: " + symbol);
}
else
{
MessageBox.Show(resp.StatusCode.ToString());
}
}
}
}
}

With netTCP binding TCP error code 10061: No connection could be made because the target machine actively refused it

With netTCP binding TCP error code 10061: No connection could be made
because the target machine actively refused it

I have my WCF service with Self Hosting on netTCP:
<system.serviceModel>
<services>
<service behaviorConfiguration="Test"
name="WcfService1.Service1">
<host>
<baseAddresses>
<add
baseAddress="net.tcp://127.0.0.1:808/Service1.svc"/>
</baseAddresses>
</host>
<endpoint address="" binding="netTcpBinding"
bindingConfiguration="NetTcpEndpointBinding"
contract="WcfService1.IService1">
<identity>
<dns value="127.0.0.1" />
</identity>
</endpoint>
<!--<endpoint address="mex" binding="mexTcpBinding"
contract="IMetadataExchange" bindingConfiguration="" />-->
</service>
</services>
<bindings>
<netTcpBinding>
<binding name="NetTcpEndpointBinding"
portSharingEnabled="true" maxConnections="1000">
<security mode="Transport">
<transport clientCredentialType="Windows" />
</security>
</binding>
</netTcpBinding>
</bindings>
<protocolMapping>
<add scheme="net.tcp" binding="netTcpBinding"/>
</protocolMapping>
<behaviors>
<serviceBehaviors>
<behavior name="Test">
<serviceAuthenticationManager
authenticationSchemes="IntegratedWindowsAuthentication"
/>
<!-- To avoid disclosing metadata information, set the
values below to false before deployment -->
<serviceMetadata httpGetEnabled="false"
httpsGetEnabled="false" />
<!-- To receive exception details in faults for
debugging purposes, set the value below to true. Set
to false before deployment to avoid disclosing
exception information -->
<serviceDebug includeExceptionDetailInFaults="false" />
<serviceThrottling maxConcurrentCalls="400"
maxConcurrentInstances ="400" maxConcurrentSessions
="400"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
</system.serviceModel>
But as soon as I run the client ,I am getting the following error:
TCP error code 10061: No connection could be made because the target
machine actively refused it 127.0.0.1:808
I have enabled the port 808. What else is missing?

Monday, 26 August 2013

jquery mobile and textpattern ... passing variable

jquery mobile and textpattern ... passing variable

I am new to jquery mobile
My scenario:
I simply want to pass the value to different page in same dom. I went
through lot of solution mentioned but could not find exactly how to solve
it. I want to get value passed through url and store in cookies and later
to want to retrieve it
Problem:
I am able to store value in cookies but when i go to page
http://test.com/test121#singlepage?eid= mention below after click event
page content is article detail related to previous cookies. Right content
only gets updated when i refresh the page
$(document).bind("pagebeforechange",function(event,data){
var u = $.mobile.path.parseUrl( data.toPage );
if ( $.mobile.path.isEmbeddedPage( u ) ) {
var u2 = $.mobile.path.parseUrl( u.hash.replace( /^#/, "" ) );
if ( u2.search ) {
if ( !data.options.dataUrl ) {
data.options.dataUrl = data.toPage;
}
var artid = queryStringToObject(u2.search);
data.options.pageData = queryStringToObject( u2.search );
data.toPage = u.hrefNoHash + "#" + u2.pathname;
selectorid = "#"+u2.filename;
selartid = u2.search;
setCookie('artidpage',artid.eid,365);
$.mobile.pageData = data.options.pageData;
}
}
})
<!--------------today------------------>
<div data-role="page" id="today" data-theme="b">
<div id="header" data-role="header" data-theme="b">
<a id="back-button" data-rel="back" data-icon="back"
class="ui-btn-right" style="margin-top:10px;">Back</a>
<h3>Today</h3>
</div>
<div id="main" date-role="content">
<txp:variable name="selected_date"><txp:skp_act_plg
orderby="Posted asc" filter='today'/></txp:variable>
<txp:article_custom limit="9999" section="events" sort="Posted
asc" time="any" id='<txp:variable name="selected_date"/>' >
<a rel="external" class="ui-link-inherit"
href="http://test.com/test121#singlepage?eid=<txp:article_id/>"
id="test">
<h3><txp:title /></h3>
<img class="thumb4 lazyload" width="100" alt=""
data-original='<txp:smd_thumbnail display="url"
id='<txp:custom_field name="article_image" />'/>'
src='<txp:smd_thumbnail display="url"
id='<txp:custom_field name="article_image"
/>'/>'/>
</a>
<txp:excerpt/>
</txp:article_custom>
</div>
<div id="footer" data-role="footer" data-theme="b">
<h4>footer</h4>
</div>
</div>
<!----------------------------single page ----------------------------->
<div data-role="page" id="singlepage" data-theme="b">
<div id="header" data-role="header" data-theme="b">
<a id="back-button" data-rel="back" data-icon="back"
class="ui-btn-right" style="margin-top:10px;">Back</a>
<h3>Single Page</h3>
</div>
<div class="ui-content" data-role="content" role="main">
<script>
</script>
<txp:etc_query data="{?artidpage}" globals="_COOKIE">
<txp:variable name="artid" value='<txp:etc_query
data="{?artidpage}" globals="_COOKIE" />' />
<txp:article_custom id='<txp:variable name="artid"/>' />
<txp:else/>
<p>no cookie no cream</p>
</txp:etc_query>
</div>
<div id="footer" data-role="footer" data-theme="b">
<h4>Mosman Events 2013</h4>
</div>
</div>
Any help appreciated. Note it should be textpattern way

flask-sqlalchemy cross database with "dynamic" schema

flask-sqlalchemy cross database with "dynamic" schema

I'm attempting to use the "application factory" pattern from flask, but I
seem to have a chicken-and-egg problem with my models.
http://flask.pocoo.org/docs/patterns/appfactories/
I am importing my views in the create_app function, which imports my
models. So, I don't have a config in the app when my models are being
defined. This is usually fine, using the bind keys, I can set up models to
connect to different dbs.
However, in this case, I have two sets of models, one from the default
database, and another set on another db connection - and I'd like to
cross-db join. I know that the usual method is to add
__table_args__ = { 'schema' : 'other_db_name' }
to my "other db" models.
But...depending on the config, the 'other_db_name' may be different.
So, now I have models being defined that require the schema name from the
config, but with no schema from the config to put in the class definition.
I also may simply be missing something in flask I wasn't aware of.
(Side note - an easy fix for this is to configure Sqlalchemy to always
output the schema name in the query, no matter what - but I can't seem to
find a setting for this.)
If anyone has any input on this, I'd be very much obliged. Thanks!

RegularExpression DataAnnotation to validate Html tags

RegularExpression DataAnnotation to validate Html tags

This regular expression validates html tags that include attributes could
someone correct this code to work in C# RegularExpression. The problem
with this expression is the quotes it stops at the first quote because
it's part of the expression doesn't any one know how to fix this or does
anyone have an alternative. P.S does anyone know of a C# .net regular
expression site to test their expressions
Here is the code:
[RegularExpression(@"</?\w+((\s+\w+(\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)/?>")]

Java program unable to create lock on Neo4j database

Java program unable to create lock on Neo4j database

I am getting the following error while connecting to Neo4j:
Exception in thread "main" java.lang.RuntimeException:
org.neo4j.kernel.lifecycle.LifecycleException: Component
'org.neo4j.kernel.StoreLockerLifecycleAdapter@1798b372' was successfully
initialized, but failed to start. Please see attached cause exception.
at
org.neo4j.kernel.InternalAbstractGraphDatabase.run(InternalAbstractGraphDatabase.java:281)
at
org.neo4j.kernel.EmbeddedGraphDatabase.<init>(EmbeddedGraphDatabase.java:106)
at
org.neo4j.graphdb.factory.GraphDatabaseFactory$1.newDatabase(GraphDatabaseFactory.java:88)
at
org.neo4j.graphdb.factory.GraphDatabaseBuilder.newGraphDatabase(GraphDatabaseBuilder.java:207)
at
org.neo4j.graphdb.factory.GraphDatabaseFactory.newEmbeddedDatabase(GraphDatabaseFactory.java:69)
at com.neo4j.NeoStart.createDatabase(NeoStart.java:41)
at com.neo4j.NeoStart.main(NeoStart.java:26)
Caused by: org.neo4j.kernel.lifecycle.LifecycleException: Component
'org.neo4j.kernel.StoreLockerLifecycleAdapter@1798b372' was successfully
initialized, but failed to start. Please see attached cause exception.
at
org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:497)
at org.neo4j.kernel.lifecycle.LifeSupport.start(LifeSupport.java:104)
at
org.neo4j.kernel.InternalAbstractGraphDatabase.run(InternalAbstractGraphDatabase.java:259)
... 6 more
Caused by: org.neo4j.kernel.StoreLockException: Could not create lock file
at org.neo4j.kernel.StoreLocker.checkLock(StoreLocker.java:74)
at
org.neo4j.kernel.StoreLockerLifecycleAdapter.start(StoreLockerLifecycleAdapter.java:40)
at
org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:491)
I have installed neo4j as: apt-get install neo4j in ubuntu 12.04
DB_PATH I am using is as below: private static final String
neo4j_DB_PATH="/var/lib/neo4j/data/graph.db";
Please help me to resolve this problem...

Creating heavy user controls in WPF

Creating heavy user controls in WPF

I know that I cannot spawn different threads and put it in the UI thread
to add it in the Visual Tree as it will throw an exception that it cannot
access that object because a different thread owns it.
My current scenario is that I am heavily creating UI controls runtime, say
like 200 (FrameworkContentElement) controls and add it to the DockWindow.
Is it possible for me not to freeze the UI while creating this and try to
load them to the UI thread? I cannot even show a progress dialog because
that will use the UI thread while showing the dialog while doing work on
another thread, that is okay if what I need to handle is data and put it
in the UI but this time I need to create these UI controls.
One approach I've thought is create the UI controls and serialize them
into MemoryStream and load them to the UI thread, one problem in here is
that I have to re-attach the DataContext to the controls but that is fine,
at that moment I can delegate it to another thread. Problem still is that
is this feasible to do?
I tried mixing Task and Thread object to make the ApartmentState to STA
but still no luck.
public static Task<T> StartSTATask<T>(Func<T> func)
{
var tcs = new TaskCompletionSource<T>();
Thread thread = new Thread(() =>
{
try
{
tcs.SetResult(func());
}
catch (Exception e)
{
tcs.SetException(e);
}
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
return tcs.Task;
}

Best practices for functions with multiple Eigen objects as parameters

Best practices for functions with multiple Eigen objects as parameters

I find the design of functions with Eigen objects as parameters
cumbersome. While the information in the Eigen Documentation is helpful,
it suggests an awkward approach for the template arguments. Suppose, we
want to write a geometric routine like a line-plane-intersection. A simple
and transparent approach would be:
template<typename _Tp>
bool planeLineIntersect(const Eigen::Matrix<_Tp, 3, 1>& planePoint,
const Eigen::Matrix<_Tp, 3, 1>& planeNormal,
const Eigen::Matrix<_Tp, 3, 1>& linePoint,
const Eigen::Matrix<_Tp, 3, 1>& lineDir,
Eigen::Matrix<_Tp, 3, 1>& intersectionPoint)
This looks relatively pleasing and someone that looks at this can learn
that every parameter shall be a 3D vector of the same type. However, this
does not allow for Eigen expressions of any kind (we would have to call
Eigen::Matrix constructors for every expression, that we use). If
expressions are used with this, we need to create unnecessary temporaries.
The suggested solution is:
template<typename Derived1, typename Derived2, typename Derived3, typename
Derived4, typename Derived5>
bool planeLineIntersect(const Eigen::MatrixBase<Derived1>& planePoint,
const Eigen::MatrixBase<Derived2>& planeNormal,
const Eigen::MatrixBase<Derived3>& linePoint,
const Eigen::MatrixBase<Derived4>& lineDir,
const Eigen::MatrixBase<Derived5>& intersectionPoint)
This does not reveal anything about the matrices that are expected, nor
which parameters are used for input and output, as we have to const-cast
the intersectionPoint to allow for expressions in output parameters. As I
understand it, this is the only way to allow for Eigen expressions in all
function parameters. Despite the unelegant expression support, the first
snippet still seems more likable to me.
My Questions:
Would you consider the second code snippet the best solution for this
example?
Do you ever use the const-cast solution for output parameters or do you
think it is not worth the loss in transparency?
What guidelines/best practices do you use for Eigen function writing?

can I upgrade my glassfish 3.1.2.2 libs to use JPA 2.1 and JSF 2.2

can I upgrade my glassfish 3.1.2.2 libs to use JPA 2.1 and JSF 2.2

I am working with glassfish 3.1.2.2 and I can not upgrade to 4 due to OS
restrictions. my question is: Can I upgrade JPA 2 version to JPA 2.1 ??
and can I upgrade from JSF 2.1 to JSF 2.2 ???
If we can, how can I achieve this ???

Windows Groups in Windows 7

Windows Groups in Windows 7

Are there method or external add-on software for Windows 7 operating
system for creating windows groups? I want to group some windows including
their current monitor, their sizes and their positions. When I click the
group from start bar all windows of this groups reappear in saved
positions.
Regards,

MYSQL Select table and column name

MYSQL Select table and column name

I've got a SQL query like this one :
" SELECT T1.id, T2.user FROM T1 INNER JOIN T2 ON T1.user_id = T2.id"
The result is something like "id | user".
I'd like to know if there's a way to have the same result with the table
name before the column name (something like "T1.id | T2.user") without
changing the query (with a concat for example) ?
Thanks !

Sunday, 25 August 2013

Dropdownlist using viewbag data in mvc4 using c#

Dropdownlist using viewbag data in mvc4 using c#

Hi i want to fill a dropdown list in my view page my code is
public class MemberBasicData
{
public int Id { get; set; }
public string Mem_NA { get; set; }
public string Mem_Occ { get; set; }
}
//controller
public ActionResult Register()
{
var users = new Member().GetAllMembers();
ViewBag.Users = users;
return View();
}
//View
@model IEnumerable<Puthencruz.Rotary.Members.Models.MemberBasicData>
@Html.DropDownListFor(model => model.Mem_Na, (SelectList)ViewBag.Users,
"--Select Users--")
i want to add Mem_NA to dropdownlist, Viewbag contains all the user
details. Problem is in View page. An error shows in model.Mem_Na. Please
help me to solve this.

Selenium possible upgrade issue?

Selenium possible upgrade issue?

I had a piece of code that worked perfectly fine until today.
public class TestSelenium {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","chromedriver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://google.com");
driver.manage().timeouts().implicitlyWait(10,
TimeUnit.SECONDS);
driver.findElement(By.name("q")).sendKeys("hello world");
}
}
The above simple code trow the following error:
Started ChromeDriver
port=25456
version=26.0.1383.0
log=C:\Users\Owner\Desktop\DOCs\CAPSTONE\java16\SearchEngine\chromedriver.log
Exception in thread "main" org.openqa.selenium.WebDriverException: Unknown
command 'WaitForAllTabsToStopLoading'. Options:
AcceptOrDismissAppModalDialog, ActionOnSSLBlockingPage, ActivateTab,
AddBookmark, AddDomEventObserver, AppendTab, ApplyAccelerator,
BringBrowserToFront, ClearEventQueue, CloseBrowserWindow, CloseTab,
CreateNewAutomationProvider, DeleteCookie, DeleteCookieInBrowserContext,
DoesAutomationObjectExist, DragAndDropFilePaths, ExecuteJavascript,
ExecuteJavascriptInRenderView, GetActiveTabIndex,
GetAppModalDialogMessage, GetBookmarkBarStatus, GetBookmarksAsJSON,
GetBrowserInfo, GetBrowserWindowCount, GetChromeDriverAutomationVersion,
GetCookies, GetCookiesInBrowserContext, GetDownloadDirectory,
GetExtensionsInfo, GetIndicesFromTab, GetLocalStatePrefsInfo,
GetMultiProfileInfo, GetNextEvent, GetPrefsInfo, GetProcessInfo,
GetSecurityState, GetTabCount, GetTabIds, GetTabInfo, GetViews, GoBack,
GoForward, InstallExtension, IsDownloadShelfVisible, IsFindInPageVisible,
IsMenuCommandEnabled, IsPageActionVisible, IsTabIdValid, MaximizeView,
NavigateToURL, OpenFindInPage, OpenNewBrowserWindow,
OpenNewBrowserWindowWithNewProfile, OpenProfileWindow,
OverrideGeoposition, RefreshPolicies, Reload, RemoveBookmark,
RemoveEventObserver, ReparentBookmark, RunCommand, SendWebkitKeyEvent,
SetBookmarkTitle, SetBookmarkURL, SetCookie, SetCookieInBrowserContext,
SetDownloadShelfVisible, SetExtensionStateById, SetLocalStatePrefs,
SetPrefs, SetViewBounds, SimulateAsanMemoryBug, TriggerBrowserActionById,
TriggerPageActionById, UninstallExtensionById, UpdateExtensionsNow,
WaitForBookmarkModelToLoad, WaitUntilNavigationCompletes,
WebkitMouseButtonDown, WebkitMouseButtonUp, WebkitMouseClick,
WebkitMouseDoubleClick, WebkitMouseDrag, WebkitMouseMove,
AcceptCurrentFullscreenOrMouseLockRequest, AddOrEditSearchEngine,
AddSavedPassword, CloseNotification,
DenyCurrentFullscreenOrMouseLockRequest, DisablePlugin, EnablePlugin,
FindInPage, GetAllNotifications, GetDownloadsInfo, GetFPS, GetHistoryInfo,
GetInitialLoadTimes, GetNTPInfo, GetNavigationInfo, GetOmniboxInfo,
GetPluginsInfo, GetSavedPasswords, GetSearchEngineInfo, GetV8HeapStats,
ImportSettings, IsFullscreenBubbleDisplayed,
IsFullscreenBubbleDisplayingButtons, IsFullscreenForBrowser,
IsFullscreenForTab, IsFullscreenPermissionRequested,
IsMouseLockPermissionRequested, IsMouseLocked, KillRendererProcess,
LaunchApp, LoadSearchEngineInfo, OmniboxAcceptInput,
OmniboxMovePopupSelection, PerformActionOnDownload,
PerformActionOnInfobar, PerformActionOnSearchEngine,
RemoveNTPMostVisitedThumbnail, RemoveSavedPassword,
RestoreAllNTPMostVisitedThumbnails, SaveTabContents, SetAppLaunchType,
SetOmniboxText, SetWindowDimensions, WaitForAllDownloadsToComplete,
WaitForNotificationCount, (WARNING: The server did not provide any
stacktrace information)
Command duration or timeout: 52 milliseconds
Build info: version: '2.28.0', revision: '18309', time: '2012-12-11 20:21:18'
System info: os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1',
java.version: '1.7.0_11'
Session ID: 48617161e339ad279277f5cc183f7dba
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{platform=XP, chrome.chromedriverVersion=26.0.1383.0,
acceptSslCerts=false, javascriptEnabled=true, browserName=chrome,
rotatable=false, locationContextEnabled=false, version=29.0.1547.57,
cssSelectorsEnabled=true, databaseEnabled=false, handlesAlerts=true,
browserConnectionEnabled=false, webStorageEnabled=true, nativeEvents=true,
applicationCacheEnabled=false, takesScreenshot=true}]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at
org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:187)
at
org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:145)
at
org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:533)
at
org.openqa.selenium.remote.RemoteWebDriver.get(RemoteWebDriver.java:276)
at genealogy2.TestSelenium.main(TestSelenium.java:21)
I am very confused ... What is wrong with the Fluent wait? Have there been
any changes to Selenium or is it possible that this kind of error is
because of the automatic Java upgrades? (PS: I did not upgrade Java and
Selenium manually)

Prevent EXE being copied to another PC - keep some info inside EXE file (e.g. some flag)

Prevent EXE being copied to another PC - keep some info inside EXE file
(e.g. some flag)

I want to prevent executable being copied to another PC and thus i need to
somehow save information inside my EXE file about that it was already used
somewhere else on another PC.
Can i embed small piece of information like user's hard drive number into
my EXE file so this information would be available when this EXE is copied
to another PC?
I thought maybe there is a way to read and write to some resource file
embedded in an EXE file but i presume that resource file is read only and
if so is there is a place inside EXE file where i could keep information
which i need?

Why this error is showing?

Why this error is showing?

I'm facing a strange error sometimes on my php wap site! Its not
persistent, just occurs somwtimes & If I refresh page, error is went out
and normal page appears. I'm attaching errors screenshot-

172 line of fun.inc.php is-
return mysql_real_escape_string($str);
I'm pasting line 164 to 212 for better understanding
function clean($str)
{
$str = @trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
$str = str_replace("<",'',$str);
$str = str_replace(">",'',$str);
}
return mysql_real_escape_string($str);
}
function regchars($word){
$chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
for($i=0;$i<strlen($word);$i++){
$ch = substr($word,$i,1);
$nol = substr_count($chars,$ch);
if($nol==0){
return true;
}
}
return false;
}
function nospace($word){
$pos = strpos($word," ");
if($pos === false){
return false;
}else{
return true;
}
}
function checknumber($word){
$chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
$ch = substr($word,0,1);
$sres = ereg("[0-9]",$ch);
$ch = substr($word,0,1);
$nol = substr_count($chars,$ch);
if($nol==0){
return true;
}
return false;
}
function registerform($ef)
{
$errl = "";
switch($ef)
{
Is its a problem of my code or problem from hosting server? How can I
prevent users from showing such code??

and error in SQL syntax

and error in SQL syntax

Here is the mysql error im getting:
You have an error in your SQL syntax; check the manual that corresponds to
your MySQL server version for the right syntax to use near 'SELECY * FORM
user WHERE username='' AND password='' LIMIT 1' at line 1
Here is my code:
<?php
session_start();
include_once("connect.php");
if (isset($_POST['username'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECY * FORM users WHERE username='".$username."' AND
password='".$password."' LIMIT 1";
$res = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($res) == 1) {
$row = mysql_fetch_assoc($res);
$_SESSION['uid'] = $row ['id'];
$_SESSION['username'] = $row ['username'];
header("Location: index.php");
exit();
} else {
echo "Invalid login information. Please return to the previous
page.";
exit();
}
}
?>
Someone that can help me? :) i dont know what im doing working here, cant
find the error.

django different user authentication

django different user authentication

I have a question concerning different user authentication in Django.
Suppose I have two kind of users, and I want to give them different access
to different pages or views. I know that there is @login_required to
differentiate login user and visitor. I am just wondering how to
differentiate two different kind of logged in users. If using
@login_required, I need to do another check to see whether that user is
belonged to either group, which may not be the good way to solve the
problem.
Any suggestions? Thanks a million!

Saturday, 24 August 2013

What's a good way to level pottery?

What's a good way to level pottery?

I'm working on Coldain Prayer Shawl 1.0 #4: Fur-lined Coldain Prayer
Shawl, and want to get my pottery skill over 122? What's the fastest way
to do this?

Dynamic Table alternate background - MVC3

Dynamic Table alternate background - MVC3

I have two tables in my view; trying to change the background of alternate
rows in one table. in my style file I am using:
.alternateRow
{
table-layout: auto;
border-collapse: collapse;
border-spacing: 0px;
empty-cells: hide;
}
.alternateRow tr {
background-color:#aa0000;
}
.alternateRow tr.odd {
background-color:#00AA00;
}
This is how I make the dynamic table:
<table class="alternateRow">
<% List<Question> wrongs = ViewBag.wrongs;
for (var i = 0; i < wrongs.Count; ++i)
{ %>
<tr>
<td>
<%= wrongs[i].TheQuestion %>
</td>
<td>
Correct Answer
</td>
<td>
<%= wrongs[i].CorrectAnswer %>
</td>
<td>
<%= wrongs[i].Explanations %>
</td>
</tr>
<% } %>
I did not work, both rows have the same color. Any idea what I am doing
wrong, thanks in advance.

Understanding the createServer arguments in node.js

Understanding the createServer arguments in node.js

Sorry for the rather un constructive question: I was watching a tutorial
on creating a web server in node.js and i did not understand the meaning
of the arguments "response" and "request", so what do they mean exactly ?
I have been looking for answers in the documentation but i was still
confused because i am new to node.js.
Thanks for any help and apologies for this question being quite vague.

Printing backtrace doesn't work

Printing backtrace doesn't work

I have a block of code as follows:
try
... (* body *)
with
| e ->
Printexc.record_backtrace true;
printf "Unexpected exception : %s\n" (Printexc.to_string e);
let x = Printexc.get_backtrace () in
print_string x;
Printexc.print_backtrace stdout
The code in body does raise an exception, and it shows as follows:
`Unexpected exception : Not_found`
However it doesn't print any backtrace.
I compile the file with -g and export OCAMLRUNPARAM=b, does anyone know
the reason why the backtrace cannot be printed?

Android: layer list without animation scaling

Android: layer list without animation scaling

I'm working first time with animation on Android. And I discovered this
fact and I became really angry. I had a template for button with rectangle
as background and an image bitmap centered using layer list. OK, now I
want to replace bitmap image with an animation. I created animation-list
drawable and changed my buttons code:
<layer-list>
<item>
<shape android:shape="rectangle">
<gradient
android:startColor="#666666"
android:endColor="#666666"
android:angle="90"
android:centerY="10%"
/>
<corners android:radius="0dp" />
</shape>
</item>
<item
android:drawable="@drawable/arrowseq">
</item>
There is no possibility to avoid this very anoying auto-scaling like for
bitmap. Could you please help me or explain WHY?
Lot of thanks!

How can I access a c# Memory Mapped File from Coldfusion 10?

How can I access a c# Memory Mapped File from Coldfusion 10?

I have a c# application that generates data every 1 second (stock tick
data) which can be discarded after each itteration. I would like to pass
this data to a Coldfusion (10) application and I have considered having
the c# application writing the data to a file every second and then having
the Coldfusion application reading that data, but this is most likely
going to cause issues with the potential for both applications trying to
read or write to the file at the same time ?
I was wondering if using Memory Mapped Files would be a better approach ?
If so, how could I access the memory mapped file from Coldfusion ?
Any advice would be greatly appreciated. Thanks.

Friday, 23 August 2013

How to create JSON object with array of nested arrays for multipletimes and multiple times?

How to create JSON object with array of nested arrays for multipletimes
and multiple times?

$data=array
(
"Maths" : [
{
"Name" : "ramesh", // First element
"Marks" : 67,
"age" : 23
}, {
"Name" : "mayur", // Second element
"Marks" : 65,
"age" : 21
}
],
"Science" : [
{
"Name" : "ram", // First Element
"Marks" : 56,
"age" : 27
},
{
"Name" : "Santosh", // Second Element
"Marks" : 78,
"age" : 41
}
]
);

using socket to communicate a button click event

using socket to communicate a button click event

I have a device or micro-controller i'll call it a mc that I need to
communicate to when a web page button is clicked using sockets.
MC1
<button id ='on1' name='mc1'>On</button>
<button id ='off1' name='mc1'>off</button>
what I am trying to accomplish is when a button is clicked pass the info
to the mc.
Currently I can listens to a port and can write data to the mc as well as
receive data. To do this im starting a file though the server php cli. The
file contains these basic socket functions.
$socket = @socket_create_listen("port#");
$client = socket_accept($socket);
socket_write($client, $msg);
socket_read ($client, 256);
the mc then connect to the server at the port#
Im having difficulties understanding how to bridge the gap between my php
web page with the button and passing the data that the button has been
clicked to the mc.
can i have the file that listens to the port run and then in a seperate
file write to the client?
Thanks JT

Creating a custom round button in android

Creating a custom round button in android

Can anyone help me out here. I am trying to create a small round button
that would represent a lottery ball using a very simple self created XML
class round_button.xml. However I keep getting the error over and over
even when Ive put the code through a w3schools validator that " Error
parsing XML: junk after document element." I cannot see what the issue is
here and maybe I am missing something very clear, I dont know. Could
anyone please help me out. Here is the code:
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval" />
<solid
android:color="#FF0000"
</shape>

Detect X and Y of Each Multitouch Event in Corona SDK

Detect X and Y of Each Multitouch Event in Corona SDK

After activating multitouch in Corona SDK, is there a way I can track the
x and y coordinates of each simultaneous touch?
An ideal function would be like this:
local function detectMultitouch(touches)
for i = 0, #touches do
print(touches[i].x .. " ".. touches[i].y) end
end

Cookie wrapper in MVC4 c#

Cookie wrapper in MVC4 c#

I'd like to create a cookie wrapper in my application to help support a
DRY approach to coding common cookie methods, provide intellisense for
cookie-type properties (keys), and protect against typo-errors when
working with cookies from multiple classes and namespaces.
The best structure for this (that I can think of) is to apply a base class
like such:
abstract class CookieBase{
protected HttpRequestBase request;
protected HttpCookie cookie;
protected string name;
public HttpCookie Cookie { }
public string Name { get; }
public HttpCookie Get(){ ... }
protected string GetValue(string key){ ... }
public bool IsSet(){ ... }
protected void SetValue(string key, string value){ ... }
}
Then for each cookie-type that inherits the base class define properties
for each key that should be stored in the HttpCookie, and define a
constructor that accepts the Request object as a parameter and
instantiates the Cookie property of the base class.
Any ideas on how I might improve this design, or suggestions to
alternative approaches to attaining the goals I stated at the start of
this post?

How to make a stable sort of binary values in linear time?

How to make a stable sort of binary values in linear time?

Let us suppose that we have a:
class Widget;
std::vector<Widget>;
And we have a function:
bool belongsToLeft(Widget w);
I would like to sort the container according to this predicate. So far I
though up this algorithm. It progresses from both ends of the range. Once
it finds a pair of values that simultaneously belong to the other end, it
swaps them.
template <typename TIterator, typename TPredicate>
TIterator separate(TIterator begin, TIterator end, TPredicate belongsLeft)
{
while (true)
{
while (begin != end && belongsLeft(*begin))
++begin;
while (begin != end && !belongsLeft(*end))
--end;
if (begin == end)
return begin;
std::swap(*begin, *end);
}
}
The problem is that this algorithm is not stable:
#include <vector>
#include <iostream>
int main()
{
std::vector<int> numbers = {6, 5, 4, 3, 2, 1};
separate(numbers.begin(), numbers.end(), [](int x){return x%2 == 0;});
for (int x : numbers)
std::cout << x << std::endl;
return 0;
}
outputs:
6
2
4
3
5
1
How can I modify this algorithm to be stable and keep the linear time?

Thursday, 22 August 2013

check constarints not working

check constarints not working

CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL CHECK (AGE >= 18),
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
I have created table. But it allowed me to add age <18. How to solve it .
I need to check age>=18. how to write query for that?

error index array out of bond exception in android

error index array out of bond exception in android

I have to create array list from string like this code
ArrayList<String> lg = new ArrayList<String>();
String[]
rl=c.getResources().getStringArray(R.array.CountryCodes);
for(int i=0;i<rl.length;i++){
String[] g=rl[i].split(",");
lg.add(g[2]);
}
CountryCodes is a string like this --> 1,US,United States
And I want to save United States to array list but it show error like this
JavaArrayIndexOutoFBond Exception in line lg.add(g[2]);
any solution??

jQuery get the actual class of element

jQuery get the actual class of element

This gives me a list of classes the clicked element has:
$("#nav li ul li").click(function(e){
var cla=$(this).attr('class')
});
I only want the actual class written beside the element, I don't want the
others.

Upload DHT22 Sensor Data to Xively Feed

Upload DHT22 Sensor Data to Xively Feed

I am trying to modify some of the predefined code that exists for the
DHT22 sensor. I would like to modify Adafruit's DHT_Driver so that it
returns an array corresponding to the Temperature value and Humidity value
that the sensor outputs. I would like to make this change so that I can
utilize the output array in a Python snippet. Namely, I want to use the
output array values to upload data to a Xively feed.
I am looking for something similar to this...
#!/usr/bin/env python
import time
import os
import eeml
# Xively variables specific to my account.
API_KEY = 'API Key Here'
FEED = 'FEED # Here'
API_URL = '/v2/feeds/{feednum}.xml' .format(feednum = FEED)
# Continuously read data from the DHT22 sensor and upload
# the results to the Xively feed.
while True:
# Read the data from the sensor.
sensorData = .... // Call on the main method within the DHT_Driver.c file
temp_C = sensorData[0]
humidity = sensorData[1]
if DEBUG:
print("sensorData:\t", sensorData)
print("\n")
if LOGGER:
# Initialize the users Xively account.
pac = eeml.Pachube(API_URL, API_KEY)
# Prepare the data to be uploaded to the Xively
# account.
# temp_C & humidity are extracted from their indices
# above.
pac.update([eeml.Data(0, temp_C, unit=eeml.Celsius())])
pac.update([eeml.Data(1, humidity, unit=eeml.%())])
# Upload the data to the Xively account.
pac.put()
# Wait 30 seconds to avoid flooding the Xively feed.
time.sleep(30)
I need some feedback on getting the Temperature and Humidity vaules from
the sensor. It must utilize C because Python isn't fast enough to process
the data from the sensor. Ideally I could just return an array containing
the two values and access the values like this:
temp_C = sensorData[0]
humidity = sensorData[1]
Also, if, within this Python snippet, I were to call on the main method
within the DHT_Driver.c file would this be limited by the Python
interpreter (i.e. will the C based program run with similar performance to
a Python based program)?
I am very unfamiliar with Python and I am just beginning C so if there are
any suggestions and or positive criticism, please feel free to chime in.

Link styled as a button, printed as link without styling

Link styled as a button, printed as link without styling

I'm using bootstrap and when I create a styled link like:
<a href="http://www.google.com" class="btn btn-primary">Button</a>
When I want to print the page, the styled buttons are printed like a
unstyled link. Is there some way to fix this?

How to extract a path from an ActionDispatch object

How to extract a path from an ActionDispatch object

I'm trying to upload a file to Wistia.com. What is the correct way to get
the path_to_video variable from params as it's an ActionDispatch object.
The controller is something like this:
def create
post_video_to_wistia(params[:upload][:file].tempfile)
end
The upload code looks something like this
def post_video_to_wistia(path_to_video)
uri = URI('https://upload.wistia.com/')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post::Multipart.new uri.request_uri, {
'api_password' => [WISTIA_PASSWORD],
'file' => UploadIO.new(File.open(path_to_video),
'application/octet-stream',
File.basename(path_to_video)
)
}
response = http.request(request)
return response
end
Here are the params:
Parameters:
{"upload"=>{"file"=>#<ActionDispatch::Http::UploadedFile:0x007fa8201d58d8
@original_filename="123.mp4", @content_type="video/mp4",
@headers="Content-Disposition: form-data; name=\"upload[file]\";
filename=\"123.mp4\"\r\nContent-Type: video/mp4\r\n",
@tempfile=#<File:/var/15741-1xiizbz>>}, "commit"=>"Send", "id"=>"2"}

CSS opacity background color and text not working

CSS opacity background color and text not working

im making an app for firefox OS and i want to make button background
opacity 0.5 and the text opacity 1... but it didnt work... check the css:
.button{
height:40px;
width:180px;
border-radius: 100px 100px 100px 100px;
border: 1px solid #FF9924;
display:inline-block;
background-color:#FF9924;
padding-top:5px;
opacity:0.5;
}
h1{
padding: 5px 5px 5px 5px;
text-align:center;
font-size:20px;
font-family: firstone;
opacity:1.0;
}
on page:
<div class="menu">
<div class="button"><h1>Start the fight</h1></div>
</div>

Wednesday, 21 August 2013

Efficient way to map my Ip address with subnet and subnet mask in java

Efficient way to map my Ip address with subnet and subnet mask in java

I am having set of subnet and subnet masks in a db table with a APN. I
want retrieve the mapping APN.
10.0.0.0, 255.0.0.0, broadband
172.28.0.0, 255.255.0.0, internet
20.12.0.0, 255.255.0.0, video
How can I map my ip with a given set of subnet and subnet mask in Java

SQL Union exclude row if value already exists in first table

SQL Union exclude row if value already exists in first table

I have two tables which i wish to combine. However, there is a field in
both tables that should have the same value in the second table the second
tables record should be excluded.
These are a MSSQL 2012 tables.
The only way i can think of is something nasty like this.
Select A, B from Tab1 Union Select C, D from Tab2 where Tab2.c not in
(Select A from Tab1)
It looks relatively clean in my example but the selects for Tab1 and tab2
have long and complex where clauses and i would need to duplicated that in
the "not in" select statement.
I've seen other solutions but not in MSSQL. Any one out there have a
better example ?
Thanks

JavaScript timing issue - window closing before sessionStorage values are set

JavaScript timing issue - window closing before sessionStorage values are set

We are putting together an FSSO API that requires a popup window for the
user to log in. In the popup, we perform two tasks:
Calling a service to populate a profile values, then setting a page to
redirect the user to based on the event type (login or registration).
Redirecting the user to the redirect page in the parent window and closing
the FSSO popup.
Code:
$(document).ready(function() {
var nextPage = "index.html",
storage = window.opener.sessionStorage;
function setStorage(callback){
$.ajax({
type: "GET",
cache: false,
dataType: "json",
url: "https://someserviceURL/service/profile",
success: function(objJSON){
//storage.op is set on the parent page when login
or reg link is clicked
if (storage.op == "login") {
storage.firstname = objJSON.firstName;
storage.lastname = objJSON.lastName;
storage.setItem('loggedIn',JSON.stringify(true));
//Some browsers don't support booleans in
sessionStorage
nextPage = "dashboard.html";
}
else if (storage.op == "register") {
storage.firstname = objJSON.firstName;
storage.lastname = objJSON.lastName;
storage.setItem('loggedIn',JSON.stringify(true));
nextPage = "options.html";
}
},
error: function( jqXHR, textStatus, errorThrown){
//display error message
}
});
callback();
}
setStorage(function(){
if (typeof window.opener != "undefined" && window.opener
!= null){
setTimeout(function(){
window.opener.location.href = nextPage;
window.close();
},3000);
}
});
});
Problem: The window seems to be closing before I'm able to set the
sessionStorage values if I set the timeout to anything less than 3000. I
just want to close the window in response to those values being set, not
some arbitrary amount of time passing. I tried the trick of setting the
timeout to 0 but no luck, and I tried just the callback with no timeout.
Looking for best practices here on handling timing issues like these, what
I have now feels hacky. :)

Iframe in phonegap doesn't scroll to the bottom of the page

Iframe in phonegap doesn't scroll to the bottom of the page

I have a phonegap app that puts an iframe on the page. That works fine,
except that you can't scroll ("swipe") all the way to the bottom of that
iframe. It appears as though the bottom of the page is above where the
actual bottom is. And the fake bottom of the page is at different places
each time.
However, when you change the orientation of your phone, it now recognizes
the actual length of the page and now you can scroll all the way to the
bottom. It's like changing the orientation shocks it into behaving
properly.
I don't have this problem when just using a regular browser, only in
phonegap.
I'm wondering if maybe the outer page thinks the iframe page is a certain
length, then suddenly the iframe page grows bigger because an image was
finally loaded or something, and the outer page doesn't get properly
notified.
Any ideas? Any work-arounds?

List of named lists

List of named lists

I need to create a list of named lists in a python script.
What I want to do is create a mklist method that will take strings in a
list and create lists named for each of the strings. So, from here:
a = "area"
for i in range(1, 37):
x = str(a) + str("%02d" % (i,))
' '.join(x.split())
I want to get the following:
area01 = []
area02 = []
area03 = []
area04 = []
area05 = []
area06 = []
area07 = []
area08 = []
area09 = []
area10 = []
area11 = []
area12 = []
area13 = []
area14 = []
area15 = []
area16 = []
area17 = []
area18 = []
area19 = []
area20 = []
area21 = []
area22 = []
area23 = []
area24 = []
area25 = []
area26 = []
area27 = []
area28 = []
area29 = []
area30 = []
area31 = []
area32 = []
area33 = []
area34 = []
area35 = []
area36 = []
Any advice? I can't seem to get it. Thanks! E

IE9 Webdriver NoSuchWindowException

IE9 Webdriver NoSuchWindowException

I have problem with webdriver on IE9 (win7, c#, selenium 2.3). I get
NoSuchWindowException exception. I found that I need to change 'Enable
Protected Mode' for all Security Level to the same value. But I don't want
to change my settings generally and manually, just programmatically for
time of testing. I thought that I've just need to set
IntroduceInstabilityByIgnoringProtectedModeSettings to true and it will be
working, but it doesn't. My code (these lines work ok):
var option = new InternetExplorerOptions();
option.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
IWebDriver Driver = new InternetExplorerDriver(option);
Driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5));
Driver.Navigate().GoToUrl(baseUrl);
This cause exception:
Driver.Manage().Window.Maximize();
An exception of type 'OpenQA.Selenium.NoSuchWindowException' occurred in
WebDriver.dll but was not handled in user code
Additional information: Error retrieving window with handle current
also this:
string pageSource = Driver.PageSource;
An exception of type 'OpenQA.Selenium.NoSuchWindowException' occurred in
WebDriver.dll but was not handled in user code
Additional information: Unable to get browse
Do you have idea what is going wrong/what can I do to run my test?

Simple if statement stops code from working [duplicate]

Simple if statement stops code from working [duplicate]

This question already has an answer here:
How do I compare strings in Java? 28 answers
I'm having a problem with a simple if statement and i'm not too sure why.
I've got an edittext box and a button, when the user inputs a value into
the edittext and then presses the button, whatever was input into the box
is converted to string and stored in a variable, this variable is then
displayed in a toast. Now this works perfectly fine as it is but I would
like it to only display if a certain value is input into the editbox but
when I put in an if statement to validate this, it seems to completely
disgregard the if statement and does nothing. It does not cause any errors
but it stops any toast from being displayed even if the correct string is
input. I'm sure this is something simple but I can't seem to work it out.
It would be great if anyone could work out why it does this.
Code below:

Working code when the if statement is commented out:

saveBtn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Global.controlNum = inputTxt1.getText().toString();
// if((Global.controlNum == "1")||(Global.controlNum == "2" )){
Toast toast= Toast.makeText(SettingsScreen.this,"hello " +
Global.controlNum, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, -100);
toast.show();
// }
}
});

if the if statement is brought in then it will do nothing:

saveBtn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Global.controlNum = inputTxt1.getText().toString();
if((Global.controlNum == "1")||(Global.controlNum == "2" )){
Toast toast= Toast.makeText(SettingsScreen.this,"hello "
+ Global.controlNum, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, -100);
toast.show();
}
}
});

Tuesday, 20 August 2013

how to run multiple sql queries in cakephp

how to run multiple sql queries in cakephp

i am try to create dynamic menu. so i have to to run multiple sql queries.
i am trying a lot. i do this using normal php code.
"> "; while($fetch2=mysql_fetch_array($query2)){?>
"> "; while($fetch3=mysql_fetch_array($query3)){?>
">
"; } echo ""; } echo "
"; } echo ""; } echo ""; ?> but i cann't do this using cakephp. so please
help me how we can do this using cakephp. i can create the dynamic menu
using cakephp. i am using cakephp first time..

Yahoo web hosting with cakephp

Yahoo web hosting with cakephp

I have a problem about hosting at yahoo web hosting. i can't upload
.htaccess files so my cakephp site is not working there.
how can correct this issue please help.

Whats wrong with my mySQL_query?

Whats wrong with my mySQL_query?

When I use the query below, it only updates if the new value is shorter
than what was originally there, anyone know why this is?
mysql_query("UPDATE users SET first_name='$first_name',
last_name='$last_name', email='$email', bio='$bio' WHERE id='$id'");

Can't get a DIV to float above a DIV with image in it

Can't get a DIV to float above a DIV with image in it

Here are links to the syntax for the index page and the related CSS sheet.
(Used pastebin) I am trying to get "InfoBox" to float above the main
header image but instead it just pushes the image down. I have tried using
z-indexes and adjusting position but I can't get it to work. If anyone has
any ideas please let me know. Thanks :)
HTML Code: http://pastebin.com/WZ0zY8GD CSS Code:
http://pastebin.com/3atWdyEV

How to invoke or start an asp.net web service (asmx) from another project in C#

How to invoke or start an asp.net web service (asmx) from another project
in C#

How do I invoke or start a asp.net web service (asmx) from another project
in C#. The another project can be a console application. I am not asking
to consume the web service (which I am doing in Java) but how to start the
web service in C# but from a different project.
I already tried including the webservice project in my console application
project and also added a reference to the webservice project, included the
namespace but I get an error,
The type 'System.Web.Services.WebService' is defined in an assembly that
is not referenced. You must add a reference to assembly
'System.Web.Services, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a'.
I am trying to invoke the webservice by creating an instant of the
webservice class which I guess is already a wrong way.
Thanks in advance!

HTML anchors and content position

HTML anchors and content position

I have a sidebar with links (anchors) to the different parts of the site
content. The problem is that I have a fixed header and content position is
calculated from the top of the page. Is there any solution using only CSS
and HTML how to "jump" to the right position?
+----------------+
| fixed header |
+----------------+
| anch | content |
| | |
| | |
| | |
+------+---------+
Here is the link http://cafepavlac.cz/newcafe/content/page-list.php

PhpExcel won't create file on IE10

PhpExcel won't create file on IE10

I am using PhpExcel to create files containing a variable amount of data.
Here's how it works :
The user selects a start date and an end date
A list of profils is generated
The user clicks on a button called "To Excel" and a file containing a list
of events between the two selected dates for each profil is generated
When every xlsx file have been created, a zip archive is generated and the
usal download window appears
I tested it on FF, Chrome, Opera and IE9 and everything seems to be good.
The zip archive is valid and I can extract all the xlsx files which are
rightly generated.
Unfortunatly, on IE10, something strange happens: it only works half the
time (I tried once, it didn't work. I refreshed. It worked. I refreshed.
It didn't work and so on). What happens is that one or more xlsx file is
missing. For exemple, I expected to have 16 files and I only received only
15.
So I did things like this : when the user hits the "To Excel" button, for
each element of the list, an AJAX request is done and calls the "Excel
Script"
$.ajax({
type: "GET",
url: "rap_spec_excel_alt.php",
data:
"displayFacturation="+displayFacturation+"&startDateRapSpec="+startDate+"&endDateRapSpec="+endDate+"&codeEntSpec="+thisVal+"&delete=0&download=0&nbfiles="+nbFilesExpected,
success: function(data) {
},
error: function() {
}
});
I also test if it the current element is the first or the last element of
the list. If it is the first element, in my "Excel Script", I empty the
temporary folder containing the old xlsx files. If it is the last element,
on success, I call the "Zip Script" like this :
window.open("download_xls_zip.php?nbfiles="+nbFilesExpected);
So, in that way, I have the "confirm download box". My "Excel Script" is
huge so I will not post it entirely, but here's a glimpse :
//Delete old files
if ($_GET["delete"] == 1) {
$files = glob('tempxls/*');
foreach($files as $file){
if(is_file($file)) {
unlink($file);
}
}
}
//PHPExcel
include '../libs/pclzip/pclzip.lib.php';
error_reporting(E_ALL);
include '../libs/phpexcel/Classes/PHPExcel.php';
include '../libs/phpexcel/Classes/PHPExcel/Writer/Excel2007.php';
$objPHPExcel = new PHPExcel();
$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_discISAM;
PHPExcel_Settings::setCacheStorageMethod($cacheMethod);
$objPHPExcel->getProperties()->setCreator("John Doe");
$objPHPExcel->getProperties()->setLastModifiedBy("John Doe);
$objPHPExcel->getProperties()->setTitle($year.$month."_".$_GET["codeEntSpec"]);
$objPHPExcel->getProperties()->setSubject("File for ".$_GET["codeEntSpec"]);
$objPHPExcel->getProperties()->setDescription("File for
".$_GET["codeEntSpec"]);
$objPHPExcel->getDefaultStyle()->getFont()->setName('Arial');
$objPHPExcel->getDefaultStyle()->getFont()->setSize(8);
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(7.33);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(12);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(8);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(9.33);
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(22.67);
$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(15.67);
$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(14.67);
$objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(10.83);
$objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(9);
$objPHPExcel->setActiveSheetIndex(0);
//... AND SO ON ...
$objPHPExcel->getActiveSheet()->setTitle("File for ".$_GET["codeEntSpec"]);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('tempxls/'.$year.$month.'_'.$_GET["codeEntSpec"].'.xlsx');
When the "Zip Script" is called, it knows how many files should be in the
temporary folder. So it waits until every file has arrived and then, the
zip archive is created.
//PCLZip
include '../libs/pclzip/pclzip.lib.php';
//Number of files expected
$nbFilesExpected = $_GET["nbfiles"];
$filecount = 0;
//Count the files in the folder
while ($filecount != $nbFilesExpected) {
$dir = 'tempxls';
$i = 0;
if ($handle = opendir($dir)) {
while (($file = readdir($handle)) !== false){
if (!in_array($file, array('.', '..')) && !is_dir($dir.$file))
$i++;
}
}
$filecount = $i;
}
//Zip archive
if ($filecount == $nbFilesExpected) {
$archive = new PclZip('tempzip/archive.zip');
$archive->add('tempxls/');
header("content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=archive.zip");
readfile("tempzip/archive.zip");
flush();
unlink("tempzip/archive.zip");
}
Like I said, everything is good on with FF, Chrome, Opera and IE9. The
files are there, the zip archive also and the xlsx files are well formated
with the right data. But not in IE10...
What I've noticed, is if I choosed a large interval between each date, I
have many more data (of course). So, some files are not created because
they are to large (I have some limitations on my server) and a fatal error
appears. Therefore, the zip archive can't be created because some files
are missing.
I thought it could be the answer and I tried to solve the problem with
"$cacheMethod" but it didn't work. When the problem appears, I look in the
IE10's console but there is nothing (I even installed Firebug on IE...).
Can someone can give me a hand or just explain to me what I do wrong? It
would be much apprecietaded! Thank you very much!

Monday, 19 August 2013

Add application shortcut upon app installation

Add application shortcut upon app installation

I want to create my app's shortcut/launcher icon on the homescreen as soon
as I install my app (even before I start it). Is that possible ? How to do
that ?

added following to improve page speed to .htaccess

added following to improve page speed to .htaccess

I input the following into my .htaccess file for www.localmarketingus.com
<ifModule mod_deflate.c>
<filesMatch "\.(css|js|x?html?|php|xml|html)$">
SetOutputFilter DEFLATE
</filesMatch>
</ifModule>
# BEGIN Turn ETags Off
<ifModule mod_headers.c>
Header unset Pragma
Header unset ETag
</ifModule>
FileETag None
# END Turn ETags Off
# BEGIN Compress text files
<ifModule mod_deflate.c>
<filesMatch "\.(css|js|x?html?|php|xml|html)$">
SetOutputFilter DEFLATE
</filesMatch>
</ifModule>
# END Compress text files
# BEGIN Expire Headers
<IfModule mod_expires.c> ExpiresActive On
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType text/css "access plus 1 month"
ExpiresByType text/html "access plus 1 month"
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType text/x-javascript "access plus 1 year"
ExpiresByType application/javascript "access plus 1 month"
ExpiresByType application/x-javascript "access plus 1 month"
ExpiresByType application/x-shockwave-flash "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 year"
ExpiresDefault "access plus 1 month"
</IfModule>
#END Expire headers
#BEGIN Vary Accept Encoding
<IfModule mod_headers.c>
<FilesMatch "\.(js|css|xml|gz)$">
Header append Vary: Accept-Encoding
</FilesMatch>
</IfModule>
#END Vary Accept Encoding
<IfModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file \.(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</IfModule>
# BEGIN Cache-Control Headers
<ifModule mod_headers.c>
<filesMatch "\.(ico|jpe?g|png|gif|swf)$">
Header set Cache-Control "max-age=2592000, public"
</filesMatch>
<filesMatch "\.(css)$">
Header set Cache-Control "max-age=604800, public"
</filesMatch>
<filesMatch "\.(js)$">
Header set Cache-Control "max-age=216000, private"
</filesMatch>
<filesMatch "\.(x?html?|php)$">
Header set Cache-Control "max-age=600, private, must-revalidate"
</filesMatch>
</ifModule>
# END Cache-Control Headers
# BEGIN Remove Last-Modified Header
<ifModule mod_headers.c>
Header unset Last-Modified
</ifModule>
# END Remove Last-Modified Header
However, when i ran GTMetrix and PageSpeed insights it still said that i
need to leverage browser caching and vary: accept encoding??
Is there something I did wrong in the code??
Thanks,

convertion from dictionary to list preserving elements

convertion from dictionary to list preserving elements

I've a problem with convertion from this:
Counter({('pintor', 'NCMS000'): 1, ('ser', 'VSIS3S0'): 1, ('muralista',
'AQ0CS0'): 1, ('diego_rivera', 'NP00000'): 1, ('frida_kahlo', 'NP00000'):
1, ('caso', 'NCMS000'): 1})
that is obtained from this code:
res = collections.Counter(map(tuple, listaPalabras)) return res
But what I need is a list in this form:
[['pintor', 'NCMS000', 1], ['ser', 'VSIS3S0', 1], ['muralista', 'AQ0CS0',
1], ['diego_rivera', 'NP00000', 1], ['frida_kahlo', 'NP00000', 1],
('caso', 'NCMS000', 1]]
Thanks in advanced!

adding line break on pseudo element

adding line break on pseudo element

After each h2 I want to append and style a dash and after that a line break.
I tried the following:
h2:after {
content: '\A\2014';
white-space: pre;
font-size: 70px;
}
It does work in general, but when I in- or decrease the font-size, the
space both over and under the dash change, instead of just the dash-size.
I also tried adding a line-height: 0.6em; but it seems to move everything
around.
At the moment I'm getting this:

I want to get this, being able to change the space:

Here is the FIDDLE

Based on $form_id switch functions that are called

Based on $form_id switch functions that are called

We are creating a module to attach to some simple contact forms. Based on
the $form_id we need to scrape different hidden fields from the form. I've
written a simple switch statement:
switch ($form_id) {
case 4:
$this->stc_lead_tracker_service_call($form, &$form_state);
break;
case 2309:
$this->stc_lead_tracker_service_call_trucking($form, &$form_state);
break;
case 22:
$this->stc_lead_tracker_service_call_contact($form, &$form_state);
break;
}
The function is simply written like:
function stc_lead_tracker_service_call($form, &$form_state) {
do some stuff
}
Two questions. 1) am I using the correct syntax to call a function in the
switch statement? 2) Do I include ($form, &$form_state) in both the switch
and the function itself?

Sunday, 18 August 2013

QSqlDatabase Transactions,QSqlQuery Creation and QSqlQuery finish

QSqlDatabase Transactions,QSqlQuery Creation and QSqlQuery finish

I noticed that the QSqlDatabase documentation says that
"Note: When using transactions, you must start the transaction before you
create your query."
Doesn't this limit the usefulness of QSqlQuery::prepare() in case of
transactions if you have to create the query only after you have started
the transaction? The same question has been asked here... but no
satisfactory answer was provided.
My another question is that if you prepare a query using
QSqlQuery::prepare() and call QSqlQuery::finish(), should the query be
prepared again? I am asking this because there is no mention of prepared
queries in case QSqlQuery::finish() in docs.

Why does TimeSpan use duplicated TimeToTicks?

Why does TimeSpan use duplicated TimeToTicks?

TimeSpan has following constructors.
public TimeSpan(int hours, int minutes, int seconds)
{
this._ticks = TimeSpan.TimeToTicks(hours, minutes, seconds);
}
public TimeSpan(int days, int hours, int minutes, int seconds)
{
this = new TimeSpan(days, hours, minutes, seconds, 0);
}
public TimeSpan(int days, int hours, int minutes, int seconds, int
milliseconds)
{
long num = ((long)days * 3600L * 24L + (long)hours * 3600L +
(long)minutes * 60L + (long)seconds) * 1000L + (long)milliseconds;
if (num > 922337203685477L || num < -922337203685477L)
{
throw new ArgumentOutOfRangeException(null,
Environment.GetResourceString("Overflow_TimeSpanTooLong"));
}
this._ticks = num * 10000L;
}
I think TimeToTicks is just a simplification version of the last constructor.
Why does the first one not use this = new TimeSpan(days, hours, minutes,
seconds, 0);?

JQUERY - BUG - Sliding Window Does NOT Appear

JQUERY - BUG - Sliding Window Does NOT Appear

Please help me fixing this JQUERY issue. The code seems to be alright but
it must be something that I am missing.
Main Site: http://codeberg.com/demo/cnc/
The Jquery in issue resides here: http://codeberg.com/demo/cnc/js/cb2.js
Issue: Upon clicking over the buttion namely "Choose Your CNC Machine [+]"
, (Please Follow the Steps Below), Machines Disapper properly but Sliding
Window Does NOT Appear.
Issue Recreation:
Click on Any Machine Pictures on the top part of the webpage, EXCEPT for
the 2nd Last Machine (CNC JR Table Top) from the Right.

You will notice a sliding window poping under. You will also notice that
all the machine images get hidden.

You will also notice a Button to appear on the Top Right hand corner.

All is good here till this far.
Now, click on the "Choose Your CNC Machine [+]" button on the top right
hand corner.

It will lead you back to the Images of the Machines being visible now. But
the sliding window will remain visible. It is okay also

All is good here till this far.
However if I now click on the 2nd Last Machine (CNC JR Table Top) from the
right, the machine images disapper properly but

the content of the Sliding Window Does NOT Appear. This is supposed to
appear.
Expected Solution: A code fix or identification of error for me to display
the sliding window - #cb_container_jr-table-top (as per html source code).

Assigning fetched NSManagedObject to a property

Assigning fetched NSManagedObject to a property

This question may seem long, but I'm sure it's relativity simple for
Core-Data experts. Showing the configuration made this Question long.
Thanks!
In CoreData I have a User entity and an NSManagedObject subclass
(User.h/.m) created from that entity. Not sure if it's relevant, but I'm
using remote Database with Stackmob.
Here is what my fetch request looks like in Review.m:
if (fetchedObjects.count>=1)
{
NSLog(@"Number of Objects Returned %i", fetchedObjects.count);
NSManagedObject *fetchedObject = [fetchedObjects
objectAtIndex:0];
}
Here is the log:
2013-08-18 10:26:25.082 Time[995:c07] Number of Objects Returned 1
2013-08-18 10:26:25.082 Time[995:c07] User Object: <User: 0xe07b260>
(entity: User; id: 0xa65ab70
<x-coredata://392983AD-D649-4D68-A93F-D86109BC009C-995-000004B584F1BB06/User/piphone5>
; data: <fault>)
Several weeks ago I had created the User Object successfully with the
following:
User *newUser = [[User alloc]
initIntoManagedObjectContext:self.managedObjectContext];
[newUser setValue:self.usernameField.text forKey:[newUser primaryKeyField]];
[newUser setValue:self.emailAddressField.text forKey:@"email"];
[newUser setPassword:self.passwordField.text];
[newUser setValue:self.gender forKey:@"gender"];
[self.managedObjectContext saveOnSuccess:^{
[self.client loginWithUsername:self.usernameField.text
password:self.passwordField.text onSuccess:^(NSDictionary *results) {
NSLog(@"Login Success %@",results);
} onFailure:^(NSError *error) {
NSLog(@"Login Fail: %@",error);
}];
This is what I would like to do in Review.m:
@interface Review()
@property (strong, nonatomic) User *user;
@end
@sythesize = user;
....
if (fetchedObjects.count>=1)
{
NSLog(@"Number of Objects Returned %i", fetchedObjects.count);
NSManagedObject *fetchedObject = [fetchedObjects objectAtIndex:0];
NSLog(@"fetchObject Object %@", fetchedObject);
//Addition
user = (User*)(fetchedObject);
NSLog(@"User %@", user);
}
Here is the log:
2013-08-18 11:07:13.313 Time[1177:c07] Number of Objects Returned 1
2013-08-18 11:07:13.314 Time[1177:c07] fetchObject Object <User:
0xa532cc0> (entity: User; id: 0xb426de0
<x-coredata://3336122B-7117-4D92-B0A1-DDBAF80DDBF7-1177-000006EEE046E326/User/piphone5>
; data: <fault>)
2013-08-18 11:07:13.314 Time[1177:c07] User <User: 0xa532cc0> (entity:
User; id: 0xb426de0
<x-coredata://3336122B-7117-4D92-B0A1-DDBAF80DDBF7-1177-000006EEE046E326/User/piphone5>
; data: <fault>)
Why is this not working? User still shows up as Fault?
The Following is the reason I need to do this:
Notification *notificationObject = [NSEntityDescription
insertNewObjectForEntityForName:@"Notification"
inManagedObjectContext:self.managedObjectContext];
[notificationObject setValue:[NSNumber numberWithInt:1] forKey:@"appType"];
[notificationObject setValue:[notificationObject assignObjectId]
forKey:[notificationObject primaryKeyField]];
NSError *error = nil;
if (![self.managedObjectContext saveAndWait:&error])
{
NSLog(@"There was an error");
}
else
{
NSLog(@"Notification Object Created");
}
//I need to Add the fetchedObject as UsersObject (which is a
relationship)
[notificationObject addUsersObject:user];
[self.managedObjectContext saveOnSuccess:^{ ....
Here is my CoreData Setup:
Why is this not working? User still shows up as Fault?