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.

python mechanize cannot send a form on tumblr ask_form

python mechanize cannot send a form on tumblr ask_form

trying to automate sending a form to the ask_form (ask me anything) on
tumblr using : http://www.tumblr.com/ask_form/[site]
example: http://www.tumblr.com/ask_form/thinkpurplenae.tumblr.com
i have tried simply sending via br.submit() and
urlopen(br.click("ask_button")) but both end in an error (an error on the
tumblr site not in the script)
br.open('http://www.tumblr.com/ask_form/thinkpurplenae.tumblr.com'
br.select_form(nr=0)
br.form['post[one]']="blah blah"
l4=mechanize.urlopen(br.click(id="ask_button"))
l40=l4.read()
print l40
and i get
Error Sorry, we seem to be having technical trouble. Please try again later.
any idea what I can do to solve 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

How to prevent computer users from changing file permissions in the security tab. C#

How to prevent computer users from changing file permissions in the
security tab. C#

this is my first question in this website.
i am trying to prevent read/write access to a file (or folder) with C#.
The file is being locked as it is supposed to but the problem is that i
can easily go to the security tab abd change the permissions. How can i
prevent all computer users from changing these permissions ?
The Code i am using is this (Based on an article from MSDN) :
DirectorySecurity fs =
System.IO.Directory.GetAccessControl(textBox1.Text); fs.SetAccessRule(new
FileSystemAccessRule("Users", FileSystemRights.Modify |
FileSystemRights.ReadPermissions | FileSystemRights.TakeOwnership |
FileSystemRights.ChangePermissions, AccessControlType.Deny));
System.IO.Directory.SetAccessControl(textBox1.Text, fs);
Thank you in advance...
Rafael

Updating wpf parent window after some action on another window

Updating wpf parent window after some action on another window

i have one wpf window called usermanagement and there is a listbox showing
all the users, i have one button in usermanagement window called add user
and when i click on that new window opens called adduser, in this window
there are input fields to add new user, what i need when i save data and
this adduser window close then the usermanagement window update the
listbox, means users again update (the new added user should show there
after adding). at the moment i needed to open the usermanagement window
again to see the new added user. Thanks!

Friday, 30 August 2013

Removing pucntuation marks using ispunct()

Removing pucntuation marks using ispunct()

ispunct() words well when words are separated in this way "one, two;
three". Then it will remove ", ;" and replace with given character.
But if string is given in this manner"ts='TOK_STORE_ID';"then it will take
"ts='TOK_STORE_ID';" as one single token
or
"one,one, two;four$three two" as three tokens 1. "one,one" 2.
"two;four$three" 3. "two"
Is there any one so that "one,one, two;four$three two" could be considered
as "one one two four three two" each separate token?
Writing manual code like:
for(i=0;i<str.length();i++)
{
//validating each character
}
This operation will become very costly when string is very very long.
So is there any other function like ispunct()? or anything else?

Thursday, 29 August 2013

taskFactory: WCF service call and wait

taskFactory: WCF service call and wait

I'm calling a WCF service in my multi-threaded program. I'm in need of
calling a WCF service API, where I have to get a repeatedly call Five(or
3) times with a specified interval in-between (These are idempotent
operations, so I can call howmanyever times I want) untill I get a
response or Exception,maybe. How can I insert an interval in my thread so
that my control stays here. One option I is to have Thread.sleep(2000).
Is there any suggestions for doing this ? Thanks !
Also am having a taskFactory to maintain/run my threads.

merge 2 identical tables rows

merge 2 identical tables rows

I have 2 tables which have the identical columns. First table lets me
store the user's bills, and the second table stores the bill cancelation.
first table
-----------
id - total
-----------
1 - 100
2 - 85
3 - 50
second table
-----------
id - total
-----------
2 - 85
Result of JOIN
------------------------
id - total - status
------------------------
1 - 100 - OK
2 - 85 - OK
3 - 50 - OK
2 - 85 - CANCEL
How can I do get the above result?

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

java.lang.NoClassDefFoundError: Could not initialize class play.data.format.Formatters

java.lang.NoClassDefFoundError: Could not initialize class
play.data.format.Formatters

I'm using Play 2.1.2 and I want to use dynamic forms. I tried it in my own
small hello world project and everything worked fine, but when I use forms
in other bigger project I'm getting an exception. Here is my code (in both
project is the same):
Controller
public static Result signInForm() {
DynamicForm form = Form.form().bindFromRequest(); //exception on
this line
return renderJapid(form);
}
Routes
GET /sign-in
controllers.Authentication.signInForm()
When I go to localhost:9000/sign-in I get this exception:
Caused by: java.lang.NoClassDefFoundError: Could not initialize class
play.data.format.Formatters
at play.data.Form.bind(Form.java:320) ~[play-java_2.10.jar:2.1.2]
at play.data.DynamicForm.bind(DynamicForm.java:100)
~[play-java_2.10.jar:2.1.2]
at play.data.DynamicForm.bindFromRequest(DynamicForm.java:71)
~[play-java_2.10.jar:2.1.2]
at controllers.Authentication.signInForm(Authentication.java:310) ~[na:na]
at
Routes$$anonfun$routes$1$$anonfun$applyOrElse$19$$anonfun$apply$19.apply(routes_routing.scala:305)
~[na:na]
at
Routes$$anonfun$routes$1$$anonfun$applyOrElse$19$$anonfun$apply$19.apply(routes_routing.scala:305)
~[na:na]
Please, can you help me? Where could be the problem? I've checked
Global.java and application.conf in both projects but I didn't find
anything what could cause this problem.

function to extract ids and find and change background color

function to extract ids and find and change background color

Im making a function that will get innerHTML of textarea in an array and
then it will search ids in that array.For example innerHTML was
Football,Basketball, then that will be stored in an array and then ids
Football Basketball will be extracted from it and then ids with the name
football and basketball will have backgroundColor changed onpage load.Here
cluster is the textarea name.
window.onload = checkids;
window.onload = btnsInit;
var selected = {};//keeps list of selected links
var val="";
function checkids() {
var check=document.getElementById("cluster").value;
selected = check.split(',');
var j, i, a = document.getElementById('boxpopup').getElementsByTagName('a');
for(j=0;j < selected.length; j++) {
for(i=0;i < a.length ; ++i) {
if(selected[j]==a[i]) {
var x=a[i];
x.style.backgroundColor="#2BBBF3";
}
}
}
}
function btnsInit() {
var i, a = document.getElementById('boxpopup').getElementsByTagName('a');
for (i = 0; i < a.length; ++i) {
a[i].onclick = btnClick;
}
}
function btnClick(e) {
if (selected[this.id]) {
this.style.backgroundColor ="grey";
delete selected[this.id];//deleting if already been clicked
} else {
this.style.backgroundColor ="#2BBBF3";
selected[this.id] = this.id;//adding to the selected list
}
updateTextArea();
xPreventDefault(e);
return false;
}
function updateTextArea() {
var cluster = document.getElementById('cluster');
var val="";
for ( var id in selected) {
val += selected[id] + ",";
}
cluster.value = val;//updating from selected list
}
function xPreventDefault(e) {
if (e && e.preventDefault)
e.preventDefault();
else if (window.event)
window.event.returnValue = false;
}

Detecting Touch in a Div Box ? Javascript

Detecting Touch in a Div Box ? Javascript

Say I have setup a basic div like this :
<div id='signatureBox'></div>
I then want to register whenever the box is clicked on / touched in any
area. I am trying without success :
//Register signature callback
var signature = document.getElementById("signatureBox");
signature.onclick() = function () {
alert('signature JavaScript triggered');
}
Can anyone help ?
Thanks !

select all child div's in all parents div's

select all child div's in all parents div's

This is my code: I want to select all children classes
attribute(tbox,tarea,cts,tox) inside of all parent
var s = $('div.cts').children().attr('class');
alert(s);
but it showing only first parent first child class attribute
<fieldset id="tt">
<div class="cts">
<div class="tbox">
<input type="text"/>
</div>
</div>
<div class="cts">
<div class="tarea">
<input type="hidden">
</div>
</div>
<div class="cts">
<div class="tss">
<input type="password">
</div>
</div>
<div class="cts">
<div class="tox">
<input type="text">
</div>
</div>

Tuesday, 27 August 2013

Spring Injection with annotation

Spring Injection with annotation

How to perform Spring Injection with and ?
when we use then we do not have to specify our bean for controller so how
to give ref when we use .

How to pass the correct data to an OpenGL-ES 2.0 shader program Android

How to pass the correct data to an OpenGL-ES 2.0 shader program Android

