Thursday, 3 October 2013

'xmlrpclib.Fault: Request contains to few param' error when using ldtp

'xmlrpclib.Fault: Request contains to few param' error when using ldtp

I've been trying to use the Windows implementation of LDTP (Cobra) for
testing a stand-alone application within Python. It seems to work fine at
first, albeit running slow most of the time. For example I was able to
select menu items:
selectmenuitem('Sample App','File;New')
However, when I tried to execute any of the following lines:
waittillguiexist('Sample App', 'btnOK')
rightclick('Sample App','tblcBRANCH')
I get the following error in Python:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "build\bdist.win-amd64\egg\ldtp\client.py", line 69, in __call__
File "C:\Python27\lib\xmlrpclib.py", line 1578, in __request
verbose=self.__verbose
File "build\bdist.win-amd64\egg\ldtp\client.py", line 186, in request
xmlrpclib.Fault: <Fault 0: 'Request contains too few param elements based on
method signature.'>
I assume that I may still encounter this error with other functions. Are
there any problems with my installation of LDTP? Any help is very much
appreciated.

Wednesday, 2 October 2013

SVN TO GIT Convert

SVN TO GIT Convert

Just want to how can I convert the below SVN Command into GIT
ssh user@server svn info svn+ssh://svn/TPTDev/MyProject/trunk

Xcode 5 iOS7 Storyboard Examples

Xcode 5 iOS7 Storyboard Examples

I am fairly new to Xcode/iOS.Objective C. Writing a new iPad app and I
want to use Storyboards. For the life of me I cannot find any tutorials or
examples of Storyboards in Xcode 5/iOS7. It seems Storyboards have changed
quite a bit.
Any pointers to where to begin?

How to show money format in C#

How to show money format in C#

Hi I am having a problem in displaying the amount using this kind of
format: 0,000.00 . I am using a grid view and data reader to show the
amount from mySQL Database with Decimal as my datatype, my output only
shows 0000.00
Can you help me how to resolve this problem? Thank You.
private void DisplayOrderDetails(int nOrderNo)
{
OpenConnection();
SqlCommand cmdSelect = new SqlCommand();
cmdSelect.Connection = cn;
cmdSelect.CommandType = CommandType.Text;
cmdSelect.Transaction = trnOrder;
cmdSelect.CommandText =
"SELECT OrderDetailNo, OrderNo, PackagingOutside,
Quantity, Unit, ProductNo, ProductName, " +
"ProductSize, PackagingInside, " +
"SellingDiscount1, SellingDiscount2, SellingDiscount3,
SellingDiscount4, " +
"SellingPrice, Amount FROM OrderDetails WHERE OrderNo = '"
+ nOrderNo + "'";
SqlDataAdapter daDetail = new SqlDataAdapter();
daDetail.SelectCommand = cmdSelect;
DataSet ds = new DataSet();
daDetail.Fill(ds, "OrderDetails");
grdDetails.DataSource = null;
grdDetails.DataSource = ds.Tables["OrderDetails"];
DisplayTotal();
}
private void DisplayTotal()
{
double dTotal = 0;
//for encountering errors in the future
try
{
for (int nRow = 0;
nRow <= dsDetail.Tables["OrderDetails"].Rows.Count - 1;
nRow++)
{
dTotal = dTotal +
Convert.ToDouble(dsDetail.Tables["OrderDetails"].Rows[nRow]["Amount"].ToString());
}
}
catch //(Exception ex)
{
//MessageBox.Show(ex.Message);
}
lblTotal.Text = String.Format("{0:#,###,##0.00}", dTotal);
}

How can I launch an activity from a location on the screen, like on the home screen or in recent apps?

How can I launch an activity from a location on the screen, like on the
home screen or in recent apps?

