Thursday, 3 October 2013

SSRS report builder 2.0 store STATIC DATA to use to query results

SSRS report builder 2.0 store STATIC DATA to use to query results

Does any one know if there is a way to import a spreadsheet into report
builder 2.0 and then use my data set to make calculations against.
This might seem like a novice question as my limited experience of report
builder does not help.
The reason i want to do this is so that i don't have to have my main
data-set run the query on working out averages of hundreds of thousands of
records as it take ages to run. by having the benchmark average data
static i would want to run my query and do the calculations in report
builder which will make it a 100 times faster.
Thank you for your time in advance

Wednesday, 2 October 2013

Python, replace long dash with short dash?

Python, replace long dash with short dash?

In python, I am trying to figure out how to replace strings with " – "
with " - ". The first one is a long dash, while the second one is a long
dash.
If I do something like:
If " – " in string:
string = string.replace(" – ", " - ")
then I get the following error:
SyntaxError: Non-ASCII character '\xe2' in file ./script.py on line 76,
but no encoding declared; see http://www.python.org/peps/pep-0263.html for
details
How can I fix this? Line 76 that the error is pointing to is my "If"
statement up there.

XML invalid tags

XML invalid tags

what i should do to prevent invalid XML tags in the custom getaway's
callback function?
$h = fopen("banks/Mybank/log.txt", 'a');
fwrite($h, 'ConfirmRequest:
'.print_r($_REQUEST['ConfirmRequest'],true)."\n");
fclose($h);
the output is:
ConfirmRequest: <ConfirmRequest><TransactionId> Cool Attitude
#89</TransactionId><PaymentId>327600020200</PaymentId><PaymentDate>02.10.2013
23:41:26</PaymentDate><Amount>7000</Amount><CardType>VISA!472291******9871</CardType><Status>N</Status><Reason>Declined
by merchant</Reason></ConfirmRequest>
the result is same on
$_REQUEST['ConfirmRequest'];
and
$this->resuest->request['ConfirmRequest'];

Creating a color array with distinct colors

Creating a color array with distinct colors

I'm trying to create an array which includes separate distinct colors.
Color array will created automatically when the range 'n' given. It's
something as following:
variable n = 2;
colourarrray = [red,green];
variable n = 4;
colourarrray = [red,green,blue,yellow];
What is the easiest method to generate such a color array?

django-facebook is not JSON serializable

django-facebook is not JSON serializable

I've been developing a django web-app, and I have to allow users to log in
using Facebook. In order to get this done I tried using django-facebook. I
simply followed their installation instructions but every time I try to
log-in with facebook I get the following error:
TypeError at /facebook/connect/
<open_facebook.api.OpenFacebook object at 0x7fb9311648d0> is not JSON
serializable
I've tried searching for all of the django-facebook related issues on
StackOverflow, and even rummaged through the issues on their GitHub repo,
but I couldn't find anything similar to my problem. I've also tried
searching for generic "object is not JSON serializable" questions, but I'm
not really sure how I would be able to apply any of those solutions since
the error seems to be happening in the django-facebook code.
Here's the full traceback:

Environment:
Request Method: POST
Request URL: http://foodtrip.ph/facebook/connect/?facebook_login=1
Django Version: 1.5.4
Python Version: 2.7.3
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'pinax_theme_bootstrap',
'django_forms_bootstrap',
'autocomplete_light',
'django_facebook',
'foodtrips')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django_facebook.middleware.FacebookCanvasMiddleWare')
Traceback:
File
"/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py"
in get_response
115. response = callback(request,
*callback_args, **callback_kwargs)
File
"/usr/local/lib/python2.7/dist-packages/django/views/decorators/csrf.py"
in wrapped_view
77. return view_func(*args, **kwargs)
File
"/usr/local/lib/python2.7/dist-packages/django_facebook/decorators.py"
in wrapped_view
98. response = self.authenticate(self.fn, request,
*args, **kwargs)
File
"/usr/local/lib/python2.7/dist-packages/django_facebook/decorators.py"
in authenticate
178. fn, request, graph=graph, *args, **kwargs)
File
"/usr/local/lib/python2.7/dist-packages/django_facebook/decorators.py"
in execute_view
137. result = view_func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django_facebook/views.py"
in connect
40. response = _connect(request, graph)
File "/usr/local/lib/python2.7/dist-packages/django_facebook/views.py"
in _connect
81. request, connect_facebook=connect_facebook)
File
"/usr/local/lib/python2.7/dist-packages/django_facebook/connect.py" in
connect_user
82. user = _login_user(request, converter, auth_user,
update=update)
File
"/usr/local/lib/python2.7/dist-packages/django_facebook/connect.py" in
_login_user
110. login(request, authenticated_user)
File
"/usr/local/lib/python2.7/dist-packages/django/contrib/auth/__init__.py"
in login
91. request.session.cycle_key()
File
"/usr/local/lib/python2.7/dist-packages/django/contrib/sessions/backends/base.py"
in cycle_key
271. self.create()
File
"/usr/local/lib/python2.7/dist-packages/django/contrib/sessions/backends/db.py"
in create
34. self.save(must_create=True)
File
"/usr/local/lib/python2.7/dist-packages/django/contrib/sessions/backends/db.py"
in save
51.
session_data=self.encode(self._get_session(no_load=must_create)),
File
"/usr/local/lib/python2.7/dist-packages/django/contrib/sessions/backends/base.py"
in encode
84. serialized = self.serializer().dumps(session_dict)
File "/usr/local/lib/python2.7/dist-packages/django/core/signing.py"
in dumps
100. return json.dumps(obj, separators=(',',
':')).encode('latin-1')
File "/usr/lib/python2.7/json/__init__.py" in dumps
238. **kw).encode(obj)
File "/usr/lib/python2.7/json/encoder.py" in encode
201. chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python2.7/json/encoder.py" in iterencode
264. return _iterencode(o, 0)
File "/usr/lib/python2.7/json/encoder.py" in default
178. raise TypeError(repr(o) + " is not JSON serializable")
Exception Type: TypeError at /facebook/connect/
Exception Value: is not JSON serializable
The settings file:

# Django settings for foodtripph project.
import os
PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__),
os.pardir))
PACKAGE_ROOT = os.path.abspath(os.path.dirname(__file__))
try:
DB_PASS = os.environ["DB_PASS"]
except KeyError:
error_msg = 'Please set the "DB_PASS" environment variable'
raise ImproperlyConfigured(error_msg)
try:
FACEBOOK_APP_ID = os.environ["FACEBOOK_APP_ID"]
except KeyError:
error_msg = 'Please set the "FACEBOOK_APP_ID" environment variable'
raise ImproperlyConfigured(error_msg)
try:
FACEBOOK_APP_SECRET = os.environ["FACEBOOK_APP_SECRET"]
except KeyError:
error_msg = 'Please set the "FACEBOOK_APP_SECRET" environment
variable'
raise ImproperlyConfigured(error_msg)
try:
SECRET_KEY = os.environ["SECRET_KEY"]
except KeyError:
error_msg = 'Please set the "SECRET_KEY" environment variable'
raise ImproperlyConfigured(error_msg)
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add
'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'dev', # Or path to database file
if using sqlite3.
# The following settings are not used with sqlite3:
'USER': 'ubuntu',
'PASSWORD': DB_PASS,
'HOST': 'localhost', # Empty for
localhost through domain sockets or '127.0.0.1' for localhost
through TCP.
'PORT': '', # Set to empty string for
default.
}
}
# Hosts/domain names that are valid for this site; required if DEBUG
is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = ['.foodtrip.ph', '.foodtrip.ph.', '.facebook.com',
'.facebook.com.']
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'Asia/Manila'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
# Absolute filesystem path to the directory that will hold
user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = os.path.join(PROJECT_ROOT, "site_media", "uploads")
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = "/media/"
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = os.path.join(PROJECT_ROOT, "site_media", "static")
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = "/static/"
# Additional locations of static files
STATICFILES_DIRS = [
]
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# List of callables that know how to import templates from various
sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
TEMPLATE_CONTEXT_PROCESSORS = [
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'django.core.context_processors.static',
'django.core.context_processors.tz',
'django.core.context_processors.request',
'django.contrib.messages.context_processors.messages',
#external
# 'account.context_processors.account',
'pinax_theme_bootstrap.context_processors.theme',
'django_facebook.context_processors.facebook',
]
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django_facebook.middleware.FacebookCanvasMiddleWare',
# 'account.middleware.LocaleMiddleware',
# 'account.middleware.TimezoneMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'foodtripph.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'foodtripph.wsgi.application'
TEMPLATE_DIRS = [
os.path.join(PROJECT_ROOT, 'site_media', 'templates'),
]
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
#theme
'pinax_theme_bootstrap',
'django_forms_bootstrap',
#external
# 'account',
'autocomplete_light',
'django_facebook',
#project
'foodtrips',
)
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer'
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
AUTH_USER_MODEL = 'django_facebook.FacebookCustomUser'
AUTHENTICATION_BACKENDS = (
'django_facebook.auth_backends.FacebookBackend',
'django.contrib.auth.backends.ModelBackend',
)
urls.py

