What is meaning of [_|\_|\.]? in Javascript regexps?
I have a js codeF
/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/
But what's meaning of [_|\_|\.]?ijs regexpj
Thursday, 3 October 2013
Wednesday, 2 October 2013
How can i make setExpressCheckout in PayPal SOAP php
How can i make setExpressCheckout in PayPal SOAP php
I have a problem with setExpressCheckout in PayPal. When i try GetBalance
or GetTransactionDetail all is ok. But in this code when i try make
SetExpressCheckout i have error with Version is not suported. But i think
is not about version. i was spend 4 days on try to resolve and can not :(
$client = new SoapClient('https://www.paypal.com/wsdl/PayPalSvc.wsdl', array(
'soap_version' => '106.0',
'trace' => 1,
'exceptions' => 1,
'location'=> 'https://api-3t.paypal.com/2.0/',
));
$cred = array(
'Username' => 'my username',
'Password' => 'KO23W9UJSB57HIJD',
'Signature' => 'AFcWxV21C7fd0v98TYYRCpSSRl31A7MbjiHUHOLDgv0HmrH.pJcvMr.r'
);
$Credentials = new stdClass();
$Credentials->Credentials = new SoapVar( $cred, SOAP_ENC_OBJECT,
'Credentials' );
$headers = new SoapVar( $Credentials,
SOAP_ENC_OBJECT,
'CustomSecurityHeaderType',
'urn:ebay:apis:eBLBaseComponents'
);
$client->__setSoapHeaders( new SoapHeader(
'urn:ebay:api:PayPalAPI',
'RequesterCredentials',
$headers
));
$args = array(
'Version' => '106.0',
'ReturnAllCurrencies' => '1'
);
$GetBalanceRequest = new stdClass();
$GetBalanceRequest->GetBalanceRequest = new SoapVar( $args,
SOAP_ENC_OBJECT,
'GetBalanceRequestType',
'urn:ebay:api:PayPalAPI'
);
$params = new SoapVar( $GetBalanceRequest, SOAP_ENC_OBJECT,
'GetBalanceRequest' );
$result = $client->GetBalance( $params );
echo 'Balance is: ', $result->Balance->_, ' ', $result->Balance->currencyID;
/*
This is correct and i see my bakance
*/
//set Express checkout
$args2 = array(
'OrderTotal' => '10.0 PLN',
'PaymentRequestID' => '78y3h7y8y78',
);
$PaymentDetails = new stdClass();
$PaymentDetails->PaymentDetails = new SoapVar( $args2,
SOAP_ENC_OBJECT,
'PaymentDetailsType',
'urn:ebay:api:PayPalAPI'
);
$args3 = array(
'PayPalAccountID' => '3C988uJMfU7A',
'PaymentRequestID' => '3366y66uug',
);
$SellerDetails = new stdClass();
$SellerDetails->SellerDetails = new SoapVar( $args3,
SOAP_ENC_OBJECT,
'SellerDetailsType',
'urn:ebay:api:PayPalAPI'
);
$paymentDetailsArray = array();
$paymentDetailsArray[] = $PaymentDetails->PaymentDetails;
$args1 = array(
'Version' => '106.0',
'ReturnURL' => 'linkTOsuccess',
'CancelURL' => 'linkTOcancel',
'ReqConfirmShipping' => '0',
'NoShipping' => '1',
'PaymentDetails' => $paymentDetailsArray,
);
$SetExpressCheckoutRequestDetails = new stdClass();
$SetExpressCheckoutRequestDetails->SetExpressCheckoutRequestDetails = new
SoapVar( $args1,
SOAP_ENC_OBJECT,
'SetExpressCheckoutRequestDetailsType',
'urn:ebay:api:PayPalAPI'
);
//var_dump($SetExpressCheckoutRequestDetails);
//die();
$params = new SoapVar( $SetExpressCheckoutRequestDetails, SOAP_ENC_OBJECT,
'SetExpressCheckoutRequestDetails' );
$result = $client->SetExpressCheckout( $params );
var_dump($result);
die();
And this time i have error VERSION NOT SUPORTED but it is not about
version i think
I have a problem with setExpressCheckout in PayPal. When i try GetBalance
or GetTransactionDetail all is ok. But in this code when i try make
SetExpressCheckout i have error with Version is not suported. But i think
is not about version. i was spend 4 days on try to resolve and can not :(
$client = new SoapClient('https://www.paypal.com/wsdl/PayPalSvc.wsdl', array(
'soap_version' => '106.0',
'trace' => 1,
'exceptions' => 1,
'location'=> 'https://api-3t.paypal.com/2.0/',
));
$cred = array(
'Username' => 'my username',
'Password' => 'KO23W9UJSB57HIJD',
'Signature' => 'AFcWxV21C7fd0v98TYYRCpSSRl31A7MbjiHUHOLDgv0HmrH.pJcvMr.r'
);
$Credentials = new stdClass();
$Credentials->Credentials = new SoapVar( $cred, SOAP_ENC_OBJECT,
'Credentials' );
$headers = new SoapVar( $Credentials,
SOAP_ENC_OBJECT,
'CustomSecurityHeaderType',
'urn:ebay:apis:eBLBaseComponents'
);
$client->__setSoapHeaders( new SoapHeader(
'urn:ebay:api:PayPalAPI',
'RequesterCredentials',
$headers
));
$args = array(
'Version' => '106.0',
'ReturnAllCurrencies' => '1'
);
$GetBalanceRequest = new stdClass();
$GetBalanceRequest->GetBalanceRequest = new SoapVar( $args,
SOAP_ENC_OBJECT,
'GetBalanceRequestType',
'urn:ebay:api:PayPalAPI'
);
$params = new SoapVar( $GetBalanceRequest, SOAP_ENC_OBJECT,
'GetBalanceRequest' );
$result = $client->GetBalance( $params );
echo 'Balance is: ', $result->Balance->_, ' ', $result->Balance->currencyID;
/*
This is correct and i see my bakance
*/
//set Express checkout
$args2 = array(
'OrderTotal' => '10.0 PLN',
'PaymentRequestID' => '78y3h7y8y78',
);
$PaymentDetails = new stdClass();
$PaymentDetails->PaymentDetails = new SoapVar( $args2,
SOAP_ENC_OBJECT,
'PaymentDetailsType',
'urn:ebay:api:PayPalAPI'
);
$args3 = array(
'PayPalAccountID' => '3C988uJMfU7A',
'PaymentRequestID' => '3366y66uug',
);
$SellerDetails = new stdClass();
$SellerDetails->SellerDetails = new SoapVar( $args3,
SOAP_ENC_OBJECT,
'SellerDetailsType',
'urn:ebay:api:PayPalAPI'
);
$paymentDetailsArray = array();
$paymentDetailsArray[] = $PaymentDetails->PaymentDetails;
$args1 = array(
'Version' => '106.0',
'ReturnURL' => 'linkTOsuccess',
'CancelURL' => 'linkTOcancel',
'ReqConfirmShipping' => '0',
'NoShipping' => '1',
'PaymentDetails' => $paymentDetailsArray,
);
$SetExpressCheckoutRequestDetails = new stdClass();
$SetExpressCheckoutRequestDetails->SetExpressCheckoutRequestDetails = new
SoapVar( $args1,
SOAP_ENC_OBJECT,
'SetExpressCheckoutRequestDetailsType',
'urn:ebay:api:PayPalAPI'
);
//var_dump($SetExpressCheckoutRequestDetails);
//die();
$params = new SoapVar( $SetExpressCheckoutRequestDetails, SOAP_ENC_OBJECT,
'SetExpressCheckoutRequestDetails' );
$result = $client->SetExpressCheckout( $params );
var_dump($result);
die();
And this time i have error VERSION NOT SUPORTED but it is not about
version i think
printing first word in a txt file unix bash
printing first word in a txt file unix bash
So I'm trying to print the first word in each line of a txt file. The
words are separated by one blank.
cut -c 1 txt file
Thats the code I have so far but it only prints the first character of
each line. Thanks
So I'm trying to print the first word in each line of a txt file. The
words are separated by one blank.
cut -c 1 txt file
Thats the code I have so far but it only prints the first character of
each line. Thanks
ExtJs Store no record found, but saved one recently
ExtJs Store no record found, but saved one recently
Im working on a project with Sencha Touch and the sqLite proxy you can
find here
I have this WorkShift model which is used by WorkShifts store.
Model:
Ext.define('KCS.model.WorkShift', {
extend: 'Ext.data.Model',
config: {
fields: [
{ name: 'id', type: 'int' },
{ name: 'WorkShiftID', type: 'int' },
{ name: 'StartDate', type: 'date' },
{ name: 'ClosureDate', type: 'date' },
],
proxy: {
type: 'sqlitestorage',
dbConfig: {
tablename: 'tbl_WorkShift',
dbConn: KCS.util.InitSQLite.getConnection()
}
}
}
});
And the store:
Ext.define('KCS.store.WorkShifts', {
extend: 'Ext.data.Store',
requires: ['KCS.model.WorkShift'],
config: {
model: 'KCS.model.WorkShift',
autoLoad: true,
storeId: 'WorkShifts',
pageSize: 1000
}
});
Now, in my Controller, i want to see if there is an opened WorkShift (if
the app crashed or was closed without closing the last Workshift.) So i
use the launch callback like this:
launch : function(){
var workShifts = Ext.getStore('WorkShifts');
workShifts.clearFilter(true);
var openedWS = workShifts.findBy( function( record ){
return (record.get("StartDate") != null) &&
(record.get("ClosureDate") == null);
});
if( openedWS != -1 ){
// do stuff when an opened WS is found
}
else{
// do normal stuff
}
},
I did a bunch of tests, First, there is a bunch of valid entries in my
sqLite proxy, and i can create WS from the store and model. There is also
an entry that meets the findBy function filter. I've tried
workShifts.getCount() and even workShifts.getAllCount() but both functions
return 0. What the hell is happening?
Im working on a project with Sencha Touch and the sqLite proxy you can
find here
I have this WorkShift model which is used by WorkShifts store.
Model:
Ext.define('KCS.model.WorkShift', {
extend: 'Ext.data.Model',
config: {
fields: [
{ name: 'id', type: 'int' },
{ name: 'WorkShiftID', type: 'int' },
{ name: 'StartDate', type: 'date' },
{ name: 'ClosureDate', type: 'date' },
],
proxy: {
type: 'sqlitestorage',
dbConfig: {
tablename: 'tbl_WorkShift',
dbConn: KCS.util.InitSQLite.getConnection()
}
}
}
});
And the store:
Ext.define('KCS.store.WorkShifts', {
extend: 'Ext.data.Store',
requires: ['KCS.model.WorkShift'],
config: {
model: 'KCS.model.WorkShift',
autoLoad: true,
storeId: 'WorkShifts',
pageSize: 1000
}
});
Now, in my Controller, i want to see if there is an opened WorkShift (if
the app crashed or was closed without closing the last Workshift.) So i
use the launch callback like this:
launch : function(){
var workShifts = Ext.getStore('WorkShifts');
workShifts.clearFilter(true);
var openedWS = workShifts.findBy( function( record ){
return (record.get("StartDate") != null) &&
(record.get("ClosureDate") == null);
});
if( openedWS != -1 ){
// do stuff when an opened WS is found
}
else{
// do normal stuff
}
},
I did a bunch of tests, First, there is a bunch of valid entries in my
sqLite proxy, and i can create WS from the store and model. There is also
an entry that meets the findBy function filter. I've tried
workShifts.getCount() and even workShifts.getAllCount() but both functions
return 0. What the hell is happening?
Rotate just the text in a CSS button
Rotate just the text in a CSS button
i ve created a css button. I want to rotate the text vertical in button
but just only the text. How can i achieve this. My css button code:
.button_example{
border:1px solid #7d99ca;
-webkit-border-radius: 3px;
display: table-column-group;
/*-webkit-transform: rotate(-90deg); rotate the whole button*/
-moz-border-radius: 3px;
border-radius: 5px;
font-size:22px;
font-family:Impact, Charcoal, sans-serif;
padding: 10px 10px 10px 10px;
text-decoration:none;
display:inline-block;
text-shadow: -1px -1px 0 rgba(0,0,0,0.3);
font-weight:strong;
color: #00a19c;
color: #3388fa;
background: transparent; /* size and positioning*/
margin-left: 121px;
margin-top: 1px;
width: 24px;
height: 485px;
font-size:14px;
font-weight:700;
position:absolute;left:1120px;top:180px;
background-image: linear-gradient(to bottom, #FFFFFF, #FFFFFF);
filter:progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr=#FFFFFF,
endColorstr=#FFFFFF);
}
Any idea how to rotate just the text?
i ve created a css button. I want to rotate the text vertical in button
but just only the text. How can i achieve this. My css button code:
.button_example{
border:1px solid #7d99ca;
-webkit-border-radius: 3px;
display: table-column-group;
/*-webkit-transform: rotate(-90deg); rotate the whole button*/
-moz-border-radius: 3px;
border-radius: 5px;
font-size:22px;
font-family:Impact, Charcoal, sans-serif;
padding: 10px 10px 10px 10px;
text-decoration:none;
display:inline-block;
text-shadow: -1px -1px 0 rgba(0,0,0,0.3);
font-weight:strong;
color: #00a19c;
color: #3388fa;
background: transparent; /* size and positioning*/
margin-left: 121px;
margin-top: 1px;
width: 24px;
height: 485px;
font-size:14px;
font-weight:700;
position:absolute;left:1120px;top:180px;
background-image: linear-gradient(to bottom, #FFFFFF, #FFFFFF);
filter:progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr=#FFFFFF,
endColorstr=#FFFFFF);
}
Any idea how to rotate just the text?
Tuesday, 1 October 2013
Unity: The type InjectionPolicy cannot be constructed.
Unity: The type InjectionPolicy cannot be constructed.
This is a puzzle I've been struggling with for hours. Here's the background:
We use Unity IoC in an MVC4 web app
We have a couple ApiControllers (IHttpController) and a bunch of regular
controllers (IController)
Resolution of the IControllers works fine
Resolution of the IHttpControllers has been working fine for months and
now fails with the a type resolution error having the details "The type
InjectionPolicy cannot be constructed. You must configure the container to
supply this value"
Both the regular and Api controllers take an ICustomerService dependency
which has an ICustomerRepository dependency which in turn has an IClient
dependency, but none of this is new or different.
Removing the ICustomerService dependency from the ApiController solves the
problem (but that interface is clearly configured and working everywhere
else)
We have in place an HttpControllerActivator that is registered in Unity
and is intercepting calls to resolve the IHttpControllers - it fails on
container.Resolve, even though looking into the container, the controller
is clearly there.
I have searched on this particular error and find nothing. Has anyone seen
it before or does it give you any clues as to what might be going on?
Thanks so much!
This is a puzzle I've been struggling with for hours. Here's the background:
We use Unity IoC in an MVC4 web app
We have a couple ApiControllers (IHttpController) and a bunch of regular
controllers (IController)
Resolution of the IControllers works fine
Resolution of the IHttpControllers has been working fine for months and
now fails with the a type resolution error having the details "The type
InjectionPolicy cannot be constructed. You must configure the container to
supply this value"
Both the regular and Api controllers take an ICustomerService dependency
which has an ICustomerRepository dependency which in turn has an IClient
dependency, but none of this is new or different.
Removing the ICustomerService dependency from the ApiController solves the
problem (but that interface is clearly configured and working everywhere
else)
We have in place an HttpControllerActivator that is registered in Unity
and is intercepting calls to resolve the IHttpControllers - it fails on
container.Resolve, even though looking into the container, the controller
is clearly there.
I have searched on this particular error and find nothing. Has anyone seen
it before or does it give you any clues as to what might be going on?
Thanks so much!
Redirect to jQuery Dialog after Action call
Redirect to jQuery Dialog after Action call
I have an asp.net MVC website (Visual Studio 2012, C#) that users can log
into. When they click the "Login" link, it opens a jQuery dialog which
renders a partial login view. I can get the dialog to post to the right
action and controller but I need help with redirecting back to the dialog
screen if the username/password combination is invalid. I already have the
error checking on the Submit button to check if a value exists in both
before proceeding but need help with the other part.
I'll do my best to explain how the website is laid out:
_HeaderPartial View
<header id="header" class="style2">
<link
href="@Url.Content("~/Content/themes/base/minified/jquery-ui.min.css")"
rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-ui-1.8.20.min.js")"
type="text/javascript"></script>
<script type="text/javascript">
var jq = jQuery.noConflict(true);
jq(document).ready(function ($) {
$("#ViewLogin").live("click", function (e) {
var url = $(this).attr('href');
$("#login_panel").dialog({
title: 'Client Login',
closeOnEscape: true,
autoOpen: false,
resizable: false,
height: 350,
width: 400,
show: { effect: 'drop', direction: "up" },
modal: true,
draggable: true,
open: function (event, ui) {
$(this).load(url);
},
close: function (event, ui) {
$(this).dialog('destroy');
}
});
$("#login_panel").dialog('open');
return false;
});
});
</script>
<div class="container">
<!-- logo -->
<h1 id="logo"><a href="@Url.Action("Index", "Home")">
<img src="~/images/small_logo.png" alt="Logo"></a></h1>
<ul class="topnav navRight">
<li> </li>
@if (Session["LoggedIn"] == null ||
Convert.ToBoolean(Session["LoggedIn"])==false)
{
<li><a href="@Url.Action("ViewLogin", "Home")"
id="ViewLogin">LOGIN</a></li>
}
else
{
<li><a href="@Url.Action("LogOut", "Home")">LOGOUT</a></li>
}
</ul>
<other generic html markup omitted>
As you can see, the jQuery opens a dialog when the "Login" link is
clicked, which is a simple div named "login_panel":
_Layout View
<div id="login_panel" style="display: none"></div>
_Login View
@model MyApp.LoginViewModel
@{
Layout = null;
}
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"
type="text/javascript"></script>
<div id="login_panel">
<div class="inner-container login-panel">
<h4>SIGN IN TO ACCESS YOUR ACCOUNT</h4>
@using (Html.BeginForm("Login", "Home", FormMethod.Post))
{
<div class="validation-text">
<h5>@Html.ValidationSummary()</h5>
</div>
<div>
@Html.LabelFor(x => x.Username)
@Html.TextBoxFor(x => x.Username, new { placeholder =
"Username..." })
</div>
<div>
@Html.LabelFor(x => x.Password)
@Html.PasswordFor(x => x.Password, new { placeholder =
"Password..." })
</div>
<br />
<button class="btn btn-danger" type="submit">LOG IN</button>
<div class="links"><a href="#"
onclick="ppOpen('#forgot_panel', '350');">FORGOT YOUR USERNAME
or PASSWORD?</a></div>
}
</div>
</div>
LoginViewModel
public class LoginViewModel
{
[Required(ErrorMessage = "Username is required.")]
public string Username { get; set; }
[Required(ErrorMessage = "Password is required.")]
public string Password { get; set; }
}
And the HomeController
public ActionResult ViewLogin()
{
return View("_Login");
}
public ActionResult LogOut()
{
Session["LoggedIn"] = false;
return RedirectToAction("Index", "Home");
}
[HttpPost]
public ActionResult Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
using (ProPhysiqueContext db = new ProPhysiqueContext())
{
var user = db.Users
.Where(u => u.EmailAddress == model.Username &&
u.WebPassword ==
model.Password).FirstOrDefault();
if (user != null)
{
Session["LoggedIn"] = true;
return RedirectToAction("Index", "ClientStats");
}
}
}
ModelState.AddModelError("", "Invalid Username or Password.");
return PartialView("_Login", model);
}
So as you can see, I can get the dialog to render the _Login partial view
correctly and it will post to the Login action on the Home controller. I
just can't figure out how to reopen the dialog from within the Action. The
way it is now, the website redirects to _Login partial view on the main
page, not in a dialog.
ANY help is appreciated.
I have an asp.net MVC website (Visual Studio 2012, C#) that users can log
into. When they click the "Login" link, it opens a jQuery dialog which
renders a partial login view. I can get the dialog to post to the right
action and controller but I need help with redirecting back to the dialog
screen if the username/password combination is invalid. I already have the
error checking on the Submit button to check if a value exists in both
before proceeding but need help with the other part.
I'll do my best to explain how the website is laid out:
_HeaderPartial View
<header id="header" class="style2">
<link
href="@Url.Content("~/Content/themes/base/minified/jquery-ui.min.css")"
rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-ui-1.8.20.min.js")"
type="text/javascript"></script>
<script type="text/javascript">
var jq = jQuery.noConflict(true);
jq(document).ready(function ($) {
$("#ViewLogin").live("click", function (e) {
var url = $(this).attr('href');
$("#login_panel").dialog({
title: 'Client Login',
closeOnEscape: true,
autoOpen: false,
resizable: false,
height: 350,
width: 400,
show: { effect: 'drop', direction: "up" },
modal: true,
draggable: true,
open: function (event, ui) {
$(this).load(url);
},
close: function (event, ui) {
$(this).dialog('destroy');
}
});
$("#login_panel").dialog('open');
return false;
});
});
</script>
<div class="container">
<!-- logo -->
<h1 id="logo"><a href="@Url.Action("Index", "Home")">
<img src="~/images/small_logo.png" alt="Logo"></a></h1>
<ul class="topnav navRight">
<li> </li>
@if (Session["LoggedIn"] == null ||
Convert.ToBoolean(Session["LoggedIn"])==false)
{
<li><a href="@Url.Action("ViewLogin", "Home")"
id="ViewLogin">LOGIN</a></li>
}
else
{
<li><a href="@Url.Action("LogOut", "Home")">LOGOUT</a></li>
}
</ul>
<other generic html markup omitted>
As you can see, the jQuery opens a dialog when the "Login" link is
clicked, which is a simple div named "login_panel":
_Layout View
<div id="login_panel" style="display: none"></div>
_Login View
@model MyApp.LoginViewModel
@{
Layout = null;
}
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"
type="text/javascript"></script>
<div id="login_panel">
<div class="inner-container login-panel">
<h4>SIGN IN TO ACCESS YOUR ACCOUNT</h4>
@using (Html.BeginForm("Login", "Home", FormMethod.Post))
{
<div class="validation-text">
<h5>@Html.ValidationSummary()</h5>
</div>
<div>
@Html.LabelFor(x => x.Username)
@Html.TextBoxFor(x => x.Username, new { placeholder =
"Username..." })
</div>
<div>
@Html.LabelFor(x => x.Password)
@Html.PasswordFor(x => x.Password, new { placeholder =
"Password..." })
</div>
<br />
<button class="btn btn-danger" type="submit">LOG IN</button>
<div class="links"><a href="#"
onclick="ppOpen('#forgot_panel', '350');">FORGOT YOUR USERNAME
or PASSWORD?</a></div>
}
</div>
</div>
LoginViewModel
public class LoginViewModel
{
[Required(ErrorMessage = "Username is required.")]
public string Username { get; set; }
[Required(ErrorMessage = "Password is required.")]
public string Password { get; set; }
}
And the HomeController
public ActionResult ViewLogin()
{
return View("_Login");
}
public ActionResult LogOut()
{
Session["LoggedIn"] = false;
return RedirectToAction("Index", "Home");
}
[HttpPost]
public ActionResult Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
using (ProPhysiqueContext db = new ProPhysiqueContext())
{
var user = db.Users
.Where(u => u.EmailAddress == model.Username &&
u.WebPassword ==
model.Password).FirstOrDefault();
if (user != null)
{
Session["LoggedIn"] = true;
return RedirectToAction("Index", "ClientStats");
}
}
}
ModelState.AddModelError("", "Invalid Username or Password.");
return PartialView("_Login", model);
}
So as you can see, I can get the dialog to render the _Login partial view
correctly and it will post to the Login action on the Home controller. I
just can't figure out how to reopen the dialog from within the Action. The
way it is now, the website redirects to _Login partial view on the main
page, not in a dialog.
ANY help is appreciated.
Check bluez version on Ubuntu 12.04
Check bluez version on Ubuntu 12.04
I am using 12.04 on my machine. I want to check which version of bluez
right now my machine using. How to check that.
I am using 12.04 on my machine. I want to check which version of bluez
right now my machine using. How to check that.
bijective correspondence involing homomorphsims to a direct product of groups?
bijective correspondence involing homomorphsims to a direct product of
groups?
Let $G$, $G'$ and $H$ be groups. Establish a bijective correspondence
between homomorphisms $\Phi: H \to G \times G'$ from $H$ to the product
group and pairs $(\varphi, \varphi')$ consisting of a homomorphism
$\varphi: H \to G$ and a homomorphism $\varphi': H \to G'$.
I am confused as to what a bijective correspondence is referring to in
this context.
groups?
Let $G$, $G'$ and $H$ be groups. Establish a bijective correspondence
between homomorphisms $\Phi: H \to G \times G'$ from $H$ to the product
group and pairs $(\varphi, \varphi')$ consisting of a homomorphism
$\varphi: H \to G$ and a homomorphism $\varphi': H \to G'$.
I am confused as to what a bijective correspondence is referring to in
this context.
Monday, 30 September 2013
Extracting a zip file in my machne givs me CRC error?
Extracting a zip file in my machne givs me CRC error?
I have a large zip that contain hundreds of file. I've unzip'ed it in more
than one machine and didn't have any problem before. However, for this
particular machine (Ubuntu Server 12.04) I keep getting CRC error for some
of the files inside my zip. I've unzip'ed the same file it on anther
machine just to and its fine.
Any clue?
I have a large zip that contain hundreds of file. I've unzip'ed it in more
than one machine and didn't have any problem before. However, for this
particular machine (Ubuntu Server 12.04) I keep getting CRC error for some
of the files inside my zip. I've unzip'ed the same file it on anther
machine just to and its fine.
Any clue?
How to stop reusing uitableviewCell?
How to stop reusing uitableviewCell?
Hi in my app i have to load images to UITableViewCell .which are coming
from the server.so the problem is when ever i scroll the tableview images
are loading every time and its loading lazy so i tried to stop reusing
cells but its not working ,How to stop reusing the cells in UITableView.
my code is
-(UITableViewCell*)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier=@"Cell";
RestaurantCustomCell *cell =(RestaurantCustomCell*) [tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
NSArray *topLevelObjects ;
topLevelObjects= [[NSArray alloc]init];
if(cell==nil)
{
topLevelObjects = [[NSBundle mainBundle]
loadNibNamed:@"RestaurantCustomCell" owner:self options:nil];
for(id currentObject in topLevelObjects)
{
if([currentObject isKindOfClass:[UITableViewCell class]])
{
cell = (RestaurantCustomCell *) currentObject;
break;
}
}
}
NSDictionary *dict=[restauarantsArr objectAtIndex:indexPath.row];
NSString *imgStr=[dict valueForKey:@"Img"];
[self processImageDataWithURLString:imgStr andBlock:^(NSData *imageData) {
if (self.view.window)
{
UIImage *img = [UIImage imageWithData:imageData];
if(img!=nil)
{
UIGraphicsBeginImageContext(CGSizeMake(100, 100));
[img drawInRect:CGRectMake(0,0,100,100)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
cell.restaurantImg.image=newImage;
UIGraphicsEndImageContext();
}
}
}];
cell.nameLbl.text=[dict valueForKey:@"Restaurants"];
cell.typeLbl.text=[dict valueForKey:@"Rest_Cuisine"];
cell.timingsLbl.text=[dict valueForKey:@"Rest_Timings"];
cell.categoryLbl.text=[dict valueForKey:@"Rest_Category"];
cell.addressLbl.text=[dict valueForKey:@"Address"];
return cell;
}
Hi in my app i have to load images to UITableViewCell .which are coming
from the server.so the problem is when ever i scroll the tableview images
are loading every time and its loading lazy so i tried to stop reusing
cells but its not working ,How to stop reusing the cells in UITableView.
my code is
-(UITableViewCell*)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier=@"Cell";
RestaurantCustomCell *cell =(RestaurantCustomCell*) [tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
NSArray *topLevelObjects ;
topLevelObjects= [[NSArray alloc]init];
if(cell==nil)
{
topLevelObjects = [[NSBundle mainBundle]
loadNibNamed:@"RestaurantCustomCell" owner:self options:nil];
for(id currentObject in topLevelObjects)
{
if([currentObject isKindOfClass:[UITableViewCell class]])
{
cell = (RestaurantCustomCell *) currentObject;
break;
}
}
}
NSDictionary *dict=[restauarantsArr objectAtIndex:indexPath.row];
NSString *imgStr=[dict valueForKey:@"Img"];
[self processImageDataWithURLString:imgStr andBlock:^(NSData *imageData) {
if (self.view.window)
{
UIImage *img = [UIImage imageWithData:imageData];
if(img!=nil)
{
UIGraphicsBeginImageContext(CGSizeMake(100, 100));
[img drawInRect:CGRectMake(0,0,100,100)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
cell.restaurantImg.image=newImage;
UIGraphicsEndImageContext();
}
}
}];
cell.nameLbl.text=[dict valueForKey:@"Restaurants"];
cell.typeLbl.text=[dict valueForKey:@"Rest_Cuisine"];
cell.timingsLbl.text=[dict valueForKey:@"Rest_Timings"];
cell.categoryLbl.text=[dict valueForKey:@"Rest_Category"];
cell.addressLbl.text=[dict valueForKey:@"Address"];
return cell;
}
JavaScript onkeypress delayed trigger
JavaScript onkeypress delayed trigger
I have an html input for an optional phone number, along with 2 radio
inputs (Leave Message, Dont Leave Message):
<input type="text" class="input-medium phoneNum2" name="secondaryPhone"
id="secondaryPhone" onkeypress="toggleRadio(this)"
onblur="toggleRadio(this)" placeholder="703-555-1010"
value="<cfoutput>#session.secondaryPhone#</cfoutput>" />
Notice I have two events running (deleting one of them yields the same
issue, having both helps out, but I'd rather have only 1 event unless
necessary).
The scenario here is: The second somebody starts typing into the input, it
checks to see if one of the radio buttons is already checked. If not,
default select yes. If for some reason they delete the phone number as
they do not want to give it, both radio buttons should be de-selected
(only the onblur works there). And if the "Don't Leave Message" is
selected BEFORE the user starts typing, it should not default to yes.
Here is the JavaScript:
function toggleRadio(x) {
y = document.getElementById("contactSecondaryYes");
z = document.getElementById("contactSecondaryNo");
if (x.value.length < 1) {
y.checked = false;
z.checked = false;
}
if (x.value.length > 0 && !z.checked) y.checked = true;
}
Now for the issue: The default option yes is only triggered when I type in
2 characters, instead of the desired 1 (almost like a delay in the code?).
If I have "No" Selected before I start typing, it defaults to yes once I
type in the 2 characters. Likewise for reverse, nothing is "de-selected"
when there are 0 characters during the onkeypress event, only when the
input loses focus during the onblur event.
Am I using the wrong events? Is there a logic flaw? There are no error
messages, and no, I cannot use jQuery here, so please don't give me jQuery
answers or the usual "Why no jQuery?" (I love jQuery I simply have reasons
I cannot use it).
Edit: I also tried ordering the JavaScript like this, to no avail.
function toggleRadio(x) {
y = document.getElementById("contactSecondaryYes");
z = document.getElementById("contactSecondaryNo");
if (x.value.length > 0 && !z.checked) y.checked = true;
if (x.value.length < 1) {
y.checked = false;
z.checked = false;
}
}
Basically I want to know why the code is acting like there is a delay, and
is there a way to fix it?
I have an html input for an optional phone number, along with 2 radio
inputs (Leave Message, Dont Leave Message):
<input type="text" class="input-medium phoneNum2" name="secondaryPhone"
id="secondaryPhone" onkeypress="toggleRadio(this)"
onblur="toggleRadio(this)" placeholder="703-555-1010"
value="<cfoutput>#session.secondaryPhone#</cfoutput>" />
Notice I have two events running (deleting one of them yields the same
issue, having both helps out, but I'd rather have only 1 event unless
necessary).
The scenario here is: The second somebody starts typing into the input, it
checks to see if one of the radio buttons is already checked. If not,
default select yes. If for some reason they delete the phone number as
they do not want to give it, both radio buttons should be de-selected
(only the onblur works there). And if the "Don't Leave Message" is
selected BEFORE the user starts typing, it should not default to yes.
Here is the JavaScript:
function toggleRadio(x) {
y = document.getElementById("contactSecondaryYes");
z = document.getElementById("contactSecondaryNo");
if (x.value.length < 1) {
y.checked = false;
z.checked = false;
}
if (x.value.length > 0 && !z.checked) y.checked = true;
}
Now for the issue: The default option yes is only triggered when I type in
2 characters, instead of the desired 1 (almost like a delay in the code?).
If I have "No" Selected before I start typing, it defaults to yes once I
type in the 2 characters. Likewise for reverse, nothing is "de-selected"
when there are 0 characters during the onkeypress event, only when the
input loses focus during the onblur event.
Am I using the wrong events? Is there a logic flaw? There are no error
messages, and no, I cannot use jQuery here, so please don't give me jQuery
answers or the usual "Why no jQuery?" (I love jQuery I simply have reasons
I cannot use it).
Edit: I also tried ordering the JavaScript like this, to no avail.
function toggleRadio(x) {
y = document.getElementById("contactSecondaryYes");
z = document.getElementById("contactSecondaryNo");
if (x.value.length > 0 && !z.checked) y.checked = true;
if (x.value.length < 1) {
y.checked = false;
z.checked = false;
}
}
Basically I want to know why the code is acting like there is a delay, and
is there a way to fix it?
Cannot git clone android source code from remote server
Cannot git clone android source code from remote server
Firstly I
$ git clone https://android.googlesource.com/platform/frameworks/base
Cloning into 'base'...
remote: Sending approximately 1.04 GiB ...
remote: Counting objects: 43200, done
remote: Finding sources: 100% (3713/3713)
remote: Getting sizes: 100% (1738/1738)
remote: Compressing objects: 99% (27152/27153)
Receiving objects: 4% (36212/787666), 16.81 MiB | 183 KiB/s
For a while, the git hung and didn't go ahead, So I break git and
$ git clone http://android.googlesource.com/platform/frameworks/base
Cloning into 'base'...
remote: Sending approximately 1.04 GiB ...
remote: Counting objects: 43200, done
remote: Finding sources: 100% (3713/3713)
remote: Getting sizes: 100% (1738/1738)
remote: Compressing objects: 99% (27152/27153)
error: RPC failed; result=56, HTTP code = 20075 MiB | 186 KiB/s
fatal: The remote end hung up unexpectedly
fatal: early EOF
fatal: index-pack failed
Now it failed as above, I tried several times and every time got same
error as above.
How to resolve or workaround?
Firstly I
$ git clone https://android.googlesource.com/platform/frameworks/base
Cloning into 'base'...
remote: Sending approximately 1.04 GiB ...
remote: Counting objects: 43200, done
remote: Finding sources: 100% (3713/3713)
remote: Getting sizes: 100% (1738/1738)
remote: Compressing objects: 99% (27152/27153)
Receiving objects: 4% (36212/787666), 16.81 MiB | 183 KiB/s
For a while, the git hung and didn't go ahead, So I break git and
$ git clone http://android.googlesource.com/platform/frameworks/base
Cloning into 'base'...
remote: Sending approximately 1.04 GiB ...
remote: Counting objects: 43200, done
remote: Finding sources: 100% (3713/3713)
remote: Getting sizes: 100% (1738/1738)
remote: Compressing objects: 99% (27152/27153)
error: RPC failed; result=56, HTTP code = 20075 MiB | 186 KiB/s
fatal: The remote end hung up unexpectedly
fatal: early EOF
fatal: index-pack failed
Now it failed as above, I tried several times and every time got same
error as above.
How to resolve or workaround?
Sunday, 29 September 2013
Apperently Simple Puzzle
Apperently Simple Puzzle
So a picture appeared on FB asking for the answer to the picture below, to
which many people responded "14".
Everywhere I looked, people answered 14. However, I stood out because I
was the only one who said that the answer is 11.25.
The problem can be represented algebraically like this:
4x = 5
x = 1.25
9x = ?
9(1.25) = 11.25
So my question is..how the heck did people get 14? Am I using the wrong
approach?
So a picture appeared on FB asking for the answer to the picture below, to
which many people responded "14".
Everywhere I looked, people answered 14. However, I stood out because I
was the only one who said that the answer is 11.25.
The problem can be represented algebraically like this:
4x = 5
x = 1.25
9x = ?
9(1.25) = 11.25
So my question is..how the heck did people get 14? Am I using the wrong
approach?
"Yum Update" reinstalling removed packages
"Yum Update" reinstalling removed packages
On my Fedora 19 system, yum update attempts to reinstall a large number
packages I have previously removed. This should not happen, as the
packages listed are not installed and should not be suggested by yum. How
can I make yum work in the expected manner - with updates suggesting only
upgrades to preinstalled packages.
Background: I have been trying out new DEs - installing and removing them
as I go. Currently, I'm in a DE-less state, booting directly into a tty
terminal. My system has no (or a few hidden) xfce or cinnamon packages to
"upgrade", yet the package manager is suggesting 300 packages to install,
totaling 600M of new install.
On my Fedora 19 system, yum update attempts to reinstall a large number
packages I have previously removed. This should not happen, as the
packages listed are not installed and should not be suggested by yum. How
can I make yum work in the expected manner - with updates suggesting only
upgrades to preinstalled packages.
Background: I have been trying out new DEs - installing and removing them
as I go. Currently, I'm in a DE-less state, booting directly into a tty
terminal. My system has no (or a few hidden) xfce or cinnamon packages to
"upgrade", yet the package manager is suggesting 300 packages to install,
totaling 600M of new install.
Wrong resource folder being chosen by Android system
Wrong resource folder being chosen by Android system
I've been having problems with my app on a 7 inch device. For debugging
purposes I've added a toast message that displays after the app loads, to
tell me which resource folder the app is using, ie. which qualifiers. I
have strings.xml files in each of the following resource folders:
values
values-normal
values-large
values-xlarge
values-sw600dp
values-sw720dp
The content of the string used by the toast message is based on the folder
in which the string is located. I also have six layout folders with the
same qualifiers as above, and I have valid layout xml files in all six of
the layout folders. My app works perfectly on 'normal' screens and 10 inch
tablet screens.
The troublesome 7 inch device (my mate's) is a cheap 'Audiosonic' running
Android 4.1.1. Apparently the resolution is 800x480, and the physical
smallest width of the screen is 86mm, or 3.4 inches. This means 142dpi.
Given the equation dp = (pixels x 160) / dpi The smallest width should be
541dp.
Now here comes the crazy part, and my question...why on earth are the
sw720dp resources being used by my app on this 7 inch device?!
I've been having problems with my app on a 7 inch device. For debugging
purposes I've added a toast message that displays after the app loads, to
tell me which resource folder the app is using, ie. which qualifiers. I
have strings.xml files in each of the following resource folders:
values
values-normal
values-large
values-xlarge
values-sw600dp
values-sw720dp
The content of the string used by the toast message is based on the folder
in which the string is located. I also have six layout folders with the
same qualifiers as above, and I have valid layout xml files in all six of
the layout folders. My app works perfectly on 'normal' screens and 10 inch
tablet screens.
The troublesome 7 inch device (my mate's) is a cheap 'Audiosonic' running
Android 4.1.1. Apparently the resolution is 800x480, and the physical
smallest width of the screen is 86mm, or 3.4 inches. This means 142dpi.
Given the equation dp = (pixels x 160) / dpi The smallest width should be
541dp.
Now here comes the crazy part, and my question...why on earth are the
sw720dp resources being used by my app on this 7 inch device?!
How to get the value of radio button in Zend Form
How to get the value of radio button in Zend Form
This is my form, I have a radio button from 1 to 5 (very bad to very good)
parent::__construct($name);
$this->setAttribute('method', 'post');
$this->add(array(
'type' => 'Zend\Form\Element\Radio',
'name' => 'rate_box',
'options' => array(
'label' => 'Please choose your rate',
'value_options' => array(
'1' => ' Very Bad',
'2' => ' Bad',
'3' => ' Fine',
'4' => ' Good',
'5' => ' Very Good',
),
),
'attributes' => array(
'value' => '1' //set checked to '1'
)
));
$this->add(array(
'name' => 'submit',
'type' => 'Submit',
'attributes' => array(
'id' => 'submit',
'class' => 'btn btn-primary',
),
));
This is the related part of my controller
$form = new VoteForm();
$request = $this->getRequest();
if ($request->isPost())
{
$form->setData($request->getPost());
if ($form->isValid())
{
$formdata = $form->getData();
$vote = new Vote();
$data = $vote->getArrayCopy();
$data['user_id'] = $user_id;
$data['voted_user_id'] = $voted_user_id;
$data['ratescore'] = $formdata['rate_box']; //Here I take
the value of radion button
$vote->populate($data);
try
{
$this->getEntityManager()->persist($vote);
$this->getEntityManager()->flush();
return
$this->redirect()->toRoute('home',array('user_id' =>
$user_id,
'action' =>
'home',
));
}
catch(DBALException $e){
}
}
}
Why I can't retrieve the value of "rate_box" and save to my
$data['ratescore']? Thank you!
This is my form, I have a radio button from 1 to 5 (very bad to very good)
parent::__construct($name);
$this->setAttribute('method', 'post');
$this->add(array(
'type' => 'Zend\Form\Element\Radio',
'name' => 'rate_box',
'options' => array(
'label' => 'Please choose your rate',
'value_options' => array(
'1' => ' Very Bad',
'2' => ' Bad',
'3' => ' Fine',
'4' => ' Good',
'5' => ' Very Good',
),
),
'attributes' => array(
'value' => '1' //set checked to '1'
)
));
$this->add(array(
'name' => 'submit',
'type' => 'Submit',
'attributes' => array(
'id' => 'submit',
'class' => 'btn btn-primary',
),
));
This is the related part of my controller
$form = new VoteForm();
$request = $this->getRequest();
if ($request->isPost())
{
$form->setData($request->getPost());
if ($form->isValid())
{
$formdata = $form->getData();
$vote = new Vote();
$data = $vote->getArrayCopy();
$data['user_id'] = $user_id;
$data['voted_user_id'] = $voted_user_id;
$data['ratescore'] = $formdata['rate_box']; //Here I take
the value of radion button
$vote->populate($data);
try
{
$this->getEntityManager()->persist($vote);
$this->getEntityManager()->flush();
return
$this->redirect()->toRoute('home',array('user_id' =>
$user_id,
'action' =>
'home',
));
}
catch(DBALException $e){
}
}
}
Why I can't retrieve the value of "rate_box" and save to my
$data['ratescore']? Thank you!
Saturday, 28 September 2013
extended initializer lists being seen as functions
extended initializer lists being seen as functions
I'm trying to compile an opensource project but I'm getting this problem
from g++
error: function definition does not declare parameters
the code is something like this
#include <iostream>
namespace hi {
class hello {
public:
bool first { true };
};
}
int main(int argc, char *argv[])
{
hi::hello h
std::cout << "output: " << h.first << std::endl;
return 0;
}
which produces the same compilation problem as the code of the opensource
project when compiled with
g++ -O2 bools.cpp -o bools -std=c++0x
however if I try to compile this code with the same options it compiles
and runs as it should
#include <iostream>
int main(int argc, char *argv[])
{
bool value { true };
std::cout << "output: " << value << std::endl;
return 0;
}
I'm using g++ 4.6.3 on Ubuntu 64bit.
thanks for your time.
I'm trying to compile an opensource project but I'm getting this problem
from g++
error: function definition does not declare parameters
the code is something like this
#include <iostream>
namespace hi {
class hello {
public:
bool first { true };
};
}
int main(int argc, char *argv[])
{
hi::hello h
std::cout << "output: " << h.first << std::endl;
return 0;
}
which produces the same compilation problem as the code of the opensource
project when compiled with
g++ -O2 bools.cpp -o bools -std=c++0x
however if I try to compile this code with the same options it compiles
and runs as it should
#include <iostream>
int main(int argc, char *argv[])
{
bool value { true };
std::cout << "output: " << value << std::endl;
return 0;
}
I'm using g++ 4.6.3 on Ubuntu 64bit.
thanks for your time.
"An unknown error occurred" when logging in in Visual Studio 2013 SPA template on IIS8 express
"An unknown error occurred" when logging in in Visual Studio 2013 SPA
template on IIS8 express
I have used the SPA template in VS2013 and try to host it in IIS8 on Win8.
When I try to Log In in the Todo list I get a An unknown error occurred.
When I run the solution in VS2013 (preview v.12.0.20623.01 update) through
the development webserver it runs alright.
But I want to use the real IIS and hence created an application in
IIS8express for the same folder.
When I try to register or log in to the todo list I get the error above.
Running aspnet development on the IIS is no problem, I have done it for
years.
Looking through the code it looks like it has something to do with the
Identity providers, like the code cannot enumerate them when running in
IIS. I just can't get my head around it.
template on IIS8 express
I have used the SPA template in VS2013 and try to host it in IIS8 on Win8.
When I try to Log In in the Todo list I get a An unknown error occurred.
When I run the solution in VS2013 (preview v.12.0.20623.01 update) through
the development webserver it runs alright.
But I want to use the real IIS and hence created an application in
IIS8express for the same folder.
When I try to register or log in to the todo list I get the error above.
Running aspnet development on the IIS is no problem, I have done it for
years.
Looking through the code it looks like it has something to do with the
Identity providers, like the code cannot enumerate them when running in
IIS. I just can't get my head around it.
show value percentages in excel pivot table
show value percentages in excel pivot table
I have this data table and created the pivot table underneath it. How can
I get the pivot table to show data like table no.3 , or even change values
to percentages even better
I have this data table and created the pivot table underneath it. How can
I get the pivot table to show data like table no.3 , or even change values
to percentages even better
JNDI requires JDK?
JNDI requires JDK?
I try to configure Oracle datesource for Tomcat6 from SUSE Linux
Enterprise Server. I add datasource to context.xml file:
<Resource
name="jdbc/UCPPool"
auth="Container"
factory="oracle.ucp.jdbc.PoolDataSourceImpl"
type="oracle.ucp.jdbc.PoolDataSource"
description="Pas testing UCP Pool in Tomcat"
connectionFactoryClassName="oracle.jdbc.pool.OracleDataSource"
minPoolSize="2"
maxPoolSize="5"
inactiveConnectionTimeout="20"
user="scott"
password="tiger"
url="jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)
(HOST=beast.au.oracle.com)(PORT=1523))(CONNECT_DATA=
(SERVICE_NAME=linux11gr2)))"
connectionPoolName="UCPPool"
validateConnectionOnBorrow="true"
sqlForValidateConnection="select 1 from DUAL" />
In my application in persistence.xml add non-jta-data-source property. But
each time when I want to start application, tomcat throw this exception:
Caused by: org.hibernate.service.jndi.JndiException: Unable to lookup
JNDI name [java:comp/env/jdbc/nameDB]
at
org.hibernate.service.jndi.internal.JndiServiceImpl.locate(JndiServiceImpl.java:68)
at
org.hibernate.service.jdbc.connections.internal.DatasourceConnectionProviderImpl.configure(DatasourceConnectionProviderImpl.java:116)
at
org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:75)
at
org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:159)
at
org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:131)
at
org.hibernate.engine.jdbc.internal.JdbcServicesImpl.buildJdbcConnectionAccess(JdbcServicesImpl.java:223)
at
org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:89)
at
org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:75)
at
org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:159)
at
org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:131)
at
org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:78)
at
org.hibernate.cfg.Configuration.buildSettingsInternal(Configuration.java:2283)
at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2279)
at
org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1748)
at
org.hibernate.ejb.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:94)
at
org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:920)
... 28 more
Caused by: javax.naming.NamingException: This context must be accessed
throught a java: URL
org.hibernate.service.jndi.internal.JndiServiceImpl.locate(JndiServiceImpl.java:65)
I tried the same configuration on OpenSuse and there it works. The only
difference I found is that SLSE has installed JAVA SE form IBM and
openSUSE use OpenJDK java as a defualt.
So JNDI require JDK or it is some bug in IBM java implmenetation?
I try to configure Oracle datesource for Tomcat6 from SUSE Linux
Enterprise Server. I add datasource to context.xml file:
<Resource
name="jdbc/UCPPool"
auth="Container"
factory="oracle.ucp.jdbc.PoolDataSourceImpl"
type="oracle.ucp.jdbc.PoolDataSource"
description="Pas testing UCP Pool in Tomcat"
connectionFactoryClassName="oracle.jdbc.pool.OracleDataSource"
minPoolSize="2"
maxPoolSize="5"
inactiveConnectionTimeout="20"
user="scott"
password="tiger"
url="jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)
(HOST=beast.au.oracle.com)(PORT=1523))(CONNECT_DATA=
(SERVICE_NAME=linux11gr2)))"
connectionPoolName="UCPPool"
validateConnectionOnBorrow="true"
sqlForValidateConnection="select 1 from DUAL" />
In my application in persistence.xml add non-jta-data-source property. But
each time when I want to start application, tomcat throw this exception:
Caused by: org.hibernate.service.jndi.JndiException: Unable to lookup
JNDI name [java:comp/env/jdbc/nameDB]
at
org.hibernate.service.jndi.internal.JndiServiceImpl.locate(JndiServiceImpl.java:68)
at
org.hibernate.service.jdbc.connections.internal.DatasourceConnectionProviderImpl.configure(DatasourceConnectionProviderImpl.java:116)
at
org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:75)
at
org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:159)
at
org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:131)
at
org.hibernate.engine.jdbc.internal.JdbcServicesImpl.buildJdbcConnectionAccess(JdbcServicesImpl.java:223)
at
org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:89)
at
org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:75)
at
org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:159)
at
org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:131)
at
org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:78)
at
org.hibernate.cfg.Configuration.buildSettingsInternal(Configuration.java:2283)
at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2279)
at
org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1748)
at
org.hibernate.ejb.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:94)
at
org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:920)
... 28 more
Caused by: javax.naming.NamingException: This context must be accessed
throught a java: URL
org.hibernate.service.jndi.internal.JndiServiceImpl.locate(JndiServiceImpl.java:65)
I tried the same configuration on OpenSuse and there it works. The only
difference I found is that SLSE has installed JAVA SE form IBM and
openSUSE use OpenJDK java as a defualt.
So JNDI require JDK or it is some bug in IBM java implmenetation?
Friday, 27 September 2013
Android - Save to a text file
Android - Save to a text file
I am trying to write text to a file but i cant seem to get it to work.
public static void saveState(){
String data = age + "," ;
FileOutputStream fos;
Context con = getApplicationContext();
try {
fos = con.openFileOutput("state", 0);
OutputStreamWriter outputStreamWriter = new
OutputStreamWriter(fos);
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
I have looked around and it seems i cant call openFileOutput() with out
the context but have no idea "Context con = getApplicationContext()" will
not work. it just tells me that getapplicationcontext is undefined for the
type. Can anyone help me out here?
I am trying to write text to a file but i cant seem to get it to work.
public static void saveState(){
String data = age + "," ;
FileOutputStream fos;
Context con = getApplicationContext();
try {
fos = con.openFileOutput("state", 0);
OutputStreamWriter outputStreamWriter = new
OutputStreamWriter(fos);
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
I have looked around and it seems i cant call openFileOutput() with out
the context but have no idea "Context con = getApplicationContext()" will
not work. it just tells me that getapplicationcontext is undefined for the
type. Can anyone help me out here?
How can i hide the form1 ? I want that the icon of the form only will be show in the taskbar in the bottom
How can i hide the form1 ? I want that the icon of the form only will be
show in the taskbar in the bottom
public Form1()
{
InitializeComponent();
this.Visible = false;
}
Didn't work so I tried this.Hide();, also didn't work. What am I missing ?
show in the taskbar in the bottom
public Form1()
{
InitializeComponent();
this.Visible = false;
}
Didn't work so I tried this.Hide();, also didn't work. What am I missing ?
Matlab Plot 3d axis on a specifi point
Matlab Plot 3d axis on a specifi point
I want to plot the axis x,y,z as vectors from a specific point.x will
be(+-1,0,0) (if the point was the origin)y=(0,+-1,0) and z(0,0,+-1).How
can i plot them with different colors in an figure tha already contains
some informations
To be specific i have an animated 3D skeleton and i want to have the axes
showed in the root of the skeleton.
furthermore if anyone knows how to plot a plane in the same animated 3D
skeleton!i want the plane to be as a disc
Thanks in advance for any response
I want to plot the axis x,y,z as vectors from a specific point.x will
be(+-1,0,0) (if the point was the origin)y=(0,+-1,0) and z(0,0,+-1).How
can i plot them with different colors in an figure tha already contains
some informations
To be specific i have an animated 3D skeleton and i want to have the axes
showed in the root of the skeleton.
furthermore if anyone knows how to plot a plane in the same animated 3D
skeleton!i want the plane to be as a disc
Thanks in advance for any response
UIImageView is not updating
UIImageView is not updating
Hi iam using following code for loading image to uiimageview its working
when i loading that UIviewcontroller but if i open any other
uiviewcontroller from the existing one and came back to the old
uiviewcontroller and if i click a thumnail image its not not updating
UIimageview uiviewcontroller.
img contains image path (inside device) in viewdidload
[self setBookimage:img];
in setBookimage()
- (void)setBookImage:(UIImage *)bookImage{
book_cover_image.image=nil;
book_cover_image.image = bookImage;
CATransition *transition = [CATransition animation];
transition.duration = 1.0f;
transition.timingFunction = [CAMediaTimingFunction
functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.type = kCATransitionFade;
[book_cover_image.layer addAnimation:transition forKey:nil];
}
Hi iam using following code for loading image to uiimageview its working
when i loading that UIviewcontroller but if i open any other
uiviewcontroller from the existing one and came back to the old
uiviewcontroller and if i click a thumnail image its not not updating
UIimageview uiviewcontroller.
img contains image path (inside device) in viewdidload
[self setBookimage:img];
in setBookimage()
- (void)setBookImage:(UIImage *)bookImage{
book_cover_image.image=nil;
book_cover_image.image = bookImage;
CATransition *transition = [CATransition animation];
transition.duration = 1.0f;
transition.timingFunction = [CAMediaTimingFunction
functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.type = kCATransitionFade;
[book_cover_image.layer addAnimation:transition forKey:nil];
}
Amazon s3 Metadata Tags
Amazon s3 Metadata Tags
I am trying to get my s3 bucket to serve gzipped assets as opposed to the
minified versions.
I have precompiled my assets, a gzip version has been created, all i need
to do know is serve it.
After reading some guides and blogs it seems i need to add
Content-Type text/html
Content-Encoding gzip
When i am in my s3 bucket management screen i should be able to find
metadata within properties, but it is not there...
Can i set this configuration in the CORS properties?
Does anyone know why this could be?
I am trying to get my s3 bucket to serve gzipped assets as opposed to the
minified versions.
I have precompiled my assets, a gzip version has been created, all i need
to do know is serve it.
After reading some guides and blogs it seems i need to add
Content-Type text/html
Content-Encoding gzip
When i am in my s3 bucket management screen i should be able to find
metadata within properties, but it is not there...
Can i set this configuration in the CORS properties?
Does anyone know why this could be?
How to rename order status in frontend in magento?
How to rename order status in frontend in magento?
I need to rename order status in magento only for customers.
For exmaple:
Customer`s order has a status "fraud". In frontend(for cusntomer) it
should be displayed as "Open", but in backand it should stay "Suspected
fraud"
I use Magento 1.7. Thanks
I need to rename order status in magento only for customers.
For exmaple:
Customer`s order has a status "fraud". In frontend(for cusntomer) it
should be displayed as "Open", but in backand it should stay "Suspected
fraud"
I use Magento 1.7. Thanks
Thursday, 26 September 2013
Pad - How to detect that multitasking gestures are disable in xcode 5?
Pad - How to detect that multitasking gestures are disable in xcode 5?
1.Disable Multitasking Gesture in ios 7 in my app not from setting screen
2.Is there any way so that Ican disable this feature for my app.?
1.Disable Multitasking Gesture in ios 7 in my app not from setting screen
2.Is there any way so that Ican disable this feature for my app.?
Wednesday, 25 September 2013
get values from href link using jquery
get values from href link using jquery
I have to split values from href link.
my href link as follows
var val =location.href // outputs
http://localhost:8080/index.html?username=test@gmail.com&joid=68
i want to get username value and joid value separately.
I tried following but not working
var emailrogh= val.split("&");
email=emailrogh[0];
var idrough=emailrogh[1].split("=");
var id=idrough[1];
how can i extract test@gmail.com and 68
I have to split values from href link.
my href link as follows
var val =location.href // outputs
http://localhost:8080/index.html?username=test@gmail.com&joid=68
i want to get username value and joid value separately.
I tried following but not working
var emailrogh= val.split("&");
email=emailrogh[0];
var idrough=emailrogh[1].split("=");
var id=idrough[1];
how can i extract test@gmail.com and 68
Thursday, 19 September 2013
xwindows working but not unity desktop
xwindows working but not unity desktop
I'm running Ubuntu 13.04 64 bit w/ unity desktop
What I'm experiencing: When I turn on my computer, the Ubuntu loading
screen appears but disappears in wake of a shell which I can log into.
Once logged in, I can start Unity via sudo start lightdm and subsequently
login via unity gui.
However, the desktop software doesnt seem to be running. There is now
tool-bar/menu-thing. I cannot use Alt+Tab to cycle between open windows,
and I cannot restore windows which I minimize.
In every respect, I would have the same experience issuing sudo startx
from an xterminal. I have reinstalled unity to no avail. installation
seems to go just fine.
Any ideas on where I might go about addressing this problem? Thanks
I'm running Ubuntu 13.04 64 bit w/ unity desktop
What I'm experiencing: When I turn on my computer, the Ubuntu loading
screen appears but disappears in wake of a shell which I can log into.
Once logged in, I can start Unity via sudo start lightdm and subsequently
login via unity gui.
However, the desktop software doesnt seem to be running. There is now
tool-bar/menu-thing. I cannot use Alt+Tab to cycle between open windows,
and I cannot restore windows which I minimize.
In every respect, I would have the same experience issuing sudo startx
from an xterminal. I have reinstalled unity to no avail. installation
seems to go just fine.
Any ideas on where I might go about addressing this problem? Thanks
Duplicates in JSP's include directive
Duplicates in JSP's include directive
This code is not real, but is simpler and show the problem
Suppose that I have First File named Base.jsp
<%!
class Base{
public String Parm0 = "";
public String Parm1 = "";
}
javax.servlet.jsp.JspWriter Out;
void PrintMessage(String Msg){
try {
Out.print("<P style=\"color:rgb(255,0,0)\">"+Msg+"</P>");
}
catch (Exception e) {}
}
%>
Now I have a Second File that use the base file: Fil0.jsp
<%@ include file="Base.jsp" %>
<%!
class File0 {
public Base MyBase;
File0 () {
MyBase = new Base();
PrintMessage("Based Used!!");
}
%>
Now I have a Third File that use the base file: Fil1.jsp
<%@ include file="Base.jsp" %>
<%@ include file="Fil0.jsp" %>
<%!
class Fil1 {
public Base MyBase;
public Fil0 MyFil0;
File0 () {
MyBase = new Base();
MyFil0 = new Fil0();
PrintMessage("Based and Fil0 Created!!");
}
%>
As you can see... this code will produce messages like:
Duplicate field Fil1_jsp.Out
Duplicate method PrintMessage(String) in type Fil1_jsp
How solve this error Before I need to include Base in two files: File0 and
File1. And File1 have Base and File0...
The compiler find two declarations...
This code is not real, but is simpler and show the problem
Suppose that I have First File named Base.jsp
<%!
class Base{
public String Parm0 = "";
public String Parm1 = "";
}
javax.servlet.jsp.JspWriter Out;
void PrintMessage(String Msg){
try {
Out.print("<P style=\"color:rgb(255,0,0)\">"+Msg+"</P>");
}
catch (Exception e) {}
}
%>
Now I have a Second File that use the base file: Fil0.jsp
<%@ include file="Base.jsp" %>
<%!
class File0 {
public Base MyBase;
File0 () {
MyBase = new Base();
PrintMessage("Based Used!!");
}
%>
Now I have a Third File that use the base file: Fil1.jsp
<%@ include file="Base.jsp" %>
<%@ include file="Fil0.jsp" %>
<%!
class Fil1 {
public Base MyBase;
public Fil0 MyFil0;
File0 () {
MyBase = new Base();
MyFil0 = new Fil0();
PrintMessage("Based and Fil0 Created!!");
}
%>
As you can see... this code will produce messages like:
Duplicate field Fil1_jsp.Out
Duplicate method PrintMessage(String) in type Fil1_jsp
How solve this error Before I need to include Base in two files: File0 and
File1. And File1 have Base and File0...
The compiler find two declarations...
mysql access denied for only one IP on a multi-NIC system
mysql access denied for only one IP on a multi-NIC system
I'm having this strange problem. We have a ubuntu 12.04 server with 2
NICs. One public with 172.30.1.1, the other is private with 192.168.1.1.
We have a MySQL server running. In /etc/mysql/my.conf, we have
bind-address = 0.0.0.0.
A table is created and privilege granted.
CREATE DATABASE db;
GRANT ALL ON db.* TO 'user0'@'%' IDENTIFIED BY 'password';
GRANT ALL ON db.* TO 'user0'@'localhost' IDENTIFIED BY 'password';
The hostname is 'myhost', and it's in /etc/hostname. /etc/hosts has
127.0.0.1 localhost
127.0.1.1 myhost
192.168.1.1 myhost
When I connect with 172.30.1.1, it's fine. But when I use 192.168.1.1, the
access is denied. mysql -h 192.168.1.1 -uuser0 -ppassword ERROR 1045
(28000): Access denied for user 'user0'@'myhost' (using password: YES) I
have the user table like this.
mysql> SELECT user, host FROM mysql.user;
+------------------+-----------+
| user | host |
+------------------+-----------+
| user0 | % |
| root | 127.0.0.1 |
| root | ::1 |
| | localhost |
| debian-sys-maint | localhost |
| user0 | localhost |
| root | localhost |
| | myhost |
| root | myhost |
+------------------+-----------+
I observed the difference is that I have 192.168.1.1 myhost line in
/etc/hosts file; not 172.30.1.1. If I remove that line or change the
hostname after the IP, it will work fine. If I add 172.30.1.1 myhost to
/etc/hosts, then I can't connect with 172 IP. How to explain this?
I'm having this strange problem. We have a ubuntu 12.04 server with 2
NICs. One public with 172.30.1.1, the other is private with 192.168.1.1.
We have a MySQL server running. In /etc/mysql/my.conf, we have
bind-address = 0.0.0.0.
A table is created and privilege granted.
CREATE DATABASE db;
GRANT ALL ON db.* TO 'user0'@'%' IDENTIFIED BY 'password';
GRANT ALL ON db.* TO 'user0'@'localhost' IDENTIFIED BY 'password';
The hostname is 'myhost', and it's in /etc/hostname. /etc/hosts has
127.0.0.1 localhost
127.0.1.1 myhost
192.168.1.1 myhost
When I connect with 172.30.1.1, it's fine. But when I use 192.168.1.1, the
access is denied. mysql -h 192.168.1.1 -uuser0 -ppassword ERROR 1045
(28000): Access denied for user 'user0'@'myhost' (using password: YES) I
have the user table like this.
mysql> SELECT user, host FROM mysql.user;
+------------------+-----------+
| user | host |
+------------------+-----------+
| user0 | % |
| root | 127.0.0.1 |
| root | ::1 |
| | localhost |
| debian-sys-maint | localhost |
| user0 | localhost |
| root | localhost |
| | myhost |
| root | myhost |
+------------------+-----------+
I observed the difference is that I have 192.168.1.1 myhost line in
/etc/hosts file; not 172.30.1.1. If I remove that line or change the
hostname after the IP, it will work fine. If I add 172.30.1.1 myhost to
/etc/hosts, then I can't connect with 172 IP. How to explain this?
xampp - SSL works on https://localhost, but not on https://127.0.0.1
xampp - SSL works on https://localhost, but not on https://127.0.0.1
I have changed the configuration on my XAMPP for SSL use, following this
tutorial:
https://avosapi.delicious.com/api/v1/posts/redirect?url=http%3A%2F%2Frobsnotebook.com%2Fxampp-ssl-encrypt-passwords
It works partially. I can access https://localhost/phpmyadmin and others
URLs that use the term localhost, but on https://127.0.0.1/magento it does
not recognize the certificate (it shows that message on the browser about
insecure certificates). How can I solve these differences between
localhost and 127.0.0.1?
Tks in advance.
I have changed the configuration on my XAMPP for SSL use, following this
tutorial:
https://avosapi.delicious.com/api/v1/posts/redirect?url=http%3A%2F%2Frobsnotebook.com%2Fxampp-ssl-encrypt-passwords
It works partially. I can access https://localhost/phpmyadmin and others
URLs that use the term localhost, but on https://127.0.0.1/magento it does
not recognize the certificate (it shows that message on the browser about
insecure certificates). How can I solve these differences between
localhost and 127.0.0.1?
Tks in advance.
How to combine node.js and Java buildpack in Heroku
How to combine node.js and Java buildpack in Heroku
We have an application that is a HTML5/JavaScript frontend that
communicates with a pure Java backend via REST. The JavaScript frontend
relies on Backbone.js rather than Node.js. For now, this is packaged as
one application, and deployed in Heroku using the standard Java buildpack.
But what we want to do now is to add Grunt to the build process, in order
to concatenate, minify, etc, the JavaScript. It works fine locally, but
how would we make it work with Heroku? We are not interested in committing
the Grunted files. We want it to be a part of the buildpack. Any
suggestions?
We have an application that is a HTML5/JavaScript frontend that
communicates with a pure Java backend via REST. The JavaScript frontend
relies on Backbone.js rather than Node.js. For now, this is packaged as
one application, and deployed in Heroku using the standard Java buildpack.
But what we want to do now is to add Grunt to the build process, in order
to concatenate, minify, etc, the JavaScript. It works fine locally, but
how would we make it work with Heroku? We are not interested in committing
the Grunted files. We want it to be a part of the buildpack. Any
suggestions?
error in php Catchable fatal error: Object of class mysqli_result could not be converted to string in
error in php Catchable fatal error: Object of class mysqli_result could
not be converted to string in
this is query
SELECT room_id,stages FROM booked_room
this is error
Catchable fatal error: Object of class mysqli_result could not be
converted to string in
$query ="SELECT room_id,stages FROM booked_room";
$result2 =$mysqli->query($query);
echo $mysqli->error;
if($result2->num_rows > 0){echo"some thing";}
not be converted to string in
this is query
SELECT room_id,stages FROM booked_room
this is error
Catchable fatal error: Object of class mysqli_result could not be
converted to string in
$query ="SELECT room_id,stages FROM booked_room";
$result2 =$mysqli->query($query);
echo $mysqli->error;
if($result2->num_rows > 0){echo"some thing";}
p:selectOneMenu not calling setter on form submit
p:selectOneMenu not calling setter on form submit
I'm kinda new to JSF and primefaces and I'm running into a very annoying
problem.
I'm making a very basic application to learn a bit more about primefaces.
I have a simple form that has several textual input fields, two
datepickers and one dropdown (selectOneMenu).
Everything works all values are put in the backing bean when I submit the
form, except for the value from the dropdown menu. The setter for that
item is never called. And the application does not call the public void
saveNewActivity(ActionEvent evt) method on the controller as defined on
the commandbutton. When I however remove or comment out the dropdown menu
in html it does call that method (but the field for the dropdown menu is
obviously null).
I've been trying things for nearly two days, and still can't get this to
work properly.
I have the following code (snippets):
My html/jsf code
<div id="newActivitycontent">
<h:form id="newActivityForm">
<h:messages id="messages"/>
<table>
<tr>
<td>Gebruiker:</td>
<td><p:selectOneMenu
value="#{plannedActivityController.newActivity.organiser}}"
converter="#{userConverter}">
<f:selectItem itemLabel="Kies een gebruiker"
itemValue=""/>
<f:selectItems
value="#{plannedActivityController.users}"
var="user"
itemLabel="#{user.firstname}
#{user.lastname}"
itemValue="#{user}"/>
</p:selectOneMenu></td>
</tr>
<tr>
<td>Titel:</td>
<td><p:inputText
value="#{plannedActivityController.newActivity.name}"/></td>
</tr>
<tr>
<td>Beschrijving:</td>
<td><p:inputText
value="#{plannedActivityController.newActivity.desctription}"/></td>
</tr>
<tr>
<td>Startdatum:</td>
<td><p:calendar
value="#{plannedActivityController.newActivity.startDateDate}"/></td>
</tr>
<tr>
<td>Einddatum:</td>
<td><p:calendar
value="#{plannedActivityController.newActivity.endDateDate}"/></td>
</tr>
</table>
<p:commandButton id="btnSaveNewActivity" value="Opslaan"
actionListener="#{plannedActivityController.saveNewActivity}"
update=":overviewForm:activityTable
messages"/>
<p:commandButton id="btnCancelNewActivity" value="Annuleren"
actionListener="#{plannedActivityController.cancelNewActivity}"
onclick="hideAddNewUI()"
update=":overviewForm:activityTable"
type="reset" immediate="true"/>
</h:form>
</div>
The controller that is used by that code:
@Named
@SessionScoped
public class PlannedActivityController implements Serializable {
@Inject
private ApplicationModel appModel;
@Inject
private SessionModel sessionModel;
@Inject
private ActivityMapper activityMapper;
@Inject
private UserMapper userMapper;
private ActivityBean newActivity;
private ActivityBean selectedActivity;
private List<ActivityBean> activities;
private List<UserBean> users;
public PlannedActivityController() {
}
@PostConstruct
public void onCreated() {
convertActivities();
onNewActivity();
users = userMapper.mapToValueObjects(appModel.getUsers());
}
public void convertActivities() {
List<PlannedActivity> originalActivities = appModel.getActivities();
this.activities =
activityMapper.mapToValueObjects(originalActivities);
}
public void onRowEditComplete(RowEditEvent event) {
System.out.println("row edited : " + event.getObject());
//TODO: save changes back to db!
}
public void onRowSelectionMade(SelectEvent event) {
System.out.println("row selected : " + event.getObject());
selectedActivity = (ActivityBean)event.getObject();
}
//Activity crud methods
public void onNewActivity() {
newActivity = new ActivityBean();
newActivity.setId(new Date().getTime());
}
public void saveNewActivity(ActionEvent evt) {
PlannedActivity newAct = activityMapper.mapToEntity(newActivity);
if(newAct != null) {
appModel.getActivities().add(newAct);
}
convertActivities();
}
public void cancelNewActivity() {
//TODO: cleanup.
}
public void deleteSelectedActivity() {
if(selectedActivity != null) {
activities.remove(selectedActivity);
appModel.setActivities(activityMapper.mapToEntities(activities));
convertActivities();
} else {
//TODO: show error or information dialog, that delete cannot
be done when nothing has been selected!
}
}
//Getters & Setters
public ApplicationModel getAppModel() {
return appModel;
}
public void setAppModel(ApplicationModel appModel) {
this.appModel = appModel;
}
public SessionModel getSessionModel() {
return sessionModel;
}
public void setSessionModel(SessionModel sessionModel) {
this.sessionModel = sessionModel;
}
public ActivityMapper getActivityMapper() {
return activityMapper;
}
public void setActivityMapper(ActivityMapper activityMapper) {
this.activityMapper = activityMapper;
}
public UserMapper getUserMapper() {
return userMapper;
}
public void setUserMapper(UserMapper userMapper) {
this.userMapper = userMapper;
}
public ActivityBean getNewActivity() {
return newActivity;
}
public void setNewActivity(ActivityBean newActivity) {
this.newActivity = newActivity;
}
public ActivityBean getSelectedActivity() {
return selectedActivity;
}
public void setSelectedActivity(ActivityBean selectedActivity) {
this.selectedActivity = selectedActivity;
}
public List<ActivityBean> getActivities() {
return activities;
}
public void setActivities(List<ActivityBean> activities) {
this.activities = activities;
}
public List<UserBean> getUsers() {
return users;
}
public void setUsers(List<UserBean> users) {
this.users = users;
}
}
My activitybean:
public class ActivityBean implements Serializable {
private Long id = 0L;
private String name;
private String desctription;
private UserBean organiser;
private Calendar startDate;
private Calendar endDate;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesctription() {
return desctription;
}
public void setDesctription(String desctription) {
this.desctription = desctription;
}
public UserBean getOrganiser() {
return organiser;
}
public void setOrganiser(UserBean organiser) {
this.organiser = organiser;
}
public Calendar getStartDate() {
return startDate;
}
public void setStartDate(Calendar startDate) {
this.startDate = startDate;
}
public Date getStartDateDate() {
if(this.startDate == null) {
return null;
}
return this.endDate.getTime();
}
public void setStartDateDate(Date startDate) {
if(this.startDate == null) {
this.startDate = new GregorianCalendar();
}
this.startDate.setTime(startDate);
}
public String getStartDateString() {
if(this.startDate == null) {
return null;
}
return startDate.get(Calendar.DAY_OF_MONTH) + "/" +
startDate.get(Calendar.MONTH) + "/" + startDate.get(Calendar.YEAR)
+ "";
}
public Calendar getEndDate() {
return endDate;
}
public void setEndDate(Calendar endDate) {
this.endDate = endDate;
}
public Date getEndDateDate() {
if(this.endDate == null) {
return null;
}
return endDate.getTime();
}
public void setEndDateDate(Date endDate) {
if(this.endDate == null) {
this.endDate = new GregorianCalendar();
}
this.endDate.setTime(endDate);
}
public String getEndDateString() {
if(this.endDate == null) {
return null;
}
return endDate.get(Calendar.DAY_OF_MONTH) + "/" +
endDate.get(Calendar.MONTH) + "/" + endDate.get(Calendar.YEAR) +
"";
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ActivityBean that = (ActivityBean) o;
if (id != null ? !id.equals(that.id) : that.id != null) return false;
return true;
}
@Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
}
My userbean:
public class UserBean {
private Long id;
private String username;
private String firstname;
private String lastname;
private String email;
private String phone;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserBean userBean = (UserBean) o;
if (id != null ? !id.equals(userBean.id) : userBean.id != null)
return false;
return true;
}
@Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
}
And the converter used by the selectOneMenu:
@Named
public class userConverter implements Converter{
@Inject
private PlannedActivityController activityController;
@Override
public Object getAsObject(FacesContext facesContext, UIComponent
uiComponent, String s) {
for (UserBean user : activityController.getUsers()) {
if(user.getId().toString().equals(s)) {
return user;
}
}
return null;
}
@Override
public String getAsString(FacesContext facesContext, UIComponent
uiComponent, Object o) {
if(o instanceof UserBean) {
UserBean user = (UserBean)o;
return user.getId().toString();
}
return "";
}
}
I'm kinda new to JSF and primefaces and I'm running into a very annoying
problem.
I'm making a very basic application to learn a bit more about primefaces.
I have a simple form that has several textual input fields, two
datepickers and one dropdown (selectOneMenu).
Everything works all values are put in the backing bean when I submit the
form, except for the value from the dropdown menu. The setter for that
item is never called. And the application does not call the public void
saveNewActivity(ActionEvent evt) method on the controller as defined on
the commandbutton. When I however remove or comment out the dropdown menu
in html it does call that method (but the field for the dropdown menu is
obviously null).
I've been trying things for nearly two days, and still can't get this to
work properly.
I have the following code (snippets):
My html/jsf code
<div id="newActivitycontent">
<h:form id="newActivityForm">
<h:messages id="messages"/>
<table>
<tr>
<td>Gebruiker:</td>
<td><p:selectOneMenu
value="#{plannedActivityController.newActivity.organiser}}"
converter="#{userConverter}">
<f:selectItem itemLabel="Kies een gebruiker"
itemValue=""/>
<f:selectItems
value="#{plannedActivityController.users}"
var="user"
itemLabel="#{user.firstname}
#{user.lastname}"
itemValue="#{user}"/>
</p:selectOneMenu></td>
</tr>
<tr>
<td>Titel:</td>
<td><p:inputText
value="#{plannedActivityController.newActivity.name}"/></td>
</tr>
<tr>
<td>Beschrijving:</td>
<td><p:inputText
value="#{plannedActivityController.newActivity.desctription}"/></td>
</tr>
<tr>
<td>Startdatum:</td>
<td><p:calendar
value="#{plannedActivityController.newActivity.startDateDate}"/></td>
</tr>
<tr>
<td>Einddatum:</td>
<td><p:calendar
value="#{plannedActivityController.newActivity.endDateDate}"/></td>
</tr>
</table>
<p:commandButton id="btnSaveNewActivity" value="Opslaan"
actionListener="#{plannedActivityController.saveNewActivity}"
update=":overviewForm:activityTable
messages"/>
<p:commandButton id="btnCancelNewActivity" value="Annuleren"
actionListener="#{plannedActivityController.cancelNewActivity}"
onclick="hideAddNewUI()"
update=":overviewForm:activityTable"
type="reset" immediate="true"/>
</h:form>
</div>
The controller that is used by that code:
@Named
@SessionScoped
public class PlannedActivityController implements Serializable {
@Inject
private ApplicationModel appModel;
@Inject
private SessionModel sessionModel;
@Inject
private ActivityMapper activityMapper;
@Inject
private UserMapper userMapper;
private ActivityBean newActivity;
private ActivityBean selectedActivity;
private List<ActivityBean> activities;
private List<UserBean> users;
public PlannedActivityController() {
}
@PostConstruct
public void onCreated() {
convertActivities();
onNewActivity();
users = userMapper.mapToValueObjects(appModel.getUsers());
}
public void convertActivities() {
List<PlannedActivity> originalActivities = appModel.getActivities();
this.activities =
activityMapper.mapToValueObjects(originalActivities);
}
public void onRowEditComplete(RowEditEvent event) {
System.out.println("row edited : " + event.getObject());
//TODO: save changes back to db!
}
public void onRowSelectionMade(SelectEvent event) {
System.out.println("row selected : " + event.getObject());
selectedActivity = (ActivityBean)event.getObject();
}
//Activity crud methods
public void onNewActivity() {
newActivity = new ActivityBean();
newActivity.setId(new Date().getTime());
}
public void saveNewActivity(ActionEvent evt) {
PlannedActivity newAct = activityMapper.mapToEntity(newActivity);
if(newAct != null) {
appModel.getActivities().add(newAct);
}
convertActivities();
}
public void cancelNewActivity() {
//TODO: cleanup.
}
public void deleteSelectedActivity() {
if(selectedActivity != null) {
activities.remove(selectedActivity);
appModel.setActivities(activityMapper.mapToEntities(activities));
convertActivities();
} else {
//TODO: show error or information dialog, that delete cannot
be done when nothing has been selected!
}
}
//Getters & Setters
public ApplicationModel getAppModel() {
return appModel;
}
public void setAppModel(ApplicationModel appModel) {
this.appModel = appModel;
}
public SessionModel getSessionModel() {
return sessionModel;
}
public void setSessionModel(SessionModel sessionModel) {
this.sessionModel = sessionModel;
}
public ActivityMapper getActivityMapper() {
return activityMapper;
}
public void setActivityMapper(ActivityMapper activityMapper) {
this.activityMapper = activityMapper;
}
public UserMapper getUserMapper() {
return userMapper;
}
public void setUserMapper(UserMapper userMapper) {
this.userMapper = userMapper;
}
public ActivityBean getNewActivity() {
return newActivity;
}
public void setNewActivity(ActivityBean newActivity) {
this.newActivity = newActivity;
}
public ActivityBean getSelectedActivity() {
return selectedActivity;
}
public void setSelectedActivity(ActivityBean selectedActivity) {
this.selectedActivity = selectedActivity;
}
public List<ActivityBean> getActivities() {
return activities;
}
public void setActivities(List<ActivityBean> activities) {
this.activities = activities;
}
public List<UserBean> getUsers() {
return users;
}
public void setUsers(List<UserBean> users) {
this.users = users;
}
}
My activitybean:
public class ActivityBean implements Serializable {
private Long id = 0L;
private String name;
private String desctription;
private UserBean organiser;
private Calendar startDate;
private Calendar endDate;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesctription() {
return desctription;
}
public void setDesctription(String desctription) {
this.desctription = desctription;
}
public UserBean getOrganiser() {
return organiser;
}
public void setOrganiser(UserBean organiser) {
this.organiser = organiser;
}
public Calendar getStartDate() {
return startDate;
}
public void setStartDate(Calendar startDate) {
this.startDate = startDate;
}
public Date getStartDateDate() {
if(this.startDate == null) {
return null;
}
return this.endDate.getTime();
}
public void setStartDateDate(Date startDate) {
if(this.startDate == null) {
this.startDate = new GregorianCalendar();
}
this.startDate.setTime(startDate);
}
public String getStartDateString() {
if(this.startDate == null) {
return null;
}
return startDate.get(Calendar.DAY_OF_MONTH) + "/" +
startDate.get(Calendar.MONTH) + "/" + startDate.get(Calendar.YEAR)
+ "";
}
public Calendar getEndDate() {
return endDate;
}
public void setEndDate(Calendar endDate) {
this.endDate = endDate;
}
public Date getEndDateDate() {
if(this.endDate == null) {
return null;
}
return endDate.getTime();
}
public void setEndDateDate(Date endDate) {
if(this.endDate == null) {
this.endDate = new GregorianCalendar();
}
this.endDate.setTime(endDate);
}
public String getEndDateString() {
if(this.endDate == null) {
return null;
}
return endDate.get(Calendar.DAY_OF_MONTH) + "/" +
endDate.get(Calendar.MONTH) + "/" + endDate.get(Calendar.YEAR) +
"";
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ActivityBean that = (ActivityBean) o;
if (id != null ? !id.equals(that.id) : that.id != null) return false;
return true;
}
@Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
}
My userbean:
public class UserBean {
private Long id;
private String username;
private String firstname;
private String lastname;
private String email;
private String phone;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserBean userBean = (UserBean) o;
if (id != null ? !id.equals(userBean.id) : userBean.id != null)
return false;
return true;
}
@Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
}
And the converter used by the selectOneMenu:
@Named
public class userConverter implements Converter{
@Inject
private PlannedActivityController activityController;
@Override
public Object getAsObject(FacesContext facesContext, UIComponent
uiComponent, String s) {
for (UserBean user : activityController.getUsers()) {
if(user.getId().toString().equals(s)) {
return user;
}
}
return null;
}
@Override
public String getAsString(FacesContext facesContext, UIComponent
uiComponent, Object o) {
if(o instanceof UserBean) {
UserBean user = (UserBean)o;
return user.getId().toString();
}
return "";
}
}
In which manner array of characters is allocated memory locally?
In which manner array of characters is allocated memory locally?
This is the code I've written,
char *foo();
void main()
{
char *str=foo();
strcpy(str,"Holy sweet moses! I blew my stack!!");
printf("%s",str);
}
char * foo()
{
char str[256];
return str;
}
When I use char array in function foo(), the strcpy in main() function
doesn't copy the string into str. But, when I use int array in function
foo(), main() strcpy copies successfully.
i.e.
int str[256]; //in funtion foo
output
Holy sweet moses! I blew my stack!!
if
char str[256]; //in foo()
output : nothing!
This is the code I've written,
char *foo();
void main()
{
char *str=foo();
strcpy(str,"Holy sweet moses! I blew my stack!!");
printf("%s",str);
}
char * foo()
{
char str[256];
return str;
}
When I use char array in function foo(), the strcpy in main() function
doesn't copy the string into str. But, when I use int array in function
foo(), main() strcpy copies successfully.
i.e.
int str[256]; //in funtion foo
output
Holy sweet moses! I blew my stack!!
if
char str[256]; //in foo()
output : nothing!
Wednesday, 18 September 2013
UIView animateWithDuration in Delphi FireMonkey
UIView animateWithDuration in Delphi FireMonkey
What is the best way to perform the same thing as UIView
animateWithDuration using Delphi and FireMonkey? I would like it to work
on iOS and Android (using Delphi XE5)
What is the best way to perform the same thing as UIView
animateWithDuration using Delphi and FireMonkey? I would like it to work
on iOS and Android (using Delphi XE5)
Elixir Dynamo start multiple apps
Elixir Dynamo start multiple apps
What is the best way to start multiple apps using Dynamo. When we create
the project dynamo generates a default app. I would like to add one more
app in lib and start it as soon as i start the server.
However, i tried putting it in lib folde, apps folder also modified
mix.exs but mix compile is not generating the app file.
What is the best way to start multiple apps using Dynamo. When we create
the project dynamo generates a default app. I would like to add one more
app in lib and start it as soon as i start the server.
However, i tried putting it in lib folde, apps folder also modified
mix.exs but mix compile is not generating the app file.
I need to learn basic Unity with C# fast, I have a assignment due next week
I need to learn basic Unity with C# fast, I have a assignment due next week
I know how to program OOP (beginner/moderate). I have to make a simple
game in Unity based off any old Atari game system for class. I usually go
to new Boston to learn stuff fast but he does not cover anything about
unity. Anyone have any good links for basic tutorials in c# or javascript?
I know how to program OOP (beginner/moderate). I have to make a simple
game in Unity based off any old Atari game system for class. I usually go
to new Boston to learn stuff fast but he does not cover anything about
unity. Anyone have any good links for basic tutorials in c# or javascript?
Activate subform for data entry using a button on main form
Activate subform for data entry using a button on main form
How can I reference a button click event on the main form to a subform,
similar to:
DoCmd.GoToRecord , , acNewRec
I want to use the subform both for viewing and entering new records but my
button is on the main form.
How can I reference a button click event on the main form to a subform,
similar to:
DoCmd.GoToRecord , , acNewRec
I want to use the subform both for viewing and entering new records but my
button is on the main form.
Pseudo-polynomial time dynamic programming solution from TWO sets with TWO limitations
Pseudo-polynomial time dynamic programming solution from TWO sets with TWO
limitations
I´ve read at wiki
http://en.wikipedia.org/wiki/Subset_sum_problem#Pseudo-polynomial_time_dynamic_programming_solution
about the sumsubsetproblem and wonder if i can adapt it to the following
problem:
I need all possible subsets ss1, ss2 restricted by n1, n2 being the number
of elements out of 2 sets s1,s2
I will use the elements of S1 as positive elements and the elements of s2
as negative elements to answer the question if the subsets of size n1 and
n2 have sum equal 0
My special problem here is that the sets can contain 0 itselfs and i
thought i solve this by setting these elements to 1 or -1 repectivly ( 1
is not a member of my input, which will be (0,10,50,100,200,500) ) and the
next problem is that this algorithm gives me yes or no only, but i know
this answer already ( its a precondition ) what i need is the results.
Is this still fast enough ? i ´ve read here about an perl implementation
where the OP posted a list with runtimes an 30 elements had a computation
time of 30-40 seconds wich is far too slow for my needs and i need to
implement in java, wich is, as far as i know even slower then perl
regards
dirk
limitations
I´ve read at wiki
http://en.wikipedia.org/wiki/Subset_sum_problem#Pseudo-polynomial_time_dynamic_programming_solution
about the sumsubsetproblem and wonder if i can adapt it to the following
problem:
I need all possible subsets ss1, ss2 restricted by n1, n2 being the number
of elements out of 2 sets s1,s2
I will use the elements of S1 as positive elements and the elements of s2
as negative elements to answer the question if the subsets of size n1 and
n2 have sum equal 0
My special problem here is that the sets can contain 0 itselfs and i
thought i solve this by setting these elements to 1 or -1 repectivly ( 1
is not a member of my input, which will be (0,10,50,100,200,500) ) and the
next problem is that this algorithm gives me yes or no only, but i know
this answer already ( its a precondition ) what i need is the results.
Is this still fast enough ? i ´ve read here about an perl implementation
where the OP posted a list with runtimes an 30 elements had a computation
time of 30-40 seconds wich is far too slow for my needs and i need to
implement in java, wich is, as far as i know even slower then perl
regards
dirk
Unable to replace HTML file in Web Application hosted by IIS 7.5 on Win Server 2008 R2 due to locking IIS Worker Process
Unable to replace HTML file in Web Application hosted by IIS 7.5 on Win
Server 2008 R2 due to locking IIS Worker Process
When attempting to delete/replace an entire .NET Web Application hosted by
IIS 7.5 on Windows Server 2008 R2, targeting .NET 4.5, programmatic
deletion of the landing page (an .html page) via VB.NET code results in
"System.IO.IOException: The process cannot access the file
'[filename].html'. because it is being used by another process"
Attempting to delete the HTML file using Windows Explorer results in
"The action can't be completed because file is open in IIS Worker Process."
This happens immediately after the landing page is served up by IIS. The
lock lasts for a while, approximately an hour or two. Recycling the App
Pool that hosts the application removes the lock immediately making
deletion possible. I can see the IIS Worker Process disappear via Process
Explorer after the recycle.
This is happening on multiple, redundant production servers but does not
happen on a comparable test server (very similar set up).
I've checked
Server setup and configuration (software installed, features installed,
.NET framework asp.config file, etc)
web.config file setups
IIS Application and App Pool configurations.
toggled application Output Caching Settings
There are a few similar questions to this posted but they have not helped
me resolve the issue.
Note that replacing the web application files is required as a business
need to host payment pages on behalf of customers. Because there are
multiple customers' web applications hosted on the same IIS instance,
restarting the instance is not an option. I'm not even comfortable
recycling the app pool in order to be able to publish one customer's
changes.
Thank you for taking the time to consider this post.
Server 2008 R2 due to locking IIS Worker Process
When attempting to delete/replace an entire .NET Web Application hosted by
IIS 7.5 on Windows Server 2008 R2, targeting .NET 4.5, programmatic
deletion of the landing page (an .html page) via VB.NET code results in
"System.IO.IOException: The process cannot access the file
'[filename].html'. because it is being used by another process"
Attempting to delete the HTML file using Windows Explorer results in
"The action can't be completed because file is open in IIS Worker Process."
This happens immediately after the landing page is served up by IIS. The
lock lasts for a while, approximately an hour or two. Recycling the App
Pool that hosts the application removes the lock immediately making
deletion possible. I can see the IIS Worker Process disappear via Process
Explorer after the recycle.
This is happening on multiple, redundant production servers but does not
happen on a comparable test server (very similar set up).
I've checked
Server setup and configuration (software installed, features installed,
.NET framework asp.config file, etc)
web.config file setups
IIS Application and App Pool configurations.
toggled application Output Caching Settings
There are a few similar questions to this posted but they have not helped
me resolve the issue.
Note that replacing the web application files is required as a business
need to host payment pages on behalf of customers. Because there are
multiple customers' web applications hosted on the same IIS instance,
restarting the instance is not an option. I'm not even comfortable
recycling the app pool in order to be able to publish one customer's
changes.
Thank you for taking the time to consider this post.
How to Validate users by SqlDataSource Control?
How to Validate users by SqlDataSource Control?
I make a Login page to validate user. I have a sql table like following:
table: tblUsers
userID (int is identity)
username (nvarchr (50))
password (nvarchr (50))
Login.ASPX
Username<asp:TextBox ID="txtUsername" runat="server"></asp:TextBox><br />
Password <asp:TextBox ID="txtPassword"
runat="server"></asp:TextBox><br />
<asp:Button ID="cmdLogin" runat="server" Text="Login"
onclick="cmdLogin_Click" /><br />
<asp:Label ID="lblError" runat="server"
EnableViewState="False"></asp:Label><br />
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConStr %>"
SelectCommand="SELECT * FROM [tblUser] WHERE (([username] =
@username) AND ([password] = @password))">
<SelectParameters>
<asp:ControlParameter ControlID="txtPassword" Name="username"
PropertyName="Text" Type="String" />
<asp:ControlParameter ControlID="txtPassword" Name="password"
PropertyName="Text" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
Validate users is in SelectCommand of SqlDataSource.
SELECT * FROM [tblUser] WHERE (([username] = @username) AND ([password] =
@password))
how to validate user by SqlDataSource? I want code for Login button.
I make a Login page to validate user. I have a sql table like following:
table: tblUsers
userID (int is identity)
username (nvarchr (50))
password (nvarchr (50))
Login.ASPX
Username<asp:TextBox ID="txtUsername" runat="server"></asp:TextBox><br />
Password <asp:TextBox ID="txtPassword"
runat="server"></asp:TextBox><br />
<asp:Button ID="cmdLogin" runat="server" Text="Login"
onclick="cmdLogin_Click" /><br />
<asp:Label ID="lblError" runat="server"
EnableViewState="False"></asp:Label><br />
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConStr %>"
SelectCommand="SELECT * FROM [tblUser] WHERE (([username] =
@username) AND ([password] = @password))">
<SelectParameters>
<asp:ControlParameter ControlID="txtPassword" Name="username"
PropertyName="Text" Type="String" />
<asp:ControlParameter ControlID="txtPassword" Name="password"
PropertyName="Text" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
Validate users is in SelectCommand of SqlDataSource.
SELECT * FROM [tblUser] WHERE (([username] = @username) AND ([password] =
@password))
how to validate user by SqlDataSource? I want code for Login button.
how to develop Admin Panel in ASP.Net
how to develop Admin Panel in ASP.Net
I am developing an asp.net website in which i need to create admin panel.
So please tell me how to decide role and membership and also way of
development.
thanks
I am developing an asp.net website in which i need to create admin panel.
So please tell me how to decide role and membership and also way of
development.
thanks
How do I expect and verify the same method in JMockit
How do I expect and verify the same method in JMockit
Having the following class:
class ToTest{
@Autowired
private Service service;
public String make(){
//do some calcs
obj.setParam(param);
String inverted = service.execute(obj);
return "<" + inverted.toString() + ">";
}
}
I'd like to add a test that asserts me that service.execute is called with
an object with the param X.
I'd do that with a verification. I want to mock this call and make it
return something testable. I do that with an expectations.
@Tested
ToTest toTest;
@Injected
Service service;
new Expectations(){
{
service.exceute((CertainObject)any)
result = "b";
}
};
toTest.make();
new Verifications(){
{
CertainObject obj;
service.exceute(obj = withCapture())
assertEquals("a",obj.getParam());
}
};
I get a null pointer on obj.getParam(). Apparently the verification does
not work. If I remove the expectation it works but then I get a null
pointer in inverted.toString().
How would you guys make this work?
Having the following class:
class ToTest{
@Autowired
private Service service;
public String make(){
//do some calcs
obj.setParam(param);
String inverted = service.execute(obj);
return "<" + inverted.toString() + ">";
}
}
I'd like to add a test that asserts me that service.execute is called with
an object with the param X.
I'd do that with a verification. I want to mock this call and make it
return something testable. I do that with an expectations.
@Tested
ToTest toTest;
@Injected
Service service;
new Expectations(){
{
service.exceute((CertainObject)any)
result = "b";
}
};
toTest.make();
new Verifications(){
{
CertainObject obj;
service.exceute(obj = withCapture())
assertEquals("a",obj.getParam());
}
};
I get a null pointer on obj.getParam(). Apparently the verification does
not work. If I remove the expectation it works but then I get a null
pointer in inverted.toString().
How would you guys make this work?
Tuesday, 17 September 2013
Problems occurred when invoking code from plug-in: "org.eclipse.core.resources" when using eclipse
Problems occurred when invoking code from plug-in:
"org.eclipse.core.resources" when using eclipse
I am developing a J2EE application using Eclipse...and in that
application..i used a jquery Plugin "DataTable 1.9.4" to create a table
grid with all its functionality.
But in javascript file of DataTable plugin..an error occured like below :
!MESSAGE Problems occurred when invoking code from plug-in:
"org.eclipse.core.resources".
!STACK 0
java.lang.ClassCastException:
org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding cannot be cast
to org.eclipse.wst.jsdt.internal.compiler.lookup.LocalVariableBinding
at
org.eclipse.wst.jsdt.internal.compiler.ast.SingleNameReference.localVariableBinding(SingleNameReference.java:226)
at
org.eclipse.wst.jsdt.internal.compiler.ast.Expression.checkNPE(Expression.java:320)
at
org.eclipse.wst.jsdt.internal.compiler.ast.MessageSend.analyseCode(MessageSend.java:67)
at
org.eclipse.wst.jsdt.internal.compiler.ast.SingleNameReference.analyseAssignment(SingleNameReference.java:84)
at
org.eclipse.wst.jsdt.internal.compiler.ast.Assignment.analyseCode(Assignment.java:63)
at
org.eclipse.wst.jsdt.internal.compiler.ast.MethodDeclaration.analyseCode(MethodDeclaration.java:91)
at
org.eclipse.wst.jsdt.internal.compiler.ast.AbstractMethodDeclaration.analyseCode(AbstractMethodDeclaration.java:110)
at
org.eclipse.wst.jsdt.internal.compiler.ast.FunctionExpression.analyseCode(FunctionExpression.java:74)
at
org.eclipse.wst.jsdt.internal.compiler.ast.FieldReference.analyseAssignment(FieldReference.java:91)
at
org.eclipse.wst.jsdt.internal.compiler.ast.Assignment.analyseCode(Assignment.java:63)
at
org.eclipse.wst.jsdt.internal.compiler.ast.MethodDeclaration.analyseCode(MethodDeclaration.java:91)
at
org.eclipse.wst.jsdt.internal.compiler.ast.AbstractMethodDeclaration.analyseCode(AbstractMethodDeclaration.java:110)
at
org.eclipse.wst.jsdt.internal.compiler.ast.FunctionExpression.analyseCode(FunctionExpression.java:74)
at
org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration.analyseCode(LocalDeclaration.java:73)
at
org.eclipse.wst.jsdt.internal.compiler.ast.MethodDeclaration.analyseCode(MethodDeclaration.java:91)
at
org.eclipse.wst.jsdt.internal.compiler.ast.AbstractMethodDeclaration.analyseCode(AbstractMethodDeclaration.java:110)
at
org.eclipse.wst.jsdt.internal.compiler.ast.FunctionExpression.analyseCode(FunctionExpression.java:74)
at
org.eclipse.wst.jsdt.internal.compiler.ast.MessageSend.analyseCode(MessageSend.java:86)
at
org.eclipse.wst.jsdt.internal.compiler.ast.MethodDeclaration.analyseCode(MethodDeclaration.java:91)
at
org.eclipse.wst.jsdt.internal.compiler.ast.AbstractMethodDeclaration.analyseCode(AbstractMethodDeclaration.java:110)
at
org.eclipse.wst.jsdt.internal.compiler.ast.FunctionExpression.analyseCode(FunctionExpression.java:74)
at
org.eclipse.wst.jsdt.internal.compiler.ast.Expression.analyseCode(Expression.java:184)
at
org.eclipse.wst.jsdt.internal.compiler.ast.MessageSend.analyseCode(MessageSend.java:65)
at
org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration.analyseCode(CompilationUnitDeclaration.java:155)
at org.eclipse.wst.jsdt.internal.compiler.Compiler.process(Compiler.java:609)
at org.eclipse.wst.jsdt.internal.compiler.Compiler.compile(Compiler.java:355)
at
org.eclipse.wst.jsdt.internal.core.builder.AbstractImageBuilder.compile(AbstractImageBuilder.java:288)
at
org.eclipse.wst.jsdt.internal.core.builder.BatchImageBuilder.compile(BatchImageBuilder.java:86)
at
org.eclipse.wst.jsdt.internal.core.builder.AbstractImageBuilder.compile(AbstractImageBuilder.java:227)
at
org.eclipse.wst.jsdt.internal.core.builder.BatchImageBuilder.build(BatchImageBuilder.java:58)
at
org.eclipse.wst.jsdt.internal.core.builder.JavaBuilder.buildAll(JavaBuilder.java:291)
at
org.eclipse.wst.jsdt.internal.core.builder.JavaBuilder.build(JavaBuilder.java:199)
at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:728)
at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
at
org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:199)
at
org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:239)
at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:292)
at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
at
org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:295)
at
org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:351)
at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:374)
at
org.eclipse.core.internal.events.AutoBuildJob.doBuild(AutoBuildJob.java:143)
at org.eclipse.core.internal.events.AutoBuildJob.run(AutoBuildJob.java:241)
at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54)
To resolve this error i explored about it..and below are links which i
explored :
Bug 391880 - javascript validator throws error, unable to build project
ClassCastException
but still i didn't get any proper solution to resolve this error.... So
please guide me to remove this error...its very urgent for me..
Thanks in advance..
"org.eclipse.core.resources" when using eclipse
I am developing a J2EE application using Eclipse...and in that
application..i used a jquery Plugin "DataTable 1.9.4" to create a table
grid with all its functionality.
But in javascript file of DataTable plugin..an error occured like below :
!MESSAGE Problems occurred when invoking code from plug-in:
"org.eclipse.core.resources".
!STACK 0
java.lang.ClassCastException:
org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding cannot be cast
to org.eclipse.wst.jsdt.internal.compiler.lookup.LocalVariableBinding
at
org.eclipse.wst.jsdt.internal.compiler.ast.SingleNameReference.localVariableBinding(SingleNameReference.java:226)
at
org.eclipse.wst.jsdt.internal.compiler.ast.Expression.checkNPE(Expression.java:320)
at
org.eclipse.wst.jsdt.internal.compiler.ast.MessageSend.analyseCode(MessageSend.java:67)
at
org.eclipse.wst.jsdt.internal.compiler.ast.SingleNameReference.analyseAssignment(SingleNameReference.java:84)
at
org.eclipse.wst.jsdt.internal.compiler.ast.Assignment.analyseCode(Assignment.java:63)
at
org.eclipse.wst.jsdt.internal.compiler.ast.MethodDeclaration.analyseCode(MethodDeclaration.java:91)
at
org.eclipse.wst.jsdt.internal.compiler.ast.AbstractMethodDeclaration.analyseCode(AbstractMethodDeclaration.java:110)
at
org.eclipse.wst.jsdt.internal.compiler.ast.FunctionExpression.analyseCode(FunctionExpression.java:74)
at
org.eclipse.wst.jsdt.internal.compiler.ast.FieldReference.analyseAssignment(FieldReference.java:91)
at
org.eclipse.wst.jsdt.internal.compiler.ast.Assignment.analyseCode(Assignment.java:63)
at
org.eclipse.wst.jsdt.internal.compiler.ast.MethodDeclaration.analyseCode(MethodDeclaration.java:91)
at
org.eclipse.wst.jsdt.internal.compiler.ast.AbstractMethodDeclaration.analyseCode(AbstractMethodDeclaration.java:110)
at
org.eclipse.wst.jsdt.internal.compiler.ast.FunctionExpression.analyseCode(FunctionExpression.java:74)
at
org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration.analyseCode(LocalDeclaration.java:73)
at
org.eclipse.wst.jsdt.internal.compiler.ast.MethodDeclaration.analyseCode(MethodDeclaration.java:91)
at
org.eclipse.wst.jsdt.internal.compiler.ast.AbstractMethodDeclaration.analyseCode(AbstractMethodDeclaration.java:110)
at
org.eclipse.wst.jsdt.internal.compiler.ast.FunctionExpression.analyseCode(FunctionExpression.java:74)
at
org.eclipse.wst.jsdt.internal.compiler.ast.MessageSend.analyseCode(MessageSend.java:86)
at
org.eclipse.wst.jsdt.internal.compiler.ast.MethodDeclaration.analyseCode(MethodDeclaration.java:91)
at
org.eclipse.wst.jsdt.internal.compiler.ast.AbstractMethodDeclaration.analyseCode(AbstractMethodDeclaration.java:110)
at
org.eclipse.wst.jsdt.internal.compiler.ast.FunctionExpression.analyseCode(FunctionExpression.java:74)
at
org.eclipse.wst.jsdt.internal.compiler.ast.Expression.analyseCode(Expression.java:184)
at
org.eclipse.wst.jsdt.internal.compiler.ast.MessageSend.analyseCode(MessageSend.java:65)
at
org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration.analyseCode(CompilationUnitDeclaration.java:155)
at org.eclipse.wst.jsdt.internal.compiler.Compiler.process(Compiler.java:609)
at org.eclipse.wst.jsdt.internal.compiler.Compiler.compile(Compiler.java:355)
at
org.eclipse.wst.jsdt.internal.core.builder.AbstractImageBuilder.compile(AbstractImageBuilder.java:288)
at
org.eclipse.wst.jsdt.internal.core.builder.BatchImageBuilder.compile(BatchImageBuilder.java:86)
at
org.eclipse.wst.jsdt.internal.core.builder.AbstractImageBuilder.compile(AbstractImageBuilder.java:227)
at
org.eclipse.wst.jsdt.internal.core.builder.BatchImageBuilder.build(BatchImageBuilder.java:58)
at
org.eclipse.wst.jsdt.internal.core.builder.JavaBuilder.buildAll(JavaBuilder.java:291)
at
org.eclipse.wst.jsdt.internal.core.builder.JavaBuilder.build(JavaBuilder.java:199)
at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:728)
at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
at
org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:199)
at
org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:239)
at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:292)
at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
at
org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:295)
at
org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:351)
at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:374)
at
org.eclipse.core.internal.events.AutoBuildJob.doBuild(AutoBuildJob.java:143)
at org.eclipse.core.internal.events.AutoBuildJob.run(AutoBuildJob.java:241)
at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54)
To resolve this error i explored about it..and below are links which i
explored :
Bug 391880 - javascript validator throws error, unable to build project
ClassCastException
but still i didn't get any proper solution to resolve this error.... So
please guide me to remove this error...its very urgent for me..
Thanks in advance..
Retrieve Session value in Javascript from Code behind file Aspx.cs
Retrieve Session value in Javascript from Code behind file Aspx.cs
I am storing some value in session through code behind file named
Index4.aspx.cs by using this code: Session[txtUsername.Text.ToUpper() +
"ChannelID_BC"] = 1111110;
But now how to retrieve it in Index$.aspx page through JavaScript
I am storing some value in session through code behind file named
Index4.aspx.cs by using this code: Session[txtUsername.Text.ToUpper() +
"ChannelID_BC"] = 1111110;
But now how to retrieve it in Index$.aspx page through JavaScript
ideas reseting stats in class
ideas reseting stats in class
Hi I made a simple program but when my monster dies the stats dont
reset(hp mainly) I am lost In how to make it reset every time the monsters
hp reaches 0 and the xp is awarded. I know that I can wright the code over
again and again but I would like to be able to make it continue is as
little amount of code as possible. Im still learning python so I dont
really know as much as everyone else here. Ive gotten to classes but not
so much in depth here is the code:
import random
def title():
print"hello Hero, welcome to staghold"
print"you have traveld along way, and you find yourself"
print"surrounded by and army of monsters as far as the eye can see"
print"begin to draw your sword.....you run full speed towards the army"
print"how many monsters can you kill before the inevatable comes?"
raw_input("(press enter to continue)")
def stats():
print"you have 200 health"
print"your level is 1"
print"you have 0 exp"
raw_input("(press enter to continue)")
class monster:
hp=50
monsterattack=random.randint
xp=random.randint(20,50)
health=200
level=1
exp=0
wave=1
title()
stats()
print"you run into a wave"
while level==1:
if monster.hp<=0:
print"you have defeated this wave of monsters"
wave+=1
exp+=monster.xp
print" you get, "+str(monster.xp)+" exp from the monster"
print"you now have, "+str(exp)+" exp"
if exp>=300:
level+=1
if level==2:
print"CONGRADULATIONS YOU HAVE REACHED LEVEL 2"
elif monster.hp>=0:
choice=raw_input("Will you 'fight' or 'run' from this horde?")
if choice=='fight':
print"you swing your sword at the monster"
att=random.randint(2, 13)
health-=monster.monsterattack(2,15)
monster.hp-=att
hp=200-health
print"you do, "+str(att)+" damage to the monster"
print"the monster does, "+str(hp)+" damage to you"
print"you have, "+str(health)+" health left"
print"the monster has, "+str(monster.hp)+" health left"
elif choice=="run":
print"you got away from this wave safely"
else:
print"NOT A VALID CHOICE"
Hi I made a simple program but when my monster dies the stats dont
reset(hp mainly) I am lost In how to make it reset every time the monsters
hp reaches 0 and the xp is awarded. I know that I can wright the code over
again and again but I would like to be able to make it continue is as
little amount of code as possible. Im still learning python so I dont
really know as much as everyone else here. Ive gotten to classes but not
so much in depth here is the code:
import random
def title():
print"hello Hero, welcome to staghold"
print"you have traveld along way, and you find yourself"
print"surrounded by and army of monsters as far as the eye can see"
print"begin to draw your sword.....you run full speed towards the army"
print"how many monsters can you kill before the inevatable comes?"
raw_input("(press enter to continue)")
def stats():
print"you have 200 health"
print"your level is 1"
print"you have 0 exp"
raw_input("(press enter to continue)")
class monster:
hp=50
monsterattack=random.randint
xp=random.randint(20,50)
health=200
level=1
exp=0
wave=1
title()
stats()
print"you run into a wave"
while level==1:
if monster.hp<=0:
print"you have defeated this wave of monsters"
wave+=1
exp+=monster.xp
print" you get, "+str(monster.xp)+" exp from the monster"
print"you now have, "+str(exp)+" exp"
if exp>=300:
level+=1
if level==2:
print"CONGRADULATIONS YOU HAVE REACHED LEVEL 2"
elif monster.hp>=0:
choice=raw_input("Will you 'fight' or 'run' from this horde?")
if choice=='fight':
print"you swing your sword at the monster"
att=random.randint(2, 13)
health-=monster.monsterattack(2,15)
monster.hp-=att
hp=200-health
print"you do, "+str(att)+" damage to the monster"
print"the monster does, "+str(hp)+" damage to you"
print"you have, "+str(health)+" health left"
print"the monster has, "+str(monster.hp)+" health left"
elif choice=="run":
print"you got away from this wave safely"
else:
print"NOT A VALID CHOICE"
MIPS Assembly to C
MIPS Assembly to C
So I'm trying to translate this MIPS assembly code into C. I'm confused on
a certain part of what's going on. Here is the MIPS assembly code: Assume
we have variables f, g, h, i, j stored in $s0, $s1, $s2, $s3 and $s4,
respectively. Assume the base addresses of arrays A and B are at $s6 and
$s7 respectively and they contain 4 byte words. I have inserted comments
to show I understand most of this.
sll $t0, $s0, 2 # $t0 = f * 4
add $t0, $s6, $t0 # $t0 = &A[f]
sll $t1, $s1, 2 # $t1 = g * 4
add $t1, $s7, $t1 # $t1 = &B[g]
lw $s0, 0($t0) # f = A[f]
addi $t2, $t0, 4 <-- Here's where I am confused. Since $t0 contains the
address of A[f], what does adding 4 do to that?
lw $t0, 0($t2)
add $t0, $t0, $s0
sw $t0, 0($t1)
So I'm trying to translate this MIPS assembly code into C. I'm confused on
a certain part of what's going on. Here is the MIPS assembly code: Assume
we have variables f, g, h, i, j stored in $s0, $s1, $s2, $s3 and $s4,
respectively. Assume the base addresses of arrays A and B are at $s6 and
$s7 respectively and they contain 4 byte words. I have inserted comments
to show I understand most of this.
sll $t0, $s0, 2 # $t0 = f * 4
add $t0, $s6, $t0 # $t0 = &A[f]
sll $t1, $s1, 2 # $t1 = g * 4
add $t1, $s7, $t1 # $t1 = &B[g]
lw $s0, 0($t0) # f = A[f]
addi $t2, $t0, 4 <-- Here's where I am confused. Since $t0 contains the
address of A[f], what does adding 4 do to that?
lw $t0, 0($t2)
add $t0, $t0, $s0
sw $t0, 0($t1)
Read file in blocks
Read file in blocks
I'm having an issue which I'm currently stuck on.
I have a big file in the following format:
Block 1
Line 1: Type1/Type2
Line 2: Time
Line 3: Data we need
Line 4: 00.*
Line 5: Fix 100
Line 6: In..
Line 7: Ou..
Line 8: Data we need
Line 9: Next
Line 10: Multi_Exit
Block 2
Line 1: Type1/Type2
Line 2: Time
Line 3: Data we need
Line 4: 00.*
Line 5: Fix 100
Line 6: In..
Line 7: Ou..
Line 8: Data we need
Line 9: Next
Line 10: Multi_Exit
Block 3
Line 1: Type1/Type2
Line 2: Time
Line 3: Data we need
Line 4: 00.*
Line 5: Fix 100
Line 6: In..
Line 7: Ou..
Line 8: Data we need
Line 9: Next
Line 10: Multi_Exit
Block 4
Line 1: Type1/Type2
Line 2: Time
Line 3: Data we need
Line 4: 00.*
Line 5: Fix 100
Line 6: In..
Line 7: Ou..
Line 8: Data we need
Line 9: Next
Line 10: Multi_Exit
Etc
I want to read the first line of each block, to check if Type1 or Type2.
After this I want to print Line 3 and Line 8 of each block and keep on
doing that until file ends.
I have tried the following codes:
p = './file.txt'
fin = open(p, 'r')
for i, line in enumerate(fin):
if i%11 == 2 or i%11 == 7:
print line
fin.close()
I have noticed after this code is run on my big file the line changes. I
can only assume my block lengths isn't fixed to 10 lines (plus one line
space before the next block starts). So this method isn't ideal.
I have also tried regular expression but I'm having trouble storing my
results on the format I want such as:
For Type 1
File the output should be: Line 3: Data Line 8: Data
Single space between it.
This is the next code I have tried:
for line in fin:
if re.match("(Line 1|Line 3|Line 8)", line):
writeToFile(line)
Where writeToFile function does the following:
def writeToFile(filein):
p = './output.txt'
fo = open(p, 'a')
fo.write(filein)
fo.close()
This is how the output.txt file looks:
Line 1: Type1/Type2
Line 3: Data we need
Line 8: Data we need
Line 1: Type1/Type2
Line 3: Data we need
Line 8: Data we need
Line 1: Type1/Type2
Line 3: Data we need
Line 8: Data we need
Which is not exactly the desired outcome. I don't even mind to play around
with this output file and check for Line 1 if Type 1. Then get Line 3 and
Line 8 put them in the same line. Keep on doing that, until Type 2 is
found and do the same with Line 3 and Line 8 and store it in different
output file.
I hope I haven't complicated things.
I'm having an issue which I'm currently stuck on.
I have a big file in the following format:
Block 1
Line 1: Type1/Type2
Line 2: Time
Line 3: Data we need
Line 4: 00.*
Line 5: Fix 100
Line 6: In..
Line 7: Ou..
Line 8: Data we need
Line 9: Next
Line 10: Multi_Exit
Block 2
Line 1: Type1/Type2
Line 2: Time
Line 3: Data we need
Line 4: 00.*
Line 5: Fix 100
Line 6: In..
Line 7: Ou..
Line 8: Data we need
Line 9: Next
Line 10: Multi_Exit
Block 3
Line 1: Type1/Type2
Line 2: Time
Line 3: Data we need
Line 4: 00.*
Line 5: Fix 100
Line 6: In..
Line 7: Ou..
Line 8: Data we need
Line 9: Next
Line 10: Multi_Exit
Block 4
Line 1: Type1/Type2
Line 2: Time
Line 3: Data we need
Line 4: 00.*
Line 5: Fix 100
Line 6: In..
Line 7: Ou..
Line 8: Data we need
Line 9: Next
Line 10: Multi_Exit
Etc
I want to read the first line of each block, to check if Type1 or Type2.
After this I want to print Line 3 and Line 8 of each block and keep on
doing that until file ends.
I have tried the following codes:
p = './file.txt'
fin = open(p, 'r')
for i, line in enumerate(fin):
if i%11 == 2 or i%11 == 7:
print line
fin.close()
I have noticed after this code is run on my big file the line changes. I
can only assume my block lengths isn't fixed to 10 lines (plus one line
space before the next block starts). So this method isn't ideal.
I have also tried regular expression but I'm having trouble storing my
results on the format I want such as:
For Type 1
File the output should be: Line 3: Data Line 8: Data
Single space between it.
This is the next code I have tried:
for line in fin:
if re.match("(Line 1|Line 3|Line 8)", line):
writeToFile(line)
Where writeToFile function does the following:
def writeToFile(filein):
p = './output.txt'
fo = open(p, 'a')
fo.write(filein)
fo.close()
This is how the output.txt file looks:
Line 1: Type1/Type2
Line 3: Data we need
Line 8: Data we need
Line 1: Type1/Type2
Line 3: Data we need
Line 8: Data we need
Line 1: Type1/Type2
Line 3: Data we need
Line 8: Data we need
Which is not exactly the desired outcome. I don't even mind to play around
with this output file and check for Line 1 if Type 1. Then get Line 3 and
Line 8 put them in the same line. Keep on doing that, until Type 2 is
found and do the same with Line 3 and Line 8 and store it in different
output file.
I hope I haven't complicated things.
Cannot install CMake for Mac OS X 10.8
Cannot install CMake for Mac OS X 10.8
I do not have cmake in terminal, so I went to it's webpage download page,
downloaded the "Mac OSX 64/32-bit Universal (for Intel, Snow Leopard/10.6
or later)" item, and the installer does nothing! I tried all 3 of them!!!
can anyone help me install cmake ????? huge thanks in advance!
I do not have cmake in terminal, so I went to it's webpage download page,
downloaded the "Mac OSX 64/32-bit Universal (for Intel, Snow Leopard/10.6
or later)" item, and the installer does nothing! I tried all 3 of them!!!
can anyone help me install cmake ????? huge thanks in advance!
Do I need a temporary table?
Do I need a temporary table?
I have the following query and I need to add "and distance < 10" to the
where clause. Because 'distance' is computed variable it can't be used in
where clause. I have tried HAVING instead of where but that breaks the
replace part.
I think the answer is to use a temporary table for the distance
computation but i can't figure out the syntax as everything I have tried
doesn't work.
All help appreciated please. Thanks.
select
Contractor.contractorID,
Contractor.firstName,
Contractor.lastName,
Contractor.emailAddress,
Contractor.nationality,
Contractor.dateOfBirth,
Contractor.address1,
Contractor.address2,
Contractor.city,
Contractor.county,
Contractor.postcode,
Contractor.country,
Contractor.tel,
Contractor.mob,
postcodes.Grid_N Grid_N1,
postcodes.Grid_E Grid_E1,
(select Grid_N from postcodes where pCode='".$postcode."') Grid_N2,
(select Grid_E from postcodes where pCode='".$postcode."') Grid_E2,
( (select
sqrt(((Grid_N1-Grid_N2)*(Grid_N1-Grid_N2))+((Grid_E1-Grid_E2)*(Grid_E1-Grid_E2)))
))/1000*0.621371192 as distance
from
Contractor,
postcodes
where
postcodes.Pcode =
replace(substring(Contractor.postcode,1,length(Contractor.postcode)-3),'','')
order by
distance asc
I have the following query and I need to add "and distance < 10" to the
where clause. Because 'distance' is computed variable it can't be used in
where clause. I have tried HAVING instead of where but that breaks the
replace part.
I think the answer is to use a temporary table for the distance
computation but i can't figure out the syntax as everything I have tried
doesn't work.
All help appreciated please. Thanks.
select
Contractor.contractorID,
Contractor.firstName,
Contractor.lastName,
Contractor.emailAddress,
Contractor.nationality,
Contractor.dateOfBirth,
Contractor.address1,
Contractor.address2,
Contractor.city,
Contractor.county,
Contractor.postcode,
Contractor.country,
Contractor.tel,
Contractor.mob,
postcodes.Grid_N Grid_N1,
postcodes.Grid_E Grid_E1,
(select Grid_N from postcodes where pCode='".$postcode."') Grid_N2,
(select Grid_E from postcodes where pCode='".$postcode."') Grid_E2,
( (select
sqrt(((Grid_N1-Grid_N2)*(Grid_N1-Grid_N2))+((Grid_E1-Grid_E2)*(Grid_E1-Grid_E2)))
))/1000*0.621371192 as distance
from
Contractor,
postcodes
where
postcodes.Pcode =
replace(substring(Contractor.postcode,1,length(Contractor.postcode)-3),'','')
order by
distance asc
Sunday, 15 September 2013
Impact of memory footprint on performance
Impact of memory footprint on performance
We have a .Net (VS 2012) 64 bit application, running on Windows Server
2012, which loads lots of data in memory to work with it for next 24 - 48
hours. As per our design we prefer to load the data upfront by connecting
to the Data source. Net memory footprint of the process goes up to 7-8 GB,
which is because we replicate the data for 4 independent threads, which
represent the parallel clients, so it like 2 GB of Data per client.
Hardware that we are using is having 128 GB of RAM, 4 CPU (24 Core) processor
I was wondering that does the memory footprint will have an impact on the
net performance of the process, like speed of execution, processor
utilization etc
Even when we have such a good RAM and the net usage never exceed 60%, will
there still be swapping of process pages to HD, thus making it slower,
when it is continuously used for 48 hours. Is there some server settings
or .Net c# code API, that will help us taking care of performance issues
occurring due to memory footprint. We can explicitly tell the system that
our process needs lots of memory
We have a .Net (VS 2012) 64 bit application, running on Windows Server
2012, which loads lots of data in memory to work with it for next 24 - 48
hours. As per our design we prefer to load the data upfront by connecting
to the Data source. Net memory footprint of the process goes up to 7-8 GB,
which is because we replicate the data for 4 independent threads, which
represent the parallel clients, so it like 2 GB of Data per client.
Hardware that we are using is having 128 GB of RAM, 4 CPU (24 Core) processor
I was wondering that does the memory footprint will have an impact on the
net performance of the process, like speed of execution, processor
utilization etc
Even when we have such a good RAM and the net usage never exceed 60%, will
there still be swapping of process pages to HD, thus making it slower,
when it is continuously used for 48 hours. Is there some server settings
or .Net c# code API, that will help us taking care of performance issues
occurring due to memory footprint. We can explicitly tell the system that
our process needs lots of memory
Problems in Java Hex Numbers
Problems in Java Hex Numbers
I was trying to implement Hex calculations on two hex numbers, I am facing
a weird problem
When I tried adding two positive hex numbers, it gave me a negative
result. Here delta =9e3779b9 and sum=0
Here the addition must be 9E3779B9 or 2654435769 in decimal, but the code
in Java makes it negative. Here is the code:
long delta = 0x9e3779b9;
long sum = 0;
sum = sum + delta;
System.out.println(sum);
sum = sum << 5;
System.out.println(sum);
having output as
-1640531527
-52497008864
I believe this is due to the first sign bit for long, how to solve this
problem so that it can ignore the negative?
I was trying to implement Hex calculations on two hex numbers, I am facing
a weird problem
When I tried adding two positive hex numbers, it gave me a negative
result. Here delta =9e3779b9 and sum=0
Here the addition must be 9E3779B9 or 2654435769 in decimal, but the code
in Java makes it negative. Here is the code:
long delta = 0x9e3779b9;
long sum = 0;
sum = sum + delta;
System.out.println(sum);
sum = sum << 5;
System.out.println(sum);
having output as
-1640531527
-52497008864
I believe this is due to the first sign bit for long, how to solve this
problem so that it can ignore the negative?
e.preventDefault() not working
e.preventDefault() not working
Guys
I have a table which rows are generated with a click event of an element.
Now, this works perfectly, the problem is with the delete part. For
example I have already added 5 rows, when I click the delete button (the
delete button is created through JQuery too on the addRow() click event),
all rows added through the JQuery function are being deleted and the form
is submitting event though I have an e.preventDefault() method called.
Javascript/JQuery code:
var counter = 2;
window.addRow = function addRow() {
var newRow = $('<tr><td><label>'+ counter
+'</label></td><td><textarea name="txtActionStep' + counter +
'" style="width:300px; height: 50px;
word-wrap:break-word;"></textarea></td><td valign="top"><input
type="text" name="txtOwner' + counter + '"/></td><td><button
class="delete">delete</button></td></tr>');
counter++;
$('table.actionsteps-list').append( newRow );
}
$('table.actionsteps-list').on('click', '.delete', function(e){
e.preventDefault(); // stops the page jumping to the top
$(this).closest('tr').remove();
});
function postForm() {
var form = document.getElementById('actionStepsForm');
document.getElementById('rowCount').value = counter-1;
form.submit();
}
HTML Code (the form itself):
<form name="actionStepsForm" id="actionStepsForm"
action="add_reprocessing.php?action=add" method="post">
<table class="actionsteps-list" width="510">
<tr>
<th colspan="3" align="left">Action Steps</th>
</tr>
<tr>
<td>Step #</td><td>Action Step</td><td>Owner</td>
</tr>
<tr>
<td>
<label>1</label>
</td>
<td>
<textarea name="txtActionStep1" style="width:300px;
height: 50px; word-wrap:break-word;"></textarea>
</td>
<td valign="top">
<input type="text" name="txtOwner1" />
</td>
</tr>
</table>
<table width="510">
<tr>
<td align="right"><a href="#" title="" onclick="addRow();
return false;">Add Action</a></td>
</tr>
</table>
<input type="button" value="Create" onclick="postForm(); return
false;" />
<input type="hidden" value="" id="rowCount" name="rowCount" />
</form>
Believe it or not, I've been stuck here for almost 3 days now. I can't
find any fix online. I don't what's wrong.
Guys
I have a table which rows are generated with a click event of an element.
Now, this works perfectly, the problem is with the delete part. For
example I have already added 5 rows, when I click the delete button (the
delete button is created through JQuery too on the addRow() click event),
all rows added through the JQuery function are being deleted and the form
is submitting event though I have an e.preventDefault() method called.
Javascript/JQuery code:
var counter = 2;
window.addRow = function addRow() {
var newRow = $('<tr><td><label>'+ counter
+'</label></td><td><textarea name="txtActionStep' + counter +
'" style="width:300px; height: 50px;
word-wrap:break-word;"></textarea></td><td valign="top"><input
type="text" name="txtOwner' + counter + '"/></td><td><button
class="delete">delete</button></td></tr>');
counter++;
$('table.actionsteps-list').append( newRow );
}
$('table.actionsteps-list').on('click', '.delete', function(e){
e.preventDefault(); // stops the page jumping to the top
$(this).closest('tr').remove();
});
function postForm() {
var form = document.getElementById('actionStepsForm');
document.getElementById('rowCount').value = counter-1;
form.submit();
}
HTML Code (the form itself):
<form name="actionStepsForm" id="actionStepsForm"
action="add_reprocessing.php?action=add" method="post">
<table class="actionsteps-list" width="510">
<tr>
<th colspan="3" align="left">Action Steps</th>
</tr>
<tr>
<td>Step #</td><td>Action Step</td><td>Owner</td>
</tr>
<tr>
<td>
<label>1</label>
</td>
<td>
<textarea name="txtActionStep1" style="width:300px;
height: 50px; word-wrap:break-word;"></textarea>
</td>
<td valign="top">
<input type="text" name="txtOwner1" />
</td>
</tr>
</table>
<table width="510">
<tr>
<td align="right"><a href="#" title="" onclick="addRow();
return false;">Add Action</a></td>
</tr>
</table>
<input type="button" value="Create" onclick="postForm(); return
false;" />
<input type="hidden" value="" id="rowCount" name="rowCount" />
</form>
Believe it or not, I've been stuck here for almost 3 days now. I can't
find any fix online. I don't what's wrong.
File I/O python
File I/O python
I am trying to find few strings in a file but the line.find() doesn't
return true for any string in the file.Please have a look an suggest
something.The search has to be sequential and I need to hold the offset
value for every string which is found. and the search for next string
should start from that offset.
def CheckFile(*argv):
import os
Filename = argv[0]
Search = argv[1]
Flag = False
FileFlag = False
offset1 = 0
offset2 = 0
if os.path.exists(Filename) == 0:
return "File Doesn't exist", 1
else:
fh = open(Filename,"r")
for line in fh:
if line.find(Search):
print "Success"
print (line)
Flag = True
offset1 = fh.tell()
#offset1 = int(offset1)
break
else:
fh.close()
return "Could not find String %s"%(Search), 1
#fh.close()
if Flag:
fh = open(Filename,"r")
print(offset1)
fh.seek(offset1)
for line in fh:
if line.find("TestDir1\TestFile1.txt"):
print "Success"
print (line)
FileFlag = True
offset2 = fh.tell()
#offset2 = int(offset2)
break
else:
fh.close()
return "Couldn't Find File TestDir1\TestFile1.txt", 1
#fh.close()
if Flag and FileFlag:
fh = open(Filename,"r")
print(offset2)
fh.seek(offset2)
for line in fh:
if line.find("Persistent Handle: True"):
print "Success"
return "Success -- Found the strings", 0
else:
fh.close()
return "Failur -- Failed to find 'Persistent Handle: True'", 1
I am trying to find few strings in a file but the line.find() doesn't
return true for any string in the file.Please have a look an suggest
something.The search has to be sequential and I need to hold the offset
value for every string which is found. and the search for next string
should start from that offset.
def CheckFile(*argv):
import os
Filename = argv[0]
Search = argv[1]
Flag = False
FileFlag = False
offset1 = 0
offset2 = 0
if os.path.exists(Filename) == 0:
return "File Doesn't exist", 1
else:
fh = open(Filename,"r")
for line in fh:
if line.find(Search):
print "Success"
print (line)
Flag = True
offset1 = fh.tell()
#offset1 = int(offset1)
break
else:
fh.close()
return "Could not find String %s"%(Search), 1
#fh.close()
if Flag:
fh = open(Filename,"r")
print(offset1)
fh.seek(offset1)
for line in fh:
if line.find("TestDir1\TestFile1.txt"):
print "Success"
print (line)
FileFlag = True
offset2 = fh.tell()
#offset2 = int(offset2)
break
else:
fh.close()
return "Couldn't Find File TestDir1\TestFile1.txt", 1
#fh.close()
if Flag and FileFlag:
fh = open(Filename,"r")
print(offset2)
fh.seek(offset2)
for line in fh:
if line.find("Persistent Handle: True"):
print "Success"
return "Success -- Found the strings", 0
else:
fh.close()
return "Failur -- Failed to find 'Persistent Handle: True'", 1
Ways to configure Log4j XML Configuration
Ways to configure Log4j XML Configuration
I am using log4j to log information in my web application. I have chosen
log4j.xml type of configuration instead of log4j.properties. I remember
that, for log4j.properties configuration, I did not write Java code lines
to find the log4j.property file location. However, for log4j.xml file
configuration I am specifying explicitly to find it like this
DOMConfigurator.configure("log4j.xml");//it reads file from classpath,
working!
Also, tested my application removing the above statement from source. It
doesn't see to work. None of the debug statements were printed except
System.out.println();
I have read that log4j by default looks for log4jproperties file or
log4j.xml file in the classpath. I checked in the deployed web
application, log4j.xml file is in web-inf/classes. Even though it can't
find log4j.xml.
Is it that, the above code line is mandatory for log4j xml configuration
in Java? In fact, can't Java source code doesn't pickup log4j.xml from the
classpath without explicit specification as above?
I am using log4j to log information in my web application. I have chosen
log4j.xml type of configuration instead of log4j.properties. I remember
that, for log4j.properties configuration, I did not write Java code lines
to find the log4j.property file location. However, for log4j.xml file
configuration I am specifying explicitly to find it like this
DOMConfigurator.configure("log4j.xml");//it reads file from classpath,
working!
Also, tested my application removing the above statement from source. It
doesn't see to work. None of the debug statements were printed except
System.out.println();
I have read that log4j by default looks for log4jproperties file or
log4j.xml file in the classpath. I checked in the deployed web
application, log4j.xml file is in web-inf/classes. Even though it can't
find log4j.xml.
Is it that, the above code line is mandatory for log4j xml configuration
in Java? In fact, can't Java source code doesn't pickup log4j.xml from the
classpath without explicit specification as above?
Efficient all purposes PDO query for all situation
Efficient all purposes PDO query for all situation
Rather than have different PHP functions for different interaction with
the database is it possible to have a one size fits all function. Below is
my attempt which works, but what are the limitations of this if any? And
will it unnecessarily lag the performance of the site?
function
fetch($field,$table,$where,$is,$limit,$offset,$order,$eqt,$function){
global $kdb;
if(!$eqt){ $eqt = "="; }
if(!$limit){ $limit = "1"; }
if(!$function){ $function = "SELECT"; }
$sql = "$function $field FROM $table";
$wheres = explode(',',$where); $is = explode(',',$is); $eqt =
explode(',',$eqt);
$eachcount = 0;
$eachby = "WHERE";
foreach($wheres as $where){
if(!$eqt[$eachcount]){
$eqt[$eachcount] = $eqt[0];
}
if($method == 'LIKE'){
$sql .= " $eachby $where $eqt[$eachcount] '%$is[$eachcount]%' ";
}
else {
$sql .= " $eachby $where $eqt[$eachcount] '$is[$eachcount]' ";
}
$eachby = "AND";
}
$stm = $kdb->prepare($sql);
$stm->execute();
if($function == 'count'){
$row = $stm->fetchColumn();
}
elseif($stm->rowCount() <= 1) {
$row = $stm->fetch();
}
else{
$row = $stm->fetchAll();
}
return $row;
}
Rather than have different PHP functions for different interaction with
the database is it possible to have a one size fits all function. Below is
my attempt which works, but what are the limitations of this if any? And
will it unnecessarily lag the performance of the site?
function
fetch($field,$table,$where,$is,$limit,$offset,$order,$eqt,$function){
global $kdb;
if(!$eqt){ $eqt = "="; }
if(!$limit){ $limit = "1"; }
if(!$function){ $function = "SELECT"; }
$sql = "$function $field FROM $table";
$wheres = explode(',',$where); $is = explode(',',$is); $eqt =
explode(',',$eqt);
$eachcount = 0;
$eachby = "WHERE";
foreach($wheres as $where){
if(!$eqt[$eachcount]){
$eqt[$eachcount] = $eqt[0];
}
if($method == 'LIKE'){
$sql .= " $eachby $where $eqt[$eachcount] '%$is[$eachcount]%' ";
}
else {
$sql .= " $eachby $where $eqt[$eachcount] '$is[$eachcount]' ";
}
$eachby = "AND";
}
$stm = $kdb->prepare($sql);
$stm->execute();
if($function == 'count'){
$row = $stm->fetchColumn();
}
elseif($stm->rowCount() <= 1) {
$row = $stm->fetch();
}
else{
$row = $stm->fetchAll();
}
return $row;
}
Why isn't this an infinite loop?
Why isn't this an infinite loop?
Why doesn't the following loop run infinite times? I expect that upon
reaching 65535, i should overflow back to zero.
#include<stdio.h>
int main()
{
short int i = 0; //(assume short int is 2 bytes)
for(i<=5 && i>=-1; ++i; i>0)
printf("%u\n", i);
return 0;
}
Why doesn't the following loop run infinite times? I expect that upon
reaching 65535, i should overflow back to zero.
#include<stdio.h>
int main()
{
short int i = 0; //(assume short int is 2 bytes)
for(i<=5 && i>=-1; ++i; i>0)
printf("%u\n", i);
return 0;
}
Saturday, 14 September 2013
video shot detection method
video shot detection method
I wanted to get shots from a whole video. For example, if I give input as
a video, then output should be parts of video(video shots/clips).I have
tried a lot about this; but did not reach solution. So if anyone knows any
technique for splitting the video into different shots, let me know. Code
can be in mat lab or Open CV.
I wanted to get shots from a whole video. For example, if I give input as
a video, then output should be parts of video(video shots/clips).I have
tried a lot about this; but did not reach solution. So if anyone knows any
technique for splitting the video into different shots, let me know. Code
can be in mat lab or Open CV.
how to dynamically add $scope in Angular
how to dynamically add $scope in Angular
here is my HTML:
...
<table class="tickerTable">
<thead>
<th class="first">Symbol</th>
<th>Accts</th>
<th>Shares Bought</th>
<th>Shares Sold</th>
<th>Shares Own</th>
<th>Case Filed</th>
<th>Est. Losses</th>
<th>Case Status</th>
</thead>
<tbody ng-repeat="ticker in tickers | orderBy:'Status':true | filter:search">
<tr class="{{ticker.Status | status}}" ng-click="showTrades(ticker)">
<td class=" left link">{{ticker.Ticker}}</td>
<td class="middle link">{{ticker.TradeCount}}</td>
<td>{{ticker.TotalBought | number:2}}</td>
<td>{{ticker.TotalSold | number:2}}</td>
<td>{{ticker.TotalSharesNow | number:2}}</td>
<td>{{ticker.DateFiled}}</td>
<td>{{ticker.EstimatedLosses | currency}}</td>
<td class="link">{{ticker.Status | status}}</td>
</tr>
<tr ng-show="currentItem == ticker">
<td colspan="8">{{trades}}<div ng-include="loadTrades == ticker"></div>
</div></td>
</tr>
</tbody>
</table>
here is the controller:
$scope.showTrades = function(ticker){
var i = ticker.TickerID+ticker.AlertID;
$scope.trades = null;
$scope.currentItem = ticker;
return $scope.trades = Trades.query({SHFUserID:ticker.SHFUserID,
TickerID:ticker.TickerID, AlertID:ticker.AlertID});
};
the table is populated with many rows. then for each row i add a blank row
that is hidden by default. when the row is clicked the hidden row is
displayed and the $scope.trades is loaded and {{trades}} displays the
data. The problem is that since I am dynamically generating the empty TR
rows based on how many "ticker in Tickers" the {{trades}} data is
populated in each of them. even thought the data is hidden this is not the
desired result. I only want to load the {{trades}} data into the visible
TR exposed by ng-show.
here is my HTML:
...
<table class="tickerTable">
<thead>
<th class="first">Symbol</th>
<th>Accts</th>
<th>Shares Bought</th>
<th>Shares Sold</th>
<th>Shares Own</th>
<th>Case Filed</th>
<th>Est. Losses</th>
<th>Case Status</th>
</thead>
<tbody ng-repeat="ticker in tickers | orderBy:'Status':true | filter:search">
<tr class="{{ticker.Status | status}}" ng-click="showTrades(ticker)">
<td class=" left link">{{ticker.Ticker}}</td>
<td class="middle link">{{ticker.TradeCount}}</td>
<td>{{ticker.TotalBought | number:2}}</td>
<td>{{ticker.TotalSold | number:2}}</td>
<td>{{ticker.TotalSharesNow | number:2}}</td>
<td>{{ticker.DateFiled}}</td>
<td>{{ticker.EstimatedLosses | currency}}</td>
<td class="link">{{ticker.Status | status}}</td>
</tr>
<tr ng-show="currentItem == ticker">
<td colspan="8">{{trades}}<div ng-include="loadTrades == ticker"></div>
</div></td>
</tr>
</tbody>
</table>
here is the controller:
$scope.showTrades = function(ticker){
var i = ticker.TickerID+ticker.AlertID;
$scope.trades = null;
$scope.currentItem = ticker;
return $scope.trades = Trades.query({SHFUserID:ticker.SHFUserID,
TickerID:ticker.TickerID, AlertID:ticker.AlertID});
};
the table is populated with many rows. then for each row i add a blank row
that is hidden by default. when the row is clicked the hidden row is
displayed and the $scope.trades is loaded and {{trades}} displays the
data. The problem is that since I am dynamically generating the empty TR
rows based on how many "ticker in Tickers" the {{trades}} data is
populated in each of them. even thought the data is hidden this is not the
desired result. I only want to load the {{trades}} data into the visible
TR exposed by ng-show.
How to query count with 0 rows
How to query count with 0 rows
My query is to get the count of total rows, along with the columns. An
example table, which has to be a temp table is:
temp(a1,a2)
I need to query a1,a2, and total number of rows.
SELECT COUNT(*) as TotalRow, a1, a2 from #temp group by a1,a2
The query works fine for table with rows >=1. However, for some special
case, this table has zero row. In that case, TotalRow does not return a
value (it should be zero). How can I get that query work for all cases
including zero row? Thanks.
My query is to get the count of total rows, along with the columns. An
example table, which has to be a temp table is:
temp(a1,a2)
I need to query a1,a2, and total number of rows.
SELECT COUNT(*) as TotalRow, a1, a2 from #temp group by a1,a2
The query works fine for table with rows >=1. However, for some special
case, this table has zero row. In that case, TotalRow does not return a
value (it should be zero). How can I get that query work for all cases
including zero row? Thanks.
DATE field covnersion to date+time with timezone
DATE field covnersion to date+time with timezone
I am trying to convert a date into date+time with timezone as below based
on the day light savings: INPUTDATE: 12/23/1990 OUTPUT DATE: 12-23-1990
00:00:00 -5:00
kindly help with the query conversion.
I am trying to convert a date into date+time with timezone as below based
on the day light savings: INPUTDATE: 12/23/1990 OUTPUT DATE: 12-23-1990
00:00:00 -5:00
kindly help with the query conversion.
combinatorial optimization: multiple upgrade paths with inventory constraints
combinatorial optimization: multiple upgrade paths with inventory constraints
I'm playing a video game, and i want to make a program that calculates the
globally optimal build/upgrade path towards a fixed 6 item goal.
Time, Cost, Inventory constraints, and effectiveness (short/mid/long-term)
ratings are to be considered. Identifying local spikes in effectiveness
are also welcomed, but optional. I don't know how to classify this
problem, but i'm guessing its a type of graph search. The fact that
multiple criteria are being optimized is making things confusing for me.
Problem details:
There are 6 free slots in your bag to hold items.
There are 2 classes of items: basic items, and composite items.
Composite items are built/merged from basic items, and other composite items.
If you have enough gold, you can buy a composite item, and its missing sub
components, all at once, using only 1 inventory slot.
The build path for various composite items are fixed, and many basic
components are featured in more than one recipe.
Gold is earned at a fixed rate over time, as well as in small
non-deterministic bursts.
There exists no more than 50 items, maybe less.
So, thinking about the problem...
Tackling the gold/time issue first
We can either ignore the non-deterministic aspect, or use some statistical
averages. Let's make life easy, and ignore it for now. Since gold, and
time, are now directly related in our simplified version, they can be
logically merged.
Combinatorial expansion of feasible paths
A graph could be built, top down, from each of the 6 goal items,
indicating their individual upgrade hierarchies. Components that are
shared between the various hierarchies can be connected, giving branch
decisions. The edges between components can be weighted by their cost. At
this point, it sounds like a shortest path problem, except with multiple
parallel and overlapping goals.
Now the question is: how do inventory constraints play into this?
The inventory/cost constraints, add a context, that both disables (no free
slots; not enough gold), and enables (two items merged freeing a slot)
various branch decisions, based upon previous choices and elapsed time.
How does one expand all the feasible possibilities? Does it have to be
done at every given step? How many total combinations are there? Does this
fall under topological combinatorics?
Rating Effectiveness
If the above expansion produces less than a few billion possibilities, we
can just exhaustive search using OpenCL/CUDA. I'm not sure what other
options are available, since most graph search stuff seems to just solve
for one criteria.
I'm playing a video game, and i want to make a program that calculates the
globally optimal build/upgrade path towards a fixed 6 item goal.
Time, Cost, Inventory constraints, and effectiveness (short/mid/long-term)
ratings are to be considered. Identifying local spikes in effectiveness
are also welcomed, but optional. I don't know how to classify this
problem, but i'm guessing its a type of graph search. The fact that
multiple criteria are being optimized is making things confusing for me.
Problem details:
There are 6 free slots in your bag to hold items.
There are 2 classes of items: basic items, and composite items.
Composite items are built/merged from basic items, and other composite items.
If you have enough gold, you can buy a composite item, and its missing sub
components, all at once, using only 1 inventory slot.
The build path for various composite items are fixed, and many basic
components are featured in more than one recipe.
Gold is earned at a fixed rate over time, as well as in small
non-deterministic bursts.
There exists no more than 50 items, maybe less.
So, thinking about the problem...
Tackling the gold/time issue first
We can either ignore the non-deterministic aspect, or use some statistical
averages. Let's make life easy, and ignore it for now. Since gold, and
time, are now directly related in our simplified version, they can be
logically merged.
Combinatorial expansion of feasible paths
A graph could be built, top down, from each of the 6 goal items,
indicating their individual upgrade hierarchies. Components that are
shared between the various hierarchies can be connected, giving branch
decisions. The edges between components can be weighted by their cost. At
this point, it sounds like a shortest path problem, except with multiple
parallel and overlapping goals.
Now the question is: how do inventory constraints play into this?
The inventory/cost constraints, add a context, that both disables (no free
slots; not enough gold), and enables (two items merged freeing a slot)
various branch decisions, based upon previous choices and elapsed time.
How does one expand all the feasible possibilities? Does it have to be
done at every given step? How many total combinations are there? Does this
fall under topological combinatorics?
Rating Effectiveness
If the above expansion produces less than a few billion possibilities, we
can just exhaustive search using OpenCL/CUDA. I'm not sure what other
options are available, since most graph search stuff seems to just solve
for one criteria.
Subscribe to:
Comments (Atom)