I have a renderer which is an attempt to draw points as a textured square.
Nothing is crashing and I have other items being drawn fine, but these
squares are not being rendered, I believe it has something to do with data
passed to the shader program in my drawTexturedPoint() function.
I have a FloatBuffer geometryBuffer which holds the vertice positions. 6
vertices with exactly the same vertices coordinates, one for each corner
of the two triangles. There are multiple points within this buffer.
The shader program takes these vertices and manipulates them into the
correct position based on the point (or square) size passed to the shader.
protected String getPointVertexShader()
{
// Define a simple shader program for our points.
final String pointVertexShader =
"uniform vec2 u_pointSize;
+ "uniform mat4 u_MVPMatrix; \n"
+ "attribute vec4 a_Position; \n"
+ "attribute vec2 a_TexCoordinate; \n"
+ "varying vec2 v_TexCoordinate; \n" // Passed into the
fragment shader.
+ "void main() \n"
+ "{ \n"
+ " v_TexCoordinate = a_TexCoordinate; \n" // Pass through the
texture coordinate.
+ " gl_Position = u_MVPMatrix * a_Position; \n" //
gl_Position is a special variable used to store the final position.
+ " gl_Position += vec4(gl_Position.w * u_pointSize *
(a_TexCoordinate - vec2(0.5,0.5)), 0, 0);\n"
+ "} \n";
return pointVertexShader;
}
protected String getPointFragmentShader()
{
final String pointFragmentShader =
"precision mediump float; \n"
+ "uniform sampler2D u_Texture; \n" // The input texture.
+ "varying vec2 v_TexCoordinate;\n" // Interpolated texture coordinate
per fragment.
+ "void main() \n" // The entry point for our
fragment shader.
+ "{ \n"
+ " gl_FragColor = (texture2D(u_Texture, v_TexCoordinate));\n" //
Pass the color directly through the pipeline.
+ "} \n";
return pointFragmentShader;
}
Note that u_pointSize is a vec2 in normalised device coordinates; the
value should be the size in pixels divided by the viewport size in pixels.
Below is the function where it passes the data to the shader and does the
draw.
private void drawTexturedPoint(final FloatBuffer geometryBuffer)
{
//GeometryBuffer holds all the points in one buffer.
GLES20.glUseProgram(mPointsProgramHandle);
mPointSizeHandle = GLES20.glGetAttribLocation(mPointsProgramHandle,
"u_pointSize");
mPointMVPMatrixHandle =
GLES20.glGetUniformLocation(mPointsProgramHandle, "u_MVPMatrix");
mTextureUniformHandle =
GLES20.glGetUniformLocation(mPointsProgramHandle, "u_Texture");
mPointPositionHandle =
GLES20.glGetAttribLocation(mPointsProgramHandle, "a_Position");
mTextureCoordinateHandle =
GLES20.glGetAttribLocation(mPointsProgramHandle, "a_TexCoordinate");
// Pass in the texture coordinate information
mPointSize.position(0);
GLES20.glVertexAttribPointer(mPointSizeHandle, mVec2DataSize,
GLES20.GL_FLOAT, false, 0, mPointSize);
GLES20.glEnableVertexAttribArray(mPointSizeHandle);
// Pass in the position information
geometryBuffer.position(0);
GLES20.glVertexAttribPointer(mPointPositionHandle, mPositionDataSize,
GLES20.GL_FLOAT, false, mPositionFloatStrideBytes, geometryBuffer);
GLES20.glEnableVertexAttribArray(mPointPositionHandle);
// Pass in the texture coordinate information
mSquareTextureCoordinates.position(0);
GLES20.glVertexAttribPointer(mTextureCoordinateHandle, mVec2DataSize,
GLES20.GL_FLOAT, false, 0, mSquareTextureCoordinates);
GLES20.glEnableVertexAttribArray(mTextureCoordinateHandle);
GLES20.glUniformMatrix4fv(mPointMVPMatrixHandle, 1, false, mMVPMatrix,
0);
// Draw the cube.
GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0,
geometryBuffer.capacity()/mPositionDataSize);
}
Here are a few other relevant variables used in the draw function
private final int mBytesPerFloat = 4;
private final int mPositionOffset = 0;
private final int mPositionDataSize = 3;
private final int mPositionFloatStrideBytes = mPositionDataSize *
mBytesPerFloat;
private FloatBuffer mPointSize;
private final int mVec2DataSize = 2;
// Texture coordinate data.
final float[] squareTextureCoordinateData =
{
// Front face
0.0f, 0.0f,
0.0f, 1.0f,
1.0f, 0.0f,
0.0f, 1.0f,
1.0f, 1.0f,
1.0f, 0.0f
};
This is the way I set the square size (hard-coded for now).
float psize = 25f/480f;
mPointSize.position(0);
mPointSize.put(psize);
mPointSize.put(psize);
mPointSize.flip();
Be most greatful for some assistance!

fail2ban doesnt permanently block

fail2ban doesnt permanently block

Fail2ban doesn't seem to block permanently.
I have bantime =-1 but if i look a bit later on my iptables its just not
there anymore all ill see is
Chain fail2ban-ssh (1 references)
target prot opt source destination
RETURN all -- 0.0.0.0/0 0.0.0.0/0
Why is this happening if i set it to -1, is there something else i need to
configure?

Can Java Objects reinstantiate on their own?

Can Java Objects reinstantiate on their own?

I have a process in my application that uploads a document to my server
via a Servlet and waits for completion, the server then processes the file
using 2 threads, and keeps the Status while it is running.
This is how the Status class looks:
class Status implements Serializable {
private Integer read;
private Integer validated = 0;
private Integer processed = 0;
private Integer failed = 0;
public Status (int read) {
this.read = read;
}
/*
* Getter methods go here.
* No Setter methods.
*/
public void incrementValidated() {
synchronized(validated) { validated++; }
}
public void incrementProcessed() {
synchronized(processed) { processed++; }
}
public void incrementFailed() {
synchronized(failed) { failed++; }
}
}
Now, the server processes the file in this way:
A thread validates the read rows according to DB values, putting in a
queue those that are OK.
A thread waits until it has a batch of items in the queue, and then it
persists the batch of X items.
The Status is updated when the items are OK (incrementValidated), when the
items are persisted (incrementProcessed), and when an item is invalid
(incrementFailed). The Status stored in a ConcurrentHashMap<String,
Status>, where the key is the user's sessionID (because this process can
handle multiple requests).
While the process is running, the client is polling the server via Servlet
too, and all it does is return statusMap.get(sessionId); until the process
is complete.
My problem comes on files that run for too long, for example 5min. When it
is running and polling the server to get the status, sometimes all the
values are set back to 0, and the only value that stays the same is the
read property.
I'm not sure how is that possible, since the object has no setters, so all
I can imagine is that the object is being re-instantiated using the same
value on the constructor, and therefore keeping the same value.
Is that even possible? or am I missing something?
(it looks like the address changes when this happens)

Customise UIAlert View _bodyTextLabel text with NSAttributed String?

Customise UIAlert View _bodyTextLabel text with NSAttributed String?

My question is about Alert view. In my app I want to show a Disclaimer and
for this i'm using an UIAlertView. I used the delegate method of AlertView
and the NSAttributted String in my code, the problem is that i want to set
the Disclaimer message as colourful. The Title is customised but the
message doesn't have any effect.
Can any one help..! i posting the code.
http://i.stack.imgur.com/pCWVk.png
code:
//UIAlert View Method// -(void)willPresentAlertView:(UIAlertView
*)alertView {
UILabel *title = [alertView valueForKey:@"_titleLabel"];
UIColor *_green=[UIColor colorWithPatternImage:[UIImage
imageNamed:@"tab_strip@2x.png"]];
NSShadow *shadowDic=[[NSShadow alloc] init];
[shadowDic setShadowBlurRadius:5.0];
[shadowDic setShadowColor:[UIColor grayColor]];
[shadowDic setShadowOffset:CGSizeMake(0, 3)];
NSMutableAttributedString *attb_String=[[NSMutableAttributedString alloc]
initWithString:title.text];
[attb_String addAttribute:NSFontAttributeName value:[UIFont
fontWithName:@"HelveticaNeue-Bold" size:21.0] range:NSMakeRange(0, 1)];
[attb_String addAttribute:NSFontAttributeName value:[UIFont
fontWithName:@"HelveticaNeue-Bold" size:23.0] range:NSMakeRange(0,
title.text.length)];
[attb_String addAttribute:NSStrokeColorAttributeName value:_green
range:NSMakeRange(0, title.text.length)];
[attb_String addAttribute:NSStrokeWidthAttributeName value:[NSNumber
numberWithFloat:3.0] range:NSMakeRange(0, title.text.length)];
[attb_String addAttribute:NSShadowAttributeName value:shadowDic
range:NSMakeRange(0, title.text.length)];
[attb_String addAttribute:NSStrokeWidthAttributeName value:[NSNumber
numberWithFloat:-3.0] range:NSMakeRange(0, title.text.length)];
title.attributedText=attb_String;
UILabel *body = [alertView valueForKey:@"_bodyTextLabel"];
[body setAdjustsLetterSpacingToFitWidth:YES];
[body setAdjustsFontSizeToFitWidth:YES];
NSLog(@"body value=%d",body.text.length);
NSMutableAttributedString *attb_BodyString=[[NSMutableAttributedString
alloc] initWithString:body.text];
[attb_BodyString addAttribute:NSFontAttributeName value:[UIFont
fontWithName:@"HelveticaNeue-Bold" size:28.0]
range:NSMakeRange(0,body.text.length)];
[attb_BodyString addAttribute:NSStrokeColorAttributeName value:_green
range:NSMakeRange(0, body.text.length)];
// NSMutableParagraphStyle *paragrahStyle = [[NSMutableParagraphStyle
alloc] init]; // [paragrahStyle setAlignment:NSTextAlignmentCenter]; //
[attb_BodyString addAttribute:NSParagraphStyleAttributeName
value:paragrahStyle range:NSMakeRange(0, body.text.length)];
//[body setMinimumScaleFactor:15.0/body.font.pointSize];
//[body setLineBreakMode:NSLineBreakByWordWrapping];
body.attributedText=attb_BodyString;
}
and i also want to use the NSMutableParagraphStyle but it throws the error
"NSAttributedString invalid for autoresizing, it must have a single
spanning paragraph style (or none) with a non-wrapping lineBreakMode"