from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin, auth
from django.views.generic import TemplateView
import autocomplete_light
autocomplete_light.autodiscover()
admin.autodiscover()
urlpatterns = patterns('',
#static pages
url(r'^$', TemplateView.as_view(template_name='homepage.html'),
name='home'),
# apps
url(r'^foodtrips', include('foodtrips.urls', namespace='foodtrips')),
#account
# url(r'^account/', include('account.urls')),
url(r'^facebook/', include('django_facebook.urls')),
url(r'^accounts/', include('django_facebook.auth_urls')),
# autocomplete
url(r'^autocomplete/', include('autocomplete_light.urls')),
# admin
url(r'^admin/', include(admin.site.urls)),
)
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
I have absolutely no idea how to go about fixing this problem. Any help is
greatly appreciated (and needed)!

Tuesday, 1 October 2013

c++ LibCURL Get a page's "full source"

c++ LibCURL Get a page's "full source"

A quick question on LibCURL with c++. I've got LibCURL getting page's
source from the web, going through it and picking data out.
Everything is working great bar one page. I had this problem during
offline testing while using ifstream and the page source saved to a .html
file. basically what's happening i think is the web page renders html +
data, the parts i want through js calls (not 100% sure of this) so its not
directly rendered in the source.
How i got around this in offline testing was to download the full web page
as a offline mode file on saffari, i believe it was called a .webarchive
file? this way when i viewed it as source code the html and data was
rendered in the source.
I've trolled the internet for an answer but can't seem to find one, can
anyone help me here on a setting in curl to download the webpage in its
"fullness"?
Here is what options i use currently.
curl_easy_setopt(this->curl, CURLOPT_URL, url);
curl_easy_setopt(this->curl, CURLOPT_FOLLOWLOCATION, 1);
curl_easy_setopt(this->curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Macintosh;
Intel Mac OS X 10.8; rv:24.0) Gecko/20100101 Firefox/24.0");
curl_easy_setopt(this->curl, CURLOPT_COOKIEFILE, "cookies.txt");
curl_easy_setopt(this->curl, CURLOPT_COOKIEJAR, "cookies.txt");
curl_easy_setopt(this->curl, CURLOPT_POSTFIELDS, postData); // if needed
curl_easy_setopt(this->curl, CURLOPT_WRITEFUNCTION, this->WriteCallback);
curl_easy_setopt(this->curl, CURLOPT_WRITEDATA, &readBuffer);
res = curl_easy_perform(this->curl);
Thanks in advance for your time! Regards, Matt

How does AutoHotKey determine if a copied string is a number?

How does AutoHotKey determine if a copied string is a number?

The following AutoHotKey snippet is supposed to:
Verify if copied string is a number
If so, search for that number in a website and in Windows Search.
Nothing happens. The If's expression is not seeing integers and bypasses
code.
Any ideas?
Send ^c
if ClipBoard is integer
{
Run, https://website/SREdit.jsp?id=%ClipBoard%
Run, search-ms:query=%ClipBoard%
}

Safe to install Nvidia drivers with my setup?

Safe to install Nvidia drivers with my setup?

I'm running Ubuntu 13.04 with Optirun/Primusrun installed, and I'm
experiencing a lot of Xorg crashes (Both in Unity and Gnome 3.8), and I
want to install the Nvidia drivers, as I'm currently using the standard
Intel drivers.
Is it safe for me to install the nvidia drivers through their installer?
or is it better to install them through apt-get?
And what do I do if it fails to boot?
Extra info:
GPU: Intel/Nvidia Geforce 520MX (Optimus Card)

Send logs to mulitple syslog servers

Send logs to mulitple syslog servers

we have a cisco 6500 chasis and I would like to send to the logs to two
separate syslog servers.
At present, it is already sent to one syslog server. That goes to our
security team. But we would like one to go to our network infrastructure
team as well.
Is that possible? If it is, can you assist?

Monday, 30 September 2013

How to perform If Statement in Field Calculator of ArcGIS for Desktop=?iso-8859-1?Q?=3F_=96_gis.stackexchange.com?=

How to perform If Statement in Field Calculator of ArcGIS for Desktop? –
gis.stackexchange.com

I have a shapefile containing two numeric fields ("Dist_1" and "Dist_2").
I want a Field Calculation that will populate an additional field
("Result") with one of three answers: First if Dist_1 is …

What is the best way to selectively grant and revoke access to FTP directories that are outside of the users home directory?

What is the best way to selectively grant and revoke access to FTP
directories that are outside of the users home directory?

I am the sysadmin for a public facing Debian server. This server primarily
serves websites from a custom built CMS. We have many contractors who are
preparing themes for these websites which are served from another server
where they have FTP access (this is a convenience while the themes are
under development). The themes are comprised of a CSS file plus supporting
fonts/images. The contractors do not currently have direct access to the
server that hosts the website (and is the ultimate resting place for the
themes). This has been a deliberate security decision but I'm looking at
opening that up now as it is preventing them from making changes to markup
which is the source of much frustration.
The way the system works is that each website has it's own "filestore"
directory which is where the theme and any custom code for the website
(MVC type structure) is based. The CMS application lives in /apps/appname
and the filestore directory lives on the same filesystem in
/apps/filestore. Each website has an ID and it's files are stored in
/apps/filestore/1234 for example.
I have recently installed proftpd to see whether I can configure it as
required and so far so good. I have specified that users (actual users on
the machine) are locked to their home directories which prevents them from
escaping and exploring the filesystem, however I still want to selectively
grant and revoke their access to the filestore directories which are
outside of their home directories. In my case giving them access to the
entire server and limiting their access via user and group permissions
isn't really an option.
For example, if bob needs to work on /apps/filestore/1234 I have
discovered that I can mount that directory from bob's home directory as
follows:
root@server:/home/bob# mkdir -p filestore/1234
root@server:/home/bob# mount --bind /apps/filestore/1234
/home/bob/filestore/1234
Then bob can log into his FTP account, go into filestore/1234 and access
the files as required. I can then remove his access by umounting the
directory later. This appears to work just nicely. It will be a small
sysadmin pain to have to do the mounting by hand all the time so I need to
automate the mounting / unmounting a little better, but is this the right
want to do it?
Thanks for your comments!
- Bob -

MySql Match() Against() return all rows containg a word

MySql Match() Against() return all rows containg a word

I currently use the following query to get search results, and it works ok.
select name from table where MATCH(name) AGAINST(:searchTerm IN BOOLEAN MODE)
Thing is, if a row contained a word MariaDb, and a user search for Maria,
it'll return no results. How is it possible to do a search query that'll
return all rows containing the words Maria?
Users can also search for multiple words like Computer software

Using Joins to query two tables

Using Joins to query two tables

I have two tables, "inventory" and "inventory_type". The "inventory" table
stores the name of it and the type, and the "inventory_type" table stores
the type name such as RAM, CPU, etc. and the sort order. I have never used
JOINS before and I am not sure which type to use, but none of them seem to
work with the following code.
As a side question, with my code below, would "inventory" be the left
table or would "inventory_type" be joined in on the left?
function getInventoryOptions($db, $default_value, $datacenter)
{
$query = "SELECT inventory.id, inventory.name, inventory_type.short_name
FROM inventory LEFT JOIN inventory_type
ON inventory.type = inventory_type.id WHERE
inventory.datacenter = " . $datacenter . " ORDER BY
inventory_type.sort_order ASC";
$result = mysql_query($query, $db);
echo '<option value="">None</option>';
if ($result)
{
while($row = mysql_fetch_array($result))
{
$id = $row["inventory.id"];
$name = $row["inventory.name"];
$type = $row["inventory_type.short_name"];
if ($default_value == $id)
{
echo '<option selected value="' . $id . '">' . $type . ":
" . $name . '</option>';
}
else
{
echo '<option value="' . $id . '">' . $type . ": " . $name
. '</option>';
}
}
}
}

Sunday, 29 September 2013

How can I keep my content from being cutoff with apache fop?

How can I keep my content from being cutoff with apache fop?

I am going through the Apache FOP quickstart. From the command line I am
converting a simple xml file that contains an svg element and converting
it to a pdf file. I am able to do this, but the image generated by the svg
is being cut off. I am new to XSL-FO & Apache FOP, but I did check out the
w3c documentation of properties. Now I'm even more confused,
unfortunately. I have tried the following with no luck: altering the width
& height properties in the svg itself; setting page-height & page-width to
"auto" in the simple page master element; eliminating the margin property.
I didn't see anything indicating the region-body starts with some default
size.
Here is the xml:
<chart>
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="600"
height="100">
<circle cx="50" cy="50" r="40" stroke="black" stroke-width="2"
fill="red" />
<circle cx="100" cy="100" r="40" stroke="black" stroke-width="2"
fill="green" />
</svg>
And here's the xsl:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:fo="http://www.w3.org/1999/XSL/Format">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">
<fo:root>
<fo:layout-master-set>
<fo:simple-page-master master-name="A4-portrait"
margin="10">
<fo:region-body/>
</fo:simple-page-master>
</fo:layout-master-set>
<fo:page-sequence master-reference="A4-portrait">
<fo:flow flow-name="xsl-region-body">
<fo:block>
<fo:instream-foreign-object
xmlns:svg="http://www.w3.org/2000/svg" content-width="600"
content-height="300">
<svg:svg>
<xsl:copy-of select="/chart/svg:svg"/>
</svg:svg>
</fo:instream-foreign-object>
</fo:block>
</fo:flow>
</fo:page-sequence>
</fo:root>
</xsl:template>
</xsl:stylesheet>
The image is supposed to show a red & green circle overlapping, but it's
only showing the upper left corner of the green one. I expect there's a
property in the block element I am missing, but I don't know which. I
looks like the block is limited to a 100px x 100px size.
What am I missing of the properties and how can I get the whole svg image
to show properly (two full circles overlapping)?
Thanks,
Brandt
PS: I would have sent an image showing the problem, but I don't have a
high enough reputation.