I want to create a "maximizing" effect from a dialog into my full
activity, so I want the opening animation to show the activity expanding
from a box to full size.
The stock launcher has done this this since Jelly Bean (pressing an app
shortcut will zoom into the application from that icon's location and the
Recent Apps menu has done this since ICS.

Tuesday, 1 October 2013

Extern variable has different values in different C files

Extern variable has different values in different C files

I'm trying to use a shared variable in multi C files. So, I write a
program to use its value:
In the path: sonnh\epan\dissectors\socket_sonnh.h , I defined a extern
variable: extern int ServerSocket;
In the path: sonnh\tshark.c , after #include
<epan/dissectors/socket_sonnh.h> I create the init value ServerSocket =
socket(AF_INET,SOCK_STREAM,IPPROTO_IP);
In the path: sonnh\epan\dissectors\packet-camel.c, after #include
"socket_sonnh.h" I want to use the value of ServerSocket by command i =
send(ServerSocket, cSendBuff, 20, 0);
The flow of code is: after creation of ServerSocket in tshark.c --> (call
func in other file) --> (somewhere I don't know) --> call func in
packet-camel.c to send socket. I know this because i check the log.
But actually, I check the value of ServerSocket at the top and bottom of
tshark.c, it is always 336, but the value of this in packet-camel.c is
always 0. i think it is extern variable , so it keeps its value while
running in different files but in this case, i cannot see the value of
ServerSocket being the same with the value of 336 as seen in tshark.c.
Could you please help me to find out why and how can I solve this problem
to have the value of ServerSocket in packket-camel.c (using shared
variable). Thank you so much.

For a 2nd order linear ODE,find the interval where some non-trivial solutions remain bounded and some become unbounded

For a 2nd order linear ODE,find the interval where some non-trivial
solutions remain bounded and some become unbounded

$$y^{''}+(2\alpha-3)y^{'}+\alpha(\alpha-3)y = 0$$
Determine all values of $\alpha$, if any, for which some non-trivial
solutions remain bounded and some become unbounded as $t \rightarrow
\infty$.
The general solution I got is
$$y(t) = C_1e^{(3-\alpha)t}+C_2e^{-at}$$
And I think the interval is $(-\infty,3]$, but this is not the correct
answer. Can anyone help me?

How to enable log messages during boot process

How to enable log messages during boot process

I'm using Linaro Raring Ubuntu for Cubieboard A20.
How can I enable the log messages in boot process?
I've already read this post:
How to enable boot messages to be printed on screen during boot up?
But I don't have grub, it's a SDCARD boot with a DOS partition and .scr,
.bin files and uDev.txt file.

How to solve this question(set cardinality)?

How to solve this question(set cardinality)?


about the cardinality and power set, how to find the bijection?

Monday, 30 September 2013

Is there a continuous bijection between an interval and a square: $[0=?iso-8859-1?Q?=2C1]_\mapsto_[0=2C1]_\times_[0=2C1]$=3F_=96_math.stackexc?=hange.com

Is there a continuous bijection between an interval and a square: $[0,1]
\mapsto [0,1] \times [0,1]$? – math.stackexchange.com

Is there a continuous bijection from $[0,1]$ onto $[0,1] \times [0,1]$?
That is with $I=[0,1]$ and $S=[0,1] \times [0,1]$, is there a continuous
bijection $$ f: I \to S? $$ I know there is a ...

Transferring data from one table to another, some relational columns

Transferring data from one table to another, some relational columns

Table 1 - this table is completely populated from an XLSX file...

Tables 2 and 3 - contain 1-1 references for a couple of the columns in the
final table.

Table 3 - the on I am trying to get populated with first three tables....

As you can see, the tables are sensible, there is no einsteinic equations
or conversions going on. Here is the code that I have already tried,
unsuccessfully:
INSERT INTO att_oem_orders SELECT NULL, ost.om_or_po, (SELECT j.job_id
FROM jobs j WHERE j.project_number = project_no), NULL, (SELECT ao.id FROM
att_oem WHERE ao.item_no = item_no), ost.po_number, (SELECT ol.id FROM
order_lsc WHERE STATUS = ol.line_status_code), ost.ordered_date,
ost.shipment_date, NULL, NULL, ost.item_qty, NULL, NULL, NULL, NULL,
ost.shipping_to, ost.tracking_number, ost.carrier) FROM oem_temp_sync
WHERE ost.item_qty > 0

How to reload view asynchronously when carrierwave_backgrounder processing completes?

How to reload view asynchronously when carrierwave_backgrounder processing
completes?

I am using the carrierwave_backgrounder gem in a Rails 3.2 app to handle
background processing of image files and transfer to S3 via queue_classic.
The gem sets a file_processing boolean to null when processing is
complete, enabling the following:
#partial
<% if file.file_processing.nil? %>
<%= image_tag file %>
<% else %>
<p>processing</p>
<% end %>
I am using jquery to handle multiple file uploads (jquery-fileupload).
When a file upload completes, it triggers an ajax response via create.js
to render the partial.
This is fine, but means I end up with a long list of 'processing'.
Is there a callback I can take advantage of to reload the partial when
background processing is complete?

How To Use MySql in Html Button with php

How To Use MySql in Html Button with php

PHP
$con=mysqli_connect("localhost","root","","mmogezgini");
$menuler = mysqli_query($con,"SELECT * FROM menuler");
while($menu = mysqli_fetch_array($menuler))
{
echo "<button class=\"ust_link\"
onClick=\"window.location.href='Menu_Url.php'\">Menu_Name</button>";
}
mysqli_close($con);
Mysql codes are ready and mysql connection is successful just i dont know
how to place menu['name'] and menu['url'] instead of Menu_Name and
Menu_Url

Sunday, 29 September 2013

Resharper ToString Format Completion

Resharper ToString Format Completion

In the Reshaper 8.1 the new ToString() Format Completion is great, but for
DateTime all the options seem to be in America culture, eg month/ day
/year, being in Australia this is not very useful is there any way you can
chnage the default completion options so that day/month/year and
day-month-year could be added or replace the current list of formats,
If not how can I turn off only the datetime toString code completion ?

Error in copying of an class object in another window of application

Error in copying of an class object in another window of application

I am stuck. Even don't know what it might be. I trying to use properties
of an object in Main Window on its copy in child window, but this action
gives me an error. Link to download My project
Fragment of code where an error appears: public double this[int index_row,
int index_column] { get { return
double.Parse(data.Rows[index_row][index_column] + ""); } set {
data.Rows[index_row].SetField<double>(index_column, value); } }

how do I set the right side container to scroll in it's own place

how do I set the right side container to scroll in it's own place

So here's the link to my site. I wanted the right container to scroll in
place. How can I do this? I tried adding position: fixed to the right
column but then that destroys the layout. Right now the overflow always
scrolls all the way to the top.. Basically I wanted insta-shop-grid to
scroll inside that container itself.

Autocomplete, problems with source link (MVC, Knockout)

Autocomplete, problems with source link (MVC, Knockout)

I have working autocomplete. My Search Method is situated in
HomeController, but I want to do some changes. I created api controller
named "Vacancy" and transfered Search method there but I can't make it
work: Status Code:404 Not Found (Search method doesn't even start). After
transfering all changes I've made is:
Changed source link in View:
autocomplete="@Url.Action("Search", "Vacancy")"
Changed Search Method:
public object Search(string term)
{
var vacancyHeaders =
new UnitOfWork().Repository<Vacancy>()
.Get()
.Where(v =>
v.Header.ToLower().Contains(term.ToLower()))
.Select(v => new { label = v.Header })
.Distinct()
.Take(10);
return vacancyHeaders;
}
Please, help, why my Search method doesn't start? Below is my working code
without api controller:
View:
<form data-bind="submit: search">
<input data-bind="value: SearchArgument, valueUpdate: 'blur'"
data-autocomplete="@Url.Action("Search", "Home")"
class="form-text" name="search" size="32" maxlength="64"
placeholder="Search"/>
<input type="submit" value="search" />
</form>
Script
$(":input[data-autocomplete]").each(function() {
$(this).autocomplete({ source:
$(this).attr("data-autocomplete")});
});
Search Method
public ActionResult Search(string term)
{
var vacancyHeaders =
new UnitOfWork().Repository<Vacancy>()
.Get()
.Where(v =>
v.Header.ToLower().Contains(term.ToLower()))
.Select(v => new { label = v.Header })
.Distinct()
.Take(10);
return Json(vacancyHeaders, JsonRequestBehavior.AllowGet);
}

Saturday, 28 September 2013

How to add jquery to jasmine/angularjs unittests

How to add jquery to jasmine/angularjs unittests

I have a project which is builded on plain angular.js code. We creates
unittest with jasmine. But now we need to grab some 3rd party components
(some directives from Angular-Bootstrap), which is also pure angular.js
inside, but for testing that components some jQuery code and methods calls
used. And now a lot of 3rd party tests failed with exception like [object]
had no method 'trigger' and stuff like that
So my question is how to include jquery to my tests, to make 3rd party
unitests valid. I run tests with Karma.

Understanding php class structure from a javascript OOP background (how to adapt code workflow)

Understanding php class structure from a javascript OOP background (how to
adapt code workflow)

I have been attempting to write a simple RESTful api in php. Part of my
goal in doing this is to get a good grasp on how to approach php OOP
projects. In javascript, I have no issue with encapsulation, inheritance,
etc. I generally start out with a single object (maybe even just as a
namespace) that I will nest everything in, i.e.var appName = {}. A simpler
object may just be a group of methods...then are a few typical needs like
an init function to set things up and/or execute/run function in which I
can detail a flow. I like to use a few general functions there that
summarize everything that will happen, then detail them, then detail
those, etc, so it is always easy to see how the result is produced, and
you can investigate the details further as needed. I also keep everything
independent so that each function doesn't have to worry about how it gets
its dependencies, etc. So, I hope that gives you an idea of where I'm
coming from.. I am utterly lost in the world of oop php.
I went ahead and wrote a simple api in js just to demonstrate what I'm
trying to do. It could be better, but this is just a quick example.
http://jsbin.com/AmIfApO/3/edit I'll include that code at the end of my
post. I have attempted for weeks to achieve this functionality in php, and
have failed, failed, failed. I can make it work, but it's just awful code
and I am determined to write it using best practices. For the sake of not
appearing lazy, here's the latest php rewrite I tried....ended in disaster
like always http://pastebin.com/cKw9YeVz.
With js, I eventually saw the right example/ got the right advice and the
idea became pretty clear. I think that seeing even just the basic design
flow of how this would be done in php would probably help me tie in
everything I've learned. Something just hasn't clicked. If you can give me
an example of what classes I should have here or how to divide things up,
I would be so appreciative.
var request1 = {
collection: 'articles',
item: null,
verb: 'GET',
format: 'json'
};
var request2 = {
collection: 'articles',
item: null,
verb: 'DELETE',
format: 'json'
};
var api = {
request : (function() {
//parse url into collection, item, format, verb
return request1; //change to request2 for error test
}()),
output : {
data: {},
errors: []
},
respond : function() {
var handler = this.handler(this.request);
this.output.data = this.format(handler());
console.log(this.output);
},
error : function(msg) {
this.output.errors.push(msg);
},
handler : function(request) {
var handler;
if (request.collection) {
if (request.item) {
handler = this.handlers[request.collection].item;
}
else {
handler = this.handlers[request.collection].collection;
}
}
else {
handler = this.handlers.def;
}
return handler[request.verb];
},
format : function(output) {
return output;
},
handlers : {
def: {
collection : {
GET : function() {
return 'generic test data!';
},
POST : function() {
},
PUT : function() {
},
DELETE : function() {
api.error("Collection can't be deleted");
}
},
item : {
GET : function() {
},
POST : function() {
},
PUT : function() {
},
DELETE : function() {
}
}
}
}
};
api.handlers.articles = Object.create(api.handlers.def);
api.handlers.articles.collection.GET = function() {
return 'specific test data!';
};
api.respond();

Different increment on a for loop depending on a boolean

Different increment on a for loop depending on a boolean

How can i select the increment on a for loop depending on a boolean,i am
trying to do something like this:
for (int y = iniY; isdown? (y >= endY): (y <= iniY+dy) ; isdown?
--y:y++);
the for loop accepts the termination but not the increment...
The working code i currently have is something like this:
if(isdown)
for (int y = iniY; y >= endY; --y) {
code lines...
}
else
for (int y = iniY; y <= iniY+dy; ++y) {
code lines...
}
the code can not be extracted to a new method because it works on many
variables...

Cannot call method 'lookup' of undefined when saving model in emberjs

Cannot call method 'lookup' of undefined when saving model in emberjs

im using LSA as my application adapter. im trying to update a model but i
get an error that say
Uncaught TypeError: Cannot call method 'lookup' of undefined
ember-data.js:231
i have a controller and in actions of controller i write these codes :
al:function(id){
console.log(this.store.find('axisModel'));
this.store.find('axisModel',id).then(function(item){
item.set('orderId','1000');
item.save();
//console.log(item);
});
},
i have access to store and store can find a record and when i set orderId
it set on ui but when i try item.save() for saving in localstorage i get
an error.my ember-data verison is v1.0.0-beta.1-39-g80dcf42 and ember
version is v1.0.0 . if i comment item.save() the ui was update but the
model in local storage dosent update and if i uncomment this i get an
error .

Friday, 27 September 2013

Adding to url with link

Adding to url with link

My url contains many variables that I want untouched (don't worry they
aren't important).
Let's say it contained...
../index.php?id=5
How would I make a url that just adds
&current=1
rather than replacing it entirely?
I'd like...
../index.php?id=5&current=1
rather than..
../index.php?current=1
I know it's a simple question but that's why I can't figure it out.
Thanks.

setInterval crashes my browser when running a user script?

setInterval crashes my browser when running a user script?

Okay so the script works but setInterval keeps crashing my browser after
30secs or so. At least I think that's what's happening.
Here's the code:
var count = 0;
setInterval(function()
{
var ifLose = document.getElementById('result-text').innerHTML;
if (ifLose.length > 4)
{
count++;
document.getElementById("bet-multiplier").click();
document.getElementById("bet-bt").click();
}
else
{
for (count > 0; count--;)
{
document.getElementById("bet-divider").click();
}
document.getElementById("bet-bt").click();
}
}, 1000);
What am I doing wrong? Does it have something to do with count and the for
loop? Any help is greatly appreciated!

Force close and not getting the output!! Thank u in advance

Force close and not getting the output!! Thank u in advance

I'm trying to get the contact number(which is selected) by user's
activity.Please solve me regarding this issue.Force close and not getting
the output!! Thank u in advance.. I'm in need of this. have read many
tutorials but was not so helpful to me!!
package com.example.c_p;
import java.util.Iterator;
import java.util.Set;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final int CONTACT_PICKER_RESULT = 1001;
public static final String DEBUG_TAG = null;
EditText emailEntry = (EditText) findViewById(R.id.invite_email);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void doLaunchContactPicker(View view)
{
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
Contacts.CONTENT_URI);
startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT);
}
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data)
{
if (resultCode == RESULT_OK) {
switch (requestCode)
{
case CONTACT_PICKER_RESULT:
Cursor cursor = null;
String phone = "";
try {
Bundle extras = data.getExtras();
Set<String> keys = extras.keySet();
Iterator<String> iterate = keys.iterator();
while (iterate.hasNext()) {
String key = iterate.next();
Log.v(DEBUG_TAG, key + "[" + extras.get(key) + "]");
}
Uri result = data.getData();
Log.v(DEBUG_TAG, "Got a contact result: "
+ result.toString());
// get the contact id from the Uri
String id = result.getLastPathSegment();
cursor = getContentResolver().query(Phone.CONTENT_URI,
null, Phone.CONTACT_ID + "=?", new String[] {
id },
null);
int PhoneIdx = cursor.getColumnIndex(Phone.DATA);
if (cursor.moveToFirst()) {
phone = cursor.getString(PhoneIdx);
Log.v(DEBUG_TAG, "Got number: " + phone);
} else {
Log.w(DEBUG_TAG, "No results");
}
} catch (Exception e) {
Log.e(DEBUG_TAG, "Failed to Number", e);
}
finally {
if (cursor != null) {
cursor.close();
}
emailEntry.setText(phone);
if (phone.length() == 0) {
Toast.makeText(this, "No number found for contact.",
Toast.LENGTH_LONG).show();
}
}
break;
}
} else {
Log.w(DEBUG_TAG, "Warning: activity result not ok");
}
}
}

