Saturday, 31 August 2013

How to inject jQuery or JavaScript to an iFrame?

How to inject jQuery or JavaScript to an iFrame?

I am trying to build a HTML,CSS, jQuery/JavaScript editor... How can I
inject JavaScript or jQuery into an iFrame? I tried searching all related
answers here, but none of the solutions is helping...
here's what I am talking about...#css, #js are textareas, while #iframe_id
is an iframe used to preview the changes.
css_code = $('#css').val();
js_code = $('#js').val();
css_content = "<style>" + css_code + "</style>"; // working
js_content = "<script>" + js_code + "</script>"; // does not work
$('#iframe_id').contents().find('head').append(css_content); // working
$('#iframe_id').contents().find('body').append(js_content); // does not work
The following works but only if I use core JavaScript, not sure
why...frame[0] basically is the same iframe (#iframe_id)...
var js_content = jsEditor.getValue();
frames[0].window.eval(js_content); // works only when JavaScript is
entered (not jQuery)
It may be something to do with the 'script' tags, maybe jQuery has a
problem with it...not sure why.

Generating unique token on the fly with Rails

Generating unique token on the fly with Rails

I want to generate a token in my controller for a user in the
"user_info_token" column. However, I want to check that no user currently
has that token. Would this code suffice?
begin
@new_token = SecureRandom.urlsafe_base64
user = User.find_by_user_info_token(@new_token)
end while user != nil
@seller.user_info_token = @new_token
Or is there a much cleaner way to do this?

Jquery with php and send mail

Jquery with php and send mail

I have one question , i have my form working very well with jquery - no
send at the moment - , this jquery works over website with page with his
header , body and footer and many divs inside , this jquery auto call the
same page for send the form and no call external page
My code it´s this :
<script>
jQuery(document).ready(function() {
$("#form1").submit(function(e){
e.preventDefault();
var data = jQuery('#form1').serialize();
jQuery.ajax({
data: data,
cache: false,
url: 'home.php',
type: 'POST',
async:false,
success: function(){
var tit=$("#title_s").val();
var men=$("#mensaje_s").val();
if (tit=="" || men=="")
{
jQuery("#cp_asesor_request_ok").show();
}
else
{
jQuery("#cp_asesor_request_ok").show();
}
}
});
});
});
</script>
**The Form**
<div id="cp_asesor_request_ok" style="display:none;">Form Send</div>
<div id="cp_asesor_request_fail" style="display:none;">Error Send</div>
<form id="form1" name="form1" method="post" action="">
<p>
<label for="textfield"></label>
<input type="text" name="title" id="title_s" class="cp_input_asesor"
value="title" onclick="this.value=''"/>
</p>
<p>
<label for="textarea"></label>
<textarea name="message" id="mensaje_s" class="cp_textarea_asesor"
cols="45" rows="5" title="Insertar Mensaje de Solicitud"></textarea>
<input type="submit" name="button" class="cp_submit_asesor" value="Send" />
</p>
</form>
The question it´s how i can send the email from form because all do from
jquery but how i can call to the php mail function from the same page , i
need yes or yes call to external page for send the email ? or from the
same page called home.php i can send the email , the page it´s home.php
and need call other time to home.php for send email , if no use jquery
it´s easy buut if use jquery how i can do it
Thank´s

add aocolumns with $.parseJson() datatables.js

add aocolumns with $.parseJson() datatables.js

I need a little of help here.
I need to fill a table with json from the server, the aaData and
aoColumns, but the thing is that I need a column with a button.
I have this code
$('#divGrid').html('<table cellpadding="0" cellspacing="0"
border="0" class="display" id="example"></table>');
var results=result.split('@_@');
$('#example').dataTable({
"aaData": $.parseJSON(results[0]) ,
, "aoColumns": $.parseJSON(results[1])
});
}
my results are
results[0]="[["jpa","SI","","","","PADILLA",1],["sid","SI","","","","MIRAMONTES",2]]"
results[1]=[{"sTitle":"UserName"},{"sTitle":"ID_CENTRO_TRABAJO"},{"sTitle":"rolName"},{"sTitle":"dominio"},{"sTitle":"recibeAlertas"},{"sTitle":"NOMBRE"},{"sTitle":"edit",
"fnRender": 'function(obj){ return '<input type='button' name='hola'
value='Play'></input>';}'}]"
but my console is clean, no errors are throw. The value apperas but the
button is not.
thanks for any help

phpmailer exception in Gravity form

phpmailer exception in Gravity form

I have involved with a Mailer error. I am using gravity forms and there is
my form. I submitted to form and a email had delivered successful. but i
got error everytime
Fatal error: Cannot redeclare class phpmailerException in
/home/content...../class-phpmailer.php on line 2825
i have used also:-
if (!class_exists('PHPMailer')) {
require_once('class.phpmailer.php');
}
Don not know why i am getting. please help me

how to position arrow of tag?

how to position arrow of tag?

My site is RTL and every thing is ok. But the categories tag box arrow is
poisoned right over text. when i disable styling (Obacity), it positions
left What is wrong with my style. The theme is originally LTR and i am
converting it to RTL Thanks
arabspages[dot]com

django delete object from post (bootstrap)

django delete object from post (bootstrap)

I'm trying to implement a way to delete objects from frontend using a form
and Bootstrap. The alert box is closing but upon page refresh the object
is still present and no deletion is made in database.
What's the proper way of implementing this? Please help!
forms.py
class DeleteAlertForm(forms.ModelForm):
def is_valid(self):
form = super(DeleteAlertForm, self).is_valid()
for f, error in self.errors.iteritems():
if f != '__all__':
self.fields[f].widget.attrs.update({'class': 'error', 'value':
strip_tags(error)})
return form
class Meta:
model = Alert
fields = []
views.py
@login_required
def delete(request, alert_id):
if request.method == "POST":
form = DeleteAlertForm(request.POST)
if form.is_valid(): # checks CSRF
a_id = request.POST.get('alert_id', False)
alert = New.objects.get(pk=a_id)
alert.delete()
return HttpResponseRedirect("/")
else:
return redirect('/')
return redirect('/')
template.html
<div class="alert alert-info alert-block">
<form action="/delete/" method="post">
{% csrf_token %}
<input type="hidden" value="{{alert.id}}" name="alert_id">
<button type="submit" class="close" data-dismiss="alert">×</button>
</form>
</div>

i want to animate text smoothly from left and right in continuous loop can any suggest me something

i want to animate text smoothly from left and right in continuous loop can
any suggest me something

i want to animate text smoothly from left and right in continuous loop can
any suggest me something here is the fiddle link
Here's http://jsfiddle.net/yLNGn/3/
$(document).ready(function () { $('.kp').animate({ left: '10px' }, 600);
$('.kp').delay(600).animate({ left: '-128px' }, 600);
$('.rp').delay(2000).animate({ left: '10px' }, 600);
$('.rp').delay(600).animate({ left: '-108px' }, 600);
$('.kpp').delay(4000).animate({ left: '10px' }, 600); });

Friday, 30 August 2013

Where does 0.5 belong?

Where does 0.5 belong?

I'm working on a problem that predicts either 0 or 1. I'm using a software
and most of the time it outputs 0.5 exactly. So, how do I categorize that?
Do I assume that it's closer to 0, or should I assume it's closer to 1?

Thursday, 29 August 2013

Server Authorization error on Playready License Server

Server Authorization error on Playready License Server

I am getting following exception in Playready license server whenever my
silverlight player tries to play the PR protected streams
Internal service error.\r\nClient record locator =
3a7d80c8-530a-45b0-86d4-a00a2043b4bc \r\n\r\n
Microsoft.Media.Drm.RMServerException: Caught an exception while trying to
load the configured handler type \"ServerAuthorization\". --->
System.Reflection.TargetInvocationException: Exception has been thrown by
the target of an invocation. ---> System.NullReferenceException: Object
reference not set to an instance of an object. at
ServerAuthorization..ctor() --- End of inner exception stack trace --- at
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean
publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle&
ctor, Boolean& bNeedSecurityCheck) at
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean
fillCache) at System.RuntimeType.CreateInstanceImpl(Boolean publicOnly,
Boolean skipVisibilityChecks, Boolean fillCache) at
System.Activator.CreateInstance(Type type, Boolean nonPublic) at
Microsoft.Media.Drm.HandlerLoader.GetHandler(Type handlerType
Please let me know if anybody has faced the same error and found a solution.
Thanks,
Tarun Singhal

Wednesday, 28 August 2013

Google OAuth2 not working on local development server - PHP Codeigniter spark

Google OAuth2 not working on local development server - PHP Codeigniter spark

I am trying to use the Codeigniter spark (
http://getsparks.org/packages/oauth2/versions/HEAD/show) to allow users to
login to my php site with fb and google.
My local dev site (on wampserver) is called mysite.dev, for which I have a
etc/hosts file like :
127.0.0.1 mysite.dev
Facebook login works absolutely fine. But when I try logging with google,
google complains : Invalid parameter value for redirect_uri: Non-public
domains not allowed: http://mysite.dev/index.php/oauth2/session/google
where oauth2 is my controller and session is the function where I specify
fb/google, etc
any clues/hints ? thanks

properties lang.NullPointerException reading from same package

properties lang.NullPointerException reading from same package

I've tried variations on the path to the properties file, but can't seem
to get it correct.
Here's the structure:
src/
„¥„Ÿ„Ÿ properties.properties
„¤„Ÿ„Ÿ teln
„¥„Ÿ„Ÿ ConnectMUD.java
„¥„Ÿ„Ÿ IOUtil.java
„¤„Ÿ„Ÿ PropertiesReader.java
and the error:
run:
Exception in thread "main" java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:434)
at java.util.Properties.load0(Properties.java:353)
at java.util.Properties.load(Properties.java:341)
at teln.PropertiesReader.getProps(PropertiesReader.java:16)
at teln.ConnectMUD.main(ConnectMUD.java:18)
and the class in question:
package teln;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
public class PropertiesReader {
private static final Logger LOG =
Logger.getLogger(PropertiesReader.class.getName());
private static Properties props = new Properties();
public static Properties getProps() {
try {
props.load(PropertiesReader.class.getResourceAsStream("/teln/teln.properties"));
} catch (IOException ex) {
Logger.getLogger(PropertiesReader.class.getName()).log(Level.SEVERE,
null, ex);
}
LOG.fine(props.toString());
return props;
}
}
The project is Teln and the package is teln (not good choices, maybe).
see also: http://stackoverflow.com/a/8285636/262852

How to get Jquery scrollTo plugin work with AngularJS - without flickering

How to get Jquery scrollTo plugin work with AngularJS - without flickering

I'm trying to combine the scrollTo plugin for Jquery with AngularJS. The
reason why I want to do this is that I want to have automated scrolling to
a specific section of the website if the corresponding URL will be used.
Until now this works, but not perfectly. There is a short flickering if
one clicks on a link, just before the animation starts.
I think the problem can be solved by using:
event.preventDefault();
But I don't know how to combine the call of preventDefault function with
my AngularJS code ... I'm new to AngularJS so maybe there is a simple
solution which I just don't know yet. I tried several solutions which I
found on the net but without success.
Here you can find an abstract of the current solution :
http://jsfiddle.net/Hcb4b/6/ It's not runnable because I can't include the
easing plugin ...
Thanks in advance

Listing all of the files in a folder / If file is image, display a preview

Listing all of the files in a folder / If file is image, display a preview

I have the following code:
echo "<table> <tr>";
function listFolderFiles($dir){
$ffs = scandir($dir);
$c = 0;
foreach($ffs as $ff){
$c++;
if($ff != '.' && $ff != '..'){
$extensions = array(".png",".jpg",".jpeg",".bmp",".gif","");
foreach($extensions as $extension) {
if(stripos($ff, $extension)) {
// file is an image, give a preview
}
}
echo '<td style="padding:20px; border: 1px solid
lightgray;"><img src="'.$ff.'">'.$ff;
if(is_dir($dir.'/'.$ff)) listFolderFiles($dir.'/'.$ff);
echo '</td>';
}
if($c >= 5) { $c = 0; echo "</tr> <tr>"; }
}
}
listFolderFiles('files/martin');
Basically, what im trying to do is:
List all files and folders
If file is an image, display a image preview
If file is an audio format, display a preview using the html5 tag
I'm stuck with the last 2 steps, can anyone help?

Tuesday, 27 August 2013

how to count number of files in zipfile in c#

how to count number of files in zipfile in c#

Please tell me how to count the number of files in ZIP file.
I need a C# code to do this job in visual studio. Tried many codes when I
Googled but getting an error saying:
The namespace or assembly is not found for ZIPENTRY/ZIPFILE.
Can anyone tell me what i should include/anything need to be
installed/provide me any code to count the number of files?

Bootstrap 3 WYSIWYG Editor

Bootstrap 3 WYSIWYG Editor

I know probably isn't the kind of questions you should ask on
stackoverflow, but I couldn't find it anywhere on the internet.
I'm looking for a (simple) WYSIWYG Editor jQuery Plugin that's compatible
with Bootstrap 3. I've seen a lot WYSIWYG Editors jQuery Plugin that were
compatible with the previous Bootstrap, but my website uses Bootstrap 3,
so each time I implemented such a jQuery Plugin, my Bootstrap 3 would ruin
the buttons and mess the whole editor up.
Is there a WYSIWYG Editor jQuery Plugin that's compatible with Bootstrap
3? It only needs a few options such as to make text bold, italic,
underlined and be able to add links (and preferably a 'Preview' button).

See GoogleDrive files on ListView of my app

See GoogleDrive files on ListView of my app

I'm trying to build an app that should show user's files on the ListView,
i've seen 2 video tutorial on Google Developers but at the end they don't
explain nothing of i wanted know. Can someone explain me (maybe with code
or some web example) how i can do this?

Name resolution stops working after some time, dnscache needs a stop and start

Name resolution stops working after some time, dnscache needs a stop and
start

I have a Windows 2012 Server (on Windows Azure), with AD Controller and
DNS on it. Next to that, I have another machine, who is domain joined.
Now I can ping from the AD controller to that other machine using the FQN:
C:\Users\Alexander>ping exsertuscdtest.exsertuscd.local
Pinging exsertuscdtest.exsertuscd.local [10.0.0.5] with 32 bytes of data:
Reply from 10.0.0.5: bytes=32 time=1ms TTL=125
Reply from 10.0.0.5: bytes=32 time<1ms TTL=125
Reply from 10.0.0.5: bytes=32 time<1ms TTL=125
Reply from 10.0.0.5: bytes=32 time<1ms TTL=125
Ping statistics for 10.0.0.5:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 0ms, Maximum = 1ms, Average = 0ms
So, no problem here. But after a while (like 20 minutes), I'm not able to
ping anymore:
C:\Users\Alexander>ping exsertuscdtest.exsertuscd.local
Ping request could not find host exsertuscdtest.exsertuscd.local. Please
check t
he name and try again.
Ping with IP address works without any problem. The only thing that helps is:
C:\Users\Alexander>net stop dnscache
The DNS Client service is stopping.
The DNS Client service was stopped successfully.
C:\Users\Alexander>net start dnscache
The DNS Client service is starting.
The DNS Client service was started successfully.
I can then ping the machine again using the FQDN. There is no
error/warning in event log or whatsoever.. I have no clue what is
happening?
Anyone?

Using Apple Thunderbolt display with Windows 7 PC

Using Apple Thunderbolt display with Windows 7 PC

I have a 2013 27" Apple Thunderbolt display which I'd like to connect to a
Windows 7 Laptop.
I have both HDMI and VGA conversion cables, and the Windows machine
recognises the display, but is unable to turn it on.
Will this work, or do I need different hardware?

drupal anonymous users add specific content mail confirmation

drupal anonymous users add specific content mail confirmation

I would like to enable anonymous users to add specific content to my
drupal site. The content should be confirmed by an administrator user
(directly via 'secret' e-mail link).
I followed this tutorial:
http://www.druplicity.com/content/email-confirmation-anonymous-content-through-rules-and-flag
but I think this is way to complicated.
Is there any tutorial out there that could help with my issue?
My Idea:
1. Generate a specific content type and set the publishing options to "non
published" by default
2. If the user is an anonymous user and the content-type is a specific
one: send an e-mail to the administrator mail address
3. The secret link in the mail should be ..../node/NUMBER/secret/publish
or something like that?
Thanks! Florian

Monday, 26 August 2013

Spliting a string with no inbetween elements

Spliting a string with no inbetween elements

I am trying to split a String into individual elements in an array.
The string is something like this:
NSString = "123456789"
And then I tried to use this to separate it:
NSArray *intString = [x componentsSeparatedByString: @""];
But it only seems to enter it into one element in the array, and I'm not
really sure how to go about it. Any help would be great.

The different between 'attribute', 'member' and 'property' for javascript objects

The different between 'attribute', 'member' and 'property' for javascript
objects

A JavaScript object in a key-value structure and the key portion is called
attribute. Would it be wrong if I called it a member or a property? If so,
what are the differences?
So I have learned that a property is one kind of member from this answer,
but this is for C#. Does the same rule apply for Javascript? I want to say
that member == property in Javascript. Please tell me why I would be
wrong.

Get last row by timestamp in pig

Get last row by timestamp in pig

I have some slowly changing metadata that is stored in real-time onto
HDFS. I would like to write a pig job that condenses these rows down to
the most recent row for each key.
For example, for these data (column headers added for clarity):
ts meta key
-- ---- ---
1 foo id1
2 que id2
3 que id2
4 foo id1
5 pasa id2
6 pasa id2
7 foo id1
8 pasa id2
9 pasa id2
10 pasa id2
11 pasa id2
12 hombre id2
13 foo id1
14 foo id1
15 hombre id2
16 bar id1
17 bar id1
18 bar id1
19 bar id1
20 bar id1
I would expect to get the output:
15 hombre id2
20 bar id1
Is there a built-in way to do this in pig or some library already, or
should I look at writing a UDF?

IIS is taking lot of time to deliver first javascript and image file

IIS is taking lot of time to deliver first javascript and image file

We have a Content Management Application and when we did the testing using
a load runner we saw very good performance (pages were rendered less than
2 seconds (most of them in milliseconds).
But now we are monitoring the application with various tools and we
noticed that the first session of the user is taking a lot of time (like
50 seconds) and when we check the first javascript and the first image
loads in about 20 to 30 seconds each. It is always the first javascript
and first image (how small the file size is, I swapped the file order and
see the same behavior) I am not sure where to start the debugging. Any
help where to start the debugging will be highly appricated.
Thanks

Jquery under png image mouse move?

Jquery under png image mouse move?

my problem is this link
[the is link and sample][1]
One image is puzzle, Second image is earth,
I'am rotateable, dragable, and resize earth it's worked but front of the
puzzle,
Sample image is puzzle,front of the earth I'am not touch earth, dragable
or rotateable...
How's solution this problem I want to move earth, but front of puzzle
image... Please help..
[1]: http://jsfiddle.net/nRkNm/

How can i access the Windows Explorer context menu from a C# application?

How can i access the Windows Explorer context menu from a C# application?

I have an application listing in my application and I would like to allow
people to right-click on an item and show the Windows Explorer context
menu. I'm assuming I would need to use the IContextMenu interface, but I'm
not really sure where to start.

Checking if I'm connected to a device

Checking if I'm connected to a device

I'm writing a program to control two devices: a trinamic motor via the
PANDrive PD2-110-42-202 and a frequency counter. I use the boost library.
If the user chooses the correct port number I don't have any difficulties
to connecting with it.
However, if the user enters an incorrect port number and the boost library
doesn't throw an exception, I send a command to check, if I'm really
connected to the device and wait for the response. If the response doesn't
come, I assume that the port number is wrong and show an appropriate
message.
This approach generally works, but not when the user wants to connect with
the port which is already connected to the Intel(R) Active Management
Technology SOL.
When I try to connect to this port for the first few times, the boost
library doesn't throw an exception (which is strange for me, because this
port is used, so it should be opened). What's more, I can't send a command
to this device. When I try to do it, my program freezes. I use the
following function:
boost::asio::write(*port,boost::asio::buffer(cmd.c_str(), cmd.length()));
I don't understand, why it happens. Even if I'm not connected to the right
port, I should be able to send a command.
It happens only when the user wants to connect to this, one, port for the
motor and the frequency counter.
I'm not interested in receiving a valid response in this case, so I also
tried to send an empty command. I'm able to do it, my program doesn't
freeze, but I don't fave any response, even If I'm connected to the right
port.
When I try to connect to this port many times, the boost library throws an
exception, that the port is opened.
Is there any general way to check if I'm connected to the device?
Why can't I send a command to this particular port?

Sunday, 25 August 2013

Error when creating a child theme for Salient

Error when creating a child theme for Salient

I am attempting to create a child theme for Salient and everything seems
to be fine except when I try to access the theme's custom admin menu, I
get this error below the screen:
Warning:
require(/home/content/38/87666/html/mysite/wp-content/themes/MyChildTheme/css/colors.php)
[function.require]:
failed to open stream: No such file or directory in
/home/content/38/87666/html/mysite/wp-content/themes/salient
/functions.php on line 1101
Fatal error: require() [function.require]: Failed opening required
'/home/content/38/87666/html/mysite/wp-content/themes/MyChildTheme
/css/colors.php' (include_path='.:/usr/local/php5/lib/php') in
/home/content/38/87666/html/mysite/wp-content/themes/salient/
functions.php on line 1101

[ Running ] Open Question : Is it okay to workout if sore?

[ Running ] Open Question : Is it okay to workout if sore?

My hips/sides of my butt are very sore and it's uncomfortable to walk/run
but is it okay to anyway? If not, how long should I wait? Will it get
better on its own? I *assume* it is just from overuse. I run 3-5 miles
everyday + walk about 6 miles a day....so on average I'm doing 10 a day
and I rarely take days off.

Android importing project of different API level

Android importing project of different API level

I am already having one small project in android that is build in API-10.
And i am using the latest version of the API-17 and having the same SDK
manager.
Now when i import this project it shows error like Unable to resolve
target 'android-10' and some more lines.
So, when i Googled about this problem i found that i think i need to
download API-10 and the SDK.
So i wanted to know why its needed?
Because my existing code is built in API-10 then i think it should be
compatible with API-17.
I am new to Android i just understood some concepts like Activity,
Services and many more but when i came around this issue i really shocked?
I just wanted to understand why its needed while i am already having SDK
for API-17?

Add images dynamically based on number selected

Add images dynamically based on number selected

I have the following layout which displays an image and a text string:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center" >
<ImageView
android:id="@+id/ivIcon"
android:layout_width="@dimen/number_icon"
android:layout_height="@dimen/number_icon"
android:scaleType="fitXY"
android:layout_marginTop="@dimen/letter_icon_margin_top" />
<Button
android:id="@+id/btnNumber"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_margin="5dp"
android:layout_weight="3"
android:text=""
android:gravity="center"
android:textSize="@dimen/word_size_text"
android:textColor="#000000"
android:textStyle="bold"
android:background="@drawable/borderaction" />
</LinearLayout>
The ivIcon is displaying the images based on user input. It worked great
when displaying one image per letter. But how do i fix the above layout so
it displays the number of images based on user selection.
For example this is what is looking like when I use it for letter:

For the number, if the user chooses 5 the display should be:

If the user chooses 1 the display should be:

The code that is setting the image for the letter is:
ivLetterIcon = (ImageView) findViewById(R.id.ivIcon);
ivLetterIcon.setImageResource(R.drawable.apple);
How would I accomplish the number images?
Would it be best to have a blank layout without the images and add the
ImageView at runtim depending on the number and have it centered? This way
the images(s) are centered to the parent view layout?

Change the default IP address of a CentOS 6 dedicated server

Change the default IP address of a CentOS 6 dedicated server

I have a dedicated box running CentOS 6. I'd like to change the default IP
address, I googled a lot and I found this suggestion:
(1) Run these two commands via SSH:
sudo -n ifconfig eth0 down
sudo -n ifconfig eth0 up NEW_IP
(2) Change Apache's ServerName directive to the new IP address in
httpd.conf, ie.
ServerName 111.222.333.44:80
(3) Restart apache
(4) Change any domain pointing to this server/old IP address to point to
the new one.
I'm going to do this on a live server, so I'd like to know if these
instructions are correct before I proceed (I don"t wanna screw things up)



Can someone please confirm (or correct me if I'm wrong) if this is the way
to go?

Saturday, 24 August 2013

Steps to configure iPod shuffle in Fedora 19

Steps to configure iPod shuffle in Fedora 19

I am using Fedora 19 GNOME version.
After I plugin my iPod to the USB, it is not listed in my filesystem.
The output of the lsusb command is:
Bus 002 Device 003: ID 090c:237c Silicon Motion, Inc. - Taiwan (formerly
Feiya Technology Corp.)
Bus 002 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 003: ID 05ac:1303 Apple, Inc. iPod Shuffle 4.Gen
Bus 001 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
the output of fdisk -l is:
Disk /dev/sda: 500.1 GB, 500107862016 bytes, 976773168 sectors Units =
sectors of 1 * 512 = 512 bytes Sector size (logical/physical): 512 bytes /
4096 bytes I/O size (minimum/optimal): 4096 bytes / 4096 bytes Disk label
type: gpt
Start End Size Type Name 1 2048 411647 200M EFI System EFI System Partition 2
411648 1435647 500M Microsoft basic 3 1435648
976773119 465.1G Linux LVM
Disk /dev/mapper/fedora-root: 53.7 GB, 53687091200 bytes, 104857600
sectors Units = sectors of 1 * 512 = 512 bytes Sector size
(logical/physical): 512 bytes / 4096 bytes I/O size (minimum/optimal):
4096 bytes / 4096 bytes
Disk /dev/mapper/fedora-swap: 4177 MB, 4177526784 bytes, 8159232 sectors
Units = sectors of 1 * 512 = 512 bytes Sector size (logical/physical): 512
bytes / 4096 bytes I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disk /dev/mapper/fedora-home: 441.5 GB, 441505021952 bytes, 862314496
sectors Units = sectors of 1 * 512 = 512 bytes Sector size
(logical/physical): 512 bytes / 4096 bytes I/O size (minimum/optimal):
4096 bytes / 4096 bytes
Disk /dev/sdb: 2018 MB, 2018496512 bytes, 492797 sectors Units = sectors
of 1 * 4096 = 4096 bytes Sector size (logical/physical): 4096 bytes / 4096
bytes I/O size (minimum/optimal): 4096 bytes / 4096 bytes Disk label type:
dos Disk identifier: 0x00000000
Device Boot Start End Blocks Id System
So, sdb is my iPod.
The output of mount -t hfsplus /dev/sdb /media/ipod/ is:
mount: wrong fs type, bad option, bad superblock on /dev/sdb, missing
codepage or helper program, or other error
In some cases useful info is found in syslog - try
dmesg | tail or so.
Then I tried checking the logfile dmesg | tail -30. The output was:
[254134.677536] usbcore: registered new interface driver usb-storage
[254135.680855] scsi 6:0:0:0: Direct-Access Apple iPod
2.70 PQ: 0 ANSI: 2 [254135.681654] sd 6:0:0:0: Attached scsi generic sg2
type 0 [254135.682437] sd 6:0:0:0: [sdb] 492797 4096-byte logical blocks:
(2.01 GB/1.87 GiB) [254135.683072] sd 6:0:0:0: [sdb] Write Protect is off
[254135.683077] sd 6:0:0:0: [sdb] Mode Sense: 6e 00 00 08 [254135.683678]
sd 6:0:0:0: [sdb] Incomplete mode parameter data [254135.683682] sd
6:0:0:0: [sdb] Assuming drive cache: write through [254165.979596] usb
1-1.2: reset high-speed USB device number 3 using ehci-pci [254197.054873]
usb 1-1.2: reset high-speed USB device number 3 using ehci-pci
[254228.066118] usb 1-1.2: reset high-speed USB device number 3 using
ehci-pci [254259.205331] usb 1-1.2: reset high-speed USB device number 3
using ehci-pci [254259.294409] sd 6:0:0:0: [sdb] 492797 4096-byte logical
blocks: (2.01 GB/1.87 GiB) [254259.295670] sd 6:0:0:0: [sdb] Incomplete
mode parameter data [254259.295674] sd 6:0:0:0: [sdb] Assuming drive
cache: write through [254290.152447] usb 1-1.2: reset high-speed USB
device number 3 using ehci-pci [254321.227721] usb 1-1.2: reset high-speed
USB device number 3 using ehci-pci [254352.238989] usb 1-1.2: reset
high-speed USB device number 3 using ehci-pci [254383.250192] usb 1-1.2:
reset high-speed USB device number 3 using ehci-pci [254383.337942] sdb:
[254383.339261] sd 6:0:0:0: [sdb] 492797 4096-byte logical blocks: (2.01
GB/1.87 GiB) [254383.340499] sd 6:0:0:0: [sdb] Incomplete mode parameter
data [254383.340503] sd 6:0:0:0: [sdb] Assuming drive cache: write through
[254414.261274] usb 1-1.2: reset high-speed USB device number 3 using
ehci-pci [254445.400659] usb 1-1.2: reset high-speed USB device number 3
using ehci-pci [254476.411854] usb 1-1.2: reset high-speed USB device
number 3 using ehci-pci [254507.423071] usb 1-1.2: reset high-speed USB
device number 3 using ehci-pci [254507.509440] sd 6:0:0:0: [sdb] Attached
SCSI removable disk [254606.269395] hfsplus: unable to find HFS+
superblock [254921.669943] hfsplus: unable to find HFS+ superblock
I also have gtpod and banshee installed. How do I get the iPod configured
and running?

Prevent form injection with JavaScript?

Prevent form injection with JavaScript?

I have a page where users must create a custom profile picture using an
HTML5 Canvas and JavaScript. The base64 image data of the canvas is stored
in a hidden input field element in a form where they enter the rest of
their user information. I only want people on the site having their
profile pictures made with my JavaScript / Canvas designer, but users are
able to go into the Chrome console, or use the address bar, or a
user-script to set the contents of the hidden input field to the base-64
image data of their choice (not made with my canvas).
How can I prevent people from doing this? I was thinking maybe some sort
of method using AJAX to POST data to a PHP file which sets $_SESSION data,
but I can't think of a way to do that which would prevent users from
injecting javascript to change the parameter.

batch file skip record

batch file skip record

Below is a batch file to redirect the first field of all files to a new
file. I am looking for a method to also skip the first record.
@echo off
for %%x in (*.csv) do (
type nul>"%%~nx.new"
for /F "usebackqdelims=," %%A in ("%%~x") do (echo(%%A)>> "%%~nx.new"
)

What exactly is the 'pumping length' in the Pumping lemma?

What exactly is the 'pumping length' in the Pumping lemma?

I'm trying to understand what is this 'margical' number 'n' that is used
in every application of the Pumping lemma. After hours of research on the
subject, I came to this website -->
http://elvis.rowan.edu/~nlt/TheoryNotes/PumpingLemma.pdf
that states
Processing z requires tracing a path of |z| edges ¡ª thus |z|+1 nodes ¡ª
through the FA graph (one arc per symbol in z). q0 q1 q2 ... qlength(z)
The FA has some &#64257;nite number of states ¡ª say, s. If |z| ¡Ý s, then
some state must occur twice in the above sequence ¡ª thus, the sequence
contains a loop. If there¡¯saloop, then you could go around the loop as
many times as you wanted and still get strings in L. n is the longest a
string can be without having a loop. The biggest n can be is s, though it
might be smaller for some particular language.
From what I understand if there is a Language L then the pumping length of
L is the amount of states in the Finite State Automata that recognizes L.
Is this true?
If it is then what exactly does the last line from above say "though it
might be smaller for some particular language" ?? Complete mess in my
head. Could somebody clear it up, please?

How to recognize the audio stream format?

How to recognize the audio stream format?

Here I have the code which records a audio stream to file. The problem is
I'd like to save this file with correct file extension (mainly .mp3 and
.aac). How can I achieve this?
URLConnection conn = new URL(StringUrls[0]).openConnection();
InputStream in = conn.getInputStream();
BufferedOutputStream bufOutstream = new
BufferedOutputStream(new FileOutputStream(new
File(env.getExternalStorageDirectory()+"/temp.file")));
byte[] buffer = new byte[4096];
int len = in.read(buffer);
while (len != -1) {
bufOutstream.write(buffer, 0, len);
len = in.read(buffer);
if (Recorder.this.isCancelled) break;
}
bufOutstream.close();

How to make links in a Javascript "slide out" menu work

How to make links in a Javascript "slide out" menu work

I have created a very simple website using Jquery and CSS.
There is a navigation menu on the left hand side. Each menu item links to
an external website. Unfortunately, these links do not actually WORK!
What am I missing?? I am very new to JS.
Here is the JS:
<script type='text/javascript'>
$(document).ready(function(){
$('#slideout').hover(function() {screen
$(this).animate({right:'0px'}, {queue:false, duration: 500});
}, function() {
$(this).animate({right:'-270px'}, {queue:false, duration: 500});
});
});
</script>
Here is the HTML:
<div id="slideout">
<div id="slidefont">selected works</div>
<div id="slideout_inner">
<ul>
<li>
<a href="http://websitegoeshere.com" target="blank">test1</a>
</li>
<li>
<a href="http://websitegoeshere2.com" target="blank">test2</a>
</li>
</ul>
</div>
</div>

From a high level programming perspective, what is the major difference between C# and F#?

From a high level programming perspective, what is the major difference
between C# and F#?

I'm aware that they both use different programming paradigms, but from a
high level perspective apart from differing syntax it seems most basic
tasks can be achieved in similar fashion.
I only say this because when I've previously touched functional
programming languages such as Haskell, writing code for basics tasks was
(at first) difficult, frustrating, and required a completely different
mindset.
For example the following took some time to get to grips with using
recursive syntax:
loop :: Int -> IO ()
loop n = if 0 == n then return () else loop (n-1)
Where as an F# loop is recognisable and understable almost immediately:
let list1 = [ 1; 5; 100; 450; 788 ]
for i in list1 do
printfn "%d" i
When C# programmers start learning F# they are advised to completely
re-think their thought pattern (which was definitely required for
Haskell), but I've now written several F# programs dealing with
conditions, loops, data sets etc to perform practical tasks, and I'm
wondering where the 'different-paradigm' barrier really kicks in?
Hopefully someone will be able to solve my confusion.

Managing multiple account from gmail

Managing multiple account from gmail

Ive got 2 work email accounts both from different company (both running on
separate domains on google apps for business using so they are using
gmails infrastructure) at the moment im managing them using mac mac which
is ok, but id like to move to use the gmail in the browser to view /
manage / compose emails.
At the moment in mac mail can switch between my two accounts like this
(image below)
Is there something similar inside of gmail that i can setup ?

Duplicate of Entity

Duplicate of Entity

I am not able to get this working and I find no example for my special
case. In short words: I have a main entity with relationships. Now I want
to make a copy of a sub-entity and link this new sub-entity to the main
entity. Best I try to make a short example. I skip the getter and setter
methods to make it shorter:
Entity Entry:
@Entity
public class Entry implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToMany(mappedBy = "entry", cascade=CascadeType.ALL)
private List<EntryData> entriesDataList = new LinkedList<>();
@OneToOne(cascade=CascadeType.ALL)
private EntryData entryData;
}
Entity EntryData:
@Entity
public class EntryData implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String subject;
@ManyToOne(optional = false)
private Entry entry;
@ManyToMany(mappedBy = "entries", cascade = {CascadeType.ALL} )
private List<EntryTag> tags = new LinkedList<>();
}
Entity EntryTag:
@Entity
public class EntryTag implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(unique=true)
private String name;
@ManyToMany()
private List<EntryData> entries = new LinkedList<>();
}
Now I want to do the following:
@Stateless
public class NewEntryData {
@PersistenceContext
private EntityManager em;
public void makeNewEntryData(){
Entry e = em.find(Entry.class, 10);
em.detach(e);
EntryData ed = e.getEntryData();
ed.setSubject("New Subject");
ed.setId(null);
for (Iterator<EntryTag> it = ed.getTags().iterator();
it.hasNext();) {
it.next().addEntryData(ed);
}
em.merge(e);
}
}
What I expected:
A new Entity EntryData is generated which has the same content as the old
one which was stored in Entry.entryData, except the new subject. In
Entry.entryData a link to the new EntryData is generated. The old
EntryData consists in the database as it was.
What I get at em.merge(e):
org.eclipse.persistence.exceptions.ValidationException
Exception Description: The attribute [id] of class [test.EntryData] is
mapped to a primary key column in the database. Updates are not allowed.
Can someone help me how to solve this?