Crystal Report Sum of a Column data

Crystal Report Sum of a Column data

I have field GrandTotal in my dataset which i am showing in my report.i
want show the total of all data in the footer .
My column data are string .
I tried to make a formula as bellow
SUM(ToNumber({Ds.Grandtotal}))
But its saying a field is require.Please help me.

Flash action script tweenlite 1084

Flash action script tweenlite 1084

I'm a beginner in flash i got an error in actions script 3.0
I'm using tween lite
I got the error 1084: Syntax error: expecting colon before comma.
its about this line
TweenLite.to(balk_mc, 1, {x:141,35, y:balk_mc.y});
And it says line 10 and 16
The whole code im using is:
import flash.events.MouseEvent;
import com.greensock.*;
stop();
button1.addEventListener(MouseEvent.CLICK, button1_clicked);
function button1_clicked(e:MouseEvent):void{
gotoAndStop("page1");
TweenLite.to(balk_mc, 1, {x:141,35, y:balk_mc.y});
}
button2.addEventListener(MouseEvent.CLICK, button2_clicked);
function button2_clicked(e:MouseEvent):void{
gotoAndStop("page2");
TweenLite.to(balk_mc, 1, {x:330,6, y:balk_mc.y});
}
button3.addEventListener(MouseEvent.CLICK, button3_clicked);
function button3_clicked(e:MouseEvent):void{
gotoAndStop("page3");
TweenLite.to(balk_mc, 1, {x:551, y:balk_mc.y});
var number:Number = 1;
next_btn.addEventListener(MouseEvent.CLICK, nextImage);
checkNumber();
function nextImage(event:MouseEvent):void {
//trace("next button geklikt!");
number++;
loader.source = "images/tommorrowland"+number+".png";
checkNumber();
}
previous_btn.addEventListener(MouseEvent.CLICK, previousImage);
function previousImage(event:MouseEvent):void {
//trace("previous button geklikt!");
number--;
loader.source = "images/tommorrowland"+number+".png";
checkNumber();
}
function checkNumber():void {
next_btn.visible = true;
previous_btn.visible = true;
if(number == 4){
next_btn.visible = false;
}
if(number == 1){
previous_btn.visible = false;
}
}
}
button4.addEventListener(MouseEvent.CLICK, button4_clicked);
function button4_clicked(e:MouseEvent):void{
gotoAndStop("page4");
TweenLite.to(balk_mc, 1, {x:551, y:balk_mc.y});
}

array in function outputs nothing

array in function outputs nothing

When I am trying to add values to an array it just output array for me,
function getAllRoles($format='ids')
{
$format = strtolower($format);
$query = $this->db->prepare("SELECT * FROM roles");
$query->execute();
$resp = array();
foreach ($query as $row){
if ($format == 'full'){
$resp[] = array("ID"=>$row['ID'],"Name"=>$row['roleName']);
}else{
$resp[] = $row['ID'];
}
}
return $resp;
}
To get the array I typed,
echo "<br>getAllRoles: ".$Secure->getAllRoles("full");

Saturday, 28 September 2013

cannot change content of div - Uncaught TypeError: Cannot set property 'innerHTML' of null

cannot change content of div - Uncaught TypeError: Cannot set property
'innerHTML' of null

I would like to change the contents of a div, using javascript and innerHTML.
I cannot get it to work. I just added the code for changing the div,
before that the code was working fine. I double checked the syntax.
I'm using webshims, openlayers and jquery/javascript
In the in the console I see
Uncaught TypeError: Cannot set property 'innerHTML' of null imagegaledit -
myFile.php :768 so.onmessage - myFile.php :324
768 is that line document.getElementById("imgedtitle").innerHTML=mnmi[0];
and 324 is this imagegaledit(0);
Little help? Thanks
edit websockets work and responce fine
Here is the code (concise and simplified)
<!doctype html>
<header>
<meta charset="utf-8">
<meta http-equiv="content-type" content="text/html">
<script src="jquery-1.8.2.min.js"></script>
<script src="js-webshim/minified/extras/modernizr-custom.js"></script>
<script src="js-webshim/minified/polyfiller.js"></script>
<script>
$.webshims.polyfill();
</script>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<!--open layers api library-->
<script type='text/javascript' src='OpenLayers.js'></script>
<script type='text/javascript'>
//openlayers vars and stuff here...
function init(){
//when a point on map clicked...
function selected_feature(event){
//some openlayers magic...
var so = new WebSocket("ws://localhost:8000");
so.onerror=function (evt)
{response.textContent = evt;}
so.onopen = function(){
response.textContent = "opened";
so.send(JSON.stringify({command:'map',fmid:jas}));
}
so.onmessage = function (evt) {
var received_msg = evt.data;
var packet = JSON.parse(received_msg);
//pass data to var and arrays...
imagegaledit(0);
}
}//closes function selected_feature
}//closes init
function imagegaledit (w){
if (w==0){
document.getElementById("imgedtitle").innerHTML=mnmi[0];
}
}//closes imagegaledit
</script>
<body onload='init();'>
Title</br><div id="imgedtitle"> </div> </br>
</body>

Button Variable VB.Net

Button Variable VB.Net

im creating a game the uses Skills such as heal, strike etc. i want they
player to be able to assign the skill to a hotkey. but im looking for a
way where i can make a "Variable" button, that can do things like this:
change a variable like "Name"'s value to an already created button name
value. EX:
Dim bla As New Button
Private Sub btnHot3_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnHot3.Click
bla = New Button
bla.Name = "btnHot3"
Hotkey(SkillUsed, bla)
End Sub
Sub Hotkey(ByVal skillused As Integer, ByVal bla As Button)
If SkillSelected = 1 Then
btnHot3.Image = My.Resources.Heal
ElseIf SkillSelected = 2 Then
bla.Image = My.Resources.Strike
ElseIf SkillSelected = 3 Then
bla.Image = My.Resources.Finisher
End If
End Sub

slow website load and high memory usage

slow website load and high memory usage

my site has been slowed down last couple of days ... some image doesn't
show up ... i got
408 Request Time-out: Server timeout waiting for the HTTP request from the
client
couple of times which never happened before .
i did a little performance checking , basically top command in ssh
this is the result
http://up.akstube.com/images/vdtebe9sr10si1eyycd.jpg
as you can see memory usage is very high ... or i think it is .
i've rebooted the server ... it wend down but after while it goes up again
.... (this is about an hour after reboot )
http://up.akstube.com/images/49xjeylxy0st7vwn4ojl.png
after half an hour =>
top - 16:14:22 up 1:56, 2 users, load average: 0.62, 0.90, 1.15
Tasks: 303 total, 1 running, 302 sleeping, 0 stopped, 0 zombie
Cpu(s): 8.0%us, 0.2%sy, 0.0%ni, 91.4%id, 0.0%wa, 0.0%hi, 0.3%si,
0.0%st
Mem: 32840004k total, 21037648k used, 11802356k free, 430832k buffers
Swap: 1050616k total, 0k used, 1050616k free, 16527108k cached
right now
[root@ns4008353 ~]# top
top - 16:33:25 up 2:15, 2 users, load average: 0.88, 0.94, 0.98
Tasks: 303 total, 3 running, 300 sleeping, 0 stopped, 0 zombie
Cpu(s): 6.8%us, 0.2%sy, 0.0%ni, 92.8%id, 0.0%wa, 0.0%hi, 0.1%si,
0.0%st
Mem: 32840004k total, 22388160k used, 10451844k free, 434964k buffers
Swap: 1050616k total, 0k used, 1050616k free, 17324104k cached
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
7532 mysql 20 0 3750m 492m 5556 S 18.0 1.5 49:53.58 mysqld
12903 apache 20 0 232m 40m 4864 S 16.3 0.1 0:56.74 httpd
7748 apache 20 0 235m 43m 5256 S 11.6 0.1 1:33.36 httpd
8010 apache 20 0 262m 70m 4856 R 6.7 0.2 1:32.05 httpd
7747 apache 20 0 235m 43m 5220 S 1.3 0.1 1:06.37 httpd
7749 apache 20 0 222m 30m 5164 S 1.3 0.1 1:58.53 httpd
7996 apache 20 0 250m 59m 5476 S 1.3 0.2 1:37.37 httpd
10 root 20 0 0 0 0 S 0.3 0.0 0:09.72 rcu_sched
7714 apache 20 0 265m 73m 4972 S 0.3 0.2 1:34.53 httpd
7905 named 20 0 669m 24m 3020 S 0.3 0.1 0:02.01 named
7999 apache 20 0 232m 40m 4968 S 0.3 0.1 1:17.67 httpd
20865 root 20 0 0 0 0 S 0.3 0.0 0:01.05 kworker/2:2
21491 root 20 0 15212 1308 852 S 0.3 0.0 0:01.38 top
23810 root 20 0 15212 1340 852 R 0.3 0.0 0:00.07 top
1 root 20 0 19404 1568 1268 S 0.0 0.0 0:00.58 init
2 root 20 0 0 0 0 S 0.0 0.0 0:00.00 kthreadd
free m
[root@ns4008353 ~]# free -m
total used free shared buffers cached
Mem: 32070 21897 10173 0 424 16955
-/+ buffers/cache: 4516 27553
Swap: 1025 0 1025
do you think this the reason of slow response ? is there any comment to
get more info about what is using the memory ?