Strange output for Binary Search when result is not found

Strange output for Binary Search when result is not found

I am getting a strange output when the result is not found.
import java.util.Arrays;
import java.util.Comparator;
public class BinarySearch {
public static void main(String args[]) {
String arr[] = { "c", "a", "e", "f", "z" };
MySort ms = new MySort();
Arrays.sort(arr, ms);
for (String c : arr) {
System.out.println(c);
}
System.out.println(Arrays.binarySearch(arr, "b", ms));
}
static class MySort implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
return o2.compareTo(o1);
}
}
}
Output: z f e c a -6
Why does it print -2 when i pass "y" as my query param and -5 when i pass
b. Can anyone let me know what is happening if the result is not found.

Can't find the right way to get parameter value from the HttpRequest:

Can't find the right way to get parameter value from the HttpRequest:

Can't find the right way to get parameter value from the HttpRequest:
this is my Jquray file:
$(document).ready(function() {
var currBoard;
var currCell;
$(".cell").click(function() {
Cardboard = $ (this). attr ('name');
currCell = $(this).attr('id');
$.get('InGameServlet', function(responseText) {
$("#"+currCell).text(responseText);
alert("cell num:" + currCell + " Board: " + currBoard);
});
});
});
This is my Servlet:
@WebServlet(name = "InGameServlet", urlPatterns = {"/InGameServlet"})
public class InGameServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
printSign(request.getAttribute("currBoard"),
request.getAttribute("currCell"), response);
}
in debug mode i see that the values i get from the request are NULL!
What am i doing wrong?

Create HTML slides with knitr, Rmarkdown and pandoc

Create HTML slides with knitr, Rmarkdown and pandoc

I am trying to create a HTML slides with knitr, Rmarkdown and pandoc. I
got a reference from
http://rprogramming.net/create-a-slideshow-powerpoint-with-r-knitr-pandoc-and-slidy/.
But I meet a problem at the step5. After executing
##
knit("test4.Rmd")
system("pandoc -s -t slidy test4.md -o test4.html")
##
I got a message
pandoc.exe: Could not parse YAML header:
found character that cannot start any token "source" (line 13, column 1)
Please help me to solve this problem.

Thursday, 26 September 2013

Spawning multiple threads that monitor different files in a servlet

Spawning multiple threads that monitor different files in a servlet

I am trying to spawn multiple threads that monitor different log files. So
basically user types in the host and path of log file to tail, then hits
the montior button which will then start a thread and initiate the
tailing. My problem is that I know threads are not supposed to be spawned
in a servlet as it would cause tomcat to complain about resources. The
other thing is I need to be able to stop tailing of the file whenever the
user decides to stop monitoring button. My first approach was to have a
map that takes in the thread and starts tailing of file, then whenever I
hit stop monitoring file then I get thread by key then call a method
stopThread which I flag a volatile attribute in and set it to false then
it stops. Is there a way which I can do it maybe using ExecutorService and
make the thread run without halting the program as I understand that
Callable will wait for results to return which in my case I don't want
halting. Any shed of ligh is highly appreciated. Thank you in advance.

Thursday, 19 September 2013

How to make a PPTP VPN in any languag

How to make a PPTP VPN in any languag

Well I am on a student account in school and I want to make my own PPTP
program that would connect to any PPTP connect. I do have my own VPS to
establish the connection. Is there anyway I can make this program? Java is
preferred as I'm learning it now

Jquery type error on cannot read property 'length' of undefined

Jquery type error on cannot read property 'length' of undefined

I am working on to change drop down menu on selection. For that I am using
jquery, ajax with json.
function ChooseGroupScript() {
$.getJSON('edit_scripts.php',
{group:$('#group').val()}, function(data) {
var select = $('#subject');
var options = select.attr('options');
$('option', select).remove();
$.each(data, function(index, array) {
options[options.length] = new
Option(array['subject']);
});
});
}
$(document).ready(function() {
ChooseGroupScript();
$('#group').change(function() {
ChooseGroupScript();
});
});
I checked in console: i am getting error like this:
Jquery type error on cannot read property 'length' of undefined
this is my PHP:
if(isset($_GET['group'])){
$currentscript = $clients->curr_group_content($_GET['group']);
$scriptscount = sizeof($currentscript);
for($i=0;$i<$scriptscount;$i++){
$subject = $currentscript[$i]['subject'];
}
}
echo json_encode($subject);

Absolutely positioned element margins move other elements

Absolutely positioned element margins move other elements

I need to animate the margin of form inputs without affecting any other
element's positions. So I gave all the inputs position: absolute for all
of the inputs in the form.
However, this has created a problem for me: all of the inputs stick close
together and if add a margin-top: 40px to them it affects all of the
inputs as one element rather than spacing them out individualy.


How do I space out all the input elements individually?

Setting text of text area in javascript

Setting text of text area in javascript

Why won't this work to set text of text area?
document.getElementById("code").value = "hey farmer";
I even tried: document.getElementById('code').value = "hey farmer";
Is there a way to use getElementByName to set value?
Any help is appreciated

Spring post - multirow table

Spring post - multirow table

Hi im trying to recieve a table of inputs VIA POST method in my
controller, but i dont know why it returns me just the object alone or
null
Here is my implementation:
JSP:
<c:if test="${not empty configs}">
<form:form method="POST" id="propertiesForm" action="/configuracion"
modelAttribute="configs">
<table class="tablaListado" cellspacing="0">
<c:forEach var="o" items="${configs}" varStatus="status">
<tr class="renglonListado">
<td style="visibility: hidden;"
align="center">${status.count}</td>
<td class="colListado">${o.key}</td>
<td class="colListado">
<input type="text" class="valor"
name="configs[${status.index}].value" value="${o.value}"
onchange="marcarCambio(this.parentNode.parentNode);"/>
</td>
<td class="colListado"></td>
</tr>
</c:forEach>
</table>
</form:form>
</c:if>
CTRL:
@RequestMapping(value = "/configuracion", method= RequestMethod.POST)
public String login(HttpServletRequest request,
@ModelAttribute("configs") Object lista, ModelMap map) {
@SuppressWarnings("unchecked")
List<SystemConfiguration> list = (List<SystemConfiguration>) lista;
list.size();
return "configuracion";
}
Notice SystemConfiguration is my DTO class and im rendering a list ot
SystemConfiguration in my view passing it to the model in my GET method by
doing: model.addAttribute("configs", lista);
Where lista is: List lista = getConfigurations();

Python xml.dom.minidom schema validation

Python xml.dom.minidom schema validation

Is there any pure python way to validate xml files with xsd. My python
version is 2.x and the code is already using xml.dom.minidom for xml
parsing, so I cannot use element tree and lxml

Java Arrays: Find Two Points In A Three-Dimensional Space Nearest To Each Other

Java Arrays: Find Two Points In A Three-Dimensional Space Nearest To Each
Other

As the title suggests, I'm working on a homework assignment where we are
limited to using multi-dimensional arrays in order to create a program
that finds two points nearest to each other in a three dimensional space.
So far my code looks like this (hybridized from examples in my textbook
and my own code):
package exercise7_7;
public class Exercise7_7 {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.println("Enter the number of points:");
int numberOfPoints = input.nextInt();
double[][] points = new double[numberOfPoints][3];
System.out.println("Enter " + numberOfPoints + " points:");
for (int i = 0; i < points.length; i++) {
points[i][0] = input.nextDouble();
points[i][1] = input.nextDouble();
points[i][2] = input.nextDouble();
}
int p1 = 0, p2 = 1, p3 = 2;
double shortestDistance = distance(points[p1][0] , points[p1][1] ,
points[p1][2] ,
points[p2][0] , points[p2][1] , points[p2][2] ,
points[p3][0] , points[p3][1] , points[p3][2]);
for (int i = 0; i < points.length; i++) {
for (int j = i + 1; j < points.length; j++) {
double distance = distance(points[i][0] , [points[j][0] ,
points[j][1] , points[j][2]);
if (shortestDistance > distance) {
p1 = i;
p2 = j;
shortestDistance = distance;
}
}
}
System.out.println("The closest two points are " + "(" + points[p1][0]
+ "," + points[p1][1] +
and (" + points[p2][0] + "," );
}
public static double distance(
double x1, double y1, double z1, double x2, double y2, double z2) {
return Math.sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1)) +
((z2 - z1) * (z2 - z1)));
}
}
Thanks for the help guys. I'm running on 2 hours of sleep for 2 days now
so please excuse any stupid questions or sloppy code.

