This is 2013. C++11 and C++14 is on us. But why still no dedicated IDE for
C++?
I'm 26 years old. C++ is nearly 35 years old.
I'm really baffled at seeing the evolution of C++ in my 15 years of
programming. I started with Turbo C blue screen in late 90's to vim in
early 2000's. From there, I have moved on to Java, Python and Ruby. All
beautiful languages having extensive set of IDE's which makes programming
in these languages easy and fun.
But As for C++. With it's latest iteration in C++11 and coming iteration
C++14, There's still no full fledged, dedicated Editor which full support
for latest standard and documentation of libraries and intellisense. This
is really ironic, since today, almost every language have extensive
toolsets.
C++ is not as easy to learn. An IDE will surely go a long way getting new
programmers on-boarding process easy to a great extent.
If anyone knows any reason behind it, please edify us.
Saturday, 31 August 2013
Undefined reference to function in class
Undefined reference to function in class
main.cpp:
#include <iostream>
#include "pokemonList.h"
void pokemonLookup();
int main() {
pokemonLookup();
return 0;
}
void pokemonLookup() {
pokemonList pL;
std::cout<<std::endl<<"What Pokemon do you want to look up? ";
std::string pokemonLookup;
std::cin>>pokemonLookup;
pL.displayPokemon(pokemonLookup);
}
pokemonList.h:
#ifndef POKEMONLIST_H
#define POKEMONLIST_H
#include <iostream>
class pokemonList
{
private:
struct pokemonTemplate {
std::string pokemonName;
std::string pokemonMoves[3];
int pokemonLevel;
int baseATK;
int baseDEF;
int baseSPATK;
int baseSPDEF;
int baseSPEED;
};
pokemonTemplate bulbasaur;
pokemonTemplate pikachu;
public:
void displayPokemon(std::string pokemon);
protected:
};
main.cpp:
#include <iostream>
#include "pokemonList.h"
void pokemonLookup();
int main() {
pokemonLookup();
return 0;
}
void pokemonLookup() {
pokemonList pL;
std::cout<<std::endl<<"What Pokemon do you want to look up? ";
std::string pokemonLookup;
std::cin>>pokemonLookup;
pL.displayPokemon(pokemonLookup);
}
pokemonList.h:
#ifndef POKEMONLIST_H
#define POKEMONLIST_H
#include <iostream>
class pokemonList
{
private:
struct pokemonTemplate {
std::string pokemonName;
std::string pokemonMoves[3];
int pokemonLevel;
int baseATK;
int baseDEF;
int baseSPATK;
int baseSPDEF;
int baseSPEED;
};
pokemonTemplate bulbasaur;
pokemonTemplate pikachu;
public:
void displayPokemon(std::string pokemon);
protected:
};
Codeigniter Strange Query Results.
Codeigniter Strange Query Results.
I am trying to build a messaging system in codeigniter. I have three
tables as below.
messages: id--thread_id--message_id--subject--message--sent
messages_thread id--thread_id
messages_participants id--thread_id--to_id--from_id--message_id
I am easily able to compase a new message, and the recipient can see that
a message has been recieved.
The problem comes when there is a reply. After replying the results are
duplicated. it show that the initial message was sent from both the
originator and the reciever and is returning 4 rows instead of the
expected 2 rows. can anyone tell me where I am going wrong?
Here is my model.
function reply_to_thread(){
//Generate random string for the ticket number
$rand = substr(str_shuffle(MD5(microtime())), 0, 11);
//Add the random string to the hash
$messageid = $rand;
$messageinsert = array(
'message_id' => $messageid,
'subject' => $this->input->post('subject'),
'message' => $this->input->post('message'),
'thread_id' => $this->input->post('thread_id'),
);
$participantsinsert = array(
'message_id' => $messageid,
'from_id' => $this->input->post('from_id'),
'to_id' => $this->input->post('to_id'),
'thread_id' => $this->input->post('thread_id'),
);
$this->db->insert('messages',$messageinsert);
$this->db->insert('messages_participants',$participantsinsert);
}
function view_thread($thread_id){
$this->db->where('messages.thread_id', $thread_id);
$this->db->join('messages_participants',
'messages_participants.thread_id = messages.thread_id');
$this->db->join('users', 'messages_participants.from_id = users.id');
$result = $this->db->get('messages');
var_dump($result);
return $result->result_array();
}
My controller:
function check_messages(){
$id = $this->session->userdata('id');
$data['thread'] = $this->message_model->check_messages($id);
$this->load->view('messages/my_messages', $data);
}
function view_thread($thread_id){
$data['thread'] = $this->message_model->view_thread($thread_id);
$this->load->view('messages/view_thread',$data);
}
function reply(){
$this->message_model->reply_to_thread();
redirect('messages/get_messages');
}
and my view thread view:
<div class="well">
<h3>View Messages</h3>
<?php foreach($thread as $threadfield):?>
<div class="message">
<img class="avatar pull-left" src="<?php echo
$threadfield['avatar'];?>">
<div class="message-actions">
<button class="btn btn-success"
id="reply">Reply</button>
</div>
<p>
<strong>From: <a href="profile.html"> Users
id: <?php echo
$threadfield['from_id'];?></a></strong> <span
class="badge
badge-important">Unread</span><br>
<strong>Date:</strong> <?php echo date('M j Y
g:i A', strtotime($threadfield['sent']));?>
</p>
<p><strong>Subject:</strong> <a href =
"/messages/view_thread/<?php echo
$threadfield['thread_id'];?>"><?php echo
$threadfield['subject'];?></a></p>
<p><strong>Message:</strong> <?php echo
$threadfield['message'];?></p>
<hr>
</div>
<?php endforeach; ?>
</div>
<div class="row-fluid" id="replyform" style="display: none">
<div class="well">
<h3>Reply to <?php echo $threadfield['username'];?>'s
Message.</h3>
<?php echo form_open('messages/reply');?>
<input type="text" value="<?php echo
$threadfield['thread_id'];?>" name="thread_id"
id="thread_id">
<input type="text" value="<?php echo
$this->session->userdata('id');?>" name="from_id"
id="from_id">
<input type="text" value="<?php echo
$threadfield['from_id'];?>" name="to_id" id="to_id">
<input type="text" value="RE: <?php echo
$threadfield['subject'];?>" name="subject"
id="subject">
<input type="text" placeholder="Message......."
name="message" id="message">
<button class="btn" type="submit">Submit Reply</button>
<?php echo form_close();?>
</div>
thanks in advance.
I am trying to build a messaging system in codeigniter. I have three
tables as below.
messages: id--thread_id--message_id--subject--message--sent
messages_thread id--thread_id
messages_participants id--thread_id--to_id--from_id--message_id
I am easily able to compase a new message, and the recipient can see that
a message has been recieved.
The problem comes when there is a reply. After replying the results are
duplicated. it show that the initial message was sent from both the
originator and the reciever and is returning 4 rows instead of the
expected 2 rows. can anyone tell me where I am going wrong?
Here is my model.
function reply_to_thread(){
//Generate random string for the ticket number
$rand = substr(str_shuffle(MD5(microtime())), 0, 11);
//Add the random string to the hash
$messageid = $rand;
$messageinsert = array(
'message_id' => $messageid,
'subject' => $this->input->post('subject'),
'message' => $this->input->post('message'),
'thread_id' => $this->input->post('thread_id'),
);
$participantsinsert = array(
'message_id' => $messageid,
'from_id' => $this->input->post('from_id'),
'to_id' => $this->input->post('to_id'),
'thread_id' => $this->input->post('thread_id'),
);
$this->db->insert('messages',$messageinsert);
$this->db->insert('messages_participants',$participantsinsert);
}
function view_thread($thread_id){
$this->db->where('messages.thread_id', $thread_id);
$this->db->join('messages_participants',
'messages_participants.thread_id = messages.thread_id');
$this->db->join('users', 'messages_participants.from_id = users.id');
$result = $this->db->get('messages');
var_dump($result);
return $result->result_array();
}
My controller:
function check_messages(){
$id = $this->session->userdata('id');
$data['thread'] = $this->message_model->check_messages($id);
$this->load->view('messages/my_messages', $data);
}
function view_thread($thread_id){
$data['thread'] = $this->message_model->view_thread($thread_id);
$this->load->view('messages/view_thread',$data);
}
function reply(){
$this->message_model->reply_to_thread();
redirect('messages/get_messages');
}
and my view thread view:
<div class="well">
<h3>View Messages</h3>
<?php foreach($thread as $threadfield):?>
<div class="message">
<img class="avatar pull-left" src="<?php echo
$threadfield['avatar'];?>">
<div class="message-actions">
<button class="btn btn-success"
id="reply">Reply</button>
</div>
<p>
<strong>From: <a href="profile.html"> Users
id: <?php echo
$threadfield['from_id'];?></a></strong> <span
class="badge
badge-important">Unread</span><br>
<strong>Date:</strong> <?php echo date('M j Y
g:i A', strtotime($threadfield['sent']));?>
</p>
<p><strong>Subject:</strong> <a href =
"/messages/view_thread/<?php echo
$threadfield['thread_id'];?>"><?php echo
$threadfield['subject'];?></a></p>
<p><strong>Message:</strong> <?php echo
$threadfield['message'];?></p>
<hr>
</div>
<?php endforeach; ?>
</div>
<div class="row-fluid" id="replyform" style="display: none">
<div class="well">
<h3>Reply to <?php echo $threadfield['username'];?>'s
Message.</h3>
<?php echo form_open('messages/reply');?>
<input type="text" value="<?php echo
$threadfield['thread_id'];?>" name="thread_id"
id="thread_id">
<input type="text" value="<?php echo
$this->session->userdata('id');?>" name="from_id"
id="from_id">
<input type="text" value="<?php echo
$threadfield['from_id'];?>" name="to_id" id="to_id">
<input type="text" value="RE: <?php echo
$threadfield['subject'];?>" name="subject"
id="subject">
<input type="text" placeholder="Message......."
name="message" id="message">
<button class="btn" type="submit">Submit Reply</button>
<?php echo form_close();?>
</div>
thanks in advance.
MFC Debug Assertion Failed
MFC Debug Assertion Failed
I have a "Debug Assertion Faled" error. Is there some suggestions for
solving this problem? I tried hotfix and I updated VS 2008 to Service Pack
1 but it didn't helped.I installed VS 2012 too, and I switched proprties
tu "Use Multi-Byte Character Set". Thanks in advance.
I have a "Debug Assertion Faled" error. Is there some suggestions for
solving this problem? I tried hotfix and I updated VS 2008 to Service Pack
1 but it didn't helped.I installed VS 2012 too, and I switched proprties
tu "Use Multi-Byte Character Set". Thanks in advance.
Can we call a method at class level rather than in a method [Java]?
Can we call a method at class level rather than in a method [Java]?
Can someone please tell me, how to call a method at class level?
Suppose I have a class like below, then can we call test1Method at class
level? If it is not correct please tell me the reason..
class Test2 {
Test1 t1=new Test1();
t1.test1Method();
public void test2Method() { }
}
Can someone please tell me, how to call a method at class level?
Suppose I have a class like below, then can we call test1Method at class
level? If it is not correct please tell me the reason..
class Test2 {
Test1 t1=new Test1();
t1.test1Method();
public void test2Method() { }
}
How to check JDialog state
How to check JDialog state
I have a JDialog and I'd like to check whether its state is maximized,
minimized or normal. How can I do that?
I have tried:
private JDialog dialog = new JDialog();
dialog.addWindowStateListener(new WindowStateListener() {
@Override
public void windowStateChanged(WindowEvent e) {
if(e.getNewState()==JFrame.MAXIMIZED_BOTH){
System.out.println(" state MAXIMIZED_BOTH");
dialog.repaint();
}
}
});
but it doesn't work of course.
Thanks
I have a JDialog and I'd like to check whether its state is maximized,
minimized or normal. How can I do that?
I have tried:
private JDialog dialog = new JDialog();
dialog.addWindowStateListener(new WindowStateListener() {
@Override
public void windowStateChanged(WindowEvent e) {
if(e.getNewState()==JFrame.MAXIMIZED_BOTH){
System.out.println(" state MAXIMIZED_BOTH");
dialog.repaint();
}
}
});
but it doesn't work of course.
Thanks
how do i make a get request without a redirect in php?
how do i make a get request without a redirect in php?
How do i make a GET request using curl without making a redirect? I want
the request sent in the background. Here is my code:
$curl_handle = curl_init();
curl_setopt( $curl_handle, CURLOPT_URL, 'http://www.example.com/?test=123' );
curl_exec( $curl_handle ); // Execute the request
curl_close( $curl_handle );
I want something that sends the request in the background like this:
<img src="http://www.example.com/?test=123">
The get request is issued from www.example1.com to www.example.com, the
problem is it redirects to www.example.com, i want it to stay on
www.example1.com and send the request in the background silently. Thanks
to anyone who can help. This should be pretty simple but i'm not sure how
to achieve it. I know it's possible when dealing with post data but i'd
appreciate an example with get requests. Thanks to anyone who can help.
How do i make a GET request using curl without making a redirect? I want
the request sent in the background. Here is my code:
$curl_handle = curl_init();
curl_setopt( $curl_handle, CURLOPT_URL, 'http://www.example.com/?test=123' );
curl_exec( $curl_handle ); // Execute the request
curl_close( $curl_handle );
I want something that sends the request in the background like this:
<img src="http://www.example.com/?test=123">
The get request is issued from www.example1.com to www.example.com, the
problem is it redirects to www.example.com, i want it to stay on
www.example1.com and send the request in the background silently. Thanks
to anyone who can help. This should be pretty simple but i'm not sure how
to achieve it. I know it's possible when dealing with post data but i'd
appreciate an example with get requests. Thanks to anyone who can help.
Friday, 30 August 2013
infix to postfix using stacks as linked lists in C language
infix to postfix using stacks as linked lists in C language
i have written a program to convert infix to postfix using C language in
UBUNTU...but my program is not woarking properly can any one help??? MY
PROGRAM IS AS FOLLOWS
#include<stdio.h>
#include<stdlib.h>
char op[50];
struct node
{
char data;
struct node *next;
} *l1=NULL;
void push(char x) // pushes char into the linkedlist
{
if(l1==NULL)
{
l1=(struct node *)malloc(sizeof(struct node));
l1->data=x;
l1->next=NULL;
}
else
{
struct node *p;
p=(struct node *)malloc(sizeof(struct node));
p->data=x;
p->next=l1;
l1=p;
}
}
char pop() // pops char outof linkedlist
{
char c;
struct node *p;
if (l1==NULL)
{
printf("the stack is empty\n");
// exit(1);
}
else
{
c=l1->data;
p=l1->next;
free (l1);
l1=p;
}
return c;
}
void display(struct node *start)
{
{
int i=0;
struct node *p;
p=start;
if(p==NULL)
printf("Empty list");
else
{
while(p!=NULL)
{
printf("%c->",p->data);
p=p->next;
}
printf("NULL\n");
}
}
}
int prior(char s, char c)
{
if ( c=='^' && s=='+' || s=='-' ||s=='/' || s=='*')
return 1;
else if( c=='*' || c=='/')
{
if(s=='+' || s=='-' )
return 1;
else
return 0;
}
else if( c=='+' || c=='-' )
return 0;
}
void cnvrt(char s[], int n) // convert infix to postfix
{
char g;
int i,j,x;
for(i=0,j=0;i<n;i++)
{
if (s[i]>='0'&&s[i]<='9' || s[i]>='a' && s[i]<='z'|| s[i]>='A' &&
s[i]<='Z')
{
op[j]=s[i];
j++;
}
else if(s[i]=='(')
{
push(s[i]);
}
else if (s[i]=='+' || s[i]=='/' || s[i]=='-' || s[i]=='*' ||
s[i]=='^')
{
if( l1==NULL)
push(s[i]);
else if(l1->data=='(')
push(s[i]);
else if(prior(l1->data, s[i] )!=1)
push(s[i]);
else
{ op[j]=pop();
j++;
push(s[i]);
}
}
else if(s[i]==')')
{
while(l1!=NULL && l1->data!='(')
{
op[j]=pop();
j++;
}
g=pop();
}
}
while(l1!=NULL)
{
op[j]=pop();
j++;
l1=l1->next;
}
}
void main()
{
int i,n;
char c[50];
printf(" enter the no of characters in infix string\n ");
scanf("%d",&n);
printf(" enter the infix string\n");
//for(i=0;i<n;i++)
scanf("%s",c);
cnvrt(c,n);
printf("the postfix string is \n");
for(i=0;i<n;i++)
{
printf("%c",op[i]);
}
}
always one of the operators is missing in the answer..also it gives CORE
DUMPED as output sometimes......... and if infix contains '(' ot ')'
.......then it gives output as stack is empty...... Plz help guys... i am
a student...so ther mi8 b mistakes in my program
i have written a program to convert infix to postfix using C language in
UBUNTU...but my program is not woarking properly can any one help??? MY
PROGRAM IS AS FOLLOWS
#include<stdio.h>
#include<stdlib.h>
char op[50];
struct node
{
char data;
struct node *next;
} *l1=NULL;
void push(char x) // pushes char into the linkedlist
{
if(l1==NULL)
{
l1=(struct node *)malloc(sizeof(struct node));
l1->data=x;
l1->next=NULL;
}
else
{
struct node *p;
p=(struct node *)malloc(sizeof(struct node));
p->data=x;
p->next=l1;
l1=p;
}
}
char pop() // pops char outof linkedlist
{
char c;
struct node *p;
if (l1==NULL)
{
printf("the stack is empty\n");
// exit(1);
}
else
{
c=l1->data;
p=l1->next;
free (l1);
l1=p;
}
return c;
}
void display(struct node *start)
{
{
int i=0;
struct node *p;
p=start;
if(p==NULL)
printf("Empty list");
else
{
while(p!=NULL)
{
printf("%c->",p->data);
p=p->next;
}
printf("NULL\n");
}
}
}
int prior(char s, char c)
{
if ( c=='^' && s=='+' || s=='-' ||s=='/' || s=='*')
return 1;
else if( c=='*' || c=='/')
{
if(s=='+' || s=='-' )
return 1;
else
return 0;
}
else if( c=='+' || c=='-' )
return 0;
}
void cnvrt(char s[], int n) // convert infix to postfix
{
char g;
int i,j,x;
for(i=0,j=0;i<n;i++)
{
if (s[i]>='0'&&s[i]<='9' || s[i]>='a' && s[i]<='z'|| s[i]>='A' &&
s[i]<='Z')
{
op[j]=s[i];
j++;
}
else if(s[i]=='(')
{
push(s[i]);
}
else if (s[i]=='+' || s[i]=='/' || s[i]=='-' || s[i]=='*' ||
s[i]=='^')
{
if( l1==NULL)
push(s[i]);
else if(l1->data=='(')
push(s[i]);
else if(prior(l1->data, s[i] )!=1)
push(s[i]);
else
{ op[j]=pop();
j++;
push(s[i]);
}
}
else if(s[i]==')')
{
while(l1!=NULL && l1->data!='(')
{
op[j]=pop();
j++;
}
g=pop();
}
}
while(l1!=NULL)
{
op[j]=pop();
j++;
l1=l1->next;
}
}
void main()
{
int i,n;
char c[50];
printf(" enter the no of characters in infix string\n ");
scanf("%d",&n);
printf(" enter the infix string\n");
//for(i=0;i<n;i++)
scanf("%s",c);
cnvrt(c,n);
printf("the postfix string is \n");
for(i=0;i<n;i++)
{
printf("%c",op[i]);
}
}
always one of the operators is missing in the answer..also it gives CORE
DUMPED as output sometimes......... and if infix contains '(' ot ')'
.......then it gives output as stack is empty...... Plz help guys... i am
a student...so ther mi8 b mistakes in my program
Wednesday, 28 August 2013
Can't get string resource from R.string.*
Can't get string resource from R.string.*
I have SQlite table with two column _id and name. For internationalization
purpose I store the name like R.string.today Now I want to get string
resource associated with R.string.today:
String column = myCursor.getString(myCursor.getColumnIndex(MainDb.NAME));
int resId = getApplicationContext().getResources().getIdentifier(column,
"strings", getApplicationContext().getPackageName());
String buttonText;
if (resId != 0)
{
buttonText = getApplicationContext().getString(resId);
} else
{
buttonText = "Resource is null!";
}
resId is always 0. Variable "column" have the right value, I've checked it
with debugger. I've tried different variations in resId: 1) "string"
instead of "strings" in defType. 2) Different variation of getResources
like Resources.getSystem()... 3) Different variation of getPackageName()
What I'm doing wrong?
I have SQlite table with two column _id and name. For internationalization
purpose I store the name like R.string.today Now I want to get string
resource associated with R.string.today:
String column = myCursor.getString(myCursor.getColumnIndex(MainDb.NAME));
int resId = getApplicationContext().getResources().getIdentifier(column,
"strings", getApplicationContext().getPackageName());
String buttonText;
if (resId != 0)
{
buttonText = getApplicationContext().getString(resId);
} else
{
buttonText = "Resource is null!";
}
resId is always 0. Variable "column" have the right value, I've checked it
with debugger. I've tried different variations in resId: 1) "string"
instead of "strings" in defType. 2) Different variation of getResources
like Resources.getSystem()... 3) Different variation of getPackageName()
What I'm doing wrong?
Access attribute specified by XPath with xml_grep
Access attribute specified by XPath with xml_grep
How can I access the value of an attribute specified via XPath with xml_grep?
I've tried:
# svn info http://unladen-swallow.googlecode.com/svn/trunk/ --xml > x
# cat x
<?xml version="1.0"?>
<info>
<entry
kind="dir"
path="trunk"
revision="1171">
<url>http://unladen-swallow.googlecode.com/svn/trunk</url>
<repository>
<root>http://unladen-swallow.googlecode.com/svn</root>
<uuid>05521daa-c0b4-11dd-bb00-bd6ab96fe29a</uuid>
</repository>
<commit
revision="1171">
<author>ebo@4geeks.de</author>
<date>2010-08-21T18:17:31.382601Z</date>
</commit>
</entry>
</info>
# xml_grep uuid x --text_only
05521daa-c0b4-11dd-bb00-bd6ab96fe29a
# xml_grep //info/entry/@path x --text_only # correct XPath syntax
error: unrecognized expression in handler: '//info/entry/@path' at
/usr/bin/xml_grep line 198
# xml_grep //info/entry/[@path] x --text_only
# # no output
I've looked at the online help pages, but the only syntax that matches a
property at all is far too verbose:
# xml_grep '*[@path]' x
<?xml version="1.0" ?>
<xml_grep version="0.7" date="Wed Aug 28 15:22:13 2013">
<file filename="x">
<entry kind="dir" path="trunk" revision="1171">
<url>http://unladen-swallow.googlecode.com/svn/trunk</url>
<repository>
<root>http://unladen-swallow.googlecode.com/svn</root>
<uuid>05521daa-c0b4-11dd-bb00-bd6ab96fe29a</uuid>
</repository>
<commit revision="1171">
<author>ebo@4geeks.de</author>
<date>2010-08-21T18:17:31.382601Z</date>
</commit>
</entry>
</file>
</xml_grep>
#
What's the correct syntax?
How can I access the value of an attribute specified via XPath with xml_grep?
I've tried:
# svn info http://unladen-swallow.googlecode.com/svn/trunk/ --xml > x
# cat x
<?xml version="1.0"?>
<info>
<entry
kind="dir"
path="trunk"
revision="1171">
<url>http://unladen-swallow.googlecode.com/svn/trunk</url>
<repository>
<root>http://unladen-swallow.googlecode.com/svn</root>
<uuid>05521daa-c0b4-11dd-bb00-bd6ab96fe29a</uuid>
</repository>
<commit
revision="1171">
<author>ebo@4geeks.de</author>
<date>2010-08-21T18:17:31.382601Z</date>
</commit>
</entry>
</info>
# xml_grep uuid x --text_only
05521daa-c0b4-11dd-bb00-bd6ab96fe29a
# xml_grep //info/entry/@path x --text_only # correct XPath syntax
error: unrecognized expression in handler: '//info/entry/@path' at
/usr/bin/xml_grep line 198
# xml_grep //info/entry/[@path] x --text_only
# # no output
I've looked at the online help pages, but the only syntax that matches a
property at all is far too verbose:
# xml_grep '*[@path]' x
<?xml version="1.0" ?>
<xml_grep version="0.7" date="Wed Aug 28 15:22:13 2013">
<file filename="x">
<entry kind="dir" path="trunk" revision="1171">
<url>http://unladen-swallow.googlecode.com/svn/trunk</url>
<repository>
<root>http://unladen-swallow.googlecode.com/svn</root>
<uuid>05521daa-c0b4-11dd-bb00-bd6ab96fe29a</uuid>
</repository>
<commit revision="1171">
<author>ebo@4geeks.de</author>
<date>2010-08-21T18:17:31.382601Z</date>
</commit>
</entry>
</file>
</xml_grep>
#
What's the correct syntax?
Intermitten System.InvalidOperationException: The specified cast from a materialized
Intermitten System.InvalidOperationException: The specified cast from a
materialized
Currently we are running EF 4.0 with , using the repository and Unit Of
Work design patterns. Each page request creates its' own ObjectContext for
capturing data in the unit of work and throughout the lifecycle of the
page, uses this one objectcontext.
We now, in production only, have the below error occur intermittently, on
average maybe once every week or two. The only way to resolve the issue is
to reset the IIS AppPool. Once this error starts, it cascades across the
entire site and can occur on any page for any and all users for any DB
calls through EF. For instance, we had on 8/27 the first occurrence at
1:19PM and over 500 occurrences after that until the app pool reset at
1:26PM. This does not correlate to spikes in usage or any other pattern we
can detect.
Is there any way to determine the culprit? It also seems to corrupt our
event viewer each time this happens.
System.InvalidOperationException: The specified cast from a materialized
'System.Int32' type to the 'System.Boolean' type is not valid. at
System.Data.Common.Internal.Materialization.Shaper.ErrorHandlingValueReader1.GetValue(DbDataReader
reader, Int32 ordinal) at
System.Data.Common.Internal.Materialization.Shaper.GetColumnValueWithErrorHandling[TColumn](Int32
ordinal) at
System.Data.Common.Internal.Materialization.Coordinator1.ReadNextElement(Shaper
shaper) at
System.Data.Common.Internal.Materialization.Shaper1.SimpleEnumerator.MoveNext()
at System.Linq.Enumerable.Single[TSource](IEnumerable1 source) at
System.Linq.Queryable.Any[TSource](IQueryable1 source, Expression1
predicate) at
BSAH.eCommerce.SitefinityWebApp.ButlerModules.UserProfile.UI.UserProfile.ShowUserGroupMaintenanceLink(User
user) in
c:\b\8\ButlerScheinCom\BSCom_Prod_ECom_Web_Compile\Sources\BSAH.Web\Presentation
Layer\ButlerModules\UserProfile\UI\BSCUserProfile.ascx.cs:line 694 at
BSAH.eCommerce.SitefinityWebApp.ButlerModules.UserProfile.UI.UserProfile.SetupLoginControls(Boolean
logoutVisiblility) in
c:\b\8\ButlerScheinCom\BSCom_Prod_ECom_Web_Compile\Sources\BSAH.Web\Presentation
Layer\ButlerModules\UserProfile\UI\BSCUserProfile.ascx.cs:line 631 at
BSAH.eCommerce.SitefinityWebApp.ButlerModules.UserProfile.UI.UserProfile.Page_Load(Object
sender, EventArgs e) in
c:\b\8\ButlerScheinCom\BSCom_Prod_ECom_Web_Compile\Sources\BSAH.Web\Presentation
Layer\ButlerModules\UserProfile
materialized
Currently we are running EF 4.0 with , using the repository and Unit Of
Work design patterns. Each page request creates its' own ObjectContext for
capturing data in the unit of work and throughout the lifecycle of the
page, uses this one objectcontext.
We now, in production only, have the below error occur intermittently, on
average maybe once every week or two. The only way to resolve the issue is
to reset the IIS AppPool. Once this error starts, it cascades across the
entire site and can occur on any page for any and all users for any DB
calls through EF. For instance, we had on 8/27 the first occurrence at
1:19PM and over 500 occurrences after that until the app pool reset at
1:26PM. This does not correlate to spikes in usage or any other pattern we
can detect.
Is there any way to determine the culprit? It also seems to corrupt our
event viewer each time this happens.
System.InvalidOperationException: The specified cast from a materialized
'System.Int32' type to the 'System.Boolean' type is not valid. at
System.Data.Common.Internal.Materialization.Shaper.ErrorHandlingValueReader1.GetValue(DbDataReader
reader, Int32 ordinal) at
System.Data.Common.Internal.Materialization.Shaper.GetColumnValueWithErrorHandling[TColumn](Int32
ordinal) at
System.Data.Common.Internal.Materialization.Coordinator1.ReadNextElement(Shaper
shaper) at
System.Data.Common.Internal.Materialization.Shaper1.SimpleEnumerator.MoveNext()
at System.Linq.Enumerable.Single[TSource](IEnumerable1 source) at
System.Linq.Queryable.Any[TSource](IQueryable1 source, Expression1
predicate) at
BSAH.eCommerce.SitefinityWebApp.ButlerModules.UserProfile.UI.UserProfile.ShowUserGroupMaintenanceLink(User
user) in
c:\b\8\ButlerScheinCom\BSCom_Prod_ECom_Web_Compile\Sources\BSAH.Web\Presentation
Layer\ButlerModules\UserProfile\UI\BSCUserProfile.ascx.cs:line 694 at
BSAH.eCommerce.SitefinityWebApp.ButlerModules.UserProfile.UI.UserProfile.SetupLoginControls(Boolean
logoutVisiblility) in
c:\b\8\ButlerScheinCom\BSCom_Prod_ECom_Web_Compile\Sources\BSAH.Web\Presentation
Layer\ButlerModules\UserProfile\UI\BSCUserProfile.ascx.cs:line 631 at
BSAH.eCommerce.SitefinityWebApp.ButlerModules.UserProfile.UI.UserProfile.Page_Load(Object
sender, EventArgs e) in
c:\b\8\ButlerScheinCom\BSCom_Prod_ECom_Web_Compile\Sources\BSAH.Web\Presentation
Layer\ButlerModules\UserProfile
A day without midnight
A day without midnight
There's at least one time zone that skips from 23:59:59 to 1:00:00 when
"springing forward" for DST. Does anyone know what it is?
The following normally gets today's date, but it fails one day a year for
time zones matching the above criteria.
$ perl -MDateTime -E'say DateTime->today( time_zone => $ARGV[0] )->ymd;' \
America/New_York
2013-08-28
There's at least one time zone that skips from 23:59:59 to 1:00:00 when
"springing forward" for DST. Does anyone know what it is?
The following normally gets today's date, but it fails one day a year for
time zones matching the above criteria.
$ perl -MDateTime -E'say DateTime->today( time_zone => $ARGV[0] )->ymd;' \
America/New_York
2013-08-28
How to upload any type of file in phonegap and jquery mobile ?
How to upload any type of file in phonegap and jquery mobile ?
I am creating an app in the phonegap android in which i want to upload a
file to the server. What i want is when an user will click on the upload
button an option dialog will open from where the user will select a file
to be uploaded and then when user click on the save button the file will
be uploaded. The dialog will be like normal window same as we see when we
click on the attach button in the mail in the desktop. Can anyone tell me
how to do this in android mobile? Any help is appreciated.
Thanks in advance.
I am creating an app in the phonegap android in which i want to upload a
file to the server. What i want is when an user will click on the upload
button an option dialog will open from where the user will select a file
to be uploaded and then when user click on the save button the file will
be uploaded. The dialog will be like normal window same as we see when we
click on the attach button in the mail in the desktop. Can anyone tell me
how to do this in android mobile? Any help is appreciated.
Thanks in advance.
foreach contents getting skipped
foreach contents getting skipped
I've got an ASP.NET MVC4 view that looks like this:
@model IEnumerable<Bloom.Models.GalleryImageVM>
<div id="gallery">
@foreach (var img in Model)
{
<a href="#" id="@img.Title">
<img src="@img.URL" />
</a>
}
</div>
GalleryImageVM is an object with two string properties:
public class GalleryImageVM
{
public string URL { get; set; }
public string Title { get; set; }
}
Data is definitely getting populated since Model has the expected values
in it. However, nothing inside the foreach gets hit. A breakpoint won't
get hit, and if I step through it, the execution will touch each of the
expected parts of the foreach definition, but won't enter the curly
braces.
What am I missing?
I've got an ASP.NET MVC4 view that looks like this:
@model IEnumerable<Bloom.Models.GalleryImageVM>
<div id="gallery">
@foreach (var img in Model)
{
<a href="#" id="@img.Title">
<img src="@img.URL" />
</a>
}
</div>
GalleryImageVM is an object with two string properties:
public class GalleryImageVM
{
public string URL { get; set; }
public string Title { get; set; }
}
Data is definitely getting populated since Model has the expected values
in it. However, nothing inside the foreach gets hit. A breakpoint won't
get hit, and if I step through it, the execution will touch each of the
expected parts of the foreach definition, but won't enter the curly
braces.
What am I missing?
Tuesday, 27 August 2013
AFNetworking and HTTPS
AFNetworking and HTTPS
I googled around a little bit and read some SO posts, but I was still a
little confused so I figured I'd post a question here: is making a request
using HTTPS any different than making one using HTTP with AFNetworking? If
so, what needs to be changed? Thanks!
I googled around a little bit and read some SO posts, but I was still a
little confused so I figured I'd post a question here: is making a request
using HTTPS any different than making one using HTTP with AFNetworking? If
so, what needs to be changed? Thanks!
jQuery .extend not interpolating a config value. why?
jQuery .extend not interpolating a config value. why?
I have something simple I believe, yet I am getting js error.
$.extend(hashONE,{options.item1 : options.item2});
also tried:
$.extend(hashONE,{options[item1] : options[item2]});
also
var opt = {options[item1] : options[item2]};
$.extend(hashONE, opt);
All these generate an error on the "."
I must be daft, this is suppose to be easy :-)
I have something simple I believe, yet I am getting js error.
$.extend(hashONE,{options.item1 : options.item2});
also tried:
$.extend(hashONE,{options[item1] : options[item2]});
also
var opt = {options[item1] : options[item2]};
$.extend(hashONE, opt);
All these generate an error on the "."
I must be daft, this is suppose to be easy :-)
Log4j SyslogAppender not attempting a connection
Log4j SyslogAppender not attempting a connection
I have an application that uses log4j to write log files. I don't have
access to the source code, but I can assume that if I create an appender
in the log4j.xml file that it should use that appender without needing a
code change.
Currently I can confirm that no packets are being generated from the
system to the remote syslog server via wireshark. I can telnet to the
remote syslog server on port 514 and write messages without an issue. I
can assume that something isn't right with my XML, but I have no messages
to tell me what the error is.
Here's the Appender:
<appender name="SYSLOG" class="org.apache.log4j.net.SyslogAppender">
<param name="Facility" value="USER" />
<param name="syslogHost" value="172.16.81.39:514" />
<param name="Threshold" value="INFO" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="[%d{yyyy/MM/dd
HH:mm:ss.SSS}][%5p](%t) %m%n" />
</layout>
</appender>
I have also tried the Log4j 2 syntax
<appender name="syslog" class="org.apache.log4j.net.SyslogAppender">
<param name="format" value="bsd" />
<param name="host" value="172.16.81.39" />
<param name="port" value="514" />
<param name="protocol" value="TCP" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="[%d{yyyy/MM/dd
HH:mm:ss.SSS}][%5p](%t) %m%n" />
</layout>
</appender>
Here's the corresponding Logger:
<logger name="printing.com.application" additivity="false">
<level value="INFO" />
<appender-ref ref="SYSLOG" />
</logger>
If I change the <appender-ref /> to the default PRINTING_MONTHLY_ROLL then
it will print to the log file.
I have an application that uses log4j to write log files. I don't have
access to the source code, but I can assume that if I create an appender
in the log4j.xml file that it should use that appender without needing a
code change.
Currently I can confirm that no packets are being generated from the
system to the remote syslog server via wireshark. I can telnet to the
remote syslog server on port 514 and write messages without an issue. I
can assume that something isn't right with my XML, but I have no messages
to tell me what the error is.
Here's the Appender:
<appender name="SYSLOG" class="org.apache.log4j.net.SyslogAppender">
<param name="Facility" value="USER" />
<param name="syslogHost" value="172.16.81.39:514" />
<param name="Threshold" value="INFO" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="[%d{yyyy/MM/dd
HH:mm:ss.SSS}][%5p](%t) %m%n" />
</layout>
</appender>
I have also tried the Log4j 2 syntax
<appender name="syslog" class="org.apache.log4j.net.SyslogAppender">
<param name="format" value="bsd" />
<param name="host" value="172.16.81.39" />
<param name="port" value="514" />
<param name="protocol" value="TCP" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="[%d{yyyy/MM/dd
HH:mm:ss.SSS}][%5p](%t) %m%n" />
</layout>
</appender>
Here's the corresponding Logger:
<logger name="printing.com.application" additivity="false">
<level value="INFO" />
<appender-ref ref="SYSLOG" />
</logger>
If I change the <appender-ref /> to the default PRINTING_MONTHLY_ROLL then
it will print to the log file.
Making a confirm box
Making a confirm box
I am trying to make my own dialog box. I want to use jquery for this. For
some buttons on my site I need a confirmation dialog (like "Are you sure
you want to delete" yes/no). When the dialog is active, the rest of the
site should not be clickable.
So, I made this:
<div class="overlay" id="overlay" style="display:none;">
<div class="overlaycontent" id="overlaycontent">
<div id="overlaytext" class="overlaytext ">
<span id="overlaymessage" class="mediumtext bold">Deze klant
verwijderen?</span>
<br><br>
<button id="nobutton" class="button1 highbutton hand"
onclick="confirmno()">Nee</button>
<button id="yesbutton" class="button2 highbutton hand"
onclick="confirmyes()">Ja</button>
</div>
</div>
</div>
ID overlay is over the whole page. ID overlaycontent creates a white box
on top of it. ID overlaytext centers the message ID overlaymessage
contains the question/message. ID nobutton is the button to say no :) ID
yesbutton is.. guess what :)
Now, the javascript to display a message:
function confirm(message,nobutton,yesbutton){
$('#overlaymessage').html(message);
$('#nobutton').html(nobutton);
$('#yesbutton').html(yesbutton);
$('#overlay').show();
}
function confirmno(){
$('#overlay').hide();
}
function confirmyes(){
????
}
So far, it works fine (except the yes button of course, please read
further on), but for the next step I lack the knowledge. Say that I have a
button somewhere to delete a user on my website.
<button class="redbutton" onclick="deleteuser(22)">
The button needs javascript like:
<script language="javascript">
function deleteuser(userid){
confirm('Delete user?','No','Yes');
??????
}
</script>
Now where the question marks are, I want the function to do something
based on the fact the user clicked yes or no. How to catch this? I don't
have any idea. Please help me out. I don't want to use Jquireui.dialog.
I am trying to make my own dialog box. I want to use jquery for this. For
some buttons on my site I need a confirmation dialog (like "Are you sure
you want to delete" yes/no). When the dialog is active, the rest of the
site should not be clickable.
So, I made this:
<div class="overlay" id="overlay" style="display:none;">
<div class="overlaycontent" id="overlaycontent">
<div id="overlaytext" class="overlaytext ">
<span id="overlaymessage" class="mediumtext bold">Deze klant
verwijderen?</span>
<br><br>
<button id="nobutton" class="button1 highbutton hand"
onclick="confirmno()">Nee</button>
<button id="yesbutton" class="button2 highbutton hand"
onclick="confirmyes()">Ja</button>
</div>
</div>
</div>
ID overlay is over the whole page. ID overlaycontent creates a white box
on top of it. ID overlaytext centers the message ID overlaymessage
contains the question/message. ID nobutton is the button to say no :) ID
yesbutton is.. guess what :)
Now, the javascript to display a message:
function confirm(message,nobutton,yesbutton){
$('#overlaymessage').html(message);
$('#nobutton').html(nobutton);
$('#yesbutton').html(yesbutton);
$('#overlay').show();
}
function confirmno(){
$('#overlay').hide();
}
function confirmyes(){
????
}
So far, it works fine (except the yes button of course, please read
further on), but for the next step I lack the knowledge. Say that I have a
button somewhere to delete a user on my website.
<button class="redbutton" onclick="deleteuser(22)">
The button needs javascript like:
<script language="javascript">
function deleteuser(userid){
confirm('Delete user?','No','Yes');
??????
}
</script>
Now where the question marks are, I want the function to do something
based on the fact the user clicked yes or no. How to catch this? I don't
have any idea. Please help me out. I don't want to use Jquireui.dialog.
Access the Spring Properties in jsp
Access the Spring Properties in jsp
We are using strusts2+spring3.2+struts.spring.plugin Also we are using the
property place holder to access the properties in actions
Something like:
@Value("${web.site.name}") private String siteName;
And we have siteName ready and populated.
Is it possible that we can access the value in the JSP pages too? Or we
should first get it from struts action and then pass it to JSP.
We are using strusts2+spring3.2+struts.spring.plugin Also we are using the
property place holder to access the properties in actions
Something like:
@Value("${web.site.name}") private String siteName;
And we have siteName ready and populated.
Is it possible that we can access the value in the JSP pages too? Or we
should first get it from struts action and then pass it to JSP.
plone diazo with esi
plone diazo with esi
Is that possible to avoid having the doctype, <html>, <head>, <body> added
to a page when it is rendered with diazo?
My problem is that when varnish is loading content from an <esi:include
src="/mypage"> tag, diazo adds the <!DOCTYPE, html head and body tags, to
the loaded page. I would like to have only the html as it's given by
"/mypage".
Thank you!
Is that possible to avoid having the doctype, <html>, <head>, <body> added
to a page when it is rendered with diazo?
My problem is that when varnish is loading content from an <esi:include
src="/mypage"> tag, diazo adds the <!DOCTYPE, html head and body tags, to
the loaded page. I would like to have only the html as it's given by
"/mypage".
Thank you!
Monday, 26 August 2013
Setting a fixed date and counting the number of days to an input birthdate to determing day of week - Java
Setting a fixed date and counting the number of days to an input birthdate
to determing day of week - Java
My task is such - I need to set a specific date - 01/01/1913, which is a
wednesday. I then need the user to input their birthdate. The program will
then calculate which day of the week the person was born in. We are not
allowed to use the gregorian calendar to do it for us, we are required to
input the algorithm ourselves.
So far, I have the input set up,
public class FindDay4Birthdate {
public static void main(String[] args) {
// declare variables
String bbday = "";
String bbmonth = "";
String bbyear = "";
int bday;
int bmonth;
int byear;
String daysList[] = {"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"};
Scanner sc = new Scanner(System.in);
System.out.print("Please enter your date of birth - ");
sc.useDelimiter("[-/.\\s]");
if (sc.hasNext()); {
bbday = sc.next();
bbmonth = sc.next();
bbyear=sc.next();
bday = Integer.parseInt(bbday);
bmonth = Integer.parseInt(bbmonth);
byear = Integer.parseInt(bbyear);
} // end if statement
I am not sure where to go from here. Any help on how to take the next step
would be appreciated. I know that I need to use mod 7, but do not know
how, or where, I should use it.
to determing day of week - Java
My task is such - I need to set a specific date - 01/01/1913, which is a
wednesday. I then need the user to input their birthdate. The program will
then calculate which day of the week the person was born in. We are not
allowed to use the gregorian calendar to do it for us, we are required to
input the algorithm ourselves.
So far, I have the input set up,
public class FindDay4Birthdate {
public static void main(String[] args) {
// declare variables
String bbday = "";
String bbmonth = "";
String bbyear = "";
int bday;
int bmonth;
int byear;
String daysList[] = {"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"};
Scanner sc = new Scanner(System.in);
System.out.print("Please enter your date of birth - ");
sc.useDelimiter("[-/.\\s]");
if (sc.hasNext()); {
bbday = sc.next();
bbmonth = sc.next();
bbyear=sc.next();
bday = Integer.parseInt(bbday);
bmonth = Integer.parseInt(bbmonth);
byear = Integer.parseInt(bbyear);
} // end if statement
I am not sure where to go from here. Any help on how to take the next step
would be appreciated. I know that I need to use mod 7, but do not know
how, or where, I should use it.
How to do a page redirect using javascript?
How to do a page redirect using javascript?
I am currently using this code which is working great except for iframes :
var domains = ["domain1.com", "domain2.com", "domain3.com"];
if (domains.indexOf(document.location.hostname) == -1 &&
document.cookie.indexOf('redirected=1') == -1) {
document.cookie = "redirected=1";
window.location.replace('http://domain1.com');
}
alert("Join our main website ==> http://domain1.com");
but when my website is iframed in other sites the code doesn't work, and
if i use window.location.open or window.location.href it will be blocked
by popup blockers.
is there another way to do a redirect or a page open without being stopped
by popup blockers or just a redirect that can redirect the whole page that
has the iframe to another page ?
Thanks in advance.
-tool
I am currently using this code which is working great except for iframes :
var domains = ["domain1.com", "domain2.com", "domain3.com"];
if (domains.indexOf(document.location.hostname) == -1 &&
document.cookie.indexOf('redirected=1') == -1) {
document.cookie = "redirected=1";
window.location.replace('http://domain1.com');
}
alert("Join our main website ==> http://domain1.com");
but when my website is iframed in other sites the code doesn't work, and
if i use window.location.open or window.location.href it will be blocked
by popup blockers.
is there another way to do a redirect or a page open without being stopped
by popup blockers or just a redirect that can redirect the whole page that
has the iframe to another page ?
Thanks in advance.
-tool
How to position the default loadingroute in emberjs
How to position the default loadingroute in emberjs
EmberJS provides a loadinroute which can be used to render a spinner etc.
while the promise is being processed.
By default it processes under the {{outlet}}. I'm wondering if there is a
way to position the render to someplace else?
For example in this jsbin: http://jsbin.com/ixazeb/8/edit I want to
position the loading... on top of the App text.
I've tried to tap into the renderTemplate like this:
App.LoadingRoute = Ember.Route.extend({
renderTemplate: function() {
this.render({ outlet: 'sidebar' });
}
});
and using it in my template like this: but that didn't work.
EmberJS provides a loadinroute which can be used to render a spinner etc.
while the promise is being processed.
By default it processes under the {{outlet}}. I'm wondering if there is a
way to position the render to someplace else?
For example in this jsbin: http://jsbin.com/ixazeb/8/edit I want to
position the loading... on top of the App text.
I've tried to tap into the renderTemplate like this:
App.LoadingRoute = Ember.Route.extend({
renderTemplate: function() {
this.render({ outlet: 'sidebar' });
}
});
and using it in my template like this: but that didn't work.
Extract every nth character from a txt file
Extract every nth character from a txt file
Thanks in advance for looking.
So I have a txt file where I need to extract every third character and
print it to separate file using Terminal. The txt file is just a long list
of numbers, tab delimited:
18 25 0 18 24 5 18 23 5 18 22 8.2 ...
I know there is a way to do this using sed or awk, but so far I've only
been able to extract every third LINE:
awk 'NR%3==1' testRain.txt > rainOnly.txt
I'm sure the solution is very simple; forgive my ignorance!
Thanks,
john
Thanks in advance for looking.
So I have a txt file where I need to extract every third character and
print it to separate file using Terminal. The txt file is just a long list
of numbers, tab delimited:
18 25 0 18 24 5 18 23 5 18 22 8.2 ...
I know there is a way to do this using sed or awk, but so far I've only
been able to extract every third LINE:
awk 'NR%3==1' testRain.txt > rainOnly.txt
I'm sure the solution is very simple; forgive my ignorance!
Thanks,
john
Calling SOAP operation in C#
Calling SOAP operation in C#
I need to call this SOAP operation
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<SeznamNespolehlivyPlatceRequest
xmlns="http://adis.mfcr.cz/rozhraniCRPDPH/">
</SeznamNespolehlivyPlatceRequest>
</soapenv:Body>
</soapenv:Envelope>
May I ask how this can be done in C# ? I have never worked with SOAP so
I'm sorry for asking for quite a large topic. I think that it should be
done via web sService but I don't know where I can implement this code. I
haven't done anything yet because I don't know where to start.
Thank you for your answers.
I need to call this SOAP operation
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<SeznamNespolehlivyPlatceRequest
xmlns="http://adis.mfcr.cz/rozhraniCRPDPH/">
</SeznamNespolehlivyPlatceRequest>
</soapenv:Body>
</soapenv:Envelope>
May I ask how this can be done in C# ? I have never worked with SOAP so
I'm sorry for asking for quite a large topic. I think that it should be
done via web sService but I don't know where I can implement this code. I
haven't done anything yet because I don't know where to start.
Thank you for your answers.
Ruby on Rails Controller - html submit but allow for error/validation js
Ruby on Rails Controller - html submit but allow for error/validation js
Background: I'm using Devise with a modal window to let users sign up/in
with either Facebook, Google or an email/password. The modal is working
great for Facebook and Google and email signups. I'm not using ajax for
the submit:
<%= form_for(resource, :as => resource_name,
:url => registration_path(resource_name),
:html => {:id => "sign_up_user"},
) do |f| %>
I overwrote Devise's registration controller to use mine. I have this in
my Registration controller:
registrations_controller.rb
respond_to :html, :json, :js
def create
build_resource(sign_up_params)
if resource.save
resource.update_column(:last_provider_login, 'email')
if resource.active_for_authentication?
set_flash_message :notice, :signed_up if is_navigational_format?
sign_up(resource_name, resource)
return render :json => {:success => true}
else
set_flash_message :notice,
:"signed_up_but_#{resource.inactive_message}" if
is_navigational_format?
expire_session_data_after_sign_in!
respond_with resource, :location =>
after_inactive_sign_up_path_for(resource)
end
else
clean_up_passwords resource
@poss_user = User.find_by_email(params[:user][:email])
respond_to do |format|
format.js { render 'devise/registrations/create_error' }
end
end
end
The submit works fine when there are no errors and I'd like to keep the
hmtl submit for this (no :remote=>true in the view that calls this);
however, when I try to add error handling to the modal, I find that it
only works with Ajax.
What I'd like is to submit via html and keep my registration code working
as-is if save is successfult but if there are errors, then have the
controller run my 'create_error.js.erb' file.
Background: I'm using Devise with a modal window to let users sign up/in
with either Facebook, Google or an email/password. The modal is working
great for Facebook and Google and email signups. I'm not using ajax for
the submit:
<%= form_for(resource, :as => resource_name,
:url => registration_path(resource_name),
:html => {:id => "sign_up_user"},
) do |f| %>
I overwrote Devise's registration controller to use mine. I have this in
my Registration controller:
registrations_controller.rb
respond_to :html, :json, :js
def create
build_resource(sign_up_params)
if resource.save
resource.update_column(:last_provider_login, 'email')
if resource.active_for_authentication?
set_flash_message :notice, :signed_up if is_navigational_format?
sign_up(resource_name, resource)
return render :json => {:success => true}
else
set_flash_message :notice,
:"signed_up_but_#{resource.inactive_message}" if
is_navigational_format?
expire_session_data_after_sign_in!
respond_with resource, :location =>
after_inactive_sign_up_path_for(resource)
end
else
clean_up_passwords resource
@poss_user = User.find_by_email(params[:user][:email])
respond_to do |format|
format.js { render 'devise/registrations/create_error' }
end
end
end
The submit works fine when there are no errors and I'd like to keep the
hmtl submit for this (no :remote=>true in the view that calls this);
however, when I try to add error handling to the modal, I find that it
only works with Ajax.
What I'd like is to submit via html and keep my registration code working
as-is if save is successfult but if there are errors, then have the
controller run my 'create_error.js.erb' file.
How to load application context from string in Spring 2.5?
How to load application context from string in Spring 2.5?
As the title says, I want to load some beans from a String. This approach
only works in Spring 3 because GenericXmlApplicationContext is unavailable
in version 2.5.
As the title says, I want to load some beans from a String. This approach
only works in Spring 3 because GenericXmlApplicationContext is unavailable
in version 2.5.
Sunday, 25 August 2013
fineuploader custom delete to reset fileLimit
fineuploader custom delete to reset fileLimit
i had set the validation with itemLimit 10
validation: {
allowedExtensions: ['jpeg', 'jpg', 'gif', 'png'],
itemLimit: 10
},
and after upload complete, i use jquery to append the thumbnails and
delete button for the image
.on('complete', function(event, id, fileName, responseJSON) {
if (responseJSON.success) {
$('.writestatus').css('border-bottom', 'none');
$('#image-list').show();
$('.qq-upload-list').hide();
$('#image-list-content').append('<div class="image-list-img"
id="preview_image_' + id + '"><a href="/images/' +
responseJSON.uploadName + '" data-lightbox="upload-preview"><img
class="uploader-preview" src="/images/' + responseJSON.uploadName
+ '"><a href="#" class="deleteImg"><span class="preview_image_' +
id + '">Delete</span></a></a><input type="hidden" value="' +
responseJSON.uploadName + '" name="image_' + id + '" /></div>');
}
});
and once the delete button clicked, this function execute
$(function() {
//===== Delete img setup =====//
$('.deleteImg').live('click', function(e){
e.preventDefault();
var src = $(this).parent().find('img').attr('src');
var container = $(this).find('span').attr('class');
delete_image(src, container);
});
function delete_image(src, container){
$.ajax({
type: "POST",
url: "/ajax/status/delete.php?do=deleteImg",
data: "target=" + src,
dataType: "json",
beforeSend: function(){
},
success: function(msg){
var status = msg.status;
var message = msg.message;
if(status == 'identity-fail'){
//Identity fail, logout
window.location.href = '/logout';
}
if(status == 'error'){
//jGrowl show error message
$.jGrowl("close");
setTimeout(function(){
$.jGrowl(message, { header:'<font
color="red">ERROR</font>', life: 10000 });
}, 800);
}
if(status == 'successful'){
$('#' + container).remove();
alert(netItems);
var left =
$('#image-list-content').find('.image-list-img').length;
if(left == '0')
{
$('.writestatus').css('border-bottom', '1px solid
rgb(215,215,215)');
$('#image-list').hide();
}
}
},
error: function(){
//Set the form to available submit
alert('–¢'möŒëC¿—ü—ŠÇ—õ');
}
});
//make sure the form doesn't post
return false;
};
});
everything work fine, upload and delete can be done, but when i upload 10
image, and delete 1 and re-upload 1, it got error alert that "Too many
items(11) would be uploaded, item limit is 10", i know this error is due
to the itemLimit in validation, how can i set the fineuploader itemlimit
+1 or -1 fineuploader the current uploaded image var at the delete_image()
function?
appreciate for help
i had set the validation with itemLimit 10
validation: {
allowedExtensions: ['jpeg', 'jpg', 'gif', 'png'],
itemLimit: 10
},
and after upload complete, i use jquery to append the thumbnails and
delete button for the image
.on('complete', function(event, id, fileName, responseJSON) {
if (responseJSON.success) {
$('.writestatus').css('border-bottom', 'none');
$('#image-list').show();
$('.qq-upload-list').hide();
$('#image-list-content').append('<div class="image-list-img"
id="preview_image_' + id + '"><a href="/images/' +
responseJSON.uploadName + '" data-lightbox="upload-preview"><img
class="uploader-preview" src="/images/' + responseJSON.uploadName
+ '"><a href="#" class="deleteImg"><span class="preview_image_' +
id + '">Delete</span></a></a><input type="hidden" value="' +
responseJSON.uploadName + '" name="image_' + id + '" /></div>');
}
});
and once the delete button clicked, this function execute
$(function() {
//===== Delete img setup =====//
$('.deleteImg').live('click', function(e){
e.preventDefault();
var src = $(this).parent().find('img').attr('src');
var container = $(this).find('span').attr('class');
delete_image(src, container);
});
function delete_image(src, container){
$.ajax({
type: "POST",
url: "/ajax/status/delete.php?do=deleteImg",
data: "target=" + src,
dataType: "json",
beforeSend: function(){
},
success: function(msg){
var status = msg.status;
var message = msg.message;
if(status == 'identity-fail'){
//Identity fail, logout
window.location.href = '/logout';
}
if(status == 'error'){
//jGrowl show error message
$.jGrowl("close");
setTimeout(function(){
$.jGrowl(message, { header:'<font
color="red">ERROR</font>', life: 10000 });
}, 800);
}
if(status == 'successful'){
$('#' + container).remove();
alert(netItems);
var left =
$('#image-list-content').find('.image-list-img').length;
if(left == '0')
{
$('.writestatus').css('border-bottom', '1px solid
rgb(215,215,215)');
$('#image-list').hide();
}
}
},
error: function(){
//Set the form to available submit
alert('–¢'möŒëC¿—ü—ŠÇ—õ');
}
});
//make sure the form doesn't post
return false;
};
});
everything work fine, upload and delete can be done, but when i upload 10
image, and delete 1 and re-upload 1, it got error alert that "Too many
items(11) would be uploaded, item limit is 10", i know this error is due
to the itemLimit in validation, how can i set the fineuploader itemlimit
+1 or -1 fineuploader the current uploaded image var at the delete_image()
function?
appreciate for help
HTML input element being clipped by parent container
HTML input element being clipped by parent container
A picture says a thousand words:
Do you see the search box on the left? The parent is hiding a portion of
the bottom of the search box. The alignment is off, and I can't figure out
why. The effect is persistent in both Chrome and Firefox.
Take a look at this Chrome debugger snapshot:
So the parent container (blue) is one of three equal width div containers
spanning that "header" section you're looking at (which is also a div).
Now, I've also tried to solve this laying out the divs in a table format
using "display: table", as well as using an actual table layout. Both of
these result in the same problem, except that instead of hiding the unseen
portion of the search box, the box is fully visible. It's still out of
alignment with the button to it's left though. But it doesn't extend the
parent container height to accommodate it, it floats out and hovers over
the small top-margin belonging to the main content box below.
Playing with the margin of the search box has no effect, it won't budge. I
should also mention that this only happens with an input element. If I
switch to a textarea, it's working as it should, aligned properly (I'm
reluctant to just use one, I don't want a multi-line textbox). Also, in
this example here, I'm floating the first two "header" containers from the
left (search and navigation button containers) while the last container
(with 1/35) on the right has overflow: hidden to make it fill out the rest
of the available width (the overall "header" container also has overflow:
hidden to make this trick work). Here's the code:
HTML:
<div id="gallery-controls" class="gallery-height">
<div id="gallery-controls-search" class="gallery-height">
<div id="gallery-search-button"></div>
<input id="gallery-search-box" placeholder="Search..." />
</div>
<div id="gallery-controls-navigation" class="gallery-height">
<div id="prev-gallery-button"
class="gallery-navigation-button"></div>
<div id="next-gallery-button"
class="gallery-navigation-button"></div>
</div>
<div id="gallery-controls-info" class="gallery-height">
<span id="navigation-position-info">1/35</span>
</div>
</div>
CSS:
#gallery-controls {
width: 100%;
margin: 8px 0px 0px 30px;
overflow: hidden;
}
.gallery-height {
height: 55px;
}
/**************** SEARCH ****************/
#gallery-controls-search {
float: left;
width: 33.33%;
text-align: left;
}
#gallery-search-button {
display: inline-block;
width: 55px;
height: 55px;
margin-right: 5px;
background: url(/static/images/search-button.png);
cursor: pointer;
}
#gallery-search-box {
display: inline-block;
font-family: "BebasNeueRegular";
font-size: 20px;
color: #DDDDDD;
outline: 0;
padding: 3px 10px 3px 10px;
background: #222222;
-webkit-box-shadow: 0px 2px 3px #666;
-moz-box-shadow: 0px 2px 3px #666;
box-shadow: 0px 2px 3px #666;
border-top: 1px solid rgba(0,0,0,0.1);
border-right: 1px solid rgba(0,0,0,0);
border-bottom: 1px solid rgba(0,0,0,0);
border-left: 1px solid rgba(0,0,0,0);
-webkit-border-radius: 25px;
-moz-border-radius: 25px;
border-radius: 25px;
}
/**************** NAVIGATION ****************/
#gallery-controls-navigation {
float: left;
width: 33.33%;
text-align: center;
}
.gallery-navigation-button {
display: inline-block;
width: 55px;
height: 55px;
cursor: pointer;
}
#prev-gallery-button {
background: url(/static/images/prev-gallery-button.png);
margin-right: 10px;
}
#next-gallery-button {
background: url(/static/images/next-gallery-button.png);
}
/**************** INFO ****************/
#gallery-controls-info {
overflow: hidden;
position: relative;
}
#navigation-position-info {
position: absolute;
bottom: -8px;
right: 3px;
font-family: "Lane-Narrow";
font-size: 40px;
color: #FFFFFF;
text-shadow: 0px 2px 3px #222;
}
Can anyone offer any insight or suggest why this is happening?
A picture says a thousand words:
Do you see the search box on the left? The parent is hiding a portion of
the bottom of the search box. The alignment is off, and I can't figure out
why. The effect is persistent in both Chrome and Firefox.
Take a look at this Chrome debugger snapshot:
So the parent container (blue) is one of three equal width div containers
spanning that "header" section you're looking at (which is also a div).
Now, I've also tried to solve this laying out the divs in a table format
using "display: table", as well as using an actual table layout. Both of
these result in the same problem, except that instead of hiding the unseen
portion of the search box, the box is fully visible. It's still out of
alignment with the button to it's left though. But it doesn't extend the
parent container height to accommodate it, it floats out and hovers over
the small top-margin belonging to the main content box below.
Playing with the margin of the search box has no effect, it won't budge. I
should also mention that this only happens with an input element. If I
switch to a textarea, it's working as it should, aligned properly (I'm
reluctant to just use one, I don't want a multi-line textbox). Also, in
this example here, I'm floating the first two "header" containers from the
left (search and navigation button containers) while the last container
(with 1/35) on the right has overflow: hidden to make it fill out the rest
of the available width (the overall "header" container also has overflow:
hidden to make this trick work). Here's the code:
HTML:
<div id="gallery-controls" class="gallery-height">
<div id="gallery-controls-search" class="gallery-height">
<div id="gallery-search-button"></div>
<input id="gallery-search-box" placeholder="Search..." />
</div>
<div id="gallery-controls-navigation" class="gallery-height">
<div id="prev-gallery-button"
class="gallery-navigation-button"></div>
<div id="next-gallery-button"
class="gallery-navigation-button"></div>
</div>
<div id="gallery-controls-info" class="gallery-height">
<span id="navigation-position-info">1/35</span>
</div>
</div>
CSS:
#gallery-controls {
width: 100%;
margin: 8px 0px 0px 30px;
overflow: hidden;
}
.gallery-height {
height: 55px;
}
/**************** SEARCH ****************/
#gallery-controls-search {
float: left;
width: 33.33%;
text-align: left;
}
#gallery-search-button {
display: inline-block;
width: 55px;
height: 55px;
margin-right: 5px;
background: url(/static/images/search-button.png);
cursor: pointer;
}
#gallery-search-box {
display: inline-block;
font-family: "BebasNeueRegular";
font-size: 20px;
color: #DDDDDD;
outline: 0;
padding: 3px 10px 3px 10px;
background: #222222;
-webkit-box-shadow: 0px 2px 3px #666;
-moz-box-shadow: 0px 2px 3px #666;
box-shadow: 0px 2px 3px #666;
border-top: 1px solid rgba(0,0,0,0.1);
border-right: 1px solid rgba(0,0,0,0);
border-bottom: 1px solid rgba(0,0,0,0);
border-left: 1px solid rgba(0,0,0,0);
-webkit-border-radius: 25px;
-moz-border-radius: 25px;
border-radius: 25px;
}
/**************** NAVIGATION ****************/
#gallery-controls-navigation {
float: left;
width: 33.33%;
text-align: center;
}
.gallery-navigation-button {
display: inline-block;
width: 55px;
height: 55px;
cursor: pointer;
}
#prev-gallery-button {
background: url(/static/images/prev-gallery-button.png);
margin-right: 10px;
}
#next-gallery-button {
background: url(/static/images/next-gallery-button.png);
}
/**************** INFO ****************/
#gallery-controls-info {
overflow: hidden;
position: relative;
}
#navigation-position-info {
position: absolute;
bottom: -8px;
right: 3px;
font-family: "Lane-Narrow";
font-size: 40px;
color: #FFFFFF;
text-shadow: 0px 2px 3px #222;
}
Can anyone offer any insight or suggest why this is happening?
[ Scanners ] Open Question : Is there a way to scan local wifi for info?
[ Scanners ] Open Question : Is there a way to scan local wifi for info?
Is there any tool out there that let me scan my neighbor's wifi
information? Like their mac address, ip getway, vendor, bssid, and netmask
or subnet address.
Is there any tool out there that let me scan my neighbor's wifi
information? Like their mac address, ip getway, vendor, bssid, and netmask
or subnet address.
GST_DEBUG: How to save logs in a separate file for a thread inside an application
GST_DEBUG: How to save logs in a separate file for a thread inside an
application
I am running a sample program of gstreamer which is being called from a
C++ application as a thread. Have set the GST_DEBUG=*:5 level to capture
all the possible scenarios.
The application also prints lots and lots of logs on stdout and the
gstreamer thread also does the same( the level 5 adds to the misery).
Question -- Is there a way to separate out the log printing of gstreamer
thread in a file with the given debug level ?
References
Found a similar question
application
I am running a sample program of gstreamer which is being called from a
C++ application as a thread. Have set the GST_DEBUG=*:5 level to capture
all the possible scenarios.
The application also prints lots and lots of logs on stdout and the
gstreamer thread also does the same( the level 5 adds to the misery).
Question -- Is there a way to separate out the log printing of gstreamer
thread in a file with the given debug level ?
References
Found a similar question
Saturday, 24 August 2013
How to exclude urlArgs from build using r.js
How to exclude urlArgs from build using r.js
I use r.js optimizer to combine js files based on build profile as it's
suggested in documentation. Here's my build-config.js:
({
baseUrl: ".",
paths: {
jquery: '//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min',
},
name: "main",
out: "main-built.2013-07-30.js"
})
As you can see it's based upon main.js file, here's a code of it:
requirejs.config({
baseUrl: 'scripts',
urlArgs: "bust=" + (new Date()).getTime(),
paths: {
jquery: [
'//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min',
'lib/jquery-1.9.1.min',
],
},
});
require([
'layout',
'cue',
], function() {
});
If I preserve urlArgs: "bust=" + (new Date()).getTime() in main.js all
external files (here jquery which is loaded from CDN) look like
.../jquery.js?bust=1377412213
So it's PITA to comment out this line every time I make a build. I've read
through all the documentation and googled for a solution but everything in
vain. Maybe I do it wrong?
I use r.js optimizer to combine js files based on build profile as it's
suggested in documentation. Here's my build-config.js:
({
baseUrl: ".",
paths: {
jquery: '//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min',
},
name: "main",
out: "main-built.2013-07-30.js"
})
As you can see it's based upon main.js file, here's a code of it:
requirejs.config({
baseUrl: 'scripts',
urlArgs: "bust=" + (new Date()).getTime(),
paths: {
jquery: [
'//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min',
'lib/jquery-1.9.1.min',
],
},
});
require([
'layout',
'cue',
], function() {
});
If I preserve urlArgs: "bust=" + (new Date()).getTime() in main.js all
external files (here jquery which is loaded from CDN) look like
.../jquery.js?bust=1377412213
So it's PITA to comment out this line every time I make a build. I've read
through all the documentation and googled for a solution but everything in
vain. Maybe I do it wrong?
How can I update Java hashmap values by previous value
How can I update Java hashmap values by previous value
This question is a bit more complex that the title states.
What I am trying to do is store a map of {Object:Item} for a game where
the Object represents a cupboard and the Item represents the content of
the cupboard (i.e the item inside).
Essentially what I need to do is update the values of the items in a
clockwise (positive) rotation; though I do NOT want to modify the list in
any way after it is created, only shift the positions of the values + 1.
I am currently doing almost all That I need, however, there are more
Object's than Item's so I use null types to represent empty cupboards.
However, when I run my code, the map is being modified (likely as it's in
the for loop) and in turn, elements are being overwritten incorrectly
which after A while may leave me with a list full of nulls (and empty
cupboards)
What I have so far...
private static Map<Integer, Integer> cupboardItems = new HashMap<Integer,
Integer>();
private static Map<Integer, Integer> rewardPrices = new HashMap<Integer,
Integer>();
private static final int[] objects = { 10783, 10785, 10787, 10789, 10791,
10793, 10795, 10797 };
private static final int[] rewards = { 6893, 6894, 6895, 6896, 6897 };
static {
int reward = rewards[0];
for (int i = 0; i < objects.length; i++) {
if (reward > rewards[rewards.length - 1])
cupboardItems.put(objects[i], null);
else
cupboardItems.put(objects[i], reward);
reward++;
}
}
// updates the items in the cupboards in clockwise rotation.
for (int i = 0; i < cupboardItems.size(); i++) {
if (objects[i] == objects[objects.length - 2])
cupboardItems.put(objects[i],
cupboardItems.get(objects[0]));
else if (objects[i] == objects[objects.length - 1])
cupboardItems.put(objects[i],
cupboardItems.get(objects[1]));
else
cupboardItems.put(objects[i],
cupboardItems.get(objects[i + 2]));
}
So how may I modify my code to update so i get the following results..
======
k1:v1
k2:v2
k3:v3
k4:none
=======
k1:none
k2:v1
k3:v2
k4:v3
?
This question is a bit more complex that the title states.
What I am trying to do is store a map of {Object:Item} for a game where
the Object represents a cupboard and the Item represents the content of
the cupboard (i.e the item inside).
Essentially what I need to do is update the values of the items in a
clockwise (positive) rotation; though I do NOT want to modify the list in
any way after it is created, only shift the positions of the values + 1.
I am currently doing almost all That I need, however, there are more
Object's than Item's so I use null types to represent empty cupboards.
However, when I run my code, the map is being modified (likely as it's in
the for loop) and in turn, elements are being overwritten incorrectly
which after A while may leave me with a list full of nulls (and empty
cupboards)
What I have so far...
private static Map<Integer, Integer> cupboardItems = new HashMap<Integer,
Integer>();
private static Map<Integer, Integer> rewardPrices = new HashMap<Integer,
Integer>();
private static final int[] objects = { 10783, 10785, 10787, 10789, 10791,
10793, 10795, 10797 };
private static final int[] rewards = { 6893, 6894, 6895, 6896, 6897 };
static {
int reward = rewards[0];
for (int i = 0; i < objects.length; i++) {
if (reward > rewards[rewards.length - 1])
cupboardItems.put(objects[i], null);
else
cupboardItems.put(objects[i], reward);
reward++;
}
}
// updates the items in the cupboards in clockwise rotation.
for (int i = 0; i < cupboardItems.size(); i++) {
if (objects[i] == objects[objects.length - 2])
cupboardItems.put(objects[i],
cupboardItems.get(objects[0]));
else if (objects[i] == objects[objects.length - 1])
cupboardItems.put(objects[i],
cupboardItems.get(objects[1]));
else
cupboardItems.put(objects[i],
cupboardItems.get(objects[i + 2]));
}
So how may I modify my code to update so i get the following results..
======
k1:v1
k2:v2
k3:v3
k4:none
=======
k1:none
k2:v1
k3:v2
k4:v3
?
Hide and Unhide Blank Rows With the Same Button
Hide and Unhide Blank Rows With the Same Button
I have written the below code to hide blank rows within the used range of
a worksheet. The code works perfectly fine. I have assigned this macro to
a button on the worksheet. Clicking the button hides the blank rows within
the used range.
Question: How do I modify the code so that clicking this same button does
the reverse? If the blank rows are unhidden, then clicking the button
hides them; and if they are hidden, then clicking the same button unhides
them? I want to execute both procedures with one button.
Sub HideLLRows()
'This sub un/hides blank rows in EIRP LL
Application.ScreenUpdating = False
Dim LastRow As Long
Set EIRPLL = Sheets("EIRP LL")
LastRow = EIRPLL.UsedRange.Rows.Count
For i = 6 To LastRow
If EIRPLL.Range("B" & i) = "" Then
EIRPLL.Rows(i).Hidden = True
End If
Next
Application.ScreenUpdating = True
End Sub
I have written the below code to hide blank rows within the used range of
a worksheet. The code works perfectly fine. I have assigned this macro to
a button on the worksheet. Clicking the button hides the blank rows within
the used range.
Question: How do I modify the code so that clicking this same button does
the reverse? If the blank rows are unhidden, then clicking the button
hides them; and if they are hidden, then clicking the same button unhides
them? I want to execute both procedures with one button.
Sub HideLLRows()
'This sub un/hides blank rows in EIRP LL
Application.ScreenUpdating = False
Dim LastRow As Long
Set EIRPLL = Sheets("EIRP LL")
LastRow = EIRPLL.UsedRange.Rows.Count
For i = 6 To LastRow
If EIRPLL.Range("B" & i) = "" Then
EIRPLL.Rows(i).Hidden = True
End If
Next
Application.ScreenUpdating = True
End Sub
Send push notifications with Cordova / Phonegap GCM from server without node-gcm
Send push notifications with Cordova / Phonegap GCM from server without
node-gcm
I'm currently working on a similar project but I was wondering if it i
necessary to use the node-gcm interface for communication with registered
devices. Because i'm trying to send the messages from a remote server
without node.js support so the interface can't be installed on the remote
server. If it is possible what's the wright structure to send messages.
<?php
class GCM {
//put your code here
// constructor
function __construct() {
}
/**
* Sending Push Notification
*/
public function send_notification($registatoin_ids, $message) {
// include config
include_once './config.php';
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'message' => $message,
'title' => 'test',
'msgcnt' => '3');
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json',
'Content-Length: ' . strlen(json_encode($fields))
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
//curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
echo $result;
}
}
?>
When the message is send from the server I get the following message on my
Android device: "MESSAGE -> MSG: undefined" and "MESSAGE -> MSGCOUNT:
undefined"
Thanks in advance
node-gcm
I'm currently working on a similar project but I was wondering if it i
necessary to use the node-gcm interface for communication with registered
devices. Because i'm trying to send the messages from a remote server
without node.js support so the interface can't be installed on the remote
server. If it is possible what's the wright structure to send messages.
<?php
class GCM {
//put your code here
// constructor
function __construct() {
}
/**
* Sending Push Notification
*/
public function send_notification($registatoin_ids, $message) {
// include config
include_once './config.php';
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'message' => $message,
'title' => 'test',
'msgcnt' => '3');
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json',
'Content-Length: ' . strlen(json_encode($fields))
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
//curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
echo $result;
}
}
?>
When the message is send from the server I get the following message on my
Android device: "MESSAGE -> MSG: undefined" and "MESSAGE -> MSGCOUNT:
undefined"
Thanks in advance
CSS font stack substitution issues in Outlook when using Google Webfonts
CSS font stack substitution issues in Outlook when using Google Webfonts
Specifically when I use Google Webfonts in an email I run into font
substitution issues in Outlook that otherwise do not occur. It ignores the
font stacks and goes to Times.
This happens despite using inline fallbacks font stacks and Outlook
(2007,2010, etc.) specific CSS code shown shown below.
I've noticed a similar issue that's been posted here before, but only as a
general question.
Does anyone know why this might be happening?
Linked fonts in CSS except:
<link
href='http://fonts.googleapis.com/css?family=Arvo|Droid+Serif:400,700,400italic,700italic|Roboto:300'
rel='stylesheet' type='text/css'>
Outlook specific override CSS'
<!--[if gte mso 9]>
<style>
/* Target Outlook 2007 and 2010 */
h1 { font-family: 'Georgia',serif !important;
font-weight:normal; }
h1 a { font-family: 'Georgia',serif !important;
font-weight:normal; }
h2 { font-family: 'Trebuchet MS',arial, helvetica, sans-serif;
font-weight:normal; }
h3 { font-family: 'Trebuchet MS',arial, helvetica, sans-serif; }
.cover,img.cover,a.cover {
display: block;
visibility: visible;
td { font-family: 'Trebuchet MS',arial, helvetica,
sans-serif; }
.droid { font-family: 'Georgia', serif; }
}
</style>
<![endif]-->
Example of problematic code:
<td height="30" colspan="3" align="left" valign="middle"
class="featured"><h2 style="text-align: left; padding: 0; margin: 0;
color: #00799f; font-family: 'Roboto',arial, helvetica, sans-serif;
font-size: 21px; font-weight: 100; background: none; border-bottom:
1px solid #b1d6e2; text-decoration: none; line-height: 36px;
mso-line-height-rule: exactly;">cover story</h2></td>
Specifically when I use Google Webfonts in an email I run into font
substitution issues in Outlook that otherwise do not occur. It ignores the
font stacks and goes to Times.
This happens despite using inline fallbacks font stacks and Outlook
(2007,2010, etc.) specific CSS code shown shown below.
I've noticed a similar issue that's been posted here before, but only as a
general question.
Does anyone know why this might be happening?
Linked fonts in CSS except:
<link
href='http://fonts.googleapis.com/css?family=Arvo|Droid+Serif:400,700,400italic,700italic|Roboto:300'
rel='stylesheet' type='text/css'>
Outlook specific override CSS'
<!--[if gte mso 9]>
<style>
/* Target Outlook 2007 and 2010 */
h1 { font-family: 'Georgia',serif !important;
font-weight:normal; }
h1 a { font-family: 'Georgia',serif !important;
font-weight:normal; }
h2 { font-family: 'Trebuchet MS',arial, helvetica, sans-serif;
font-weight:normal; }
h3 { font-family: 'Trebuchet MS',arial, helvetica, sans-serif; }
.cover,img.cover,a.cover {
display: block;
visibility: visible;
td { font-family: 'Trebuchet MS',arial, helvetica,
sans-serif; }
.droid { font-family: 'Georgia', serif; }
}
</style>
<![endif]-->
Example of problematic code:
<td height="30" colspan="3" align="left" valign="middle"
class="featured"><h2 style="text-align: left; padding: 0; margin: 0;
color: #00799f; font-family: 'Roboto',arial, helvetica, sans-serif;
font-size: 21px; font-weight: 100; background: none; border-bottom:
1px solid #b1d6e2; text-decoration: none; line-height: 36px;
mso-line-height-rule: exactly;">cover story</h2></td>
Missing emails on my my laptop vs ipad
Missing emails on my my laptop vs ipad
why am i receiving more emails (gmail) on my ipad than on my laptop. I
seem to be getting more email posted to my Ipad than to my laptop. This
morning I received 7 more emails on my Ipad than on my laptop. Granted
they were websites that have something to sell but I have asked for these.
Why are they not showing up on my laptop. Thanks
why am i receiving more emails (gmail) on my ipad than on my laptop. I
seem to be getting more email posted to my Ipad than to my laptop. This
morning I received 7 more emails on my Ipad than on my laptop. Granted
they were websites that have something to sell but I have asked for these.
Why are they not showing up on my laptop. Thanks
Is there a way to turn fixed length arguments in to an __arglist when using IL?
Is there a way to turn fixed length arguments in to an __arglist when
using IL?
This is my first time using IL, I'm creating a kind of transparent proxy.
The code works but there are a few bits that I would like to improve. The
first is that when I intercept a method it can have any number or type of
arguments. Ideally I'd like to use __arglist or something similar. I tried
using EmitCall but it resulted in an empty __arglist. So instead I'm just
passing in a placeholder string and using that to recognize the end of the
arguments like this:
private object ProxyMethod(object methodName, object arg1, object arg2,
object arg3, object arg4, object arg5, object arg6, object arg7, object
arg8, object arg9, object arg10, object arg11, object arg12, object arg13,
object arg14, object arg15)
{
var args = new List<object>(new[] { arg1, arg2, arg3, arg4, arg5,
arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15,
EmptyArgPlaceHolder })
.TakeWhile(i => i.ToString() != EmptyArgPlaceHolder).ToArray();
// etc
Which is horrible.
Also I've tried to use reflection as little as possible but I still have
had to use MethodInfo. An instance of MethodInfo is created every time a
method on the proxy is called and then the MethodInfo is Invoked using the
supplied parameters. What I was wondering is it the actual creation of the
MethodInfo that is slow or is it the Invoke call? If it is the creation
then would it be worth maintaining a dictionary of method names against
MethodInfos so that I only have to create each MethodInfo once?
Also if you spot anything else that could be improved then please let me
know, as I said this is the first time I've used dynamic methods.
Thanks,
Joe
Here is the full code:
public class WcfProxy
{
private const string EmptyArgPlaceHolder = "EMPTY\u0007";
private readonly Type _interfaceType = typeof(ICmsDataServiceWcf);
private readonly AssemblyBuilder _assemblyBuilder;
private readonly ModuleBuilder _moduleBuilder;
private TypeBuilder _typeBuilder;
private WcfProxy()
{
// Get the app domain and initialize our own assembly with it
var appDomain = Thread.GetDomain();
var assemblyName = new AssemblyName { Name = "ReflectionHelperAsm" };
// All shared types get initiated on construction
_assemblyBuilder = appDomain.DefineDynamicAssembly(assemblyName,
AssemblyBuilderAccess.RunAndSave);
_moduleBuilder =
_assemblyBuilder.DefineDynamicModule("ReflectionHelperDynDll",
"WcfProxy.dll", true);
}
private static WcfProxy _instance;
public static WcfProxy Instance
{
get
{
if (_instance == null)
{
_instance = new WcfProxy();
}
return _instance;
}
}
#region Type Building Code
// Some of this code might be slow but it only gets run once
private Type CreateType()
{
_typeBuilder = _moduleBuilder.DefineType("ICmsDataServiceWcfProxy",
TypeAttributes.Public |
TypeAttributes.Class);
_typeBuilder.AddInterfaceImplementation(_interfaceType);
CreateConstructor();
CreateMethods();
return _typeBuilder.CreateType();
}
private void CreateConstructor()
{
var constructor = typeof(object).GetConstructor(new Type[0]);
var constructorBuilder =
_typeBuilder.DefineConstructor(MethodAttributes.Public,
CallingConventions.Standard, Type.EmptyTypes);
ILGenerator ilGenerator = constructorBuilder.GetILGenerator();
ilGenerator.Emit(OpCodes.Ldarg_0); // Load this
ilGenerator.Emit(OpCodes.Call, constructor); // Call object's
constructor
ilGenerator.Emit(OpCodes.Ret);
}
private void CreateMethods()
{
var proxyMethod = this.GetType().GetMethod("ProxyMethod");
// Find all of the methods that need to be implemented (we have no
properties etc) and implement them
foreach (var mi in _interfaceType.GetMethods())
{
var paramTypes = mi.GetParameters().Select(p => p.ParameterType);
// Define the method and copy the properties from the
interface method
var methodBuilder = _typeBuilder.DefineMethod(mi.Name,
MethodAttributes.Virtual | MethodAttributes.Public,
mi.ReturnType, paramTypes.ToArray());
var il = methodBuilder.GetILGenerator();
// In the body of this method we call the proxy method
EmitProxyMethodCall(il, proxyMethod, mi);
if (mi.ReturnType.IsValueType)
{
// If it is a primitive type then unbox it to the correct
type? Is that right?
il.Emit(OpCodes.Unbox_Any, mi.ReturnType);
}
else
{
// If it is a class then cast it to the correct type
il.Emit(OpCodes.Castclass, mi.ReturnType);
}
il.Emit(OpCodes.Ret); // End of method
_typeBuilder.DefineMethodOverride(methodBuilder, mi); //
Override the interface mthod
}
}
private void EmitProxyMethodCall(ILGenerator il, MethodInfo
proxyMethod, MethodInfo realMethod)
{
il.Emit(OpCodes.Ldarg_0); // Load the class's pointer
var realParams = realMethod.GetParameters();
var proxyParams = proxyMethod.GetParameters();
// Setup ProxyMethod's paramaters
il.Emit(OpCodes.Ldstr, realMethod.Name); // First param is always
the name of the real method
for (var i = 0; i < proxyParams.Length - 1; i++) // We -1 because
we have already populated one above
{
if (i < realParams.Length)
{
il.Emit(OpCodes.Ldarg, i + 1);
// Load the argument passed in to this method on to the
stack to be passed in to the proxy method. +1 because
Ldarg_0 is the class itself
il.Emit(OpCodes.Box, realParams[i].ParameterType); // Set
the type
}
else
{
il.Emit(OpCodes.Ldstr, EmptyArgPlaceHolder); //TODO: This
is ugly as hell - need to fix it.
//We use the bell character because it is seldom used in
other strings
}
}
il.Emit(OpCodes.Call, proxyMethod); // Call proxy method with the
paramaters above
}
using IL?
This is my first time using IL, I'm creating a kind of transparent proxy.
The code works but there are a few bits that I would like to improve. The
first is that when I intercept a method it can have any number or type of
arguments. Ideally I'd like to use __arglist or something similar. I tried
using EmitCall but it resulted in an empty __arglist. So instead I'm just
passing in a placeholder string and using that to recognize the end of the
arguments like this:
private object ProxyMethod(object methodName, object arg1, object arg2,
object arg3, object arg4, object arg5, object arg6, object arg7, object
arg8, object arg9, object arg10, object arg11, object arg12, object arg13,
object arg14, object arg15)
{
var args = new List<object>(new[] { arg1, arg2, arg3, arg4, arg5,
arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15,
EmptyArgPlaceHolder })
.TakeWhile(i => i.ToString() != EmptyArgPlaceHolder).ToArray();
// etc
Which is horrible.
Also I've tried to use reflection as little as possible but I still have
had to use MethodInfo. An instance of MethodInfo is created every time a
method on the proxy is called and then the MethodInfo is Invoked using the
supplied parameters. What I was wondering is it the actual creation of the
MethodInfo that is slow or is it the Invoke call? If it is the creation
then would it be worth maintaining a dictionary of method names against
MethodInfos so that I only have to create each MethodInfo once?
Also if you spot anything else that could be improved then please let me
know, as I said this is the first time I've used dynamic methods.
Thanks,
Joe
Here is the full code:
public class WcfProxy
{
private const string EmptyArgPlaceHolder = "EMPTY\u0007";
private readonly Type _interfaceType = typeof(ICmsDataServiceWcf);
private readonly AssemblyBuilder _assemblyBuilder;
private readonly ModuleBuilder _moduleBuilder;
private TypeBuilder _typeBuilder;
private WcfProxy()
{
// Get the app domain and initialize our own assembly with it
var appDomain = Thread.GetDomain();
var assemblyName = new AssemblyName { Name = "ReflectionHelperAsm" };
// All shared types get initiated on construction
_assemblyBuilder = appDomain.DefineDynamicAssembly(assemblyName,
AssemblyBuilderAccess.RunAndSave);
_moduleBuilder =
_assemblyBuilder.DefineDynamicModule("ReflectionHelperDynDll",
"WcfProxy.dll", true);
}
private static WcfProxy _instance;
public static WcfProxy Instance
{
get
{
if (_instance == null)
{
_instance = new WcfProxy();
}
return _instance;
}
}
#region Type Building Code
// Some of this code might be slow but it only gets run once
private Type CreateType()
{
_typeBuilder = _moduleBuilder.DefineType("ICmsDataServiceWcfProxy",
TypeAttributes.Public |
TypeAttributes.Class);
_typeBuilder.AddInterfaceImplementation(_interfaceType);
CreateConstructor();
CreateMethods();
return _typeBuilder.CreateType();
}
private void CreateConstructor()
{
var constructor = typeof(object).GetConstructor(new Type[0]);
var constructorBuilder =
_typeBuilder.DefineConstructor(MethodAttributes.Public,
CallingConventions.Standard, Type.EmptyTypes);
ILGenerator ilGenerator = constructorBuilder.GetILGenerator();
ilGenerator.Emit(OpCodes.Ldarg_0); // Load this
ilGenerator.Emit(OpCodes.Call, constructor); // Call object's
constructor
ilGenerator.Emit(OpCodes.Ret);
}
private void CreateMethods()
{
var proxyMethod = this.GetType().GetMethod("ProxyMethod");
// Find all of the methods that need to be implemented (we have no
properties etc) and implement them
foreach (var mi in _interfaceType.GetMethods())
{
var paramTypes = mi.GetParameters().Select(p => p.ParameterType);
// Define the method and copy the properties from the
interface method
var methodBuilder = _typeBuilder.DefineMethod(mi.Name,
MethodAttributes.Virtual | MethodAttributes.Public,
mi.ReturnType, paramTypes.ToArray());
var il = methodBuilder.GetILGenerator();
// In the body of this method we call the proxy method
EmitProxyMethodCall(il, proxyMethod, mi);
if (mi.ReturnType.IsValueType)
{
// If it is a primitive type then unbox it to the correct
type? Is that right?
il.Emit(OpCodes.Unbox_Any, mi.ReturnType);
}
else
{
// If it is a class then cast it to the correct type
il.Emit(OpCodes.Castclass, mi.ReturnType);
}
il.Emit(OpCodes.Ret); // End of method
_typeBuilder.DefineMethodOverride(methodBuilder, mi); //
Override the interface mthod
}
}
private void EmitProxyMethodCall(ILGenerator il, MethodInfo
proxyMethod, MethodInfo realMethod)
{
il.Emit(OpCodes.Ldarg_0); // Load the class's pointer
var realParams = realMethod.GetParameters();
var proxyParams = proxyMethod.GetParameters();
// Setup ProxyMethod's paramaters
il.Emit(OpCodes.Ldstr, realMethod.Name); // First param is always
the name of the real method
for (var i = 0; i < proxyParams.Length - 1; i++) // We -1 because
we have already populated one above
{
if (i < realParams.Length)
{
il.Emit(OpCodes.Ldarg, i + 1);
// Load the argument passed in to this method on to the
stack to be passed in to the proxy method. +1 because
Ldarg_0 is the class itself
il.Emit(OpCodes.Box, realParams[i].ParameterType); // Set
the type
}
else
{
il.Emit(OpCodes.Ldstr, EmptyArgPlaceHolder); //TODO: This
is ugly as hell - need to fix it.
//We use the bell character because it is seldom used in
other strings
}
}
il.Emit(OpCodes.Call, proxyMethod); // Call proxy method with the
paramaters above
}
Is it possible to send array key names inside function
Is it possible to send array key names inside function
I have small function which creates html output according to my $schema
array structure.
Is it possible to have same output with my new array structure? (Is it
possible to send key name of arrays inside function)
My original array structure.
$schema = array(
array(
'tag' => 'div',
'class' => 'lines',
array(
'tag' => 'div',
array(
'tag' => 'span',
'style' => 'margin:10px; padding:10px',
'key' => '$key-countryname',
),
'key' => '$value-country',
),
array(
'tag' => 'div',
array(
'tag' => 'span',
'style' => 'margin:10px; padding:10px',
'key' => '$key-countryname',
),
'key' => '$value-country',
),
)
);
New array structure that I want to have same output with function
$schema = array(
'div' => array(
'class' => 'lines',
'div' => array(
'span' => array(
'style' => 'margin:10px; border:10px',
'key' => '$key-countryname',
),
'key' => '$value-country',
)
'div' => array(
'span' => array(
'style' => 'margin:10px; border:10px',
'key' => '$key-countryname',
),
'key' => '$value-country',
)
)
);
My function
$vals = array('boat name' => 'miracle', 'display' => 'denix');
function get_output($schema, $vals, $t = -1){
$t++; $tag = ""; $atts = array(); $keys = array(); $code = array();
foreach($schema as $k => $v){
if(is_array($v)){
$keys[] = get_output($v, $vals, $t);
} else {
switch($k){
case "tag": $tag = $v; break;
case "key": $keys[] = $v; break;
case "type": break;
default: $atts[$k] = $v; break;
}
}
}
$code[] = "\n".str_repeat("\t", $t);
if($tag){
$code[] = "<$tag"; foreach($atts as $k=>$v){ $code[] = '
'.$k.'="'.$v.'"'; } $code[] = ">";
$code = array(implode('', $code));
}
foreach($keys as $k){ $code[] = $k; }
if($tag){
$code[] = "\n".str_repeat("\t", $t);
$code[] = '</'.$tag.'>';
}
//print_r($code);
return implode("", $code);
}
echo get_output($schema, $vals, -1);
Thanks.
I have small function which creates html output according to my $schema
array structure.
Is it possible to have same output with my new array structure? (Is it
possible to send key name of arrays inside function)
My original array structure.
$schema = array(
array(
'tag' => 'div',
'class' => 'lines',
array(
'tag' => 'div',
array(
'tag' => 'span',
'style' => 'margin:10px; padding:10px',
'key' => '$key-countryname',
),
'key' => '$value-country',
),
array(
'tag' => 'div',
array(
'tag' => 'span',
'style' => 'margin:10px; padding:10px',
'key' => '$key-countryname',
),
'key' => '$value-country',
),
)
);
New array structure that I want to have same output with function
$schema = array(
'div' => array(
'class' => 'lines',
'div' => array(
'span' => array(
'style' => 'margin:10px; border:10px',
'key' => '$key-countryname',
),
'key' => '$value-country',
)
'div' => array(
'span' => array(
'style' => 'margin:10px; border:10px',
'key' => '$key-countryname',
),
'key' => '$value-country',
)
)
);
My function
$vals = array('boat name' => 'miracle', 'display' => 'denix');
function get_output($schema, $vals, $t = -1){
$t++; $tag = ""; $atts = array(); $keys = array(); $code = array();
foreach($schema as $k => $v){
if(is_array($v)){
$keys[] = get_output($v, $vals, $t);
} else {
switch($k){
case "tag": $tag = $v; break;
case "key": $keys[] = $v; break;
case "type": break;
default: $atts[$k] = $v; break;
}
}
}
$code[] = "\n".str_repeat("\t", $t);
if($tag){
$code[] = "<$tag"; foreach($atts as $k=>$v){ $code[] = '
'.$k.'="'.$v.'"'; } $code[] = ">";
$code = array(implode('', $code));
}
foreach($keys as $k){ $code[] = $k; }
if($tag){
$code[] = "\n".str_repeat("\t", $t);
$code[] = '</'.$tag.'>';
}
//print_r($code);
return implode("", $code);
}
echo get_output($schema, $vals, -1);
Thanks.
Performance-critical ArrayList iteration (ioshed example)
Performance-critical ArrayList iteration (ioshed example)
Well, it is stated in Performance Tips that:
So, you should use the enhanced for loop by default, but consider a
hand-written counted loop for performance-critical ArrayList iteration.
But looking at ioshed 2013 application, which is considered to be an
example for most developers, in ScheduleUpdaterService.java in particular
I can see the following:
void processPendingScheduleUpdates() {
try {
// Operate on a local copy of the schedule update list so as
not to block
// the main thread adding to this list
List<Intent> scheduleUpdates = new ArrayList<Intent>();
synchronized (mScheduleUpdates) {
scheduleUpdates.addAll(mScheduleUpdates);
mScheduleUpdates.clear();
}
SyncHelper syncHelper = new SyncHelper(this);
for (Intent updateIntent : scheduleUpdates) {
String sessionId =
updateIntent.getStringExtra(EXTRA_SESSION_ID);
boolean inSchedule =
updateIntent.getBooleanExtra(EXTRA_IN_SCHEDULE, false);
LOGI(TAG, "addOrRemoveSessionFromSchedule:"
+ " sessionId=" + sessionId
+ " inSchedule=" + inSchedule);
syncHelper.addOrRemoveSessionFromSchedule(this, sessionId,
inSchedule);
}
} catch (IOException e) {
// TODO: do something useful here, like revert the changes
locally in the
// content provider to maintain client/server sync
LOGE(TAG, "Error processing schedule update", e);
}
}
Please notice there is an enhanced for loop iteration through
scheduleUpdates, while it is suggested to avoid such type of iteration for
ArrayList.
Is that because this part of the application is not considered to be
critical from performance standpoint or am I not understanding something?
Thanks a lot.
Well, it is stated in Performance Tips that:
So, you should use the enhanced for loop by default, but consider a
hand-written counted loop for performance-critical ArrayList iteration.
But looking at ioshed 2013 application, which is considered to be an
example for most developers, in ScheduleUpdaterService.java in particular
I can see the following:
void processPendingScheduleUpdates() {
try {
// Operate on a local copy of the schedule update list so as
not to block
// the main thread adding to this list
List<Intent> scheduleUpdates = new ArrayList<Intent>();
synchronized (mScheduleUpdates) {
scheduleUpdates.addAll(mScheduleUpdates);
mScheduleUpdates.clear();
}
SyncHelper syncHelper = new SyncHelper(this);
for (Intent updateIntent : scheduleUpdates) {
String sessionId =
updateIntent.getStringExtra(EXTRA_SESSION_ID);
boolean inSchedule =
updateIntent.getBooleanExtra(EXTRA_IN_SCHEDULE, false);
LOGI(TAG, "addOrRemoveSessionFromSchedule:"
+ " sessionId=" + sessionId
+ " inSchedule=" + inSchedule);
syncHelper.addOrRemoveSessionFromSchedule(this, sessionId,
inSchedule);
}
} catch (IOException e) {
// TODO: do something useful here, like revert the changes
locally in the
// content provider to maintain client/server sync
LOGE(TAG, "Error processing schedule update", e);
}
}
Please notice there is an enhanced for loop iteration through
scheduleUpdates, while it is suggested to avoid such type of iteration for
ArrayList.
Is that because this part of the application is not considered to be
critical from performance standpoint or am I not understanding something?
Thanks a lot.
Friday, 23 August 2013
When using countdown timer i can only see the number 4 appearing in Flash as3?
When using countdown timer i can only see the number 4 appearing in Flash
as3?
I'm making a app in flash and i have a countdown timer. It starts at 60
seconds and goes down to zero but i can only see the number 4 appearing
from numbers like 54, 44, 40, 34, 24, 14 and 4. I have tried this code
separately on a another blank scene and it works but not on my app.
'myText_txt' is an instance name of dynamic text box. Help Please.
var count:Number = 60;
var myTimer:Timer = new Timer(1000,count);
myTimer.addEventListener(TimerEvent.TIMER, countdown);
myTimer.start();
function countdown(event:TimerEvent):void {
myText_txt.text = String((count)-myTimer.currentCount);
}
as3?
I'm making a app in flash and i have a countdown timer. It starts at 60
seconds and goes down to zero but i can only see the number 4 appearing
from numbers like 54, 44, 40, 34, 24, 14 and 4. I have tried this code
separately on a another blank scene and it works but not on my app.
'myText_txt' is an instance name of dynamic text box. Help Please.
var count:Number = 60;
var myTimer:Timer = new Timer(1000,count);
myTimer.addEventListener(TimerEvent.TIMER, countdown);
myTimer.start();
function countdown(event:TimerEvent):void {
myText_txt.text = String((count)-myTimer.currentCount);
}
Formula for Combinations With Replacement
Formula for Combinations With Replacement
I understand how combinations and permutations work (without replacement).
I also see why a permutation of $n$ elements ordered $k$ at a time (with
replacement) is equal to $n^{k}$. Through some browsing I've found that
the number of combinations with replacement of $n$ items taken $k$ at a
time can be expressed as $((\frac{n}{k}))$ [please disregard the division
sign, I don't know how to use the binomial coefficient in MathJax: this
"double" set of parentheses is the notation developed by Richard Stanley
to convey the idea of combinations with replacement].
Alternatively, $((\frac{n}{k}))$ = $(\frac{n+k-1}{k})$ [again without the
division sign: it's a binomial coefficient]. This is more familiar
notation. Unfortunately, I have not found a clear explanation as to why
the above formula applies to the combinations with replacement. Could
anyone be so kind to explain how this formula was developed?
I understand how combinations and permutations work (without replacement).
I also see why a permutation of $n$ elements ordered $k$ at a time (with
replacement) is equal to $n^{k}$. Through some browsing I've found that
the number of combinations with replacement of $n$ items taken $k$ at a
time can be expressed as $((\frac{n}{k}))$ [please disregard the division
sign, I don't know how to use the binomial coefficient in MathJax: this
"double" set of parentheses is the notation developed by Richard Stanley
to convey the idea of combinations with replacement].
Alternatively, $((\frac{n}{k}))$ = $(\frac{n+k-1}{k})$ [again without the
division sign: it's a binomial coefficient]. This is more familiar
notation. Unfortunately, I have not found a clear explanation as to why
the above formula applies to the combinations with replacement. Could
anyone be so kind to explain how this formula was developed?
Trying to clone raid (striped) To USB Hard Drive
Trying to clone raid (striped) To USB Hard Drive
I am trying to clone a raid drive that was striped over to an external USB
hard drive.
I have tried Paragon in both clone and image and restore, EaseUS in both
clone options, and Acronis. Nothing seems to work.
I did this once before a few years ago, and cannot seem to get it right
this time.
I have archived image. That won't restore to the drive. I have tried to
clone the partition(s), clone the drive itself. Always I get a sector
error.
I realize the sectors are different, but isn't there something that just
copies and makes the conversion?
I am trying to clone a raid drive that was striped over to an external USB
hard drive.
I have tried Paragon in both clone and image and restore, EaseUS in both
clone options, and Acronis. Nothing seems to work.
I did this once before a few years ago, and cannot seem to get it right
this time.
I have archived image. That won't restore to the drive. I have tried to
clone the partition(s), clone the drive itself. Always I get a sector
error.
I realize the sectors are different, but isn't there something that just
copies and makes the conversion?
Custom sort order of list ( Part # 2 )
Custom sort order of list ( Part # 2 )
You are about to be provided with information to
start your own Google.
Some people posted comments and said this can not
be done because google has 1 million servers and we do not.
The truth is, google has those many servers for trolling
purposes (e.g. google +, google finance, youtube the bandwidth consuming
no-profit making web site, etc ).
all for trolling purposes.
if you wanted to start your own search engine...
you need to know few things.
1 : you need to know how beautiful mysql is.
2: you need to not listen to people that tell you to use a framework
with python, and simply use mod-wsgi.
3: you need to cache popular searches when your search engine is running.
4: you need to connect numbers to words. maybe even something like..
numbers to numbers to words.
in other words let's say in the past 24 hours people searched for
some phrases over and over again.. you cache those and assign numbers
to them, this way you are matching numbers with numbers in mysql.
not words with words.
in other words let's say google uses 1/2 their servers for trolling
and 1/2 for search engine.
we need technology and ideas so that you can run a search engine
on 1 or 2 dedicated servers that cost no more than $100/month each.
once you make money, you can begin buying more and more servers.
after you make lots of money.. you probably gonna turn into a troll
too like google inc.
because god is brutal.
god is void-state
it keeps singing you songs when you are sleeping and says
"nothing matters, there is simply no meaning"
but of course to start this search engine, you need a jump start.
if you notice google constantly links to other web sites with a
trackable way when people click on search results.
this means google knows which web sites are becoming popular
are popular, etc. they can see what is rising before it rises.
it's like being able to see the future.
the computer tells them " you better get in touch with this guy
before he becomes rich and becomes un-stopable "
sometimes they send cops onto people. etc.
AMAZON INC however..
will provide you with the top 1 million web sites in the world.
updated daily in a csv file.
downloadable at alexa.com
simply click on 'top sites' and then you will see the downloadable
file on the right side.
everyday they update it. and it is being given away for free.
google would never do this.
amazon does this.
this list you can use to ensure you show the top sites first in your
search engine .
this makes your search engine look 'credible'
in other words as you start making money, you first display things
in a "Generic" way but at the same time not in a "questionable" way
by displaying them based on "rank"
of course amazon only gives you URLS of the web sites.
you need to grab the title and etc from the web sites.
the truth is, to get started you do not need everything from web sites.
a title and some tags is all you need.
simple.
basic.
functional
will get peoples attention.
i always ask questions on SO but most questions get deleted. here's
something that did not get deleted..
How do I ensure that re.findall() stops at the right place?
use python, skrew php, php is no good.
do not use python frameworks, it's all lies and b.s. use mod-wsgi
use memcache to cache the templates and thus no need for a template engine.
always look at russian dedicated servers, and so on.
do not put your trust in america.
it has all turned into a mafia.
google can file a report, fbi can send cops onto you, and next thing you know
they frame you as a criminal, thug, mentally ill, bipolar, peadophile, and
so on.
all you can do is bleed to death behind bars.
do not give into the lies of AMERICA.
find russian dedicated servers.
i tried signing up with pw-service.com but i couldn't do it due to
restrictions with their russian payment systems and so on..
again, amazon's web site alexa.com provides you with downloadable
top 1 mil web sites in the form of a csv file.
use it.
again, do not give into python programmers suggesting frameworks for python.
it's all b.s. use mod_wsgi with memcache.
again, american corporations can ruin you with lies and all you can do is
bleed to death behind bars
again, a basic search engine needs : url, title, tags, and popular searches
can be "cached" and words can be connected to "numbers" within the mysql.
mysql has capabilities to cache things as well.
cache once, cache twice, and you will not need 1 million servers in order
to troll.
if you need some xdotool commands to deal with people calling you a troll
here it is;
xdotool key ctrl+c
xdotool key Tab Tab Tab Return
xdotool type '@'
xdotool key ctrl+v
xdotool type --clearmodifiers ', there can not be such thing as a `troll`
unless compared to a stationary point, if you are complaining, you are not
stationary. which means you are the one that is trolling.'
xdotool key Tab Return
create an application launcher on your gnome-panel, and then select the
username in the comments section that called you a 'troll' and click the
shortcut on the gnome-panel.
it will copy the selected username to the clipboard and then hit TAB TAB
TAB RETURN
which opens the comment typing box. and then it will type @ + username +
comma, and then the rest.
###########################################################################
You are about to be provided with information to
start your own Google.
Some people posted comments and said this can not
be done because google has 1 million servers and we do not.
The truth is, google has those many servers for trolling
purposes (e.g. google +, google finance, youtube the bandwidth consuming
no-profit making web site, etc ).
all for trolling purposes.
if you wanted to start your own search engine...
you need to know few things.
1 : you need to know how beautiful mysql is.
2: you need to not listen to people that tell you to use a framework
with python, and simply use mod-wsgi.
3: you need to cache popular searches when your search engine is running.
4: you need to connect numbers to words. maybe even something like..
numbers to numbers to words.
in other words let's say in the past 24 hours people searched for
some phrases over and over again.. you cache those and assign numbers
to them, this way you are matching numbers with numbers in mysql.
not words with words.
in other words let's say google uses 1/2 their servers for trolling
and 1/2 for search engine.
we need technology and ideas so that you can run a search engine
on 1 or 2 dedicated servers that cost no more than $100/month each.
once you make money, you can begin buying more and more servers.
after you make lots of money.. you probably gonna turn into a troll
too like google inc.
because god is brutal.
god is void-state
it keeps singing you songs when you are sleeping and says
"nothing matters, there is simply no meaning"
but of course to start this search engine, you need a jump start.
if you notice google constantly links to other web sites with a
trackable way when people click on search results.
this means google knows which web sites are becoming popular
are popular, etc. they can see what is rising before it rises.
it's like being able to see the future.
the computer tells them " you better get in touch with this guy
before he becomes rich and becomes un-stopable "
sometimes they send cops onto people. etc.
AMAZON INC however..
will provide you with the top 1 million web sites in the world.
updated daily in a csv file.
downloadable at alexa.com
simply click on 'top sites' and then you will see the downloadable
file on the right side.
everyday they update it. and it is being given away for free.
google would never do this.
amazon does this.
this list you can use to ensure you show the top sites first in your
search engine .
this makes your search engine look 'credible'
in other words as you start making money, you first display things
in a "Generic" way but at the same time not in a "questionable" way
by displaying them based on "rank"
of course amazon only gives you URLS of the web sites.
you need to grab the title and etc from the web sites.
the truth is, to get started you do not need everything from web sites.
a title and some tags is all you need.
simple.
basic.
functional
will get peoples attention.
i always ask questions on SO but most questions get deleted. here's
something that did not get deleted..
How do I ensure that re.findall() stops at the right place?
use python, skrew php, php is no good.
do not use python frameworks, it's all lies and b.s. use mod-wsgi
use memcache to cache the templates and thus no need for a template engine.
always look at russian dedicated servers, and so on.
do not put your trust in america.
it has all turned into a mafia.
google can file a report, fbi can send cops onto you, and next thing you know
they frame you as a criminal, thug, mentally ill, bipolar, peadophile, and
so on.
all you can do is bleed to death behind bars.
do not give into the lies of AMERICA.
find russian dedicated servers.
i tried signing up with pw-service.com but i couldn't do it due to
restrictions with their russian payment systems and so on..
again, amazon's web site alexa.com provides you with downloadable
top 1 mil web sites in the form of a csv file.
use it.
again, do not give into python programmers suggesting frameworks for python.
it's all b.s. use mod_wsgi with memcache.
again, american corporations can ruin you with lies and all you can do is
bleed to death behind bars
again, a basic search engine needs : url, title, tags, and popular searches
can be "cached" and words can be connected to "numbers" within the mysql.
mysql has capabilities to cache things as well.
cache once, cache twice, and you will not need 1 million servers in order
to troll.
if you need some xdotool commands to deal with people calling you a troll
here it is;
xdotool key ctrl+c
xdotool key Tab Tab Tab Return
xdotool type '@'
xdotool key ctrl+v
xdotool type --clearmodifiers ', there can not be such thing as a `troll`
unless compared to a stationary point, if you are complaining, you are not
stationary. which means you are the one that is trolling.'
xdotool key Tab Return
create an application launcher on your gnome-panel, and then select the
username in the comments section that called you a 'troll' and click the
shortcut on the gnome-panel.
it will copy the selected username to the clipboard and then hit TAB TAB
TAB RETURN
which opens the comment typing box. and then it will type @ + username +
comma, and then the rest.
###########################################################################
How do you specify file upload directory for express within sails?
How do you specify file upload directory for express within sails?
I'm uploading a file from a browser <input type="file" name="myfile"
id="myfile" using sails. I need to place it in other than the default
express location. I'd use the following code in naked Express:
app.use(express.bodyParser({ keepExtensions: true, uploadDir: uploadFolder
}))
For sails I wrote code along the lines of this relevant answer
First, I tried SkyTecLabs' answer. policies/configfileupload.js contains
'use strict';
var sailsExpress = require('../../node_modules/sails/node_modules/express'),
path = require('path');
console.log('.. initializing policies/configFileUpload');
module.exports = function configFileUpload (req, res, next) {
var uploadFolder = path.normalize(__dirname + '/../public/uploads');
console.log('.. in policies/configfileupload.js. uploadFolder=',
uploadFolder);
console.log('typeofs are=',typeof req, typeof res, typeof next, typeof
sailsExpress);
sailsExpress.bodyParser({ keepExtensions: true, uploadDir: uploadFolder });
next();
};
config/policies.js contains
'SchedController' : {
'uploadsubmit': 'configfileupload'
}
Express continues to upload the file to the default directory. Typeof req,
res, next, sailsexpress are: object, object, function, function so the
signature looks OK. (I tried returning the function configFileUpload just
in case, but the controller was never called.)
Then I tried mikemcneil's suggestion. config/express.js
'use strict';
var sailsExpress = require('../node_modules/sails/node_modules/express'),
path = require('path');
module.exports.express = {
customMiddleware: function (app) {
var uploadFolder = path.normalize(__dirname + '/../public/uploads');
console.log('.. in config/express.js. uploadFolder=', uploadFolder);
console.log('typeof sailsExpress=', typeof sailsExpress, 'typeof
app=', typeof app);
app.use(sailsExpress.bodyParser({ keepExtensions: true, uploadDir:
uploadFolder }));
}
};
and the upload was still placed in the default directory. The typeofs
sailsexpress and app are both function.
Any suggestions?
I'm uploading a file from a browser <input type="file" name="myfile"
id="myfile" using sails. I need to place it in other than the default
express location. I'd use the following code in naked Express:
app.use(express.bodyParser({ keepExtensions: true, uploadDir: uploadFolder
}))
For sails I wrote code along the lines of this relevant answer
First, I tried SkyTecLabs' answer. policies/configfileupload.js contains
'use strict';
var sailsExpress = require('../../node_modules/sails/node_modules/express'),
path = require('path');
console.log('.. initializing policies/configFileUpload');
module.exports = function configFileUpload (req, res, next) {
var uploadFolder = path.normalize(__dirname + '/../public/uploads');
console.log('.. in policies/configfileupload.js. uploadFolder=',
uploadFolder);
console.log('typeofs are=',typeof req, typeof res, typeof next, typeof
sailsExpress);
sailsExpress.bodyParser({ keepExtensions: true, uploadDir: uploadFolder });
next();
};
config/policies.js contains
'SchedController' : {
'uploadsubmit': 'configfileupload'
}
Express continues to upload the file to the default directory. Typeof req,
res, next, sailsexpress are: object, object, function, function so the
signature looks OK. (I tried returning the function configFileUpload just
in case, but the controller was never called.)
Then I tried mikemcneil's suggestion. config/express.js
'use strict';
var sailsExpress = require('../node_modules/sails/node_modules/express'),
path = require('path');
module.exports.express = {
customMiddleware: function (app) {
var uploadFolder = path.normalize(__dirname + '/../public/uploads');
console.log('.. in config/express.js. uploadFolder=', uploadFolder);
console.log('typeof sailsExpress=', typeof sailsExpress, 'typeof
app=', typeof app);
app.use(sailsExpress.bodyParser({ keepExtensions: true, uploadDir:
uploadFolder }));
}
};
and the upload was still placed in the default directory. The typeofs
sailsexpress and app are both function.
Any suggestions?
Android custom camera crashes on resume
Android custom camera crashes on resume
I have this custom camera activity in my app, which is working just fine,
but when I press the home button while in camera activity, and then return
to the app, it crashes, and the logcat says there was a null pointer
exception at the surface view creation. This setup method is called on
onResume:
public void setup()
{
preview = new CameraPreview(this);
((FrameLayout) findViewById(R.id.camera_preview)).addView(preview);
head=(ImageView)findViewById(R.id.head);
head.setX((float)(Shared.screenWidth/5*1.8));
head.setY((float)(Shared.screenHeight*0.03));
LayoutParams params = (LayoutParams) head.getLayoutParams();
params.width = (int)((Shared.screenWidth/5*3.2)-(head.getX()));
params.height=(int)((Shared.screenHeight/3.8)-(head.getY()));
head.setLayoutParams(params);
body=(ImageView)findViewById(R.id.body);
body.setX((float)(Shared.screenWidth/7));
body.setY((float)(Shared.screenHeight/3.8));
LayoutParams params2 = (LayoutParams) body.getLayoutParams();
params2.width = (int)((Shared.screenWidth/7*6)-(body.getX()));
params2.height=(int)((Shared.screenHeight)-(body.getY()));
body.setLayoutParams(params2);
go=(Button)findViewById(R.id.go);
again=(Button)findViewById(R.id.again);
stop=(ImageButton)findViewById(R.id.stop);
stop.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
Intent i =new Intent(CamActivity.this,Main.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
});
btn = (ImageButton) findViewById(R.id.takePic);
btn.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
preview.camera.takePicture(shutterCallback, rawCallback,
jpegCallback);
btn.setVisibility(View.INVISIBLE);
btn.setEnabled(false);
go.setVisibility(View.VISIBLE);
go.setEnabled(true);
head.setVisibility(View.INVISIBLE);
body.setVisibility(View.INVISIBLE);
go.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
Shared.bm=Bitmap.createScaledBitmap(bmp,
Shared.screenWidth, Shared.screenHeight, true);
Intent i=new Intent(CamActivity.this,IKill.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
});
again.setVisibility(View.VISIBLE);
again.setEnabled(true);
again.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= 11) {
recreate();
} else {
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
}
});
}
});
}
In addition, on my onCreate method I also have this:
requestWindowFeature(Window.FEATURE_NO_TITLE);
// hide status bar
final Window win = getWindow();
win.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_camera);
and the logcat:
08-23 08:56:20.174: E/AndroidRuntime(835): FATAL EXCEPTION: main
08-23 08:56:20.174: E/AndroidRuntime(835): java.lang.NullPointerException
08-23 08:56:20.174: E/AndroidRuntime(835): at
com.example.i_kill.CameraPreview.surfaceCreated(CameraPreview.java:38)
08-23 08:56:20.174: E/AndroidRuntime(835): at
android.view.SurfaceView.updateWindow(SurfaceView.java:569)
08-23 08:56:20.174: E/AndroidRuntime(835): at
android.view.SurfaceView.access$000(SurfaceView.java:86)
08-23 08:56:20.174: E/AndroidRuntime(835): at
android.view.SurfaceView$3.onPreDraw(SurfaceView.java:174)
08-23 08:56:20.174: E/AndroidRuntime(835): at
android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:680)
08-23 08:56:20.174: E/AndroidRuntime(835): at
android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1842)
08-23 08:56:20.174: E/AndroidRuntime(835): at
android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989)
08-23 08:56:20.174: E/AndroidRuntime(835): at
android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4351)
08-23 08:56:20.174: E/AndroidRuntime(835): at
android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
08-23 08:56:20.174: E/AndroidRuntime(835): at
android.view.Choreographer.doCallbacks(Choreographer.java:562)
08-23 08:56:20.174: E/AndroidRuntime(835): at
android.view.Choreographer.doFrame(Choreographer.java:532)
08-23 08:56:20.174: E/AndroidRuntime(835): at
android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
08-23 08:56:20.174: E/AndroidRuntime(835): at
android.os.Handler.handleCallback(Handler.java:725)
08-23 08:56:20.174: E/AndroidRuntime(835): at
android.os.Handler.dispatchMessage(Handler.java:92)
08-23 08:56:20.174: E/AndroidRuntime(835): at
android.os.Looper.loop(Looper.java:137)
08-23 08:56:20.174: E/AndroidRuntime(835): at
android.app.ActivityThread.main(ActivityThread.java:5041)
08-23 08:56:20.174: E/AndroidRuntime(835): at
java.lang.reflect.Method.invokeNative(Native Method)
08-23 08:56:20.174: E/AndroidRuntime(835): at
java.lang.reflect.Method.invoke(Method.java:511)
08-23 08:56:20.174: E/AndroidRuntime(835): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-23 08:56:20.174: E/AndroidRuntime(835): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-23 08:56:20.174: E/AndroidRuntime(835): at
dalvik.system.NativeStart.main(Native
Method)
08-23 08:56:26.065: E/Trace(909): error opening trace file: No such file
or directory
and here's the entire class: package com.example.i_kill;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
public class CamActivity extends Activity {
public static final int MEDIA_TYPE_IMAGE = 1;
public static String TAG="MainActivity";
private static Camera camera;
private CameraPreview preview;
private ImageView head,body;
private ImageButton btn, stop;
private Button again,go;
private Bitmap bmp;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
// hide status bar
final Window win = getWindow();
win.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_camera);
}
public void setup()
{
preview = new CameraPreview(this);
((FrameLayout) findViewById(R.id.camera_preview)).addView(preview);
head=(ImageView)findViewById(R.id.head);
head.setX((float)(Shared.screenWidth/5*1.8));
head.setY((float)(Shared.screenHeight*0.03));
LayoutParams params = (LayoutParams) head.getLayoutParams();
params.width = (int)((Shared.screenWidth/5*3.2)-(head.getX()));
params.height=(int)((Shared.screenHeight/3.8)-(head.getY()));
head.setLayoutParams(params);
body=(ImageView)findViewById(R.id.body);
body.setX((float)(Shared.screenWidth/7));
body.setY((float)(Shared.screenHeight/3.8));
LayoutParams params2 = (LayoutParams) body.getLayoutParams();
params2.width = (int)((Shared.screenWidth/7*6)-(body.getX()));
params2.height=(int)((Shared.screenHeight)-(body.getY()));
body.setLayoutParams(params2);
go=(Button)findViewById(R.id.go);
again=(Button)findViewById(R.id.again);
stop=(ImageButton)findViewById(R.id.stop);
stop.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
Intent i =new Intent(CamActivity.this,Main.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
});
btn = (ImageButton) findViewById(R.id.takePic);
btn.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
preview.camera.takePicture(shutterCallback, rawCallback,
jpegCallback);
btn.setVisibility(View.INVISIBLE);
btn.setEnabled(false);
go.setVisibility(View.VISIBLE);
go.setEnabled(true);
head.setVisibility(View.INVISIBLE);
body.setVisibility(View.INVISIBLE);
go.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
Shared.bm=Bitmap.createScaledBitmap(bmp,
Shared.screenWidth, Shared.screenHeight, true);
Intent i=new Intent(CamActivity.this,IKill.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
});
again.setVisibility(View.VISIBLE);
again.setEnabled(true);
again.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= 11) {
recreate();
} else {
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
}
});
}
});
}
ShutterCallback shutterCallback = new ShutterCallback() {
public void onShutter() {
Log.d(TAG, "onShutter'd");
}
};
PictureCallback rawCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
Log.d(TAG, "onPictureTaken - raw");
}
};
/** Handles data for jpeg picture */
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
bmp=BitmapFactory.decodeByteArray(data, 0, data.length );
System.out.println(bmp.getHeight());
System.out.println(bmp.getWidth());
};
};
public void onPause(){
super.onPause();
if(camera!=null){
camera.stopPreview();
camera.setPreviewCallback(null);
camera.release();
camera = null;
}
}
public void onResume()
{
super.onResume();
setup();
}
}
and camera preview class:
package com.example.i_kill;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.hardware.Camera;
import android.hardware.Camera.PreviewCallback;
import android.hardware.Camera.Size;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class CameraPreview extends SurfaceView implements
SurfaceHolder.Callback {
private SurfaceHolder holder;
public Camera camera;
public static String TAG="CameraPreview";
public CameraPreview(Context context) {
super(context);
holder=getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, now tell the camera where to draw the
preview.
camera = getCameraInstance();
try {
camera.setPreviewDisplay(holder);
camera.setPreviewCallback(new PreviewCallback() {
public void onPreviewFrame(byte[] data, Camera arg1) {
FileOutputStream outStream = null;
try {
outStream = new
FileOutputStream(String.format("/sdcard/%d.jpg",
System.currentTimeMillis()));
outStream.write(data);
outStream.close();
Log.d(TAG, "onPreviewFrame - wrote bytes: " + data.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
CameraPreview.this.invalidate();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
if(camera!=null){
camera.stopPreview();
camera.setPreviewCallback(null);
camera.release();
camera = null;
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
Camera.Parameters parameters = camera.getParameters();
List<Size> previewSizes = parameters.getSupportedPreviewSizes();
Size bestSize = null;
int bestDiff = 0;
int diff = 0;
for (Size size : previewSizes) {
diff = Math.abs(h - size.height) + Math.abs(w - size.width);
if (bestSize == null || diff < bestDiff) {
bestSize = size;
bestDiff = diff;
}
parameters.setPreviewSize(bestSize.width, bestSize.height);
camera.setParameters(parameters);
}
//start preview of camera
camera.startPreview();
}
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
Paint p= new Paint(Color.RED);
Log.d(TAG,"draw");
canvas.drawText("PREVIEW", canvas.getWidth()/2, canvas.getHeight()/2,
p );
}
private Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e){
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
}
Thanks for your help :)
I have this custom camera activity in my app, which is working just fine,
but when I press the home button while in camera activity, and then return
to the app, it crashes, and the logcat says there was a null pointer
exception at the surface view creation. This setup method is called on
onResume:
public void setup()
{
preview = new CameraPreview(this);
((FrameLayout) findViewById(R.id.camera_preview)).addView(preview);
head=(ImageView)findViewById(R.id.head);
head.setX((float)(Shared.screenWidth/5*1.8));
head.setY((float)(Shared.screenHeight*0.03));
LayoutParams params = (LayoutParams) head.getLayoutParams();
params.width = (int)((Shared.screenWidth/5*3.2)-(head.getX()));
params.height=(int)((Shared.screenHeight/3.8)-(head.getY()));
head.setLayoutParams(params);
body=(ImageView)findViewById(R.id.body);
body.setX((float)(Shared.screenWidth/7));
body.setY((float)(Shared.screenHeight/3.8));
LayoutParams params2 = (LayoutParams) body.getLayoutParams();
params2.width = (int)((Shared.screenWidth/7*6)-(body.getX()));
params2.height=(int)((Shared.screenHeight)-(body.getY()));
body.setLayoutParams(params2);
go=(Button)findViewById(R.id.go);
again=(Button)findViewById(R.id.again);
stop=(ImageButton)findViewById(R.id.stop);
stop.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
Intent i =new Intent(CamActivity.this,Main.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
});
btn = (ImageButton) findViewById(R.id.takePic);
btn.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
preview.camera.takePicture(shutterCallback, rawCallback,
jpegCallback);
btn.setVisibility(View.INVISIBLE);
btn.setEnabled(false);
go.setVisibility(View.VISIBLE);
go.setEnabled(true);
head.setVisibility(View.INVISIBLE);
body.setVisibility(View.INVISIBLE);
go.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
Shared.bm=Bitmap.createScaledBitmap(bmp,
Shared.screenWidth, Shared.screenHeight, true);
Intent i=new Intent(CamActivity.this,IKill.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
});
again.setVisibility(View.VISIBLE);
again.setEnabled(true);
again.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= 11) {
recreate();
} else {
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
}
});
}
});
}
In addition, on my onCreate method I also have this:
requestWindowFeature(Window.FEATURE_NO_TITLE);
// hide status bar
final Window win = getWindow();
win.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_camera);
and the logcat:
08-23 08:56:20.174: E/AndroidRuntime(835): FATAL EXCEPTION: main
08-23 08:56:20.174: E/AndroidRuntime(835): java.lang.NullPointerException
08-23 08:56:20.174: E/AndroidRuntime(835): at
com.example.i_kill.CameraPreview.surfaceCreated(CameraPreview.java:38)
08-23 08:56:20.174: E/AndroidRuntime(835): at
android.view.SurfaceView.updateWindow(SurfaceView.java:569)
08-23 08:56:20.174: E/AndroidRuntime(835): at
android.view.SurfaceView.access$000(SurfaceView.java:86)
08-23 08:56:20.174: E/AndroidRuntime(835): at
android.view.SurfaceView$3.onPreDraw(SurfaceView.java:174)
08-23 08:56:20.174: E/AndroidRuntime(835): at
android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:680)
08-23 08:56:20.174: E/AndroidRuntime(835): at
android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1842)
08-23 08:56:20.174: E/AndroidRuntime(835): at
android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989)
08-23 08:56:20.174: E/AndroidRuntime(835): at
android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4351)
08-23 08:56:20.174: E/AndroidRuntime(835): at
android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
08-23 08:56:20.174: E/AndroidRuntime(835): at
android.view.Choreographer.doCallbacks(Choreographer.java:562)
08-23 08:56:20.174: E/AndroidRuntime(835): at
android.view.Choreographer.doFrame(Choreographer.java:532)
08-23 08:56:20.174: E/AndroidRuntime(835): at
android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
08-23 08:56:20.174: E/AndroidRuntime(835): at
android.os.Handler.handleCallback(Handler.java:725)
08-23 08:56:20.174: E/AndroidRuntime(835): at
android.os.Handler.dispatchMessage(Handler.java:92)
08-23 08:56:20.174: E/AndroidRuntime(835): at
android.os.Looper.loop(Looper.java:137)
08-23 08:56:20.174: E/AndroidRuntime(835): at
android.app.ActivityThread.main(ActivityThread.java:5041)
08-23 08:56:20.174: E/AndroidRuntime(835): at
java.lang.reflect.Method.invokeNative(Native Method)
08-23 08:56:20.174: E/AndroidRuntime(835): at
java.lang.reflect.Method.invoke(Method.java:511)
08-23 08:56:20.174: E/AndroidRuntime(835): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-23 08:56:20.174: E/AndroidRuntime(835): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-23 08:56:20.174: E/AndroidRuntime(835): at
dalvik.system.NativeStart.main(Native
Method)
08-23 08:56:26.065: E/Trace(909): error opening trace file: No such file
or directory
and here's the entire class: package com.example.i_kill;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
public class CamActivity extends Activity {
public static final int MEDIA_TYPE_IMAGE = 1;
public static String TAG="MainActivity";
private static Camera camera;
private CameraPreview preview;
private ImageView head,body;
private ImageButton btn, stop;
private Button again,go;
private Bitmap bmp;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
// hide status bar
final Window win = getWindow();
win.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_camera);
}
public void setup()
{
preview = new CameraPreview(this);
((FrameLayout) findViewById(R.id.camera_preview)).addView(preview);
head=(ImageView)findViewById(R.id.head);
head.setX((float)(Shared.screenWidth/5*1.8));
head.setY((float)(Shared.screenHeight*0.03));
LayoutParams params = (LayoutParams) head.getLayoutParams();
params.width = (int)((Shared.screenWidth/5*3.2)-(head.getX()));
params.height=(int)((Shared.screenHeight/3.8)-(head.getY()));
head.setLayoutParams(params);
body=(ImageView)findViewById(R.id.body);
body.setX((float)(Shared.screenWidth/7));
body.setY((float)(Shared.screenHeight/3.8));
LayoutParams params2 = (LayoutParams) body.getLayoutParams();
params2.width = (int)((Shared.screenWidth/7*6)-(body.getX()));
params2.height=(int)((Shared.screenHeight)-(body.getY()));
body.setLayoutParams(params2);
go=(Button)findViewById(R.id.go);
again=(Button)findViewById(R.id.again);
stop=(ImageButton)findViewById(R.id.stop);
stop.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
Intent i =new Intent(CamActivity.this,Main.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
});
btn = (ImageButton) findViewById(R.id.takePic);
btn.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
preview.camera.takePicture(shutterCallback, rawCallback,
jpegCallback);
btn.setVisibility(View.INVISIBLE);
btn.setEnabled(false);
go.setVisibility(View.VISIBLE);
go.setEnabled(true);
head.setVisibility(View.INVISIBLE);
body.setVisibility(View.INVISIBLE);
go.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
Shared.bm=Bitmap.createScaledBitmap(bmp,
Shared.screenWidth, Shared.screenHeight, true);
Intent i=new Intent(CamActivity.this,IKill.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
});
again.setVisibility(View.VISIBLE);
again.setEnabled(true);
again.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= 11) {
recreate();
} else {
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
}
});
}
});
}
ShutterCallback shutterCallback = new ShutterCallback() {
public void onShutter() {
Log.d(TAG, "onShutter'd");
}
};
PictureCallback rawCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
Log.d(TAG, "onPictureTaken - raw");
}
};
/** Handles data for jpeg picture */
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
bmp=BitmapFactory.decodeByteArray(data, 0, data.length );
System.out.println(bmp.getHeight());
System.out.println(bmp.getWidth());
};
};
public void onPause(){
super.onPause();
if(camera!=null){
camera.stopPreview();
camera.setPreviewCallback(null);
camera.release();
camera = null;
}
}
public void onResume()
{
super.onResume();
setup();
}
}
and camera preview class:
package com.example.i_kill;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.hardware.Camera;
import android.hardware.Camera.PreviewCallback;
import android.hardware.Camera.Size;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class CameraPreview extends SurfaceView implements
SurfaceHolder.Callback {
private SurfaceHolder holder;
public Camera camera;
public static String TAG="CameraPreview";
public CameraPreview(Context context) {
super(context);
holder=getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, now tell the camera where to draw the
preview.
camera = getCameraInstance();
try {
camera.setPreviewDisplay(holder);
camera.setPreviewCallback(new PreviewCallback() {
public void onPreviewFrame(byte[] data, Camera arg1) {
FileOutputStream outStream = null;
try {
outStream = new
FileOutputStream(String.format("/sdcard/%d.jpg",
System.currentTimeMillis()));
outStream.write(data);
outStream.close();
Log.d(TAG, "onPreviewFrame - wrote bytes: " + data.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
CameraPreview.this.invalidate();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
if(camera!=null){
camera.stopPreview();
camera.setPreviewCallback(null);
camera.release();
camera = null;
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
Camera.Parameters parameters = camera.getParameters();
List<Size> previewSizes = parameters.getSupportedPreviewSizes();
Size bestSize = null;
int bestDiff = 0;
int diff = 0;
for (Size size : previewSizes) {
diff = Math.abs(h - size.height) + Math.abs(w - size.width);
if (bestSize == null || diff < bestDiff) {
bestSize = size;
bestDiff = diff;
}
parameters.setPreviewSize(bestSize.width, bestSize.height);
camera.setParameters(parameters);
}
//start preview of camera
camera.startPreview();
}
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
Paint p= new Paint(Color.RED);
Log.d(TAG,"draw");
canvas.drawText("PREVIEW", canvas.getWidth()/2, canvas.getHeight()/2,
p );
}
private Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e){
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
}
Thanks for your help :)
Thursday, 22 August 2013
Does axiomatizability in zeroth-order logic have important consequences?
Does axiomatizability in zeroth-order logic have important consequences?
If a theory is equationally axiomatizable, this has important consequences
(that are studied e.g. in universal algebra).
However, many theories fail to be equationally axiomatizable - examples
include fields, integral domains, and partially ordered sets. Nonetheless,
all of these examples are zeroth-order axiomatizable. Does this have
important consequences?
For instance, the theory of partially ordered sets is generated by the
following axioms.
$x \leq x$
$(x \leq y) \wedge (y \leq x) \rightarrow x = y$
$(x \leq y) \wedge (y \leq z) \rightarrow x \leq z$
If a theory is equationally axiomatizable, this has important consequences
(that are studied e.g. in universal algebra).
However, many theories fail to be equationally axiomatizable - examples
include fields, integral domains, and partially ordered sets. Nonetheless,
all of these examples are zeroth-order axiomatizable. Does this have
important consequences?
For instance, the theory of partially ordered sets is generated by the
following axioms.
$x \leq x$
$(x \leq y) \wedge (y \leq x) \rightarrow x = y$
$(x \leq y) \wedge (y \leq z) \rightarrow x \leq z$
Why shouldn't I use System.out.println() in android
Why shouldn't I use System.out.println() in android
In this code style they said that we shouldn't use System.out.println()
but I don't understand their's idea. can Anyone explain about that? What
should I use to trace the log of my app?
System.out.println() (or printf() for native code) should never be used.
System.out and System.err get redirected to /dev/null, so your print
statements will have no visible effects. However, all the string building
that happens for these calls still gets executed.
In this code style they said that we shouldn't use System.out.println()
but I don't understand their's idea. can Anyone explain about that? What
should I use to trace the log of my app?
System.out.println() (or printf() for native code) should never be used.
System.out and System.err get redirected to /dev/null, so your print
statements will have no visible effects. However, all the string building
that happens for these calls still gets executed.
Use generated JAXB class with lists in web servise wsdl/xsd
Use generated JAXB class with lists in web servise wsdl/xsd
I have class definition in xsd file. I generated class using JAXB binding.
For lists I haven't setters.
After that, I used this classes in my web services. I created wsdl + xsd
for service. But ... in xsd I haven't some field definition (for lists,
because I haven't setters for these).
How can I generate correctly wsdl + xsd for my classes?
Netbeans 7.3.1 + Glassfish
I have class definition in xsd file. I generated class using JAXB binding.
For lists I haven't setters.
After that, I used this classes in my web services. I created wsdl + xsd
for service. But ... in xsd I haven't some field definition (for lists,
because I haven't setters for these).
How can I generate correctly wsdl + xsd for my classes?
Netbeans 7.3.1 + Glassfish
Are these 3 input-filter-functions 100% safe against sql injection?
Are these 3 input-filter-functions 100% safe against sql injection?
generally i don't like using sql prepared statements, so i have built 3
functions to check whether an input is safe. i want to know if there is
ANY CHANCE to be hacked.
Function 1: (for username and password inputs. this function does not
accept any symbol or space)
<?php
function safe_input($input) // no symbols
{
// symbols to exclude
$safe[0]="'";
$safe[1]="(";
$safe[2]=")";
$safe[3]=",";
$safe[4]=".";
$safe[5]="-";
$safe[6]="=";
$safe[7]='"';
$safe[8]="+";
$safe[9]="*";
$safe[10]="&";
$safe[11]="^";
$safe[12]="%";
$safe[13]="$";
$safe[14]="#";
$safe[15]="@";
$safe[16]="!";
$safe[17]=" ";
$safe[18]="_";
$safe[19]="[";
$safe[20]="]";
$safe[21]="{";
$safe[22]="}";
$safe[23]=":";
$safe[24]=";";
$safe[25]="<";
$safe[26]=">";
$safe[27]="/";
$safe[28]="?";
$is_safe=true;
for ($i=0; $i<=(count($safe)-1); $i++)
{
$check_count_n=count(explode($safe[$i],$input));
if ($check_count_n>1)
{
$is_safe=false;
}
}
return $is_safe;
}
?>
In the 2nd function, i need to filter id-like inputs. only numbers
<?php
function safe_input_id($input)
{
if (is_numeric($input))
{
return true;
}
else
{
return false;
}
}
?>
And finally the 3rd function is a filter for text-like inputs, like mails.
What i do is declaring a global variable $safeguard which i put between
every char in the input. for example if the input is "HELLO" and the
safeguard is "@r8#" the returned value will be "H@r8#E@r8#L@r8#L@r8#O@r8#"
and will be saved in the database. In order to retrieve the value from the
database, i use the unguard function to remove the safeguard.
<?php
global $safeguard;
$safeguard='8#3r7';
function text_guard($text,$safeguard)
{
$new_text='';
for ($i=0; $i<=strlen($text)-1; $i++)
{
$new_text=$new_text.$text[$i].$safeguard;
}
$new_text=str_replace("'","\'",$new_text);
return $new_text;
}
function text_unguard($text,$safeguard)
{
$new_text='';
$text_array=explode($safeguard,$text);
for ($i=0; $i<=count($text_array)-1; $i++)
{
$new_text=$new_text.$text_array[$i];
}
$new_text=str_replace("\'","'",$new_text);
return $new_text;
}
?>
ARE THESE 3 FUNCTIONS 100% SAFE? Thanks in advance
generally i don't like using sql prepared statements, so i have built 3
functions to check whether an input is safe. i want to know if there is
ANY CHANCE to be hacked.
Function 1: (for username and password inputs. this function does not
accept any symbol or space)
<?php
function safe_input($input) // no symbols
{
// symbols to exclude
$safe[0]="'";
$safe[1]="(";
$safe[2]=")";
$safe[3]=",";
$safe[4]=".";
$safe[5]="-";
$safe[6]="=";
$safe[7]='"';
$safe[8]="+";
$safe[9]="*";
$safe[10]="&";
$safe[11]="^";
$safe[12]="%";
$safe[13]="$";
$safe[14]="#";
$safe[15]="@";
$safe[16]="!";
$safe[17]=" ";
$safe[18]="_";
$safe[19]="[";
$safe[20]="]";
$safe[21]="{";
$safe[22]="}";
$safe[23]=":";
$safe[24]=";";
$safe[25]="<";
$safe[26]=">";
$safe[27]="/";
$safe[28]="?";
$is_safe=true;
for ($i=0; $i<=(count($safe)-1); $i++)
{
$check_count_n=count(explode($safe[$i],$input));
if ($check_count_n>1)
{
$is_safe=false;
}
}
return $is_safe;
}
?>
In the 2nd function, i need to filter id-like inputs. only numbers
<?php
function safe_input_id($input)
{
if (is_numeric($input))
{
return true;
}
else
{
return false;
}
}
?>
And finally the 3rd function is a filter for text-like inputs, like mails.
What i do is declaring a global variable $safeguard which i put between
every char in the input. for example if the input is "HELLO" and the
safeguard is "@r8#" the returned value will be "H@r8#E@r8#L@r8#L@r8#O@r8#"
and will be saved in the database. In order to retrieve the value from the
database, i use the unguard function to remove the safeguard.
<?php
global $safeguard;
$safeguard='8#3r7';
function text_guard($text,$safeguard)
{
$new_text='';
for ($i=0; $i<=strlen($text)-1; $i++)
{
$new_text=$new_text.$text[$i].$safeguard;
}
$new_text=str_replace("'","\'",$new_text);
return $new_text;
}
function text_unguard($text,$safeguard)
{
$new_text='';
$text_array=explode($safeguard,$text);
for ($i=0; $i<=count($text_array)-1; $i++)
{
$new_text=$new_text.$text_array[$i];
}
$new_text=str_replace("\'","'",$new_text);
return $new_text;
}
?>
ARE THESE 3 FUNCTIONS 100% SAFE? Thanks in advance
Subscribe to:
Comments (Atom)