i have a dedicate server :
Processor Name Intel(R) Xeon(R) CPU E3-1245 V2 @ 3.40GHz
Vendor ID GenuineIntel
Processor Speed (MHz) 1600.000
Total Memory 32840004 kB
Free Memory 10416752 kB
Total Swap Memory 1050616 kB
Free Swap Memory 1050616 kB
System Uptime 0 Days, 2 Hours and 22 Minutes
Apache 2.2.24 Running
DirectAdmin 1.43.0 Running
Exim 4.76 Running
MySQL 5.5.31 Running
Named 9.8.2rc1 Running
ProFTPd 1.3.4d Running
sshd Running
dovecot 2.2.4 Running
Php 5.3.26 Installed

What are the causes of booting problems?

What are the causes of booting problems?

Can anyone please help me by answering these questions(all related to
booting):
F2 not working when trying to enter BIOS settings.
The Motherboard load screen will not continue loading unless a keyboard
key is pressed.
Keyboard not working when entering the F12 Booting Options.
These problems have been bugging me for 3 days now I had some friends help
me fix it but still it remains. Can anyone tell me why those things
enumerated above are happening? Please!

Friday, 27 September 2013

virtualenvwrapper: where is virtualenv info stored?

virtualenvwrapper: where is virtualenv info stored?

I regularly use setvirtualenvproject /path/to/my/project/ to set the
root/base directory of my virtual env. This is useful when switching to a
virtual env using workon myenv.
I was wondering though, if this path is available anywhere else?
In my case, I want to run a pre-push hook in git, and need to get the full
path to some of my files. e.g. something like this in my pre-push hook:
do_something $VIRTUALENV_PROJECT/my/important/file.txt
Is there any way I can retrieve this 'virtualenvproject' info, or where is
it stored?
I've tried looking in env, the .virtualenvs dir and every other place I
can think of, but I just can't find where the info's stored.

Distinct on one column with multiple results

Distinct on one column with multiple results

I have a problem with my query through visual basic to access database.
Lets say I have two tables as bellow.
+-------+-------------+-------------+------------+
| ID | Date1 | Date2 | CustomerID |
+-------+-------------+-------------+------------+
| 1 | 1-1-2013 | 1-1-2012 | 1 |
| 2 | 1-1-2013 | 1-1-2012 | 1 |
| 3 | 1-1-2013 | 1-1-2012 | 2 |
| 4 | 1-1-2013 | 1-1-2012 | 3 |
| 5 | 1-1-2013 | 1-1-2012 | 3 |
+-------+-------------+-------------+------------+
and
+----------+---------+
| ID | Name |
+----------+---------+
| 1 | John |
| 2 | Tina |
| 3 | Patrick |
+----------+---------+
I would like to get result with only unique numbers from Customer - ID in
first table like this one bellow.
+----------+----------+-------------+------------+
| ID | Date1 | Date2 | CustomerID |
+----------+----------+-------------+------------+
| 1 | 1-1-2013 | 1-1-2012 | 1 |
| 2 | 1-1-2013 | 1-1-2012 | 2 |
| 3 | 1-1-2013 | 1-1-2012 | 3 |
+----------+----------+-------------+------------+
I've tried with this query but with no luck.
sqL = " SELECT DISTINCT Order.ID, Order.Date1, Order.Date2, Customer.Name
FROM Order (Order INNER JOIN Customer ON Order.CustomerID = Customer.ID)"
But the code does not give me the result I wanted. Can you please provide
me some help with my query.

Ajax Tooltips with data-id

Ajax Tooltips with data-id

I´m using qtip2 ajax-tooltips. This is the script
(http://jsfiddle.net/craga89/L6yq3/):
// Create the tooltips only when document ready
$(document).ready(function()
{
// MAKE SURE YOUR SELECTOR MATCHES SOMETHING IN YOUR HTML!!!
$('a').each(function() {
$(this).qtip({
content: {
text: 'Loading...',
ajax: {
url: 'http://qtip2.com/demos/data/owl',
loading: false
}
},
position: {
viewport: $(window)
},
style: 'qtip-wiki'
});
});
});
To use the script i need the link of the ajax file:
<a href='http://qtip2.com/demos/data/snowyowl'>Snowy Owl</a>
I want to call the ajax file without the link, but with the data-id
attribute, so it looks like:
<a href="#" data-id="1">Snowy Owl</a>
How to make it?
To make it more clear, something like this code:
var urlFormat = "/content/web/tooltip/ajax/ajaxContent{0}.html";
$(document).ready(function() {
$("#products").qtip({
filter: "a",
content: {
url: "/content/web/tooltip/ajax/ajaxContent1.html"
},
width: 520,
position: "top",
requestStart: function(e) {
e.options.url = qtip.format(urlFormat,
e.target.data("id"));
}
});
$("#products").find("a").click(false);
});

Struggling to parse different text files based on their delimiters

Struggling to parse different text files based on their delimiters

Ive been working on this on and off today.
Here is my method, which basically needs to accept a .data (txt) file
location, and then go through the contents of that text file and break it
up into strings based on the delimiters present. These are the 2 files.
The person file.
Person ID,First Name,Last Name,Street,City
1,Ola,Hansen,Timoteivn,Sandnes
2,Tove,Svendson,Borgvn,Stavanger
3,Kari,Pettersen,Storgt,Stavanger
The order file.
Order ID|Order Number|Person ID
10|2000|1
11|2001|2
12|2002|1
13|2003|10
public static void openFile(String url) {
//initialize array for data to be held
String[][] myStringArray = new String[10][10];
int row = 0;
try {
//open the file
FileInputStream fstream = new FileInputStream(url);
BufferedReader br = new BufferedReader(new
InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
//ignores any blank entries
if (!"".equals(strLine)) {
//splits by comma(\\| for order) and places
individually into array
String[] splitStr = new String[5];
//splitStr = strLine.split("\\|");
/*
* This is the part that i am struggling with getting
to work.
*/
if (strLine.contains("\\|")) {
splitStr = strLine.split("\\|");
} else if (strLine.contains(",")) {
splitStr = strLine.split(",");
}else{
System.out.println("error no delimiter detected");
}
for (int i = 0; i < splitStr.length; i++) {
myStringArray[row][i] = splitStr[i];
System.out.println(myStringArray[row][i]);
}
}
}
//Close the input stream
br.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE,
null, ex);
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE,
null, ex);
}
}
The person file is correctly read and parsed. But the order file with the
"|" delimiter is having none of it. I just get 'null' printouts.
Whats confusing me is that when i just have splitStr =
strLine.split("\|"); It works but i need this method to be able to detect
the delimiter present and then apply the correct split.
Any help will be much appreciated

Magento needs a storeview set to update attribute on website scope

Magento needs a storeview set to update attribute on website scope

It seems like I have to set a store view before I can update an attribute
on website scope – is that correct?
My code:
Mage::app('admin');
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$product = Mage::getModel('catalog/product');
$product->load(123);
$product->setStoreId('1'); // without this line the attribute is not updated
$product->setSomeattribute("abc");
$product->save();

Start server with help of Jetty runner

Start server with help of Jetty runner

What I have:
Application which starts embedded jetty server in main method. When I need
to move it on the server I should make a myApp.jar and launch it on the
server.
What I want: Not start embedded jetty server inside of application, but
make myApp.war file and start it with help of Jetty runner
What a problem: Before start embedded server I set WebsocketHandler to my
server, and then ResourceHandler to the WebsocketHandler (see code below).
I have no idea how to pass those params with help of jetty runner command.
Question:
May I use java -jar jetty-runner.jar contexts/my.xml? If yes, how can I do
that?
WebSocketHandler handler = new WebSocketHandler() {
@Override
public void configure(WebSocketServletFactory factory) {
factory.getPolicy().setMaxMessageSize(4533423);
factory.getPolicy().setIdleTimeout(Long.MAX_VALUE);
factory.setCreator(creator);
}
};
Server server = new Server(8080);
server.setHandler(handler);
ResourceHandler resourceHandler = new ResourceHandler();
resourceHandler .setDirectoriesListed(true);
resourceHandler .setResourceBase(WEB_CLIENT_PATH);
handler.setHandler(resourceHandler );
server.start();
server.join();

postgresql copy command delimiter non aphanumeric character

postgresql copy command delimiter non aphanumeric character

I am facing issue while copying a file which is delimited by §. The
database version is 9.1
File content are as below:
a§b§c 1§4§5
Copy command: copy test.test_ingestion (a,b,c) from 'b.csv' CSV HEADER
DELIMITER as E'§';
Error : invalid byte sequence for encoding "UTF8": 0xa7
As per my understanding § is a UTF-8 character and encoding of database is
set to UTF-8. So why is it failing to copy file delimited by §.

