Monday, September 30, 2013

Is there a word for the action of lifting the mouse to go further=?iso-8859-1?Q?=3F_=96_english.stackexchange.com?=

Is there a word for the action of lifting the mouse to go further? –
english.stackexchange.com

Using a computer mouse to point to a far away target and running out of
table surface (or hand range), one typically lifts the mouse, moves it in
the opposite direction, puts it back down, and ...

Major differences between mod_fastcgi and mod_proxy_fcgi

Major differences between mod_fastcgi and mod_proxy_fcgi

I noticed there are a couple of modules for Apache that provide FastCGI
support. The two most popular seem to be mod_fastcgi and mod_proxy_fcgi.
There seem to be other ones as well.
My questions are:
Which of these module are the most popular?
Which of them are considered obsolete.
The reason I am asking is that I'm writing FastCGI support for a certain
scripting language and I wonder which setups I should primarily test with.
Granted, FastCGI is a standard so, in theory everything should be
portable. On the other hand, there seem to be certain differences
concerning application server start-up, etc. I would also like to write
some "how-to's" once I'm finished, so I would like to know which options
to cover primarily.
Hope this is not an open-ended question.

How to delete a row by selecting a check box using jdbc?

How to delete a row by selecting a check box using jdbc?

I am writing a program using (MVC) framework in which the below code will
fetch total no. of request made by a user and each with 7 columns. Now i
want to do is delete a particular row using a check box which user
selects. Can anyone tell me how can i detect which check box user has
selected so that only that row is deleted ?
import java.io.*;
import java.lang.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class allrequestcontrol extends TagSupport
{
HttpServletRequest request;
HttpServletResponse response;
String f="111";
String ss="";
public ResultSet check()
{
JspWriter out=pageContext.getOut();
Connection con;
Statement stmt;
ResultSet rs=null;
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch( ClassNotFoundException ex)
{
}
try
{
con=
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","gaurav","oracle");
stmt=con.createStatement();
rs=stmt.executeQuery("select * from myadmin where employe_id='"+f+"'");
}
catch(SQLException ex)
{
}
return rs;
}
public int doEndTag() throws JspException
{
JspWriter out=pageContext.getOut();
ResultSet rs= check();
try
{
out.println("<table border=2>");
out.println("<tr>");
out.println("<th>EmployeId</th>");
out.println("<th>Supervisor</th>");
out.println("<th>Department</th>");
out.println("<th>PickDate.</th>");
out.println("<th>PickTime</th>");
out.println("<th>DropDate</th>");
out.println("<th>DropTime</th>");
out.println("<th>Status</th>");
out.println("<th>Check</th>");
out.println("</tr>");
while(rs.next())
{
out.println("<tr>");
out.println("<td>"+rs.getString(1)+"</td>")
out.println("<td>"+rs.getString(2)+"</td>");
out.println("<td>"+rs.getString(3)+"</td>");
out.println("<td>"+rs.getString(4)+"</td>");
out.println("<td>"+rs.getString(5)+"</td>");
out.println("<td>"+rs.getString(6)+"</td>");
out.println("<td>"+rs.getString(7)+"</td>");
out.println("<td>"+rs.getString(8)+"</td>");
out.println("<td><input type=checkbox name=check value=check></td>");
out.println("</tr>");
}
}
catch(Exception ex)
{
}
return super.doEndTag();
}
}

2 calculations with one populate button

2 calculations with one populate button

I have a simple worksheet that auto populates hours based on key values.
This all works fine. The problem I have now is that I need to add some
form of a contingency column which is a percentage figure of the total
hours used up to this column. Add the contingency figures to the sheet and
carry on with the populate.
Is there anyway i can do the first populate up to the contingency column.
Stop. Get the current value (for total hours) then do some calculations
and then carry on with the auto populate?
I don't really have any code I can share, but any pointers in the right
direction would be extremely useful.
Thankyou for your time.

Sunday, September 29, 2013

How to open a link in the default browser on Firefox OS?

How to open a link in the default browser on Firefox OS?

I have a Firefox OS app where I want a link to open outside of the
application (the link is to a different site, and opening it
in-application would make the application unusable without a force-quite).
How do I do that?

Assembly language offsetting multiple ways to store words?

Assembly language offsetting multiple ways to store words?

I am using MIPS with the mars editor and I was wondering if something like
sw $s0,8($v0)
Is equivalent to:
sw $s0,$v0(8)
My instinct tells me this is not the case because it takes the address of
whatevers in the brackets and adds the value of whatever is outside it.
However in the solution posted by codeknight in the link beliw he
http://www.masmforum.com/board/index.php?PHPSESSID=786dd40408172108b65a5a36b09c88c0&topic=1062.0

Why is Internet traffic being blocked for .NET programs ONLY?

Why is Internet traffic being blocked for .NET programs ONLY?

We have a POS-based application in Windows Forms written in VB.NET, which
we're rolling out to franchise stores - 70, so far.
The application replicates data by means of a connection to a head office
server: all communication is by means of Web Services (upload & download).
All is working really well, except - you knew it was coming - on literally
a handful of stores we cannot connect to the web services, although we
know that the Internet service is good!
Here's a bullet-point summary of the situation:
in this handful of stores, ALL .NET (only) internet traffic fails on this
POS computer.
primarily this traffic is using port 80 to connect to web services, using
SOAP (standard)
BUT they can successfully use a browser in the POS to see web pages; also,
a test program I created in Clarion (straight Win 32) also connects to the
web service ok.
In addition, an associated data conversion app (again in VB.NET) also
fails when trying to connect to MS SQL at HQ (and only for this handful of
stores). Note: this uses a standard ADO connection, thus a completely
different protocol to the above.
So it's just all .NET Internet that fails... different apps, different
protocol. The error message in all cases is "The operation has timed out"
Note: timeout is set to 15 seconds - ample time for simple web service,
esp. as the initial method is just a time-check.
Take a POS that's failing to connect and move to a different site: all good
Take a POS that's failing to connect and change the router: all good
But the routers in failing stores are not all the same
It looks as if the .NET setup on the POS pc is somehow being 'blocked'.
Too weird - what am I missing here?
Grateful for pointers... I'm stumped! Steve.

Google Chrome Extensions as standalone application

Google Chrome Extensions as standalone application

Is it possible to run a Google Chrome extensions outside of Chrome? For
instance, there is an add-on called TLDR which summarizes text on a web
page. Is it possible to write a program that can somehow "tap" into it's
summarization capabilities?

Saturday, September 28, 2013

How to load a column generated by awk into a python list

How to load a column generated by awk into a python list

With awk it is very easy to extract a column of data in the bash terminal
using.
awk '{print $1}'
I am doing this inside a python script where i use a bash sequence to
extract the data i'm interested in
os.system(" qstat | awk '{print $1}' ")
If i call this in a certain context I get a column of numbers. I would
like to load all of those numbers into a python list. Can this be done
easily?

How do I approach this program?

How do I approach this program?

I need to fill in the code for this program. It is supposed to read
integer scores from a file and print out their average. We are supposed to
account for files that do not contain any integer values. The output is
just a simple print line displaying the averaged out scores.
he gives us a hint:"if input is a Scanner object associated with a file,
input.hasNextInt() returns true if there is an integer value left unread
in the file; otherwise it returns false."
import java.io.*;
import java.util.Scanner;
public class GradeAvg
{
public static void main(String[] args)
{
Scanner input = null;
double average=0.0;
try
{
input = new Scanner(new File("scores.dat"));
}
catch (FileNotFoundException e)
{
System.out.println("*** Can't open scores.dat ***");
System.exit(1);
}
System.out.println("The average of the test scores in the file are: ");
}
}

Turn off vibration inside my app

Turn off vibration inside my app

I'm developing an app and need to completely turn off vibration alerts
when my app is running. For example if an call comes in while my app is
open I don't want to have the vibration alert, the same with emails and
anyother notification.
So I've been googling around for a while and found this:
AudioManager amanager=(AudioManager)getSystemService(Context.AUDIO_SERVICE);
amanager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER,AudioManager.VIBRATE_SETTING_OFF);
The problem is that this method is deprecated. And I can't find an other
way of doing this.
The minSdkVersion = 9 and targetSdkVersion = 17.
Any idea?
Thanks!!

SAS / SAS2..... compatible?

SAS / SAS2..... compatible?

Is it theoretically possible to mix a SAS2 controller with a SAS expander?
We just happen to have this scenario - the expander (which works fine with
an older SAS adaptec controller) is not found and Adaptec (which handle
the new 71605Q raid controller) insists on telling me this is because the
expander is a SA expander and not a SAS2 expander.
We are in the proces of upgrading our infrastructure - so this test case
is not by any means a deaster - but we can not remove certain SAS elements
YET (mostly because not everything is available as SAS2 yet).
I was using my google-fu trying to find an answer but I can not find any
auhorititative document / description about whether this should work in
general.

Friday, September 27, 2013

How to create a self configuring mobile app with Javascript

How to create a self configuring mobile app with Javascript

I am looking at using Jquery mobile and Phonegap to create a mobile app.
If I know the structure of my app beforehand I can do this. However, I
want to be able to have the ability for the app to connect to a server and
add/remove pages based on the configuration for the app stored on the
server.
Once the app has reconfigured itself it should work completely offline.
Is there some way to manage this in Javascript land or do I need to manage
the reconfiguration with native code?

Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension - Aptana

Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native
extension - Aptana

I am getting this error while doing bundle install. I checked that my
RailsInstaller directory does not contain any spaces. Also the Devkit path
I added in the path variable. I am not sure why am I getting this error.
Here is the error:
c:/RailsInstaller/Ruby1.9.3/bin/ruby.exe extconf.rb
c:/RailsInstaller/Ruby1.9.3/bin/ruby.exe: invalid switch in RUBYOPT: -S
(RuntimeError)
Any help would be appreciated. Thanks in advance.

jQuery slider opacity error only on Google Chrome

