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.

MVC4 Ajax form in partial view returns whole page when inside kendo window

MVC4 Ajax form in partial view returns whole page when inside kendo window

I've searched and searched and for the life of me cannot figure out what
I'm doing wrong. I have a Kendo UI window like so:
<a id="@(item.POD_ID)" class="k-button btn-reminder" title="Add Reminder"
onclick="$('#windowR@(item.POD_ID)').data('kendoWindow').open();"><span
class="icon-reminder icon-only btn-reminder"></span></a
@(Html.Kendo().Window()
.Name("windowR" + item.POD_ID)
.Title("Set Reminder")
.Content("loading...")
.LoadContentFrom("_LoadReminder", "Purchasing", new { id = item.POD_ID })
//.Iframe(true)
.Draggable()
//.Resizable()
.Modal(true)
.Visible(false)
.Width(200)
.Height(80)
.Events(events => events
.Close("onCloseReminder")
.Open("onOpenReminder")
.Deactivate("function() { this.refresh();}")
.Activate("function(){ $('#empNumBox').focus(); }")
)
)
And, if the window is an Iframe, all of this works just fine, however I
cannot have it as an Iframe, because that means reloading all of the
scripts and styles within it and more difficult to reference parent.
So this window, loads content from the partial view like so:
@using (Ajax.BeginForm("SetReminders", "Purchasing", new AjaxOptions {
UpdateTargetId = "result" }))
{
<div id="result"></div>
<input type="number" id="empNumBox" name="empNum" style="width: 70px"
class="k-textbox" required autofocus="autofocus"
value="@(ViewBag.EMP_NUM)"/>
<input type="hidden" value="@ViewBag.POD_ID" name="podID"
id="POD_ID_Form_Field"/>
<input type="submit" id="submitReminder_button" style="width:auto;"
class="k-button submitReminder_button" value="Remind" />
}
That partial view also renders fine. Here is the problem though, when you
submit the ajax form, and the kendo window is not an iframe, it will
render the whole page as whatever the controller returns (and I have tried
several things, you can see in the commented out code below:
[HttpPost]
public ActionResult SetReminders(int empNum, int podID)
{
//some database stuff that works fine
string response;
if (existingReminder == 0)
{
//more db stuff that also works fine
db.SaveChanges();
response = "Success!";
}
else
{
response = "Reminder exists.";
//return PartialView("_LoadReminder", new string[] { "Reminder
already exists!" });
}
//
$('#submitReminder_button').closest('.k-window-content').data('kendoWindow').close();
//alert('Hello world!');
//return Content("<script
type='text/javascript/>function(){alert('Hello
world!');}</script>");
return PartialView("_SubmitSuccess");
//return Json(response);
//return Content(response, "text/html");
}
If anyone is curious, all that the _SubmitSuccess contains is the word
"Success!".
Here's an example that I found with the ajax response being put in a div,
which I followed:
http://pratapreddypilaka.blogspot.com/2012/01/htmlbeginform-vs-ajaxbeginform-in-mvc3.html
It seems the real issue here is the Kendo window, but I have yet to find
something on their forums about this, doesn't seem that there's a lot of
examples of using a kendo window to load a partial view that submits an
form via ajax and returns a different partial view to be loaded within the
same window and does not use an iframe.
Any suggestions welcome, even about other parts of the code, I'm always
looking to improve.

saxon:indent-spaces attribute is being ignored

saxon:indent-spaces attribute is being ignored

In my question here I'm trying to pass in a param to my stylesheet so a
user can specify the level of indentation desired. Apparently Xalan cannot
read the value of a param into its indent-amount attribute, so I'm trying
with Saxon instead.
Saxon has the attribute indent-spaces which I am trying to use as follows:
<xsl:stylesheet
version="2.0"
xmlns:saxon="http://saxon.sf.net"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- <xsl:param name="indent-spaces" select="0"/> -->
<xsl:output indent="yes" method="xml" omit-xml-declaration="yes"
saxon:indent-spaces="10"/><!-- Doesn't matter what I make the value of
indent-spaces, the output is always indented 3 spaces -->
Why is indent-spaces being ignored?

Can't find my app "404 Not Found"

Can't find my app "404 Not Found"

I created my app on Google App Engine and deployed it several days ago. It
available on this standard url http://pereshilla2.appspot.com So, I would
like that this app will available on this domain www.pereshilla.com.ua. I
did everything step by step as in this article
http://otvety.google.ru/otvety/thread?tid=299fd091094b9806 but my app is
not available durning several days ((( Help me please!!

need help on sql injection attack

need help on sql injection attack

Checking my web site with google webmaster tools I found a strange thing :
somebody tried to use to link to my site using this (I change the real
name of my site for obvious security reasons ) :
....://mysite.com/tarifs.php?annee=aaatoseihmt&mois=10&cours=1828
I try it and understand it was a sql injection with the results :
Warning: mktime() expects parameter 6 to be long, string given in
/home/cogerino/public_html/stagephotoparisien/sba_stages_photo_tarifs.php
on line 72
my code line 72 is :
mktime (0, 0, 0, $mois, "01", $annee)
part of this:
<?php
include ("include.php");
if (!$link = mysql_connect($host, $user, $pass)) {
echo "Could not connect to mysql";
exit;
}
if (!mysql_select_db($bdd, $link)) {
echo "Could not select database";
exit;
}
mysql_query("SET NAMES 'utf8'");
$annee = "";
$mois = "";
$stage = "";
if (isset($_GET['annee'])) {$annee=$_GET['annee'];}
if (isset($_GET['mois'])) {$mois=$_GET['mois'];}
if (isset($_GET['stage'])) {$stage=$_GET['stage'];}
if($annee == "")
{
$annee = date("Y");
}
if($mois == "")
{
$mois = date("m");
}
$date_du_jour = date("d")."-".date("m")."-".date("Y");
if($mois == "12")
{
$mois_precedent = "11";
$mois_suivant = "01";
$annee_mois_precedent = $annee;
$annee_mois_suivant = $annee + 1;
}
elseif($mois == "01")
{
$mois_precedent = "12";
$mois_suivant = "02";
$annee_mois_precedent = $annee - 1;
$annee_mois_suivant = $annee;
}
else
{
$mois_precedent = sprintf("%02s", $mois-1);
$mois_suivant = sprintf("%02s", $mois+1);
$annee_mois_precedent = $annee;
$annee_mois_suivant = $annee;
}
$jour_en_cours = date("d");
$mois_francais = array("Janvier", "Février", "Mars", "Avril", "Mai",
"Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre",
"Décembre");
$dt_deb_genere = $annee."-".$mois."-01";
$dt_fin_genere = $annee_mois_suivant."-".$mois_suivant."-01";
$dt_date = mktime (0, 0, 0, $mois, "01", $annee);
$jour_de_la_semaine = date("w", $dt_date);
?>
what can I do to protect my site against this ?
I tried to understand how to it with "similar question" but I think I am
to new to php and mysql to be able to understand.So any help is really
great !
Thanks if you can help on this ! I worked hard for months now on my site
and don't want to lose my business.
.blc.

OnItemSelectedListener in a Fragment that uses a custom Adapter not responding

OnItemSelectedListener in a Fragment that uses a custom Adapter not
responding

I have a list in a fragment with custom cells adapter,
The problem is that the onItemSelected is not responding,
how to fix this please?
public class PhoneMenuList extends SherlockFragment implements
OnItemSelectedListener{
Fragment newContent = null;
ListView productList;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState){
View mView = inflater.inflate(R.layout.list, container, false);
return mView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
//SET THE LIST ADAPTER!
Hamburger hambu_data[] = new Hamburger[]
{
new Hamburger(R.drawable.icon_hambu_folder, "My Documents"),
new Hamburger(R.drawable.icon_hambu_favs, "Top 10 viewed"),
new Hamburger(R.drawable.icon_hambu_validate, "Validate
Document"),
new Hamburger(R.drawable.icon_hambu_how, "How to use"),
new Hamburger(R.drawable.icon_hambu_about, "About")
};
productList= (ListView) getActivity().findViewById(R.id.listView1);
HamburgerAdapter adapter = new HamburgerAdapter(getActivity(),
R.layout.hamburger_item_row, hambu_data);
productList= (ListView) getActivity().findViewById(R.id.listView1);
View header =
(View)getLayoutInflater(savedInstanceState).inflate(R.layout.hamburger_item_row,
null);
productList.addHeaderView(header);
productList.setAdapter(adapter);
//listener
productList.setOnItemSelectedListener(this);
}
//@Override
public void onListItemClick(ListView l, View v, int position, long id) {
Log.d("mensa", "chapuzea");
}
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Log.d("mensa", "abacus");
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
Log.d("mensa", "semper");
}
}

Wednesday, 11 September 2013

MySQL date_format showing '1st', '2nd', '3rd'

MySQL date_format showing '1st', '2nd', '3rd'

I'm making a change to my date outputs and trying to show nd, rd, st,
etc., like 1st September 2013 or 3rd. Looking at the manual 'jS' should do
it but it is just outputting nonsense. Does anyone know what are the
correct letter(s) to use?
DATE_FORMAT(date, "%jS %M %Y") AS Displaydate
EDIT: my bad, I thought date_format was PHP not MySQL - sorry.

Deserialization Error attempting to parse embedded document in XML

Deserialization Error attempting to parse embedded document in XML

I have code that accepts a string of XML and deserializes it into a .NET
object. The string includes a few Base64 encoded documents of modestly
large size.
In various testing internally and with an external vendor I've received
200-300 of these without issue, but generally with smaller files (100K -
2MB). Receiving a few larger files, I've run into the following on three
of seven attempts with embedded docs over 7MB.
There is an error in XML document (168, 3735935).
Message:
An error occurred while parsing EntityName. Line 168, position 3735935.
at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader
xmlReader, String encodingStyle, XmlDeserializationEvents events)
at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader
xmlReader, String encodingStyle)
The code itself is pretty straightforwrd:
var searchResult = new XmlSerializer(typeof(MyType));
var resultObject =
(MyType)searchResult.Deserialize(StringToStream(SourceXml));
My original thought was memory--not that 10MB is massive--but might
explain the intermittent issues and that at least in one case resubmitting
the same worked. But another failed on the same byte in multiple runs.
Has anyone encountered (and hopefully) solved this?

A c# program that login at facebook when we provide our userid and Password

A c# program that login at facebook when we provide our userid and Password

what I have done so far is by Process class i m able to open chrome and
and then Facebook but now I have to log in at Facebook, so how can i done
this by pro grammatically
Process p1 = new Process();
p1.StartInfo.FileName = "chrome.exe";
p1.StartInfo.Arguments = url_tb.Text;
p1.Start();

pandas data frame transform INT64 columns to boolean

pandas data frame transform INT64 columns to boolean

Some column in dataframe df, df.column, is stored as datatype int64.
The values are all 1s or 0s.
Is there a way to replace these values with boolean values?

How to open transaction in Filter

How to open transaction in Filter

I use spring 3.2.4 and create a Filter. This Filter has to start the
transaction. In other words what I want to implement :
beginTransaction()
chain.doFilter(request, response);
endTransaction()
I tried to use @Transactional annotation with doFilter method but this
apparently does not work
(TransactionSynchronizationManager.isActualTransactionActive(); returns
false). Then I added OpenEntityManagerInViewFilter before my filter to
obtain the entityManager but
@PersistenceContext
EntityManager em;
still returns null. Is there any way to open the transaction in spring so
that transaction interceptor knows about it?

A webpage return 404 when exist on server

A webpage return 404 when exist on server

I have a website on a server. When I request the homepage I get it in the
browser, but when I request another webpage I don't. I have no idea why
this is happening.
My website is Asp.net. The server is vps.
Edit: On the local server my website working well, no problems, just in
the real server it is causing problems - returns a 404 error when the page
exists.

Tuesday, 10 September 2013

Rails 4 lambda route request.session not yet loaded

Rails 4 lambda route request.session not yet loaded

I'm having trouble trying to access the request session in one of my route
constraints. I've used something like this in Rails 3 before and I've seen
tutorials using something similar on other sites as well. For some reason
though in Rails 4 this no longer works. Do I have to make adjustments to
the middle ware loading?
config/routes.rb
admin_constraint = lambda do |request|
request.session[:user_id] == 1
end
Exception that is raised:
#<ActionDispatch::Request::Session:0x7fc878b35400 not yet loaded>

Corona reading and writing files (first time access)

Corona reading and writing files (first time access)

I'm trying to write a function that will read sound and music states
before starting my application. The problem is: The first time it will
run, there will be no data recorded.
First, I tried the suggested JSON function from here and I got this error:
Attempt to call global 'saveTable' (a nil value)
Is there a way to test if the file exists?
Then, I tried this one:
-- THIS function is just to try to find the file.
-- Load Configurations
function doesFileExist( fname, path )
local results = false
local filePath = system.pathForFile( fname, path )
--filePath will be 'nil' if file doesn't exist and the path is
'system.ResourceDirectory'
if ( filePath ) then
filePath = io.open( filePath, "r" )
end
if ( filePath ) then
print( "File found: " .. fname )
--clean up file handles
filePath:close()
results = true
else
print( "File does not exist: " .. fname )
end
return results
end
local fexist= doesFileExist("optionsTable.json","")
if (fexist == false) then
print (" optionsTable = nil")
optionsTable = {}
optionsTable.soundOn = true
optionsTable.musicOn = true
saveTable(optionsTable, "optionsTable.json") <<<--- ERROR HERE
print (" optionsTable Created")
end
The weird thing is that I'm getting an error at the
saveTable(optionsTable,"optionsTable.json"). I just can't understand why.
If you have a working peace of code that handles the first time situation
it will be enough to me. Thanks.

PIG - HBASE - HBaseStorage key filter (gt, lt)

PIG - HBASE - HBaseStorage key filter (gt, lt)

In a PIG script, I'm using HBaseStorage to load all the rows from an
HBase-table. However, I'd like to filter the rows by the rowkey.
I looked at the source code, and i can send in -gt & -lt through the
constructor. However, I can't figure out how to pass my value into the
constructor. It is a byte[]...
Here is where I'm at:
LOAD 'hbase://TABLE' USING
org.apache.pig.backend.hadoop.hbase.HBaseStorage('CF:I','-caster
HBaseBinaryConverter') AS (product_id:bytearray);
If possible could you pls provide sample code...

Conflict between font-lock and string literal coloring in Emacs

Conflict between font-lock and string literal coloring in Emacs

In Emacs, I am writing a PHP file that mixes both PHP and non-PHP code,
which will be in C++ mode. I would like the PHP code to be highlighted
with a link-pink background in order to make it stand out visually.
To do this, I use the font-lock setting:
(make-face 'font-lock-special-macro-face)
(set-face-background 'font-lock-special-macro-face "pink")
(defun add-custom-keyw()
"adds a few special keywords for c and c++ modes"
;
(font-lock-add-keywords nil
'(
("<\\?[^\\?]*\\?>" . 'font-lock-special-macro-face )
; more of those would go here
)
)
)
(setq font-lock-multiline t)
(add-hook 'c++-mode-hook 'add-custom-keyw)
The regular expression expression matches the typical PHP tags and their
enclosed text. However, if there are any string literals in the body of
the PHP block, then the highlighting fails. I think this is because the
face defined above is clashing with the coloring of string literals, which
are by default colored text.
What should I do to fix this issue? I would like to keep both coloring
schemes (highlighting and colored string literals) if possible.
Here is an example:
The code <?= $className ?> is highlighted with a pink background.
The code <?= inputs_to_vector($factors, 'factors') ?> does not have a
highlighted background and the string literal 'factors' is displayed with
red colored text.
This happens regardless of whether the leading PHP tag <? or <?= is used.

2d Array that swaps all the integers or characters in opposing rows/columns

2d Array that swaps all the integers or characters in opposing rows/columns

. Write the implementation of the method switchRows. This method receives
a 2-dimensional array of integers and switches the values in opposing
rows. For example, given a 2-dimensional array (shown left, below), the
method should swap its row values (shown right, below) where the values on
the 1st row (index 0) are switched with the values on the 5th row (index
4), and the values on the 2nd row (index 1) are switched with those on the
4th (index 3). Since this example shows an array with odd-numbered rows,
the 3rd row (index 2) did not have an opposing row with which to get
swapped. Nevertheless, the method should work with any 2-dimensional
array.
Write the implementation of the method switchColumns. This method receives
a 2-dimensional array of characters and switches the values in opposing
columns. For example, given a 2-dimensional array (shown left, below), the
method should swap its column values (shown right, below). The method
should work with any 2-dimensional array.
I feel like I'm getting this problem turned around in my head because rows
and columns are easy to mix up. Can someone help show me where I'm going
wrong.
public static void switchRows( int[][] anArray ){
int num = 1;
for(int i = 0; anArray.length > i; i++){
for(int j = 0; anArray[i].length > j; j++){
int[][] temp = new int[anArray.length][anArray[i].length];
temp[i] = anArray[i];
anArray[i] = anArray[anArray.length - num];
anArray[anArray.length - num] = temp[i];
}
num++;
}
}
public static void switchColumns( char[][] anArray ){
int col = 1;
for(int i = 0; anArray.length > i; i++){
for(int j = 0; anArray[i].length > j; j++){
char[][] temp = new char[anArray.length]
[anArray[i].length];
temp[j] = anArray[j];
anArray[j] = anArray[anArray[i].length - col];
anArray[anArray[i].length - col] = temp[j];
}
col++;
}

$.post not posting data

$.post not posting data

hi this is my code for page.php
<?php session_start(); ?>
<script type="text/javascript" src="js/jquery-1.8.2.js"></script>
<script type="text/javascript" src="js/jquery.colorbox.js"></script>
<script type="text/javascript" src="js/new-landing.js"></script>
<script>
var ans1 = "home";
function aa(){
$.post("ajax.php", { "ans": "test" },
function(data){
alert("Posted");
}, "html");
};
</script>
<a href="#" id="q1" onClick="javascript:aa();" >click</a>
and this is where i want to see if my data is posted.
<?php
session_start();
$te = $_POST['ans'];
$_SESSION['demo'] = $te;
echo "<pre>".print_r($_SESSION,'/n')."</pre>";
?>
when i click the anchor tag. the alert box is shown. but when i refresh
the ajax.php page. it shows an error..Notice: Undefined index: ans in
C:\xampp\htdocs\healthqueens\hello\ajax.php on line 3
and the print of session is also empty. Array ( [demo] => ) Please if
anyone can show me the mistake.