Thursday, 26 September 2013

MongoDB and Node js Asynchronous programming

MongoDB and Node js Asynchronous programming

I am trying to solve an exam problem, so I cannot post my exam code as it
is. So I have simplified such that it addresses the core concept that I do
not understand. Basically, I do not know how to slow down node's
asynchronous execution so that my mongo code can catch up with it. Here is
the code:
MongoClient.connect('mongodb://localhost:27017/somedb', function(err, db) {
if (err) throw err;
var orphans = [];
for (var i; i < 100000; i++) {
var query = { 'images' : i };
db.collection('albums').findOne(query, function(err, doc_album) {
if(err) throw err;
if (doc_album === null) {
orphans.push(i);
}
});
}
console.dir(orphans.length);
return db.close();
});
So I am trying to create an array of those images who do not match my
query criteria. I end up with a orphans.length value of 0 since Node does
not wait for the callbacks to finish. How can I modify the code such that
the callbacks finish executing before I count the number of images in the
array that did not meet my query criteria?
Thanks in advance for your time.
Bharat

Wednesday, 25 September 2013

wordpress :The uploaded file could not be moved to wp-content/uploads

wordpress :The uploaded file could not be moved to wp-content/uploads

i am trying to upload the pictures in wordpress but i get the error "The
uploaded file could not be moved to wp-content/uploads."
i am using it in localhost but the answers i have found are in the server
to change the folder permission to 777.
the thing i tried is making a upload folder myself, but its of no use and
there is no option to change the folder permission except read and write
i am new to wordpress, is there a soulution towards it?
i am using xaamp and Mac OS

Thursday, 19 September 2013

Pros and cons of live search

Pros and cons of live search

I searched everywhere but couldn't find the pros and cons of using live
search (autocomplete). Can please someone list them? I want to know if its
good idea to use live search because I think if too many users use live
search at the same time there may be lag or other problems.

How to swap an H1 element from an H1 in another document using JQuery

How to swap an H1 element from an H1 in another document using JQuery

Please bear with me because I'm student. My instructor had us watch 5
YouTube videos and now expects us to program using JQuery instead of
standard JavaScript. All I want to do is swap an element with an element
from another file.
Here's my HTML code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Testing JQuery</title>
<script src="jquery-1.7.2.min.js"></script>
</head>
<body>
<h1 id="header">Testing JQuery</h1>
<p id ="dummy">Lorem Ipsum </p>
<script src="changes.js"></script>
<form name="input" action="changes.js">
<input type="button" value="Change the Header">
</form>
</body>
</html>
Here is my JavaScript/JQuery code:
$(document).ready(function() {
$('input').click(function() {
var url = $(this).attr('form');
$('#header').load( greeting.html + '#ajax h1');
return false;
});
});
The third file is called greeting.html and this is all it contains:
<h1 id="ajax">Hello from jQuery with AJAX</h1>

How to extract a part of a string in a CSV file and replace it with

How to extract a part of a string in a CSV file and replace it with

I am trying to search and replace the text with the following pattern in
the CSV file.
20130910-083850-msaifullah-2205859.jpg in the cell row of a CSV and needs
to be replaced with their respective text which is the last digits of the
name '2205859' and no extension before or after the numbers should be
outputted and replaced in the CSV.

JQuery javascript Galleria IO

JQuery javascript Galleria IO

i have a galleria using IO everything runs smoothly but i have a problem
when i try to delete the selected image on the gallery.
here is the code i am using
var gallery = $('#galleriaID').data('galleria');
var index = gallery.getIndex();
gallery.splice(index,1);
gallery.next();
everything runs smoothly but when i try to delete the penultimate image on
the gallery doesn't remove and the gallery is blocked in the console i am
watching
TypeError: data is undefined
version "+version+" to use one or more
components.";if(Galleria.version<version...
galler...BC32189 (line 3)
TypeError: self.getData(...) is undefined
i am aware is only trying to delete the penultimate image int the gallery
what i am doing wrong there is some workaround??
thanks a lot...

Insert sequnce number into a table

Insert sequnce number into a table

I want to insert into a table a sequence number for each row, I am using
this query but it is not working: INSERT INTO header(seqno) values
(rownum)

Bean property is not readable with Spring MVC

Bean property is not readable with Spring MVC

I am building a system using spring MVC and now I am doing the .jsp page
and I get the following error message :
Invalid property 'flrequest' of bean class
[se.lowdin.jetbroker.agent.mvc.FlightRequestBean]: Bean property
'flrequest' is not readable or has an invalid getter method
Does the return type of the getter match the parameter type of the setter?
I have put this code in my flightRequest.jsp:
<tr>
<th>Departure Airport</th>
<td><form:select path="flrequest" items="${airport}"/></td>
</tr>
<tr>
<th>Arrival Airport</th>
<td><form:select path="flrequest" items="${airport}"/></td>
</tr>
And my bean looks like this:
public class FlightRequestBean {
private Customer customer;
private long id;
private FlightStatus flightStatus;
private long numberOfPassengers;
private DateTime datetime;
public void copyValuesToBean(FlightRequest request){
setCustomer(request.getCustomer());
setId(request.getId());
setFlightStatus(request.getFlightStatus());
setNumberOfPassengers(request.getNumberOfPassengers());
setDatetime(request.getDatetime());
}
public void copyBeanToFlightRequest(FlightRequest request){
request.setCustomer(getCustomer());
request.setId(getId());
request.setFlightStatus(getFlightStatus());
request.setNumberOfPassengers(getNumberOfPassengers());
request.setDatetime(getDatetime());
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getNumberOfPassengers() {
return numberOfPassengers;
}
public void setNumberOfPassengers(long numberOfPassengers) {
this.numberOfPassengers = numberOfPassengers;
}
public DateTime getDatetime() {
return datetime;
}
public void setDatetime(DateTime datetime) {
this.datetime = datetime;
}
public FlightStatus getFlightStatus() {
return flightStatus;
}
public void setFlightStatus(FlightStatus flightStatus) {
this.flightStatus = flightStatus;
}
}
I also have a hashmap that contains mocked airports I am trying to display
it in my form:select. When I et the error. The indexcontroller holding are
having other list that disply well but the hashmap aint displyaing.
@Controller
public class IndexController {
@Inject
CustomerService customerService;
@Inject
FlightRequestService flightService;
@Inject
AirportService airportService;
@RequestMapping("/index.html")
public ModelAndView index() {
List<FlightRequest> requests = flightService.getAllFlightRequest();
List<Customer> customers = customerService.getAllCustomers();
HashMap<Long, Airport>airport = airportService.getAllAirportCodes();
ModelAndView mav = new ModelAndView("index");
mav.addObject("flightRequests", requests);
mav.addObject("customers", customers);
mav.addObject("airportCodes", airport);
return mav;
}
}
Then finally I have my flightRequest controller :
@Controller
@RequestMapping("/flightRequest/{id}.html")
public class FlightRequestController {
@Inject
FlightRequestService service;
@RequestMapping(method = RequestMethod.GET)
public ModelAndView index(@PathVariable long id) {
FlightRequestBean bean = new FlightRequestBean();
if (id > 0) {
FlightRequest flrequest = service.getFlightRequest(id);
bean.copyValuesToBean(flrequest);
}
ModelAndView mav = new ModelAndView("flightRequest");
mav.addObject("flightRequestBean", bean);
return mav;
}
@RequestMapping(method = RequestMethod.POST)
public ModelAndView handleSubmit(FlightRequestBean bean) {
if (bean.getId() > 0) {
FlightRequest flrequest = service.getFlightRequest(bean.getId());
bean.copyBeanToFlightRequest(flrequest);
service.updateFlightRequest(flrequest);
} else {
FlightRequest flrequest = new FlightRequest();
bean.copyValuesToBean(flrequest);
service.createFlightRequest(flrequest);
}
return new ModelAndView("redirect:/index.html");
}
}
So somewhere there is a problem causing that error message. Does anyone
have a clue what is the cause of that problem? The error message say
something about invalid getters and setters? But how can it be since I am
using a hashmap and not

Wednesday, 18 September 2013

Printing data from mysql via web app

Printing data from mysql via web app

My dad's recommended to me that I add functionality to my web-based job
tracking system that'll allow users to print job cards for a physical copy
of the captured job.
I know that most web browsers handle this sort of functionality to allow
you to print out the page, but to actually retrieve the job data from the
database and send it straight to the printer is beyond me.
I have, in the past, generated PDF files from stored data that can be
downloaded to a client pc and then printed, but for some reason, I'm
thinking there's a more direct way to manage it, can anyone suggest any
possible solutions I could try?
I'll happily accept a "your PDF export is the only way you're going to do
this" type of answer as well.

Trigger jQuery event (bPopup) on specific dropdown value selected

Trigger jQuery event (bPopup) on specific dropdown value selected

I am trying to trigger a popup to appear if and only if a given value is
selected from the list.
The value of the dropdown menu is determined by session data, as such the
dropdown can be any of the options available on page load.
I want a popup (I am using bPopup plugin) to appear if a specific
selection is set on page load.
My dropdown
This is the HTML/javascript as it appears in browser source:
<select
onchange="this.form.submit()"
name="country"
id="country_drop"
>
<option value="select">Please Select</option>
<option value="Afghanistan">Afghanistan</option>
<option value="Angola">Angola</option>
<option value="Argentina">Argentina</option>
</select>
This is the jquery I'm trying to use to generate the popup if the slection
is Angola on page load:
$(document).ready(function() {
if($("#country_drop").val()=="Angola");
{
$('#popup').bPopup({
opacity: 0.6,
modalClose: true
});
}
});
What is currently happening:
Page loads popup on page load irrespective of selection, 100% of the time.

Android TextWatcher afterTextChanged

Android TextWatcher afterTextChanged

I have to take the value of the EditText and divide it by 1.21....where is
the error
private TextWatcher filterTextWatcher = new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int
end) {
}
public void afterTextChanged(Editable s) {
double imponibile21;
Importo.getText().toString();
if (spinnerIva.getSelectedItem().toString().equals("21%")){
Double value = Double.valueOf(""+Importo);
imponibile21 = (value/1.21);
NumberFormat formatter = NumberFormat.getCurrencyInstance();
String Imponibile = formatter.format(imponibile21 );
mImponibile.setText(Imponibile);
09-18 22:59:56.617: E/AndroidRuntime(27425):
java.lang.NumberFormatException: Invalid double:
"android.widget.EditText{421f9c38 VFED..CL .F...... 0,664-1080,781
#7f08000b app:id/ed_importo_fattura}"
09-18 22:59:56.617: E/AndroidRuntime(27425): at
java.lang.StringToReal.invalidReal(StringToReal.java:63) 09-18
22:59:56.617: E/AndroidRuntime(27425): at
java.lang.StringToReal.initialParse(StringToReal.java:114) 09-18
22:59:56.617: E/AndroidRuntime(27425): at
java.lang.StringToReal.parseDouble(StringToReal.java:263) 09-18
22:59:56.617: E/AndroidRuntime(27425): at
java.lang.Double.parseDouble(Double.java:295) 09-18 22:59:56.617:
E/AndroidRuntime(27425): at java.lang.Double.valueOf(Double.java:332)
09-18 22:59:56.617: E/AndroidRuntime(27425): at
fatture.acquisti.Inserisci_fatture$2.afterTextChanged(Inserisci_fatture.java:178)
09-18 22:59:56.617: E/AndroidRuntime(27425): at
android.widget.TextView.sendAfterTextChanged(TextView.java:7841) 09-18
22:59:56.617: E/AndroidRuntime(27425): at
android.widget.TextView$ChangeWatcher.afterTextChanged(TextView.java:9754)
09-18 22:59:56.617: E/AndroidRuntime(27425): at
android.text.SpannableStringBuilder.sendAfterTextChanged(SpannableStringBuilder.java:970)
09-18 22:59:56.617: E/AndroidRuntime(27425): at
android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:497)
09-18 22:59:56.617: E/AndroidRuntime(27425): at
android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:435)
09-18 22:59:56.617: E/AndroidRuntime(27425): at
android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:30)
09-18 22:59:56.617: E/AndroidRuntime(27425): at
android.view.inputmethod.BaseInputConnection.replaceText(BaseInputConnection.java:676)
09-18 22:59:56.617: E/AndroidRuntime(27425): at
android.view.inputmethod.BaseInputConnection.commitText(BaseInputConnection.java:196)
09-18 22:59:56.617: E/AndroidRuntime(27425): at
com.android.internal.widget.EditableInputConnection.commitText(EditableInputConnection.java:183)
09-18 22:59:56.617: E/AndroidRuntime(27425): at
com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:279)
09-18 22:59:56.617: E/AndroidRuntime(27425): at
com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:77)
09-18 22:59:56.617: E/AndroidRuntime(27425): at
android.os.Handler.dispatchMessage(Handler.java:99) 09-18 22:59:56.617:
E/AndroidRuntime(27425): at android.os.Looper.loop(Looper.java:137) 09-18
22:59:56.617: E/AndroidRuntime(27425): at
android.app.ActivityThread.main(ActivityThread.java:5328) 09-18
22:59:56.617: E/AndroidRuntime(27425): at
java.lang.reflect.Method.invokeNative(Native Method) 09-18 22:59:56.617:
E/AndroidRuntime(27425): at
java.lang.reflect.Method.invoke(Method.java:511) 09-18 22:59:56.617:
E/AndroidRuntime(27425): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
09-18 22:59:56.617: E/AndroidRuntime(27425): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869) 09-18
22:59:56.617: E/AndroidRuntime(27425): at
dalvik.system.NativeStart.main(Native Method)