jQuery slider opacity error only on Google Chrome

I have a custom built slider on a Magento site. It's responsive and have
custom touch behaviour on it. The behaviour should be the following:
Three images slider, the middle one should have opacity 1.0, the rest just
0.15
On smaller resolutions, only show 2 images. The one on the right should
have 1.0 the left image should have 0.15 opacity
On mobile, show 1 image. The current shown image should have 1.0 opacity.
I made it work with CSS/jQuery mix.
HTML
<ul class="more-views">
<li><a href="someURL"><img src=..... /></li>
<li class="active"><a href="someURL"><img src=..... /></li>
<li><a href="someURL"><img src=..... /></li>
<li><a href="someURL"><img src=..... /></li>
<li><a href="someURL"><img src=..... /></li>
</ul>
CSS .more-views ul li { opacity: .15; } .more-views ul li.active {
opacity: 1.0; }
JAVASCRIPT is long, you might want to inspect element. But the idea is the
following. When you click NEXT arrow, the first element of the list is
cloned, appended to the back of the and destroyed from the first position.
Later on the active class is removed and added to the second <li> in the
list. Something like this
<ul>
<li class="elem1"></li>
<li class="elem2 active"></li>
<li class="elem3"></li>
<li class="elem4"></li>
</ul>
STEP 1
<ul>
<li class="elem1"></li>
<li class="elem2 active"></li>
<li class="elem3"></li>
<li class="elem4"></li>
<li class="elem1"></li>
</ul>
STEP 2
<ul>
<li class="elem2 active"></li>
<li class="elem3"></li>
<li class="elem4"></li>
<li class="elem1"></li>
</ul>
STEP 3
<ul>
<li class="elem2"></li>
<li class="elem3 active"></li>
<li class="elem4"></li>
<li class="elem1"></li>
</ul>
Current small issue is the following: 1. If you click the right arrow
(next arrow) one time, the first element in the list keeps the opacity as
1.0 (only on Chrome). 2. If you inspect the element is says it has an
opacity of 0.15 3. If you resize the browser you'll see that the opacity
is set to .15 again 4. If you enable/disable the opacity in Firebug it
works like it should. 5. If you click 2 times on the next arrow the
opacity error disappears.
You can see the live example here:
http://www.mackage.com/ca/en/jeffrey-black-leather-jacket

Having trouble saving node input to a string

Having trouble saving node input to a string

Below is a class I have for a 2 class project. Basically I want to parse
the title of the wiki page, and save it to the string title or something I
can call from another class using something like
retrieveTitle.setText(WikiSearcherExtension.title); In eclipse its telling
me the local variable title isnt being used at all to store the node
information.
It wouldnt let me paste the xml as a block of code so here is the url I
have been using
http://en.wikipedia.org/w/api.php?action=query&prop=revisions&format=xml&rvprop=timestamp&rvlimit=1&rvtoken=rollback&titles=test&redirects=
public class WikiParserTrials {
private String wikiInformation;
private String wikiUrl;
String title;
public void urlRefactor(String url) throws IOException {
String wikiPageName = url.replaceAll(" ", "_");
wikiUrl =
"http://en.wikipedia.org/w/api.php?action=query&prop=revisions&format=xml&rvprop=timestamp&rvlimit=1&rvtoken=rollback&titles=test&redirects=";
setUrlInformation();
}
private void setUrlInformation() throws IOException {
URL url = new URL(wikiUrl);
URLConnection connection = url.openConnection();
BufferedReader reader = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
wikiInformation = "";
for (String line = reader.readLine(); line != null; line =
reader.readLine()) {
wikiInformation += line;
}
}
public class ReadAndPrintXMLFile {
public void main(String argv[]) {
try {
DocumentBuilderFactory dbf =
DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(wikiInformation));
Document doc = db.parse(is);
NodeList nodes = doc.getElementsByTagName("normalized");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList name = element.getElementsByTagName("to");
Element line = (Element) name.item(0);
String title = (getCharacterDataFromElement(line));
}
}
catch (Throwable t) {
t.printStackTrace();
}
}
}
}

Get QUERY_STRING using python

Get QUERY_STRING using python

Struggling to see why this isn't working:
import MySQLdb
import cgi, cgitb
import os
from wsgiref.simple_server import make_server
from cgi import parse_qs, escape
def index(req):
d = parse_qs(os.environ['QUERY_STRING'])
dtbox = d.get('dt', [''])[0]
tmbox = d.get('tm', [''])[0]
The script returns a KeyError: QUERY_STRING
I can see the URL which is:
http://myserver/currentcost.py?dt=2013-09-10&tm=00
I'm simply lost!

Thursday, September 26, 2013

PayPal PDT auth parameter

PayPal PDT auth parameter

I'm setting up PayPal PDT and IPN for a subscription/recurring payment
button.
I'm using PayPal's documentation to explain the returned parameters, but
one of them is not mentioned.
The auth parameter is ~87 characters long and looks like this:
AHJkv4ukrM7kwTPe7tt9Q.TPnHnUeQWJyNz4WQsMOKhYrZoaPknmceOp-G.voqTJ2V0ODJYC2u1maUdxl9-iBkg
What is this parameter? and how can I use it?

Wednesday, September 25, 2013

What would be a safe and practical way to copy a string as defined by this prompt in C?

What would be a safe and practical way to copy a string as defined by this
prompt in C?

The purpose of this function is to copy a string into a "buffer" -
essentially another string. However, the problem seems overly complicated
than what would be practical.
"Copies at most n-1 characters of string in into the buffer pointed to by
out. If n is reached, returns -2. Otherwise, returns -1 for malformed
input and 0 upon successful completion."
This is what I have:
#include <stdio.h>
#include <assert.h>
int copyStringN(register char *in, register char *out, register int n){
//Declarations
int i; //Dummy index
if(!in || !out) return -1;
for(i=0; i<n; i++){
*out++ = *in++;
}
*out = '\0';
return 0;
}
int main(void){
//Declarations
char in[] = "I'm not trying to inject malicious code...\\x29A.";
const int N = sizeof(in);
char out[N];
int err;
//Main execution
printf("\nThis function will copy at most n-1 characters of string
into\nthe buffer pointed to by out.\n\n");
err = copyStringN(in, out, N);
assert(!err);
printf("%s\n", out);
printf("\nPlease press enter to exit...");
getchar();
return 0;
}
This general form was suggested, but it seems overly convoluted than what
needs to be done. Why would n ever be reached? The execution should stop
before n. Furthermore, wouldn't N = sizeof(in) match the length of the
original string?
Personally, I would rather use a function closer to
int copyStringN(register char *in, register char *out)
{
if((!in || !out) && (sizeof(in)<=sizeof(out))) return -1;
else{
while(*t++ = *from++);
return 0;
}
}
int main(void){
//Declarations
char in[] = "I'm not trying to inject malicious code...\\x29A.";
const int N = sizeof(in);
char out[N];
int err;
..
..
..
I believe it would have the same effect with less statements. Let me make
this more of a question, how could I write a function that copies a string
into another array with the protection defined in the prompt? Also, are
the two programs that I presented somehow vulnerable in a way I don't
recognize?
Constructive input is appreciated.

Thursday, September 19, 2013

PHP - Force integer conversion to float with three decimals

PHP - Force integer conversion to float with three decimals

I am trying to convert a big array of numbers to a specific format which
is +/-NNN.NNN. So, if I have these numbers:
$numbers1 = array(-1.23, 0.3222, 10, 5.54);
I want their final format to be
$numbers2 = array(-001.023, +000.322, +010.000, +005.054);
I am trying to do it like this:
foreach ($numbers1 as $n) {
$fnum = abs(number_format((float)$n, 3, '.', ''));
if ($fnum>0 && $fnum<10) {
$fnum = '00'.$fnum;
} else if ($fnum >= 10 && $fnum<100) {
$fnum = '0'.$fnum;
}
if ($n>0) $fnum = '+'.$fnum;
if ($n<0) $fnum = '-'.$fnum;
if ($n == 0) $fnum = '+000.000';
$numbers2[] = $fnum;
}
This is wrong and I just don't know what to use in order to achieve it.

Can't print contents of array

Can't print contents of array

I am doing my homework and it says that I have to ask user for how many
members they want to be present in the array. Then the user should enter
the number in their array and then the program prints the array. I cannot
print contents from my array in the console window.
Here is my code:
.data
max: .word -9999
array: .space 12
message1: .asciiz "Enter an integer:\n"
message2: .asciiz "Specify how many numbers should be stored in the
array (atmost 8): \n"
message3: .asciiz "The array content is: \n"
message4: .asciiz "The maximum is: \n"
message5: .asciiz "They have the same maximum.\n"
message6: .asciiz "The first array has a larger maximum.\n"
message7: .asciiz "The second array has a larger maximum.\n"
.text
.globl main
main:
lw $s1, max
la $s3, array
li $s2, 3
la $a0, message2
li $v0, 4
syscall
li $v0, 5
syscall
move $t0, $v0
blt $t0, $s2, Read
Read:
la $a0, message1
li $v0, 4
syscall
li $v0, 5
syscall
move $t1, $v0
sw $t1, 0($s3)
addi $s3, $s3, 4
addi $t0, $t0, -1
bgt $t0, $zero, Read
j Print
#blt $t0, $s2, Print
Print:
la $a0, message3,
li $v0, 4
syscall
jr $ra
Thanks for the help.

Haskell differenct in showing Data.Text

Haskell differenct in showing Data.Text

Consider the next code in GHCi:
*> data R = R { s :: Text }
*> instance Show R where show x = unpack $ s x
*> let r = R $ pack "¶"
*> r

*> s r
"\182"
Why does it shows the paragraph sign without the quotes and when showing R
datatype. And showing like [Char] (actually, :t s r is Text) when showing
s r?

matplotlib.pyplot contourf function introduces holes or gaps when plotting regular data

matplotlib.pyplot contourf function introduces holes or gaps when plotting
regular data

I am trying to plot a 3D dataset using the contourf function in
matplotlib.pyplot. All of this is being run inside an iPython notebook. A
surface plot of the data looks fine, but the contourf plot has a big hole
in it.
A simplified version of the code I am using is:
import numpy as np # import modules
import scipy.io as spio
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure(figsize=(12,5))
zMin = 1.2
data = spio.loadmat('./OD_SurfMatFiles/surf_k2_c3.mat')
X = data['xVal']
Y = data['yVal']
Z = data['zVal']
plotX, plotY = numpy.meshgrid(X, Y)
ax = fig.add_subplot(1,2,1, projection='3d')
colourLevels = [0.0, 0.4, 0.8, 1.2, 1.6, 2.0, 2.4];
cset = ax.contourf(plotX, plotY, Z, colourLevels, zdir='z',offset=zMin,
cmap=cm.autumn)
CB = plt.colorbar(cset, shrink=0.5, extend='both')
The result can be seen here:
http://nbviewer.ipython.org/url/www.alexbaldwin.org.uk/pynotebooks/OD%2520Appendix%2520HM%2520Noise%2520Aperture%2520SurfBug%2520MWE%25202.ipynb
The data that is being plotted is:
Exported from MATLAB:
xVal =
384 416 448 480 512 544 576 608 640 672
yVal =
18 19 20 21 22
zVal =
Columns 1 through 9
1.1717 1.1421 1.1358 1.2124 1.1721 1.1840 1.1809
1.1399 1.1708
1.1286 1.2183 1.1654 1.1675 1.1810 1.1745 1.2100
1.2284 1.2096
1.2132 1.3057 1.2616 1.1742 1.2639 1.2316 1.2039
1.2277 1.2367
1.2363 1.1987 1.2367 1.2171 1.2718 1.2040 1.2462
1.1802 1.2218
1.2230 1.2601 1.2411 1.2436 1.2635 1.2197 1.2300
1.2266 1.2368
Column 10
1.2357
1.2039
1.3010
1.2273
1.2336
I originally had this problem with matplotlib 1.2. I considered that they
may have fixed it in a later version, but even with u'1.4.x' it still
occurs.

mutliple if conditions in javascript

mutliple if conditions in javascript

I am having multiple conditions in if as bellow
if((readCookie("endData") != "" && readCookie("lastRowArray") != "" &&
readCookie("histClickedImgId") != "" && readCookie("histClickedPage") !=
"" && readCookie("remove_count") != "" && readCookie("histBack") != "") &&
(readCookie("endData") && readCookie("lastRowArray") &&
readCookie("histClickedImgId") && readCookie("histClickedPage") &&
readCookie("remove_count") && readCookie("histBack") )){ cdtChecked =
true;
}
Is there any way to reduce the code.

how totalorder partitioner works in hadoop?

how totalorder partitioner works in hadoop?

i am new to this concept of totalorder partitioner in hadoop
i have some questions on this concept
1) how the sorting happens internally using totalorder partitioner?
2)why are we using an input sampler in this concept?
3)how can i know the number of reducers to set?
4) why are we using partitioner here?
5)what is a partition file?
i had above doubts while going through that concept.can anyone explain me
these concepts?
Thanks in Advance