Friday, 23 August 2013

Web api with two get actions

Web api with two get actions

I have a Test controller with the following -
public string Get(int id)
{
return "hi from test " + id;
}
[HttpGet]
public string Search(string text)
{
return "you searched for " + text;
}
I can call
- http://localhost:58635/api/Test/2
- http://localhost:58635/api/Test?id=2
- http://localhost:58635/api/Test/Search?text=textToSearcFor
but NOT http://localhost:58635/api/Test/Search/textToSearcFor
My route are like those in this post
config.Routes.MapHttpRoute(
name: "ApiById",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: new { id = @"^[0-9]+$" }
);
config.Routes.MapHttpRoute(
name: "ApiByName",
routeTemplate: "api/{controller}/{action}/{name}",
defaults: null
);
config.Routes.MapHttpRoute(
name: "ApiByAction",
routeTemplate: "api/{controller}/{action}",
defaults: new { action = "Get" }
);
What am I doing wrong?

d3: use anchor elements as chart labels

d3: use anchor elements as chart labels

I am getting started with D3 and SVG but I haven't found anything clear on
how to add hyperlinks. Here is some code I have to write labels to the
left of the bars in a D3 bar chart. Is there a good sample somewhere to
convert these labels to hyperlinks (say objects in rangeData had an href
and name property)? I searched around a bit but haven't gotten much
further than the svg spec for adding an anchor element.
chart.selectAll(".bar.barLabel")
.data(rangeData)
.enter().append("text")
.attr("class", "bar")
.attr("x", 0)
.attr("y", function (d, i) { return height(i) + barHeight(y, i) /
2; })
.attr("dx", -20)
.attr("dy", ".35em")
.attr("text-anchor", "end")
.text(function (d) { return d.label; });