About Plack::Middleware::Session, Do we really need to store the sessions?

About Plack::Middleware::Session, Do we really need to store the sessions?

In the builder part of a psgi app, I use the following code which I
remember seeing somewhere.
enable 'Plack::Middleware::Session',
store => Plack::Session::Store::DBI->new(
get_dbh => #....
),
state => Plack::Session::State::Cookie->new(
session_key => 'id_session',
httponly => 1,
);
1) Why do people store the sessions? And store the sessions in the server
side? 2) What happens if no sessions are stored?
I have a psgi running, where I used 'Plack::Middleware::Session' without
knowing its real purpose and now my sessions table is approaching 500
megas, so I really want to erase this if there is no need.

Wednesday, 18 September 2013

NSDictionary - (for id foo in dict) vs (for NSString *foo in [dict allKeys])

NSDictionary - (for id foo in dict) vs (for NSString *foo in [dict allKeys])

Suppose there is an NSDictionary *dict. What is the difference between the
following?
for (id key in dict) {
NSLog(@"value: %@", dict[key]);
}
for (NSString *key in [dict allKeys]) {
NSLog(@"value: %@", dict[key]);
}
I didn't know that the first version existed, and when I saw it I thought
it would be a compile-time error.

Invalid route name: 'users/:columnname_index' - Can't rollback, change column name, nor display some pages

Invalid route name: 'users/:columnname_index' - Can't rollback, change
column name, nor display some pages

I created a migration to add a Urlname column to Users table. Then I added
an index to the migration. Here's the resulting migration:
class AddUrlnameToUsers < ActiveRecord::Migration
def change
add_column :users, :urlname, :string
add_index :users, :urlname, :unique => true
end
end
Then I used rake db:migrate.
schema.rb contains the 'urlname' column & says it has a unique index.
However, certain pages on my site have errors: Invalid route name:
'users/:urlname_index'.
Fine, I don't want to call it 'urlname' anyway. I want to call it
'permalink'. But now I can't generate a FixColumnName migration, a
RemoveUrlNameFromUsers, nor can I rollback - same "Invalid route name:
'users/:urlname_index'" error for all three.
So I removed add_index :users, :urlname, :unique => true from the
migration file, even though I had already migrated it. That didn't help.
My routes.rb contains
Crowdpublishtv::Application.routes.draw do
devise_for :users
resources :users
#resources 'users/:urlname', :to => 'User#booklist'
#match 'users/:urlname_index', :to => 'users#show'
devise_for :users
authenticated :user do
root :to => "users#booklist"
end
get "attachments/show"
resources :users do
resources :books
end
devise_for :users
resources :users do
member do
get 'booklist', 'blog', 'profileinfo', 'readerprofileinfo',
'orgprofileinfo'
end
end
end
I tried commenting out & uncommenting out the lines that are marked with
#. Didn't help.
Here's the relevant db:migrate status:
Status Migration ID Migration Name
--------------------------------------------------
up 20130319002105 Create users
up 20130328235904 ********** NO FILE **********
up 20130703205730 Add devise to users
up 20130911002912 Add bookfiles to users
up 20130917143106 Add urlname to users
The *NO FILE* was something I thought I had rolled back... But since it
was long before 'Add urlname to users,' I'm pretty sure it's irrelevant.
Any insight as to what is incorrect? I'm on rails 3.1.0, ruby 1.9.2, with
sqlite3, if that matters.

Parsing complex URLs

Parsing complex URLs

I try to parse a list of url strings, after two hours of work I don't
reach any result, the list of url strings look like this:
$url_list = array(
'http://google.com',
'http://localhost:8080/test/project/',
'http://mail.yahoo.com',
'http://www.bing.com',
'http://www.phpromania.net/forum/viewtopic.php?f=24&t=7549',
'https://prodgame10.alliances.commandandconquer.com/12/index.aspx',
'https://prodgame10.alliances.commandandconquer.ro/12/index.aspx',
);
Output should be:
Array
(
[0] => .google.com
[1] => .localhost
[2] => .yahoo.com
[3] => .bing.com
[4] => .phpromania.net
[5] => .commandandconquer.com
)
The first thing what induce me in the error zone is more than 2 dots in
the url. Any algorithm example?



This is what I try:
$url_list = array(
'http://google.com',
'http://localhost:8080/test/project/',
'http://mail.yahoo.com',
'http://www.bing.com',
'http://www.phpromania.net/forum/viewtopic.php?f=24&t=27549',
'https://prodgame10.alliances.commandandconquer.com/12/index.aspx',
);
function size($list)
{
$i=0;
while($list[++$i]!=NULL);
return $i;
}
function url_Host($list)
{
$listSize = size($list)-1;
do
{
$strSize = size($list[$listSize]);
$points = 0;
$dpoints = 0;
$tmpString = '';
do
{
$currentChar = $list[$listSize][$strSize];
if(ord('.')==ord($currentChar))
{
$tmpString .= '.';
$points++;
}
else if(ord(':')==ord($currentChar))
{
$tmpString .= ':';
$dpoints++;
}
}while($list[$listSize][--$strSize]!=NULL);
print $tmpString;
$strSize = size($list[$listSize]);
$tmpString = '';
do
{
$slice = false;
$currentChar = $list[$listSize][$strSize];
if($dpoints > 2)
{
if(ord('\\')==ord($curentChar)) $slice = true;
$tmpString .= '';
}
}while($list[$listSize][--$strSize]!=NULL);
print $tmpString."<br />";
}while($list[--$listSize]);
}
url_Host($url_list);

FFMPEG : add marquee like text overlay

FFMPEG : add marquee like text overlay

I want to grab a video from v4l2 device, add overlay of moving text and
stream it to vlc, how can i do this ? Is there any way to add dynamic
overlay using ffmpeg.

Binding dropdown values using knockout js

Binding dropdown values using knockout js

I have the below JS:
function RowData(Township, Range, Section,Crop, Acres) {
var self = this;
self.Township = Township;
self.Range = Range;
self.Section = Section;
self.Crop = [{ value: "1", crop: "Irrigated Corn" }, { value: "2", crop:
"Irrigated Sugar Beets" }, { value: "3", crop: "Irrigated Soybeans" }, {
value: "4", crop: "Irrigated Sorghum (Milo, Sudan)" }, { value: "5", crop:
"Irrigated Dry Edible Beans" }, { value: "6", crop: "Irrigated Potatoes"
}, { value: "7", crop: "Irrigated Alfalfa" }, { value: "8", crop:
"Irrigated Small Grains" }, { value: "9", crop: "Range/Pasture/Grass
(Brome, Hay, CRP)" }, { value: "10", crop: "Urban Land" }, { value: "11",
crop: "Open Water" }, { value: "12", crop: "Riparian Forest and Woodlands"
}, { value: "13", crop: "Wetlands" }, { value: "14", crop: "Other
Agricultural Lands (Farmsteads, Feedlots, etc.)" }, { value: "15", crop:
"Irrigated Sunflower" }, { value: "16", crop: "Summer Fallow" }, { value:
"17", crop: "Roads" }, { value: "18", crop: "Dryland Corn" }, { value:
"19", crop: "Dryland Soybeans" }, { value: "20", crop: "Dryland Sorghum"
}, { value: "21", crop: "Dryland Dry Edible Beans" }, { value: "22", crop:
"Dryland Alfalfa" }, { value: "23", crop: "Dryland Small Grains" }, {
value: "24", crop: "Dryland Sunflower" }, { value: "25", crop: "Dryland
Sugar Beets" }, { value: "26", crop: "Dryland Potatoes" }, { value: "27",
crop: "Irrigated Hay" }, { value: "28", crop: "Irrigated Rotation Pasture"
}];
self.Acres = Acres;
}
function PBHEPViewModel() {
var self = this;
//Present Conditions
self.present_conditions = ko.observableArray([
new RowData()
]);
self.present_AddRow = function () {
self.present_conditions.push(new RowData())
}
self.present_RemoveRow = function (row) {
self.present_conditions.remove(row) };
//Future Conditions
self.future_conditions = ko.observableArray([
new RowData()
]);
self.future_AddRow = function () {
self.future_conditions.push(new RowData())
}
self.future_RemoveRow = function (row) {
self.future_conditions.remove(row) };
//submit the data
self.submit_conditions = function () {
var PC_data = ko.toJSON(self.present_conditions());
var FC_data = ko.toJSON(self.future_conditions());
$.post("/Home/PBHEP", { "PC": PC_data, "FC": FC_data});
}
}
ko.applyBindings(new PBHEPViewModel());
And my HTML is:
<tbody data-bind="foreach:future_conditions">
<tr>
<td style =" text-align:center">
<input class="input-small" type="text"
placeholder="Township" data-bind="value: Township"></td>
<td style =" text-align:center">
<input class="input-small" type="text"
placeholder="Range"data-bind="value: Range"></td>
<td style =" text-align:center">
<input class="input-small" type="text"
placeholder="Section"data-bind="value: Section"></td>
<td style =" text-align:center">
<select name="" data-bind="options: Crop, optionsValue:
'value', optionsText: function (i) { return i.crop },
optionsCaption: 'Choose a Crop...'"></select>
</td>
<td style =" text-align:center">
<input class="input-small" type="text"
placeholder="Acres"data-bind="value: Acres"></td>
<td>
<button class="btn btn-small btn btn-danger" type="button"
data-bind="click: $root.future_RemoveRow"><i
class="icon-minus-sign icon-white"></i></button>
</td>
</tr>
</tbody>
When I do the post I have all the entire array in the crop field where i
only want to post the value that has been selected.
How do I achieve this where am I going wrong. Thank you in advance