Wednesday, September 18, 2013

how to display image in html using jsp call?

how to display image in html using jsp call?

Im trying to display an image in html page calling a jsp page in tag as
follows. I have created dynamic web project, and added index.html under
webcontent folder. and timeseries.jsp under webcontent->jsp folder. when i
run the project on server, adding apache tomcat 6.0.18, its synchronised,
but when i enter url localhost:8080/jfree it displays only hello doctor
and image icon on the page but no image there.
my html is,
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
Hello doctor
<img src="/jfree/jsp/Timeseries.jsp" alt="Progress chart" />
</body>
</html>
my jsp is,
<%@ page import="java.awt.Image" %>
<%@ page import="java.awt.*"%>
<%@ page import="java.text.SimpleDateFormat"%>
<%@ page import="java.awt.BasicStroke"%>
<%@ page import ="org.jfree.ui.ApplicationFrame"%>
<%@ page import="java.io.*" %>
<%@ page import="java.io.File"%>
<%@ page import="org.jfree.chart.*" %>
<%@ page import="org.jfree.chart.axis.*" %>
<%@ page import="org.jfree.chart.entity.*" %>
<%@ page import="org.jfree.chart.labels.*" %>
<%@ page import="org.jfree.chart.plot.*" %>
<%@ page import="org.jfree.chart.renderer.category.*" %>
<%@ page import="org.jfree.chart.urls.*" %>
<%@ page import="org.jfree.data.category.*" %>
<%@ page import="org.jfree.data.general.*" %>
<%@ page import="org.jfree.data.time.Minute"%>
<%@ page import="org.jfree.data.time.Hour"%>
<%@ page import="org.jfree.data.time.TimeSeries"%>
<%@ page import="org.jfree.data.time.TimeSeriesCollection"%>
<%@ page import="org.jfree.data.xy.XYDataset"%>
<%@ page import="org.jfree.chart.plot.XYPlot"%>
<%@ page import="org.jfree.chart.renderer.xy.StandardXYItemRenderer"%>
<%@ page import="org.jfree.chart.renderer.xy.XYItemRenderer"%>
<%@ page import= "java.sql.Connection" %>
<%@ page import ="java.sql.DriverManager" %>
<%@ page import = "java.sql.SQLException" %>
<%@ page import = "java.sql.PreparedStatement" %>
<%@ page import = "java.sql.ResultSet" %>
<%@ page import = "java.sql.Statement" %>
<%@ page import= "javax.servlet.*" %>
<%@ page import ="javax.servlet.http.*" %>
<%@ page import="java.awt.image.BufferedImage"%>
<%
try
{
File image = File.createTempFile("image", "tmp");
//chart class instance
Fms fm = new Fms("Graph");
JFreeChart chart = fm.createChart(fm.dataset);
ChartUtilities.saveChartAsPNG(image, chart, 500, 400);
//get input stream
FileInputStream fileInStream = new FileInputStream(image);
//output stream foe returning chart as image
OutputStream outStream = response.getOutputStream();
long fileLength;
byte[] byteStream;
fileLength = image.length();
byteStream = new byte[(int)fileLength];
//read chart image
fileInStream.read(byteStream, 0, (int)fileLength);
//returns chart image whenever called
response.setContentType("image/png");
response.setContentLength((int)fileLength);
response.setHeader("Cache-Control","no-store,no-cache, must-revalidate,
post-check=0, pre-check=0");
response.setHeader("Pragma", "no-cache");
fileInStream.close();
outStream.write(byteStream);
outStream.flush();
outStream.close();
}
catch (IOException e)
{
System.err.println("Problem occurred creating chart.");
}
%>
<%! public class Fms extends ApplicationFrame {
//Main class
XYDataset dataset= null;
public Fms(final String title) {
super(title);
dataset= createDataset();
final JFreeChart chart = createChart(dataset);
final ChartPanel chartPanel = new ChartPanel(chart);
chartPanel.setPreferredSize(new java.awt.Dimension(700, 570));
chartPanel.setMouseZoomable(true, false);
setContentPane(chartPanel);
}
//chart creation method
JFreeChart createChart(final XYDataset dataset) {
final JFreeChart chart = ChartFactory.createTimeSeriesChart(
"Speed Chart",
"Time",
"Speed",
dataset,
true,
true,
false
);
chart.setBackgroundPaint(Color.white);
final XYPlot plot = chart.getXYPlot();
plot.setBackgroundPaint(Color.lightGray);
plot.setDomainGridlinePaint(Color.white);
plot.setRangeGridlinePaint(Color.white);
plot.setDomainCrosshairVisible(true);
plot.setRangeCrosshairVisible(false);
final XYItemRenderer renderer = plot.getRenderer();
if (renderer instanceof StandardXYItemRenderer) {
final StandardXYItemRenderer rr = (StandardXYItemRenderer)
renderer;
rr.setShapesFilled(true);
renderer.setSeriesStroke(0, new BasicStroke(1.0f));
renderer.setSeriesStroke(1, new BasicStroke(1.0f));
}
final DateAxis axis = (DateAxis) plot.getDomainAxis();
axis.setDateFormatOverride(new SimpleDateFormat("dd:MM"));
try{
final ChartRenderingInfo info = new ChartRenderingInfo
(new StandardEntityCollection());
final File file1 = new File("c:/Documents and
Settings/accounts/WebApplication2/web/barchart.png");
ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info);
}catch(Exception e){}
return chart;
}
//data set generation method
private XYDataset createDataset() {
final TimeSeriesCollection dataset = new TimeSeriesCollection();
dataset.setDomainIsPointsInTime(true);
final TimeSeries s1 = new TimeSeries("Series 1", Minute.class);
s1.add(new Minute(0, 0, 7, 7, 2003), 10.2);
s1.add(new Minute(30, 12, 7, 8, 2003), 23.0);
s1.add(new Minute(15, 14, 7, 9, 2003), 48.0);
final TimeSeries s2 = new TimeSeries("Series 2", Minute.class);
s2.add(new Minute(0, 0, 7, 7, 2003), 23.0);
s2.add(new Minute(30, 12, 7, 8, 2003), 9.0);
s2.add(new Minute(15, 14, 7, 9, 2003), 36.0);
dataset.addSeries(s1);
dataset.addSeries(s2);
return dataset;
}
}
%>
but its not dispaying the image in jsp? any help?

Alphabetical selection sort of a 2D array

Alphabetical selection sort of a 2D array

My assignment asks me to store inputted data in a 2D array and use a
selection sort to sort the crimes in alphabetical order. How can I alter
the following selection sort:
//selection sort
for(i = 0; i < criminal.length; i++){
smallest = i;
for(j = i; j < criminal.length; j++){
//compare smallest to current position
if(criminal[j] < criminal[smallest]){
smallest = j;
}
//swap smallest with position in the array
temp = criminal[i];
criminal[i] = criminal[smallest];
age[smallest] = temp;
}
}
//output
for(i = 0; i < criminal.length; i++){
System.out.println(criminal[i]);
}
So that it can accommodate a 2D array that looks like this:
//loop to request to fill array
for (i = 0; i < criminals.length ; i++) {
System.out.print("Enter first and last name of criminal: ");
criminals[i][0] = br.readLine(); //Criminal Name
System.out.print("Enter crime committed: ");
criminals[i][1] = br.readLine(); //Criminal Crime
System.out.print("Enter year of conviction: ");
criminals[i][2] = br.readLine(); //Year of conviction
}
That's it. Any help would be great! I really need to finish this ASAP.
Thanks in advance. :)