What would happen if I dispatch_barrier_(a)sync to the queue that target to concurrent queue in GCD?

What would happen if I dispatch_barrier_(a)sync to the queue that target
to concurrent queue in GCD?

I have a question about dispatch_barrier and the target queue. I have a
custom serial queue and custom concurrent queue and I set the target queue
of the serial to concurrent queue
(serial queue) -> (concurrent queue) -> (global concurrent queue)
What happen when I dispatch_barrier blocks on the queue that serial queue?
Will I block the execution of the blocks submitted to the targeted queue
too or just the execution blocks in the serial queue only? Or if I
dispatch_barrier blocks to the concurrent queue, will I block the
execution of the blocks submitted to the targeted queue too or just the
execution blocks in the concurrent queue only?
Thank you for your interesting :)

Create heatmap comparing two sets of data in R

Create heatmap comparing two sets of data in R

I have a set of data points. It's a 6xn matrix of data points. Each row is
denoted by a unique identifier, with data points for 6 columns. What I
have is a subset of these unique identifiers that I want to compare to the
rest of the set. So I am essentially splitting the complete set into two
subsets - one of interest and one of everything else.
Now, what I would like is to have the subset of interest cluster to itself
in the heatmap, so I can compare the relative clustering within the subset
compared to everything else for all the columns. This way I can look to
see if there is any extreme differences in the profile for the subset of
interest compared to the rest of it.
As an example, my data set may look like this.
id col1 col2 col3 col4
S1 a1 a2 a3 a4
S2 b1 b2 b3 b4
S3 c1 c2 c3 c4
E4 e1 e2 e3 e4
E5 f1 f2 f3 f4
E6 g1 g2 g3 g4
E7 h1 h2 h3 h4
E8 i1 i2 i3 i4
And what I want in the heatmap is for S1-S4 to cluster together and E4-E8
to cluster together, but all of them will rest on the same z-score
gradation in the heatmap. I would want to have the values normalized by
column.

Apache module for Ruby on Rails on Windows

Apache module for Ruby on Rails on Windows

I have a none standard need: I am going to develop an application that is
part desktop app, part web app, but both are running on my customers
machines. So there will be an install that will install everything,
including the web server(s) on the customers machine. One requirement is
that this system target both Windows and OSX users. I have three viable
options: Java, PHP, or Ruby on Rails. My preference is Ruby on Rails, but
I need to find an Apache module that will work with Windows. Is there such
a beast? If not, how do folks run Ruby on Rails on Windows under Apache?
I am fully aware of the fact that Ruby on Rails does not need Apache, but
the application will need Apache to fulfill all it's requirements. Thus
the preference would be for an Apache module. If that isn't possible, I am
open to other options.

Where does IIS express put temporary website files?

Where does IIS express put temporary website files?

I am deploying a website to IIS Express from Visual Studio.
Does IIS cache/store-locally the html/css/js files? I don't want to
re-deploy the website if it's a very small UI (HTML/CSS) change.
If it's plain HTML I should be able to make some change and refresh the
page to see the change. Where does IIS store the files temporarily where I
can make the minor changes and see them right away without having to
deploy again?

What is expected from 'try & catch & keyboard'? Matlab

What is expected from 'try & catch & keyboard'? Matlab

This is the matlab code I tried to figure out.
try
fprintf('svmkernellearn: svm opts ''%s''\n', svm_opts_) ;
res = svmtrain(y(:), [(1:n)' K], svm_opts_) ;
catch
fprintf('svmkernellearn: caught something\n');
keyboard;
end
Here are the lines show in command window.
svmkernellearn: svm opts ' -t 4 -s 0 -v 10 -c 1e-005'
svmkernellearn: caught something
K>>
I never use try&catch before, and I have no idea what is the 'keyboard'
here expecting me to enter.
What should I enter after 'K>>'??
Thank you!

Tuesday, 17 September 2013

WAV file error while playing - need help in reconstruction

WAV file error while playing - need help in reconstruction

I have a wav file but when I open it, it doesn't play and gives an error
and I have tried various players for this but no help.
I viewed the hex of the file as follows, copied first few lines only.
..D.........G..4;...B....M........E.A....M..E.;M.......3....M.9M..............E..E..E.........D..%.....E.;...i....M..E.k....d........o......|........E....U.....E....U......+..........]..@..........]..E.........Au..]......E..........z....]......E..E........
Please if anyone could help me on this.

Table Elements and Unordered Lists cannot be viewed properly on all versions of Internet Explorer

Table Elements and Unordered Lists cannot be viewed properly on all
versions of Internet Explorer

I'd like to ask if anyone knows why the table elements and unordered lists
cannot be viewed properly on ALL VERSIONS of Internet Explorer? The table
cells go dark and the unordered lists look really messy.
I have a website that clearly shows this:
http://www.feimediasolutions.com/Dairen_Website/products_rheem85vp.htm
Help is deeply appreciated. Thanks!!