Sbt compile error with poi-ooxml-schemas-3.9.jar using Scala

Sbt compile error with poi-ooxml-schemas-3.9.jar using Scala

I'm trying to compile my project with SBT, but I get this error and can
not figure out why:
YoBre$ sbt compile
[info] Loading project definition from
/opt/virtualenvs/venv1/scala/name/project
[info] Set current project to name (in build
file:/opt/virtualenvs/venv1/scala/name/)
[info] Compiling 4 Scala sources and 5 Java sources to
/opt/virtualenvs/venv1/scala/name/target/scala-2.10/classes...
[error] error while loading CTP, class file
'/opt/virtualenvs/venv1/scala/name/lib_managed/jars/org.apache.poi/poi-ooxml-schemas/poi-ooxml-schemas-3.9.jar(org/openxmlformats/schemas/wordprocessingml/x2006/main/CTP.class)'
is broken
[error] (class java.lang.NullPointerException/null)
[error] error while loading CTTbl, class file
'/opt/virtualenvs/venv1/scala/name/lib_managed/jars/org.apache.poi/poi-ooxml-schemas/poi-ooxml-schemas-3.9.jar(org/openxmlformats/schemas/wordprocessingml/x2006/main/CTTbl.class)'
is broken
[error] (class java.lang.NullPointerException/null)
[error] error while loading CTTc, class file
'/opt/virtualenvs/venv1/scala/name/lib_managed/jars/org.apache.poi/poi-ooxml-schemas/poi-ooxml-schemas-3.9.jar(org/openxmlformats/schemas/wordprocessingml/x2006/main/CTTc.class)'
is broken
[error] (class java.lang.NullPointerException/null)
[error] three errors found
[error] (compile:compile) Compilation failed
[error] Total time: 6 s, completed 18-set-2013 12.31.36
This project contains code Java and Scala. The error occurred when I
translated into Scala a feature related to the splitting of the word
documents that was previously written in java. The error is in fact tied
to a jar file library org.apache.poi.
I tried to document but I have not found similar cases.
Any idea?
thanks

Program to print open and close brackets [on hold]

Program to print open and close brackets [on hold]

if n=1 output {}
if n=2 print {}{},{{}}
if n=3 print {}{}{},{}{{}},{{}}{},{{}{}}{{{}}}
using any coding language.
I need a program to print the open and close bracket based on the given
input n. n is an integer. open bracket should not come after close
bracket.

Items are not populated in the list view

Items are not populated in the list view

<ListView
android:id="@+id/titleListView"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</ListView>
String[] monthsArray = { "JAN", "FEB", "MAR", "APR", "MAY", "JUNE", "JULY",
"AUG", "SEPT", "OCT", "NOV", "DEC" };
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, monthsArray);
titleListView.setAdapter(adapter);
This is my array Array adapter code...
And the above one is the layout code for list view.
I have one array of string called "Months array" and i need to show this
as a list view.

Tuesday, 17 September 2013

HDFS FileSplit locations

HDFS FileSplit locations

I have a cluster with an installation of hadoop-2.1.0-beta. Is there a way
to learn where each filesplit is located in my cluster? What I am looking
for is a list such as the following
filesplit_0001 node1
filesplit_0002 node4
...
edit: I know that such a list is available in Microsoft Azure.

how to build a 64 bit project in visual studio

how to build a 64 bit project in visual studio

In my visual studio 2010 ultimate, codes in #if _WIN64 region is always
dark. I selected X64 platform in my configuration manager. What do I do to
compile a 64 bit project?

how to read interleaved data with memmapfile()?

how to read interleaved data with memmapfile()?

I have a large (4GB+) data file I'd like to access. It contains samples i
of a number of different signals {a, b, c} as follows:
a_1 b_1 c_1 a_2 b_2 c_2 .... a_n b_n c_n
I would like to use memmapfile to retrieve, say, the a stream. Since I
know the number of signals and the number of samples, I tried:
m = memmapfile('data.dat','Format',{'int16',[nSignals
1],'sid'},'repeat',nSamples);
but this returns the useless m field
Data: nSamples x 1 struct array with fields:
sid
Of course the following works fine, but is very slow:
m = memmapfile('data.dat','Format','int16');
a = m.Data(1:nSignals:end);
How can I recover a without having to access the full data matrix?

XslCompiledTransform - Compile Error When Transforming XML Using XSLT Stylesheet

XslCompiledTransform - Compile Error When Transforming XML Using XSLT
Stylesheet

I am trying to take a sheet in Excel and create an XML document using VBA
then transform that document using a XSLT stylesheet.
I have included the code below up to the point that I am having problems.
When I try to create an object like so:
Dim transformer As XslCompiledTransform ' transform document
I get this error:
Compile Error: User defined type - not defined
I was previously experiencing this error when defining
Dim objDom As DOMDocument
but referencing this question solved that problem for me. However, I
cannot find anything similar for this case.
Can someone explain to me if there is a reference that I need to include
and how to find these in the future?
Note: I am using the Visual Basic Editor in Excel 2003 to create this VBA
macro
Sub CreateXML()
'Variable to hold all rows in excel file
Dim rows As Variant
'Variables used to iterate through row array
Dim i As Integer
Dim j As Integer
'Create objects for manipulating XML
Dim objDom As DOMDocument
Dim objXMLRootelement As IXMLDOMElement
Dim objXMLelement As IXMLDOMElement
Dim objXMLattr As IXMLDOMAttribute
'Represents the top level of the XML source
Set objDom = New DOMDocument
'~~> Creates root element
Set objXMLRootelement = objDom.createElement("Project")
objDom.appendChild objXMLRootelement
'~~> Saves XML data to a file
objDom.Save ("C:\Users\JSLAMKIN\Desktop\test.xml")
'Create an instance of the DOMDocument class:
Dim xDoc As DOMDocument
Set xDoc = New DOMDocument
'Create the file as output
Dim output As DOMDocument
Dim transformer As XslCompiledTransform ' transform document
...

Python Requests: follow a link

Python Requests: follow a link

Suppose I have the following script:
import requests
username = 'myUser'
password = 'myPswd'
url = 'https://NTLMwebsite/base.com'
nextPage = 'https://NTLMwebsite/base/next.com'
r = requests.get(url, auth=HttpNtlmAuth(username,password))
#Cool, but how do I access nextPage?
How do I request another page once I've passed NTLM? authentication. If I
simply do another request via: requests.get(nextPage,
auth=HttpNtlmAuth(username,password)), then it redirects me back to the
base website since it creates a NEW request and has to re-certify NTLM
authentication.
Does anyone know how to follow a link ONCE you've bypassed NTLM?

how to make condition ignore capslock?

how to make condition ignore capslock?