android - my app can't access to internet

android - my app can't access to internet

I need to get html content from url.
I create my project in Eclipse(Java ADT) with Android 4.3 SDK and I can't
get HTML content.
But when I create this project in Eclipse(INDIGO) with Android 2.1 SDK , I
can get HTML content!!
Please Help me!
Edited---
My simple project file is this.
I use this code in Androidmanifest.xml:
<uses-permission android:name="android.permission.INTERNET"/>
my code in MainActivity Class:
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textview1 = (TextView) findViewById(R.id.textview1);
site getcontent = new site();
try {
String data = getcontent.getData().toString();
textview1.setText(data);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
textview1.setText("error1");
}
my class for get html content is:
public class site {
public String getData() throws Exception {
BufferedReader in = null;
String data = null;
try {
HttpClient client = new DefaultHttpClient();
URI website = new URI("http://www.google.com/");
HttpGet request = new HttpGet();
request.setURI(website);
HttpResponse response = client.execute(request);
in = new BufferedReader(new
InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.separator");
while ((l = in.readLine()) != null) {
sb.append(l + nl);
}
in.close();
data = sb.toString();
return data;
} finally {
if (in != null)
try {
in.close();
return data;
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}

Install Python 2.7 on Ubuntu 12.4

Install Python 2.7 on Ubuntu 12.4

I have install Ubuntu several day ago.
I have install Python on Windows before and everything was simple. Now on
Ubuntu I'm getting stuck with installation of Python. So my question is:
How can I install Python 2.7 on Ubuntu 12.4?
Thanks.

Unrecognized vm option when opening RubyMine on Ubuntu

Unrecognized vm option when opening RubyMine on Ubuntu

New to RubyMine. I am trying to open RubyMine on Ubuntu and getting
following error -
$ bin/rubymine.sh
Unrecognized VM option '+UseCodeCacheFlushing'
Could not create the Java virtual machine.
My java version is -
$ java -version

java version "1.6.0_10"
Java(TM) SE Runtime Environment (build 1.6.0_10-b33)
Java HotSpot(TM) Client VM (build 11.0-b15, mixed mode, sharing)

Thursday, 22 August 2013

Good NOD units against GDI infantry units in Command & Conquer: Tiberian Sun Firestorm expansion

Good NOD units against GDI infantry units in Command & Conquer: Tiberian
Sun Firestorm expansion

I just got a copy Command & Conquer: The First Decade and started playing
the Command & Conquer: Tiberian Sun Firestorm expansion.
I always start off with Tick Tank but they are somewhat weak against GDI
Disc Thrower. What are some of the recommended NOD units that is good
against GDI infantries?

How to make etckeeper use the right value for git author & email with apt-get

How to make etckeeper use the right value for git author & email with apt-get

I'm using git with etckeeper.
When I use sudo git to commit changes in /etc/, GIT_AUTHOR_NAME &
GIT_AUTHOR_EMAIL from my env is used (as intended).
When I use sudo apt-get and changes are auto-commited, the local
username@host is used instead.
Why the change in behavior and how can I make sudo apt-get use the ENV vars?

finding and Importing xml file into python

finding and Importing xml file into python

I am attempting to import an xml file into python with minidom.
>>> from xml.dom import minidom
>>> import os
>>> xmldoc =
minidom.parse('c/Users/WFD/Documents/VXWorks/XML_Parasing_Python')
and python cannot find this file even though I have specifically spelled
out where it is. I am new to python so if there is a glaring error I
apologize but can anyone explain how to import an xml file in mydocments?
Here is the error:
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
xmldoc =
minidom.parse('c/Users/WFD/Documents/VXWorks/XML_Parasing_Python')
File "C:\Python27\lib\xml\dom\minidom.py", line 1920, in parse
return expatbuilder.parse(file)
File "C:\Python27\lib\xml\dom\expatbuilder.py", line 922, in parse
fp = open(file, 'rb')
IOError: [Errno 2] No such file or directory:
'c/Users/WFD/Documents/VXWorks/XML_Parasing_Python'
Thanks!

Not sure what the value in a log message in auth log means?

Not sure what the value in a log message in auth log means?

I have the following log line item in my auth.log file.
[TimeStamp] [server] sshd[####]: Received disconnect from [IP Address]:
11: disconnected by user
Obviously this is a disconnect log from an ssh session. I know what it all
means except for the 11. What does this value indicate? Also is the form
of this log message documented somewhere?
Thanks

SetLayeredWindowAttributes to make a window transparent is only working part of the time

SetLayeredWindowAttributes to make a window transparent is only working
part of the time

I'm trying to make a window transparent so that only part of its contents
are visible, I've tried using SetLayeredWindowAttributes to make this
happen, this made the window transparent as I wanted, however it only
works that way when part of the windows picture is outside of the visible
area of my desktop. For some reason whenever the window is fully on screen
it re-draws its black background (the color I use for transparency that's
meant not to be seen.) Here is a video example of the problem. I'm not
sure what exactly is causing this to just to be safe I'm posting the full
code.
#define _WIN32_WINNT 0x501
#include "C:\Program Files\Microsoft DirectX SDK (August
2008)\Include\D3dx9core.h"
#include "C:\Documents and Settings\Death\My
Documents\Downloads\DXSprite\DXSprite\resource.h"
#include <windows.h>
#include <string>
#include <stdio.h>
//-----------------------------------------------------------------------------
// GLOBALS
//-----------------------------------------------------------------------------
HWND g_hWnd = NULL;
LPDIRECT3D9 g_pD3D = NULL;
LPDIRECT3DDEVICE9 g_pD3DDevice = NULL;
ID3DXSprite * g_pD3DXSprite = NULL;
LPDIRECT3DTEXTURE9 g_pTexture = NULL;
const int SCREEN_WIDTH = 800;
const int SCREEN_HEIGHT = 600;
//-----------------------------------------------------------------------------
// PROTOTYPES
//-----------------------------------------------------------------------------
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM
lParam);
HRESULT InitializeD3D ( );
void RenderFrame ( );
//-----------------------------------------------------------------------------
// Name: WinMain()
// Desc: The application's entry point
//-----------------------------------------------------------------------------
int WINAPI WinMain( HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow )
{
WNDCLASSEX winClass;
MSG uMsg;
HRESULT hr;
memset(&uMsg,0,sizeof(uMsg));
winClass.lpszClassName = "MY_WINDOWS_CLASS";
winClass.cbSize = sizeof(WNDCLASSEX);
winClass.style = CS_HREDRAW | CS_VREDRAW;
winClass.lpfnWndProc = WindowProc;
winClass.hInstance = hInstance;
winClass.hIcon = LoadIcon(hInstance, (LPCTSTR)IDC_DXSPRITE);
winClass.hIconSm = LoadIcon(hInstance, (LPCTSTR)IDC_DXSPRITE);
winClass.hCursor = LoadCursor(NULL, IDC_ARROW);
winClass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
winClass.lpszMenuName = NULL;
winClass.cbClsExtra = 0;
winClass.cbWndExtra = 0;
if( !RegisterClassEx(&winClass) )
return E_FAIL;
g_hWnd = CreateWindowEx( WS_EX_LAYERED, "MY_WINDOWS_CLASS",
"Direct3D 9 - ID3DXSprite Example",
WS_OVERLAPPEDWINDOW | WS_VISIBLE ,
0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, NULL, NULL,
hInstance, NULL );
if( g_hWnd == NULL )
return E_FAIL;
SetLayeredWindowAttributes(g_hWnd, RGB(0x00,0x00,0x00), 0, LWA_COLORKEY});
ShowWindow( g_hWnd, nCmdShow );
//----------------------------------------------------------------
// Create the DirectX device
//----------------------------------------------------------------
if (FAILED( InitializeD3D()))
return 0;
//----------------------------------------------------------------
// CREATE THE ID3DXSprite
//----------------------------------------------------------------
// Create the ID3DXSprite interface object
hr = D3DXCreateSprite(g_pD3DDevice, &g_pD3DXSprite );
if( FAILED(hr) )
return hr;
//----------------------------------------------------------------
// LOAD THE TEXTURE FOR THE SPRITE
//----------------------------------------------------------------
// --------------------------------------------------------
// Load the texture. I decided to use the extended
// version of the texture loading function just to show what
// it would look like.
// The texture was created with Photoshop with a transparent
// background to start with. Then line cross hairs were added.
//
// Note - If you don't use a texture image that has a power of
// 2 size for the width or height then the image may not load
// properly. This image is 256x256.
//
D3DXCreateTextureFromFileEx(
g_pD3DDevice,
"C:\\Documents and Settings\\Death\\My Documents\\45handold2.tga",
// Our texture image!
D3DX_DEFAULT, // width
D3DX_DEFAULT, // height
D3DX_DEFAULT, // MIP levels
0, // usage
D3DFMT_DXT1, // texture format
D3DPOOL_MANAGED, // mem pool
D3DX_DEFAULT, // filter
D3DX_DEFAULT, // MIP filter
0, // transparent color key
NULL, // image info struct
NULL, // palette
&g_pTexture); // the returned texture, if success
if ( FAILED(hr) )
return hr;
// ---------
// Main Loop
// ---------
while( uMsg.message != WM_QUIT )
{
if( PeekMessage( &uMsg, NULL, 0, 0, PM_REMOVE ) )
{
TranslateMessage( &uMsg );
DispatchMessage( &uMsg );
}
}
// -------------------------
// Release directx resources
// -------------------------
if (g_pD3DXSprite)
{
g_pD3DXSprite->Release();
g_pD3DXSprite = NULL;
}
if (g_pTexture)
{
g_pTexture->Release();
g_pTexture = NULL;
}
if (g_pD3DDevice)
{
g_pD3DDevice->Release();
g_pD3DDevice = NULL;
}
UnregisterClass( "MY_WINDOWS_CLASS", winClass.hInstance );
return (int)uMsg.wParam;
}
//-----------------------------------------------------------------------------
// Name: WindowProc()
// Desc: The window's message handler
//-----------------------------------------------------------------------------
LRESULT CALLBACK WindowProc( HWND hWnd,
UINT msg,
WPARAM wParam,
LPARAM lParam )
{
switch( msg )
{
case WM_KEYDOWN:
{
switch( wParam )
{
case VK_ESCAPE:
PostQuitMessage(0);
break;
}
}
break;
case WM_CLOSE:
{
PostQuitMessage(0);
}
case WM_DESTROY:
{
PostQuitMessage(0);
}
break;
default:
{
RenderFrame();
return DefWindowProc( hWnd, msg, wParam, lParam );
}
break;
}
return 0;
}
//-----------------------------------------------------------------------------
// Name: InitializeD3D()
// Desc: Create DirectX interface objects
// Initialize the view matrix.
// Setup render states that will not need changing throughout
// the life of the application.
//-----------------------------------------------------------------------------
HRESULT InitializeD3D( )
{
HRESULT hr;
// Create a direct 3D interface object
g_pD3D = Direct3DCreate9( D3D_SDK_VERSION );
if( g_pD3D == NULL )
{
// TO DO: Respond to failure of Direct3DCreate9
return E_FAIL;
}
D3DDISPLAYMODE d3ddm;
if( FAILED( hr = g_pD3D->GetAdapterDisplayMode( D3DADAPTER_DEFAULT, &d3ddm
) ) )
{
// TO DO: Respond to failure of GetAdapterDisplayMode
return hr;
}
//
if( FAILED( hr = g_pD3D->CheckDeviceFormat( D3DADAPTER_DEFAULT,
D3DDEVTYPE_HAL,
d3ddm.Format,
D3DUSAGE_DEPTHSTENCIL,
D3DRTYPE_SURFACE, D3DFMT_D16 )
) )
{
if( hr == D3DERR_NOTAVAILABLE )
// POTENTIAL PROBLEM: We need at least a 16-bit z-buffer!
return hr;
}
//
// Do we support hardware vertex processing? If so, use it.
// If not, downgrade to software.
//
D3DCAPS9 d3dCaps;
if( FAILED( hr = g_pD3D->GetDeviceCaps( D3DADAPTER_DEFAULT,
D3DDEVTYPE_HAL, &d3dCaps ) ) )
{
// TO DO: Respond to failure of GetDeviceCaps
return hr;
}
DWORD dwBehaviorFlags = 0;
if( d3dCaps.VertexProcessingCaps != 0 )
dwBehaviorFlags |= D3DCREATE_HARDWARE_VERTEXPROCESSING;
else
dwBehaviorFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING;
//
// Everything checks out - create a simple, windowed device.
//
D3DPRESENT_PARAMETERS d3dpp;
memset(&d3dpp, 0, sizeof(d3dpp));
d3dpp.BackBufferFormat = d3ddm.Format;
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dpp.Windowed = TRUE;
d3dpp.EnableAutoDepthStencil = TRUE;
d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
// Attempt to create a HAL device, end app on failure just to keep things
// simple. In other words we are not trying to create a REF device if the
// HAL fails.
if( FAILED( hr = g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL,
g_hWnd,
dwBehaviorFlags, &d3dpp, &g_pD3DDevice )
) )
{
// char blah[100];
// snprintf (blah, 1000, "%d", hr);
//MessageBox (NULL,blah,NULL,NULL);
}
// If we get here everything worked!
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: RenderFrame()
// Desc: Draw the image to the framebuffer.
//-----------------------------------------------------------------------------
void RenderFrame( )
{
if (!g_pD3DDevice && !g_pD3DXSprite && !g_pTexture)
return;
// Clear the frame & depth buffer ready for drawing (Black color)
g_pD3DDevice->Clear( 0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER,
0x00000000, 1.0f, 0 );
g_pD3DDevice->BeginScene();
{
//-------------------------
// Render the sprite
//
D3DXVECTOR3 vecPos = D3DXVECTOR3(0,0,0);
if (g_pD3DXSprite && g_pTexture)
{
g_pD3DXSprite->Begin( D3DXSPRITE_ALPHABLEND );
g_pD3DXSprite->Draw(g_pTexture, NULL, NULL, &vecPos, 0xffffffff);
g_pD3DXSprite->End();
}
}
g_pD3DDevice->EndScene();
// Frame buffer to Front buffer
g_pD3DDevice->Present( NULL, NULL, NULL, NULL );
}

Jquery - Maintain order in removing ordered list

Jquery - Maintain order in removing ordered list

I am maintaining an ordered list by adding div on click of add button. If
I am adding first element I am giving the S. no -1, In second element the
S. no -2 and so on. Here I am giving a funtionality to remove divs
randomly. Suppose we have 5 Serial Numers and I am removing number 3 in
this case I want 4 and 5 to reduce by one and will take 3 and 4.
Thanks in advance jQuery Rockers..

in cassandra-cli how to get all column names in a table and how to get it using hector in java?

in cassandra-cli how to get all column names in a table and how to get it
using hector in java?

I'm trying to get column names but could not get way to get only column
names.
In cli I executed command describe table nodes, it returned the result:
CREATE TABLE nodes (
key text PRIMARY KEY,
id text,
scores text,
topic1 text,
topic2 text,
topic3 text,
topic4 text,
topics text
) WITH COMPACT STORAGE AND
bloom_filter_fp_chance=0.010000 AND
caching='KEYS_ONLY' AND
comment='' AND
dclocal_read_repair_chance=0.000000 AND
gc_grace_seconds=864000 AND
read_repair_chance=0.100000 AND
replicate_on_write='true' AND
populate_io_cache_on_flush='false' AND
compaction={'class': 'SizeTieredCompactionStrategy'} AND
compression={'sstable_compression': 'SnappyCompressor'};
CREATE INDEX idx_nodes_id ON nodes (id);
As given in this question, I tries using following command in cli:
SELECT column_name FROM system.schema_columnfamilies WHERE keyspace_name =
'ianew' AND columnfamily_name = 'nodes';
but it gave the error:
Bad Request: Undefined name column_name in selection clause
Perhaps you meant to use CQL 2? Try using the -2 option when starting cqlsh.
As given in this post, I tried using hector in java:
SliceQuery<String, String, String> query =
HFactory.createSliceQuery(keyspace, StringSerializer.get(),
StringSerializer.get(), StringSerializer.get());
query.setColumnFamily(columnFamilyName);
query.setKey("key");
query.setRange(null, null, false, Integer.MAX_VALUE);
ColumnSliceIterator<String, String, String> iterator = new
ColumnSliceIterator<String, String, String>(query, null, "\uFFFF", false);
while (iterator.hasNext()) {
HColumnImpl<String, String> column = (HColumnImpl<String, String>)
iterator.next();
System.out.println("Column name = " + column.getName() + "; Column
value = " + column.getValue());
colNames.add(column.getName());
}
but it returned with no results.
I want output to be something like:
TABLE nodes:
Columns: key text PRIMARY KEY, id text, scores text, topic1 text, topic2
text, topic3 text, topic4 text, topics text
and similar result through Hector.
Versions I'm using:
[cqlsh 2.3.0 | Cassandra 1.2.4 | CQL spec 3.0.0 | Thrift protocol 19.35.0]

Wednesday, 21 August 2013

Battery Consumption on each app

Battery Consumption on each app

Is there some tools or method to measure battery consumption, on each
specific Android app? I tried "PowerTutor", but it didn't work well on my
Samsung, crashed almost every 2-3 hours!

ResultSet into generic List of Lists

ResultSet into generic List of Lists

I need to add a ResultSet to a list of lists. The string passed to the
method is an SQL select statement. The DB connection methods work
perfectly with all other methods in this class so that's not the problem
here. I know I can replace some of the ArrayList declarations with List
but I don't think that matters in this case.
public static ArrayList<ArrayList> selectStatement(String string) throws
SQLException {
ArrayList<ArrayList> listOfLists = null;
ArrayList list;
String[] record = null;
try {
rs = null;
dBConnectionOpen();
rs = st.executeQuery(string);
ResultSetMetaData metaData = rs.getMetaData();
int columns = metaData.getColumnCount();
while (rs.next()) {
list = null;
record = new String[columns];
for (int i = 1; i < columns; i++) {
record[i - 1] = rs.getString(i);
}
list = new ArrayList(Arrays.asList(record));
listOfLists.add(list);
}
} catch (Exception e) {
} finally {
dBConnectionClose();
}
return listOfLists;
}
I have done this before, but for some reason just it won't work this time.
What am I missing here?

Asp.Net MVC passing model via ajax

Asp.Net MVC passing model via ajax

I've got a model that I'd like to use to generate/bind a pop-up form that
remains hidden on a page until needed for use.
<table id="dlgNewEdit" class="vtableform hide">
<tr>
<td>@Html.CustomLabelFor(m => new NewEditModel().Name)</td>
<td>
@Html.HiddenFor(m => new NewEditModel().OemEquipmentMakeId)
@Html.CustomTextBoxFor(m => new NewEditModel().Name, new {
@class = "focus w300" })
@Html.ValidationMessageFor(m => new NewEditModel().Name)
</td>
</tr>
<tr>
<td>@Html.CustomLabelFor(m => new NewEditModel().Description)</td>
<td>
@Html.CustomTextAreaFor(m => new NewEditModel().Description,
new { @class = "w300" })
@Html.ValidationMessageFor(m => new NewEditModel().Description)
</td>
</tr>
</table>
Resulting in:
<table id="dlgNewEdit" class="vtableform hide">
<tr>
<td><label class="required" for="Name">* Name</label></td>
<td>
<input data-val="true" data-val-number="The field
OemEquipmentMakeId must be a number." data-val-required="The
OemEquipmentMakeId field is required." id="OemEquipmentMakeId"
name="OemEquipmentMakeId" type="hidden" value="0" />
<input autocomplete="off" class="required tip focus w300"
data-val="true" data-val-length="Cannot exceed 50 characters"
data-val-length-max="50" data-val-required="Required"
id="Name" maxlength="50" name="Name" title="Enter the make
name" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="Name"
data-valmsg-replace="true"></span>
</td>
</tr>
<tr>
<td><label for="Description">Description</label></td>
<td>
<textarea class="w300 tip" cols="20" data-val="true"
data-val-length="Cannot exceed 500 characters"
data-val-length-max="500" id="Description" name="Description"
rows="2" title="Enter a brief description">
</textarea>
<span class="field-validation-valid"
data-valmsg-for="Description"
data-valmsg-replace="true"></span>
</td>
</tr>
</table>
As you can see, I can't figure out any way to generate the correct form
Ids/Names without using "new NewEditModel()" in all my expressions. Doing
so works just fine, but it seems a bit verbose. I want my field names to
exactly match my model properties because I want the model to bind in the
following action which is called via jQuery ajax:
[HttpPost]
[ValidateAntiForgeryToken]
public JsonNetResult New(NewEditModel model)
{
}
I tried created a variable:
var myModel = new NewEditModel();
using:
@Html.HiddenFor(m => myModel.OemEquipmentMakeId)
But that generates id/name "myModel.OemEquipmentMakeId" which doesn't bind
in my action. Is there a way to do what I want in a different manor?

Clustering values by their proximity in python (machine learning?)

Clustering values by their proximity in python (machine learning?)

I have an algorithm that is running on a set of objects. This algorithm
produces a score value that dictates the differences between the elements
in the set.
The sorted output is something like this:
[1,1,5,6,1,5,10,22,23,23,50,51,51,52,100,112,130,500,512,600,12000,12230]
If you lay these values down on a spreadsheet you see that they make up
groups
[1,1,5,6,1,5] [10,22,23,23] [50,51,51,52] [100,112,130] [500,512,600]
[12000,12230]
Is there a way to programatically get those groupings?
Maybe some clustering algorithm using a machine learning library? Or am I
overthinking this?
I've looked at scikit but their examples are way too advanced for my
problem...

Insert text and Numbers in bash script Menu prompt

Insert text and Numbers in bash script Menu prompt

I'm not sure how to word this but, I am trying to create a script where
the user would run it select an option and then be prompted to enter a
$FileName and a $Number how would I do this in bash?
Here is what I have right now I need help in option [1] and [3]:
Begin
echo "-----------------------------"
echo " Data Processing Menu "
echo "-----------------------------"
begin case structure
echo "What would you like to do"
echo "*[1]Enter Number $Number of Files $FileName to output.txt*"
echo "*[2]Show Classifiers only"
echo "*[3]Auto All $All of Files $AllFileName to output.txt*"
echo "*[4]Exit/Abort*"
echo "------------------------------------------------------"
echo -n "Enter your choice [1-4]:"
read Pmenu
case $Pmenu in
1) "Building";;
2) cut -f 4 input.txt;;
3) "Building";;
4) exit 0;;
esac
Here is the data that this script is processing through (input.txt):
FilePath Filename Probability ClassifierID HectorFileType
LibmagicFileType
/mnt/Hector/Data/benign/binary/benign-pete/
01d0cd964020a1f498c601f9801742c1 19 S040PDFv02 data.pdf PDF
document
/mnt/Hector/Data/benign/binary/benign-pete/
0299a1771587043b232f760cbedbb5b7 0 S040PDFv02 data.pdf PDF
document
/mnt/Hector/Data/benign/binary/benign-pete/
02a3f29050abd76f8d5dbe5972dff932 0 S040PDFv02 data.pdf PDF
document
/mnt/Hector/Data/benign/binary/benign-pete/
068e56e175dc41a91ab0a34b4729200d 0 S040PDFv02 data.pdf PDF
document
/mnt/Hector/Data/benign/binary/benign-pete/
07812135184347a9a2c772665e14d5b2 10 S040PDFv02 data.pdf PDF
document
thank you for your help