How would I create a long running process in C#?

How would I create a long running process in C#?

This may seem very elementary, but I don't really have any experience in
this realm - all my experience has been on the web side of things.
I need to create a process of some sort that will repeatedly query an API
(around 5 times a second), get the results from the API (in JSON format),
and then my process will do what it needs to do with the results (in my
case, insert them into a SQL database). These details don't really matter
to the scope of the question I have, I just want to give you an idea on
what I'm trying to achieve in case someone wants to recommend a better way
of doing it.
My first thought was to create a console app that basically never quits
(unless I specifically tell it to). Is a console app the way to go for
this? The idea is I'll have a VM set up which will host my solution,
including this "process" I create. I'm not all too familiar with Windows
Services, or Windows Tasks, but I probably need to write some custom code
so therefore I imagine I can't use the Windows Task Scheduler, am I right?

Installing PHP_codesniffer with Pear and MAMP Pro on OSX

Installing PHP_codesniffer with Pear and MAMP Pro on OSX

I've tried all kinds of fixes to get php_codesniffer working with OSX and
Pear and am having no luck. The installation works, the scripts are there,
but when I run, for example, phpcs -h, nothing happens.
I am doing the following to install and try to run:
chris@DEATHSTAR:~$ pear clear-cache
reading directory
/var/folders/r5/3s2lsmc10zj07nw56xbx1k1m0000gn/T//pear/cache
14 cache entries cleared
chris@DEATHSTAR:~$ pear install php_codesniffer
Unknown remote channel: pear.phpunit.de
Did not download optional dependencies:
channel://pear.phpunit.de/PHP_Timer, use --alldeps to download
automatically
pear/PHP_CodeSniffer can optionally use package
"channel://pear.phpunit.de/PHP_Timer"
downloading PHP_CodeSniffer-1.4.6.tgz ...
Starting to download PHP_CodeSniffer-1.4.6.tgz (402,882 bytes)
.................................................................................done:
402,882 bytes
install ok: channel://pear.php.net/PHP_CodeSniffer-1.4.6
chris@DEATHSTAR:~$ which phpcs
/Applications/MAMP/bin/php/php5.4.10/bin/phpcs
chris@DEATHSTAR:~$ phpcs -h
chris@DEATHSTAR:~$
The PHP directory is correct in Pear config:
chris@DEATHSTAR:~/.vim$ pear config-show | grep php_bin
PHP CLI/CGI binary php_bin
/Applications/MAMP/bin/php/php5.4.10/bin/php
Not sure what else I can do to troubleshoot?
Possible related note: PHP Mass Detector does essentially the same
thing...it installs correctly, but running it seemingly does nothing as
well!

Preventing Pages theme from being imposed on each aspx page directive during compilation

Preventing Pages theme from being imposed on each aspx page directive
during compilation

in my web.config i use the following pages declaration
<pages maintainScrollPositionOnPostBack="true" Theme="Theme1">
with the intention of being able to use different themes on a web
application to customize the way it displays for a few different
clients(some of which want their own branding on the web application's
pages)
if i leave out the theme directive in my development code, it doesn't
display properly when debugging, so i want to have the Theme defined in
the web.config... however when it is defined as above and i go to publish
my solution every .aspx page declaration goes from this:
<%@ Page Language="VB" CodeFile="MRSHome.aspx.vb"%>
to this:
<%@ page language="VB" inherits="App_Web_peiwi24o" theme="Theme1"
maintainScrollPositionOnPostBack="true" %>
and page level theme declarations override the ones set in the web.config
file, i need that to remain the case since some pages programmatically
switch to a print friendly theme when the user needs it.
How do i prevent the web.configs pages settings from being appended to
each page's page declaration during compilation?

Design best practice: How to display in JSP an object with partial collection needed, for application that uses Hibernate?

Design best practice: How to display in JSP an object with partial
collection needed, for application that uses Hibernate?

I have an object Master that has a collection of Student objects. I have a
list of Master objects and I would want to display in the JSP the Master
fields and only the Students that have a score greater than some constant.
I cannot partially load a collection to have only the desired students
because Hibernate does not function like this. I can only filter it in
another collection but I won't have the collection bound to the Master
object for displaying this in the JSP.
My solution for displaying this in the JSP is to use an Wrapper object and
create instances after loading the data from the DB. After that I can use
the object to display it in the JSP:
Class WrapperMaster{
Master master;
Set<Student> filteredStudents;
}
Questions:
Won't this be just a silly and maybe reduntant thing to do?
I will have encapsulated persistent objects contained in another object
(that is unpersistent). Is this a best practice?
An alternative would be to not use the Wrapper object, but filter manually
the collection of students from the Master object in the JSP. I use
Struts2 so I would have to use many <s:if> tags.

can the for loop have double value as index in c and c++?

can the for loop have double value as index in c and c++?

Is it legal to have the following for loops in c and c++:
for(double d=2.0; d<3.1; d+=0.1)

Get USSD codes reques text in android

Get USSD codes reques text in android

i want to get USSD codes text in android.
how can do it?
for example make a call to *12345*54321# and after calling server show a
text for me i want to get that text in my app.

How do I limit the clicks numbers to 9?

How do I limit the clicks numbers to 9?

I created a lock that opens when you click "777" and I want to limit the
clicks to 9. How do I do that?
var numberOfClicks1 = 0;
var numberOfClicks2 = 0;
var numberOfClicks3 = 0;
$('#clickme1').on('click', function() {
numberOfClicks1++;
$('#click-counter1').html(numberOfClicks1);
})
$('#clickme2').on('click', function() {
numberOfClicks2++;
$('#click-counter2').html(numberOfClicks2);
})
$('#clickme3').on('click', function() {
numberOfClicks3++;
$('#click-counter3').html(numberOfClicks3);
})
$('#down-click1').on('click', function() {
numberOfClicks1--;
$('#click-counter1').html(numberOfClicks1);
})
$('#down-click2').on('click', function() {
numberOfClicks2--;
$('#click-counter2').html(numberOfClicks2);
})
$('#down-click3').on('click', function() {
numberOfClicks3--;
$('#click-counter3').html(numberOfClicks3);
})

Tuesday, September 17, 2013

What is the difference between the following two declarations and when should they be used

What is the difference between the following two declarations and when
should they be used

I am learning javascript. I am confused between the following two
notations where the newly created objects inherit the properties. How are
they different and when should i use them?
Code 1:
var Vehicle = function Vehicle() {
this.wheel=2
}
var vehicle = new Vehicle();
alert(vehicle.wheel);
Code 2:
var Vehicle = function Vehicle() {
}
Vehicle.prototype.wheel = 4;
var vehicle = new Vehicle();
alert(vehicle.wheel);
When is the keyword prototype used?

Java Math.min() Error on Integer.Max_Value

Java Math.min() Error on Integer.Max_Value

This code, which should return the smaller of the two numbers, returns a
negative number similar to the greater number:
Math.min(15, 21474836477) --> returns -2147483642
I suspected this had something to do with the range of int's, so I changed
the values to long and the program worked fine.
I don't quite understand the seemingly random number it returns- why is it
-2147483643 and not the actual number I put in, -21474836477? Is the
difference caused by the amount it overflowed, or is it influenced by the
other parameter of Math.min in some way?

Mysql datatype SET with rails

Mysql datatype SET with rails

So for some reason, our database guy decided to use the mysql datatype
set. I'm trying to make it work with rails. Here is our column:
actions => set('spoke_to','left_voicemail','emailed')
To make it work I have the following code which i'm sure could be far better:
def actions=(type)
write_attribute(:actions, pack(type))
end
def actions
read_attribute(:actions).split(",") unless
read_attribute(:actions).nil?
end
private
def pack(type)
acs = self.actions
if acs.present? && acs.include?(type)
acs.delete(type)
delete_actions(acs)
else
write_actions(acs, type)
end
end
def delete_actions(acs)
if acs.empty?
write_attribute(:actions, nil)
else
write_attribute(:actions, acs)
end
end
def write_actions(acs, type)
debugger
if acs.present?
write_attribute(:actions, acs.push(type).join(","))
else
write_attribute(:actions, type)
end
end
However, setting the action(s) works just like fine, but when I try to
unset one I have the following weird query being generated:
(72.5ms) BEGIN
(73.6ms) UPDATE `service_requests` SET `actions` = '---\n- spoke_to\n-
left_voicemail\n' WHERE `service_requests`.`nid` = 69524843
(78.2ms) COMMIT
And I have no idea why.

MySql query 7 days prior to say days ahead

MySql query 7 days prior to say days ahead

I am trying to construct a mysql query that will pull records from a
timestamp that is from 7 days from todays date and 7 days out from todays
date. I can get the rows that are 7 days either way but not both and cant
seem to figure out how to make this work. Thanks for you help.

NodeJS | Passing an object as function parameter

NodeJS | Passing an object as function parameter