how to make condition ignore capslock? i want to chang the:
if ( Name.contains ( layout.txtName.getText ().toString () ) )
and make it ignore the caps...
case R.id.Contane:
if (Name.contains(layout.txtName.getText().toString()))
{
AlertDialog.Builder alert = new
AlertDialog.Builder(MainActivity.this);
alert.setTitle("this is the first resulet for the name
that you typed");
alert.setMessage("The contact "+Name+" was found in this
phone... fuck ya");
alert.setPositiveButton("ok",new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface,
int i)
{
}
});
alert.show();
Found = true;
break;

Sunday, 15 September 2013

php form, send email with an attachment

php form, send email with an attachment

I need some help with this form please. i've already created a form and
everything is working, but when I submit the email is recived perfectly
and i don't have any problems with it. my only problem is that i need to
add an upload field and when the user submit they receive it as an
attachment, i've looked at many examples but i couldnt make it work, i
really need this to work as soon as possible, if anyone has any ideas of
how it could make it work it would be so great. also i've always came to
this website to look for solutions and its very great and this is my first
question here, i hope i could find the answer and if anyone else is
looking for the same thing then they can be helped as well thank you
this is the form
<form name="contactform" method="post" action="form.php">
<table width="450px">
<tr>
<td><label for="first_name">Title *</label></td>
<td><input type="text" name="first_name" maxlength="4" size="4"></td>
</tr>
<tr>
<td><label for="last_name">last Name *</label></td>
<td><input type="text" name="last_name" maxlength="50" size="30"></td>
</tr>
<tr>
<td><label for="email">Email Address *</label></td>
<td><input type="text" name="email" maxlength="80" size="30"></td>
</tr>
<tr>
<td><label for="telephone">Telephone Number *</label></td>
<td><input type="text" name="telephone" maxlength="30" size="30"></td>
</tr>
<tr>
<td><label for="what_trade">What trade *</label></td>
<td><input type="text" name="what_trade" maxlength="50" size="30"></td>
</tr>
<tr>
<td><label for="cscs">CSCS Card Number *</label></td>
<td><input type="text" name="cscs" maxlength="50" size="30"></td>
</tr>
<tr>
<td><label for="file">CV upload*</label></td>
<td><input type="file" name="attachment"></td>
</tr>
<tr>
<td><center><input type="submit" value="Submit"></center></td>
</tr>
</table>
</form>
and this is the php code... the only thing am missing in here is the
attachment code, please thats the only part i need, if you could only help
me with that part it would be really great
<?php
if(isset($_POST['email'])) {
$email_to = "someemail@website.com";
$email_subject = "Operative form";
function died($error) {
echo "These errors appear below.<br /><br />";
echo $error."<br /><br />";
echo "Please go back and fix these errors.<br /><br />";
die();
}
if(!isset($_POST['first_name']) ||
!isset($_POST['last_name']) ||
!isset($_POST['email']) ||
!isset($_POST['telephone']) ||
!isset($_POST['what_trade']) ||
!isset($_POST['cscs'])) {
died('We are sorry, but there appears to be a problem with the form
you submitted.');
}
$first_name = $_POST['first_name']; // required
$last_name = $_POST['last_name']; // required
$email_from = $_POST['email']; // required
$telephone = $_POST['telephone']; // not required
$what_trade = $_POST['what_trade']; // required
$cscs = $_POST['cscs']; // required
$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email_from)) {
$error_message .= 'The Email Address you entered does not appear to be
valid.<br />';
}
$string_exp = "/^[A-Za-z .'-]+$/";
if(!preg_match($string_exp,$first_name)) {
$error_message .= 'The First Name you entered does not appear to be
valid.<br />';
}
if(!preg_match($string_exp,$last_name)) {
$error_message .= 'The Last Name you entered does not appear to be
valid.<br />';
}
if(strlen($error_message) > 0) {
died($error_message);
}
$email_message = "Form details below.\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "First Name: ".clean_string($first_name)."\n";
$email_message .= "Last Name: ".clean_string($last_name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Telephone: ".clean_string($telephone)."\n";
$email_message .= "Trade: ".clean_string($what_trade)."\n";
$email_message .= "CSCS Card Number: ".clean_string($cscs)."\n";
"some code for the sending the file upload as an attachment"
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);
?>
<!-- include your own success html here -->
<?php
}
?>

Best ways of stopping sql injections? [duplicate]

Best ways of stopping sql injections? [duplicate]

This question already has an answer here:
How can I prevent SQL injection in PHP? 26 answers
Thanks to everyone for your help in advance. I am trying to learn mysql, I
was going to set up a database to practice with but I was on here reading
and looking for examples, and kept seeing people saying they where going
to get a sql injection. I have been reading about this for a while now,
and I'm getting more confused the more I read. I have decided to go with
PDO to prevent this. Even though from what I read it's the prepared
statements that makes it safe, and I will still have to whitelist it. My
question is if someone can give beginners like myself a set up we can use
that will be pretty effective at stopping these attacks. From what I
understand it seems almost imposable to stop them, I seen someone say
something about the dns is the only sure way. I would like to learn do
this the right way even though, I probably don't need to so much security
right now. If I'm not wrong they can still use blind injections even if
you use PDO, if so i was think of adding a delay of 2-5 seconds or
something like that. Idk if that would be to much on the user end, I'm
just learning, and have no real world experience. Also the type of things
I will be doing, will probably be very basic for now... mom a pop type
stuff. If I build someone a site with a user name and pass I don't want
them to get these attacks, I just don't like it. So if it is a little slow
but more secure I would like to be at least able to give them that option.
My thinking is to be really annoying to them and hopefully not be worth
it. From what I read also the length of the table names or user names can
make it harder for them, say using phrases instead of just 6-8 letters.
Also I think least privilege will help as well, but there seems there is
always a way around everything, and if your new and don't know exactly
what your doing, your going to vulnerable. I have copyied code from
somewhere that I was going to fit it for my needs, but I really have not
tried to put together what I'm looking for yet, still in the reading and
learning phase.
<?php
require_once "dBug!.php";
$dsn = "mysql:host=";
$user_name = "";
$pass_word = "";
$connect = new PDO($dsn, $user_name, $pass_word);
$sql = "SELECT * FROM books WHERE id <= 10";
$result = $connect->prepare($sql);
$status = $result->execute();
if (($status) && ($result->rowCount() > 0))
{
$results = array();
while ($row = $result->fetch(PDO::FETCH_ASSOC))
{
$results[] = $row;
}
new dBug($results);
}
$connect = null;
?>

Better way to test .animate with qUnit

Better way to test .animate with qUnit

Getting to know TDD i wrote a simple test suit for moving dom elements to
the left.
I testing animations I need to wait for them to finish. I didn't want to
use promises since it feels like monkey patching and I ended up using
qUnit example form:
test("move 50", function () {
//Creates an element for testing and attaches to document
var el = appendToTest();
ok(el.css('left') == "auto", "element 0");
stop();
moveLeft(el, 50, 100);
setTimeout(function () {
equal(el.css("left"), "50px");
start();
}, 101);//Timeout duration
});
full fiddle
The test fails on all jQuery versions but 2.x (edge)
failed
Expected:
"50px"
Result:
"49.69220733642578px"
Diff:
"50px" "49.69220733642578px"
Incrementing the timeout duration enough makes the test pass so I figured
the animation didn't finish before being probed for the left property.
But this doesn't seem right. Having to guess how long to wait. Is there a
better way to do this?

Get model from partial view to controller

Get model from partial view to controller

Is it possible to pass model to controller with @Html.Partial?
Using plain <td> in view return list of rows, while this exact same <td>
wrapped in partial returns null on form submit
@using ( Html.BeginForm() )
{
<table>
<tr>
<th></th>
</tr>
<tr>
@for ( int i = 0; i < Model.Rows.Count; i++ )
{
@*<td class="row">Book @Html.DisplayFor(x =>
Model.Rows[i].RowNum) @Html.DropDownListFor(x =>
Model.Rows[i].Selected, Model.Rows[i].Data)
</td>*@
@Html.Partial("Row", Model.Rows[i])
}
</tr>
</table>
<input type="submit" value="Submit" />
}

std::make_pair with float array (float2, unsigned int)

std::make_pair with float array (float2, unsigned int)

I have a vector containing templated with a float2, unsigned int pair like:
std::vector<std::pair<float2, unsigned int>> myVec;
And then I'm trying to add such a pair to the vector:
unsigned int j = 0;
float2 ab = {1.0, 2.0};
myVec.push_back(std::make_pair(ab, j));
This is how I expect it should work, though when I try to compile it I get
the error:
1>C:\Program Files (x86)\Microsoft Visual Studio
10.0\VC\include\utility(163): error C2536:
'std::_Pair_base<_Ty1,_Ty2>::std::_Pair_base<_Ty1,_Ty2>::first' : cannot
specify explicit initializer for arrays
1> with
1> [
1> _Ty1=float2 ,
1> _Ty2=unsigned int
1> ]
1> C:\Program Files (x86)\Microsoft Visual Studio
10.0\VC\include\utility(166) : see declaration of
'std::_Pair_base<_Ty1,_Ty2>::first'
1> with
1> [
1> _Ty1=float2 ,
1> _Ty2=unsigned int
1> ]
1> C:\Program Files (x86)\Microsoft Visual Studio
10.0\VC\include\utility(247) : see reference to function template
instantiation 'std::_Pair_base<_Ty1,_Ty2>::_Pair_base<float(&)[2],unsigned
int&>(_Other1,_Other2)' being compiled
1> with
1> [
1> _Ty1=float2 ,
1> _Ty2=unsigned int,
1> _Other1=float (&)[2],
1> _Other2=unsigned int &
1> ]
1> myTest.cpp(257) : see reference to function template
instantiation 'std::pair<_Ty1,_Ty2>::pair<float2(&),unsigned
int&>(_Other1,_Other2)' being compiled
1> with
1> [
1> _Ty1=float2,
1> _Ty2=unsigned int,
1> _Other1=float2 (&),
1> _Other2=unsigned int &
1> ]**strong text**
What is the correct way to add this data type to my pair holding vector?
The float2 type is defined as:
typedef float float2[2];

UISlider change value smoothly

UISlider change value smoothly

I have a UIslider setting the position for a AVAdioRecording:
CGRect frame = CGRectMake(50.0, 230.0, 200.0, 10.0);
aSlider = [[UISlider alloc] initWithFrame:frame];
// Set a timer which keep getting the current music
time and update the UISlider in 1 sec interval
sliderTimer = [NSTimer
scheduledTimerWithTimeInterval:0.4 target:self
selector:@selector(updateSlider) userInfo:nil
repeats:YES];
// Set the maximum value of the UISlider
aSlider.maximumValue = player.duration;
// Set the valueChanged target
[aSlider addTarget:self
action:@selector(sliderChanged:)
forControlEvents:UIControlEventValueChanged];
[self.ViewA addSubview:aSlider];
- (void)updateSlider {
// Update the slider about the music time
[UIView beginAnimations:@"returnSliderToInitialValue" context:NULL];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
[UIView setAnimationDuration:1.3];
aSlider.value = player.currentTime;
[UIView commitAnimations];
}
- (IBAction)sliderChanged:(UISlider *)sender {
// Fast skip the music when user scroll the UISlider
[player stop];
[player setCurrentTime:aSlider.value];
[player prepareToPlay];
[player play];
}
There are three questions i would like to ask.
1) Why does the animation for the value change not work? 2) Why does the
slider position move only when I release my finger from the button and
does not follow it? 3) Is using an NSTimer the best way to do it? I have
heard that NSTimer is a lot memory consuming...