I want to play a audio in call background in rooted phone. How can I do that on android development?

I want to play a audio in call background in rooted phone. How can I do
that on android development?

I want to play a audio in call background in rooted phone. How can I do
that on android development.
Please advice me.

Tuesday, 20 August 2013

How to read data at server side sent by HttpPost

How to read data at server side sent by HttpPost

I'm working on creating sample application which sends a XML file to the
local server. In the server side I need to read the data which is sent by
client and write it into a new file.
Below is the client side code I'm using to read a XML file and send it to
the server.
HttpClient httpclient = new DefaultHttpClient();
// Below code is used to connect with the local tomact server or
servlet
HttpPost httppost = new HttpPost("http://xxx.xxx.xxx.xxx:yyyy");
File file = new File("C:\\Files\\sample.xml");
InputStreamEntity reqEntity = new InputStreamEntity(
new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true);
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
int respcode = response.getStatusLine().getStatusCode();
System.out.println("respcode: " + respcode);
Kindly let me know by using tomact how to fetch the data from the client
and write it into the server side. Do I need to use servlets to handle
this?
I had visited many blogs but I'm not getting how to create a server side
code to accomplish this task.
Thanks in advance!

Panel update no longer works when panels are local

Panel update no longer works when panels are local

I am working on a swing project, and I was following the example here of
how to add a Jpanel by clicking a Jbutton. The example works fine, but I
have one question. If I change the panels to be local variables instead of
global, the MainPanel class now becomes:
class MainPanel extends JPanel {
...
public void checkPanel() {
Panel1 p1 = new Panel1();
Panel2 p2 = new Panel2();
if (i == 1) {
this.add(p1);
this.remove(p2);
} else if (i == 2) {
this.add(p2);
this.remove(p1);
}
}
...
}
Yet, when the panels are local variables, the example no longer works as
intended. Why is this?

