Operating System tuned for High Performance Computing
I am trying to write efficient kernels in the area of scientific
computing. I use C. I do not know which operating system is better to
obtain correct timing results; since I do not want daemons, etc. to
interrupt my code. When I run my code, the CPUs of the system should
execute only my code.
I have installed Ubuntu Server on the systems that I test my code on. Is
there a document that shows how to tune Ubuntu for high performance
computing (HPC)? Or is there any other OS which is freely available for
HPC?
Saturday, 31 August 2013
JS in Rails App only loads the first time
JS in Rails App only loads the first time
I am using a fade effect on some links on my applications home page. This
is being accomplished by some JQuery:
javascripts/pages.js
$(document).ready(function() {
$('.home_tile_text').hide().removeClass('text').addClass('text-js');
$('.home_tile_overlay').hide().removeClass('overlay').addClass('overlay-js');
$('.home_tile').mouseenter(function(){
$(this).find('.text-js').finish().hide().fadeIn();
$(this).find('.overlay-js').finish().hide().fadeIn();
});
$('.home_tile').mouseleave(function(){
$(this).find('.text-js').finish().show().fadeOut();
$(this).find('.overlay-js').finish().show().fadeOut();
});
});
This all works great when I fire up the app for the first time. However,
if I navigate away from the home page, when I come back, the fade effect
no longer works until I "refresh" the page. Any ideas?
I am using a fade effect on some links on my applications home page. This
is being accomplished by some JQuery:
javascripts/pages.js
$(document).ready(function() {
$('.home_tile_text').hide().removeClass('text').addClass('text-js');
$('.home_tile_overlay').hide().removeClass('overlay').addClass('overlay-js');
$('.home_tile').mouseenter(function(){
$(this).find('.text-js').finish().hide().fadeIn();
$(this).find('.overlay-js').finish().hide().fadeIn();
});
$('.home_tile').mouseleave(function(){
$(this).find('.text-js').finish().show().fadeOut();
$(this).find('.overlay-js').finish().show().fadeOut();
});
});
This all works great when I fire up the app for the first time. However,
if I navigate away from the home page, when I come back, the fade effect
no longer works until I "refresh" the page. Any ideas?
Rails cache fetch with failover
Rails cache fetch with failover
We use this to get a value from an external API:
def get_value
Rails.cache.fetch "some_key", expires_in: 15.second do
# hit some external API
end
end
But sometimes the external API goes down and when we try to hit it, it
raises exceptions.
To fix this we'd like to:
try updating it every 15 seconds
but if it goes offline, use the old value for up to 5 minutes, retrying
every 15 seconds or so
if it's stale for more than 5 minutes, only then start raising exceptions
Is there a convenient wrapper/library for this or what would be a good
solution? We could code up something custom, but it seems like a common
enough use case there should be something battle tested out there. Thanks!
We use this to get a value from an external API:
def get_value
Rails.cache.fetch "some_key", expires_in: 15.second do
# hit some external API
end
end
But sometimes the external API goes down and when we try to hit it, it
raises exceptions.
To fix this we'd like to:
try updating it every 15 seconds
but if it goes offline, use the old value for up to 5 minutes, retrying
every 15 seconds or so
if it's stale for more than 5 minutes, only then start raising exceptions
Is there a convenient wrapper/library for this or what would be a good
solution? We could code up something custom, but it seems like a common
enough use case there should be something battle tested out there. Thanks!
Jquery with php and send mail
Jquery with php and send mail
I have one question , i have my form working very well with jquery - no
send at the moment - , this jquery works over website with page with his
header , body and footer and many divs inside , this jquery auto call the
same page for send the form and no call external page
My code it´s this :
<script>
jQuery(document).ready(function() {
$("#form1").submit(function(e){
e.preventDefault();
var data = jQuery('#form1').serialize();
jQuery.ajax({
data: data,
cache: false,
url: 'home.php',
type: 'POST',
async:false,
success: function(){
var tit=$("#title_s").val();
var men=$("#mensaje_s").val();
if (tit=="" || men=="")
{
jQuery("#cp_asesor_request_ok").show();
}
else
{
jQuery("#cp_asesor_request_ok").show();
}
}
});
});
});
</script>
**The Form**
<div id="cp_asesor_request_ok" style="display:none;">Form Send</div>
<div id="cp_asesor_request_fail" style="display:none;">Error Send</div>
<form id="form1" name="form1" method="post" action="">
<p>
<label for="textfield"></label>
<input type="text" name="title" id="title_s" class="cp_input_asesor"
value="title" onclick="this.value=''"/>
</p>
<p>
<label for="textarea"></label>
<textarea name="message" id="mensaje_s" class="cp_textarea_asesor"
cols="45" rows="5" title="Insertar Mensaje de Solicitud"></textarea>
<input type="submit" name="button" class="cp_submit_asesor" value="Send" />
</p>
</form>
The question it´s how i can send the email from form because all do from
jquery but how i can call to the php mail function from the same page , i
need yes or yes call to external page for send the email ? or from the
same page called home.php i can send the email , the page it´s home.php
and need call other time to home.php for send email , if no use jquery
it´s easy buut if use jquery how i can do it
Thank´s
I have one question , i have my form working very well with jquery - no
send at the moment - , this jquery works over website with page with his
header , body and footer and many divs inside , this jquery auto call the
same page for send the form and no call external page
My code it´s this :
<script>
jQuery(document).ready(function() {
$("#form1").submit(function(e){
e.preventDefault();
var data = jQuery('#form1').serialize();
jQuery.ajax({
data: data,
cache: false,
url: 'home.php',
type: 'POST',
async:false,
success: function(){
var tit=$("#title_s").val();
var men=$("#mensaje_s").val();
if (tit=="" || men=="")
{
jQuery("#cp_asesor_request_ok").show();
}
else
{
jQuery("#cp_asesor_request_ok").show();
}
}
});
});
});
</script>
**The Form**
<div id="cp_asesor_request_ok" style="display:none;">Form Send</div>
<div id="cp_asesor_request_fail" style="display:none;">Error Send</div>
<form id="form1" name="form1" method="post" action="">
<p>
<label for="textfield"></label>
<input type="text" name="title" id="title_s" class="cp_input_asesor"
value="title" onclick="this.value=''"/>
</p>
<p>
<label for="textarea"></label>
<textarea name="message" id="mensaje_s" class="cp_textarea_asesor"
cols="45" rows="5" title="Insertar Mensaje de Solicitud"></textarea>
<input type="submit" name="button" class="cp_submit_asesor" value="Send" />
</p>
</form>
The question it´s how i can send the email from form because all do from
jquery but how i can call to the php mail function from the same page , i
need yes or yes call to external page for send the email ? or from the
same page called home.php i can send the email , the page it´s home.php
and need call other time to home.php for send email , if no use jquery
it´s easy buut if use jquery how i can do it
Thank´s
How to get rid of NullReferenceExcetion error
How to get rid of NullReferenceExcetion error
Hi I got this error NullReferenceException was unhandled by user code. The
error occurs in PropertyChanged(this, new
PropertyChangedEventArgs("AboveAircraft")); I tried if( this != null) and
it still got the error. How do I get rid of it. The code is like this:
public int AboveAircraft
{
get { return _above; }
set
{
if (SetProperty(ref _above, value, "AboveAircraft") &&
_updateModel)
{
if (Model.AltitudeBand == null)
{
Model.AltitudeBand = new AltitudeBand();
}
if (this != null && AboveAircraft != null)
{
PropertyChanged(this, new
PropertyChangedEventArgs("AboveAircraft"));
if (_above < _below)
{
BelowAircraft = _above;
}
}
Model.AltitudeBand .Above = new AltitudeBandLimit() { Unit
= AltitudeUnit.Foot, Value = _above };
}
}
}
Hi I got this error NullReferenceException was unhandled by user code. The
error occurs in PropertyChanged(this, new
PropertyChangedEventArgs("AboveAircraft")); I tried if( this != null) and
it still got the error. How do I get rid of it. The code is like this:
public int AboveAircraft
{
get { return _above; }
set
{
if (SetProperty(ref _above, value, "AboveAircraft") &&
_updateModel)
{
if (Model.AltitudeBand == null)
{
Model.AltitudeBand = new AltitudeBand();
}
if (this != null && AboveAircraft != null)
{
PropertyChanged(this, new
PropertyChangedEventArgs("AboveAircraft"));
if (_above < _below)
{
BelowAircraft = _above;
}
}
Model.AltitudeBand .Above = new AltitudeBandLimit() { Unit
= AltitudeUnit.Foot, Value = _above };
}
}
}
How to make array data in custom jQuery Function?
How to make array data in custom jQuery Function?
I'm looking for some tutorial to make an array data in custom jQuery
Function, but I can't find any. Can you tell me how to make an array in
jQuery Function? I want to call my function like this :
$(this).myPlugin({
data_first: '1'
data_second: 'Hello'
});
my function script
(function($) {
$.fn.myPlugin = function(data) {
return this.each(function() {
alert(data[data_first]+' bla bla '+ data[data_second]);
});
}
})(jQuery);
I'm looking for some tutorial to make an array data in custom jQuery
Function, but I can't find any. Can you tell me how to make an array in
jQuery Function? I want to call my function like this :
$(this).myPlugin({
data_first: '1'
data_second: 'Hello'
});
my function script
(function($) {
$.fn.myPlugin = function(data) {
return this.each(function() {
alert(data[data_first]+' bla bla '+ data[data_second]);
});
}
})(jQuery);
How Can i send the Message or Notification to Particular Friend In Facebook
How Can i send the Message or Notification to Particular Friend In Facebook
I need to send the Notification or Message to Particular Friend In
Facebook, I have used the WCF Webservice and i also get the Friend's ID
but when i send the message or Notification then I m getting the Following
Error AS "(OAuthException - #200) (#200) Feed story publishing to other
users is disabled for this application"
Please reply me ASAP Thanks in Advance !!!
Nikunj
I need to send the Notification or Message to Particular Friend In
Facebook, I have used the WCF Webservice and i also get the Friend's ID
but when i send the message or Notification then I m getting the Following
Error AS "(OAuthException - #200) (#200) Feed story publishing to other
users is disabled for this application"
Please reply me ASAP Thanks in Advance !!!
Nikunj
open pdf toprint in new tab using javascript in asp.net c#
open pdf toprint in new tab using javascript in asp.net c#
hiexperts,
i need your help. i have a web application and i am creating a pdf using
itext sharp and trying to print it silently.
after creating the pdf i am tring to print it using the code
MemoryStream ms = new MemoryStream();
string baseUrl = Request.Url.GetLeftPart(UriPartial.Authority);
var urlPdf = Server.MapPath("~/MERGPdf/Merge_doc.pdf");
PdfReader ps = new PdfReader(urlPdf);
/*inserts js into pdf*/
PdfStamper pdf = new PdfStamper(ps, ms);
pdf.JavaScript = "this.print({bUI: false, bSilent: true, bShrinkToFit:
true});";
but my issue is, the pdf is opening in same window and the user has to
click back button to go to page.. how can avoid it..
regards,
Sivajith S.
hiexperts,
i need your help. i have a web application and i am creating a pdf using
itext sharp and trying to print it silently.
after creating the pdf i am tring to print it using the code
MemoryStream ms = new MemoryStream();
string baseUrl = Request.Url.GetLeftPart(UriPartial.Authority);
var urlPdf = Server.MapPath("~/MERGPdf/Merge_doc.pdf");
PdfReader ps = new PdfReader(urlPdf);
/*inserts js into pdf*/
PdfStamper pdf = new PdfStamper(ps, ms);
pdf.JavaScript = "this.print({bUI: false, bSilent: true, bShrinkToFit:
true});";
but my issue is, the pdf is opening in same window and the user has to
click back button to go to page.. how can avoid it..
regards,
Sivajith S.
CSS3 image rotating spinner in JS for non CSS3 browsers?
CSS3 image rotating spinner in JS for non CSS3 browsers?
I have a rotating image spinner that looks fantastic...in browsers that
support it. it can be seen at kingpetroleum.co.uk/background.php - it's in
the top corner.
I need to somehow create the same effect for users that are using browsers
that can't display it.
I'm not great with javascript so would be hoping on finding a good
tutorial / guide etc but after a bit of googling I've not come up with
anything.
Any help is appreciated.
I have a rotating image spinner that looks fantastic...in browsers that
support it. it can be seen at kingpetroleum.co.uk/background.php - it's in
the top corner.
I need to somehow create the same effect for users that are using browsers
that can't display it.
I'm not great with javascript so would be hoping on finding a good
tutorial / guide etc but after a bit of googling I've not come up with
anything.
Any help is appreciated.
Friday, 30 August 2013
cookies handling in plone python
cookies handling in plone python
i have created 2 cookies using
self.request.response.setCookie('lastvisit', left_src) this comand after
that when it complete its work it will be deleted but some times browser
page display in previous value cookie
self.request.response.expireCookie("lastvisit") this is my deleting
command so any one can help me
i have created 2 cookies using
self.request.response.setCookie('lastvisit', left_src) this comand after
that when it complete its work it will be deleted but some times browser
page display in previous value cookie
self.request.response.expireCookie("lastvisit") this is my deleting
command so any one can help me
Thursday, 29 August 2013
Activate View for header delegate for specific section in single table
Activate View for header delegate for specific section in single table
I am developing an application in which I need header to customize and add
my own button just for single section. I googled and done some code where
I am able to add button, but I am facing two issue.
Titles of other's section is not showing.
Button not show properly because of tableview scroll size same after
adding button. Here is what I am doing.
(UIView *) tableView:(UITableView *)tableView
viewForHeaderInSection:(NSInteger)section{
UIView * headerView = [[[UIView alloc] initWithFrame:CGRectMake(1, 0,
tableView.bounds.size.width, 40)] autorelease]; [headerView
setBackgroundColor:[UIColor clearColor]]; if(section==2){ float width =
tableView.bounds.size.width; int fontSize = 18; int padding = 10;
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(padding, 2,
width - padding, fontSize)]; label.text = @"Texto"; label.backgroundColor
= [UIColor clearColor]; label.textColor = [UIColor whiteColor];
label.shadowColor = [UIColor darkGrayColor]; label.shadowOffset =
CGSizeMake(0,1); label.font = [UIFont boldSystemFontOfSize:fontSize];
[headerView addSubview:label];
UIButton * registerButton = [UIButton buttonWithType:UIButtonTypeCustom];
[registerButton setImage:[UIImage imageNamed:@"P_register_btn.png"]
forState:UIControlStateNormal]; [registerButton setFrame:CGRectMake(0, 0,
320, 150)]; [headerView addSubview:registerButton];
return headerView; } return headerView;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 3;
}
(NSString *)tableView:(UITableView *)tableView
titleForHeaderInSection:(NSInteger)section{ if(section==0) return
@"Registration"; else if(section==1) return @"Player Detail"; return nil;
}
Here is Image of my out put in which Texto text show but button is under
that area where the end limit of table view scroll height and also section
0 and 1 title is not showing I also block code for first and second
section in viewforheaderinsection. Thanks in advance.
I am developing an application in which I need header to customize and add
my own button just for single section. I googled and done some code where
I am able to add button, but I am facing two issue.
Titles of other's section is not showing.
Button not show properly because of tableview scroll size same after
adding button. Here is what I am doing.
(UIView *) tableView:(UITableView *)tableView
viewForHeaderInSection:(NSInteger)section{
UIView * headerView = [[[UIView alloc] initWithFrame:CGRectMake(1, 0,
tableView.bounds.size.width, 40)] autorelease]; [headerView
setBackgroundColor:[UIColor clearColor]]; if(section==2){ float width =
tableView.bounds.size.width; int fontSize = 18; int padding = 10;
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(padding, 2,
width - padding, fontSize)]; label.text = @"Texto"; label.backgroundColor
= [UIColor clearColor]; label.textColor = [UIColor whiteColor];
label.shadowColor = [UIColor darkGrayColor]; label.shadowOffset =
CGSizeMake(0,1); label.font = [UIFont boldSystemFontOfSize:fontSize];
[headerView addSubview:label];
UIButton * registerButton = [UIButton buttonWithType:UIButtonTypeCustom];
[registerButton setImage:[UIImage imageNamed:@"P_register_btn.png"]
forState:UIControlStateNormal]; [registerButton setFrame:CGRectMake(0, 0,
320, 150)]; [headerView addSubview:registerButton];
return headerView; } return headerView;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 3;
}
(NSString *)tableView:(UITableView *)tableView
titleForHeaderInSection:(NSInteger)section{ if(section==0) return
@"Registration"; else if(section==1) return @"Player Detail"; return nil;
}
Here is Image of my out put in which Texto text show but button is under
that area where the end limit of table view scroll height and also section
0 and 1 title is not showing I also block code for first and second
section in viewforheaderinsection. Thanks in advance.
Multiple id's in single javascript click event
Multiple id's in single javascript click event
In javascript I am using click event to change chart data. below is a
method for click event.
$('#pro1').click(function () {
chart.series[0].update({
data: pro1
});
});
$('#pro2').click(function () {
chart.series[0].update({
data: pro2
});
});
$('#pro3').click(function () {
chart.series[0].update({
data: pro3
});
});
I need to minify these three click events in one event, means I want to
write one click event which handle the id's. some thing like below code.
$('#pro'+i).click(function () {
chart.series[0].update({
data: pro+i
});
});
I don't know how to do it exactly. above code is not correct it is just my
half knowledge of javascript.
In javascript I am using click event to change chart data. below is a
method for click event.
$('#pro1').click(function () {
chart.series[0].update({
data: pro1
});
});
$('#pro2').click(function () {
chart.series[0].update({
data: pro2
});
});
$('#pro3').click(function () {
chart.series[0].update({
data: pro3
});
});
I need to minify these three click events in one event, means I want to
write one click event which handle the id's. some thing like below code.
$('#pro'+i).click(function () {
chart.series[0].update({
data: pro+i
});
});
I don't know how to do it exactly. above code is not correct it is just my
half knowledge of javascript.
Wednesday, 28 August 2013
Upload photo to facebook fan page wall
Upload photo to facebook fan page wall
This tutorial has helped me writing the following code; with it I am able
to upload a photo to an album on my fan page. How can I make it so that I
can publish to the fan page wall and not just upload the photo to the
album? I am looking in implementing the required code within this below.
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
require_once 'library/facebook.php';
$facebook = new Facebook(array(
'appId' => 'My APP ID',
'secret' => 'My Secret KEY',
'fileUpload' => true
));
#It can be found at https://developers.facebook.com/tools/access_token/
#Change to your token.
$access_token = 'My access token';
$params = array('access_token' => $access_token);
#The id of the fanpage
$fanpage = 'My Fan Page ID';
#The id of the album
$album_id ='My Album ID';
$accounts = $facebook->api('/My User Name/accounts', 'GET', $params);
foreach($accounts['data'] as $account) {
if( $account['id'] == $fanpage || $account['name'] == $fanpage ){
$fanpage_token = $account['access_token'];
}
}
$valid_files = array('image/jpeg', 'image/png', 'image/gif');
if(isset($_FILES) && !empty($_FILES)){
if( !in_array($_FILES['pic']['type'], $valid_files ) ){
echo 'Only jpg, png and gif image types are supported!';
}else{
$img = realpath($_FILES["pic"]["tmp_name"]);
$args = array(
'message' => 'This photo was uploaded via WebSpeaks.in',
'image' => '@' . $img,
'aid' => $album_id,
'no_story' => 1,
'access_token' => $fanpage_token
);
$photo = $facebook->api($album_id . '/photos', 'post', $args);
if( is_array( $photo ) && !empty( $photo['id'] ) ){
echo '<p><a target="_blank"
href="http://www.facebook.com/photo.php?fbid='.$photo['id'].'">Click
here to watch this photo on Facebook.</a></p>';
}
}
}
?>
This tutorial has helped me writing the following code; with it I am able
to upload a photo to an album on my fan page. How can I make it so that I
can publish to the fan page wall and not just upload the photo to the
album? I am looking in implementing the required code within this below.
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
require_once 'library/facebook.php';
$facebook = new Facebook(array(
'appId' => 'My APP ID',
'secret' => 'My Secret KEY',
'fileUpload' => true
));
#It can be found at https://developers.facebook.com/tools/access_token/
#Change to your token.
$access_token = 'My access token';
$params = array('access_token' => $access_token);
#The id of the fanpage
$fanpage = 'My Fan Page ID';
#The id of the album
$album_id ='My Album ID';
$accounts = $facebook->api('/My User Name/accounts', 'GET', $params);
foreach($accounts['data'] as $account) {
if( $account['id'] == $fanpage || $account['name'] == $fanpage ){
$fanpage_token = $account['access_token'];
}
}
$valid_files = array('image/jpeg', 'image/png', 'image/gif');
if(isset($_FILES) && !empty($_FILES)){
if( !in_array($_FILES['pic']['type'], $valid_files ) ){
echo 'Only jpg, png and gif image types are supported!';
}else{
$img = realpath($_FILES["pic"]["tmp_name"]);
$args = array(
'message' => 'This photo was uploaded via WebSpeaks.in',
'image' => '@' . $img,
'aid' => $album_id,
'no_story' => 1,
'access_token' => $fanpage_token
);
$photo = $facebook->api($album_id . '/photos', 'post', $args);
if( is_array( $photo ) && !empty( $photo['id'] ) ){
echo '<p><a target="_blank"
href="http://www.facebook.com/photo.php?fbid='.$photo['id'].'">Click
here to watch this photo on Facebook.</a></p>';
}
}
}
?>
Sharepoint Menu enable parent navigation
Sharepoint Menu enable parent navigation
On the v4.master I have an Sharepoint:Menu, and I would like to know how
to enable the parent link. Wich property should I change on the
SharePoint:AspMenu ?
At the moment the parent has an anchor with href="#", but I would like to
configure it to be clicable and redirected to the correct link.
The ASP.Net code:
<div>
<SharePoint:DelegateControl runat="server"
ControlId="QuickLaunchDataSource">
<Template_Controls>
<asp:SiteMapDataSource
SiteMapProvider="SPNavigationProvider"
ShowStartingNode="True" id="QuickLaunchSiteMap"
StartingNodeUrl="sid:1025" runat="server" />
</Template_Controls>
</SharePoint:DelegateControl>
<SharePoint:UIVersionedContent UIVersion="3" runat="server">
<ContentTemplate>
<SharePoint:AspMenu id="QuickLaunchMenu"
runat="server" DataSourceId="QuickLaunchSiteMap"
Orientation="Vertical" StaticDisplayLevels="2"
ItemWrap="true" MaximumDynamicDisplayLevels="0"
StaticSubMenuIndent="0" SkipLinkText=""
CssClass="s4-die">
<LevelMenuItemStyles>
<asp:menuitemstyle CssClass="ms-navheader" />
<asp:menuitemstyle CssClass="ms-navitem" />
</LevelMenuItemStyles>
<LevelSubMenuStyles>
<asp:submenustyle CssClass="ms-navSubMenu1" />
<asp:submenustyle CssClass="ms-navSubMenu2" />
</LevelSubMenuStyles>
<LevelSelectedStyles>
<asp:menuitemstyle
CssClass="ms-selectednavheader" />
<asp:menuitemstyle CssClass="ms-selectednav" />
</LevelSelectedStyles>
</SharePoint:AspMenu>
</ContentTemplate>
</SharePoint:UIVersionedContent>
<SharePoint:UIVersionedContent UIVersion="4" runat="server">
<ContentTemplate>
<SharePoint:AspMenu id="V4QuickLaunchMenu"
runat="server" EnableViewState="false"
DataSourceId="QuickLaunchSiteMap"
UseSimpleRendering="true" UseSeparateCss="false"
Orientation="Vertical" StaticDisplayLevels="3"
MaximumDynamicDisplayLevels="3" SkipLinkText=""
CssClass="s4-ql" />
</ContentTemplate>
</SharePoint:UIVersionedContent>
</div>
The HTML is generated as:
CHILD NODE:
<li class="static">
<a class="static menu-item" href="/aaa/bbb">
<span class="additional-background">
<span class="menu-item-text">aadasa</span>
</span>
</a>
</li>
PARENT NODE:
<li class="static">
<a class="static menu-item close" href="#">
<span class="additional-background">
<span class="menu-item-text">dasd</span>
</span>
</a>
</li>
On the v4.master I have an Sharepoint:Menu, and I would like to know how
to enable the parent link. Wich property should I change on the
SharePoint:AspMenu ?
At the moment the parent has an anchor with href="#", but I would like to
configure it to be clicable and redirected to the correct link.
The ASP.Net code:
<div>
<SharePoint:DelegateControl runat="server"
ControlId="QuickLaunchDataSource">
<Template_Controls>
<asp:SiteMapDataSource
SiteMapProvider="SPNavigationProvider"
ShowStartingNode="True" id="QuickLaunchSiteMap"
StartingNodeUrl="sid:1025" runat="server" />
</Template_Controls>
</SharePoint:DelegateControl>
<SharePoint:UIVersionedContent UIVersion="3" runat="server">
<ContentTemplate>
<SharePoint:AspMenu id="QuickLaunchMenu"
runat="server" DataSourceId="QuickLaunchSiteMap"
Orientation="Vertical" StaticDisplayLevels="2"
ItemWrap="true" MaximumDynamicDisplayLevels="0"
StaticSubMenuIndent="0" SkipLinkText=""
CssClass="s4-die">
<LevelMenuItemStyles>
<asp:menuitemstyle CssClass="ms-navheader" />
<asp:menuitemstyle CssClass="ms-navitem" />
</LevelMenuItemStyles>
<LevelSubMenuStyles>
<asp:submenustyle CssClass="ms-navSubMenu1" />
<asp:submenustyle CssClass="ms-navSubMenu2" />
</LevelSubMenuStyles>
<LevelSelectedStyles>
<asp:menuitemstyle
CssClass="ms-selectednavheader" />
<asp:menuitemstyle CssClass="ms-selectednav" />
</LevelSelectedStyles>
</SharePoint:AspMenu>
</ContentTemplate>
</SharePoint:UIVersionedContent>
<SharePoint:UIVersionedContent UIVersion="4" runat="server">
<ContentTemplate>
<SharePoint:AspMenu id="V4QuickLaunchMenu"
runat="server" EnableViewState="false"
DataSourceId="QuickLaunchSiteMap"
UseSimpleRendering="true" UseSeparateCss="false"
Orientation="Vertical" StaticDisplayLevels="3"
MaximumDynamicDisplayLevels="3" SkipLinkText=""
CssClass="s4-ql" />
</ContentTemplate>
</SharePoint:UIVersionedContent>
</div>
The HTML is generated as:
CHILD NODE:
<li class="static">
<a class="static menu-item" href="/aaa/bbb">
<span class="additional-background">
<span class="menu-item-text">aadasa</span>
</span>
</a>
</li>
PARENT NODE:
<li class="static">
<a class="static menu-item close" href="#">
<span class="additional-background">
<span class="menu-item-text">dasd</span>
</span>
</a>
</li>
nested, recursive iterations RoR
nested, recursive iterations RoR
I have a big problem.
I'll try to clearly describe the situation!
I have a set of cars. Each car has a date on which it is available.
I have to fix an appointment day on which I'll be able to pick several
cars from my set, and this day must correspond to the day on which all of
the cars I picked are available, see the thing?
The relationships between my model: a one-to-many relationship between
availability and cars, a many-to-many relationship between appointment and
cars.
The idea I had was to pick up the first availability of the first car,
compare it to all availabilities of the second car if there's an equal do
the same with the third car availabilities, if not check the same with the
second availability of the first car etc. I think the idea could work, but
I'm having problems to put it into code. This is what I began with but
it's totally incomplete:
def add_car
@car = Car.find(params[:id])
@appointment = Appointment.find(params[:id])
@i = 0
@cars= []
@car.each do |d|
@cars << d
end
end
I have a big problem.
I'll try to clearly describe the situation!
I have a set of cars. Each car has a date on which it is available.
I have to fix an appointment day on which I'll be able to pick several
cars from my set, and this day must correspond to the day on which all of
the cars I picked are available, see the thing?
The relationships between my model: a one-to-many relationship between
availability and cars, a many-to-many relationship between appointment and
cars.
The idea I had was to pick up the first availability of the first car,
compare it to all availabilities of the second car if there's an equal do
the same with the third car availabilities, if not check the same with the
second availability of the first car etc. I think the idea could work, but
I'm having problems to put it into code. This is what I began with but
it's totally incomplete:
def add_car
@car = Car.find(params[:id])
@appointment = Appointment.find(params[:id])
@i = 0
@cars= []
@car.each do |d|
@cars << d
end
end
Tuesday, 27 August 2013
Can somebody help me setup calabash-ios to run on linux pc?
Can somebody help me setup calabash-ios to run on linux pc?
I was looking for mobile automation testing tools and found calabash as
best suit for my requirement.
I have a mobile application to be tested on both android and ios. As off
now, i had to quickly setup calabash-ios for testing the app on real
device.
Based on my research until now, i am aware that the app should have been
integrated with xcode and then installed on real device.
My question is, can we setup calabash-ios on my linux pc?
If yes, please help me with procedure.
I was looking for mobile automation testing tools and found calabash as
best suit for my requirement.
I have a mobile application to be tested on both android and ios. As off
now, i had to quickly setup calabash-ios for testing the app on real
device.
Based on my research until now, i am aware that the app should have been
integrated with xcode and then installed on real device.
My question is, can we setup calabash-ios on my linux pc?
If yes, please help me with procedure.
Convert Javascript to Php
Convert Javascript to Php
How can I turn this Google Analytics tracking code to a php. I tried
looking for something to convert javascript to php, had no luck. Doesnt
look like a big code, I dont want to have this javascript load on my site,
a php would be better, even if i add to add a fake img to the footer to
trigger the php, that would be fine too.
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXX-XXXX-XX']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type =
'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' :
'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
</script>
How can I turn this Google Analytics tracking code to a php. I tried
looking for something to convert javascript to php, had no luck. Doesnt
look like a big code, I dont want to have this javascript load on my site,
a php would be better, even if i add to add a fake img to the footer to
trigger the php, that would be fine too.
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXX-XXXX-XX']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type =
'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' :
'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
</script>
Could not Load file or assembly 'projectname'
Could not Load file or assembly 'projectname'
So basically, I was working on my C# asp.net project in Visual Studio 2012
Express for web when all of a sudden I was give a very strange warning by
visual studio. I get this warning whenever I try to build or debug the
project. Maybe I accidentally clicked on something I shouldn't have, I
don't know.
This is the warning.
"Z:\AAIA_NewCatalog\AdminSite\AdminSite\Catalogdata\Update.aspx: ASP.NET
runtime error: Could not load file or assembly 'AdminSite' or one of its
dependencies. Access is denied.
Z:\AAIA_NewCatalog\AdminSite\AdminSite\Catalogdata\Update.aspx"
AdminSite is the name of the project and the solution
And here is the error
Error 1 Unable to copy file "obj\Debug\AdminSite.dll" to
"bin\AdminSite.dll". Access to the path 'bin\AdminSite.dll' is denied.
AdminSite
I am certainly willing to post any code, I am just not sure what to post,
perhaps stuff from my Web.config.
From my perspective it could be a permissions issue, but if you have seen
this before please respond with help.
So basically, I was working on my C# asp.net project in Visual Studio 2012
Express for web when all of a sudden I was give a very strange warning by
visual studio. I get this warning whenever I try to build or debug the
project. Maybe I accidentally clicked on something I shouldn't have, I
don't know.
This is the warning.
"Z:\AAIA_NewCatalog\AdminSite\AdminSite\Catalogdata\Update.aspx: ASP.NET
runtime error: Could not load file or assembly 'AdminSite' or one of its
dependencies. Access is denied.
Z:\AAIA_NewCatalog\AdminSite\AdminSite\Catalogdata\Update.aspx"
AdminSite is the name of the project and the solution
And here is the error
Error 1 Unable to copy file "obj\Debug\AdminSite.dll" to
"bin\AdminSite.dll". Access to the path 'bin\AdminSite.dll' is denied.
AdminSite
I am certainly willing to post any code, I am just not sure what to post,
perhaps stuff from my Web.config.
From my perspective it could be a permissions issue, but if you have seen
this before please respond with help.
Jquery: Hiding the closest element
Jquery: Hiding the closest element
I have some jquery to hide content on an index page.
the commented out code in the fiddle is what i have at the moment - but it
hides all content divs if any toggle link is clicked.
I want only the class immediately following the toggle link to be
hidden/shown, but can't get it working. Have tried using parents, nextAll,
and various other methods from similar examples I've found on SO, but so
far nothing has worked.
I have some jquery to hide content on an index page.
the commented out code in the fiddle is what i have at the moment - but it
hides all content divs if any toggle link is clicked.
I want only the class immediately following the toggle link to be
hidden/shown, but can't get it working. Have tried using parents, nextAll,
and various other methods from similar examples I've found on SO, but so
far nothing has worked.
Getting all post/page IDs related to a soon-to-be-deleted tag/cat
Getting all post/page IDs related to a soon-to-be-deleted tag/cat
When deleting a tag, category or other term I would like to get the IDs of
the posts that are related to the term before deletion. Wordpress uses
wp_delete_term, which is found in taxonomy.php, to delete a term. In this
function the earliest hook is "delete_term_taxonomy". However, it seems
like the relationships are already deleted before this hook fires.
I would like to make this query:
SELECT object_id FROM $wpdb->term_relationships WHERE term_taxonomy_id = $id
This would normally return all the post ids related to a term
(category/tag/etc). Is there any other hook I can use? Or maybe a hack?
When deleting a tag, category or other term I would like to get the IDs of
the posts that are related to the term before deletion. Wordpress uses
wp_delete_term, which is found in taxonomy.php, to delete a term. In this
function the earliest hook is "delete_term_taxonomy". However, it seems
like the relationships are already deleted before this hook fires.
I would like to make this query:
SELECT object_id FROM $wpdb->term_relationships WHERE term_taxonomy_id = $id
This would normally return all the post ids related to a term
(category/tag/etc). Is there any other hook I can use? Or maybe a hack?
WSO2 ESB 4.7.0 JMS MessageStore/MessateProcessor fail to handle JSON correctly
WSO2 ESB 4.7.0 JMS MessageStore/MessateProcessor fail to handle JSON
correctly
I am using WSO2 ESB 4.7.0 with ActiveMQ. I am trying to implement a simple
store and forward configuration as per this wso2 documentation.
Here is the proxy I am using to Store in JMS and Forward :
<?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse"
name="testJMSStorenFwd"
transports="http"
startOnLoad="true"
trace="disable">
<description/>
<target>
<inSequence onError="fault">
<property name="messageType" value="application/json"
scope="axis2"/>
<property name="FORCE_ERROR_ON_SOAP_FAULT" value="true"/>
<property name="OUT_ONLY" value="true"/>
<log level="full"/>
<property name="target.endpoint" value="JMSRcvEndPoint"
format="soap11"/>
<store messageStore="FMSReadings"/>
<!--send>
<endpoint key="JMSRcvEndPoint" format="soap11"/>
</send-->
<property name="FORCE_SC_ACCEPTED" value="true" scope="axis2"/>
</inSequence>
<outSequence>
<send/>
</outSequence>
</target>
</proxy>
Here is the endpoint to which the Message should ultimately be forwarded :
<?xml version="1.0" encoding="UTF-8"?>
<endpoint xmlns="http://ws.apache.org/ns/synapse" name="JMSRcvEndPoint">
<address uri="http://kk1:8282/services/testJMSRcvProxy" format="soap11"/>
</endpoint>
Here is the proxy which receives the forwarded message ( it just logs the
received message for this test):
<?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse"
name="testJMSRcvProxy"
transports="http"
startOnLoad="true"
trace="disable">
<description/>
<target>
<inSequence onError="fault">
<property name="messageType" value="application/json" scope="axis2"/>
<property name="FORCE_ERROR_ON_SOAP_FAULT" value="true"/>
<log level="full"/>
<drop/>
</inSequence>
<outSequence>
<drop/>
</outSequence>
</target>
</proxy>
Here is my messagestore :
<?xml version="1.0" encoding="UTF-8"?>
<messageStore xmlns="http://ws.apache.org/ns/synapse"
class="org.wso2.carbon.message.store.persistence.jms.JMSMessageStore"
name="FMSReadings">
<parameter
name="java.naming.factory.initial">org.apache.activemq.jndi.ActiveMQInitialContextFactory</parameter>
<parameter name="store.jms.cache.connection">false</parameter>
<parameter
name="java.naming.provider.url">tcp://localhost:61616</parameter>
<parameter name="store.jms.JMSSpecVersion">1.1</parameter>
</messageStore>
Here is my MessageProcessor :
<?xml version="1.0" encoding="UTF-8"?>
<messageProcessor xmlns="http://ws.apache.org/ns/synapse"
class="org.apache.synapse.message.processors.forward.ScheduledMessageForwardingProcessor"
name="fwdTotestJMSRcvProxy"
messageStore="FMSReadings">
<parameter name="interval">1000</parameter>
</messageProcessor>
I am using a simple curl command with very basic JSON to test this setup
like below :
curl -v -H "Accept: application/json" -H "Content-Type:application/json"
-d '{"mail":"faisal.shaik@youtility.in"}'
http://kk1:8282/services/testJMSStorenFwd
When I run this the message gets stored and forwarded by the setup ( I can
verify from ActiveMQ web UI that a message was enqueued and dequeued) but
I get below error in ESB logs :
[2013-08-27 14:24:44,052] INFO - To: /services/testJMSStorenFwd,
MessageID: urn:uuid:bb553e52-ee61-4d15-8c1f-19be1356c8e0, Direction:
request, Envelope: <?xml version='1.0' encoding='utf-8'?><soapenv:Envelope
xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope"><soapenv:Body><mail>faisal.shaik@youtility.in</mail></soapenv:Body></soapenv:Envelope>
{org.apache.synapse.mediators.builtin.LogMediator}
[2013-08-27 14:24:44,085] ERROR - Error building message
{org.apache.synapse.transport.passthru.util.DeferredMessageBuilder}
org.apache.axis2.AxisFault: Failed to convert JSON to XML payload.
Expected a ',' or '}' at character 50 of { "xmlPayload" :
<mail>faisal.shaik@youtility.in</mail>}
at org.apache.axis2.json.JSONBuilder.processDocument(JSONBuilder.java:86)
at
org.apache.synapse.transport.passthru.util.DeferredMessageBuilder.getDocument(DeferredMessageBuilder.java:118)
If you notice in the testJMSStorenFwd proxy above I've a commented out
send section. If I uncomment that and comment out the
<property name="target.endpoint" value="JMSRcvEndPoint" format="soap11"/>
<store messageStore="FMSReadings"/>
section, I get the json properly converted to xml and following output in
the logs :
[2013-08-27 14:53:27,333] INFO - To: /services/testJMSStorenFwd,
MessageID: urn:uuid:e482aba1-98a9-4181-9c8e-c5110dcefd09, Direction:
request, Envelope: <?xml version='1.0' encoding='utf-8'?><soapenv:Envelope
xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope"><soapenv:Body><mail>faisal.shaik@youtility.in</mail></soapenv:Body></soapenv:Envelope>
{org.apache.synapse.mediators.builtin.LogMediator}
[2013-08-27 14:53:27,346] INFO - To: /services/testJMSRcvProxy,
MessageID: urn:uuid:e6da7131-60ec-4c92-b204-e3843f7e6e91, Direction:
request, Envelope: <?xml version='1.0' encoding='utf-8'?><soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Body><soapenv:Envelope><soapenv:Body><mail>faisal.shaik@youtility.in</mail></soapenv:Body></soapenv:Envelope></soapenv:Body></soapenv:Envelope>
{org.apache.synapse.mediators.builtin.LogMediator}
As you can see from above, the same input given to messagestore &
messageprocessor mechanism using same settings results in JSON to XML
conversion errors.
Is this a bug in the wso2 esb MessageStore &/or MessageProcessor or am I
doing something wrong? Is there a way to get rid of the errors I am
getting while using this JMS store & forward without resorting to the
script mediator?
correctly
I am using WSO2 ESB 4.7.0 with ActiveMQ. I am trying to implement a simple
store and forward configuration as per this wso2 documentation.
Here is the proxy I am using to Store in JMS and Forward :
<?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse"
name="testJMSStorenFwd"
transports="http"
startOnLoad="true"
trace="disable">
<description/>
<target>
<inSequence onError="fault">
<property name="messageType" value="application/json"
scope="axis2"/>
<property name="FORCE_ERROR_ON_SOAP_FAULT" value="true"/>
<property name="OUT_ONLY" value="true"/>
<log level="full"/>
<property name="target.endpoint" value="JMSRcvEndPoint"
format="soap11"/>
<store messageStore="FMSReadings"/>
<!--send>
<endpoint key="JMSRcvEndPoint" format="soap11"/>
</send-->
<property name="FORCE_SC_ACCEPTED" value="true" scope="axis2"/>
</inSequence>
<outSequence>
<send/>
</outSequence>
</target>
</proxy>
Here is the endpoint to which the Message should ultimately be forwarded :
<?xml version="1.0" encoding="UTF-8"?>
<endpoint xmlns="http://ws.apache.org/ns/synapse" name="JMSRcvEndPoint">
<address uri="http://kk1:8282/services/testJMSRcvProxy" format="soap11"/>
</endpoint>
Here is the proxy which receives the forwarded message ( it just logs the
received message for this test):
<?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse"
name="testJMSRcvProxy"
transports="http"
startOnLoad="true"
trace="disable">
<description/>
<target>
<inSequence onError="fault">
<property name="messageType" value="application/json" scope="axis2"/>
<property name="FORCE_ERROR_ON_SOAP_FAULT" value="true"/>
<log level="full"/>
<drop/>
</inSequence>
<outSequence>
<drop/>
</outSequence>
</target>
</proxy>
Here is my messagestore :
<?xml version="1.0" encoding="UTF-8"?>
<messageStore xmlns="http://ws.apache.org/ns/synapse"
class="org.wso2.carbon.message.store.persistence.jms.JMSMessageStore"
name="FMSReadings">
<parameter
name="java.naming.factory.initial">org.apache.activemq.jndi.ActiveMQInitialContextFactory</parameter>
<parameter name="store.jms.cache.connection">false</parameter>
<parameter
name="java.naming.provider.url">tcp://localhost:61616</parameter>
<parameter name="store.jms.JMSSpecVersion">1.1</parameter>
</messageStore>
Here is my MessageProcessor :
<?xml version="1.0" encoding="UTF-8"?>
<messageProcessor xmlns="http://ws.apache.org/ns/synapse"
class="org.apache.synapse.message.processors.forward.ScheduledMessageForwardingProcessor"
name="fwdTotestJMSRcvProxy"
messageStore="FMSReadings">
<parameter name="interval">1000</parameter>
</messageProcessor>
I am using a simple curl command with very basic JSON to test this setup
like below :
curl -v -H "Accept: application/json" -H "Content-Type:application/json"
-d '{"mail":"faisal.shaik@youtility.in"}'
http://kk1:8282/services/testJMSStorenFwd
When I run this the message gets stored and forwarded by the setup ( I can
verify from ActiveMQ web UI that a message was enqueued and dequeued) but
I get below error in ESB logs :
[2013-08-27 14:24:44,052] INFO - To: /services/testJMSStorenFwd,
MessageID: urn:uuid:bb553e52-ee61-4d15-8c1f-19be1356c8e0, Direction:
request, Envelope: <?xml version='1.0' encoding='utf-8'?><soapenv:Envelope
xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope"><soapenv:Body><mail>faisal.shaik@youtility.in</mail></soapenv:Body></soapenv:Envelope>
{org.apache.synapse.mediators.builtin.LogMediator}
[2013-08-27 14:24:44,085] ERROR - Error building message
{org.apache.synapse.transport.passthru.util.DeferredMessageBuilder}
org.apache.axis2.AxisFault: Failed to convert JSON to XML payload.
Expected a ',' or '}' at character 50 of { "xmlPayload" :
<mail>faisal.shaik@youtility.in</mail>}
at org.apache.axis2.json.JSONBuilder.processDocument(JSONBuilder.java:86)
at
org.apache.synapse.transport.passthru.util.DeferredMessageBuilder.getDocument(DeferredMessageBuilder.java:118)
If you notice in the testJMSStorenFwd proxy above I've a commented out
send section. If I uncomment that and comment out the
<property name="target.endpoint" value="JMSRcvEndPoint" format="soap11"/>
<store messageStore="FMSReadings"/>
section, I get the json properly converted to xml and following output in
the logs :
[2013-08-27 14:53:27,333] INFO - To: /services/testJMSStorenFwd,
MessageID: urn:uuid:e482aba1-98a9-4181-9c8e-c5110dcefd09, Direction:
request, Envelope: <?xml version='1.0' encoding='utf-8'?><soapenv:Envelope
xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope"><soapenv:Body><mail>faisal.shaik@youtility.in</mail></soapenv:Body></soapenv:Envelope>
{org.apache.synapse.mediators.builtin.LogMediator}
[2013-08-27 14:53:27,346] INFO - To: /services/testJMSRcvProxy,
MessageID: urn:uuid:e6da7131-60ec-4c92-b204-e3843f7e6e91, Direction:
request, Envelope: <?xml version='1.0' encoding='utf-8'?><soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Body><soapenv:Envelope><soapenv:Body><mail>faisal.shaik@youtility.in</mail></soapenv:Body></soapenv:Envelope></soapenv:Body></soapenv:Envelope>
{org.apache.synapse.mediators.builtin.LogMediator}
As you can see from above, the same input given to messagestore &
messageprocessor mechanism using same settings results in JSON to XML
conversion errors.
Is this a bug in the wso2 esb MessageStore &/or MessageProcessor or am I
doing something wrong? Is there a way to get rid of the errors I am
getting while using this JMS store & forward without resorting to the
script mediator?
Python: plot list of tuples
Python: plot list of tuples
I have the following data set. I would like to use python or gnuplot to
plot the data. The tuples are of the form (x,y). The Y axis should be a
log axis. I.E. log(y). A scatter plot or line plot would be ideal.
How can this be done?
[(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08),
(2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09),
(4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)]
I have the following data set. I would like to use python or gnuplot to
plot the data. The tuples are of the form (x,y). The Y axis should be a
log axis. I.E. log(y). A scatter plot or line plot would be ideal.
How can this be done?
[(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08),
(2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09),
(4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)]
Monday, 26 August 2013
Dpkg keep saying that need to --configure -a while trying for network issues on Inspiron 1545
Dpkg keep saying that need to --configure -a while trying for network
issues on Inspiron 1545
I've just installed ubuntu for the first time on a computer (version
12.10). I can't figure out how to get a wired connection to work OR a
wireless connection.
I've read similar problems, and I've tried the other recommended fixes (at
least those that I could figure out), and none of them have worked. Most
of the time the terminal just gives me an error when I try to type in the
message others recommend.
I see a lot of people recommending to type this in:
sudo apt-get remove bcmwl-kernel-source
This gives me an error message that says:
E: dpkg wasa interrupted, you must manually run 'sudo dpkg --configure -a'
to correct the problem.
So, outside of recommending that fix, what are some other options? I'm
using another computer to ask this question.
issues on Inspiron 1545
I've just installed ubuntu for the first time on a computer (version
12.10). I can't figure out how to get a wired connection to work OR a
wireless connection.
I've read similar problems, and I've tried the other recommended fixes (at
least those that I could figure out), and none of them have worked. Most
of the time the terminal just gives me an error when I try to type in the
message others recommend.
I see a lot of people recommending to type this in:
sudo apt-get remove bcmwl-kernel-source
This gives me an error message that says:
E: dpkg wasa interrupted, you must manually run 'sudo dpkg --configure -a'
to correct the problem.
So, outside of recommending that fix, what are some other options? I'm
using another computer to ask this question.
Python:How to arrange pictures randomly in a table?
Python:How to arrange pictures randomly in a table?
I have to make a memory puzzle in a cours. I have a list with all pictures
in it. My problem is how can I arrange these pictures in a table randomly.
from tkinter import*
from random import choice
from PIL import ImageTk
from PIL import Image
class Application(Frame):
def __init__(self, master):
super (Application, self).__init__(master)
self.initUI()
def initUI(self):
self.columnconfigure(0, pad=3)
self.columnconfigure(1, pad=3)
self.columnconfigure(2, pad=3)
self.rowconfigure(0, pad=3)
self.rowconfigure(1, pad=3)
self.rowconfigure(2, pad=3)
self.im=["1.png","2.png","3.png","4.png", "5.png", "6.png", "7.png",
"8.png"]
self.label1 = Label(self)
self.label1.grid(row=0, column=0)
self.label2 = Label(self)
self.label2.grid(row=0, column=1)
self.label3 = Label(self)
self.label3.grid(row=1, column=0)
self.label4 = Label(self)
self.label4.grid(row=1, column=1)
self.label5 = Label(self)
self.label5.grid(row=2, column=0)
self.label6 = Label(self)
self.label6.grid(row=2, column=1)
for element in im:
self.img = ImageTk.PhotoImage( Image.open(choice(self.im)))
self.label1['image']= self.img
self.img = ImageTk.PhotoImage( Image.open(choice(self.im)))
self.label2['image']= self.img
self.img = ImageTk.PhotoImage( Image.open(choice(self.im)))
self.label3['image']= self.img
self.img = ImageTk.PhotoImage( Image.open(choice(self.im)))
self.label4['image']= self.img
self.img = ImageTk.PhotoImage( Image.open(choice(self.im)))
self.label5['image']= self.img
self.img = ImageTk.PhotoImage( Image.open(choice(self.im)))
self.label6['image']= self.img
root = Tk()
app = Application(root)
root.mainloop()
Please help me with this, how can I arrange pictures in a table randomly.
I have to make a memory puzzle in a cours. I have a list with all pictures
in it. My problem is how can I arrange these pictures in a table randomly.
from tkinter import*
from random import choice
from PIL import ImageTk
from PIL import Image
class Application(Frame):
def __init__(self, master):
super (Application, self).__init__(master)
self.initUI()
def initUI(self):
self.columnconfigure(0, pad=3)
self.columnconfigure(1, pad=3)
self.columnconfigure(2, pad=3)
self.rowconfigure(0, pad=3)
self.rowconfigure(1, pad=3)
self.rowconfigure(2, pad=3)
self.im=["1.png","2.png","3.png","4.png", "5.png", "6.png", "7.png",
"8.png"]
self.label1 = Label(self)
self.label1.grid(row=0, column=0)
self.label2 = Label(self)
self.label2.grid(row=0, column=1)
self.label3 = Label(self)
self.label3.grid(row=1, column=0)
self.label4 = Label(self)
self.label4.grid(row=1, column=1)
self.label5 = Label(self)
self.label5.grid(row=2, column=0)
self.label6 = Label(self)
self.label6.grid(row=2, column=1)
for element in im:
self.img = ImageTk.PhotoImage( Image.open(choice(self.im)))
self.label1['image']= self.img
self.img = ImageTk.PhotoImage( Image.open(choice(self.im)))
self.label2['image']= self.img
self.img = ImageTk.PhotoImage( Image.open(choice(self.im)))
self.label3['image']= self.img
self.img = ImageTk.PhotoImage( Image.open(choice(self.im)))
self.label4['image']= self.img
self.img = ImageTk.PhotoImage( Image.open(choice(self.im)))
self.label5['image']= self.img
self.img = ImageTk.PhotoImage( Image.open(choice(self.im)))
self.label6['image']= self.img
root = Tk()
app = Application(root)
root.mainloop()
Please help me with this, how can I arrange pictures in a table randomly.
Is Compound Index on a collection is always better than having single Indexes
Is Compound Index on a collection is always better than having single Indexes
I have come across this particular line with respect to indexes in mongdb .
Each additional index on a collections does impose some overhead when
performing inserts or updates that involve changing index entries.
which means that with respect to my understanding , if there are more
number of indexes on a collection it will degrade performance during
insertion or Updation .
So is it always true that compound indexes are always better than single
indexes ??
For example if i have a collection named stocks
and a compound index is present on it as shown below
db.stocks.ensureIndex({"symbol":1,"date":1,"type": 1,"price":1},{"unique"
: false})
and the above is better than the individual indexes shown below .
db.stocks.ensureIndex({"symbol" : 1}, {"unique" : false})
db.stocks.ensureIndex({"date" : 1}, {"unique" : false})
db.stocks.ensureIndex({"type" : 1}, {"unique" : false})
db.stocks.ensureIndex({"price" : 1}, {"unique" : false})
Please let me know if i am correct or not ??
I have come across this particular line with respect to indexes in mongdb .
Each additional index on a collections does impose some overhead when
performing inserts or updates that involve changing index entries.
which means that with respect to my understanding , if there are more
number of indexes on a collection it will degrade performance during
insertion or Updation .
So is it always true that compound indexes are always better than single
indexes ??
For example if i have a collection named stocks
and a compound index is present on it as shown below
db.stocks.ensureIndex({"symbol":1,"date":1,"type": 1,"price":1},{"unique"
: false})
and the above is better than the individual indexes shown below .
db.stocks.ensureIndex({"symbol" : 1}, {"unique" : false})
db.stocks.ensureIndex({"date" : 1}, {"unique" : false})
db.stocks.ensureIndex({"type" : 1}, {"unique" : false})
db.stocks.ensureIndex({"price" : 1}, {"unique" : false})
Please let me know if i am correct or not ??
MVC 4 Telerik Upload in jQuery Dialog - removing file causes control to disappear
MVC 4 Telerik Upload in jQuery Dialog - removing file causes control to
disappear
As title states I have Telerik Upload control in jQuery Dialog. It works
fine in IE, but in Chrome/FF after uploading file and removing it (from
control, not HDD) whole control disappears. It's not even in DOM anymore.
To reproduce:
Put Upload control in jQuery dialog.
Open dialog and upload some file.
After file is uploaded remove it from Upload.
Watch whole Upload control disappear.
Here's my Upload code:
Html.Telerik().Upload()
.Localizable("pl-PL")
.Name("attachments")
.Multiple(true)
.ClientEvents(evetns =>
{
evetns.OnError("onError");
evetns.OnSuccess("onSuccess");
evetns.OnUpload("onUpload");
})
.Async(async => async
.Remove("UsunZalacznik", "Zalaczniki")
.Save("ZapiszZalaczniki", "Zalaczniki")
.AutoUpload(true))
And here's my remove action:
foreach (string fileName in fileNames)
{
SessionHelper.RemoveFromAttachments(name: fileName);
}
return Content("");
And code for RemoveFromAttachments:
var session = HttpContext.Current.Session["attachments"] as
List<UploadedFile>;
if (session != null && session.Count > 0)
{
if (id > 0) session.RemoveAll(x => x.Id == id);
else session.RemoveAll(x => x.Name == name);
HttpContext.Current.Session["attachments"] = session;
}
disappear
As title states I have Telerik Upload control in jQuery Dialog. It works
fine in IE, but in Chrome/FF after uploading file and removing it (from
control, not HDD) whole control disappears. It's not even in DOM anymore.
To reproduce:
Put Upload control in jQuery dialog.
Open dialog and upload some file.
After file is uploaded remove it from Upload.
Watch whole Upload control disappear.
Here's my Upload code:
Html.Telerik().Upload()
.Localizable("pl-PL")
.Name("attachments")
.Multiple(true)
.ClientEvents(evetns =>
{
evetns.OnError("onError");
evetns.OnSuccess("onSuccess");
evetns.OnUpload("onUpload");
})
.Async(async => async
.Remove("UsunZalacznik", "Zalaczniki")
.Save("ZapiszZalaczniki", "Zalaczniki")
.AutoUpload(true))
And here's my remove action:
foreach (string fileName in fileNames)
{
SessionHelper.RemoveFromAttachments(name: fileName);
}
return Content("");
And code for RemoveFromAttachments:
var session = HttpContext.Current.Session["attachments"] as
List<UploadedFile>;
if (session != null && session.Count > 0)
{
if (id > 0) session.RemoveAll(x => x.Id == id);
else session.RemoveAll(x => x.Name == name);
HttpContext.Current.Session["attachments"] = session;
}
How to rapidly create a dummy menu?
How to rapidly create a dummy menu?
I want to create a dummy menu with 1 or 2 level of depth. I know I can
create the menu via the administration module, but I want to know if there
is something I can use to generate fast a dummy menu.
I have a file with the sitemap indented by spaces that look as follow:
Home
Foo
Foo 1
Foo 2
Foo 3
Bar
Baz
Baz 1
Baz 2
Baz 2.1
Baz 2.3
Is there something to rapidly create the menu hierarchy into WordPress 3.6?
I want to create a dummy menu with 1 or 2 level of depth. I know I can
create the menu via the administration module, but I want to know if there
is something I can use to generate fast a dummy menu.
I have a file with the sitemap indented by spaces that look as follow:
Home
Foo
Foo 1
Foo 2
Foo 3
Bar
Baz
Baz 1
Baz 2
Baz 2.1
Baz 2.3
Is there something to rapidly create the menu hierarchy into WordPress 3.6?
What was the preferred method of holding things down in Apollo=?iso-8859-1?Q?=3F_=96_space.stackexchange.com?=
What was the preferred method of holding things down in Apollo? –
space.stackexchange.com
The Apollo space capsules had a ton of velocity changes - from liftoff, to
separations, to reentry to splashdown, there were a lot of sporadic
movements. The capsules also needed to carry things that …
space.stackexchange.com
The Apollo space capsules had a ton of velocity changes - from liftoff, to
separations, to reentry to splashdown, there were a lot of sporadic
movements. The capsules also needed to carry things that …
Sunday, 25 August 2013
type list box with increase /create buttons
type list box with increase /create buttons
i want to make list box as shown picture to increase /decrease this box
value. how to get this type of text box using jqueryui or css .please
suggest ,
i want to make list box as shown picture to increase /decrease this box
value. how to get this type of text box using jqueryui or css .please
suggest ,
[ Video & Online Games ] Open Question : GTA IV or GTA San Andreas?
[ Video & Online Games ] Open Question : GTA IV or GTA San Andreas?
im just wondering which game is better grand theft auto iv or grand theft
auto san andreas, not just based on graphics but the game as a whole
im just wondering which game is better grand theft auto iv or grand theft
auto san andreas, not just based on graphics but the game as a whole
[ Safety ] Open Question : Racial school bus issues?
[ Safety ] Open Question : Racial school bus issues?
I am the only white person on my school bus. The students, the two bus
aides, and the bus driver are all black. Now there is this one student who
is a racist, saying he hates "honkies" and various other races. I ask both
bus aides if they can move this person because I find it really offensive,
but they do nothing about it. Nobody tells this kid to stop. I feel like
they aren't doing their job to maintain safety. I don't use racial slurs
and I don't even like to talk during the bus ride. I sit there listening
to music, taking little naps. I need some help and advice.
I am the only white person on my school bus. The students, the two bus
aides, and the bus driver are all black. Now there is this one student who
is a racist, saying he hates "honkies" and various other races. I ask both
bus aides if they can move this person because I find it really offensive,
but they do nothing about it. Nobody tells this kid to stop. I feel like
they aren't doing their job to maintain safety. I don't use racial slurs
and I don't even like to talk during the bus ride. I sit there listening
to music, taking little naps. I need some help and advice.
dojo xhrGet is not working for me
dojo xhrGet is not working for me
I have written the following code to retrieve User details from my
Controller Action method.
dojo.xhrGet
({
url: "/UserManagement/GetUserDetailsFromLDAP/?userName=" + userName +
"&domain=" + domain,
load: function (data) {
alert("Data: " + data);
},
preventCache: true,
sync: true,
error: function (err) {
alert("Error=" + err);
}
});
My Controller Action method is so simple like below:
[HttpGet]
public ActionResult GetUserDetailsFromLDAP(string userName, string domain)
{
Dictionary<string, object> user =
QRProxyManager<IUsrMgmtSvc>.Execute(svc =>
svc.GetLDAPUserDetails(userName, domain));
return View("CreateUser", user);
}
I have debugged using Fiddler and I am getting the following error:
The model item passed into the dictionary is of type
'System.Collections.Generic.Dictionary`2[System.String,System.Object]',
but this dictionary requires a model item of type
'QR.NGLMS.ServicesRef.UserSvc.User'.
Can anybody please suggest what is the problem?
I have written the following code to retrieve User details from my
Controller Action method.
dojo.xhrGet
({
url: "/UserManagement/GetUserDetailsFromLDAP/?userName=" + userName +
"&domain=" + domain,
load: function (data) {
alert("Data: " + data);
},
preventCache: true,
sync: true,
error: function (err) {
alert("Error=" + err);
}
});
My Controller Action method is so simple like below:
[HttpGet]
public ActionResult GetUserDetailsFromLDAP(string userName, string domain)
{
Dictionary<string, object> user =
QRProxyManager<IUsrMgmtSvc>.Execute(svc =>
svc.GetLDAPUserDetails(userName, domain));
return View("CreateUser", user);
}
I have debugged using Fiddler and I am getting the following error:
The model item passed into the dictionary is of type
'System.Collections.Generic.Dictionary`2[System.String,System.Object]',
but this dictionary requires a model item of type
'QR.NGLMS.ServicesRef.UserSvc.User'.
Can anybody please suggest what is the problem?
Saturday, 24 August 2013
How to adjust contrast?
How to adjust contrast?
Does anyone know how to adjust the contrast on the Ubuntu Operating
system? I have an HP Pavilion G6 Laptop, any help would be great!
Does anyone know how to adjust the contrast on the Ubuntu Operating
system? I have an HP Pavilion G6 Laptop, any help would be great!
Timer not running, Cannot see why not - C++
Timer not running, Cannot see why not - C++
I am trying to make a count down timer, for some reason it seems to not be
executing the (Hour >= 1) while statement properly -- if i comment out
--Hour and the Minute = Minute +60 the program runs fine counting down
from 60 and then decrementing a minute and re starting at 60 seconds each
time ... can someone explain to me why the hour decrement doesnt want to
work ?? im new to c++ and programming in general so if you could keep it
as simple as is possible thanks. Code snippet below:
while (Hour >= 1)
{
while (Minute >= 1)
{
while (Second >= 1)
{
Sleep(1000);
--Second;
cout << Hour << " hours, " << Minute << " minutes, " << Second
<< " seconds;\n";
}
Second = Second + 60;
--Minute;
}
Minute = Minute + 60;
--Hour;
}
I am trying to make a count down timer, for some reason it seems to not be
executing the (Hour >= 1) while statement properly -- if i comment out
--Hour and the Minute = Minute +60 the program runs fine counting down
from 60 and then decrementing a minute and re starting at 60 seconds each
time ... can someone explain to me why the hour decrement doesnt want to
work ?? im new to c++ and programming in general so if you could keep it
as simple as is possible thanks. Code snippet below:
while (Hour >= 1)
{
while (Minute >= 1)
{
while (Second >= 1)
{
Sleep(1000);
--Second;
cout << Hour << " hours, " << Minute << " minutes, " << Second
<< " seconds;\n";
}
Second = Second + 60;
--Minute;
}
Minute = Minute + 60;
--Hour;
}
php code isn't executing properly
php code isn't executing properly
I have just written the following code to generate navigational menus, but
it is not executing properly. Can anybody please pinpoint the error? Thank
you.
<?php
$pages = array(
'0' => array('title' => 'Health', 'url' => 'health.php'),
'1' => array('title' => 'Weightl Loss', 'url' => 'weightloss.php'),
'2' => array('title' => 'Fitness', 'url' => 'fitness.php'),
'3' => array('title' => 'Sex', 'url' => 'sex.php'),
'4' => array('title' => 'Mind-Body', 'url' => 'mindbody.php'),
'5' => array('title' => 'Food', 'url' => 'food.php'),
'6' => array('title' => 'Beauty', 'url' => 'beauty.php'),
'7' => array('title' => 'More', 'url' => 'more.php')
);
echo "<div id=\"nav-menu\" style=\"width:65px;\">\n";
// let's create a unordered list to display the items
echo "<ul>";
echo "<li>\n";
// here's where all the items get printed
foreach ($pages as $Listing) {
echo "<a href='".[$Listing]["url"]."'>".[$Listing]["title"]."</a>\n";
}
echo "</li>\n";
// closing the unordered list
echo "</ul>";
echo "</div>\n";
?>
I have just written the following code to generate navigational menus, but
it is not executing properly. Can anybody please pinpoint the error? Thank
you.
<?php
$pages = array(
'0' => array('title' => 'Health', 'url' => 'health.php'),
'1' => array('title' => 'Weightl Loss', 'url' => 'weightloss.php'),
'2' => array('title' => 'Fitness', 'url' => 'fitness.php'),
'3' => array('title' => 'Sex', 'url' => 'sex.php'),
'4' => array('title' => 'Mind-Body', 'url' => 'mindbody.php'),
'5' => array('title' => 'Food', 'url' => 'food.php'),
'6' => array('title' => 'Beauty', 'url' => 'beauty.php'),
'7' => array('title' => 'More', 'url' => 'more.php')
);
echo "<div id=\"nav-menu\" style=\"width:65px;\">\n";
// let's create a unordered list to display the items
echo "<ul>";
echo "<li>\n";
// here's where all the items get printed
foreach ($pages as $Listing) {
echo "<a href='".[$Listing]["url"]."'>".[$Listing]["title"]."</a>\n";
}
echo "</li>\n";
// closing the unordered list
echo "</ul>";
echo "</div>\n";
?>
Possessive pronoun drops in fiction
Possessive pronoun drops in fiction
Assuming the reader knows who is being referred to, what do you think is
the effect on the reader when possessive pronouns are dropped in fiction.
For example: Brown hair is pulled back into a tight bun, giving cheeks a
stretched look.
Seems to me (note the subject pronoun drop), the result is that the reader
focuses more on the narrator than the character being discussed. All
reactions will be appreciated.
Assuming the reader knows who is being referred to, what do you think is
the effect on the reader when possessive pronouns are dropped in fiction.
For example: Brown hair is pulled back into a tight bun, giving cheeks a
stretched look.
Seems to me (note the subject pronoun drop), the result is that the reader
focuses more on the narrator than the character being discussed. All
reactions will be appreciated.
ANSI C Function to Update Database
ANSI C Function to Update Database
I'm using a ANSI C snippet that successfully connects to a MySQL database
and executes a query. As i can successfully call to a function in my
program that sends any query I want to the database, then I have some
pretty powerful options available to me.
One option I want to use is the ability to INSERT INTO one variable to a
selected table in one or more columns. That way I can use a simple
function to pass data to my database as opposed to duplicating the code
for every variable I want to store. I.e.: I want to reduce the amount of
work and time by creating a function where I can easy update my database.
My program is actually a game. It stores it's data in flat files. I'm
making a big switch where I will now store my data in a local database.
There are a lot of stats for players that are normally stored in a flat
file. Things like Name, Sex, Class, Race, Level and etc.
Example of how the old way writes this player data.
fprintf (fp, "Name %s~\n", player->name);
With a new function, I want to effectively pass 'player->name' to my query
that in result, stores to the database. As relational databases store data
in various tables and columns. I need to also have options to set a
destination table and destination column.
One solution I had was with concatenation. At least that's how it seems to
be done in PHP. This is where you concatenate SQL query with variables.
But unfortunately, I don't know how to effectively concatenate strings
together where I can pass "player->name" into my query of:
INSERT INTO test_table VALUES ('', '');
That said, here is my MySQL snippet that does work magically:
#include <mysql.h>
#include <stdio.h>
void db_update(const char * query)
{
MYSQL *conn;
MYSQL_RES *res;
MYSQL_ROW row;
char *server = "localhost";
char *user = "root";
char *password = "PASSWORD"; /* set me first */
char *database = "DATABASE";
conn = mysql_init(NULL);
/* Connect to database */
if (!mysql_real_connect(conn, server,
user, password, database, 0, NULL, 0)) {
fprintf(stderr, "%s\n", mysql_error(conn));
return;
}
/* send SQL query */
if (mysql_query(conn, query)) {
fprintf(stderr, "%s\n", mysql_error(conn));
return;
}
/* close connection */
mysql_free_result(res);
mysql_close(conn);
}
Compiling
mysql: MySQL client programs and shared library mysqlclient: Backlevel
MySQL shared libraries (old libs) mysql-devel: Files for development of
MySQL applications (a must have) mysql-server: Mysql server itself gcc,
make and other development libs: GNU C compiler
Pass --libs option - Libraries and options required to link with the MySQL
client library.
mysql_config --libs
mysql_config --cflags
Example: gcc -o output-file $(mysql_config --cflags) database.c
$(mysql_config --libs)
Final Note
This may be a bit too complex for Stackoverflow, but any leads to how I
can make this happen would be great. I want to learn as much as I can.
I'm using a ANSI C snippet that successfully connects to a MySQL database
and executes a query. As i can successfully call to a function in my
program that sends any query I want to the database, then I have some
pretty powerful options available to me.
One option I want to use is the ability to INSERT INTO one variable to a
selected table in one or more columns. That way I can use a simple
function to pass data to my database as opposed to duplicating the code
for every variable I want to store. I.e.: I want to reduce the amount of
work and time by creating a function where I can easy update my database.
My program is actually a game. It stores it's data in flat files. I'm
making a big switch where I will now store my data in a local database.
There are a lot of stats for players that are normally stored in a flat
file. Things like Name, Sex, Class, Race, Level and etc.
Example of how the old way writes this player data.
fprintf (fp, "Name %s~\n", player->name);
With a new function, I want to effectively pass 'player->name' to my query
that in result, stores to the database. As relational databases store data
in various tables and columns. I need to also have options to set a
destination table and destination column.
One solution I had was with concatenation. At least that's how it seems to
be done in PHP. This is where you concatenate SQL query with variables.
But unfortunately, I don't know how to effectively concatenate strings
together where I can pass "player->name" into my query of:
INSERT INTO test_table VALUES ('', '');
That said, here is my MySQL snippet that does work magically:
#include <mysql.h>
#include <stdio.h>
void db_update(const char * query)
{
MYSQL *conn;
MYSQL_RES *res;
MYSQL_ROW row;
char *server = "localhost";
char *user = "root";
char *password = "PASSWORD"; /* set me first */
char *database = "DATABASE";
conn = mysql_init(NULL);
/* Connect to database */
if (!mysql_real_connect(conn, server,
user, password, database, 0, NULL, 0)) {
fprintf(stderr, "%s\n", mysql_error(conn));
return;
}
/* send SQL query */
if (mysql_query(conn, query)) {
fprintf(stderr, "%s\n", mysql_error(conn));
return;
}
/* close connection */
mysql_free_result(res);
mysql_close(conn);
}
Compiling
mysql: MySQL client programs and shared library mysqlclient: Backlevel
MySQL shared libraries (old libs) mysql-devel: Files for development of
MySQL applications (a must have) mysql-server: Mysql server itself gcc,
make and other development libs: GNU C compiler
Pass --libs option - Libraries and options required to link with the MySQL
client library.
mysql_config --libs
mysql_config --cflags
Example: gcc -o output-file $(mysql_config --cflags) database.c
$(mysql_config --libs)
Final Note
This may be a bit too complex for Stackoverflow, but any leads to how I
can make this happen would be great. I want to learn as much as I can.
Android improve SQL processing speed
Android improve SQL processing speed
I'm processing 31000 Insert SQL statements reading from a file and it
takes more than 2 minutes to complete.. need some advice in improving
performance..
Here is the code:
while((line=reader.readLine())!=null){
dbs.execSQL(line);
k=(int)(i*0.0032);
if(k%10==0){fdb.publishProgress(k);}
i++;
}
I'm processing 31000 Insert SQL statements reading from a file and it
takes more than 2 minutes to complete.. need some advice in improving
performance..
Here is the code:
while((line=reader.readLine())!=null){
dbs.execSQL(line);
k=(int)(i*0.0032);
if(k%10==0){fdb.publishProgress(k);}
i++;
}
svnserve startup no longer works as documented
svnserve startup no longer works as documented
The documented methods of starting svnserve no longer work in Ubuntu 12.04
LTS.
Ref: https://help.ubuntu.com/community/Subversion
"inetd" scripts are obsolete. "xinetd" scripts are now nonstandard.
The suggested third-party upstart script at
http://pelam.fi/published_sources/svnserve.conf
looks bogus. It has the line
exec /usr/bin/svnserve --foreground --daemon --config-file
/etc/svnserve.conf --root /home/svn/
which uses an option "--config-file" not in the svnserve documentation,
runs in the foreground (inappropriate for a daemon), and appears to run as
root. Upstart runs everything as root by default. "A future release of
Upstart will have native support for (not running as root)".
This should have been handled during Ubuntu packaging.
How do I work around this mess?
The documented methods of starting svnserve no longer work in Ubuntu 12.04
LTS.
Ref: https://help.ubuntu.com/community/Subversion
"inetd" scripts are obsolete. "xinetd" scripts are now nonstandard.
The suggested third-party upstart script at
http://pelam.fi/published_sources/svnserve.conf
looks bogus. It has the line
exec /usr/bin/svnserve --foreground --daemon --config-file
/etc/svnserve.conf --root /home/svn/
which uses an option "--config-file" not in the svnserve documentation,
runs in the foreground (inappropriate for a daemon), and appears to run as
root. Upstart runs everything as root by default. "A future release of
Upstart will have native support for (not running as root)".
This should have been handled during Ubuntu packaging.
How do I work around this mess?
Friday, 23 August 2013
UTF8 Find Replace Tool?
UTF8 Find Replace Tool?
Forum Members, I am coding in XML and using a validator / parser that
chokes when it encounters a UTF8 related text hiding within my text. I am
using NotePad++ in ANSI mode, and when I switch it to UTF8 mode it shows
me where these UTF8 errors exist. Once I manually delete the unwanted UTF8
text character my validator/parser works perfectly.
NotePad++ is not able to find and replace UTF8 characters within an XML
file. My question to anyone out there. Does a NotePad++ plugin exist that
will let me globally search the file for unwanted UTF8 text and replace it
with NOTHING? Also, can a RegEx find and replace unwanted UTF8 text? Is
there a text editor out there that is capable of hunting down unwanted
UTF8 text?
In addition, can anyone out there educate me about UTF8 text and why do
they prevent an XML validator from working correctly? I spent several
hours trying to figure out why my XML code was not successfully parsing
and it would of been a lot easier if I would have had the ability to hunt
down unwanted UTF8 characters. Any help will be greatly appreciated.
Thanks in advance.
Forum Members, I am coding in XML and using a validator / parser that
chokes when it encounters a UTF8 related text hiding within my text. I am
using NotePad++ in ANSI mode, and when I switch it to UTF8 mode it shows
me where these UTF8 errors exist. Once I manually delete the unwanted UTF8
text character my validator/parser works perfectly.
NotePad++ is not able to find and replace UTF8 characters within an XML
file. My question to anyone out there. Does a NotePad++ plugin exist that
will let me globally search the file for unwanted UTF8 text and replace it
with NOTHING? Also, can a RegEx find and replace unwanted UTF8 text? Is
there a text editor out there that is capable of hunting down unwanted
UTF8 text?
In addition, can anyone out there educate me about UTF8 text and why do
they prevent an XML validator from working correctly? I spent several
hours trying to figure out why my XML code was not successfully parsing
and it would of been a lot easier if I would have had the ability to hunt
down unwanted UTF8 characters. Any help will be greatly appreciated.
Thanks in advance.
Guard-Uglify throws "only generation of JSON objects or arrays allowed"
Guard-Uglify throws "only generation of JSON objects or arrays allowed"
I'm trying to uglify javascript using guard but i get following errors:
ERROR - Guard::Uglify failed to achieve its , exception was: [#]
JSON::GeneratorError: only generation of JSON objects or arrays allowed
[#] C:/Ruby193/lib/ruby/1.9.1/json/common.rb:216:in generate' [#]
C:/Ruby193/lib/ruby/1.9.1/json/common.rb:216:ingenerate' [#]
C:/Ruby193/lib/ruby/1.9.1/json/common.rb:352:in dump' [#]
C:/Ruby193/lib/ruby/gems/1.9.1/gems/execjs-2.0.0/lib/execjs/external_runtime.rb:53:inblock
(2 levels) in compile' [#]
C:/Ruby193/lib/ruby/gems/1.9.1/gems/execjs-2.0.0/lib/execjs/external_runtime.rb:51:in
sub!' [#]
C:/Ruby193/lib/ruby/gems/1.9.1/gems/execjs-2.0.0/lib/execjs/external_runtime.rb:51:inblock
in compile' [#]
C:/Ruby193/lib/ruby/gems/1.9.1/gems/execjs-2.0.0/lib/execjs/external_runtime.rb:47:in
tap' [#]
C:/Ruby193/lib/ruby/gems/1.9.1/gems/execjs-2.0.0/lib/execjs/external_runtime.rb:47:incompile'
I'm using json 2.0.0(also tried with 1.8.0) and mutli-json 1.7.8(also
tried 1.7.9)
I'm trying to uglify javascript using guard but i get following errors:
ERROR - Guard::Uglify failed to achieve its , exception was: [#]
JSON::GeneratorError: only generation of JSON objects or arrays allowed
[#] C:/Ruby193/lib/ruby/1.9.1/json/common.rb:216:in generate' [#]
C:/Ruby193/lib/ruby/1.9.1/json/common.rb:216:ingenerate' [#]
C:/Ruby193/lib/ruby/1.9.1/json/common.rb:352:in dump' [#]
C:/Ruby193/lib/ruby/gems/1.9.1/gems/execjs-2.0.0/lib/execjs/external_runtime.rb:53:inblock
(2 levels) in compile' [#]
C:/Ruby193/lib/ruby/gems/1.9.1/gems/execjs-2.0.0/lib/execjs/external_runtime.rb:51:in
sub!' [#]
C:/Ruby193/lib/ruby/gems/1.9.1/gems/execjs-2.0.0/lib/execjs/external_runtime.rb:51:inblock
in compile' [#]
C:/Ruby193/lib/ruby/gems/1.9.1/gems/execjs-2.0.0/lib/execjs/external_runtime.rb:47:in
tap' [#]
C:/Ruby193/lib/ruby/gems/1.9.1/gems/execjs-2.0.0/lib/execjs/external_runtime.rb:47:incompile'
I'm using json 2.0.0(also tried with 1.8.0) and mutli-json 1.7.8(also
tried 1.7.9)
Is hashMap implemented as an array of linked lists
Is hashMap implemented as an array of linked lists
While reading about HashMap i see that it is implemented as an array of
buckets? Now are these buckets always linked lists? If so, why are they
called buckets and not linked lists?
While reading about HashMap i see that it is implemented as an array of
buckets? Now are these buckets always linked lists? If so, why are they
called buckets and not linked lists?
How is Delphi going on the market? Is it worth yet to make a project in Delphi? [on hold]
How is Delphi going on the market? Is it worth yet to make a project in
Delphi? [on hold]
I use Delphi since 1999 because it is visual, fast, helpful and committed
to good programming roles.
That's what I tell my friends in the university and interviewer when I
apply for a job in any software house. But I am very criticized for using
Delphi and for Windows development. It is prejudice IMHO.
They say I should use open source technologies and develop in Java, Ruby,
Python and other "new" technologies, and I should only develop for the Web
and cross-platform.
I tell them I do code in Java and PHP when necessary but I dislike script
and byte-code languages, but I would not matter if suddenly Embarcadero
did a Delphi version with Java, what matters is the IDE and the concepts
(RAD Studio still has .NET and C++). I "teach" them that those languages
are almost old as Pascal. I tell them that Delphi is so powerful that I
can do almost anything with it (with special respect for VCL) and that is
becoming a very good cross-platform software compiler, with options to
OS-X and iOS.
I think at creating a LT about Delphi to present it to people, because
after discussion they leave not convinced. And after that I always stop
later and think what if I am really wrong about it. But then I open
StackOverflow I see all these splendid professional who works with Delphi
and knows so much and I think back how can I be wrong!?
I my region clients do not care much how the software is made as long as
it works and is cheap.
So, I am wrong or not?**
So, how about Delphi acceptance in your country's market?
Is there still a place for Delphi specialized professionals, or everybody
just want C# and dotNET when it comes to Windows?
Is it worth doing a project in Delphi and some year from now have to make
a version for the web (which will take longer to be finished considering
my skills)?
Please, if you do not feel comfort on this question because there might be
opinion based answers, just focus on item 2, which can be based on
generally statistic data.
I am my own Boss and I am starting a big project. I have to make a
decision if I will go Delphi or Web. Considering that I can finish the
project much faster with Delphi (experience and facilities), it's very
important to know if I am choosing right.
I have to consider that I have years of written code that I made and reuse.
Delphi? [on hold]
I use Delphi since 1999 because it is visual, fast, helpful and committed
to good programming roles.
That's what I tell my friends in the university and interviewer when I
apply for a job in any software house. But I am very criticized for using
Delphi and for Windows development. It is prejudice IMHO.
They say I should use open source technologies and develop in Java, Ruby,
Python and other "new" technologies, and I should only develop for the Web
and cross-platform.
I tell them I do code in Java and PHP when necessary but I dislike script
and byte-code languages, but I would not matter if suddenly Embarcadero
did a Delphi version with Java, what matters is the IDE and the concepts
(RAD Studio still has .NET and C++). I "teach" them that those languages
are almost old as Pascal. I tell them that Delphi is so powerful that I
can do almost anything with it (with special respect for VCL) and that is
becoming a very good cross-platform software compiler, with options to
OS-X and iOS.
I think at creating a LT about Delphi to present it to people, because
after discussion they leave not convinced. And after that I always stop
later and think what if I am really wrong about it. But then I open
StackOverflow I see all these splendid professional who works with Delphi
and knows so much and I think back how can I be wrong!?
I my region clients do not care much how the software is made as long as
it works and is cheap.
So, I am wrong or not?**
So, how about Delphi acceptance in your country's market?
Is there still a place for Delphi specialized professionals, or everybody
just want C# and dotNET when it comes to Windows?
Is it worth doing a project in Delphi and some year from now have to make
a version for the web (which will take longer to be finished considering
my skills)?
Please, if you do not feel comfort on this question because there might be
opinion based answers, just focus on item 2, which can be based on
generally statistic data.
I am my own Boss and I am starting a big project. I have to make a
decision if I will go Delphi or Web. Considering that I can finish the
project much faster with Delphi (experience and facilities), it's very
important to know if I am choosing right.
I have to consider that I have years of written code that I made and reuse.
checking if gridview is empty using c#
checking if gridview is empty using c#
Currently i have the following:
if (dataGridView1.Rows.Count == 0)
{
MessageBox.Show("EMPTY");
}
else
{
using (var soundPlayer = new SoundPlayer(@"c:\Windows\Media\chimes.wav"))
{
soundPlayer.Play(); // can also use soundPlayer.PlaySync()
}
}
My grid view looks like this:
But it seems to go to the else statement and make the sound. I need it to
NOT make a sound if there is no data in the rows of the gridview.
Currently i have the following:
if (dataGridView1.Rows.Count == 0)
{
MessageBox.Show("EMPTY");
}
else
{
using (var soundPlayer = new SoundPlayer(@"c:\Windows\Media\chimes.wav"))
{
soundPlayer.Play(); // can also use soundPlayer.PlaySync()
}
}
My grid view looks like this:
But it seems to go to the else statement and make the sound. I need it to
NOT make a sound if there is no data in the rows of the gridview.
Thursday, 22 August 2013
angularjs ng-model fails with variable name binding when value does not exists with plnkr
angularjs ng-model fails with variable name binding when value does not
exists with plnkr
I have to create a form in which meta data is coming from server . So I
can not use hard code variable binding. Say I have a column definition
studentcol that has an expression and display name.
$scope.studentcol = {expression:"studentid","display":"name"} $scope.data
= {};
If I use . It get failed. It will work properly either I use hard code
expression say data.studentid.display or value for studentid already
exists in data then above binding works well
http://plnkr.co/edit/YBt37TuILz1KsPOUAo9q?p=preview
Please suggest
Rohit Bansal
exists with plnkr
I have to create a form in which meta data is coming from server . So I
can not use hard code variable binding. Say I have a column definition
studentcol that has an expression and display name.
$scope.studentcol = {expression:"studentid","display":"name"} $scope.data
= {};
If I use . It get failed. It will work properly either I use hard code
expression say data.studentid.display or value for studentid already
exists in data then above binding works well
http://plnkr.co/edit/YBt37TuILz1KsPOUAo9q?p=preview
Please suggest
Rohit Bansal
Trouble updating iPhone 3GS
Trouble updating iPhone 3GS
I have a jailbroken iPhone 3gs which runs iOS 4.1 (8B117). Predictably, I
can't download most of the apps and so often, I feel like it's not even an
smartphone. So I need to update it anyhow.
But everytime I try, I either receive Error 3194 or 3004. I've tried
numerous things suggested across various forums like removing the
gs.apple.com entry in the hosts file, putting it back, using TinyUmbrella
to do the same thing but all in vain. I have the latest iTunes version
installed (v.11). I've tried updating by just hitting Update/Restore, by
manually downloading the firmware and then doing Shift + Restore. I tried
by building a custom firmware from sn0wbreeze. I've even tried from
another computer. I've tried updating to multiple versions (5 and 6). But
nothing worked. I always receive either error 3194 or 3004.
I really need to update this. I'd be really really grateful for any kind
of help.
Thank you very much!
I have a jailbroken iPhone 3gs which runs iOS 4.1 (8B117). Predictably, I
can't download most of the apps and so often, I feel like it's not even an
smartphone. So I need to update it anyhow.
But everytime I try, I either receive Error 3194 or 3004. I've tried
numerous things suggested across various forums like removing the
gs.apple.com entry in the hosts file, putting it back, using TinyUmbrella
to do the same thing but all in vain. I have the latest iTunes version
installed (v.11). I've tried updating by just hitting Update/Restore, by
manually downloading the firmware and then doing Shift + Restore. I tried
by building a custom firmware from sn0wbreeze. I've even tried from
another computer. I've tried updating to multiple versions (5 and 6). But
nothing worked. I always receive either error 3194 or 3004.
I really need to update this. I'd be really really grateful for any kind
of help.
Thank you very much!
Silent Hill 3 Puzzle Unsolvable
Silent Hill 3 Puzzle Unsolvable
I'm currently playing Silent Hill 3 on PS2 in normal difficulty and get
stuck in a puzzle. The level is Dark Shopping Mall. I have to get rid of
some flying bugs with poisonous chloride gas, which I have to mix with
bleach and detergent. The problem is I didn't take the bleach in the
women' bathroom early on and now I cannot return there. It is the room
with the ladder from ceiling where the door won't open.
I'm currently playing Silent Hill 3 on PS2 in normal difficulty and get
stuck in a puzzle. The level is Dark Shopping Mall. I have to get rid of
some flying bugs with poisonous chloride gas, which I have to mix with
bleach and detergent. The problem is I didn't take the bleach in the
women' bathroom early on and now I cannot return there. It is the room
with the ladder from ceiling where the door won't open.
Unable to update mysql table using PHP script
Unable to update mysql table using PHP script
I have two pages in php,
php_mysql_multiple_edit2.php //the form
php_mysql_multiple_edit.php //the script containing mysql update command
The script ran perfectly fine and updated the table when there were few
entries in the database during testing, but does not update when I added
the actual table.
I am getting the following error "Notice: Undefined index: hdnLine in
/var/www/ELP/php_mysql_multiple_edit.php on line 6 Notice: Undefined
index: hdnLine in /var/www/ELP/php_mysql_multiple_edit.php on line 25 Save
completed."
The code for the two are are: php_mysql_multiple_edit2.php
`<html>
<head>
<title>Employee Leave Portal</title>
</head>
<body>
<p style="text-align: center">
<a href="index.html">Home</a>
</p>
<?
$objConnect = mysql_connect("localhost","root","root") or die(mysql_error());
$objDB = mysql_select_db("test");
$i=(int)0;
$strSQL = "SELECT * FROM leave_db ORDER BY firstname ASC";
$objQuery = mysql_query($strSQL) or die ("Error Query [".$strSQL."]");
?>
<form name="frmMain" method="post" action="php_mysql_multiple_edit.php">
<table align="center" width="600" border="1">
<tr>
<th bgcolor="#3366CC" width="91"> <div align="center">Employee_id
</div></th>
<th bgcolor="#3366CC" width="98"> <div align="center">firstname
</div></th>
<th bgcolor="#3366CC" width="198"> <div align="center">lastname
</div></th>
<th bgcolor="#3366CC" width="50"> <div align="center">C1 </div></th>
<th bgcolor="#3366CC" width="50"> <div align="center">C2 </div></th>
<th bgcolor="#3366CC" width="50"> <div align="center">C3 </div></th>
<th bgcolor="#3366CC" width="50"> <div align="center">Ct </div></th>
<th bgcolor="#3366CC" width="50"> <div align="center">P1 </div></th>
<th bgcolor="#3366CC" width="50"> <div align="center">P2 </div></th>
<th bgcolor="#3366CC" width="50"> <div align="center">P3 </div></th>
<th bgcolor="#3366CC" width="50"> <div align="center">Pt </div></th>
<th bgcolor="#3366CC" width="50"> <div align="center">M1 </div></th>
<th bgcolor="#3366CC" width="50"> <div align="center">M2 </div></th>
<th bgcolor="#3366CC" width="50"> <div align="center">M3 </div></th>
<th bgcolor="#3366CC" width="50"> <div align="center">Mt </div></th>
<th bgcolor="#3366CC" width="50"> <div align="center">Tt </div></th>
</tr>
<?
$i =0;
while($objResult = mysql_fetch_array($objQuery))
{
$i = $i + 1;
?>
<tr>
<td bgcolor="#3366CC"><div align="center">
<input type="hidden" name="employee_id<?=$i;?>" size="5"
value="<?=$objResult["employee_id"];?>">
<input type="text" name="employee_id<?=$i;?>" size="5"
value="<?=$objResult["employee_id"];?>">
</div></td>
<td bgcolor="#3366CC"><input type="text" name="firstname<?=$i;?>"
size="10" value="<?=$objResult["firstname"];?> "></td>
<td bgcolor="#3366CC"><input type="text" name="lastname<?=$i;?>"
size="10" value="<?=$objResult["lastname"];?> "></td>
<td bgcolor="#3366CC"><div align="center"><input type="number"
name="C1<?=$i;?>" size="2" value="<?=$objResult["C1"];?>"></div></td>
<td bgcolor="#3366CC"><div align="center"><input type="number"
name="C2<?=$i;?>" size="2" value="<?=$objResult["C2"];?>"></div></td>
<td bgcolor="#3366CC"><div align="center"><input type="number"
name="C3<?=$i;?>" size="2" value="<?=$objResult["C3"];?>"></div></td>
<td bgcolor="#B2C2F0" width="50"> <div
align="center"><?=$objResult["Ct"];?></div></td>
<td bgcolor="#3366CC"><div align="center"><input type="number"
name="P1<?=$i;?>" size="2" value="<?=$objResult["P1"];?>"></div></td>
<td bgcolor="#3366CC"><div align="center"><input type="number"
name="P2<?=$i;?>" size="2" value="<?=$objResult["P2"];?>"></div></td>
<td bgcolor="#3366CC"><div align="center"><input type="number"
name="P3<?=$i;?>" size="2" value="<?=$objResult["P3"];?>"></div></td>
<td bgcolor="#B2C2F0" width="50"> <div
align="center"><?=$objResult["Pt"];?></div></td>
<td bgcolor="#3366CC"><div align="center"><input type="number"
name="M1<?=$i;?>" size="2" value="<?=$objResult["M1"];?>"></div></td>
<td bgcolor="#3366CC"><div align="center"><input type="number"
name="M2<?=$i;?>" size="2" value="<?=$objResult["M2"];?>"></div></td>
<td bgcolor="#3366CC"><div align="center"><input type="number"
name="M3<?=$i;?>" size="2" value="<?=$objResult["M3"];?>"></div></td>
<td bgcolor="#B2C2F0" width="50"> <div
align="center"><?=$objResult["Mt"];?></div></td>
<td bgcolor="#00FFFF" width="50"> <div
align="center"><?=$objResult["Tt"];?></div></td>
</tr>
<?
}
?>
</table>
<input type="submit" name="submit" value="submit">
<input type="hidden" name="hdnLine" value="<?=(int)$i;?>">
</form>
<?
mysql_close($objConnect);
?>
</body>
</html>`
The code for php_mysql_multiple_edit.php is
<?php
$objConnect = mysql_connect("localhost","root","root") or die(mysql_error());
$objDB = mysql_select_db("test");
$i = (int)0;
//*** Update Condition ***//
for($i=1;$i<=$_POST["hdnLine"];$i++)
{
$strSQL = "UPDATE leave_db SET ";
$strSQL .="employee_id = '".$_POST["employee_id$i"]."' ";
$strSQL .=",firstname = '".$_POST["firstname$i"]."' ";
$strSQL .=",lastname = '".$_POST["lastname$i"]."' ";
$strSQL .=",C1 = '".$_POST["C1$i"]."' ";
$strSQL .=",C2 = '".$_POST["C2$i"]."' ";
$strSQL .=",C3 = '".$_POST["C3$i"]."' ";
$strSQL .=",P1 = '".$_POST["P1$i"]."' ";
$strSQL .=",P2 = '".$_POST["P2$i"]."' ";
$strSQL .=",P3 = '".$_POST["P3$i"]."' ";
$strSQL .=",M1 = '".$_POST["M1$i"]."' ";
$strSQL .=",M2 = '".$_POST["M2$i"]."' ";
$strSQL .=",M3 = '".$_POST["M3$i"]."' ";
$strSQL .="WHERE employee_id = '".$_POST["employee_id$i"]."' ";
$objQuery = mysql_query($strSQL);
}
for($i=1;$i<=$_POST["hdnLine"];$i++)
{
$SUMC1="select (C1+C2-C3) as 'SUMC2' from leave_db where
employee_id='".$_POST["employee_id$i"]."'";
$queryC1=mysql_query($SUMC1);
$rowC1=mysql_fetch_array($queryC1);
$final_sumC=$rowC1['SUMC2'];
$update_queryC=" update leave_db set Ct=$final_sumC where
employee_id='".$_POST["employee_id$i"]."'";
$objQueryC = mysql_query($update_queryC);
$SUMP1="select (P1+P2-P3) as 'SUMP2' from leave_db where
employee_id='".$_POST["employee_id$i"]."'";
$queryP1=mysql_query($SUMP1);
$rowP1=mysql_fetch_array($queryP1);
$final_sumP=$rowP1['SUMP2'];
$update_queryP=" update leave_db set Pt=$final_sumP where
employee_id='".$_POST["employee_id$i"]."'";
$objQueryP = mysql_query($update_queryP);
$SUMM1="select (M1+M2-M3) as 'SUMM2' from leave_db where
employee_id='".$_POST["employee_id$i"]."'";
$queryM1=mysql_query($SUMM1);
$rowM1=mysql_fetch_array($queryM1);
$final_sumM=$rowM1['SUMM2'];
$update_queryM=" update leave_db set Mt=$final_sumM where
employee_id='".$_POST["employee_id$i"]."'";
$objQueryM = mysql_query($update_queryM);
$SUMT1="select (Ct+Pt+Mt) as 'SUMT2' from leave_db where
employee_id='".$_POST["employee_id$i"]."'";
$queryT1=mysql_query($SUMT1);
$rowT1=mysql_fetch_array($queryT1);
$final_sumT=$rowT1['SUMT2'];
$update_queryT=" update leave_db set Tt=$final_sumT where
employee_id='".$_POST["employee_id$i"]."'";
$objQueryT = mysql_query($update_queryT);
}
//header("location:$_SERVER[PHP_SELF]");
//exit();
$strSQL2 = "SELECT * FROM leave_db ORDER BY firstname ASC";
$objQuery2 = mysql_query($strSQL2) or die ("Error Query [".$strSQL2."]");
echo "Save completed. Click <a
href='php_mysql_multiple_edit2.php'>here</a> to view.";
mysql_close($objConnect);
?>`
I have two pages in php,
php_mysql_multiple_edit2.php //the form
php_mysql_multiple_edit.php //the script containing mysql update command
The script ran perfectly fine and updated the table when there were few
entries in the database during testing, but does not update when I added
the actual table.
I am getting the following error "Notice: Undefined index: hdnLine in
/var/www/ELP/php_mysql_multiple_edit.php on line 6 Notice: Undefined
index: hdnLine in /var/www/ELP/php_mysql_multiple_edit.php on line 25 Save
completed."
The code for the two are are: php_mysql_multiple_edit2.php
`<html>
<head>
<title>Employee Leave Portal</title>
</head>
<body>
<p style="text-align: center">
<a href="index.html">Home</a>
</p>
<?
$objConnect = mysql_connect("localhost","root","root") or die(mysql_error());
$objDB = mysql_select_db("test");
$i=(int)0;
$strSQL = "SELECT * FROM leave_db ORDER BY firstname ASC";
$objQuery = mysql_query($strSQL) or die ("Error Query [".$strSQL."]");
?>
<form name="frmMain" method="post" action="php_mysql_multiple_edit.php">
<table align="center" width="600" border="1">
<tr>
<th bgcolor="#3366CC" width="91"> <div align="center">Employee_id
</div></th>
<th bgcolor="#3366CC" width="98"> <div align="center">firstname
</div></th>
<th bgcolor="#3366CC" width="198"> <div align="center">lastname
</div></th>
<th bgcolor="#3366CC" width="50"> <div align="center">C1 </div></th>
<th bgcolor="#3366CC" width="50"> <div align="center">C2 </div></th>
<th bgcolor="#3366CC" width="50"> <div align="center">C3 </div></th>
<th bgcolor="#3366CC" width="50"> <div align="center">Ct </div></th>
<th bgcolor="#3366CC" width="50"> <div align="center">P1 </div></th>
<th bgcolor="#3366CC" width="50"> <div align="center">P2 </div></th>
<th bgcolor="#3366CC" width="50"> <div align="center">P3 </div></th>
<th bgcolor="#3366CC" width="50"> <div align="center">Pt </div></th>
<th bgcolor="#3366CC" width="50"> <div align="center">M1 </div></th>
<th bgcolor="#3366CC" width="50"> <div align="center">M2 </div></th>
<th bgcolor="#3366CC" width="50"> <div align="center">M3 </div></th>
<th bgcolor="#3366CC" width="50"> <div align="center">Mt </div></th>
<th bgcolor="#3366CC" width="50"> <div align="center">Tt </div></th>
</tr>
<?
$i =0;
while($objResult = mysql_fetch_array($objQuery))
{
$i = $i + 1;
?>
<tr>
<td bgcolor="#3366CC"><div align="center">
<input type="hidden" name="employee_id<?=$i;?>" size="5"
value="<?=$objResult["employee_id"];?>">
<input type="text" name="employee_id<?=$i;?>" size="5"
value="<?=$objResult["employee_id"];?>">
</div></td>
<td bgcolor="#3366CC"><input type="text" name="firstname<?=$i;?>"
size="10" value="<?=$objResult["firstname"];?> "></td>
<td bgcolor="#3366CC"><input type="text" name="lastname<?=$i;?>"
size="10" value="<?=$objResult["lastname"];?> "></td>
<td bgcolor="#3366CC"><div align="center"><input type="number"
name="C1<?=$i;?>" size="2" value="<?=$objResult["C1"];?>"></div></td>
<td bgcolor="#3366CC"><div align="center"><input type="number"
name="C2<?=$i;?>" size="2" value="<?=$objResult["C2"];?>"></div></td>
<td bgcolor="#3366CC"><div align="center"><input type="number"
name="C3<?=$i;?>" size="2" value="<?=$objResult["C3"];?>"></div></td>
<td bgcolor="#B2C2F0" width="50"> <div
align="center"><?=$objResult["Ct"];?></div></td>
<td bgcolor="#3366CC"><div align="center"><input type="number"
name="P1<?=$i;?>" size="2" value="<?=$objResult["P1"];?>"></div></td>
<td bgcolor="#3366CC"><div align="center"><input type="number"
name="P2<?=$i;?>" size="2" value="<?=$objResult["P2"];?>"></div></td>
<td bgcolor="#3366CC"><div align="center"><input type="number"
name="P3<?=$i;?>" size="2" value="<?=$objResult["P3"];?>"></div></td>
<td bgcolor="#B2C2F0" width="50"> <div
align="center"><?=$objResult["Pt"];?></div></td>
<td bgcolor="#3366CC"><div align="center"><input type="number"
name="M1<?=$i;?>" size="2" value="<?=$objResult["M1"];?>"></div></td>
<td bgcolor="#3366CC"><div align="center"><input type="number"
name="M2<?=$i;?>" size="2" value="<?=$objResult["M2"];?>"></div></td>
<td bgcolor="#3366CC"><div align="center"><input type="number"
name="M3<?=$i;?>" size="2" value="<?=$objResult["M3"];?>"></div></td>
<td bgcolor="#B2C2F0" width="50"> <div
align="center"><?=$objResult["Mt"];?></div></td>
<td bgcolor="#00FFFF" width="50"> <div
align="center"><?=$objResult["Tt"];?></div></td>
</tr>
<?
}
?>
</table>
<input type="submit" name="submit" value="submit">
<input type="hidden" name="hdnLine" value="<?=(int)$i;?>">
</form>
<?
mysql_close($objConnect);
?>
</body>
</html>`
The code for php_mysql_multiple_edit.php is
<?php
$objConnect = mysql_connect("localhost","root","root") or die(mysql_error());
$objDB = mysql_select_db("test");
$i = (int)0;
//*** Update Condition ***//
for($i=1;$i<=$_POST["hdnLine"];$i++)
{
$strSQL = "UPDATE leave_db SET ";
$strSQL .="employee_id = '".$_POST["employee_id$i"]."' ";
$strSQL .=",firstname = '".$_POST["firstname$i"]."' ";
$strSQL .=",lastname = '".$_POST["lastname$i"]."' ";
$strSQL .=",C1 = '".$_POST["C1$i"]."' ";
$strSQL .=",C2 = '".$_POST["C2$i"]."' ";
$strSQL .=",C3 = '".$_POST["C3$i"]."' ";
$strSQL .=",P1 = '".$_POST["P1$i"]."' ";
$strSQL .=",P2 = '".$_POST["P2$i"]."' ";
$strSQL .=",P3 = '".$_POST["P3$i"]."' ";
$strSQL .=",M1 = '".$_POST["M1$i"]."' ";
$strSQL .=",M2 = '".$_POST["M2$i"]."' ";
$strSQL .=",M3 = '".$_POST["M3$i"]."' ";
$strSQL .="WHERE employee_id = '".$_POST["employee_id$i"]."' ";
$objQuery = mysql_query($strSQL);
}
for($i=1;$i<=$_POST["hdnLine"];$i++)
{
$SUMC1="select (C1+C2-C3) as 'SUMC2' from leave_db where
employee_id='".$_POST["employee_id$i"]."'";
$queryC1=mysql_query($SUMC1);
$rowC1=mysql_fetch_array($queryC1);
$final_sumC=$rowC1['SUMC2'];
$update_queryC=" update leave_db set Ct=$final_sumC where
employee_id='".$_POST["employee_id$i"]."'";
$objQueryC = mysql_query($update_queryC);
$SUMP1="select (P1+P2-P3) as 'SUMP2' from leave_db where
employee_id='".$_POST["employee_id$i"]."'";
$queryP1=mysql_query($SUMP1);
$rowP1=mysql_fetch_array($queryP1);
$final_sumP=$rowP1['SUMP2'];
$update_queryP=" update leave_db set Pt=$final_sumP where
employee_id='".$_POST["employee_id$i"]."'";
$objQueryP = mysql_query($update_queryP);
$SUMM1="select (M1+M2-M3) as 'SUMM2' from leave_db where
employee_id='".$_POST["employee_id$i"]."'";
$queryM1=mysql_query($SUMM1);
$rowM1=mysql_fetch_array($queryM1);
$final_sumM=$rowM1['SUMM2'];
$update_queryM=" update leave_db set Mt=$final_sumM where
employee_id='".$_POST["employee_id$i"]."'";
$objQueryM = mysql_query($update_queryM);
$SUMT1="select (Ct+Pt+Mt) as 'SUMT2' from leave_db where
employee_id='".$_POST["employee_id$i"]."'";
$queryT1=mysql_query($SUMT1);
$rowT1=mysql_fetch_array($queryT1);
$final_sumT=$rowT1['SUMT2'];
$update_queryT=" update leave_db set Tt=$final_sumT where
employee_id='".$_POST["employee_id$i"]."'";
$objQueryT = mysql_query($update_queryT);
}
//header("location:$_SERVER[PHP_SELF]");
//exit();
$strSQL2 = "SELECT * FROM leave_db ORDER BY firstname ASC";
$objQuery2 = mysql_query($strSQL2) or die ("Error Query [".$strSQL2."]");
echo "Save completed. Click <a
href='php_mysql_multiple_edit2.php'>here</a> to view.";
mysql_close($objConnect);
?>`
Draw a border on top of a div
Draw a border on top of a div
OK, I can't explain what I really need so I'll show it.
Or... if I give it a try with words : I need a border, NOT around the div,
NOT changing anything (width, height, margins, padding - nothing...), just
as if it was drawn on top of the aforementioned div...
Example :
CSS : (targetting the elements with attribute comp-id - bordered state is
set with the msp-selected class)
[comp-id] {
cursor:pointer;
}
[comp-id] .msp-selected, [comp-id] .msp-selected:hover {
border:2px solid red;
box-sizing:border-box;
-moz-box-sizing:border-box;
-webkit-box-sizing:border-box;
}
I've tried with border, outline, and box-sizing:border-box; but none of
the above maintains the layout.
So,... Any ideas how this can be achieved?
UPDATE (Here's what box-sizing - yep, ALL of them - does) :
Let's say we first highlight the upper element (add the border) and then
then bottom one - as you may notice, the border does affect the layout
(like if it adds padding or sth)...
OK, I can't explain what I really need so I'll show it.
Or... if I give it a try with words : I need a border, NOT around the div,
NOT changing anything (width, height, margins, padding - nothing...), just
as if it was drawn on top of the aforementioned div...
Example :
CSS : (targetting the elements with attribute comp-id - bordered state is
set with the msp-selected class)
[comp-id] {
cursor:pointer;
}
[comp-id] .msp-selected, [comp-id] .msp-selected:hover {
border:2px solid red;
box-sizing:border-box;
-moz-box-sizing:border-box;
-webkit-box-sizing:border-box;
}
I've tried with border, outline, and box-sizing:border-box; but none of
the above maintains the layout.
So,... Any ideas how this can be achieved?
UPDATE (Here's what box-sizing - yep, ALL of them - does) :
Let's say we first highlight the upper element (add the border) and then
then bottom one - as you may notice, the border does affect the layout
(like if it adds padding or sth)...
common width to span text
common width to span text
Hello I am working on a project, which I need to use anchor tag with text
and images for this I have used ul tag, but the problem is I want to right
align the image and left align the text inside LI.
here is my code
<div class="button-no-record">
<ul>
<li><a href="#"><span>ADD NEW</span><img
src="images/add_enabled.gif"></a></li>
</ul>
and the css
.button-no-record ul {
display:table-cell;
vertical-align:middle;
}
.button-no-record li{
list-style-type:none;
display:inline-block;
margin-top:10px;
margin-left:5px;
vertical-align:middle;
line-height:29px;
height:29px;
width:103px;
border-radius:8px;
background:#e4e4e4;
color:black;
font-family:Arial;
font-size:.9em;
font-weight:bold;
}
.button-no-record a span {
width:100px;
overflow:hidden;
margin-left:4px;
color:black;
width:40px;
vertical-align:middle;
}
.button-no-record a img{
vertical-align:middle;
}
I want output like this
My Text [Image]
My [Image]
but currenty it is
My Text [Image]
My [Image]
Hello I am working on a project, which I need to use anchor tag with text
and images for this I have used ul tag, but the problem is I want to right
align the image and left align the text inside LI.
here is my code
<div class="button-no-record">
<ul>
<li><a href="#"><span>ADD NEW</span><img
src="images/add_enabled.gif"></a></li>
</ul>
and the css
.button-no-record ul {
display:table-cell;
vertical-align:middle;
}
.button-no-record li{
list-style-type:none;
display:inline-block;
margin-top:10px;
margin-left:5px;
vertical-align:middle;
line-height:29px;
height:29px;
width:103px;
border-radius:8px;
background:#e4e4e4;
color:black;
font-family:Arial;
font-size:.9em;
font-weight:bold;
}
.button-no-record a span {
width:100px;
overflow:hidden;
margin-left:4px;
color:black;
width:40px;
vertical-align:middle;
}
.button-no-record a img{
vertical-align:middle;
}
I want output like this
My Text [Image]
My [Image]
but currenty it is
My Text [Image]
My [Image]
python lxml etree xpath - get information from none-static-tree
python lxml etree xpath - get information from none-static-tree
I am currently moving a german free-hosted forum into phpbb and have
chosen to do so by parsing the forum-html files with lxml etree and
python.
so far, the project is going really well and is almost finished.
However, as usual, a few snags have been thrown my way.
But first, what do I do: wget the html files from
http://www.razyboard.com/system/user_Fruchtweinkeller.html process the
files with tagsoup -nons run my script
the script will:
use etree.parse (xml)
use the xpath as allposts:
'/html/body/table[tr/td[@width="20%"]]/tr[position()>1]'
loop through all instances (for p in allposts) of the xpath and
get the content of the post with
etree.tostring(p.find("td[2]/p"),pretty_print=True)
put the content of the post through a certain function that will clean it
up (text.replace etc)
A lot snags that I encountered I could deal with. For example does this
forum generate html files that somehow suddenly add a i or b or u to the
xpath. so sometimes I get td[2]/i/p
The one snag I can not see an easy solution so far however is that if
certain codes have been used in the post (like left/center/right), it will
not be within my xpath, but following it.
I have semi-solved this by
getting td[2]/p
trying to get a following td[2]/div and
trying to get a following td[2]/ul[*]
here is an example:
http://www.razyboard.com/system/morethread-die-rezeptarchive-fruchtweinkeller-545668-1485255-0.html
But this is a crappy solution. First of all, I might miss content that I
have not seen but does use a similar "after p" approach. Even worse is
that after the div or ul there may be more text in the post without
certain tags that will definately be overlooked.
And I am not writing a script so that I can check 18000 files and 130k
posts if they were imported correctly.
One theoretical solution I could think of would be to get the whole td[2]
and dismiss everything before p (which I do not really know how) and after
the text "Signatur" Since not every post has a signatur this may cause
trouble.
Worst however will be the data I get. With my current system I get good
text without too many tags that I will have to remove. When I get the
whole td[2] this will no longer be the case and it would need extended
rewrite of my cleantext function (which I may be or may not be
knowledgeable enough)
note: I have rudimentary coding experience in c, pascal (yeah, Im old) and
bash. This is my first time with python and xpath. I have learned a lot
but will admit, lots was try and error and/or google...
I have tried to look into lxml html insted xml and could not see any
advantage of switching over.
Now, I can maybe hope someone more experienced with lxml, xml and xpath
reads this, looks at the post(s) of the forum and immediately sees a good
solution for me. It would be very welcome.
Since this is not likely, the only other avenue would be to give me hints
and pushed in the right direction of how to get the whole td[2] and remove
everything that I do not need (top and bottom) and give a similar clean
text as if I was just getting td[2]/p
Thanks in advance!
I am currently moving a german free-hosted forum into phpbb and have
chosen to do so by parsing the forum-html files with lxml etree and
python.
so far, the project is going really well and is almost finished.
However, as usual, a few snags have been thrown my way.
But first, what do I do: wget the html files from
http://www.razyboard.com/system/user_Fruchtweinkeller.html process the
files with tagsoup -nons run my script
the script will:
use etree.parse (xml)
use the xpath as allposts:
'/html/body/table[tr/td[@width="20%"]]/tr[position()>1]'
loop through all instances (for p in allposts) of the xpath and
get the content of the post with
etree.tostring(p.find("td[2]/p"),pretty_print=True)
put the content of the post through a certain function that will clean it
up (text.replace etc)
A lot snags that I encountered I could deal with. For example does this
forum generate html files that somehow suddenly add a i or b or u to the
xpath. so sometimes I get td[2]/i/p
The one snag I can not see an easy solution so far however is that if
certain codes have been used in the post (like left/center/right), it will
not be within my xpath, but following it.
I have semi-solved this by
getting td[2]/p
trying to get a following td[2]/div and
trying to get a following td[2]/ul[*]
here is an example:
http://www.razyboard.com/system/morethread-die-rezeptarchive-fruchtweinkeller-545668-1485255-0.html
But this is a crappy solution. First of all, I might miss content that I
have not seen but does use a similar "after p" approach. Even worse is
that after the div or ul there may be more text in the post without
certain tags that will definately be overlooked.
And I am not writing a script so that I can check 18000 files and 130k
posts if they were imported correctly.
One theoretical solution I could think of would be to get the whole td[2]
and dismiss everything before p (which I do not really know how) and after
the text "Signatur" Since not every post has a signatur this may cause
trouble.
Worst however will be the data I get. With my current system I get good
text without too many tags that I will have to remove. When I get the
whole td[2] this will no longer be the case and it would need extended
rewrite of my cleantext function (which I may be or may not be
knowledgeable enough)
note: I have rudimentary coding experience in c, pascal (yeah, Im old) and
bash. This is my first time with python and xpath. I have learned a lot
but will admit, lots was try and error and/or google...
I have tried to look into lxml html insted xml and could not see any
advantage of switching over.
Now, I can maybe hope someone more experienced with lxml, xml and xpath
reads this, looks at the post(s) of the forum and immediately sees a good
solution for me. It would be very welcome.
Since this is not likely, the only other avenue would be to give me hints
and pushed in the right direction of how to get the whole td[2] and remove
everything that I do not need (top and bottom) and give a similar clean
text as if I was just getting td[2]/p
Thanks in advance!
Wednesday, 21 August 2013
Java Generics List Compilation error
Java Generics List Compilation error
Why i get a compilation error in this line String s=data.get(idx);
Update: I get Type mismatch: cannot convert from E to String
public class Parent<E> {
ArrayList<E> data=new ArrayList<E>();
public void add(E d){
data.add(d);
}
public List<E> getData(){
return data;
}
}
public class Child<E> extends Parent<E>{
public void appendData(E newItem){
super.add(newItem);
}
public void displayData(int idx){
List<E> data=this.getData();
**String s=data.get(idx);**//I get compilation error in this line
System.out.println(s);
}
public static void main(String[] args) {
Child<String> c=new Child<String>();
c.appendData("Data1");
c.appendData("Data2");
c.displayData(1);
}
}
Why i get a compilation error in this line String s=data.get(idx);
Update: I get Type mismatch: cannot convert from E to String
public class Parent<E> {
ArrayList<E> data=new ArrayList<E>();
public void add(E d){
data.add(d);
}
public List<E> getData(){
return data;
}
}
public class Child<E> extends Parent<E>{
public void appendData(E newItem){
super.add(newItem);
}
public void displayData(int idx){
List<E> data=this.getData();
**String s=data.get(idx);**//I get compilation error in this line
System.out.println(s);
}
public static void main(String[] args) {
Child<String> c=new Child<String>();
c.appendData("Data1");
c.appendData("Data2");
c.displayData(1);
}
}
Access item in JSON encoded string
Access item in JSON encoded string
First time working with JSON, been stuck for 2 hours on this. I'm trying
to access a specific item in a JSON encoded string using PHP, but running
into issues.
My code:
$json = json_encode($tweets);
$result = json_decode($json, true);
var_dump($result);
echo $result['text'];
Output
array(1) { [0]=> array(22) { ["created_at"]=> string(30) "Sat Jul 20
15:03:15 +0000 2013" ["id"]=> int(1234567) ["id_str"]=> string(18)
"1234567" ["text"]=> string(112) "we have a new billing address" } }
I want to access the ["text"] element only. Any ideas? Thanks!
First time working with JSON, been stuck for 2 hours on this. I'm trying
to access a specific item in a JSON encoded string using PHP, but running
into issues.
My code:
$json = json_encode($tweets);
$result = json_decode($json, true);
var_dump($result);
echo $result['text'];
Output
array(1) { [0]=> array(22) { ["created_at"]=> string(30) "Sat Jul 20
15:03:15 +0000 2013" ["id"]=> int(1234567) ["id_str"]=> string(18)
"1234567" ["text"]=> string(112) "we have a new billing address" } }
I want to access the ["text"] element only. Any ideas? Thanks!
Trying to delete parent node based on innerHTML - Cannot read property 'nodeValue' of undefined
Trying to delete parent node based on innerHTML - Cannot read property
'nodeValue' of undefined
I need to remove the option to delete attachments. The function I tried to
do this with gave me this error: Cannot read property 'nodeValue' of
undefined
I tired doing this:
function hideDelete (){
$("a").filter(function () { return
$.trim(this.childNodes[0].nodeValue) === "Delete";
}).closest("td").hide();
}
HTML:
<td class="ms-propertysheet"><img alt="Delete"
src="/_layouts/images/rect.gif"> <a tabindex="1"
href="javascript:RemoveAttachmentFromServer('{2088EB08-E376-4637-A6F9-35675AF46E35}',1)">Delete</a></td>
'nodeValue' of undefined
I need to remove the option to delete attachments. The function I tried to
do this with gave me this error: Cannot read property 'nodeValue' of
undefined
I tired doing this:
function hideDelete (){
$("a").filter(function () { return
$.trim(this.childNodes[0].nodeValue) === "Delete";
}).closest("td").hide();
}
HTML:
<td class="ms-propertysheet"><img alt="Delete"
src="/_layouts/images/rect.gif"> <a tabindex="1"
href="javascript:RemoveAttachmentFromServer('{2088EB08-E376-4637-A6F9-35675AF46E35}',1)">Delete</a></td>
Download server for business
Download server for business
My problem is that I travel a lot and when I have to download big size
data a would like to redirect the download to a server . So my idea is can
anybody help me because I want to make a download server where i can
redirect all data i download to it.
My problem is that I travel a lot and when I have to download big size
data a would like to redirect the download to a server . So my idea is can
anybody help me because I want to make a download server where i can
redirect all data i download to it.
How do I retrieve data from an Excel Workbook without opening in VBA?
How do I retrieve data from an Excel Workbook without opening in VBA?
I have a folder, which is selectable by a user, which will contain 128
files. In my code, I open each document and copy the relevant data to my
main workbook. All this is controlled through a userform. My problem is
the time it takes to complete this process (about 50 seconds) - surely I
can do it without opening the document at all?
This code is used to select the directory to search in:
Private Sub CBSearch_Click()
Dim Count1 As Integer
ChDir "Directory"
ChDrive "C"
Count1 = 1
inputname = Application.GetOpenFilename("data files (*.P_1),*.P_1")
TBFolderPath.Text = CurDir()
End Sub
This Retrieves the files:
Private Sub CBRetrieve_Click()
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Dim i As Integer
Dim StrLen As Integer
Dim Folder As String
Dim A As String
Dim ColRef As Integer
Open_Data.Hide
StrLen = Len(TBFolderPath) + 1
Folder = Mid(TBFolderPath, StrLen - 10, 10)
For i = 1 To 128
A = Right("000" & i, 3)
If Dir(TBFolderPath + "\" + Folder + "-" + A + ".P_1") <> "" Then
Workbooks.OpenText Filename:= _
TBFolderPath + "\" + Folder + "-" + A + ".P_1" _
, Origin:=xlMSDOS, StartRow:=31, DataType:=xlDelimited,
TextQualifier:= _
xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True,
Semicolon:=False, _
Comma:=False, Space:=False, Other:=False,
FieldInfo:=Array(Array(1, 1), _
Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1)),
TrailingMinusNumbers:=True
Columns("B:B").Delete Shift:=xlToLeft
Rows("2:2").Delete Shift:=xlUp
Range(Range("A1:B1"), Range("A1:B1").End(xlDown)).Copy
Windows("Document.xls").Activate
ColRef = (2 * i) - 1
Cells(15, ColRef).Select
ActiveSheet.Paste
Windows(Folder + "-" + A + ".P_1").Activate
ActiveWindow.Close
End If
Next i
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
TBFolderPath is the contents of a textbox in the userform, and is the
location of the files.
Sorry my code is so messy! Thanks in advance, Laura
I have a folder, which is selectable by a user, which will contain 128
files. In my code, I open each document and copy the relevant data to my
main workbook. All this is controlled through a userform. My problem is
the time it takes to complete this process (about 50 seconds) - surely I
can do it without opening the document at all?
This code is used to select the directory to search in:
Private Sub CBSearch_Click()
Dim Count1 As Integer
ChDir "Directory"
ChDrive "C"
Count1 = 1
inputname = Application.GetOpenFilename("data files (*.P_1),*.P_1")
TBFolderPath.Text = CurDir()
End Sub
This Retrieves the files:
Private Sub CBRetrieve_Click()
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Dim i As Integer
Dim StrLen As Integer
Dim Folder As String
Dim A As String
Dim ColRef As Integer
Open_Data.Hide
StrLen = Len(TBFolderPath) + 1
Folder = Mid(TBFolderPath, StrLen - 10, 10)
For i = 1 To 128
A = Right("000" & i, 3)
If Dir(TBFolderPath + "\" + Folder + "-" + A + ".P_1") <> "" Then
Workbooks.OpenText Filename:= _
TBFolderPath + "\" + Folder + "-" + A + ".P_1" _
, Origin:=xlMSDOS, StartRow:=31, DataType:=xlDelimited,
TextQualifier:= _
xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True,
Semicolon:=False, _
Comma:=False, Space:=False, Other:=False,
FieldInfo:=Array(Array(1, 1), _
Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1)),
TrailingMinusNumbers:=True
Columns("B:B").Delete Shift:=xlToLeft
Rows("2:2").Delete Shift:=xlUp
Range(Range("A1:B1"), Range("A1:B1").End(xlDown)).Copy
Windows("Document.xls").Activate
ColRef = (2 * i) - 1
Cells(15, ColRef).Select
ActiveSheet.Paste
Windows(Folder + "-" + A + ".P_1").Activate
ActiveWindow.Close
End If
Next i
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
TBFolderPath is the contents of a textbox in the userform, and is the
location of the files.
Sorry my code is so messy! Thanks in advance, Laura
Expected time for winning in biased Gambler's Ruin
Expected time for winning in biased Gambler's Ruin
Consider the random walk $X_0, X_1, X_2, \ldots$ on state space
$S=\{0,1,\ldots,n\}$ with absorbing states $A=\{0,n\}$, and with
$P(i,i+1)=p$ and $P(i,i-1)=q$ for all $i \in S \setminus A$, where $p+q=1$
and $p,q>0$.
Let $T$ denote the number of steps until the walk is absorbed in either
$0$ or $n$.
Let $\mathbb{E}_k(\cdot) := \mathbb\{\cdot | X_0 = k\}$ denote the
expectation conditioned on starting in state $k \in S \setminus A$.
How to compute $\mathbb{E}_k(T|X_T = n)$?
Consider the random walk $X_0, X_1, X_2, \ldots$ on state space
$S=\{0,1,\ldots,n\}$ with absorbing states $A=\{0,n\}$, and with
$P(i,i+1)=p$ and $P(i,i-1)=q$ for all $i \in S \setminus A$, where $p+q=1$
and $p,q>0$.
Let $T$ denote the number of steps until the walk is absorbed in either
$0$ or $n$.
Let $\mathbb{E}_k(\cdot) := \mathbb\{\cdot | X_0 = k\}$ denote the
expectation conditioned on starting in state $k \in S \setminus A$.
How to compute $\mathbb{E}_k(T|X_T = n)$?
Tuesday, 20 August 2013
Distinct column names from comma separated string
Distinct column names from comma separated string
pTwo reports are using columns of a table with following queries/p
precodeSELECT [Employee Name] , [Email_ID] , [Region] , [DOB] , [Joining
Date] , [Gross Salary] FROM [tblC6FD_Data_15_EmployeeData] ORDER BY
[Employee Name] ASC, [Email_ID] ASC, [Region] ASC, [DOB] ASC, [Joining
Date] ASC, [Gross Salary] ASC /code/pre hr precodeSELECT [Employee Name] ,
[Region] , [Email_ID] , [DOB] , [Leaving Date] , [Basic Salary] FROM
[tblC6FD_Data_15_EmployeeData] ORDER BY [Employee Name] ASC, [Region] ASC,
[Email_ID] ASC, [DOB] ASC, [Joining Date] ASC, [Gross Salary] ASC
/code/pre pand i want distinct columns list of table that is being used by
reports/p pstrongExpected output/strong/p precodeEmployee Email Region DOB
Joining Date Gross Salary Leaving Date Basic Salary /code/pre pI have one
idea to split it with code,/code but a lot of confusions and complexity to
avoid other strings after strongfrom/strong keyword./p pCan anyone suggest
a simple solution./p
pTwo reports are using columns of a table with following queries/p
precodeSELECT [Employee Name] , [Email_ID] , [Region] , [DOB] , [Joining
Date] , [Gross Salary] FROM [tblC6FD_Data_15_EmployeeData] ORDER BY
[Employee Name] ASC, [Email_ID] ASC, [Region] ASC, [DOB] ASC, [Joining
Date] ASC, [Gross Salary] ASC /code/pre hr precodeSELECT [Employee Name] ,
[Region] , [Email_ID] , [DOB] , [Leaving Date] , [Basic Salary] FROM
[tblC6FD_Data_15_EmployeeData] ORDER BY [Employee Name] ASC, [Region] ASC,
[Email_ID] ASC, [DOB] ASC, [Joining Date] ASC, [Gross Salary] ASC
/code/pre pand i want distinct columns list of table that is being used by
reports/p pstrongExpected output/strong/p precodeEmployee Email Region DOB
Joining Date Gross Salary Leaving Date Basic Salary /code/pre pI have one
idea to split it with code,/code but a lot of confusions and complexity to
avoid other strings after strongfrom/strong keyword./p pCan anyone suggest
a simple solution./p
Zip images in directory
Zip images in directory
I have a directory of directories. Each directory contains ~100 images. I
want to create a zip for each directory.
How can I do that?
I have a directory of directories. Each directory contains ~100 images. I
want to create a zip for each directory.
How can I do that?
Ubuntu 12.04 not allowing incoming traffic from wan
Ubuntu 12.04 not allowing incoming traffic from wan
I've managed to install pptp server on a Ubuntu 12.04 box. It all worked
perfect until found the server was not forwarding ip4 to local lan. After
different things I've tried, now is worst. Server is only listening to LAN
request. Server has also lamp installed and ssh. I've disabled ufw and
iptables are also supposed to be disabled. Hope someone can help.
I've managed to install pptp server on a Ubuntu 12.04 box. It all worked
perfect until found the server was not forwarding ip4 to local lan. After
different things I've tried, now is worst. Server is only listening to LAN
request. Server has also lamp installed and ssh. I've disabled ufw and
iptables are also supposed to be disabled. Hope someone can help.
Ember is printing Hello World! twice
Ember is printing Hello World! twice
I'm just trying to get a basic ember app up and running on a rails
back-end. In application.js I have the following:
$(function(){ $(document).foundation(); });
Ew = Ember.Application.create();
router.coffee:
Ew.Router.map ->
@.resource('hi')
index.hbs:
<p>say hello{{/linkTo}}</p>
hi.hbs:
<h1>Hello!</h1>
When I load the page everything is working as it should. There's a link at
the top that says 'say hello'.
When i click the link the url at /#/hi renders, as it should. But when I
click the back button to go back to the index template and then the
forward button to go to the hi template, "Hello World!" shows up twice.
Anyone ever seen this before?
I'm just trying to get a basic ember app up and running on a rails
back-end. In application.js I have the following:
$(function(){ $(document).foundation(); });
Ew = Ember.Application.create();
router.coffee:
Ew.Router.map ->
@.resource('hi')
index.hbs:
<p>say hello{{/linkTo}}</p>
hi.hbs:
<h1>Hello!</h1>
When I load the page everything is working as it should. There's a link at
the top that says 'say hello'.
When i click the link the url at /#/hi renders, as it should. But when I
click the back button to go back to the index template and then the
forward button to go to the hi template, "Hello World!" shows up twice.
Anyone ever seen this before?
How to search within an array?
How to search within an array?
I have this function that it suppose to get all the from the page, I'm
trying to all all the anchors within those links, but I keep getting
Object [object HTMLAnchorElement] has no method errors, I've tried using
split, search and indexOf, but everything gives mes the same error, what
am I doing wrong?
I know I'm getting all the tags, the first alert returns their total
number. Here's what I have:
// get all the link tags from the page
var a = document.getElementsByTagName('a');
//alert(a.length)
for (var i = 0; i < a.length; i++)
{
// check which links have an anchor within them
if(a[i].search("#") > 1)
{
alert("yes");
}
else
{
alert("no");
}
}
I have this function that it suppose to get all the from the page, I'm
trying to all all the anchors within those links, but I keep getting
Object [object HTMLAnchorElement] has no method errors, I've tried using
split, search and indexOf, but everything gives mes the same error, what
am I doing wrong?
I know I'm getting all the tags, the first alert returns their total
number. Here's what I have:
// get all the link tags from the page
var a = document.getElementsByTagName('a');
//alert(a.length)
for (var i = 0; i < a.length; i++)
{
// check which links have an anchor within them
if(a[i].search("#") > 1)
{
alert("yes");
}
else
{
alert("no");
}
}
How can I configure sdiff as a merge tool for git?
How can I configure sdiff as a merge tool for git?
I am still looking for a good command line (no GUI) git merge tool as I do
not know vim or emacs. I found the following on how to use sdiff for
merging, which seems pretty simple.
I cannot seem to make sdiff work properly. I currently have the following
in my .gitconfig file, but git mergetool complains that git config option
merge.tool set to unknown tool: sdiff. I have tried different cmd (with
variables $BASE $LOCAL $REMOTE $MERGED), but to no avail.
[merge]
conflictstyle = diff3
tool = sdiff
[mergetool "sdiff"]
path = /usr/bin/sdiff
What is the correct configuration to make sdiff work as a merge tool for
git? Alternatively, if you know of a better command-line tool that does
not have a steep learning curve, I would like to know.
I am still looking for a good command line (no GUI) git merge tool as I do
not know vim or emacs. I found the following on how to use sdiff for
merging, which seems pretty simple.
I cannot seem to make sdiff work properly. I currently have the following
in my .gitconfig file, but git mergetool complains that git config option
merge.tool set to unknown tool: sdiff. I have tried different cmd (with
variables $BASE $LOCAL $REMOTE $MERGED), but to no avail.
[merge]
conflictstyle = diff3
tool = sdiff
[mergetool "sdiff"]
path = /usr/bin/sdiff
What is the correct configuration to make sdiff work as a merge tool for
git? Alternatively, if you know of a better command-line tool that does
not have a steep learning curve, I would like to know.
How to open aspx page in internet explorer
How to open aspx page in internet explorer
Im using devexpress reportviever and report toolbar.Find button cant work
across browser because it used activex so only it can work internet
explorer.My questons is how to aspx page open internet explorer?For
example after redirection page open in internet explorer. Thank you all of
members
Im using devexpress reportviever and report toolbar.Find button cant work
across browser because it used activex so only it can work internet
explorer.My questons is how to aspx page open internet explorer?For
example after redirection page open in internet explorer. Thank you all of
members
Monday, 19 August 2013
Multiply each element of an array to each other
Multiply each element of an array to each other
I have an array of float numbers: (.25, .45, .15, .27). I would like to
multiply each element with each other than divide by the number of array
elements.
foreach my $element (@array)
{
my $score = $score * $element;
}
$score = $score/$numofelements;
This produces the value 0. Not sure if my syntax is correct.
I have an array of float numbers: (.25, .45, .15, .27). I would like to
multiply each element with each other than divide by the number of array
elements.
foreach my $element (@array)
{
my $score = $score * $element;
}
$score = $score/$numofelements;
This produces the value 0. Not sure if my syntax is correct.
Probability of being up in roulette
Probability of being up in roulette
A player bets $\$1$ on a single number in a standard US roulette, that is,
38 possible numbers ($\frac{1}{38}$ chance of a win each game). A win pays
35 times the stake plus the stake returned, otherwise the stake is lost.
So, the expected loss per game is $\left(\frac{1}{38}\right)(35) +
\left(37/38\right)(-1) = -\frac{2}{38}$ dollars, and in 36 games
$36\left(-\frac{2}{38}\right) = -1.89$ dollars.
But, the player is up within 35 games if he wins a single game, thus the
probability of being up in 35 games is $1 -
\left(\frac{37}{38}\right)^{35} = 0.607$. And even in 26 games, the
probability of being up is still slightly greater than half.
This is perhaps surprising as it seems to suggest you can win at roulette
if you play often enough. I'm assuming that that this result is offset by
a very high variance, but wouldn't that also imply you could win big by
winning multiple times? Can someone with a better statistics brain shed
some light onto this problem, and extend my analyse? Thanks.
A player bets $\$1$ on a single number in a standard US roulette, that is,
38 possible numbers ($\frac{1}{38}$ chance of a win each game). A win pays
35 times the stake plus the stake returned, otherwise the stake is lost.
So, the expected loss per game is $\left(\frac{1}{38}\right)(35) +
\left(37/38\right)(-1) = -\frac{2}{38}$ dollars, and in 36 games
$36\left(-\frac{2}{38}\right) = -1.89$ dollars.
But, the player is up within 35 games if he wins a single game, thus the
probability of being up in 35 games is $1 -
\left(\frac{37}{38}\right)^{35} = 0.607$. And even in 26 games, the
probability of being up is still slightly greater than half.
This is perhaps surprising as it seems to suggest you can win at roulette
if you play often enough. I'm assuming that that this result is offset by
a very high variance, but wouldn't that also imply you could win big by
winning multiple times? Can someone with a better statistics brain shed
some light onto this problem, and extend my analyse? Thanks.
sqlite - How to fill in missing months
sqlite - How to fill in missing months
I've got the following SQL:
select strftime('%m', date) ord, case strftime('%m', date) when '01' then
'January' when '02' then 'Febuary' when '03' then 'March' when '04' then
'April' when '05' then 'May' when '06' then 'June' when '07' then 'July'
when '08' then 'August' when '09' then 'September' when '10' then
'October' when '11' then 'November' when '12' then 'December' else '' end
as month, count(*) as count from events where type='Birth' and date <> ''
group by month,ord order by ord
This gives me results similar to:
ord month count
01 January 1
02 Febuary 1
03 March 3
05 May 4
07 July 2
08 August 2
09 September 2
11 November 4
But as you can see it has gaps. Is there any way to fill in the missing
months with a 0 count?
I've got the following SQL:
select strftime('%m', date) ord, case strftime('%m', date) when '01' then
'January' when '02' then 'Febuary' when '03' then 'March' when '04' then
'April' when '05' then 'May' when '06' then 'June' when '07' then 'July'
when '08' then 'August' when '09' then 'September' when '10' then
'October' when '11' then 'November' when '12' then 'December' else '' end
as month, count(*) as count from events where type='Birth' and date <> ''
group by month,ord order by ord
This gives me results similar to:
ord month count
01 January 1
02 Febuary 1
03 March 3
05 May 4
07 July 2
08 August 2
09 September 2
11 November 4
But as you can see it has gaps. Is there any way to fill in the missing
months with a 0 count?
Looking for direction in why program is not functioning properly
Looking for direction in why program is not functioning properly
This is kind of a long question but I'm completely stumped on why my
program isn't working, and how I can begin to troubleshoot it.
I have a program that accesses "Scenarios" from a XML database and runs
tests on them. What's neat about the program is that if runs these tests
in WebBrowser control embedded in a Windows Form, so it can act as a
screensaver when the user is idle. That way, even idle computers are still
running unit tests in scenarios.
When the screensaver form loads, I call GetScenarios(). GetScenarios()
does a number of things:
Login to a portal.
Connects to the SQL DB
Starts up a SQLDataReader while loop to loop through the Scenarios in the
database
Inside of the while loop, it runs a test function on the scenarios, and
inserts the results into another database.
The main problem I have been trying to solve throughout this project has
been how to Navigate on a WebBrowser and read the DOM and inject
Javascript all inside of this global while loop, without anything being
interrupted. I'm really close to it working, but I'm still encountering a
number of problems.
Program (relevant code):
public void GetScenarios()
{
// Login to portal
PortalLogin();
using (SqlConnection conn = new
SqlConnection(Properties.Settings.Default.DBConnectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("SELECT * FROM
Scenarios WHERE IsEnabled='1'", conn))
{
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
// Store scenario ID/initialize variables
int Id = (int)reader["ScenarioID"];
int[] results = { 0, 0 };
var screenshot = new Byte[] { };
// Start reading XML Data
string Url = "";
/* Perform a test on the selected scenario
* (can do different types of tests)
* Update HasSucceeded and successes/failures
* */
results = TestScenarios(reader, cmd, Url,
results);
// Take screenshot
TakeScreenshot(screenshot);
// Insert result data into Results table
InsertResults(Id, results, screenshot);
// Mark IsEnabled as false (disable the scenario)
DisableScenario(Id);
}
reader.Close();
//MessageBox.Show("All scenarios have been marked
as disabled.");
Application.Exit();
}
else
{
//MessageBox.Show("All scenarios have been marked
as disabled.");
Application.Exit();
}
}
}
}
/// <summary>
/// Login to the portal
/// </summary>
public void PortalLogin()
{
string portalUrl = "URL";
string portalEmail = "EMAIL";
string portalPassword = "PASSWORD";
// Run when page finishes navigating
webBrowser2.DocumentCompleted += (s, e) =>
{
HtmlElement head =
webBrowser2.Document.GetElementsByTagName("head")[0];
HtmlElement testScript =
webBrowser2.Document.CreateElement("script");
IHTMLScriptElement element =
(IHTMLScriptElement)testScript.DomElement;
element.text = "function PortalLogin() {
document.getElementById('EMAIL').value = '" + portalEmail
+ "'; document.getElementById('PASSWORD').value = '" +
portalPassword + "';
document.getElementById('LOGINFORM').submit(); }";
head.AppendChild(testScript);
webBrowser2.Document.InvokeScript("PortalLogin");
};
// Navigate to O365 portal
webBrowser2.Navigate(portalUrl);
while (this.webBrowser2.ReadyState !=
WebBrowserReadyState.Complete)
{
Application.DoEvents();
Thread.Sleep(100);
}
}
/// <summary>
/// Goes to specified Url
/// Performs a test on the selected scenario
/// </summary>
public int[] TestScenarios(SqlDataReader reader, SqlCommand cmd,
string Url, int[] results)
{
// Initialize variables
string testType = "";
string testElement = "";
string expected = "";
string formElem = "";
string emailElem = "";
string passwordElem = "";
string testEmail = "";
string testPassword = "";
// Open SQLXML reader
SqlXml sqlXml = reader.GetSqlXml(1);
using (var xmlreader = sqlXml.CreateReader())
{
// Start looping through scenario steps
var document = XDocument.Load(xmlreader);
foreach (XElement step in document.Descendants("Step"))
{
// Get scenario Url
Url = step
.Attribute("Url")
.Value;
// Start looping through scenario checks
foreach (XElement substep in step.Descendants())
{
// Get type of test
testType = substep
.Attribute("Type")
.Value;
// Run when page finishes navigating
webBrowser2.DocumentCompleted += (s, e) =>
{
// If/else to determine type of test
if (testType == "ContentPresent")
{
expected = substep
.Attribute("Expected")
.Value;
HtmlAgilityPack.HtmlDocument doc = new
HtmlAgilityPack.HtmlDocument();
WebClient client = new WebClient();
string html = client.DownloadString(Url);
doc.LoadHtml(html);
var foo = (from bar in
doc.DocumentNode.DescendantNodes()
where
bar.GetAttributeValue("id",
null) == expected
select bar).FirstOrDefault();
if (foo != null)
{
results[0]++;
}
else
{
results[1]++;
}
}
else if (testType == "Click")
{
testElement = substep
.Attribute("Element")
.Value;
expected = substep
.Attribute("Expected")
.Value;
webBrowser2.Invoke(new Action(() =>
{
HtmlElement head =
webBrowser2.Document.GetElementsByTagName("head")[0];
HtmlElement testScript =
webBrowser2.Document.CreateElement("script");
IHTMLScriptElement element =
(IHTMLScriptElement)testScript.DomElement;
element.text = "FUNCTION TO INJECT JS";
head.AppendChild(testScript);
webBrowser2.Document.InvokeScript("TestClick");
}));
string TestUrl = webBrowser2.Url.AbsoluteUri;
if (TestUrl.Equals(expected))
{
results[0]++;
}
else
{
results[1]++;
}
}
else if (testType == "Login")
{
formElem = substep
.Attribute("FormElem")
.Value;
emailElem = substep
.Attribute("EmailElem")
.Value;
passwordElem = substep
.Attribute("PasswordElem")
.Value;
testEmail = substep
.Attribute("TestEmail")
.Value;
testPassword = substep
.Attribute("TestPassword")
.Value;
expected = substep
.Attribute("Expected")
.Value;
webBrowser2.Invoke(new Action(() =>
{
HtmlElement head =
webBrowser2.Document.GetElementsByTagName("head")[0];
HtmlElement testScript =
webBrowser2.Document.CreateElement("script");
IHTMLScriptElement element =
(IHTMLScriptElement)testScript.DomElement;
element.text = "FUNCTION TO SIMULATE
LOGIN";
head.AppendChild(testScript);
webBrowser2.Document.InvokeScript("TestLogin");
}));
string TestUrl = webBrowser2.Url.AbsoluteUri;
if (TestUrl.Equals(expected))
{
results[0]++;
}
else
{
results[1]++;
}
}
else
{
MessageBox.Show("Test type not valid");
}
};
// Navigate to page
webBrowser2.Navigate(Url);
while (this.webBrowser2.ReadyState !=
WebBrowserReadyState.Complete)
{
Application.DoEvents();
Thread.Sleep(100);
}
}
}
}
return results;
}
XML Data:
1st Scenario: (only XML part)
<Scenario Name="LogoPresent" Feature="Navbar">
<Steps>
<Step Url="URL">
<Check Type="ContentPresent" Expected="ELEM_ID" />
<Check Type="ContentPresent" Expected="ELEM_ID2" />
</Step>
<Step Url="URL2">
<Check Type="ContentPresent" Expected="ELEM_ID3" />
</Step>
</Steps>
</Scenario>
2nd Scenario: (only XML part)
<Scenario>
<Steps>
<Step Url="URL1">
<Check Type="ContentPresent" Expected="ELEM_ID"></Check>
</Step>
</Steps>
</Scenario>
As you can see, I've been trying to use DocumentCompleted to handle the
Navigate running asynchronously, but the output of my code is still a bit
buggy.
Expected Result:
The expected result of this program is for TestScenarios() to output a
results array of [2, 0] for the first scenario and [1,0] for the second
scenario (which means 2 successes, 0 failures, and 1 success, 0 failures,
respectively). If there is a problem with my JS injection (which I don't
think there is, because when I input it directly into the Chrome/IE
console it returns true), than it should return [0, 2] and [0, 1]
respectively.
Actual Result:
However, the actual result is a little different. For some reason, the
program always outputs a results array of [0, 6] and [0, 1], which doesn't
make sense because there are only 2 XML checks in the first scenario, so
why are 6 failures being outputted?
Interestingly, when I debug the program, it appears to run fine: the
portal appears and is logged into with the JS, and then the 3 separate
webpages appear one after another, and then the program closes.
Brainstorming what the problem is:
I've been trying to brainstorm what the problem could be and have come
across a couple of ideas:
The tests are occurring before the page is fully loaded, so they are
continually returning failures. I'm not sure if this could be the case
though, because usually an exception is thrown if the DOM is accessed
without the element having been loaded.
The nested foreach loops are not looping through the XML <Check> elements
correctly (however I asked this in another question and it seems like they
were).
The while loop is interrupting the TestScenario checks somehow...
Overall- any ideas/direction/tips are really useful, and if this question
is too large/out of scope I can delete it and try to narrow down what my
problem is.
This is kind of a long question but I'm completely stumped on why my
program isn't working, and how I can begin to troubleshoot it.
I have a program that accesses "Scenarios" from a XML database and runs
tests on them. What's neat about the program is that if runs these tests
in WebBrowser control embedded in a Windows Form, so it can act as a
screensaver when the user is idle. That way, even idle computers are still
running unit tests in scenarios.
When the screensaver form loads, I call GetScenarios(). GetScenarios()
does a number of things:
Login to a portal.
Connects to the SQL DB
Starts up a SQLDataReader while loop to loop through the Scenarios in the
database
Inside of the while loop, it runs a test function on the scenarios, and
inserts the results into another database.
The main problem I have been trying to solve throughout this project has
been how to Navigate on a WebBrowser and read the DOM and inject
Javascript all inside of this global while loop, without anything being
interrupted. I'm really close to it working, but I'm still encountering a
number of problems.
Program (relevant code):
public void GetScenarios()
{
// Login to portal
PortalLogin();
using (SqlConnection conn = new
SqlConnection(Properties.Settings.Default.DBConnectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("SELECT * FROM
Scenarios WHERE IsEnabled='1'", conn))
{
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
// Store scenario ID/initialize variables
int Id = (int)reader["ScenarioID"];
int[] results = { 0, 0 };
var screenshot = new Byte[] { };
// Start reading XML Data
string Url = "";
/* Perform a test on the selected scenario
* (can do different types of tests)
* Update HasSucceeded and successes/failures
* */
results = TestScenarios(reader, cmd, Url,
results);
// Take screenshot
TakeScreenshot(screenshot);
// Insert result data into Results table
InsertResults(Id, results, screenshot);
// Mark IsEnabled as false (disable the scenario)
DisableScenario(Id);
}
reader.Close();
//MessageBox.Show("All scenarios have been marked
as disabled.");
Application.Exit();
}
else
{
//MessageBox.Show("All scenarios have been marked
as disabled.");
Application.Exit();
}
}
}
}
/// <summary>
/// Login to the portal
/// </summary>
public void PortalLogin()
{
string portalUrl = "URL";
string portalEmail = "EMAIL";
string portalPassword = "PASSWORD";
// Run when page finishes navigating
webBrowser2.DocumentCompleted += (s, e) =>
{
HtmlElement head =
webBrowser2.Document.GetElementsByTagName("head")[0];
HtmlElement testScript =
webBrowser2.Document.CreateElement("script");
IHTMLScriptElement element =
(IHTMLScriptElement)testScript.DomElement;
element.text = "function PortalLogin() {
document.getElementById('EMAIL').value = '" + portalEmail
+ "'; document.getElementById('PASSWORD').value = '" +
portalPassword + "';
document.getElementById('LOGINFORM').submit(); }";
head.AppendChild(testScript);
webBrowser2.Document.InvokeScript("PortalLogin");
};
// Navigate to O365 portal
webBrowser2.Navigate(portalUrl);
while (this.webBrowser2.ReadyState !=
WebBrowserReadyState.Complete)
{
Application.DoEvents();
Thread.Sleep(100);
}
}
/// <summary>
/// Goes to specified Url
/// Performs a test on the selected scenario
/// </summary>
public int[] TestScenarios(SqlDataReader reader, SqlCommand cmd,
string Url, int[] results)
{
// Initialize variables
string testType = "";
string testElement = "";
string expected = "";
string formElem = "";
string emailElem = "";
string passwordElem = "";
string testEmail = "";
string testPassword = "";
// Open SQLXML reader
SqlXml sqlXml = reader.GetSqlXml(1);
using (var xmlreader = sqlXml.CreateReader())
{
// Start looping through scenario steps
var document = XDocument.Load(xmlreader);
foreach (XElement step in document.Descendants("Step"))
{
// Get scenario Url
Url = step
.Attribute("Url")
.Value;
// Start looping through scenario checks
foreach (XElement substep in step.Descendants())
{
// Get type of test
testType = substep
.Attribute("Type")
.Value;
// Run when page finishes navigating
webBrowser2.DocumentCompleted += (s, e) =>
{
// If/else to determine type of test
if (testType == "ContentPresent")
{
expected = substep
.Attribute("Expected")
.Value;
HtmlAgilityPack.HtmlDocument doc = new
HtmlAgilityPack.HtmlDocument();
WebClient client = new WebClient();
string html = client.DownloadString(Url);
doc.LoadHtml(html);
var foo = (from bar in
doc.DocumentNode.DescendantNodes()
where
bar.GetAttributeValue("id",
null) == expected
select bar).FirstOrDefault();
if (foo != null)
{
results[0]++;
}
else
{
results[1]++;
}
}
else if (testType == "Click")
{
testElement = substep
.Attribute("Element")
.Value;
expected = substep
.Attribute("Expected")
.Value;
webBrowser2.Invoke(new Action(() =>
{
HtmlElement head =
webBrowser2.Document.GetElementsByTagName("head")[0];
HtmlElement testScript =
webBrowser2.Document.CreateElement("script");
IHTMLScriptElement element =
(IHTMLScriptElement)testScript.DomElement;
element.text = "FUNCTION TO INJECT JS";
head.AppendChild(testScript);
webBrowser2.Document.InvokeScript("TestClick");
}));
string TestUrl = webBrowser2.Url.AbsoluteUri;
if (TestUrl.Equals(expected))
{
results[0]++;
}
else
{
results[1]++;
}
}
else if (testType == "Login")
{
formElem = substep
.Attribute("FormElem")
.Value;
emailElem = substep
.Attribute("EmailElem")
.Value;
passwordElem = substep
.Attribute("PasswordElem")
.Value;
testEmail = substep
.Attribute("TestEmail")
.Value;
testPassword = substep
.Attribute("TestPassword")
.Value;
expected = substep
.Attribute("Expected")
.Value;
webBrowser2.Invoke(new Action(() =>
{
HtmlElement head =
webBrowser2.Document.GetElementsByTagName("head")[0];
HtmlElement testScript =
webBrowser2.Document.CreateElement("script");
IHTMLScriptElement element =
(IHTMLScriptElement)testScript.DomElement;
element.text = "FUNCTION TO SIMULATE
LOGIN";
head.AppendChild(testScript);
webBrowser2.Document.InvokeScript("TestLogin");
}));
string TestUrl = webBrowser2.Url.AbsoluteUri;
if (TestUrl.Equals(expected))
{
results[0]++;
}
else
{
results[1]++;
}
}
else
{
MessageBox.Show("Test type not valid");
}
};
// Navigate to page
webBrowser2.Navigate(Url);
while (this.webBrowser2.ReadyState !=
WebBrowserReadyState.Complete)
{
Application.DoEvents();
Thread.Sleep(100);
}
}
}
}
return results;
}
XML Data:
1st Scenario: (only XML part)
<Scenario Name="LogoPresent" Feature="Navbar">
<Steps>
<Step Url="URL">
<Check Type="ContentPresent" Expected="ELEM_ID" />
<Check Type="ContentPresent" Expected="ELEM_ID2" />
</Step>
<Step Url="URL2">
<Check Type="ContentPresent" Expected="ELEM_ID3" />
</Step>
</Steps>
</Scenario>
2nd Scenario: (only XML part)
<Scenario>
<Steps>
<Step Url="URL1">
<Check Type="ContentPresent" Expected="ELEM_ID"></Check>
</Step>
</Steps>
</Scenario>
As you can see, I've been trying to use DocumentCompleted to handle the
Navigate running asynchronously, but the output of my code is still a bit
buggy.
Expected Result:
The expected result of this program is for TestScenarios() to output a
results array of [2, 0] for the first scenario and [1,0] for the second
scenario (which means 2 successes, 0 failures, and 1 success, 0 failures,
respectively). If there is a problem with my JS injection (which I don't
think there is, because when I input it directly into the Chrome/IE
console it returns true), than it should return [0, 2] and [0, 1]
respectively.
Actual Result:
However, the actual result is a little different. For some reason, the
program always outputs a results array of [0, 6] and [0, 1], which doesn't
make sense because there are only 2 XML checks in the first scenario, so
why are 6 failures being outputted?
Interestingly, when I debug the program, it appears to run fine: the
portal appears and is logged into with the JS, and then the 3 separate
webpages appear one after another, and then the program closes.
Brainstorming what the problem is:
I've been trying to brainstorm what the problem could be and have come
across a couple of ideas:
The tests are occurring before the page is fully loaded, so they are
continually returning failures. I'm not sure if this could be the case
though, because usually an exception is thrown if the DOM is accessed
without the element having been loaded.
The nested foreach loops are not looping through the XML <Check> elements
correctly (however I asked this in another question and it seems like they
were).
The while loop is interrupting the TestScenario checks somehow...
Overall- any ideas/direction/tips are really useful, and if this question
is too large/out of scope I can delete it and try to narrow down what my
problem is.
Subscribe to:
Comments (Atom)