OleDbException was unhandled by user code - Unspecified error

OleDbException was unhandled by user code - Unspecified error

The following error keeps popping up randomly when my program is running.
Quite new to this so i'm not sure how to go about catching this... Did a
quick search alrd but nothing seems to help.
The following is part of my code:
protected DBBase(string tableName, string primary_key)
{
string s = Application.StartupPath + "\\alliancedb.accdb";
conn = new
OleDbConnection(String.Format("Provider=Microsoft.ACE.OLEDB.12.0;
Data Source={0}", s));
if (conn.State == ConnectionState.Closed)
{
conn.Open();
dataset = new DataSet();
//query statement
string sqlStatement = String.Format("Select * from {0}
order by {1} ASC", tableName, primary_key);
//run sql
DBadpt = new OleDbDataAdapter(sqlStatement, conn);
oOrderDetailsCmdBuilder = new OleDbCommandBuilder(DBadpt);
DBadpt.Fill(dataset);
dbTab = dataset.Tables[0];
dbTab.TableName = this.tableName = tableName;
rows = dbTab.Rows;
}
else if (conn.State == ConnectionState.Open)
{
conn.Close();
conn.Open();
dataset = new DataSet();
//query statement
string sqlStatement = String.Format("Select * from {0}
order by {1} ASC", tableName, primary_key);
//run sql
DBadpt = new OleDbDataAdapter(sqlStatement, conn);
oOrderDetailsCmdBuilder = new OleDbCommandBuilder(DBadpt);
DBadpt.Fill(dataset);
dbTab = dataset.Tables[0];
dbTab.TableName = this.tableName = tableName;
rows = dbTab.Rows;
}
}

Getting a download.mp3 or download.php file instead of TMH.mp3 file by download.php script

Getting a download.mp3 or download.php file instead of TMH.mp3 file by
download.php script

i have created a download.php file as
include('../../../phpsqlconnect.php');
$sel = mysqli_select_db($link, 'download');
$id=$_GET['id'];
if(is_numeric($id)){
$result = mysqli_query($link, 'SELECT * FROM song WHERE id=$id');
$row = mysqli_fetch_assoc($result);
$url = $row['url']; // of course find the exact filename....
$name = $row['name'];
header( 'Pragma: public' ); // required
header( 'Expires: 0' );
header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' );
header( 'Cache-Control: private', false ); // required for certain browsers
header( 'Content-Type: application/octet-stream' );

header( 'Content-Disposition: attachment; filename="'. basename($url) .
'";' );
header( 'Content-Transfer-Encoding: binary' );
header( 'Content-Length: ' . filesize( $url ) );

readfile( $name );

exit;
}

this download.php is within a song folder & within song folder i have
ppnh13 folder which have ppnh.php fle
i have a download database & song table within it.
table song have 4 rows as id,url,name,movie...
in $row['url'], i have my file location as ppnh13\TMH.mp3
in $row['name'] , i have my file name as TMH



when i open the link < href="../download.php?id=1">TMH from ppnh.php file
i am getting a download.mp3 or download.php file instead of TMH.mp3 file

i want to make a common download.php file for all the folders within
folder song.

Saturday, 14 September 2013

OpenGL ES 2.0 Context in Android

OpenGL ES 2.0 Context in Android

I'm new to OpenGL on Android and I have read heavily documented samples,
and I kinda understand it. But before trying to do anything complex, I
want to draw a simple 2D white rectangle on a black bacground. Nothing
else.
I'm stuck at this error: call to OpenGL ES API with no current context,
which seems to be that I'm calling something from the non-OpenGL Thread.
The thing is that I'm not sure what is called from the OpenGL Thread. So
here's my code
//============== Activity ==================//
public class MainActivity extends Activity {
public static String TAG = MainActivity.class.getSimpleName();
MyGLSurfaceView surface;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN
);
surface = new MyGLSurfaceView(this);
setContentView(surface);
}
@Override
protected void onPause() {
super.onPause();
surface.onPause();
}
@Override
protected void onResume() {
super.onResume();
surface.onResume();
}
}
//==================== GLSurfaceView ========================//
public class MyGLSurfaceView extends GLSurfaceView {
MyGLSurfaceRenderer renderer;
public MyGLSurfaceView(Context context) {
super(context);
setEGLContextClientVersion(2);
renderer = new MyGLSurfaceRenderer(this);
setRenderer(renderer);
}
}
//================== Renderer ==========================//
public class MyGLSurfaceRenderer implements GLSurfaceView.Renderer {
Square square = new Square();
public MyGLSurfaceRenderer(MyGLSurfaceView surface) {
}
@Override
public void onDrawFrame(GL10 gl) {
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
square.draw();
}
@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
// TODO Auto-generated method stub
}
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
GLES20.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
}
}
//==================== Square ========================//
public class Square {
private FloatBuffer vertexBuffer;
private ShortBuffer drawListBuffer;
// number of coordinates per vertex in this array
static final int COORDS_PER_VERTEX = 3;
static float squareCoords[] = { -0.5f, 0.5f, 0.0f, // top left
-0.5f, -0.5f, 0.0f, // bottom left
0.5f, -0.5f, 0.0f, // bottom right
0.5f, 0.5f, 0.0f }; // top right
private short drawOrder[] = { 0, 1, 2, 0, 2, 3 }; // order to draw vertices
float color[] = { 0.63671875f, 0.76953125f, 0.22265625f, 1.0f };
private final String vertexShaderCode =
"attribute vec4 vPosition;" +
"void main() {" +
" gl_Position = vPosition;" +
"}";
private final String fragmentShaderCode =
"precision mediump float;" +
"uniform vec4 vColor;" +
"void main() {" +
" gl_FragColor = vColor;" +
"}";
int mProgram;
static final int vertexStride = COORDS_PER_VERTEX * 4;
static final int vertexCount = 4;
public Square() {
// initialize vertex byte buffer for shape coordinates
ByteBuffer bb = ByteBuffer.allocateDirect(squareCoords.length * 4); //
(# of coordinate values * 4 bytes per float)
bb.order(ByteOrder.nativeOrder());
vertexBuffer = bb.asFloatBuffer();
vertexBuffer.put(squareCoords);
vertexBuffer.position(0);
// initialize byte buffer for the draw list
ByteBuffer dlb = ByteBuffer.allocateDirect(drawOrder.length * 2); //
(# of coordinate values * 2 bytes per short)
dlb.order(ByteOrder.nativeOrder());
drawListBuffer = dlb.asShortBuffer();
drawListBuffer.put(drawOrder);
drawListBuffer.position(0);
int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexShaderCode);
int fragmentShader = loadShader(GLES20.GL_FRAGMENT_SHADER,
fragmentShaderCode);
mProgram = GLES20.glCreateProgram(); // create empty
OpenGL ES Program
GLES20.glAttachShader(mProgram, vertexShader); // add the vertex
shader to program
GLES20.glAttachShader(mProgram, fragmentShader); // add the fragment
shader to program
GLES20.glLinkProgram(mProgram); // creates OpenGL ES
program executables
}
public static int loadShader(int type, String shaderCode){
// create a vertex shader type (GLES20.GL_VERTEX_SHADER)
// or a fragment shader type (GLES20.GL_FRAGMENT_SHADER)
int shader = GLES20.glCreateShader(type);
// add the source code to the shader and compile it
GLES20.glShaderSource(shader, shaderCode);
GLES20.glCompileShader(shader);
return shader;
}
public void draw() {
// Add program to OpenGL ES environment
GLES20.glUseProgram(mProgram);
// get handle to vertex shader's vPosition member
int mPositionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition");
// Enable a handle to the triangle vertices
GLES20.glEnableVertexAttribArray(mPositionHandle);
// Prepare the triangle coordinate data
GLES20.glVertexAttribPointer(mPositionHandle, COORDS_PER_VERTEX,
GLES20.GL_FLOAT, false,
vertexStride, vertexBuffer);
// get handle to fragment shader's vColor member
int mColorHandle = GLES20.glGetUniformLocation(mProgram, "vColor");
// Set color for drawing the triangle
GLES20.glUniform4fv(mColorHandle, 1, color, 0);
// Draw the triangle
GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, vertexCount);
// Disable vertex array
GLES20.glDisableVertexAttribArray(mPositionHandle);
}
}

GoogleNetHttpTransport throws java.security.NoSuchAlgorithmException

GoogleNetHttpTransport throws java.security.NoSuchAlgorithmException