Why the python class method is different with it's object method but both of them have the same id?

Why the python class method is different with it's object method but both
of them have the same id?

While I'm studying the python attributes and methods, and read to the
Example 1.2. A function is more. I try to do a simple test base on the
example, but the result makes me a little confused.
>>> class foo(object):
... def fun(self):
... pass
...
>>> f = foo()
>>> f.fun is foo.fun
False
>>> id(f.fun)
36093064
>>> id(foo.fun)
36093064
>>>
python version, 2.7.5 operation sys, win8
Why the 'is' test return False but the id return the same value? I
expected to see the difference ids in the beginning. Thanks in advance!

Saving a dynamically generated image

Saving a dynamically generated image

So I made a script that works the way I want it etc
It basically generates an image based on 3 $_GET variables,
Name, font, image
It's using way too much resources generating the image each time so I
decided to save the image using this code:
imagepng($userbar, md5($name.$fontv.$image));
imagedestroy($userbar);
Now I face 2 issues:
1- The file saves in the directory where image.php is, I want it to be
saved in "/i/"
2- The file doesn't have the .PNG extensions, when ever I add .PNG it just
becomes ex: "dejddf9jf9dfpng"

Monday, 26 August 2013

uWSGI for running Python 2 and Python3 with django

uWSGI for running Python 2 and Python3 with django

I have uWSGI installed globally and it's running with a virtualenv of
Python 3.3 with Django just fine. But now I want to try running another
instance of uWSGI using Python 2.7. I set the option for home in the
virtualenv of Python 2.7 but the python version it's using is still 3.3
version.
Currently I have this settings for uWSGI:
# Django-related settings
# the base directory (full path)
chdir = /home/srvadmin/webapps2.7/geomuling
# Django's wsgi file
module = geomuling.wsgi
# the virtualenv (full path)
home = /home/srvadmin/py2.7
# process-related settings
# master
master = true
# maximum number of worker processes
processes = 10
# the socket (use the full path to be safe
socket = /tmp/mysite2.7.sock
# ... with appropriate permissions - may be needed
chmod-socket = 666
# clear environment on exit
vacuum = true
But I always get this
uWSGI http bound on 0.0.0.0:1234 fd 4
spawned uWSGI http 1 (pid: 31507)
uwsgi socket 0 bound to TCP address 127.0.0.1:33896 (port auto-assigned) fd 3
Python version: 3.3.2 (default, May 16 2013, 18:35:00) [GCC 4.6.3]
Set PythonHome to /home/srvadmin/py2.7/
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ImportError: No module named 'encodings'
Aborted

Hiding Media Source Links

Hiding Media Source Links

I inserted an image onto my page from my WordPress media (Add Media ->
Media Library -> Link To = None). However, when I right click on the page
to view the source, I noticed the address to my media. How do I hide this
address? I think its a security risk that the folder in which my WordPress
site lives in (my_renamed_wordpress_directory) is so easily visible. How
do I hide this? When I added the image, I selected Link To: None. Any
assistance will be appreciated. Thanks.
<a href="http://mysite.com/" target="_blank"><img
src="http://mysite.com/my_renamed_wordpress_directory/wp-content/uploads/2013/08/screenshot1.gif"
alt="screenshot1" width="320" height="197" class="alignnone size-full
wp-image-53" /></a>

Open File Using Windows 8 App with C#

Open File Using Windows 8 App with C#

I need to be able to open a PDF file with Visual C# so I can acquire its
filename and location and begin processing the application with that
information on startup (i.e., user can right-click and "Open with" the PDF
using my application). How can I go about accomplishing this? I took a
look at file associations on MSDN but it was a whole lot of what seemed
like unnecessary code to accomplish this with the sample, and I'm figuring
the solution is likely fairly simple. Thanks!

Shrinking a font

Shrinking a font

I'm looking for a possibility to horizontally shrink the font I use in my
whole document.
I do not only mean the tracking of the letters, but also (if possible) to
reduce the letter width by lets say 2%.
PS:
I tried the tracking of the "microtype" package, but it didn't work for
me, because I get tons of errors from my equations that won't compile any
longer, as soon as I \usepackage[...]{micropage}. Without that, everything
compiles fine.
! Extra \fi.
\MT@tr@outer@r@ ...er@next \relax \fi \fi \fi \fi
\fi \fi \fi \fi \fi \fi
\M...
l.35 ...rac{\epsilon_0\,k_B\,T_e}{\pi\,e^2\,n_e}}}
But tracking is anyway not really what I'm looking for, as I want to
shrink the whole font...
Also I can't rely on special fonts that allow for specific options that
would only work for that particular font...
Thanks a lot!

Change color font only in part of textview

Change color font only in part of textview

i want to change only a part of textview color.. I've tried in this way
but nothing change
TextView textView = (TextView)findViewById(R.id.Temperature);
textView.setText("Temperature: "+ "<small> <font color='#59c3fa'>" +
temperature + "°C</font></small>");
So the first part "Temperature: " has to have the textview color (Black in
this case), and the rest of part with this #59c3fa. How is wrong?

Extract socket id from websocket protocol in jmeter

Extract socket id from websocket protocol in jmeter

Can someone share me how to extract socket id via using Regular Expression
Extractor in Jmeter.

In Java How do I set my SOAP version in javax.xml.soap.SOAPConnection

In Java How do I set my SOAP version in javax.xml.soap.SOAPConnection

In this code .. I need to specify Soap Version 1.1 How do I do that:
" SOAPConnectionFactory soapConnectionFactory =
SOAPConnectionFactory.newInstance(); SOAPConnection soapConnection =
soapConnectionFactory.createConnection(); "
Thanks

Sunday, 25 August 2013

programming pic previews on the homepage and posts

programming pic previews on the homepage and posts

on my site:
http://www.travelwithcastle.com
i'd like to make two edits. any guidance is appreciated.
this site is a wp twentytwelve child theme.
1) i'd like to link the pics on the post previews on the homepage to the
actual post -- when i click the picture, in addition to when i click the
title text. right now, it only goes to the post if you directly click the
post title text. i'd like to also link the picture preview. does anyone
know how i can make the pic preview also be linked to the post?
2) this one's huge. i'd like to delete the enormous preview pic that shows
up on the actual post page at the top of the post. that pic is already
within the post content, and there is no need for me to have it up top as
well. to be clear, the picture i choose as the featured image for the post
(the one that shows up on the homepage preview) also shows up at the top
of the actual post, before the title. I'd like it not to be there since
it's already in the post content.
thank you very much

[ Politics ] Open Question : Why do some of the older generations call Generation Y the "entitlement" generation?

[ Politics ] Open Question : Why do some of the older generations call
Generation Y the "entitlement" generation?

When it's the Baby boomers who are taking everything for themselves and
once they are gone, we are left with the scraps. The baby boomers are the
ones who had pretty much everything handed to them (even social security),
but once Generation Y reaches retirement age, there won't be any
retirement.

Why is DBAL returning a SQL Syntax Error?

Why is DBAL returning a SQL Syntax Error?

I'm using Doctrine 2 along with CodeIgniter.
I'm having a query in some of my functions that trigger a SQL Error. And I
can't find the reason why
The function is the following:
private function _key_exists($key)
{
$this->CI->load->library('doctrine');
$em = $this->CI->doctrine->em;
echo "<br />Key : ".$key;
$key_object = $em->getRepository( 'Entity\Key' )->findOneBy(
array( 'key' => $key ) );
if( $key_object )
{
return TRUE;
}
else
{
return FALSE;
}
// return $this->db->where(config_item('rest_key_column'),
$key)->count_all_results(config_item('rest_keys_table')) > 0;
}
When Key ENtity is :
<?php
namespace Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Keys
*
* @ORM\Table(name="keys")
* @ORM\Entity
*/
class Key
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer", precision=0, scale=0,
nullable=false, unique=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="key", type="string", length=40, precision=0,
scale=0, nullable=false, unique=false)
*/
private $key;
/**
* @var integer
*
* @ORM\Column(name="level", type="integer", precision=0, scale=0,
nullable=false, unique=false)
*/
private $level;
/**
* @var boolean
*
* @ORM\Column(name="ignore_limits", type="boolean", precision=0,
scale=0, nullable=false, unique=false)
*/
private $ignoreLimits;
/**
* @var boolean
*
* @ORM\Column(name="is_private_key", type="boolean", precision=0,
scale=0, nullable=false, unique=false)
*/
private $isPrivateKey;
/**
* @var string
*
* @ORM\Column(name="ip_addresses", type="text", precision=0, scale=0,
nullable=true, unique=false)
*/
private $ipAddresses;
/**
* @var integer
*
* @ORM\Column(name="date_created", type="integer", precision=0,
scale=0, nullable=false, unique=false)
*/
private $dateCreated;
/* Getters and Setters ... */
}
And the error message is :
Doctrine\DBAL\DBALException: An exception occurred while executing 'SELECT
t0.id AS id1, t0.key AS key2, t0.level AS level3, t0.ignore_limits AS
ignore_limits4, t0.is_private_key AS is_private_key5, t0.ip_addresses AS
ip_addresses6, t0.date_created AS date_created7 FROM keys t0 WHERE t0.key
= ? LIMIT 1' with params {"1":"0fedfa4d50653317df76a4dba79f9f07cd7a8273"}:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error
in your SQL syntax; check the manual that corresponds to your MySQL server
version for the right syntax to use near 'keys t0 WHERE t0.key =
'0fedfa4d50653317df76a4dba79f9f07cd7a8273' LIMIT 1' at line 1 in
E:\Programmes\wamp\www\myapp\application\libraries\Doctrine\DBAL\DBALException.php
on line 47
I do see : Key : c242c67787bd0b9a9b11a54fc942fde50f099235 in the output
though
Many thanks for your help