Facebook Graph API - Access Token for email address

Facebook Graph API - Access Token for email address

Facebook Graph API not allowing access to certain email address - not
allowed by Access Token; I have repeatedly gone into the Graph API
Explorer and clicked "email" as a Node for this specific user then
clicking "submit" but it never resets. Any suggestions?

Image from my computer Saving in mysql table java help please

Image from my computer Saving in mysql table java help please

I'm a student learning java. I need to make an assignment. I need to make
a student management software using java. here's the story where i need
your help. I have to make a jframe for register students. In here i need
to take a photo/picture of student using a webcam and save in mysql
database.how can i do this. can someone please help me to build this
frame. this is how i try to save image.I want to save it to mysql
database.please help
try {
jf.setFileFilter(new FileNameExtensionFilter("Image Files", "jpg",
"gif", "png"));
int val = jf.showOpenDialog(this);
if (val == jf.APPROVE_OPTION) {
a = jf.getSelectedFile();
path1 = a.getAbsolutePath();
ic1 = new ImageIcon(a.getAbsolutePath());
BufferedImage src = ImageIO.read(new File(a.getAbsolutePath()));
int wd = jLabel14.getWidth();
int ht = jLabel14.getHeight();
AffineTransform trans =
AffineTransform.getScaleInstance((double) wd / src.getWidth(),
(double) ht / src.getHeight());
Graphics2D g = (Graphics2D) jLabel14.getGraphics();
g.drawRenderedImage(src, trans);
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
GraphicsConfiguration cg = gd.getDefaultConfiguration();
int transparency = src.getColorModel().getTransparency();
BufferedImage dest = cg.createCompatibleImage(wd, ht,
transparency);
g = dest.createGraphics();
g.drawRenderedImage(src, trans);
g.dispose();
jLabel14.setIcon(new ImageIcon(dest));
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}

ignore floating number in scanf("%d")

ignore floating number in scanf("%d")

if user enters floating number for an integer variable I want to print
invalid input. is that possible?
int a;
scanf("%d",&a); // if user enters 4.35 print invalid input
I have tried for characters like this
if(scanf("%d",&a)==1);else printf("invalid input");
but how to do for floating numbers. if user enters 4.35 it truncates to 4
but i want invalid input. any help is greatly appreciated. Thanks

Setting headers for static content: Wordpress and W3 Total Cache

Setting headers for static content: Wordpress and W3 Total Cache

I'm looking for optimised settings for expire headers for my Wordpress
sites: I use Wordpress with W3 Total Cache plugin and Cloudfront CDN.
I set my headers for JS/CSS/media files to "cache with max-age and
validation ("max-age=EXPIRES_SECONDS, public, must-revalidate,
proxy-revalidate")" and 2 weeks (1209600 seconds).
Reason I set it to 2 weeks only (as opposed to 1 year by plugin's default)
I change my JS/CSS pretty often and I want to make sure user receives the
latest version.
Is this ok, or you find it counter productive (cache time too short - no
time to spread the cache world wide)?
Thanks, Betty

SQLite and UITableView: Crash after numberOfRowsInSection

SQLite and UITableView: Crash after numberOfRowsInSection

First I would like to make clear that I do not want to use Core Data in
this case.
My Problem: whenever my tableview's delegate methodd:
numberOfRowsInSection is called, the application crashes with nothing more
than an (lldb) error message.
First I have two classes which helps me retrieve rows from my SQLite
database.
sqlite.m:
#import "sqlite.h"
#import <sqlite3.h>
@implementation sqlite
@synthesize carbohydrates = _carbohydrates;
@synthesize name = _name;
@synthesize fat = _fat;
@synthesize kcal = _kcal;
- (id)initWithName:(NSString *)name2 carbs:(NSNumber *)carbs2
fat:(NSNumber *)fat2 kcal:(NSNumber*)kcal2 {
if ((self = [super init])) {
self.carbohydrates = carbs2;
self.name = name2;
self.fat = fat2;
self.kcal = kcal2;
}
return self;
}
- (void) dealloc {
self.name = nil;
self.kcal = nil;
self.fat = nil;
self.carbohydrates = nil;
[super dealloc];
}
@end
NutritionsDB.m:
#import "NutritionsDB.h"
#import "sqlite.h"
@implementation NutritionsDB
static NutritionsDB *_database;
+ (NutritionsDB*)database {
if (_database == nil) {
_database = [[NutritionsDB alloc] init];
}
return _database;
}
- (id)init {
if ((self = [super init])) {
NSString *sqLiteDb = [[NSBundle mainBundle]
pathForResource:@"Livsmedeldatabas"
ofType:@"sqlite"];
if (sqlite3_open([sqLiteDb UTF8String], &_database) != SQLITE_OK) {
NSLog(@"Failed to open database!");
}
}
return self;
}
- (void)dealloc {
sqlite3_close(_database);
[super dealloc];
}
-(void)setUpDB{
const char *sql_stmt = "CREATE INDEX IF NOT EXISTS name_index on
livsmedel(namn)";
char *errMsg;
if (sqlite3_exec(_database, sql_stmt, NULL, NULL, &errMsg) == SQLITE_OK)
{
puts("Index successfully created");
// SQL statement execution succeeded
}
}
-(NSArray*)sqliteInfo:(NSString*)predicateString{
NSMutableArray *retval = [[[NSMutableArray alloc] init] autorelease];
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(_database, [predicateString
cStringUsingEncoding:NSUTF8StringEncoding], -1, &statement, nil)
== SQLITE_OK) {
while (sqlite3_step(statement) == SQLITE_ROW) {
char *nameChars = (char *) sqlite3_column_text(statement, 0);
char *kcalchars = (char *) sqlite3_column_text(statement, 1);
char *fatchars = (char *) sqlite3_column_text(statement, 2);
char *carbchars = (char *) sqlite3_column_text(statement, 3);
NSLog(@"\n%s, \n%s, \n%s", kcalchars, fatchars, carbchars);
NSString *name = [[NSString alloc] initWithUTF8String:nameChars];
NSString *kcal = [NSString stringWithFormat:@"%s", kcalchars];
NSString *fat = [NSString stringWithFormat:@"%s", fatchars];
NSString *carb = [NSString stringWithFormat:@"%s", carbchars];
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber * kcalNumber = [f numberFromString:kcal];
NSNumber * fatNumber = [f numberFromString:fat];
NSNumber * carbNumber = [f numberFromString:carb];
NSLog(@"\n kcalnum : %@, \n fatnum: %@, \n carbnum : %@",
kcalNumber, fatNumber, carbNumber);
[f release];
sqlite *info = [[sqlite alloc] initWithName:name
carbs:carbNumber fat:fatNumber kcal:kcalNumber] ;
NSLog(@"%@,%@,%@,%@", name, kcal, fat, carb);
[retval addObject:info];
[name release];
[kcal release];
[fat release];
[carb release];
}
sqlite3_finalize(statement);
}
return retval;
}
@end
Now, In one of my viewcontrollers, I continuously make database calls via
the method
-(NSArray*)sqliteInfo:(NSString*)predicateString.
predicateString is a copy of a text which the user enters in a search bar
inside the VC.
In addition to the UISearchBar, the VC also holds a UITableView to
represent the rows fetched from the databse.
Here is how I update the datasource contents and re-render the the table
view.
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section {
return self.nutritionList.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"hej");
static NSString *CellIdentifier = @"NutritionIdentifier";
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.font = [UIFont fontWithName:@"Avenir-Medium" size:18.0];
cell.textLabel.text = [(sqlite*)[self.nutritionList
objectAtIndex:indexPath.row] name];
return cell;
}
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString
*)searchText{
[self.nutritionList removeAllObjects];
if (searchText.length < 2) {
;
} else {
NSString *firstChar = [searchText
substringWithRange:NSMakeRange(0, 1)];
if([firstChar isEqualToString:@"å"] ||
[firstChar isEqualToString:@"Å"] ||
[firstChar isEqualToString:@"ä"] ||
[firstChar isEqualToString:@"Ä"] ||
[firstChar isEqualToString:@"ö"] ||
[firstChar isEqualToString:@"Ö"]){
NSString *lowerString = [firstChar lowercaseString];
NSString *upperString = [firstChar uppercaseString];
NSString *newSearchText = [searchText
stringByReplacingCharactersInRange:NSMakeRange(0, 1)
withString:lowerString];
NSString *newSearchText_upper = [searchText
stringByReplacingCharactersInRange:NSMakeRange(0, 1)
withString:upperString];
NSString *formatString =
[[[[[@"'"stringByAppendingString:newSearchText]stringByAppendingString:@"%'"]
stringByAppendingString:@" OR namn
like'"]stringByAppendingString:newSearchText_upper]stringByAppendingString:@"%'
ORDER BY namn COLLATE NOCASE"];
NSArray *array = [[NutritionsDB database] sqliteInfo:[NSString
stringWithFormat:@"Select * from livsmedel where namn like
%@", formatString ]];
NSLog(@"%@",[NSString stringWithFormat:@"Select * from
livsmedel where namn like %@", formatString ] );
for (sqlite *info in array) {
[self.nutritionList addObject:info];
}
}else{
NSString *formatString =
[[@"'"stringByAppendingString:searchText]stringByAppendingString:@"%'
"];
NSArray *array = [[NutritionsDB database] sqliteInfo:[NSString
stringWithFormat:@"SELECT * FROM livsmedel WHERE namn LIKE
%@", formatString ]];
NSLog(@"%@",[NSString stringWithFormat:@"Select * from
livsmedel where namn like %@", formatString ] );
for (sqlite *info in array) {
[self.nutritionList addObject:info];
NSLog(@"carbs %@, fat %@, kcal %@", info.carbohydrates,
info.fat, info.kcal);
}
}
}
[self.tableView reloadData];
}
Finally the crash occurs after the numberOfRowsInSection method is called,
but before the cellForRowAtIndexPath is called. Somewhere between them.
The console says (lldb), nothing else. The view below is the assembly
instructions that indicates where the crash occurs. However, I do not now
how to interpret them.

My question: Why does this crash occur?
Thanks for your help.

Monday, 19 August 2013

Drag and Drop Row and Coloum in Grid View Android

Drag and Drop Row and Coloum in Grid View Android

I want to Create Drag and Drop Menu. which can user set as per his
requirement. i attaches Example Image. i have also collapse tow column and
row some where.

Please help me how to do this. i can not any idea how to implement. Thanks
in Advance.

What is the largest class in .NET?

What is the largest class in .NET?

Out of pure curiosity, what is the largest public class/struct in .NET 4.5
in terms of public + protected member count? (Inherited members included)

How can I reject sync changes for my OS X Contacts?

How can I reject sync changes for my OS X Contacts?

I have my OS X Mountain Lion contacts hooked up to synchronize with Google
Contacts. Every once in a while, I receive a notice that "Syncing with
Google Contacts will change more than 25% of your contacts or groups on
this computer."
Almost always, this just means that the images are mysteriously being
removed from my contacts. My only two options are "Sync Later" or "Sync
Contacts". I would prefer to mark my local contacts as master contacts, or
to be able to reject the proposed changes. How can I do this? (Short of
manually and laboriously exporting my local contacts and uploading them to
Google Contacts every time it has a few changes I don't like).

JQuery Post URL

JQuery Post URL

I have the following Jquery function
function refreshTheGrid(myData, ceduleDateFrom, ceduleDateTo, paramOrderNo) {
var myData2 = {
CeduleDateFrom: ceduleDateFrom,
CeduleDateTo: ceduleDateTo,
ParamOrderNo: paramOrderNo
};
var theUrl = "UpdateCheckBox";
var theUrl2 = "";
$.ajax({
type: "POST",
url: theUrl,
data: myData,
dataType: "text",
success: function (data) {
$.ajax({
type: "POST",
url: theUrl2,
data: myData2,
dataType: "text",
success: function (data) {
$('#monbouton').click();
}
})
}
})
popup.Hide();
void (0);
}
My Application is http://localhost/JprMvc/
when my POST Method are called the following is capture by Fiddler2
POST /JprMvc/CeduleGlobale/UpdateCheckBox HTTP/1.1
and
POST /JprMvc/ HTTP/1.1
I had a problem with the call until I removed the CeduleGlobale part from
my URL. Now everything works.
I think it's a routing problem, but I am not sure.
my routing is
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "CeduleGlobale", action = "Index", id =
UrlParameter.Optional } // Parameter defaults
);
It works now, but it seems arbitrary.
Should I remove the defaults from my routing and put it back in the jquery.
What am i missing ?

Is there a way to notify subscribers of changes made to a shared google calendar?

Is there a way to notify subscribers of changes made to a shared google
calendar?

Is there a way to notify subscribers of a calendar when changes are made?

Sunday, 18 August 2013

Using the Facebook API to populate the feed of a public page

Using the Facebook API to populate the feed of a public page

I've been looking quite all around the internet and I couldn't find a
solution that would help me with my very specific problem.
I own a website on which I post news regularly, and I created a Facebook
public page for the project of this website. I would like to populate the
feed of this public page each time I write some news using a Facebook app
I created for this purpose.
I just can't get to manage the connection between the website and this
Facebook page so that there is a new status update on the page every time
I write a news on the website. Like:
$c = new Connection();
$c->Execute("INSERT INTO news VALUES('', '" . $title . "', '" . $content .
"', '" . $author . "', '" . date('Y-m-d H:i:s') . "')");
$c->Close();
// What should I put there?
Is there some configuration I should make ? Some specific code using the
API so that it could access a public page?
Thank you all,
Stephane.P

jQuery UI tabs go back to selected tab after ajax response

jQuery UI tabs go back to selected tab after ajax response

Hi i add here the only neccsesry code ,
My succses of my ajax response :
success:
function(result){
if(result=='correct'){
window.location='editu.php';
}
So like you see i return back to page called editu.php after all correct
from the php post, In my editu.php i have jqueryUI tabs with 2 tabs like
that :
<div id="tabs">
<ul>
<li style="float:right;font-weight:bold;"><a href="#tabs-1">edit
admins</a></li>
<li style="float:right;font-weight:bold;"><a href="#tabs-2">edit
users</a></li>
</ul>
<div id="tabs-1" >
<?php foreach()... the admins list ?>
</div>
<div id="tabs-2" >
<?php foreach()... the users list ?>
</div>
</div>
So any idea how to go back to the same tab i was before and not the
defualt tab which is tab-1 ? I tought somthing of change this :
window.location='editu.php';
To somthing else like :
window.location='editu.php#jquiry UI tab-1';
Any idea? thanks allot.

How do I define a variable in a RSpec feature?

How do I define a variable in a RSpec feature?

Im learning Rails 4 and and trying to write some tests using Rspec and
capybara. Im writing a feature test for my users and I'm trying to test a
user signing in.
feature "User" do
scenario "A user signs in" do
let(:user) { FactoryGirl.create(:user) }
visit signin_path
fill_in "Username", with: user.username
fill_in "Password", with: "123456"
click_button "Log in"
expect(page).to have_content(user.username)
end
end
Its telling me that let is an undefined method. and I'm sure that the
problem is that it is in a feature/scenario test. How do I define the user
in this kind of test?
Also, in a describe/it request test like this
describe "Something" do
it "should do something" do
expect(page).to have_content{"...")
end
end
I can shorten it like this
describe "Something" do
subject { page }
it { should have_content("...") }
end
Is there a way to shorten the expect(page)..... in a scenario? Thanks.

Advertising on iOS and Android

Advertising on iOS and Android

Do Apple and Google allow third party advertisements such as from local
businesses who will pay or "donate" to put their image and link on the
app?

Configuring Webstorm to work with Nodejs

Configuring Webstorm to work with Nodejs

I have a problem with webstorm. That is, it does not autocomplete all the
time, I've managed my scopes well, so that is not the problem.
The thing is, whenever I try to access methods inside a nodejs app, the
only completion I get is exports. So, I can get express.exports.static,
but not express.static. How do I fix this?
I am using Webstorm 7 EAP.