I am new in google api and also in all SSL world. My application try to
establish a connection with Google Calendar application. I have a unit
test establishing this connection and all seems work fine until some hour
ago. After a new test run, they were going to fail throwing the following
exception
java.security.NoSuchAlgorithmException: class configured for SSLContext:
sun.security.ssl.SSLContextImpl$TLS10Context not a SSLContext
at
it.ipiu.jaime.netwell.frontend.bean.gc.GCFacade.newCalendarService(GCFacade.java:478)
at
it.ipiu.jaime.netwell.frontend.bean.gc.GCFacade.calendarService(GCFacade.java:446)
at
it.ipiu.jaime.netwell.frontend.bean.gc.GCFacade.newCalendar(GCFacade.java:422)
at
it.ipiu.jaime.netwell.frontend.bean.gc.GCFacadeTest.testCRUDonCalendarEntry(GCFacadeTest.java:143)
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:601)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:59)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:312)
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:79)
at
org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:87)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:296)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:284)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:77)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:42)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:209)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:148)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
at
org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:27)
at
org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:37)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
at
org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:101)
at
org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at
org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:53)
at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at
org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.security.NoSuchAlgorithmException: class configured for
SSLContext: sun.security.ssl.SSLContextImpl$TLS10Context not a SSLContext
at sun.security.jca.GetInstance.checkSuperClass(GetInstance.java:258)
at sun.security.jca.GetInstance.getInstance(GetInstance.java:237)
at sun.security.jca.GetInstance.getInstance(GetInstance.java:164)
at javax.net.ssl.SSLContext.getInstance(SSLContext.java:156)
at com.google.api.client.util.SslUtils.getTlsSslContext(SslUtils.java:54)
at
com.google.api.client.http.javanet.NetHttpTransport$Builder.trustCertificates(NetHttpTransport.java:241)
at
com.google.api.client.googleapis.javanet.GoogleNetHttpTransport.newTrustedTransport(GoogleNetHttpTransport.java:55)
at
it.ipiu.jaime.netwell.frontend.bean.gc.GCFacade.newCalendarService(GCFacade.java:461)
... 30 more
It happens calling GoogleNetHttpTransport.newTrustedTransport(); Not much
is done before this call
Someone have some idea about that? Probably I don't understand the
mechanism behind the scene. There is someone that can explain me better
what happened
Thank you a lot! Alberto

Overriding a method that is called from a constructor

Overriding a method that is called from a constructor

If an instance of subclass is created, the output is sub0 sub2
Two questions on this:
Why is the subclass method called even though the superclass constructor
is not finished?
Why is the instance field not initialized when called from the superclass
constructor (the sub0 output)?
Example:
class superclass{
int i = 1;
void aMethod(){
System.out.println("super" + i);
}
superclass(){
aMethod();
}
}
class subclass extends superclass{
int i = 2;
void aMethod(){
System.out.println("sub" + i);
}
subclass(){
aMethod();
}
}

What to pair with Sinatra? Backbone, Ember, Angular, Knockout, or something else?

What to pair with Sinatra? Backbone, Ember, Angular, Knockout, or
something else?

I have a Sinatra REST service. I'm trying to put a "face" to it. Right
now, getting the information to and from the service and the database is a
bunch of JQuery AJAX calls like this:
$.getJSON()....
It's quite ugly. Given that I'm using Sinatra, which one of these
front-end frameworks would you recommend for me to learn? BTW, still
learning re: JavaScript, as I use JQuery with AJAX (though I accept that I
will probably need to learn native JS in the future), and have some
experience with MVC frameworks in PHP, but nothing yet on JavaScript.

Get parameter values of an ajax request after form submit

Get parameter values of an ajax request after form submit

I have a form_tag that looks like this:
<%= form_tag products_path, method:'get', remote: true, format: :js do %>
<%= number_field_tag :price, params[:price]%>
<%= submit_tag 'Go', class:'submit_button', :id => 'submit_button'%>
<% end %>
on the index action of the products_controller.rb, I have this:
def index
@price = params[:price]
....
end
The problem is that @price returns nil when i submit the form with remote:
true. I am able to get the value of @price when I remove remote: true and
submit the form without ajax. How can I get the parameters value(s) when i
submit the form via ajax ?

Visual C# 2010 Multiple lisbox choose

Visual C# 2010 Multiple lisbox choose

i have added 2 value in listbox as 1, it generates from MySQL code and
using While loop:
string name = myReader["name"].ToString();
string index = myReader["index"].ToString();
listBox1.Items.Add(index + " - " + name);
now im making a SELECT query with MySQL and i want to generate from
listbox, index which ill use in WHERE name = ..., i can use just string
name but when ppl have same name, it generates with errors so... example i
want to generate with index for no mistakes:
string query = "SELECT * FROM list WHERE index='" + listBox1.Text + "'";
but when it can`t choose only string index which added in top, it not
generates any name...
Finally my question is: how to force sql choose only index from listbox
when added 2 value as 1...
Thanks, hope i`ll get my answer

Friday, 13 September 2013

Equality operator issue (C++)

Equality operator issue (C++)

I'm getting the error
no match for 'operator==' in
'MyNestedClassPointer->MyClass::MyNestedClass::NestedVar == s'
Where s is a reference to a string, and NestedVar is a pointer to a
string. The offending line of code is an if statement comparing the two to
see if they're identical.
if(thePointer->theVar == s)
I have no overloaded operators, but I don't think I should have a need for
them, seeing as these are just string pointers we're dealing with. Now
correct me if I'm wrong, since I'm more than a little rusty, but can't I
do this?
I also apologize if my question is phrased 'incorrectly,' it's my first
post here.

Product searches over multiple sites

Product searches over multiple sites

So, I am not sure if there is any tools out there for this, but I have
been looking for quite some time, I want to be able to write a code that
would search a list of websites for a specific product. For example
searching for a model number and then bring back links to each page. It
would be fine if I were looking for one site alone, i would just use
Google or that site, but I want to search several sites at once. The key
is to reduce the time it takes to search all of these sites.

Best practice for repeated network tasks?

Best practice for repeated network tasks?

I have a small Android application in which I need to do some FTP stuff
every couple of seconds. After learning the hard way that running network
stuff on the UI thread is something Android does not really like, I've
come to this solution:
// This class gets declared inside my Activity
private class CheckFtpTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... dummy) {
Thread.currentThread().setName("CheckFtpTask");
// Here I'll do the FTP stuff
ftpStuff();
return null;
}
}
// Member variables inside my activity
private Handler checkFtpHandler;
private Runnable checkFtpRunnable;
// I set up the task later in some of my Activitiy's method:
checkFtpHandler = new Handler();
checkFtpRunnable = new Runnable() {
@Override
public void run() {
new CheckFtpTask().execute((Void[])null);
checkFtpHandler.postDelayed(checkFtpRunnable, 5000);
}
};
checkFtpRunnable.run();
Is this good practice to perform a recurring task that cannot run on the
UI thread directly? Furthermore, instead of creating a new AsyncTask
object all the time by calling
new CheckFtpTask().execute((Void[])null);
would it be an option to create the CheckFtpTask object once and then
reuse it? Or will that give me side effects?
Thanks in advance, Jens.

What is the equivalent of C++ '*&' in C ?. Does it even exist?

What is the equivalent of C++ '*&' in C ?. Does it even exist?

for example, how to implement this C++ code in C ?
void someFunction(type *&outParamOnly) ;
returnType someOtherFunction() ;
...
returnType someOtherFunction()
{
type *data = NULL ;
someFunction(data) ;
...
}
...
void someFunction(type *&outParamOnly)
{
bool condition ;
int array_len ;
...
if(condition) // variable's value passed to this function stays as it was
return ;
...
outParamOnly = new type[array_len] ; // value is moddified and it's
reflected in 'someOtherFunction'
...
}
...
I'm asking because I don't know how to create such equivalent. Does it's
complex ?. In fact I don't know much about C, but much more about C++
syntax, etc. I'm used to write in C++ and once I tryied C to feel
diffrence I'm not doing well when trying to implement what I want. I
expect positive answer - that it possible to create some equivalent, but
will it be running faster then in C++ or slower ? Please answer.

ZF2 how to display tweets in layout

ZF2 how to display tweets in layout

I'm developing a site using ZF2. One of the section in footer contains
tweets. I can fetch tweets but I am not sure how to display them in the
layout. I have following ideas but not sure which approach to use
Create a controller plugin and use it on each request.
Create a ViewHelper which fetches the tweets from the ServiceLocator and
call the helper in the layout
Attach an event to the MvcEvent::EVENT_RENDER in the module.php which sets
the html to a layout variable.
If there is anyother better approach, please let me know.

The charging current is not enough

The charging current is not enough

My phone is giving me that the charging current is not enough,and that i
have to switch to an ac adapter. The problem is that i'm already using an
ac adapter while charging it. I switched the screen off and turned the
entire phone off. the situation is getting worse. Can you suggest me a
solution for this problem knowing that my phone is an HTC chacha??

Thursday, 12 September 2013

Javascript nested list css

Javascript nested list css

I have a list below:
<ul>
<li>
<a>Link1</a>
<ul>
<li>
<a>SubLink1</a>
</li>
...
</ul>
</li>
<li>
<a>Link2</a>
</li>
...
</ul>
And would like to add 'css_class' to the current mouseovered <li> element:
document.getElements('li').addEvents({
mouseover: function(){
this.addClass('css_class');
},
mouseout: function(){
this.removeClass('css_class');
}
});
But this code is wrong as my parent<li> also has 'css_class'. How can I
fix this? Thanks.

How to perform triggers one hour in PostgreSQL?

How to perform triggers one hour in PostgreSQL?

I created triggers, hoping it can work in a while, such as one hour.How
can I execute this problem?