ido move files from dired

ido move files from dired

Is it possible to use ido to move files from dired? When I type C
dired-do-copy it shows the ido completion list. But when I type R
dired-do-rename it's the default Emacs directory completion.
I see this line in ido.el:
(put 'dired-do-rename 'ido 'ignore)
If I can copy from dired, I don't see why I shouldn't rename.

Should you avoid Guavas Ordering.usingToString()?

Should you avoid Guavas Ordering.usingToString()?

This question was prompted after reading Joshua Bloch's "Effective Java".
Specifically in Item #10, he argues that it is bad practice to parse an
object's string representation and use it for anything except a friendlier
printout/debug. The reason is that such a use "is error-prone, results in
fragile systems that break if you change the format". To me it looks like
guava's Ordering.usingToString() is a spot on example of this. So is it
bad practice to use it?

Saturday, 24 August 2013

Add class of column number using Masonry

Add class of column number using Masonry

Hopefully this will make sense as it's quite hard to explain but I'll give
it a shot.
Basically I was wondering if i can apply a class that contains the column
number the Masonry item is sitting in. For example if there was a two
column layout then all items that are in the left column would have a
class of 1 and all items in the right column would have a class of 2. Can
this be done?
Thanks

Directory.GetFiles() removes dashes from filenames?

Directory.GetFiles() removes dashes from filenames?

My debug output takes the values straight from this in the loop and shows
me the raw data coming from Directory.GetFiles(). It is showing what I
expect, except that one file has a dash in its name that it is removing
for no reason. As a result the program can't access the file because it
triggers an IO exception.
I mean really? What genious at microsoft thought he could get away with
removing chars from file names and not break stuff? This makes no sense
and looks like just plain stupidity from where I'm sitting.
The code is a simple for loop iterating over the results of
Directory.GetFiles(). It dumps each str from GetFiles() straight into the
debug stream without doing anything whatsoever to it. I have no idea why
it is removing the dash for no reason, but the debug output proves that
Directory.GetFiles() is doing it.

HTML Dreamweaver Left Margin

HTML Dreamweaver Left Margin

Im trying to create a website using dreamweaver but i am having a small
problem with a margin being created on the left which is like a white
gap.I have tried to set left margin to 0 using CSS but no luck
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
.Header {
background-attachment: scroll;
background-color: #FFF;
background-image: url(Background/images/images/Untitled-1_01.gif);
background-size: cover;
background-repeat: no-repeat;
height: 48px;
width: 100%;
position: fixed;
top: 0px;
background-position: center;
margin-left: 0px;
}
.Wrapper {
background-color: #FFF;
height: auto;
width: auto;
margin-left: 0px;
}
</style>
</head>
<body>
<div class="Wrapper">
<div class="Header"></div>
<div>
</div>
<p>d sdsd </p>
<p>&nbsp;</p>
</div>
</body>
</html>

Can I call a function inside mysql query?

Can I call a function inside mysql query?

can I call a function inside an MySQL Query? To ask more elaborately
consider I have a function which returns the account_id of the customer
int return_account_id(){
return (account_id);
}
Now can I call this function inside my query ? Is it possible ?
`resultset = statement->executeQuery("SELECT `account_id`, `acc_name` FROM
`account` WHERE `account_id` = "return_account_id()" ");

Having hash map (get by key) like in java in PHP?

Having hash map (get by key) like in java in PHP?

Well I've thought of having ArrayList in PHP because it was extremely
useful in PHP, and saving a lot of time.
I thought it'd be cool to have in PHP, so I did make an arrayList class in
PHP:
Class ArrayList
{
public $arrayList;
function __construct()
{
$this->arrayList = array();
}
public function add($element)
{
$this->arrayList[] = $element;
}
public function remove($index)
{
if (is_numeric($index)) {
unset($this->arrayList[$index]);
}
}
public function get($index)
{
return $this->arrayList[$index];
}
}
Now, I noticed I need an list type more of a hashmap, so I can get items
by keys. Let's say I need to get mysql db name, so Ill just do
$data->hashmap->get("db_name"). This will return the database name value.
Is there a way to do this?

What is the best way to copy a remote OpenVZ container to a local location, is it possible?

What is the best way to copy a remote OpenVZ container to a local
location, is it possible?

I rent an OpenVZ container, but I don't have much access to any tools, I
can reboot, change my root password, reinstall and create backups. Thats
about it! The backups from what I can see is just so that I can use on the
remote system. If I want any advanced features, then I'm going to have to
pay for them, which I'm not prepared to do.
What I would like to have is an image or a copy of my remote server that I
could use to install locally.
What is the best way to do this? It would have to be a solution that does
not require a gui.
Thanks

jsf ajax rendered does not work

jsf ajax rendered does not work

I would like to ask why partial rendering for primefaces does not work.
POST requests are keeping sent, but it does not rerender.
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<p:messages />
<h:form>
<table style="width: 100%">
<tr>
<td><p:outputLabel for="inp1" value="S1" /></td>
<td>
<p:inputText id="inp1" value="#{form.e.s1}">
<p:ajax process="inp1" update="msg1"
event="keyup" />
</p:inputText>
<p:watermark for="inp1" value="Wpisz S1" />
<p:message for="inp1" id="msg1" />
</td>
</tr>
<tr>
<td>Toolbox</td>
<td>
<p:selectBooleanCheckbox id="inpToolbox"
value="#{form.toolbox}">
<p:ajax process="inpToolbox"
update="toolboxOptions" />
</p:selectBooleanCheckbox><br />
<p:panel id="toolboxOptions"
rendered="#{form.toolbox}">
Name: <p:inputText
value="#{form.toolboxDescription}" /><br />
Number: <p:inputText value="#{form.toolboxNr}"
/><br />
</p:panel>
</td>
</tr>
</table>
<p:commandButton action="#{form.save}" ajax="false"
value="Save" />
</h:form>
</h:body>
</html>
I have no idea, why it should not work. I want every time changes the
toolbox value to show the additional information form about toolbox

What can I substitute fennel pollen with?

What can I substitute fennel pollen with?

In this simple spaghetti recipe, fennel pollen is used. From googling it,
it sounds like MSG :). I'd rather not buy it since it's so expensive, so
is there any way to substitute this stuff in the recipe?

unit-tests for an API and usage samples of that API

unit-tests for an API and usage samples of that API


Where can I find some well tested APIs? I need some which are tested with
JUNIT3.5 or above. Then, I need some open-source projects which use those
APIs.

In fact, I need to have some unit-test cases of an API and also some
examples that shows the way that API is used in production code.

Friday, 23 August 2013

Android emulator stopped unexpectly

Android emulator stopped unexpectly

I have the following code in my post_item.java file
package com.iwantnew.www;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class post_item extends Activity {
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
Button add_room;
EditText contact_no;
EditText no_of_room;
EditText price_per_room;
EditText description;
private static String url_create_product =
"http://10.0.2.2/android_iwant/android_add_room.php";
private static final String TAG_SUCCESS = "success";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.post_form);
//contact_no = (EditText) findViewById(R.id.contact_no);
no_of_room = (EditText) findViewById(R.id.no_of_room);
price_per_room = (EditText) findViewById(R.id.price_per_room);
//description = (EditText) findViewById(R.id.description);
contact_no = (EditText) findViewById(R.id.contact_no);
add_room = (Button) findViewById(R.id.add_room);
add_room.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// creating new product in background thread
new add_new_room().execute();
}
});
}
// suru...
class add_new_room extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(post_item.this);
pDialog.setMessage("Saving details..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
//String contact = contact_no.getText().toString();
String quantity = no_of_room.getText().toString();
String price = price_per_room.getText().toString();
//String contact = contact_no.getText().toString();
String descriptions = description.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
//params.add(new BasicNameValuePair("contact", contact));
params.add(new BasicNameValuePair("quantity", quantity));
params.add(new BasicNameValuePair("price", price));
params.add(new BasicNameValuePair("descriptions", descriptions));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(),
MainActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
i have the following in my php file.
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['quantity']) && isset($_POST['price'])) {
//$location = $_POST['location'];
$quantity = $_POST['quantity'];
$price = $_POST['price'];
//$productID = $_POST['area'];
//$contact = $_POST['contact'];
$descriptions = $_POST['descriptions'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO
room_tb(uid,categoryID,quantity,price,description)
VALUES(5,1,'$quantity','$price','$descriptions')");
//$result1 = mysql_query("INSERT INTO users(userContactNumber)
VALUES('$contact')");
// check if row inserted or not
if($result)/*&& ($result1)*/ {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Room added successfully.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
whenever i send description or contact number to the database...the
android emulator says unexpectedly stopped working and no records enters
the database..but if i only pass the quantity,price,categoryID and uid
then no error occurs and record goes to the database. what have i done
wrong?

Laravel 4 form data submit and update the database and also send an email with the help of post data.

Laravel 4 form data submit and update the database and also send an email
with the help of post data.

Here what I am trying to do is. There is a form with 3 text fields and I
have to submit that form so that I can retrieve the form post data and
send mail to the recipients. But I need to store the post value in the
variable and I can use these variables to update the database and as well
as sending an email with this data.
If someone could help me with this. It would be of great help.
I'm getting this error Symfony \ Component \ HttpKernel \ Exception \
MethodNotAllowedHttpException
Routes.php:
<?php
Route::get('mail,new',array('as' => 'new_mail' , 'uses' =>
'sendmail@new' ));
Route::post('formtest/submit','sendmail@create');
Route::get('sendmail', function(){
$data = array('detail' => 'email' );
$body = 'body here';
$recipients = 'abc@a.com,def@xyz.com';
$subject = 'test mail';
$date = new DateTime();
$d = $date->format('U = Y-m-d H:i:s');
Mail::queue('emails.sendmail', $data, function($message)
{
$message->to('abc@ymail.com', 'Pradeep G')->subject('test
--mail');
});
DB::table('sentmail')->insert(
array('recipients' => $recipients, 'subject' => $subject,
'body'=>$body, 'created_at'=> $d, 'updated_at'=> $d )
);
return View::make('emails.sent');
});
Here are the files
Routes.php http://paste.laravel.com/LuO
Controller: controllers/Sendmail.php http://paste.laravel.com/LuN
views/home/ftest.blade.php
http://paste.laravel.com/LuM
Model : models/Sendmail.php http://paste.laravel.com/LuQ

Bash script containing binary executable

Bash script containing binary executable

Is it possible to write a bash script, which would contain a binary
executable program inside?
I mean a script, which would contain a dump of an executable in a textual
form, which will be dumped back to an executable by this script when it is
executed?
I would love to know a solution, which will work out of the box without a
need of installing additional packages. Is it possible?
Thanks!

Sorting List(Of MaskedTextBox)

Sorting List(Of MaskedTextBox)

The list Private msklistclass1 As New List(Of MaskedTextBox) contains
following MaskedTextBox controls
seat112
seat212
seat312
seat412
seat512
seat612
seat122
seat222
seat322
seat422
seat522
seat622
but they aren't in the order I have shown above I suppose. When I try to
assign values to these controls in a sequential manner they don't get
assigned in an order.
I tried the following code
For i = 0 To 11 Step 1
msklistclass1(i).Text = rno312(i)
Next
Is there a possibility to sort the list msklistclass1

Applescript - move files to folder which name begins with first 7 characters of filename

Applescript - move files to folder which name begins with first 7
characters of filename

I've got 2 folders
the first folder contains all the files which I'd like to move to a
subfolder of the second folder. I'd like to this based on the first 7
characters of both the file & folder names.
So if the first 7 characters of the subfolder in FOLDER 2 matches the
first 7 characters of the file in FOLDER 1. The file get's moved into the
subfolder of FOLDER 2
Right now I've got an Applescript which works, but it's terribly slow.
Here's the script so far:
set mgFileList to ""
set mgDestFolder to ""
set mgFilesFolder to (choose folder with prompt "Where are the files
stored which you would like to move to the destination?")
set mgDestFolder to (choose folder with prompt "Where is the destination
folder?")
tell application "Finder" to set fileList to files of mgFilesFolder
repeat with aFile in fileList
set prefix to getPrefix(name of aFile)
tell application "Finder"
try
set destinationFolder to (do shell script "find " & quoted form of
(POSIX path of mgDestFolder) & "-name '" begins with prefix)
move aFile to destinationFolder
end try
end tell
end repeat
on getPrefix(aName)
set prefix to text 1 thru 7 of aName
return prefix
end getPrefix
I've only recently got into Applescripting. Can this be done more
efficiently within Applescript? I've searched around for a solution which
works with a shell script (which I think will probably be a lot faster),
but haven't been able to get any of them working.
I'm working on OSX Mountain Lion 10.8.4

Thursday, 22 August 2013

disable function using jQuery

disable function using jQuery

I'd like to disable a javascript function (dialogs()) using jQuery.
What I thought to do was:
Wrap the function in a span: "<span class = 'auto'>" + dialogs(i,0); +
"</span>"
If the checkbox is checked, do: (this if statement is in
$(document).ready(function(){)
if ($("#autodialog").is(":checked")) {
$(".auto").remove(); }
But this doesn't seem to be working.
Any thoughts?

Watch New England Patriots vs Detroit Lions live Streaming NFL 2013 Online free HD TV PC

Watch New England Patriots vs Detroit Lions live Streaming NFL 2013 Online
free HD TV PC

Watch New England Patriots vs Detroit Lions live Streaming NFL 2013 Online
HD TV PC.Watch live NFL Football, NFL Preseason Week 3, NFL Preseason Week
3 online, New England Patriots vs Detroit Lions live tv coverage, New
England Patriots vs Detroit Lions live p2p, New England Patriots vs
Detroit Lions live streaming, New England Patriots vs Detroit Lions live
broadcast TV, New England Patriots vs Detroit Lions TV On PC, watch NFL
online, New England Patriots vs Detroit Lions Football highlights.
Watch NFL Live Here@ http://goo.gl/kYJBC7
Watch NFL Match New England Patriots vs Detroit Lions live stream
Preseason Week 3 online on pc here. Just follow our streaming link and
Enjoy New England Patriots vs Detroit Lions live stream Free NFL Game
Online HD on your Pc.Are you love watching live National Football League
games? Are you finding it difficult to get to a TV or come up with the
costly payments for cable TV? Or are you working abroad and don't have
access to all the best NFL games that you want to see?If you answered yes
to any of these questions then you have come to the perfect
place.SatelliteDirect™ is your home for all the live NFL football action
that you want and crave. Click Here To Watch Live NFL Football 2013-14 New
England Patriots vs Detroit Lions live Streaming Link Watch NFL Live Here
MATCH DETAILS Preseason Week 3: Competition: NFL Preseason 2013-14 DATE:
Tuesday, August 22 2013 Kick-off Time: 07:00 pm ET Live / Repeat: Live*
Channel: FOX Don't worry,it is too easy to watch.just try it.
Watch NFL Live Here@ http://goo.gl/kYJBC7
We Ensure that you must be 100% satisfied in our service. So don't be
hesitated, just click the link bellow and start watching and enjoy FULL
SEASON +more.Best of luck. You Can enjoy all US Games like NFL, NCAAF,
MLB, NFL, NASCAR, UFC, SOCCER, BOXING, FORMULA ONE, etc live streaming
online From any location!Get instant access and most exciting sports tv
coverage live online directly on your PC.Download and install our software
and enjoy all the pleasures of the sporting world comfortably like you are
at the stadium and watching the match New England Patriots vs Detroit
Lions live of NFL Preseason 2013. Click Here New England Patriots vs
Detroit Lions Live Instant Watch Watch Football Live Online Watch live NFL
Football, NFL Preseason Week 3, NFL Preseason Week 3 online, New England
Patriots vs Detroit Lions live tv coverage, New England Patriots vs
Detroit Lions live p2p, New England Patriots vs Detroit Lions live
streaming, New England Patriots vs Detroit Lions live broadcast TV, New
England Patriots vs Detroit Lions TV On PC, watch NFL online, New England
Patriots vs Detroit Lions Football highlights.

How does ConcurrentQueue work?

How does ConcurrentQueue work?

How does it work?
I know that, you put a type in, and then you can receive it on another
thread, and also get a bool at the same time.
But what i don´t get it, how does it send the item?
for example, in Thread 1, i have a byte array in which i write some data,
then put it into a Queue.
Then Thread 2, will use TryDequeue(out byte[]) to receive it. How does
this work?
As TryDequeue, will have to write it to another byte[], so i am guessing,
it´s doing some kind of copy?
Meaning, if the byte[] that Thread 1 is writing to is public, Thread 2 can
read to it faster/better as it doesn´t have to be copied?
Though the problem is that it doesn´t know when it´s allowed to read.

DECODE with NULL values

DECODE with NULL values

i want to insert ZEROS or Spaces when the value is NULL
i tried for small column length and it worked:
INSERT INTO ABCTABLE (COLUMN1)
VALUES ('DECODE(MDSE_CD,NULL,''000'',LPAD(TO_NUMBER(MDSE_CD,''3'','' ''))');
But how do i execute the second query that has around 400 column length:
INSERT INTO ABCTABLE (COLUMN1)
VALUES ('DECODE(MDSE_CD,NULL,''see notes
below'',LPAD(TO_NUMBER(MDSE_CD,''400'','' ''))');
Note:How do i insert 400 zeros or spaces when the column is NULL

How I get data from "third" related model in django?

How I get data from "third" related model in django?

Hi guys,
I have this models:
class Pais(models.Model):
nome = models.CharField('Nome', max_length=50)
class Brinq(models.Model):
descricao = models.CharField('Nome', max_length=50)
class Filhos(models.Model):
nome = models.CharField('Nome', max_length=50)
idade = models.IntegerField('Idade')
pai = models.ForeignKey('Pais')
brinq = models.ForeignKey('Brinq', related_name='Brinq')
This view:
def editPai(request, idpai=None):
if idpai:
pai = Pais.objects.get(id=idpai)
else:
pai = None
ItensInlineFormSet = inlineformset_factory(Pais, Filhos,
form=FilhosForm, extra=1)
formPais = PaisForm()
formsetItens = ItensInlineFormSet(instance=pai)
return render_to_response("base.html", {
"formPais": formPais, "formsetItens": formsetItens
}, context_instance=RequestContext(request), )
and this forms:
class PaisForm(ModelForm):
class Meta:
model = Pais
class FilhosForm(ModelForm):
class Meta:
model = Filhos
Ok, How can I get "descricao" value from "Brinq" model in my template? I
think it's a simple question but, I tried looking, looking and looking
again from internet and I don't find anything about this.
I start to thing it's not possible to do it using django, I want to
believe that I'm wrong, but as I said, I didn't find anything about this
in internet.
I try:
{% for form in formsetItens %}
<tr>
<td> {{ form.nome }}</td>
<td> {{ form.idade }}</td>
<td> {{ form.brinq__descricao }}</td>
</tr>
{% endfor %}
and to, and nothing... :(
Can anyone help me with this problem?
Regards,

create only file permission on linux

create only file permission on linux

I would like to create a directory under linux (or mount one e.g.: nfs),
where:
every user can create files
but only the root user can modify the created files (overwrite, delete, or
move them)
How can this be done, and how secure are these solutions? (for example:
sentinel script, umask, etc.?)
Thanks, krisy

How to implement passing of variable from one service method to another angular

How to implement passing of variable from one service method to another
angular

Hi to all angular guru,
My question is how to pass the return result of one service method to the
other methods. Or to make it short I have an authentication method in my
service, the return object result for this is a token. The token will be
used to be append in my header for the rest of my http request which
reside on the same service.
E.g
my Service js
authenticatePlayer: function(postData) {
return $http({
method : 'POST',
url : api + 'auth/player',
data : postData,
headers : {'Content-Type' : 'application/json'}
})
.then(function(result) {
return result.data.token; //this is now the token
}, function (result) {
console.log(result);
});
}
within the Service js, I have other $http request such as:
getPlayerByEmail: function(email_address) {
return $http({
method : 'GET',
url : api + 'player/' + email_address,
headers : {'X-token': token}
//token here is from the authenticatePlayer method but how to
get it??
})
.then(function(result) {
return result.data;
});
}
The two services methods are called in two controllers, my extended
question is how to you pass the $scope from one controller to another that
even when the page is refreshed the $scope value won't be destroy.
Hope it make sense.

Wednesday, 21 August 2013

Entire Function Problem in Complex Analysis

Entire Function Problem in Complex Analysis

I am currently working on some review problems in complex analysis and
came upon the following conundrum of a problem.
"If $f(z)$ is an entire function, and satisfies $|f(z^2)|\le|f(z)|^2$,
prove that f(z) is a polynomial."
My intuition tells me to show that f(z) has a pole at infinity by showing
that infinity is not an essential or removable singularity. However, I am
getting stuck after this.
Thanks for the help,

A partition is necessary before installing ubuntu on windows 7?

A partition is necessary before installing ubuntu on windows 7?

Im trying to install Ubuntu on my PC that runs Windows 7. Do I need to
make a partition before installation?

CSS element extruding outside of fixed width main container causing background color to cut off

CSS element extruding outside of fixed width main container causing
background color to cut off

I have a 2-tone design the top container is at 100% width and has a bg
color of blue.
The lower part of the page has a bg color of white.
The content width of the site is at 960 with 20px of padding on each side
so total 1000px.
My problem is this map on the homepage only that extrudes outside of the
constraints of the 1000px (by design btw).
When i reduce the browser width and scroll horizontally the top container
with 100% width cuts off the bg color and it's due to the map container.
So i believe that has isolated the problem.
The solution now lies in how to make the map container extrude the main
body width constraints without causing the bg color on the top container
to cut off when the browser window is reduced and the user scrolls
horizontally?
Here is a screencast showing the issue.
Here is a codepen with the code.
Any ideas or helpful would be much appreciated.
Thanks.

Android : RSA Encrypt and Decrypt but when call it error

Android : RSA Encrypt and Decrypt but when call it error

I am implementing for RSA Encryption and Decryption in Android. I can
Perform Encryption(publickey) very well.But In Decryption (privatekey) I
got an Exception..
java.security.spec.InvalidKeySpecException:java.lang.RuntimeException:error:0D0680A8:an1
encoding routines:ASNl_CHECK_TLEN:wrong tag
when i call this function
try
{
encrypt_text.setText(decrypt(filecopy1,text_cipher));
}
catch(Exception e)
{
e.printStackTrace();
Toast.makeText(getBaseContext(),
e.toString(),Toast.LENGTH_LONG).show();
System.out.println("Exception is>>"+e);
}
public static String decrypt(String filePath1, String encrypted)
throws IOException, NoSuchAlgorithmException,
InvalidKeySpecException,NoSuchPaddingException, InvalidKeyException,
IllegalBlockSizeException, BadPaddingException {
InputStream stream = new FileInputStream(filePath1);
byte[] encodedKey1 = new byte[stream.available()];
stream.read(encodedKey1);
X509EncodedKeySpec publicKeySpec1 = new X509EncodedKeySpec(encodedKey1);
KeyFactory kf1 = KeyFactory.getInstance("RSA");
PublicKey pkPublic1 = kf1.generatePublic(publicKeySpec1);
Cipher pkCipher1 = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
pkCipher1.init(Cipher.DECRYPT_MODE, pkPublic1);
byte[] decoded = Base64Coder.decode(encrypted);
byte[] decryptedInByte = pkCipher1.doFinal(decoded);
return new String(decryptedInByte);
// return encrypted;
}
import a privatekey.when i call will give them above pic. thank in advance.

How to activate Completion Insight in JDeveloper IDE

How to activate Completion Insight in JDeveloper IDE

Can someone please direct me to how i can activate Completion Insight in
JDeveloper(12) IDE so that i can get help from Javadoc and/or ADF Faces in
editor window

+/- equation with a single textfield

+/- equation with a single textfield

I am making a very simple storage system, and i want to make it so that
the user puts a number in the box, and press the + or - button, to add or
subtract.

I don't know if it's even possible to do it, as simple as i wanted it to
be :) but anyway, here is the code so far for index.php
<?php $v_stk = "v_stk" ?>
<form action="index_sql.php" method="POST">
<input name="v_id" type="hidden" value="<?php echo $v_assoc["v_id"]
?>" />
<input name="v_stk" type="textfield" size="8" />
<input name="+" type="submit" value="+" style="height:23px;
width:35px;" />
<input name="-" type="submit" value="-" style="height:23px;
width:35px;" />
</form>
<td class="width50 sidepadding">
<?php echo $v_assoc["v_stk"]; ?></td>
<?php }; ?>
and here is for index_sql.php
<?php
require("db/db.php");
$v_id = mysql_real_escape_string($_POST["v_id"]);
$v_stk = mysql_real_escape_string($_POST["v_stk"]);
$sql = mysql_query("SELECT v_stk FROM vare WHERE v_id = '$v_id'");
$assoc = mysql_fetch_assoc($sql);
$v_nu = $v_stk + $assoc;
mysql_query("UPDATE vare SET v_nu = '$v_stk' WHERE v_id = '$v_id'");
header("location: index.php");
?>
I don't know if it is remotely close to something that would work, but
with this code it gives me: Fatal error: Unsupported operand types in
C:\wamp\www\lager\index_sql.php on line 8

Tuesday, 20 August 2013

Dart, Is it possible to pass on the members of an interface implicitly?

Dart, Is it possible to pass on the members of an interface implicitly?

In Dart I have a class:
class A implements Iterable<MyType>{
List<MyType> children;
//other members for A class
}
Is it possible, without using noSuchMethod, to implicitly forward all of
the Iterable<MyType> methods to the List<MyType> children; member?

Need javascript to open site in new window

Need javascript to open site in new window

I need to adjust this script so that when u click on the slideshow, it
opens another site in a new window. I'm not a programmer; I'm using a
given code. Currently, the site opens within the slideshow boundary,
showing only a portion of the site. If someone can please help, here is
the current code. Thanx in advance!!!:
http://fineartamerica.com/Blank.jpg' style='width: 400px; height: 400px;
padding: 0px; margin: 0px; border: 1px solid #666666; cursor: pointer;
cursor: hand;' alt='Art Prints' title='Art Prints'>

NoReserveMatch error when passing multiple parameters to template

NoReserveMatch error when passing multiple parameters to template

I'm getting a NoReverseMatch error:
Reverse for 'state' with arguments '('', '')' and keyword arguments '{}'
not found.
I have 2 ids being passed to the template and that seems to be the problem.
views.py
def state(request, country_id, state_id):
countrystate = State.objects.all()
return render_to_response("template.html", {'countrystate':
countrystate})
urls.py
url(r'^my_index/(?P<country_id>\d+)/state/(?P<state_id>\d+)/$',
'my_App.views.state', name='state'),
template.html
<form class="option_form" action="{% url "state" country.id state.id %}"
method="post">
any ideas?

No left border to the right of certain class

No left border to the right of certain class

Is there any way to specify with CSS to disable a left-border to the right
of a cell with a certain class?
As you can see in this image the border to the right is double, it has the
border of class "selected" plus the default gray border. I want the
"selected" cell's right border to override the neighboring cell's
left-border somehow.
FWIW, I think this is because of the table's CSS where I have commented
'border-collapse'. I need to do this otherwise I can't have rounded
corner's on the table.

.ui-tabs-panel td { /* default table cell */
border-bottom: 1px solid #E9EBDF;
border-left: 1px solid #E9EBDF;
padding: 7px 7px;
font-family: Tahoma;
cursor: default;
background-color: #FAFDFF;
}
.ui-tabs-panel td.selected { /* when selected */
border-right: 1px solid #94DFEB !important;
border-left: 1px double #94DFEB !important;
background-color: #FFF !important;
color: #087DBD;
}

Access denied for user root - mysql on MAC OS

Access denied for user root - mysql on MAC OS

I know how do skip this problem on ubuntu, but how can i do it on MAC OS?
mysqld --skip-grant-tables --skip-networking &
doesn't work and even more - it block console with mass of errors.
How can i set password for mysql on MAC?

How to convert wstring into byte vector

How to convert wstring into byte vector

Hi I have a few typedefs:
typedef unsigned char Byte;
typedef std::vector<Byte> ByteVector;
typedef std::wstring String;
I need to convert String into ByteVector, I have tried this:
String str = L"123";
ByteVector vect(str.begin(), str.end());
As a result vectror contains 3 elements: 1, 2, 3. However it is wstring so
every charcter in this string is wide so my expected result would be: 0,
1, 0, 2, 0, 3.
Is there any standart way to do that or I need to write some custom function.

Doctinre 2 DQL Reverse LIKE query

Doctinre 2 DQL Reverse LIKE query

I'm trying to do a "simple" LIKE in DQL but i'm getting an error:
[Syntax Error] line 0, col 55: Error: Expected =, <, <=, <>, >, >=, !=, got
'LIKE'
DQL:
SELECT t.valeur FROM Bundle:Table t WHERE 'abc' LIKE CONCAT('%',
t.value, '%')
It is working when i switch LIKE side but that's not what i'm expecting.
Is this possible in DQL or should i do in natively ?

Monday, 19 August 2013

Run/Execute CasperJS script by clicking a button on webpage

Run/Execute CasperJS script by clicking a button on webpage

I have a casperJS script which returns a JSON when run on commandline. I
want to have an arrangement such that 1) I create a webpage 2) On clicking
a button on the webpage the casperJS scripts gets executed and post/return
the result back to the webpage.
How can i do the same.

Smarter routing in Laravel 4

Smarter routing in Laravel 4

Does anyone know of any way in Laravel 4 which combines these 2 lines into
one?
Route::get('login', 'AuthController@getLogin');
Route::post('login', 'AuthController@postLogin');
So instead of having to write both you only have to write one since their
both using the 'same' method but also the URL remains as site.com/login
instead of a redirect to site.com/auth/login?
I'm curious since I remember CI has something like that where the url
remains the same and the controller is never shown:
$route['(method1|method2)'] = 'controller/$1';

Preferred method for controlled logging of Python debug messages?

Preferred method for controlled logging of Python debug messages?

I'm writing a large hardware simulation library in Python3. For logging, I
use the Python3 Logging module.
For controlling debug messages with method-level granularity, I learned
"on the street" (ok, here at StackOverflow) to create sub-loggers within
each method I wanted to log from:
sub_logger = logging.getChild("new_sublogger_name")
sub_logger.setLevel(logging.DEBUG)
# Sample debug message
sub_logger.debug("This is a debug message...")
By changing the call to setLevel(), the user is able to enable/disable
debugging messages on a per-method basis.
Now the Boss Man don't like this approach. He's advocating a single-point
at which all logging messages in the library can be enabled/disabled with
the same method-level granularity. (This was to be accomplished by writing
our own Python logging library BTW).
Not wanting to re-invent the logging wheel, I proposed to instead continue
to use the Python Logging library, but instead use Filters to allow
single-point control of logging messages.
Having not used Python Logging Filters very often, is there a consensus on
using Filters vs Sublogger.setLevel() for this application?
I'm quite used to setLevel() after using it for a while, but that may be
coloring my objectiveness. I DO NOT, however, wish to waste everyone's
time writing another Python logging library.

Xen: how to map vcpu to one logical cpu so that the vcpu is only slightly less powerful than the logical cpu

Xen: how to map vcpu to one logical cpu so that the vcpu is only slightly
less powerful than the logical cpu

I'm used to working with Hyper-V, but I'm now considering moving to Xen
since I'd be working on *nix environments a lot more.
In Hyper-V every logical cpu core gets divided into 8 vcpus that the VMs
can use. This means that each vCPU is 8 times less powerful than the
actual CPU. This is not a problem for most modern applications since they
will just spread the load.
However, I'm running a 9-year old application that can only run on one
core, is unable to multithread. With Hyper-V we hit a wall since the 1/8th
of a logical CPU isn't sufficient to run the application, it would
constantly run at 100% and become quite unstable. I was wondering if this
is different with Xen. The server that it will run on is an 8-core server
(Xeon 1230v3 @ 3.30Ghz with H/T), so I would like to use 2 of those
logical CPU cores and map them directly to two powerful vCPUs, so we
roughly have a one on one relation. I would run the VM on those two so one
can handle the VM load and the other the application load.
Is this at all possible? I know that you can pin vCPUs to certain cores,
but I would like to reserve two logical CPUs to run two powerful vCPUs,
thus pinning them one on one.
Thanks in advance.

MVC Html ActionLink with Twitter Bootstrap doesn't work with html attributes for javascript integration

MVC Html ActionLink with Twitter Bootstrap doesn't work with html
attributes for javascript integration

I'm developing an application framework using the "Twitter Bootstrap for
MVC" by Eric Hexter et al.
I'm having one minor problem with the default html.actionlink behaviour in
the shared Index page that uses a foreach loop to provide a list from the
anonymous model sent to the view.
I'm trying to add an html attribute for an "id" which will call a
javascript modal when deleting a row of data.
If I try to add attributes the routevalues variable is rendered as a
string. I've tried with an IDictionary for the html attributes but the
result is similar.
Creating an actionlink outside of the foreach loop has the javascript
working as expected.
Code (snippet) last line is where the error/confusion occurs:
@using BootstrapSupport
@model System.Collections.IEnumerable
<h4>@Model.GetLabel() <small>Listing</small></h4>
<table class="table table-striped">
<caption></caption>
<thead>
<tr>
@foreach (var property in Model.VisibleProperties())
{
<th>
@property.GetLabel()
</th>
}
<th></th>
</tr>
</thead>
@{ int index = 0; }
@foreach (var model in Model)
{
ViewData[index.ToString()] = model;
<tr>
@foreach (var property in model.VisibleProperties())
{
<td>
@Html.Display(index + "." + property.Name)
</td>
}
<td>
<div class="btn-group">
<a class="btn dropdown-toggle" data-toggle="dropdown"
href="#">
Action
<span class="caret"></span>
</a>
<ul class="dropdown-menu">
@{
@Html.TryPartial("_actions", model)
var routevalues = model.GetIdValue();
<li>@Html.ActionLink("Edit", "Edit",
routevalues)</li>
<li>@Html.ActionLink("Details", "Details",
routevalues)</li>
<li class="divider"></li>
<li>@Html.ActionLink("Delete", "Delete",
routevalues, new { id = "mylink" })</li>
Expected result:
<li><a href="/Film/Delete/1" id="mylink">Delete</a></li>
Actual result:
<li><a
href="/Film/Delete?Count=1&amp;Keys=System.Collections.Generic.Dictionary%602%2BKeyCollection%5BSystem.String%2CSystem.Object%5D&amp;Values=System.Collections.Generic.Dictionary%602%2BValueCollection%5BSystem.String%2CSystem.Object%5D"
id="mylink">Delete</a></li>
I get a slightly different but similar result when I try it with an
IDictionary (which assumes the routevalues returns a RouteValueDictionary)
Is there any way I can get the expected result without re-writing chunks
of the code behind Eric Hexter's MVC Twitter Bootsrap mod?

Sunday, 18 August 2013

Weird characters, encoding mismatches

Weird characters, encoding mismatches

I'm having this weird problem where characters are appears as symbols such
as: Ã ° Â
Sometimes this error occurs for other times not like so:
(¯`'·.¸[ ~ ]¸.·'´¯)
is converted to
(¯`'·.¸[ ~ ]¸.·'´¯)
I've set the mysql_set_charset to utf8, the HTML meta is set to output in
UTF8, the column collation that I'm adding this data to is set to
utf8_general_ci. In fact if I view the data in the database it looks
perfectly normal.
Sometimes I started making use of utf8_encode() because in the case of all
those characters, on entry to the database it was cutting short and only
entering the first parentheses e.g. ( One particularly weird thing is that
if I use utf8_decode on the (¯`'·.¸[ ~ ]¸.·'´¯) then it looks
normal. However if I use utf8_decode for all the data in the table then
that starts outputting ð&#65533;&#65533; instead of à ° Â
Edit
I should note that the text is coming from e-mails so perhaps the issue is
that the encoding is all mashed up? It is odd that it appears okay in the
database though...
I have read some similar issues on here but failed to understand them and
this case seems particularly weird... What do you advise is the problem
here?