I've had a small problem I couldn't overcome this week, I'm trying to pass
a JSON object as a parameter in a function but it always tells me that I
can't do that, but I don't want to end up sending the 50 values separately
from my json object.
Here is the set up on my app, this is working as intended with express :
app.get('/', routes.index);
Here is the routing index from the previous line of code (Note that I'm
using jade for rendering and I'm using the next function to pass
parameters to it like the name in this one :
exports.index = function(req, res){
getprofile.profileFunc(function(result) {
res.render('index', { name: result });
});
};
Next it calls the function profileFunc from getprofile :
var profileFunc = function(callback) {
var sapi = require('sapi')('rest');
sapi.userprofile('name_here', function(error, profile) {
var result = [profile.data.name];
callback.apply(null, result);
});
};
exports.profileFunc = profileFunc;
Note that I was only able to pass a string result and have it displayed in
the jade render, what I want to do is pass the profile object to use it in
the render to display name, age, birthday but I can't get it to work, it
will either pass a undefined object or not pass.
Thanks for taking time to read this.

SSH Amazon Reserved Instance

SSH Amazon Reserved Instance

I have bought Amazon Reserved Instance(HighCPU-Medim). And I don't see any
dns information to connect with SSH. While using On Demand Instance there
was this information, but in reserved I don't see. What should I do? I
appreciate any help

Sunday, September 15, 2013

Android - How to cache Json using SQLite

Android - How to cache Json using SQLite

My application should work not only in online but also in offline mode.
When my app have internet connection, it will download data (parse from
Json) and save to SQLite database. If I turn off internet, it will get
data from SQLite to display. My problems are how I know when data update
or have new data from server. I want update current records and add new
records when data change.
Ex:
First load - Load 50 records >>> save to SQLite
Second load - Load 30 records (20 current records change & 15 new records)
Total - 65 records in SQLite
Thanks for any help

Execute function only when called by using header:location PHP

Execute function only when called by using header:location PHP

I'd like to be able to only execute a PHP function when I call it by using
header location.
function username() {
$_GET['username'];
}
and only run that function when I call it from a header as followed.
header('Location:www.domain.com/index.php?=getusername')
Once I type that in the URL then the function would execute, how do I
accomplish such use?

Link not asking user to confirm

Link not asking user to confirm

I have this code
echo '<div class="bottomright"><a href="?id='
. $topic_id
. '&part=5"><img src="../assets/icons/Comments-
edit.png" /></a><a href="?id='
. $topic_id
. '&part=6"><img src="../assets/icons/Lock.png" /></a><a
href="#" onclick="return confirm("Are you sure?")"><img
src="../assets/icons/Trash.png" /></a></div>';
When I click Trash.png it is supposed to ask "Are you sure"? But it
doesn't...
Am I missing something here?

closing mongodb connection in node.js while inserting lot of data

closing mongodb connection in node.js while inserting lot of data

I am trying write a program to parse and insert iis logs data in to
mongodb. The files aren't that huge it's around 600 lines. Trying to
convince my management nodejs and mongodb is better for this compared to
.net and sql server :).
Have a look at the below code in nodejs. Logic: I parse every line and
convert into json and insert the save in db. i am using mongonative
driver.
Issue : The db connection gets closed even before all lines are inserted
into the Db.
I see the log file has 6000 lines, but num of records in db is only arnd
4000. I understand it's nodejs's async characteristic, in this how can i
close the connection in more deterministic way (after checking if all
lines got inserted)?
var MongoClient = require('mongodb').MongoClient;
var mongoServer = require('mongodb').Server;
var serverOptions = {
'auto_reconnect': true,
'poolSize': 5
};
var fs = require('fs');
var readline = require('readline');
var rd = readline.createInterface({
input:
fs.createReadStream('C:/logs/Advisor_Metrics/UI/P20VMADVSRUI01/u_ex130904.log'),
output: process.stdout,
terminal: false
});
var mongoClient = new MongoClient(new mongoServer('localhost', 27017,
serverOptions));
var db = mongoClient.db('test');
var collection = db.collection('new_file_test');
var cntr = 0;
mongoClient.open(function (err, mongoClient) {
console.log(err);
if (mongoClient)
{
rd.on('line', function (line) {
if (line.indexOf('#') == -1) {
var lineSplit = line.split(' ');
var data =
{
d: lineSplit[0],
t: lineSplit[1],
sip: lineSplit[2],
met: lineSplit[3],
uri: lineSplit[4],
cip: lineSplit[8],
cua: lineSplit[9],
stat: lineSplit[10],
tt: lineSplit[13]
};
collection.insert(data, function (err, docs) {
console.log('closing connection');
//db.close();
});
}
});
}
})
rd.on('close', function () {
db.close();
});
Sol 1 : A solution would be parse the json objects and add into an array
and add the array to mongodb. i wouldn't like to do that since that would
like parsing the entire huge log file into memory!, Any other solution?

ASP .NET WebMethods Synchronization

ASP .NET WebMethods Synchronization