How can i prevent from link to send me to the top of the page

How can i prevent from link to send me to the top of the page

i'm trying to prevent from:
<a href="#id">link</a>
to scroll the page to (0,0).
i have to use the "#" (i have to stay in the same page)
What is the most correct way to prevent the scrolling of the
page(Jqurey/Javascript/Html/Css)?

Translation function calls must NOT contain PHP variables

Translation function calls must NOT contain PHP variables

I'm using the Theme-check plugin, and it's helped me cleanup my theme
quite a bit. One of the recommended changes I make says the following:
'Possible variable $options found in translation function in
theme-options.php. Translation function calls must NOT contain PHP
variables.'
What I have is <input id='critter_theme_options[phonenumber]'
class='regular-text' type='text' name='critter_theme_options[phonenumber]'
value='<?php esc_attr_e( $options['phonenumber'] ); ?>' />
What is the correct way of saying esc_attr_e( $options['phonenumber'] );?

What breaks this table layout?

What breaks this table layout?

Simple contents layout using CSS's table, table-row and table-cell divs:
<div style="display:table-cell; border:1px solid blue">
some content <!-- this line wrappend in <p> tag in next example -->
<p>some content</p>
...
</div>
two column layout with a nested table on the right
The above example but with left cell's content placed in paragraph (the
first row):
above example but <p> breaking flow of the right table-cell
As you can see, after <p> tag put in left cell the right cell is shifted
down. It doesn't matter if I use <p> or <h1> tag. Assume it does change
line-height and 1st row in the adjacent cell is aligned to it.
Can anybody explain this behaviour. How can I prevent shifting of the
adjacent cell ?

Sunday, 15 September 2013

Php look up function

Php look up function

I am trying to do an include which have a look up value.
Below is how my include looks like.
<?php
$output1[] = ['AB1234']['FIRST Look'];
?>
I am calling it like this <?php echo $output1['AB1234']; ?>
Everything seem to be ok just that the include file I cant figure what is
the error. Any idea what is wrong here ?

What is equivalent in R with the glm regression in SAS

What is equivalent in R with the glm regression in SAS

I am trying to write a simple regression model in R, which is the same as
the glm proc in SAS.
What is equivalent in R with the glm regression in SAS?

Custom Page, with Javascript/Google issue?

Custom Page, with Javascript/Google issue?

I have a custom page that is making a call out to the gogle maps API and
displaying a map.
I am slo using the API to calculate the mileage betweent two location, and
would like to update that info in a text field on the page, first parts
works, second part doesn't. Here is the code i am am using.
If i look at the error log in Chrome is, Uncaught TypeError: Cannot set
property 'innerHTML' of null?
Also, if i execute the follwing in the development console in Chrome then
the element does get updated. I am assuming this is come kind of DOM path
related issue? The javascript is being called from within an iframe, so
that might also be part of the problem?
document.getElementById('00Nb0000004zOiz_ileinner').innerHTML = '989';
Thanks
Gareth
<apex:page standardController="Opportunity">
<apex:pageBlock >
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Directions Complex</title>
<script type="text/javascript"
src="https://maps.google.com/maps/api/js?sensor=false"></script>
</head>
<body style="font-family: Arial; font-size: 13px; color: red;">
<div id="map" style="width: 647px; height: 318px;"></div>
<script type="text/javascript">
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var startPostcode = "{!Opportunity.Warehouse_Postcode__c}";
var endPostcode = "{!Opportunity.R2_Shipping_Post_Code__c}";
var distanceInMeters;
var distanceInMiles;
var durationInSeconds;
var durationInMinutes;
var myOptions = {
zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map"), myOptions);
directionsDisplay.setMap(map);
var request = {
origin: startPostcode,
destination: endPostcode,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
distanceInMeters = response.routes[0].legs[0].distance.value;
distanceInMiles = Math.floor(distanceInMeters / 1609.344);
durationInSeconds = response.routes[0].legs[0].duration.value;
durationInMinutes = Math.floor(durationInSeconds / 60);
directionsDisplay.setDirections(response);
document.getElementById('00Nb0000004zOiz_ileinner').innerHTML =
distanceInMiles;
}
});
</script>
</body>
</html>
</apex:pageBlock>
</apex:page>

Can't connect to facebook chat using xmpphp

Can't connect to facebook chat using xmpphp

today I wanted to create a very simple php application to chat to facebook
friends, but got strucked, I am using xmpphp for connecting to facebook
chat. Below is the code I wrote.
<?php
require_once("libs/facebook/src/facebook.php");
require_once("informations/facebook_info.php");
$facebook=new Facebook($config_facebook);
if($facebook->getUser())
{
//now connect to facebook chat api
require_once('libs/xmpphp/xmpphp/xmpp.php');
$accesstoken=$facebook->getAccessToken();
$con=new
XMPPHP_XMPP('chat.facebook.com',5222,'my-id@facebook.com',$accesstoken,'xmpphp','chat.facebook.com');
$con->useEncryption=false;
$con->connect();
}else
{
header("location:index.php");
}
?>
But it is throwing me a warning saying:
Warning: fclose() expects parameter 1 to be resource, null given in
C:\wamp\www\libs\xmpphp\xmpphp\XMLStream.php on line 405
Have I missed something?

How to initialize a variable in windows command shell and echo it

How to initialize a variable in windows command shell and echo it

How to initialize a variable in windows command shell? I tried
(
var $a=1
echo $a
)
and got an error
'var' is not recognized as an internal or external command, operable
program or batch file.

Update multiple rows based on values in other rows in same table

Update multiple rows based on values in other rows in same table

I need to update multiple rows based on value in other rows with matching id.
Table structure:
ID | Sub-ID | value
----------------------------
1 | 1 | a
1 | 2 | b
1 | 3 | c
2 | 1 | x
2 | 2 | y
2 | 3 | z
3 | 1 | k
3 | 2 | l
3 | 3 | m
I need to update value of SubID = 2 with value of SubId=3 for a specific
IDs (where ID in other table )
The result should be (base on the above):
ID | Sub-ID | value
----------------------------
1 | 1 | a
1 | 2 | c
1 | 3 | c
2 | 1 | x
2 | 2 | y
2 | 3 | z
3 | 1 | k
3 | 2 | m
3 | 3 | m
What will be the most efficient way to implement it?
This what I have right now:
UPDATE data_tab tab1
SET (value) =
(SELECT tab2.value
FROM data_tab tab2
WHERE tab1.id = tab2.id
AND tab1.sub_id = 32 AND tab2.sub_id = 31
)
WHERE EXISTS (SELECT 1 FROM ids_table
WHERE id = tab1.id)

Regular Expression To Match Multiple "-" occurances in a Filename

Regular Expression To Match Multiple "-" occurances in a Filename

I am Trying to Construct a Regular Expression to Find File names Which
have Multiple - Occurrences. I Mainly need this Regular Expression to ID
Tag MP3 Files Which are in a Format - .
The Problem is that Some artists in my Collection have a - in their name.
Hence I need to Construct a Regular Expression which will list all those
File names which have Multiple - in their File name ( One for the Artist
Name, and the other that act as a separator between the Artist and the
Title [ Such as Ar-tist - Title ), to Manually Tag Them.
So far I managed to Extract File names with a Single - Using the Regular
Expression
*-*
What I need Now is a Regular Expression to Match two Literal -.
Thank you, Andrew Borg

Saturday, 14 September 2013

Set oracle database default nls_sort in oracle 10g

Set oracle database default nls_sort in oracle 10g

I am using ALTER SESSION SET nls_sort=persian in my session for correcting
my sort in Persian language.
How can I set this parameter as default. means for all sessions

Best way to store course notes / medium sized text digitally - Must be: efficient, easy to display on web, flexible

Best way to store course notes / medium sized text digitally - Must be:
efficient, easy to display on web, flexible

I am building my personal web site and I want to store my course notes on
it. My course notes are currently on paper so I will be typing them up. I
am thinking about storing each of my courses in its own XML file with a
structure that goes like: The dashes represent tags, disregard the
numbers.
COURSE1.XML
-Title -Topic 1
- Sub Topic 1.1
- Multimedia link
- Code link
- Actual Text
- Sub Topic 1.2
...
- Topic 2
...
My website idea is if user clicks on course 1 link then my program will go
find that XML parse it and display its contents.
My Requirements:
- Must be able to display on web sites
- Parsing should be fast
- In the future I might do other things so I want something that is
flexible.
Is using XML for this a good design decision? Or can I do better? If XML
is a good design decision: Should I stay with my current design of 1 XML
per-course or have a folder for a course and have 1 XML for each topic?
Other than XML, what other options do I have?
Hopefully this isn't too subjective...

Java vs. Python Regular Expression?

Java vs. Python Regular Expression?

I am searching through a string for a particular regex.
In python, my code is:
regexChecker = re.match("regularExpression", stringToSearch)
if regexChecker == true:
...
Is there an equivalent in Java? Or is something like this the only way?
boolean isRegex;
try {
Pattern.compile(input);
isRegex = true;
...
} catch (PatternSyntaxException e) {
isRegex = false;
...
}

Hiding Webview while streaming

Hiding Webview while streaming

For a online radio streaming app, I have the code below so far. The
problem that I have is when I press play, a webview opens up and when I
close it the stream stops. How do I make this webview not appear on the
screen/do it in the background?
ViewController.h
@interface ViewController : UIViewController
{
IBOutlet UIWebView *webView;
}
-(IBAction)play:(id)sender;
ViewController.m
-(IBAction)play:(id)sender
{
NSString *stream = @"STREAMING LINK";
NSURL *url = [NSURL URLWithString:stream];
NSURLRequest *urlrequest = [NSURLRequest requestWithURL:url];
[webView loadRequest:urlrequest];
}
Also while using webview, would I be able to make a pause/stop button and
a volume switch as well?

Wait until method has finished to call the method again

Wait until method has finished to call the method again

I have a method which "does stuff" do my ListView called method1(). This
is called from method2(). method2() can run very frequently (possibly
every second). I think I have a problem that if method2() is called
(therefore calling method1() again) before method1() has finished, method1
only runs the once - it does not run the second time.
Is there a way around this? I thought about adding a boolean into
method1() and setting it to true at the start and the false at the end,
but I can't think of a way I can get this to work.

Getting java.lang.NullPointerException when calling Method.invoke

Getting java.lang.NullPointerException when calling Method.invoke

I'm following this tutorial on Java annotaitons and implemented the Test
annotation as shown there. But when running the code I get the following
output.
java.lang.NullPointerException
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:616)
at TestAnnotationParser.parse(Demo.java:24)
at Demo.main(Demo.java:51)
Passed:0 Fail:1
Following is my code. Can someone point out what I have got wrong?
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface Test {
Class expected();
}
class TestAnnotationParser {
public void parse(Class<?> clazz) throws Exception {
Method[] methods = clazz.getMethods();
int pass = 0;
int fail = 0;
for (Method method : methods) {
if (method.isAnnotationPresent(Test.class)) {
Test test = method.getAnnotation(Test.class);
Class expected = test.expected();
try {
method.invoke(null);
pass++;
} catch (Exception e) {
if (Exception.class != expected) {
e.printStackTrace();
fail++;
} else {
pass++;
}
}
}
}
System.out.println("Passed:" + pass + " Fail:" + fail);
}
}
class MyTest {
@Test(expected = RuntimeException.class)
public void testBlah() {
}
}
public class Demo {
public static void main(String[] args) {
TestAnnotationParser parser = new TestAnnotationParser();
try {
parser.parse(MyTest.class);
} catch (Exception e) {
e.printStackTrace();
}
}
}