Is an atomic action supposed to be deterministic?

Is an atomic action supposed to be deterministic?

I was reading about the at most once property that defines what an atomic
action is and I've been curios about this example:
x = 0, y = 0
x = y + 1 || y = y + 1
If we use the 'at most once' definition, we can say that, indeed, x = y +
1 is atomic because
y is only referenced in an another thread and
x is not being read by any thread
But the result of this action is not deterministic, it could be 1 or 2
depending on which operation is being computed first.
I might be wrong from the start, isn't atomicity suppose to grant some
kind of determinism?

Creating a triangle with OpenGL & GLSL

Creating a triangle with OpenGL & GLSL

I'm trying to get a triangle on screen. The code works except there is no
triangle. I'm using simple pass-trough shaders to achieve this goal.
Vertex shader:
const char *vertexShader = {
"#version 150\n"
"in vec3 vPos;"
"uniform mat4 projection_matrix;"
"void main(){"
" gl_Position = vec4(vPos,1.0);"
"}"
};
Fragment shader:
const char *fragmentShader = {
"#version 150\n"
"out vec4 fColor;"
"void main(){"
" fColor = vec4(1.0,0.0,0.0,1.0);"
"}"
};
Code: http://bobdolman.com/code.html

Force widget update for debugging purposes?

Force widget update for debugging purposes?