I have a webmethod in asp.net .asmx service, wich is supposed to check if
there are records in a DB, and if there are no records it should add a
record
the simplified example of code is like this:
object Mutex = new object();
[WebMethod]
public void InsertIfNotExists(string CLI)
{
lock (Mutex)
{
using (SqlConnection conn = new SqlConnection(ConnectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter())
using (DataSet ds = new System.Data.DataSet()){
{
//I log with log4net
logger.Debug("InsertIfNotExists: Start Function: CLI:" + CLI);
int dummy = 0;
string sql = "SELECT * CLI Promote where CLI=" + CLI + " ";
adapter.SelectCommand = new SqlCommand(sql, conn);
adapter.Fill(ds);
DataTable t = ds.Tables[0];
logger.Debug("InsertIfNotExists: " + t.Rows.Count + " records
found for CLI:" + CLI);
if (t.Rows.Count == 0)
{
logger.Debug("InsertIfNotExists: starting to add to table:
CLI:" + CLI);
DataRow dr = t.NewRow();
dr["CLI"] = CLI;
dr["DateOfSend"] = DateTime.Now;
InsertToTable(t, dr, sql);
logger.Debug("InsertIfNotExists: added to table: CLI:" + CLI +
", starting re-check");
//checking if exist more then one lines - one more time
sql = "SELECT * CLI Promote where CLI=" + CLI + "";
adapter.SelectCommand = new SqlCommand(sql, conn);
adapter.Fill(ds);
t = ds.Tables[0];
logger.Debug("InsertIfNotExists: re-check for CLI:" + CLI + ",
records count=" + t.Rows.Count);
}
logger.Debug("InsertIfNotExists: Finish Function for CLI:" + CLI);
}
}
}
Actually it does more checks and logic, that's why I implement it in .net
and not in the SQL statement itself, but essentially that is it.
Most of the time the code works well, but sometimes I get into race
conditions because of multithreading, though I use lock.
Sample output I got today:
2013-09-15 11:47:14,145 [21] DEBUG Namespace.Service1 InsertIfNotExists:
Start Function: CLI: 0501234567
2013-09-15 11:47:14,145 [13] DEBUG Namespace.Service1 InsertIfNotExists:
Start Function: CLI: 0501234567
2013-09-15 11:47:14,148 [21] DEBUG Namespace.Service1 InsertIfNotExists: 0
records found for CLI: 0501234567
2013-09-15 11:47:14,148 [21] DEBUG Namespace.Service1 InsertIfNotExists:
starting to add to table: CLI: 0501234567
2013-09-15 11:47:14,148 [13] DEBUG Namespace.Service1 InsertIfNotExists: 0
records found for CLI: 0501234567
2013-09-15 11:47:14,148 [13] DEBUG Namespace.Service1 InsertIfNotExists:
starting to add to table: CLI: 0501234567
2013-09-15 11:47:14,149 [21] DEBUG Namespace.Service1 InsertIfNotExists:
added to table: CLI: 0501234567, starting re-check
2013-09-15 11:47:14,149 [13] DEBUG Namespace.Service1 InsertIfNotExists:
added to table: CLI: 0501234567, starting re-check
2013-09-15 11:47:14,154 [27] DEBUG Namespace.Service1 InsertIfNotExists:
Start Function: CLI: 0501234567
2013-09-15 11:47:14,157 [27] DEBUG Namespace.Service1 InsertIfNotExists: 2
records found for CLI: 0501234567
2013-09-15 11:47:14,157 [27] DEBUG Namespace.Service1 InsertIfNotExists:
Finish Function for CLI: 0501234567
2013-09-15 11:47:14,183 [13] DEBUG Namespace.Service1 InsertIfNotExists:
re-check for CLI: 0501234567, records count=2
2013-09-15 11:47:14,184 [21] DEBUG Namespace.Service1 InsertIfNotExists:
re-check for CLI: 0501234567, records count=2
2013-09-15 11:47:14,185 [13] DEBUG Namespace.Service1 InsertIfNotExists:
Finish Function for CLI: 0501234567
2013-09-15 11:49:19,626 [21] DEBUG Namespace.Service1 InsertIfNotExists:
Start Function: CLI:0507654321
What we see here that 3 threads attempted to insert CLI 0501234567 to the
table in the parallel. Threads 21 and 13 entered the race conditons and
each one inserted 1 record. Then thread 27 also tried to insert a record,
but found existing records and exited.
Why did they do it when locked on mutex?
Additional strange thing is that the thread 21 did never got to the line
logger.Debug("InsertIfNotExists: Finish Function for CLI:" + CLI);
and somehow jumped to starting the function from the beginning for another
CLI.
2013-09-15 11:49:19,626 [21] DEBUG Namespace.Service1 InsertIfNotExists:
Start Function: CLI:0507654321
Why does asp.net behave in such a way and what is the proper thing to
accomplishing that task without the race conditions?

Changing background color with setInterval

Changing background color with setInterval

Hi I'm trying to make a row of divs blink, but one div should blink at a
time.(not all the divs should blink at the same time [i could do that])..
kind of like the way a traffic light works. each light is part of a row of
lights and each light turns on and off one at a time going through a loop.
in my case the blinking is meant to remind the users that the divs or
clickable.
I put each box in an array but I couldn't figure out how to change the
color of each box in a loop. I guess a way to solve this is by adding and
removing a classes that contains the colors and it should do that after 1
or 2 seconds so setInterval should come in to play. I couldn't figure it
out.
but here is my sad code
var arr =[];
$(".boxes").each(function(){
arr.push($(this));
});
function bgChange(){
for(i = 0; i < arr.length; i++){
arr[i].addClass("red");
}
}
setInterval(bgChange, 2000);
});
I'm looking to forward to seeing the creative ways that you guys could
come up with to make this work.
JSFIDDLE Thank You in advanced

Saturday, September 14, 2013

Disable Jquery autocomplete dropdown from codebehind c#

Disable Jquery autocomplete dropdown from codebehind c#

I am using http://jqueryui.com/autocomplete/#combobox for my dropdownlist
and it works well. My problem here is when I disable the dropdown list
from code behind it doesn't work.
My code is here.
ASPX
<asp:DropDownList runat="server" CssClass="Dropdown" ID="ddlStatus">
</asp:DropDownList>
JS
function pageLoad() {
/******** Auto Complete *********************/
$(function () {
$("#<%= ddlStatus.ClientID %>").combobox();
});
(function ($) {
$.widget("custom.combobox", {
_create: function () {
this.wrapper = $("<span>")
.addClass("custom-combobox")
.insertAfter(this.element);
this.element.hide();
this._createAutocomplete();
this._createShowAllButton();
},
_createAutocomplete: function () {
var selected =
this.element.children(":selected"),
value = selected.val() ? selected.text() : "";
this.input = $("<input>")
.appendTo(this.wrapper)
.val(value)
.attr("title", "")
.addClass("custom-combobox-input ui-widget
ui-widget-content ui-state-default
ui-corner-left")
.autocomplete({
delay: 0,
minLength: 0,
source: $.proxy(this, "_source")
})
.tooltip({
tooltipClass: "ui-state-highlight"
});
this._on(this.input, {
autocompleteselect: function (event, ui) {
ui.item.option.selected = true;
this._trigger("select", event, {
item: ui.item.option
});
__doPostBack('<%= upnlTab.ClientID
%>', this.element.attr("id"));
},
autocompletechange: "_removeIfInvalid"
});
},
_createShowAllButton: function () {
var input = this.input,
wasOpen = false;
$("<a>")
.attr("tabIndex", -1)
//.attr("title", "Show All Items")
//.tooltip()
.appendTo(this.wrapper)
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass("ui-corner-all")
.addClass("custom-combobox-toggle
ui-corner-right")
.mousedown(function () {
wasOpen =
input.autocomplete("widget").is(":visible");
})
.click(function () {
input.focus();
// Close if already visible
if (wasOpen) {
return;
}
// Pass empty string as value to search
for, displaying all results
input.autocomplete("search", "");
});
},
_source: function (request, response) {
var matcher = new
RegExp($.ui.autocomplete.escapeRegex(request.term),
"i");
response(this.element.children("option").map(function
() {
var text = $(this).text();
if (this.value && (!request.term ||
matcher.test(text)))
return {
label: text,
value: text,
option: this
};
}));
},
_removeIfInvalid: function (event, ui) {
// Selected an item, nothing to do
if (ui.item) {
return;
}
// Search for a match (case-insensitive)
var value = this.input.val(),
valueLowerCase = value.toLowerCase(),
valid = false;
this.element.children("option").each(function
() {
if ($(this).text().toLowerCase() ===
valueLowerCase) {
this.selected = valid = true;
return false;
}
});
// Found a match, nothing to do
if (valid) {
return;
}
// Remove invalid value
if (value != '') {
this.input
.val("")
.attr("title", value + " didn't match
any item")
.tooltip("open");
this.element.val("");
this._delay(function () {
this.input.tooltip("close").attr("title",
"");
}, 2500);
this.input.data("ui-autocomplete").term = "";
} else {
this.input.val("");
this.element.val("");
this.input.data("ui-autocomplete").term = "";
}
__doPostBack('<%= upnlTab.ClientID %>',
this.element.attr("id"));
},
_destroy: function () {
this.wrapper.remove();
this.element.show();
}
});
})(jQuery);
}
C#
Based some validations I am calling this,
ddlStatus.Enabled = false;

PHP Displaying of page issues

PHP Displaying of page issues

It's a blank page and that's not how it's supposed to be :/
Can anyone help me out with this?
Code - http://pastie.org/private/9klk5tm6goixq4ev93tkq
- Mord

update data on file change?

update data on file change?

public DataUpdater(string file, ref DataTable data)
{
FileSystemWatcher fileWatcher = new FileSystemWatcher();
fileWatcher.Path = Path.GetDirectoryName(file);
fileWatcher.Filter = Path.GetFileName(file);
fileWatcher.NotifyFilter = NotifyFilters.LastWrite;
fileWatcher.Changed += (sender, e) =>
{
ref data = CSVParser.ParseCSV(file);
};
}
Hello, i'm trying to update a data table variable when a file changes but
the output says i cant have a ref or out in the changed event. please help

jQuery shows hidden content on refresh

jQuery shows hidden content on refresh

I use this fancy little jQuery toggle on my site, works great. But now I
have a little larger text area I want to hide, and therefore I've included
it in another php file, but when the site opens\refreshes the content is
briefly shown and then hidden? Have I done something wrong or does it
simply not work right with includes in it ?
<a href="#" id="toggleMe">Show me?</a>
<div class="content">
<?php include 'includes/test.php'?>
</div>
<script>
jQuery(document).ready(function() {
var par = jQuery('.content');
jQuery(par).hide();
});
jQuery('#toggleMe').click(function() {
jQuery('.content').slideToggle('fast');
return false;
});
</script>

Invalid Syntax Error with If statement

Invalid Syntax Error with If statement

So when i try to run this, i get Invalid syntax on the second if
statement, highlighting the colon. I don't understand why this is
occurring, as far as i can see, they're basically the same. So why does
the second if statement return invalid syntax but the first doesnt?
for event in pygame.event.get():
if event.type == MOUSEBUTTONDOWN :
if ROption1Exists == True:
rx, ry = event.pos
if rx >= (100*((X+3)+1)) and rx <= (100*((X+3)+2)) and ry >=
(100*(Y+1)) and ry <= (100*(Y+2)):
print('babies')
VarReset()
Pos = ((X+3), Y)
if ROption2Exists == True:
rx, ry = event.pos
if rx >= (100*((X-3)+1)) and rx <= (100*((X-3)+2)) and ry >=
(100*((Y+1)) and ry <= (100*(Y+2)):
print('babies')
VarReset()
Pos = ((X-3), Y)

How color a text from richtextbox without using selectioncolor vb,net

How color a text from richtextbox without using selectioncolor vb,net

i made a MySql chat in visual basic and i want to make the text with
colors ... without using selection color in richtextbox ... for example :
[color:FFFFFF]HEREISTHETEXT[/color]
[b]BOLD TEXT[/b]
Or using others types of codes ...
so ... when a user type something will be something like that:
[b]username[/b]: [color:00000]his message[/color]

Item popularity in mysql

Item popularity in mysql

I have a table
ItemId Items views
1 - item1 - 4
2 - item2 - 3
3 - item3 - 3
I would live to know how populair a product is
the result should be
item 1: first place
item 2: second place
item 3: second place
I have a very hard time figuring out how to do this in mysql. Is there a
query that will to exactly this ? Especially when a user is on the item3
page I would like to say: this is the second most popular product
Any help would greatly appreciated !

button is not disabling in internet explorer 10

button is not disabling in internet explorer 10

I have defined the button as
<input type="button" id="disable" disabled="disabled" value="Upload" />
But the button is not looking like disabled in chrome, firefox and safari.
and in ie it is even clicking.

Friday, September 13, 2013

c pointer Segmentation fault

c pointer Segmentation fault

void get(){
char fileNameBuf[10];
int i=0;
if (*buf=='/') {
*buf++;
while (*buf!=' ') {
fileNameBuf[i]=*buf;
*buf++;
i++;
printf("%d\n",i);
}
}
}
*buf points to string "/index.html HTTP/1.0". This while loop stores the
character that *buf points to until *buf points to a space. So fileNameBuf
should store the string "index.html". i indicates the number of times the
while loop looped which should be 10. But when i run this code, i = 381
instead and Segmentation fault (core dumped) occurs, what is wrong with
the code and how do i fix it?

Top align 3 floating divs

Top align 3 floating divs

I am trying to get 3 divs that span the width of the page to align to the
top. The idea is to have:
Left Div| Center Div | Right Div
with both the left and right divs taking 25% of the width and the centre
taking 50%. I am using float to get the left and right div's to align to
the sides of the screen. However, my problem is that once I set the center
div to 50% , the right div no longer aligns to the top. Setting 45% width
for the center gets the desired effect in terms of aligning the tops,
however the center div does not take up all the available space
simple HTML demonstrating the problem:
<div class="parent">
<div class="title-bar">Title goes Here</div>
<div class="sidecontent left">Some content</div>
<div class="content">More content and more and more More content and more
and more More content and more and more</div>
<div class="sidecontent right">Some Content</div>
</div>
CSS
.title-bar {
color: @color;
background-color: @title-color;
padding: 5px;
font-family: @font-family;
margin-bottom: 10px;
font-size: 20px;
text-align: center;
border: 1px solid #D5D5D5;
border-radius: 5px;
}
.left {
float: left;
}
.right {
float: right;
}
.sidecontent {
width: 25%;
border: 1px solid #D5D5D5;
display: inline-block;
//padding: 5px;
vertical-align: top;
height: 500px;
background-color: red;
overflow-y: auto;
}
.content {
float: left;
display: inline-block;
vertical-align: top;
width: 50%;
}
here is a jsFiddle demonstrating the problem: http://jsfiddle.net/s6vqC/
Any assistance would be appreciated (I'm new to this css thing) Thanks.

Why am I getting an undefined method `each' for nil:NilClass?

Why am I getting an undefined method `each' for nil:NilClass?

Total neophyte here. I'm just trying to list all of the objects in
'sites'. I know it's something agonizingly simple, but I just can't seem
to track it down!
The error:
NoMethodError in Home#index
Showing
/Users/jasonmurphy/data/projects/moviefeed/app/views/home/index.html.erb
where line #6 raised:
undefined method `each' for nil:NilClass
Extracted source (around line #6):
3: <u>SITES</u>
4: <br>
5:
6: <% @sites.each do |site| %>
7: <%= site.name %>
8: <% end %>
My 'sites' controller:
class SitesController < ApplicationController
def index
@sites = Site.all
end
def show
@site=Site.find(params[:id])
end
end
My view - Views/home/index.html.erb
<u>SITES</u>
<br>
<% @sites.each do |site| %>
<%= site.name %>
<% end %>
And my routes.rb
resources :sites
resources :critics
root :to => "home#index"

How to create NSDate timer with selector and time interval

How to create NSDate timer with selector and time interval

Hi I want to create an NSDate object with the following functionality as
the NSTimer line below.
[NSTimer scheduledTimerWithTimeInterval:(slider.value * 60) target:self
selector:@selector(nextFunction) userInfo:nil repeats:NO];
So what is it that appeals to me about the above like is that I can put in
the time I want for it to countdown. Also once the timer has reached 0 the
nextFunction method is called. But I need to use NSDate for a future
operation that cannot be completed with NSTimer. In summary, I want to
create an NSDate that will countdown from whatever current value my slider
holds then upon completion of countdown to call the nextFunction method.
Thanks

Code for converting html text to pdf

Code for converting html text to pdf

I want to convert html to pdf.The htmlworker from itext works but I dont
get the table,strikeout,background color on the pdf file.Please could
someone post me the java code.Or a link if possible.I want to apply it to
JSP.

Thursday, September 12, 2013

SQL Server Table Lock during bulk insert

SQL Server Table Lock during bulk insert

Below is the sample query, consider A
INSERT INTO Target (Col1,Col2,Col3,Col4) ----------------Statement#1
Select A.Col1,B.Col2,A.Col3,C.Col4 ----------------Statement#2
FROM A WITH(NOLOCK) INNER JOIN B WITH(NOLOCK)
ON A.Id = B.ID
LEFT JOIN C WITH NOLOCK
ON C.Id = B.ID
Where A.Id = 11
At which stage the lock will be applied on table [exclusive lock?], how
SQL is going to execute the query?
Result will be fetched from table A, B and C based on join and where clause.
On ready result, start inserting data in table and at same time apply the
lock on table.
So when actual data is written on the page table is locked but not during
select even though it is INSERT INTO with SELECT?

Figuring out R error-handler stack

Figuring out R error-handler stack

Having spent more time chasing my tail on this than is healthy, I'm just
going to have to ask:
In R, [how] can one figure out what error handlers are in force at a given
point in the code? Somebody somewhere is gracefully intercepting my
errors, and I want them to stop!
Thank you -
Aran

List all suggested fields given the label

List all suggested fields given the label

I have a field that has a label like First Name. Now I have a user defined
field that he chooses or types. Once he submits the typed label I want to
give him the list of suggested fields that he can map to.
So If user submitted a field labels: Name, First, Hello would get
suggested field First Name for both Name and First.
I am not asking for code. I just need an algorithm I can follow to do this.
Note: I can not use simple CONTAINS method since there might be two or
three words in user submitted label and I need to match any of those words
to existing fields.
Any mapping algorithms would be appreciated. All I need is name of
algorithm and I'll figure it out myself.

How is an event parameter passed?

How is an event parameter passed?

I've noticed in C# I can override methods in the Form() parent class, like
so:
protected override void OnPaint(PaintEventArgs e)
{
}
I don't understand how PaintEventArgs is generated and how/when it is
passed to this function. I've got to assume OnPaint() is called every time
the form needs repainting.
Furthermore, when I create button press events they look like this:
private void button1_Click(object sender, EventArgs e)
{
}
Once again, I don't understand how/why these parameters are passed when a
button click is activated.

Powerpoint VBA/Python: Applying different Font size to words in TextBox Programatically

Powerpoint VBA/Python: Applying different Font size to words in TextBox
Programatically

Aim: To programatically adjust Font size of group of words in a SINGLE
textbox in powerpoint.
Details:
I have two lists:
Labels = ["Mahon Point Retail","Park","Blackpool Drive","Balance","Finglas
Point"]
FontSize = [10,23,15,20,40]
I would like to apply the font sizes in FontSize to the labels in Labels,
by their indexes.
My script thus far:
#add all items in Labels to a single textbox
for i, label in enumerate(labels):
Shape.TextFrame.TextRange.Text += " " + label
#apply font size from FontSize list to its corresponding label
for x, num in enumerate(FontSize, 1):
Shape.TextFrame.TextRange.Words(x).Font.Size = int(num)
The PROBLEM:
I believe the problem lies with the use of "Words(x)" property, is there
any way I can define what a word is? because right now it thinks "Mahon
Point Retail" is 3 words (which it is) but I would like it to see it as a
single word...
Any advice?

How to get jQuery UI tabs element panels and set visibility on some of them?

How to get jQuery UI tabs element panels and set visibility on some of them?

How to get jQuery UI tabs tab elements panel numbers and set CSS style
visibility on some of them?
I want to get elements' panel numbers for tabs and set visibility on some
of the tabs.
<div id="tabs">
<ul>
<li><a href="#">1</a>
:
<li><a href="#">10</>
</ul>
<div id="tab-contents">
<div id="tab1">some content</div>
:
<div id="tab1">some content</div>
</div>
Get elements panel number by eq() or something, then set style visibility
= hidden; or visible; for some tab(s). I tried the following but it does
not work for jQuery 1.10.2 and jQuery UI 1.10.3.
$(function() {
var panelNumber = $("#tabs").eq();
document.getElementById("div#tabs ul li").visibility = 'hidden';
alert(panelNumber);
)};
I want to set specified tabs visible and rest of them hidden for the page
navigation. Also, I do not want DOM to create or destroy tab on tabs for
navigtion using css visibility is needed for the minimized process time
because it gets slower.

Please answer the question for the jQuery 1.10.2 and jQuery UI 1.10.3
because they deprecated length and many others for jQuery UI 1.9.* update.

Can I create a member variable that is a type parameter of a generic?

Can I create a member variable that is a type parameter of a generic?

I have a lot of proxy classes around services, and all look (almost) the
same. Can I reduce code duplication somehow by using a generics singleton
class, that takes the Service and Port class as type parameters?
This is my completely wrong code with what I want to get started:
public class MyProxy<S extends Service, P extends BindingProvider>
{
private static final MyProxy<S extends Service, P extends
BindingProvider> instance
= new Proxy<S extends Service, P extends BindingProvider>();
private S service;
public static MyProxy<S extends Service, P extends BindingProvider>
getInstance() {
return instance;
}
}
The type parameters for MyProxy I assume to be correct.
Can I declare a static instance singleton member variable, and how?
The member variable service should be more easy, can I have a type
parameter as a member, anyway?
How about the return type of getInstance(), how to I write it?

When does Dropbox request token expire?

When does Dropbox request token expire?

I am creating a request token and the authentication url when pressing one
button,
and then a different button (from another app) is making the
authentication itself
(getting the request token and url as parameters , opens web page(the
url), and obtains access token + secret using the given request token)
But I always get an exception that the session has expired.
It only works when it all happens one directly after the other, but not
when it's split up like that.
Is there a way to modify the expiration time? Or maybe a completely
different way to overcome this issue?
I don't think I can create another request token in the second button in
the other app, because then the url won't match
Maybe holding something like session in web?

Wednesday, September 11, 2013

How to manage App state

How to manage App state

Say I have designed the Page navigation in this manner :
P(1) -> goto P(2) -> goto P(3) and at P(3) , the user click the Home
button (the Microsoft button)
a) How do I get back to p(3) when the App re-launch ?
Thanks

Accessing vm on host machine through ip address

Accessing vm on host machine through ip address

I'm trying to set up a centOS vm with vmware fusion and get access to it
through the host.
I was following a tutorial online for this as this is my first time doing
this. When I try to access the ip of the vm through chrome on the host, I
should be seeing the apache centOS home page, but I get the "oops, chrome
couldn't connect to the ip".
Any help would be appreciated
edit: I am able to ping to the ip and everything is ok, is it a problem
with the hosts file? Sort of confused

Why do I get this error when I add another constructor?

Why do I get this error when I add another constructor?

I will gladly change the title of this thread to something more
appropriate once I know what subject this falls under.
If I change the parameters of the error-causing constructor, there is no
error.
This error only occurs if I include that exact constructor:
error: no matching function for call to 'Object::Object(Object)'
note: candidates are: Object::Object(Object&)
note: Object::Object()
Code:
#include <iostream>
using namespace std;
class Object {
public:
Object() {} /* default constructor - no problems at all */
Object( Object & toCopy ) {} /* Cause of error, but no error when
commented out */
Object func() {
Object obj;
return obj;
}
};
int main() {
Object o = o.func(); /* this is the line that the error is actually on */
return 0;
}

jQuery, make dropdown menu hide when click elsewhere

jQuery, make dropdown menu hide when click elsewhere

I'm using jQuery to make a simple drop down menu:
<script>
$("#optionsLink").click(function(){
$("#optionsMenu").slideToggle();
});
</script>
It works fine but I would like the menu to disappear when the user clicks
elsewhere on the screen. A bit like your standard windows drop down menu.
Clicking on "File" in my browser will display the drop down menu but
clicking somewhere else, anywhere on a page for example, will hide the
menu.
How would I go about implementing something like this?

Directly start youtube video play from mobile website

Directly start youtube video play from mobile website

Right, second question here. Hope someone is able to help me out :)
I have made a mobile website for our company, it's basically a microsite
that has a few pages, leading to 5 different categories that all have 2-7
links to youtube videos, each with an image of the item as sort of a
"cover" - nicely stacked up under each other. The problem is, that with
the links that I have inserted, using a standard , it sends the viewer on
to youtube, and then they have to play the video from there. What I need
help with is to "skip" the step of the users going to Youtube and having
to press play, and enable viewers to press the "cover image" and the video
loads up right there. So when they go back from full screen video, they
will go back to my site, and not to youtube, having to press back once
more.
I doubt the code is necessary, but here is the div that I am using to link
with:
<div class="box1">
<a href="http://youtu.be/k3FL7L9pkr4">
<div class="tekst">
<h4>Brioche Leather Jacket</h4>
<p>See details</p>
</div>
<img src="femme/sunny/2-brioche-jacket.jpg">
</a>
</div>

How to write regex to verify a comma delimited list of values

How to write regex to verify a comma delimited list of values

I am using SobiPro, a directory system for joomla and I have a field that
will have values that contain alphanumerics and hyphens only, so a sample
of what might be in this text field would be:
Toy Kites, Plastic Wheels, 1-Way Gizmos, Metal Spools, 3M Wire Ties
This regex would validate what they enter on the form prior to a field save.
I thought this: (\w+)(,\s*\w+)*
But clearly I am not right, and it does not account for the hyphens.. any
help! thanks!

In Codeigniter fetching symbols from URI intepret differently

In Codeigniter fetching symbols from URI intepret differently

I am fetching '$' symbol from uri. And I have already added $ in
permitted_uri_chars in config file. Later I am fetching data from database
using that uri string. issue can be seen from below example.
MY Url is like this ....
.....com/search/shirt/$
My Example code is this ...
echo $this->uri->segment('3');
echo "<br>";
var_dump($this->uri->segment('3'));
echo "<br>";
$dol_sign = '$';
echo $dol_sign;
echo "<br>";
var_dump($dol_sign);
MY Output of above code is this ...
$
string(5) "$"
$
string(1) "$"
it is taking segment as differently. that is why i m having issue in
fetching data from DB matching with URI segment.

undefined method `symbolize_keys', Image_tag and link_to

undefined method `symbolize_keys', Image_tag and link_to

<%= link_to(image_tag ("Logo.png"), root_url) %>
What am i doing wrong here? I have looked at all the related stackoverflow
questions and docs.

Tuesday, September 10, 2013

unicode normalizing the file input string

unicode normalizing the file input string

I get a list of files from the file input on a page using javascript and
then extract the filename for each file. I need to unicode normalize the
filenames client side using javascript. Is this even possible?

Why does Visual Studio increment the loop pointer before dereferencing it?

Why does Visual Studio increment the loop pointer before dereferencing it?

I checked out Visual Studio 2012's assembly output from the following SIMD
code:
float *end = arr + sz;
float *b = other.arr;
for (float *a = arr; a < end; a += 4, b += 4)
{
__m128 ax = _mm_load_ps(a);
__m128 bx = _mm_load_ps(b);
ax = _mm_add_ps(ax, bx);
_mm_store_ps(a, ax);
}
The loop body is:
$LL11@main:
movaps xmm1, XMMWORD PTR [eax+ecx]
addps xmm1, XMMWORD PTR [ecx]
add ecx, 16 ; 00000010H
movaps XMMWORD PTR [ecx-16], xmm1
cmp ecx, edx
jb SHORT $LL11@main
Why increment ecx, only to subtract 16 when storing it the next line?

Read Integers and count them, then rewind---C

Read Integers and count them, then rewind---C

this is a small piece of my homework that I am having difficulty with.
There is more to the function then this part but this is all that I am
having difficulty with(There is more after). When I run this, it tells me
that it failed to read the integer file. Can anyone tell me where I should
start looking on where I went wrong?
int * readIntegers(const char * filename, int * numberOfIntegers)
{
FILE* fp = fopen(filename, "r");
int count = 0;
int array;
if(fp== NULL)
{
return NULL;
}
while(fscanf(fp, "%d", &count)>0)
{
(*numberOfIntegers)++;
}
printf("%d\n",*numberOfIntegers);
Compiler warnings, I am not concerned about these since they don't have to
do with that I posted
warning: return from incompatible pointer type [enabled by default]
warning: function returns address of local variable [enabled by default]
warning: unused variable 'array' [-Wunused-variable]
And when it runs this is what I get...
./pa03 inputs/input0 > outputs/output0 ./pa03 inputs/input0 >
outputs/output0
Failed to read integer-file 'inputs/input0', aborting
cat outputs/output0
Failed to read integer-file 'inputs/input0', aborting
cat outputs/output0
Also, the print statement towards the end was diagnostic, later in the
function I will return an array that will display the answer. I was trying
to see if the numberOfInputs got updated to the correct number, which has
not happened so far. I will update my print statemnet to see if it
works...will update.
Here is the entire log now.
gcc -g -Wall -Wshadow -c -o obj/answer03.o answer03.c answer03.c: In
function 'readIntegers': answer03.c:85:2: warning: return from
incompatible pointer type [enabled by default] answer03.c:85:2: warning:
function returns address of local variable [enabled by default]
answer03.c:68:6: warning: unused variable 'array' [-Wunused-variable] gcc
-g -Wall -Wshadow -c -o obj/pa03.o pa03.c gcc -g -Wall -Wshadow
obj/answer03.o obj/pa03.o -o pa03
./pa03 inputs/input0 > outputs/output0 * glibc detected * ./pa03:
munmap_chunk(): invalid pointer: 0x00007fff9ffebad0 * ======= Backtrace:
========= /lib/x86_64-linux-gnu/libc.so.6(+0x7eb96)[0x2acd35b25b96]
./pa03[0x400c67]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xed)[0x2acd35ac876d]
./pa03[0x400699] ======= Memory map: ======== 00400000-00402000 r-xp
00000000 08:06 1443970
/home/matt/ECE264/solutions/PA03/pa03 00601000-00602000 r--p 00001000
08:06 1443970
/home/matt/ECE264/solutions/PA03/pa03 00602000-00603000 rw-p 00002000
08:06 1443970
/home/matt/ECE264/solutions/PA03/pa03 0219f000-021c0000 rw-p 00000000
00:00 0 [heap] 2acd35882000-2acd358a4000 r-xp 00000000 08:06 8130309
/lib/x86_64-linux-gnu/ld-2.15.so 2acd358a4000-2acd358a9000 rw-p 00000000
00:00 0 2acd35aa4000-2acd35aa5000 r--p 00022000 08:06 8130309
/lib/x86_64-linux-gnu/ld-2.15.so 2acd35aa5000-2acd35aa7000 rw-p 00023000
08:06 8130309
/lib/x86_64-linux-gnu/ld-2.15.so 2acd35aa7000-2acd35c5c000 r-xp 00000000
08:06 8127294
/lib/x86_64-linux-gnu/libc-2.15.so 2acd35c5c000-2acd35e5b000 ---p 001b5000
08:06 8127294
/lib/x86_64-linux-gnu/libc-2.15.so 2acd35e5b000-2acd35e5f000 r--p 001b4000
08:06 8127294
/lib/x86_64-linux-gnu/libc-2.15.so 2acd35e5f000-2acd35e61000 rw-p 001b8000
08:06 8127294
/lib/x86_64-linux-gnu/libc-2.15.so 2acd35e61000-2acd35e68000 rw-p 00000000
00:00 0 2acd35e68000-2acd35e7d000 r-xp 00000000 08:06 8130119
/lib/x86_64-linux-gnu/libgcc_s.so.1 2acd35e7d000-2acd3607c000 ---p
00015000 08:06 8130119
/lib/x86_64-linux-gnu/libgcc_s.so.1 2acd3607c000-2acd3607d000 r--p
00014000 08:06 8130119
/lib/x86_64-linux-gnu/libgcc_s.so.1 2acd3607d000-2acd3607e000 rw-p
00015000 08:06 8130119
/lib/x86_64-linux-gnu/libgcc_s.so.1 7fff9ffcd000-7fff9ffee000 rw-p
00000000 00:00 0 [stack] 7fff9ffff000-7fffa0000000 r-xp 00000000 00:00 0
[vdso] ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0
[vsyscall] ./bin/test.sh: line 20: 8797 Aborted (core dumped) ./$EXEC $INF
> $OUTF cat outputs/output0
5 Unsorted array: 35254288 0 194 5 -1610695872 Sorted array: 35254289 5
-1610695984 1 -1610695872 -- FAIL (not sorted). Integer '35254288' not
found -- FAIL. Integer '35254289' not found -- FAIL.
Checking expected output: expected/expected0 - FAIL. Expected:
Unsorted array: 4 1 3 2 5 Sorted array: 1 2 3 4 5 -- correct. Integer '4'
in the 3th position in the sorted array -- pass. Integer '5' in the 4th
position in the sorted array -- pass.
make: * [test0] Error 1
Test case: 4 1 3 2 5

Construct nested object graph from SQL hasmany relationship

Construct nested object graph from SQL hasmany relationship

Example: I have some articles and comments and I want to get something
like this:
[{
title: "Article 1",
content: "Super long article goes here",
comments: [
{ author: "Troll", message: "You suck, Sir!" },
{ author: "SpamBot", message: "http://superawesomething.com/"}
]
},{
title: "Article 2",
content: "Another long article goes here",
comments: [ ... ]
}]
Right now I see two solutions:
Get the articles first, then the comments in a second query with some IN
condition and finally add the comments to the respective articles.
Good old joins. For one I will still have to fiddle around with the data a
lot to get into the structure I want. But beyond that I'm a little
concerned since payload like articles.content will be transmitted for
every comment - unless there is a way to do the join I am not aware of.
I'm hoping that my SQL-illiteracy makes me miss the simple solution.