UITableViewHeaderFooterView can't change custom background when loading from nib

UITableViewHeaderFooterView can't change custom background when loading
from nib

I've created a custom UITableViewHeaderFooterView and successfully load
from nib into my UITableView but always get this message
"Setting the background color on UITableViewHeaderFooterView has been
deprecated. Please use contentView.backgroundColor instead."
Here the code for loading my custom UITableViewHeaderFooterView:
- (UIView *)tableView:(UITableView *)tableView
viewForFooterInSection:(NSInteger)section {
KTHeaderFooterViewIphone customHeaderIphone* = [[[NSBundle mainBundle]
loadNibNamed:@"KTHeaderFooterViewIphone" owner:self options:nil]
objectAtIndex:0];
customHeaderIphone.tintColor = [UIColor whiteColor]; // this code
worked, but the message above always show
customHeaderIphone.contentView.backgroundColor = [UIColor redColor];
// this code doesn't work, nothing's happened
customHeaderIphone.contentView.backgroundColor = [UIColor
colorWithPatternImage:[UIImage imageNamed:@"customHeader.png"]]; //
this code doesn't work too, I can't change custom background image
return customHeaderIphone;
}

listview filter suddenly broken

listview filter suddenly broken

I have a listview displaying contacts. Initially I display all contacts.
When I start typing the list goes blank, regardless of what I type.
@Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
fillContacts();
contactList.setAdapter(geoAdapter);
...
@Override
public void afterTextChanged(Editable str) {
geoAdapter.getFilter().filter(str, new Filter.FilterListener() {
@Override
public void onFilterComplete(int i) {
geoAdapter.notifyDataSetChanged();
}
});
}

Friday, 13 September 2013

Custom UIView always visible above UITabBar

Custom UIView always visible above UITabBar

I would like to present a permanent UIView in my app; I have a left and
right panel, and in the main central one I have 5 tabs. Each tab has a
UINavigationController with UITableViewControllers.
Above the UITabBar I'm thinking about adding a small, permanent
rectangular UIView. Think about Audio Controls for example.
Do you have any recommendations for doing so? I'm working mainly with
Storyboards.
Would that disturb 3.5 screens much?

Using MAPI to change attachment filename

Using MAPI to change attachment filename

Using COM and MAPI, we are trying to rename an attachment in an MSG file.
I've got everything working (we get the IAttach interface, then use
GetProps and SetProps), but I'm nervous about making sure that we change
all the properties we need to.
Does anyone know if the following is sufficient?
Check and if present, change value of:
PR_ATTACH_EXTENSION_W PR_ATTACH_FILENAME_W PR_ATTACH_LONG_FILENAME_W
PR_DISPLAY_NAME_W
Also, will setting the _W values automagically set the _A values? I think
yes, but can't find and reference documentation that says one way or
another.

wht jar file or package does PageUtil requires

wht jar file or package does PageUtil requires

PageUtil cannot be resolved what package needed to be downloaded
****Code :
try {
RequestContext rc = PageUtil.getCurrentRequestContext(pageContext);
ManagedObject mo =ContentUtil.getManagedObject(rc.getRequestOID());
}**
Error : 1.PageUtil and ContentUtil cannot be found 2. The method
getRequestOID() is undefined for the type RequestContext, ManagedObject
cannot be resolved to a type, ContentUtil cannot be resolved

get the directory where app starts to run (c++ code)

get the directory where app starts to run (c++ code)

I hope to get the current working path of app. I know the objective-c
code. But I prefer c++ code.
Your comment welcome

iOS passing string to another app

iOS passing string to another app

I know it can pass file through Interaction Controller. But is there a way
to pass a plain text (string) to another app like "Open in.."? I know
Android can do it. But how about iOS?
EDIT: I am not trying to open in a custom app handles my strings. I would
like to open in those app that support string handling in entire system.

Convert ImagePath in DocumentDirectory to NSURL Iphone

Convert ImagePath in DocumentDirectory to NSURL Iphone

I am using following code
NSArray *paths =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,
YES);
NSURL *myUrl = [[NSURL alloc]
initWithString:self.selectedRing.ringThumbNailImagePath];
[Utilities responseDataFromURL:myUrl completionBlock:^(NSData *fileData,
NSError *err)
{
if (err != nil)
{
[self.indicator stopAnimating];
[Utilities errorDisplay:@""];
}
else
{
NSString *filePath = [[paths objectAtIndex:0]
stringByAppendingPathComponent:@"Test.igo"];
NSLog(@"FilePath: %@", filePath);
if ([fileData writeToFile:filePath atomically:YES])
{
CGRect rect = CGRectMake(0 ,0 , 0, 0);
NSURL *igImageHookFile = [[NSURL alloc]
initWithString:[[NSString alloc] initWithFormat:@"file://%@",
filePath]];
NSLog(@"JPG path %@", filePath);
filePath is
Users/umar/Library/Application Support/iPhone
Simulator/6.1/Applications/B45223CF-B437-4617-A02D-DCA91C965A5A/Documents/Test.igo
however i get Nil igImageHookFile NSURL. What is wrong?

Thursday, 12 September 2013

Different date saved to database - wrong time zone

Different date saved to database - wrong time zone

When I fetch a date from FullCalendar with Javascript I have the following
values:
Fri Sep 13 2013 08:30:33 GMT-0400 (EDT)
After I save that date to database I see that in database there are
different values:
2013-09-13 12:00:00.000000
So, date is automatically converted to UTC and saved like that into
database. How to save the correct date into database? I don't want to
hardcode it :)
Thank you.

Disk Cleaner App - Freeing up disk space

Disk Cleaner App - Freeing up disk space

There is an approved app in app store that claims to cleanup disk space on
your iDevice by removing temporary files. iClean
Now here is my question,
An iOS app cannot access anything outside of its sandbox. It can only read
write files within its bounds. So how does this app claims to free up
space on users phone? There are plenty of user reviews (might be fake)
that agree with it.
When I asked a similar question before someone suggested that iClean adds
temporary files to their apps document dir till 90% of the disk space is
used up and then deletes it. Apparently by doing that iOS services cleanup
temp files. As a test I tried whole thing in a test app on my iphone and
it didn't free up anything on my 4S.
I have read through Apple documentation regarding File System Programming
and it pretty much says the same thing, apps remain within their sandbox.
Any idea what are these guys doing?

How to prevent syslogging "Error inserting nvidia" on cudaGetDeviceCount()?

How to prevent syslogging "Error inserting nvidia" on cudaGetDeviceCount()?

I have a tool that can be run on both, GPU and CPU. In some init-step I
check cudaGetDeviceCount() for the available GPUs. If the tool is being
executed on a node without video cards, this results in the following
syslog message:
Sep 13 00:21:10 [...] NVRM: No NVIDIA graphics adapter found!
How can I prevent the nvidia driver from flooding my syslog server with
this message? It's OK if the node doesn't have a video card, it's not that
critical, so I just want to get rid of the message.