Is there a way to trigger onUpdate() for debugging purposes?
(One way is to re-add the widget or reinstall the apk, but that sucks)

how to calculate mse and snr of an image?

how to calculate mse and snr of an image?

I have done adding noise to an image.now what i need is to calculate the
mse and snr of the image.here b is the orginal image k is the encrypted
image.can anyone help how to calculate the two and plot them?
clc;
clear all;
close all;
a=imread('lenna.jpg');
b=rgb2gray(a);
figure,imshow(b);
c=double(b);
d=randn(512,512);
e=exp(2*pi*i*d);
f=c.*e;
g=fft2(f);
h=randn(512,512);
s=exp(2*pi*i*h);
j=g.*s;
k=fft2(j);
k(1:512, 1:256)= 0;
figure,imshow(k);

How prove that $10(a^3+b^3+c^3)-9(a^5+b^5+c^5)\le\dfrac{9}{4}$

How prove that $10(a^3+b^3+c^3)-9(a^5+b^5+c^5)\le\dfrac{9}{4}$

let $a,b,c\ge 0$, such that $a+b+c=1$, prove that
$$10(a^3+b^3+c^3)-9(a^5+b^5+c^5)\le\dfrac{9}{4}$$
This problem is simple as 2005,china west compition problem
$$10(a^3+b^3+c^3)-9(a^5+b^5+c^5)\ge 1$$
see:(http://www.artofproblemsolving.com/Forum/viewtopic.php?p=362838&sid=00aa42b316d41e251e24e658594fcc51#p362838)
for 2005 china west problem we have two methods(or most two)
solution 1F note $$(a+b+c)^3=a^3+b^3+c^3+3(a+b)(b+c)(a+c)$$
$$(a+b+c)^5=a^5+b^5+c^5+5(a+b)(b+c)(a+c)(a^2+b^2+c^2+ab+bc+ac)$$ then
$$\Longleftrightarrow
10[1-3(a+b)(b+c)(a+c)]-9[1-5(a+b)(b+c)(a+c)(a^2+b^2+c^2+ab+bc+ac)]\ge 1$$
$$\Longleftrightarrow
3(a+b)(b+c)(a+c)(a^2+b^2+c^2+ab+bc+ac)-2(a+b)(b+c)(a+c)\ge 0$$
$$\Longleftrightarrow 3(a^2+b^2+c^2+ab+bc+ac)\ge 2=2(a+b+c)^2$$ $$
a^2+b^2+c^2-ab-bc-ac\ge 0$$ It's Obviously.
solution 2:
$$10(a+b+c)^2(a^3+b^3+c^3)-9(a^5+b^5+c^5)-(a+b+c)^5\ge0$$ it is equivalent
to $$15(a+b)(b+c)(c+a)(a^2+b^2+c^2-ab-bc-ca)\ge0$$
But for $$10(a^3+b^3+c^3)-9(a^5+b^5+c^5)\le\dfrac{9}{4}$$
This methods I can't work, can someone help deal it.Thank you

Saturday, 17 August 2013

Determine if point is within bounding box

Determine if point is within bounding box

How would you determine if a given point is within the bounding box?
My point is 48.847172 , 2.386597.
Boundingbox:
"48.7998602295",
"48.8198640442",
"2.46138595581",
"2.48138619423"

iOS 7 Status Bar Back to iOS 6 style?

iOS 7 Status Bar Back to iOS 6 style?

In iOS 7 the status bar has been designed in a way that it merges with the
view like this:

It is cool but it will kind of mess up your view when you has got
something at the top part of your view and it became overlapped with the
status bar.
Is there a simple solution (such as setting a property in info.plist) that
can change its style back to how it functions in iOS6? I know a more
straightforward solution is to have self.view.center.x +20points for every
single VC, but changing them will screw other dimensions up (having a
different self.view.center.x will cause problem to my custom segues, etc)
and suddenly it becomes a tedious job so I'll really be glad if someone
can provide me an one-liner solution.

How can I add an object to a three.js scene inside a click event handler?

How can I add an object to a three.js scene inside a click event handler?

Given a three.js scene that is initialized on document ready, how can I
add a 3D object (such as a simple cube), when the user triggers a click
event after the init() function has already fired?
Here's a fiddle that already has the scene setup.
var camera, scene, renderer;
var geometry, material, mesh;
window.addEventListener("click", onClick, false);
function onClick() {
alert("Replace me with code to add an object!");
}
var init = function () {
renderer = new THREE.CanvasRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
camera = new THREE.PerspectiveCamera(75, window.innerWidth /
window.innerHeight, 1, 1000);
camera.position.z = 500;
scene = new THREE.Scene();
geometry = new THREE.CubeGeometry(200, 200, 200);
material = new THREE.MeshBasicMaterial({
color: 0x000000,
wireframe: true,
wireframeLinewidth: 2
});
mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
}
var animate = function () {
requestAnimationFrame(animate);
mesh.rotation.x = Date.now() * 0.0005;
mesh.rotation.y = Date.now() * 0.001;
renderer.render(scene, camera);
}
init();
animate();

Problems' answers for "Basic Set Theory" by A.Shen

Problems' answers for "Basic Set Theory" by A.Shen

I recently bought the book "Basic Set Theory" by A.Shen and
N.K.Vereshchagin to teach myself some interesting math over the summer.
The book is rich in problems but I cannot find the solutions, neither in
the book nor on the internet. If you know if/where they have been
published I would be extremely grateful :-)
Thanks!

"heart advice" - jarring or beautiful?

"heart advice" - jarring or beautiful?

I'm translating a Tibetan text written in verse into English. The style is
one of direct advice rather than learned philosophy. My aim is for the
translation to have the same down-to-earth quality as the original, and as
much as possible to be accessible to anyone with a reasonable grasp of
literary English.
In some (Tibetan) Buddhist literature in English, "heart advice" (or
"heart-advice") has become somewhat common as a term for teachings that
focus on the core practises of Buddhism, with little embellishment.
My question is whether this expression is jarring or distracting or even
seems outright erroneous to a native English speaker who happens not to
have been exposed to modern Buddhist literature. (I am not a native
speaker myself.)
There is a recurring phrase in the text: "...this is my heart advice." To
anyone who knows the meaning of "direct, unembellished, rare, crucial
teaching", this sounds quite beautiful, but I'm wondering if, for an
average reader, "my heart's advice" would actually sound better?
The Tibetan word is snying gtam, snying meaning "heart" and gtam meaning
"advice, talk, discourse" etc.