text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: MVC3 Display text using Model I am trying to display a text on the view from the database.
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Admin.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<HUI.Models.Events>>" %>
Tried to use the following but did not work
<%:Model.First().Name.ToString();%>
Thanks in advance.
A: How is the semicolon after ToString not giving you a compilation error?
If Name property is of type string then this should simply suffice:
<%:Model.First().Name %>
Can you send the error details if any, if this suggestion doesn't work?
Also - error details would help us too.
A: There are two issues here.
First, you have the semi-colon at the end as others mentioned.
Secondly, you have:
IEnumerable<HUI.Models.Events>
Are you sure you don't want:
IEnumerable<HUI.Models.Event> (Event - not Events)?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578191",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: document.getElementById onclick only working once per page load I have a link:
<a id="lnk" href="${pageContext.request.contextPath}/path/path2.pdf?var0=sometext&var1=moretext" onclick="update();"target="_blank">click to export</a>
and a JavaScript function in a separate file:
function update()
{
var link = document.getElementById("lnk");
link.href += "&var2=" + document.getElementById("textareaIdName").value;
return;
}
This is supposed to grab the text from a textarea box in a jsp form to pass into controller for output. It works the first time I click the link, but then if I change the text in the box and click link again it holds the same value from the first click on every other link click until I reload the page regardless of what I change in the text box. The link returns a file download.
How can I keep getting new text from textarea without reloading the page?
A: This occurs because you are using += each time the link is pressed which will keep concatinating the var2 onto the end of the hyperlink, to make this work you should use:
var linkName = "${pageContext.request.contextPath}/path/path2.pdf?var0=sometext&var1=moretext";
function update(obj) {
obj.href = linkName + "&var2=" + document.getElementById("textareaIdName").value;
return;
}
<a id="lnk" href="" onclick="update(this);" target="_blank">click to export</a>
A: In your html:
<a ... onclick="return update(this);">click me</a>
Passing this in the handler means that this in the function references the DOM element, so you don't have to use getElementById, so the function is:
function update(link) {
link.href = /* whatever */;
}
Now you can put the handler on multiple elements without knowing or using the id.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578194",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: easy slider jquery for background image i am trying to slide background image with animate. as i want if my first background image. second will continues start
here is my code
$('.next').live('click',function() {
$('.ac_bgimage').animate({
left:"-80em"
},1500, function(){
test();
});
});
function test() {
$('.ac_bgimage').attr('src','images/2.jpg');
$('.ac_bgimage').css('left','0em');
}
as first image is working fine but it display blank screen . in this blank screen i want second upcoming screen
Thanks in advance
A: I'm not fully sure if I understand you correctly, but here are a few thoughts:
The callback is called after the animation has finished. According to your code you should see the first image move to the left and once it’s "gone" the second image should pop into it’s original place. Since an image tag can only hold one source at a time, you won't be able to get rid of this "gap" anyhow they way you're doing it.
Also animating by em might be a bad choice in this case, I'd try a px value instead. If it's a dynamic value, read it out using e.g. .width().
If you just want to have a simple image rotation, there's a million plugins for jQuery out there which do just that. I've written a really tiny solution a while ago myself, maybe the code can give you some pointers: https://github.com/polarblau/simpleslider
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578195",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Magento 1.5 CE Newsletter don't send The Newsletter is not sent in Magento CE v.15
I understand I need to set-up some sort of Cron to send newsletter. But isnt Cron (scheduled task) already built in under back end Systems>Congfiguration>Advance>System?
(I have enabled MailChimp if that could be a problem?)
Please advise or point me in the right direction. Thank you.
A: You need add cron.sh to your server crontab. More info you can read in this article.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578196",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Heroku ActiveRecord Error: PgSQL put null in id field I just deployed a simple Ruby on Rails (3.0.10) application to Heroku. There is a line of code create a new User object like this.
User.create(:name => "[name here]", :email => "[email here]")
It can run well in my local machine, which is using MySQL. After I deployed it to Heroku, I got an error.
ActiveRecord::StatementInvalid: PGError: ERROR: null value in column "id" violates not-null constraint : INSERT INTO "users" ("id", "name", "email", "created_at", "updated_at") VALUES (NULL, '[name here]', '[email here]', '2011-09-28 03:59:12.908593', '2011-09-28 03:59:12.908593') RETURNING "id"
I have no idea what's wrong with my code. Did i miss anything?
Thanks all.
UPDATE
Migration
class CreateUsers < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.string :email
t.string :name
t.timestamps
end
end
def self.down
drop_table :users
end
end
Schema
ActiveRecord::Schema.define(:version => 20110922071106) do
create_table "users", :force => true do |t|
t.string "email"
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
end
A: Did you do this:
(Taken from http://railsapps.github.com/rails-heroku-tutorial.html)
Replace SQLite with PostgreSQL If you are developing locally using
SQLite, you will need to switch to PostgreSQL for deployment to
Heroku. If you don’t want to develop using PostgreSQL locally, you
can set up your Gemfile to use SQLite for development and PostgreSQL
for production.
To switch from SQLite to PostgreSQL for deployment to Heroku, edit
your Gemfile and change this line:
gem 'sqlite3'
To this:
group :production do
gem 'pg'
end
group :development, :test do
gem 'sqlite3'
end
A: For anyone else looking, I had this same problem. Worked fine in dev, but failed in production with Postgres. The problem I had I tracked back to the CanCan plugin, specifically code I had that was creating a guest user the ability.rb file, if no user object existed. The guest account was suggested in a Railscast. I removed the User.new guest creation command and the problem resolved.
A: I just re-create the whole RoR application, and copy all the controllers, models, and views that I built to the new app. It is now running well.
I tried to compare 2 versions and didn't have any result. Will let you guys know if I find out the cause of this.
Thanks all. :)
A: I had a similar problem. if you try to reload the schema (on local, dont do it on production obviously), you should see a difference in what you think you have and what the database actually thinks.
rake db:schema:dump
rake db:schema:load
THIS WILL ERASE YOUR DATA. But you should see a difference in the schema for 'users'. This was my difference:
The fresh dump showed:
create_table "posts", :id => :false, :force => true do |t|
t.integer "id", :null => false, :limit=> 8
t.integer "object_id", :limit => 8
t.string "post_type"
t.string "from_id"
t.text "picture_url"
t.text "video_source"
t.integer "shares"
t.integer "likes"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.integer "image_size", :limit => 8
t.integer "vid_size", :limit => 8
end
But i know that id is handled by rails and this should be:
create_table "posts", :force => true do |t|
t.integer "object_id", :limit => 8
t.string "post_type"
t.string "from_id"
t.text "picture_url"
t.text "video_source"
t.integer "shares"
t.integer "likes"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.integer "image_size", :limit => 8
t.integer "vid_size", :limit => 8
end
If this is also the case for you, simply add to your user model:
set_primary_key :id
That reset it and it works now. I still don't know the cause of the problem but this fixed it for me.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578198",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: C++ - Testing Applications with QT in VS 2008 I have a scenario where I should test an application (exe) with QT Test library. I've read that it's not possible to test application (exe) because QT will hesitate in linking phase for unresolved symbols.
The solution is to set configuration type to Static Library (.lib) [Again according what I've read]. However, is there a good technical way to test this kind of application projects, with QT if possible?
Thanks a lot people!
SOLUTION:
A bit more of background: My project was composed with only one cpp (that have the logic and the main entry point.) I wanted to test it in my QT_Test_Project.
With this scenario I have to split in three files, one for just having the main entry point (.cpp), and the other ones that have the correspondent logic (.cpp and .h)
Now in my QT_Test_Project I included just the logic header, I could compile OK, but linking phase will fail since it couldn't resolved external symbols.
With this in mind, using Visual Studio 2008, I just have to include in my QT_Test_Project the .cpp logic file as an existing one (to avoid duplicating the code.), then compile and all went as expected.
I don't really know if there is an alternative way to test this kind of things.
Hope this could help anyone.
Regards.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578200",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Need ideas on fixing RSS feed parsing http://www.ibm.com/developerworks/opensource/library/x-android/
I am using the code here, specifically the AndroidSaxParser. The problem is, is that I get all 4 parts of the Message objects the same as the title. I've combed it over and over, but I can't find anything wrong with what I put together.
Any ideas on where to look?
Here is the code:
public class AndroidSaxFeedParser extends BaseFeedParser {
public AndroidSaxFeedParser(String feedUrl) {
super(feedUrl);
}
public List<Message> parse() {
final Message currentMessage = new Message();
RootElement root = new RootElement("rss");
final List<Message> messages = new ArrayList<Message>();
Element channel = root.getChild("channel");
Element item = channel.getChild(ITEM);
item.setEndElementListener(new EndElementListener(){
public void end() {
messages.add(currentMessage.copy());
}
});
item.getChild(TITLE).setEndTextElementListener(new EndTextElementListener(){
public void end(String body) {
currentMessage.setTitle(body);
}
});
item.getChild(LINK).setEndTextElementListener(new EndTextElementListener(){
public void end(String body) {
currentMessage.setLink(body);
}
});
item.getChild(DESCRIPTION).setEndTextElementListener(new EndTextElementListener(){
public void end(String body) {
currentMessage.setDescription(body);
}
});
item.getChild(PUB_DATE).setEndTextElementListener(new EndTextElementListener(){
public void end(String body) {
currentMessage.setDate(body);
}
});
try {
Xml.parse(this.getInputStream(), Xml.Encoding.UTF_8, root.getContentHandler());
} catch (Exception e) {
throw new RuntimeException(e);
}
return messages;
}
}
public abstract class BaseFeedParser implements FeedParser {
// names of the XML tags
static final String PUB_DATE = "pubDate";
static final String DESCRIPTION = "description";
static final String LINK = "link";
static final String TITLE = "title";
static final String ITEM = "item";
static final String CHANNEL = "channel";
final URL feedUrl;
protected BaseFeedParser(String feedUrl){
try {
this.feedUrl = new URL(feedUrl);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
protected InputStream getInputStream() {
try {
return feedUrl.openConnection().getInputStream();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578201",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: background url and file organisation I am changing background image dynamically, it works online but doesn't work as offline. This is how I open a web page http://localhost:8080/PROJECT/
web.xml
<welcome-file-list>
<welcome-file> myHTML/myHTML.html </welcome-file>
</welcome-file-list>
CSS
#me {
background-url: url('image/me.jpg')
}
HTML
<div id="me"></div>
Project structure
I change background image dynamically from client side as follows:
<div id="me" style="background:url('/PROJECT/imageNew/your.jpg')"></div>
Now I just save this page to client(local) machine and check, but the image goes missing when page opens locally, it only works if I change in background url as follows:
background: url(../PROJECT/imageNew/your.jpg)
But I don't want to make change each time after saving the file on client's machine. How can I specify a path which works in server and client side?
A: It seems as if the problem stems from the fact that when running on the server, your code is executing from the root directory, whereas on the client's machine (I would imagine) you are not.
You should be able to use the second path you've posted (../PROJECT/imageNew/your.jpg) in both locations. You've already verified that this works on the client's machine, and on the server, the parent directory (../) should take no effect, as your code already appears to be executing on the root of the machine, thereby effectively making the path /PROJECT/imageNew/your.jpg, which is what it was before.
Hope this helps!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578203",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to hookup the LinkButton in a GridView with a ModalPopupExtender in ASP.Net C#? I really need some help here. I am trying to hookup a linkbutton in my GridView to a ModalPopupExtender, but with no luck. Basically I have a GridView which list all the users' info from a database, and I made the username as linkbutton. When you click the username, a modalpopup should show up, and you should be able to edit the user and update the database. I also I have an Add button. when you click the button, the same modalpopup should show up and you can add a new user to the database.
Following are my aspx and code behind. So far I have two major problems.
(1) the OnClick even doesn't get fired all the time.
(2) the modalpopup doesn't show up when clicking the username linkbutton.
Really appreciated if someone could help me out here.
Here is my aspx page:
<%@ Page Title="" Language="C#" MasterPageFile="~/Default.Master" AutoEventWireup="true" CodeBehind="EditUsers.aspx.cs" Inherits="SPR2_v1.EditUsers" %>
<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="asp" %>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div id="pagetitle">
<h1>SPR Users</h1>
</div>
<div >
<asp:Label ID="lblErrorMsg" runat="server" ForeColor="Red"></asp:Label>
<table align="center" >
<tr>
<td align="right">
<asp:Button ID="btnAddUser" runat="server" Text="Add User" Width="85px"
onclick="btnAddUser_Click" />
</td>
</tr>
<tr>
<td align="left">
<asp:GridView ID="gvUsers" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False"
DataSourceID="SqlDSUsers" EnableViewState="False">
<Columns>
<asp:TemplateField HeaderText="UserName">
<ItemTemplate>
<asp:LinkButton ID="lnkUserName" runat="server"
Text='<%# Eval("UserName")%>' OnClick="lnkUserName_Click">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="UserName" HeaderText="UserName"
SortExpression="UserName" Visible="false" />
<asp:BoundField DataField="Extension" HeaderText="Extension"
SortExpression="Extension" />
<asp:BoundField DataField="Email" HeaderText="E-mail"
SortExpression="Email" />
<asp:BoundField DataField="Company" HeaderText="Company"
SortExpression="Company" />
<asp:BoundField DataField="Department" HeaderText="Department"
SortExpression="Department" />
<asp:BoundField DataField="Access Level" HeaderText="Access Level"
SortExpression="Access Level" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDSUsers" runat="server"
ConnectionString="<%$ ConnectionStrings:SPRConnectionString %>"
SelectCommand="..."></asp:SqlDataSource>
</td>
</tr>
</table>
<asp:ModalPopupExtender id="mpeAddUser" runat="server"
TargetControlID="btnAddUser"
PopupControlID="panelEditUser"
CancelControlID="btnCancel"
PopupDragHandleControlID="PopupHeader"
Drag="true"
DropShadow="true"
BackgroundCssClass="ModalPopupBG" >
</asp:ModalPopupExtender>
<asp:Button ID="btnEditUser" runat="server" style="display:none" />
<asp:ModalPopupExtender id="mpeEditUser" runat="server"
TargetControlID="btnEditUser"
PopupControlID="panelEditUser"
CancelControlID="btnCancel"
PopupDragHandleControlID="PopupHeader"
Drag="true"
DropShadow="true"
BackgroundCssClass="ModalPopupBG" >
</asp:ModalPopupExtender>
<asp:panel id="panelEditUser" style="display: none" runat="server">
<div id="ModalPopup">
<div id="PopupHeader">Add a New User</div>
<table>
<tr>
<td>First Name</td>
<td>
<asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>Last Name</td>
<td>
<asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>Extension</td>
<td>
<asp:TextBox ID="txtExtension" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>E-mail</td>
<td>
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>Company</td>
<td>
<asp:DropDownList ID="ddlCompany" runat="server" DataSourceID="SqlDSCompany"
DataTextField="ProductVendorName" DataValueField="ProductVendorID"
AppendDataBoundItems="True">
<asp:ListItem Value="" Text=""></asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ...>
</asp:SqlDataSource>
</td>
</tr>
<tr>
<td>Department</td>
<td>
<asp:DropDownList ID="ddlDepartment" runat="server"
DataSourceID="SqlDSDepartment" DataTextField="DepartmentName"
DataValueField="DepartmentID" AppendDataBoundItems="True">
<asp:ListItem Value="" Text=""></asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ...>
</asp:SqlDataSource>
</td>
</tr>
<tr>
<td>Access Level</td>
<td>
<asp:DropDownList ID="ddlAccessLevel" runat="server"
DataSourceID="SqlDSAccessLevel" DataTextField="LevelID"
DataValueField="LevelID" AppendDataBoundItems="True">
<asp:ListItem Value="" Text=""></asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ...>
</asp:SqlDataSource>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="btnEdit" runat="server" Text="Submit"
onclick="btnEdit_Click" />
<asp:Button ID="btnReset" runat="server" Text="Reset"
onclientclick="return resetUser();" />
<input id="btnCancel" type="button" value="Cancel" />
</td>
</tr>
</table>
</div></asp:panel>
</div>
</asp:Content>
Here is the code behine in C#, somehow the click event didn't get fired all the time.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Text;
namespace SPR2_v1
{
public partial class EditUsers : System.Web.UI.Page
{
...
protected void lnkUserName_Click(object sender, System.EventArgs e)
{
LinkButton lbUserName = sender as LinkButton;
GridViewRow gvr = (GridViewRow)lbUserName.NamingContainer;
txtFirstName.Text = "";
txtLastName.Text = "";
txtExtension.Text = gvr.Cells[2].Text;
txtEmail.Text = gvr.Cells[3].Text;
ddlCompany.SelectedItem.Text = gvr.Cells[4].Text;
ddlDepartment.SelectedItem.Text = gvr.Cells[5].Text;
ddlAccessLevel.SelectedItem.Text = gvr.Cells[6].Text;
btnEdit.Text = "Update User";
mpeEditUser.Show();
}
protected void btnAddUser_Click(object sender, EventArgs e)
{
btnEdit.Text = "Add User";
}
}
}
A: Too much code to write, but you need to associate each LinkButton to a ModalPopupExtender during GridView.RowDataBound.
Your real problem though is getting access to the row data to edit. If that is the real goal, see the example below and then you can integrate it with the ModalPopupExtender.
GridView Examples for ASP.NET 2.0: Editing the Underlying Data in a GridView
I recommend you go with a ListView, the templates(EditItemTemplate...etc) are much easier to work with.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578207",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: php if statement - time/date/strtotime related I am using the following code to calculate the days remaining to make edits. They have 30 days to make edits, and days count down, this code works perfectly.
<?php
// Calculate days remains to edit or change details
$today = time();
$cdate = strtotime($row_details['payment_date']);//strtotime("19:19:09 Sep 27, 2011");
$dateDiff = $today - $cdate;
$fullDays = floor($dateDiff/(60*60*24));
$dayscalculate = 30 - $fullDays; // Set number of days
echo $dayscalculate.(($dayscalculate == 1) ? " day" : " days");
//
?>
QUESTION: if days = say 3 will say 3 days.. but if days = 0 (is the last of the 30 days).. Then want to say this is your last day or something.. So need an if based on $dayscalculate..
Ideas?
Thank you
A: How about...
if ($dayscalculate == 0) {
echo 'This is your last day';
} else {
printf('%d day%s',
$dayscalculate,
$dayscalculate > 1 ? 's' : ''
);
}
You may also want to introduce an "out of time" check, ie $dayscalculate < 0 but then again, you may already be handling this scenario.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578208",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: jqgrid/mvc 3 - How to call grid in controller? I'm new to jqgrid. It's may be silly question, but please help me. I want to export data to excel file, and I watch demo on http://www.trirand.net/demoaspnetmvc.aspx , it's already support it.
However I defined grid in Views, not in Model like the demo:
$(document).ready(function () {
jQuery("#list").jqGrid({{
url: '/documents/List',{
datatype: 'json',{
mtype: 'GET',{
......
I wonder if there's a way to call this grid from controller, or how to name and use it like variable?
Thank in advance
A: You cannot call grid from your controller. Jqgrid extension just renders data on a client in a way you specify it, you have no access to it from server-side code.
If you take closer look on example which you provide, authors pass grid options in request and bind new grid object on server, then export data from this object. You need to do the same.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578212",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Java Generics: Question regarding type capture and generated inference using generic methods This is a follow-up to my previous question but since the previous thread was a long one, i decided to start another thread pertaining to the almost same topic.
public class GenericMethodInference {
static <T> void test1(T t1, T t2) {}
static <T> void test3(T t1, List <T> t2) {}
static <T> void test4(List <T> t1, List <T> t2) {}
public static void main(String [] args) {
List <Object> c = new LinkedList<Object>();
List <? extends Object> d = new ArrayList<Integer>();
List e = new ArrayList<Integer>();
test1("Hello", new Integer(1)); // ok clause (1)
GenericMethodInference.<Object>test1("Hello", new Integer(1)); // ok clause (2)
test3("Hello", c); // ok clause (3)
test4(d,d) // clause (4) Error due to different type capture generated
}
Note: If you move your cursor over each clause, you will see the inference being generated and displayed on Eclipse:
a. Clause (1) will produce <? extends Object> test1 <? extends Object, ? extends Object>
b. Clause (2) will produce exactly what's defined in the actual type parameter
c. Clause (3) will produce <Object> test3 <Object, List <Object>>
Questions:
*
*Why clause (1) didn't produce <Object>? Since <Object> works as shown in clause (2), why <? extends Object> being produce instead?
*why clause (3) produce <Object> instead of <? extends Object>?
*Since clause (4) uses the same variable, why 2 different type capture generated eventhough the parameter used is of the same variable d?
A:
Why clause (1) didn't produce <Object>? Since <Object> works as shown in clause (2), why <? extends Object> being produce instead?
This is the best question out of the three. My thinking is that the compiler/Eclipse doesn't want to assume that Object is necessarily the type T that is inferred between String and Integer, so it plays it safe. As @bringer128 pointed out, String and Integer also both implement Serializable and Comparable - so these types are also candidates for the inferred type of the method.
It's worth noting that the following code gives the compiler error "illegal start of type":
GenericMethodInference.<? extends Object>test1("Hello", new Integer(1));
This is because it's invalid to specify a wildcard as a method's type parameter. So the fact you're seeing that in the tooltip has to do with a subtlety of the compiler's/Eclipse's facility to report this information - it has determined only that T is within its bounds, not what it is.
Remember that Java's implementation of generics is solely for the convenience/sanity of programmers. Once compiled into bytecode, type erasure will have gotten rid of any notion of T. So in its checking, the compiler only needs to ensure that a valid T can be inferred, but not necessarily what it is.
why clause (3) produce <Object> instead of <? extends Object>?
Because in this case, the fact that a List<Object> is passed in where a List<T> is expected tells the compiler that T is exactly Object.
Since clause (4) uses the same variable, why 2 different type capture generated eventhough the parameter used is of the same variable d?
It isn't safe for the compiler to assume that d actually refers to the same object, even between evaluating parameters. For example:
test4(d,(d = new ArrayList<String>()));
In this case, a List<Integer> would be passed into the first parameter, and an List<String> into the second - both from d. Since this scenario is possible, it's easier for the compiler to play it safe.
A: The test1() case is actually quite sinister. see JLS3 15.12.2.7.
We are not supposed to know the details of type inference - in most cases intuition coincides with the algorithm. Alas that's not always the case, as in the seemingly trivial test1() example.
The constraints we have is T :> String and T :> Integer ( ":>" means super type)
This leads to T=lub(String,Integer), lub means "least upper bound".
Since String <: Comparable<String> and Integer <: Comparable<Integer>, this leads to lci({Comparable<String>, Comparable<Integer>}), which yields Comparable<? extends lub(String,Integer)>, i.e. Compable<? extends T>
In the end, we have T = Serializable & Compable<? extends T>, a self referenced definition! Spec calls it "infinite type":
It is possible that the process above yields an infinite type. This is permissible, and Java compilers must recognize such situations and represent them appropriately using cyclic data structures.
Let's find out how javac represents it: (javac 7)
static <T> T test1(T t1, T t2) {}
public static void main(String[] args)
{
Void x = test1("Hello", new Integer(1));
}
error: incompatible types
required: Void
found: INT#1
where INT#1,INT#2 are intersection types:
INT#1 extends Object,Serializable,Comparable<? extends INT#2>
INT#2 extends Object,Serializable,Comparable<?>
That doesn't seems right; it's not really recursive; it appears that javac detects recursion in lub() and gives up, resulting a less specific type Comparable<?>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578215",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: How to form strings in php I have an table, Now i want when after filling this table
This is the table in ssl.php page
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td class="TitleBar">Generate CSR</td>
</tr>
</table>
<table cellspacing="0" border="0" width="100%">
<tr>
<td>Country Name(only two letters) :</td>
<td >
<input name="countryname" type="text" id="countryname" MaxLength="2"/>
</td>
</tr>
<tr>
<td>State or Province Name :</td>
<td>
<input name="province" type="text" id="province"/>
</td>
</tr>
<tr>
<td>Locality Name :</td>
<td >
<input name="localityname" type="text" id="localityname"/>
</td>
<tr>
<td>Organization Name :</td>
<td>
<input name="organizationname" type="text" class="style16" id="organizationname"/>
</td>
</tr>
<tr>
<td>Organizational Unit Name :</td>
<td >
<input name="organizationunit" type="text" id="organizationunit"/>
</td>
</tr>
<tr>
<td>Common Name :</td>
<td>
<input name="commonname" type="text" id="commonname"/>
</td>
</tr>
<tr>
<td>Email Address :</td>
<td >
<input name="email" type="text" id="email"/>
</td>
</tr>
<tr>
<td style="padding-top:15px padding-bottom:10px" align="right">
<input name="gencsr" type="submit" id="button" value="Generate CSR" class="FormButton" />
</td>
</tr></table>
HERE is my inputs :-
Country Name(only two letters) :IN
State or Province Name :MAHARASHTRA
Locality Name :MUMBAI
Organization Name :Cofin Inc
Organizational Unit Name :Sales
Common Name :www.coufdffin.itdpl
I want my output like this :-
"/C=IN/ST=MAHARASHTRA/L=MUMBAI/O=Cofin Inc/OU=Sales/CN=www.coufdffin.itdpl"
How can i make the string in this format after post the table
UPdate
now i am using this
$dn = array("C" => "".trim($_POST['countryname']),
"ST" => "".trim($_POST['province']),
"L" => "".trim($_POST['localityname']),
"O" => "".trim($_POST['organizationname']),
"OU" => "".trim($_POST['organizationunit']),
"CN" => "".trim($_POST['commonname']),
"emailAddress" => "".trim($_POST['email']));
$comma_separated = implode(",", $dn);
echo $comma_separated;
What can i do plz help me?
A: Instead of :
$dn = array("C" => "".trim($_POST['countryname']),
"ST" => "".trim($_POST['province']),
"L" => "".trim($_POST['localityname']),
"O" => "".trim($_POST['organizationname']),
"OU" => "".trim($_POST['organizationunit']),
"CN" => "".trim($_POST['commonname']),
"emailAddress" => "".trim($_POST['email']));
$comma_separated = implode(",", $dn);
echo $comma_separated;
do:
$dn = array("C" => "".trim($_POST['countryname']),
"ST" => "".trim($_POST['province']),
"L" => "".trim($_POST['localityname']),
"O" => "".trim($_POST['organizationname']),
"OU" => "".trim($_POST['organizationunit']),
"CN" => "".trim($_POST['commonname']),
"emailAddress" => "".trim($_POST['email']));
$str = '';
foreach($dn as $key => $val){
$str .= "/$key=$val";
}
A: Make (C,ST,L,O,OU,CN) in one array, ang get the post array after the page posted,
construct the new string using implode() method.
A: If these fields in your html form named correctly. you can simple "add" all these string together. Let's say the name of Country Name field in form is countryname. The PHP can then read the input IN with $_POST["countryname"]. So you can generate the first session of your output like this
$output = "/C=" . $_POST["countryname"]
Use . to connect different strings in PHP.
Hope this help. :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578218",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Problem with using FusionCharts for Android I wanted to use FusionCharts with android 2.2 (may be on emulator).
I tried using Javascript and the HTML but did not get the expected result.
Any help??
My code is as follows :
WebView web;
/** Called when the activity is first created. */
@Override
public void on Create(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
web=(WebView)findViewById(R.id.webView1);
web.loadUrl("file:///android_asset/Fusioncharts/myChart.html");
}
}
Also my html,xml files :
<html>
<head>
<title>My First chart using FusionCharts
</title>
<script type="text/javascript" src="JavaScripts/FusionCharts.js">
</script>
</head>
<body>
<div id="chartContainer">FusionCharts will load here!
</div>
<script type="text/javascript">
<!--
var myChart = new FusionCharts("Pie2D.swf? dataURL=Data.xml","myChartId", "400", "300", "0", "1" );
myChart.setXMLUrl("Data.xml");
myChart.render("chartContainer");
// -->
</script>
</body>
</html>
and Data.xml :
The above code just displays me : FusionCharts will load here!
Thanks
Sneha
A: EDIT> NEW CONTENT:
You might need to enable JavaScript and plugins for the WebView:
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setPluginsEnabled(true);
http://developer.android.com/reference/android/webkit/WebView.html
What does "install Flash plugin" in WebView mean?
How to Enable Flash Plugin in Webview?
Also you might need to set proper path to the SWF and JS files. Please debug or attach code here.
OLD CONTENT:
There seems to be a JavaScript error or FusionCharts not getting loaded to do the rendering as stated by Duniyadnd.
Please check the Android debug (using adb logcat or other processes) if it traces any error.
Moreover, I did an implementation using PhoneGap which you can check-out from:
PhoneGap API to query call-logs
This is a small PhoneGap Android application which has FusionCharts to show call logs from the device. The post though showcases creation of plugin to get the calllog, you might derive the other elements which you require. Hope this might help.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578220",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why datepicker does not show up in Rails 3 form I can't figure out why jQuery datepicker doesn't show up, even though I got jQuery running on my app. Here is what I did:
I got a Rails form that includes
<div id="born_in">
<%= f.text_field :born_in %><br />
</div>
I included jQuery, jQuery-UI, CSS in head of my application.html.erb
<%= stylesheet_link_tag "http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" %>
<%= javascript_include_tag "http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js",
"http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js" %>
I also have application.js, which shows that my selector is not nil:
alert($("#born_in").length)
returns 1
I have tried:
$("#born_in").datepicker("show")
but it doesn't show anything.
So why I don't see datepicker()? Is there a bug with datepicker for this version of jquery-UI? How should I test if this function is included in my app?
Thank you.
A: was it initialized before hand? as in, did you call
$("#born_in").datepicker();
some where before that code? if not, you don't need the "show", just run the method with no parameters.
A: Rails decides it likes to prepend a form input with the controller name in the id.
For example, my controller name was "Testjqueryui" and in the _form partial, the following (much like yours) was generated:
<%= f.text_field :date %>
The generated HTML (after the embedded ruby is run) has the id of: "testjqueryui_date".
So, my suggestion would be to check the id of the field that's generated, as it likely has the controller's name prepended.
I put this in the application.js file:
$(function() {
$( "#testjqueryui_date" ).datepicker();
});
Hope this helps!
A: You just have to use a jQuery selector to find all the fields that you want displayed as datepickers. One way to do it is to give a particular css class to the datepicker fields, like this:
<div id="born_in">
<%= f.text_field :born_in, :class => "date" %>
</div>
And then, in your application.js file (or where you want), just write:
$(function() {
$('input.date').datepicker();
});
You can also use the id of the particular element instead of a css class. You know the requirements.
Hope this is useful.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578222",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is hitting time of Brownian motion independent Suppose that $B_t$ is a standard Brownian Motion. And $T_a$ $T_b$ are the hitting time whereas $a<0$, $b>0$. Then are these two random variables independent?
A: They are not independent: consider Tb conditional on Ta=T. This equivalent to the hitting time for a+b, which Is clearly different from Tb. You need to give more detail about the question if you want a more rigorous answer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578225",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Howto Persist a Map with JPA? I'm working on migrating some code that has two entities (Progress and PerformanceRating) that are related by a many-to-many relationship. Each PerformanceRating has multiple Progress and each Progress type can be assigned to several PerformanceRatings. Additionally, each PerformanceRating->Progress has an additional "amount" value that relates to the progress.
Current the PerformanceRating object contains a Map representing the "amount" of progress for each Progress type assigned to the PerformanceRating object.
It is coded as follows:
@Entity
class PerformanceRating{
....
....
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "performance_rating_progress_reward", joinColumns = { @JoinColumn(name = "id", nullable = false, updatable = false) }, inverseJoinColumns = { @JoinColumn(name = "amount", nullable = false, updatable = false) })
public Map<Progress, Integer> getRewardAmountByProgressMap() {
return this.rewardAmountByProgressMap;
}
However, when I start JBoss (with hibernate 3.6/JTA/JPA), I get the following error:
Use of @OneToMany or @ManyToMany targeting an unmapped class: fwl.domain.model.PerformanceRating.rewardAmountByProgressMap[java.lang.Integer]
I found a similar thread (Persist a Map<Integer,Float> with JPA), but that one seems to deal with non-entity types. In a case such as mine, where I am looking for an Entity/value type mapping, what is the correct syntax?
Is there a way to do this in Hibernate/JPA2?
Thanks,
Eric
A: The error you get:
Use of @OneToMany or @ManyToMany targeting an unmapped class: fwl.domain.model.PerformanceRating.rewardAmountByProgressMap[java.lang.Integer]
relates to the fact that with annotations like @OneToMany and @ManyToMany you say that the declaring class (PerformanceRating) is in a many-to-many relation with your map's value, Integer which is silly.
The value of your map should be an entity, its key should be the id with which you can identify one of those entities that your map contains (actually the key have to be only unique, I think, it needn't be an actual id).
I really don't know how your table looks like, but if your PerformanceRating (lets call it just Rating for ease's sake) looks like this:
rating
============
id int(11) PK
and your Progress table like this:
progress
============
id int(11) PK
amount int(11)
with a table connecting these like this:
progress_has_rating
============
progress_id int(11) PK
rating_id int(11) PK
then you can map these in the following way:
@Entity @Table class Rating {
@Id long id;
@ManyToMany(targetEntity = Progress.class,
cascade = CascadeType.ALL,
fetch = FetchType.EAGER)
@JoinTable(name = "progress_has_rating",
joinColumns = {@JoinColumn(name = "rating_id",
referencedColumnName = "id")},
inverseJoinColumns = {@JoinColumn(name = "progress_id",
referencedColumnName = "id")})
Set<Progress> progresses;
}
@Entity class Progress {
@Id long id;
@Basic long amount;
}
(It's quite possible that I switched up the column names in the @JoinColumn annotations that would actually work; I always switch 'em up.)
(Edit: yes, I've switched them—fixed.)
If your amount property is in your join table, then you'll need to create an entity class for that also. I think it isn't possible to get around that.
If you really want to use maps, then Hibernate can manage that. See the Collection mapping section (section 7.2.2.2 particularly) on how to map maps. Still, values in your map would need to be entities of some kind.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578231",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to add to_sentence to a :collection I have the following code that generates a list of superlatives:
<%= render :partial => 'superlative', :collection => @profile.superlatives %>
The :partial code referenced above is as follows:
<li class="superlative"><span title="<%= superlative.name %>">
<%= superlative.body %>
</span></li>
How can I add to_sentence to the @profile.superlatives collection? I tried:
<%= render :partial => 'superlative', :collection => @profile.superlatives.to_sentence %>
Doing so however makes the @profile.superlatives disappear from the view.
I looked at the docs but couldn't find an answer.
A: Ohhh, now I understand. Sorry for the confusion. Here's what I would do:
In your controller:
@superlative_bodies = @profile.superlatives.map &:body
# Equivalent to: @superlative_bodies = @profile.superlatives.map {|sup| sup.body }
In your view:
= @superlative_bodies.to_sentence
Some people would do this all in the view instead, which is up to you:
= @profile.superlatives.map(&:body).to_sentence
To explain, .map is a super-useful Ruby method that takes an array or other Enumerable and a block and returns a new array where each element is the corresponding element from the original array after the block has been applied to it. For example:
[ 'foo', 'bar', 'baz' ].map {|word| word.upcase } # => [ 'FOO', 'BAR', 'BAZ' ]
# or
[ 'foo', 'bar', 'baz' ].map &:upcase # => [ 'FOO', 'BAR', 'BAZ' ]
(The latter is just a shortened version of the former for when you only want to call the same single method on every element.)
A: Something like this, perhaps?
module ProfilesHelper
# ...
def superlatives_items (profile)
@@acb ||= ActionController::Base.new # required to access render_to_string
profile.superlatives.collect |superlative|
acb.render_to_string :partial => 'path/to/partial/superlative',
:layout => false,
:locals => { :superlative => superlative }
end
end
# ...
end
# In view:
# <%= raw(superlatives_items(@profile).to_sentence) %>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578233",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to send hashmap value to another activity using an intent How to send HashMap value from one Intent to second Intent?
Also, how to retrieve that HashMap value in the second Activity?
A: I hope this must work too.
in the sending activity
Intent intent = new Intent(Banks.this, Cards.class);
intent.putExtra("selectedBanksAndAllCards", (Serializable) selectedBanksAndAllCards);
startActivityForResult(intent, 50000);
in the receiving activity
Intent intent = getIntent();
HashMap<String, ArrayList<String>> hashMap = (HashMap<String, ArrayList<String>>) intent.getSerializableExtra("selectedBanksAndAllCards");
when I am sending a HashMap like following,
Map<String, ArrayList<String>> selectedBanksAndAllCards = new HashMap<>();
Hope it would help for someone.
A: Java's HashMap class extends the Serializable interface, which makes it easy to add it to an intent, using the Intent.putExtra(String, Serializable) method.
In the activity/service/broadcast receiver that receives the intent, you then call
Intent.getSerializableExtra(String) with the name that you used with putExtra.
For example, when sending the intent:
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("key", "value");
Intent intent = new Intent(this, MyOtherActivity.class);
intent.putExtra("map", hashMap);
startActivity(intent);
And then in the receiving Activity:
protected void onCreate(Bundle bundle) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
HashMap<String, String> hashMap = (HashMap<String, String>)intent.getSerializableExtra("map");
Log.v("HashMapTest", hashMap.get("key"));
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578236",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "88"
}
|
Q: assert property of mocked object has been assigned correctly using Rhino.Mocks In a (web) application I've implemented the MVP pattern for seperation of core concerns. My presenters directly query the database using LINQ-to-NHibernate, or sometimes they use query objects when the query becomes complex (but I digress).
An simple example of one of my presenters is as follows (note: VB.NET is not my preference, but a requirement for this):
Public Class CampusListPresenter
Inherits BasePresenter(Of ICampusListView)
Public Sub New(ByVal view As ICampusListView)
MyBase.New(view)
End Sub
Public Sub NeedDataSource()
Using uow As ISession = _sessionManager.OpenSession()
_view.DataSource = uow.Queryable(Of Campus)() _
.Cacheable() _
.AsEnumerable()
End Using
End Sub
End Class
The (simplified) base presenter class is as follows:
Public MustInherit Class BasePresenter(Of TView)
Protected _view As TView
Protected _sessionManager As ISessionManager
Public Sub New(ByVal view As TView)
Guard.Against(view Is Nothing, "view cannot be null.")
_view = view
End Sub
Public WriteOnly Property SessionManager As ISessionManager
Set(ByVal value As ISessionManager)
_sessionManager = value
End Set
End Property
End Class
I'm trying to unit test my presenters (specifically the LINQ queries) using NUnit and Rhino Mocks. In my unit test case for the above CampusListPresenter, I pass a mocked view to the presenter. Essentially I want perform an assertion on this mocked view object to confirm the Datasouce property gets set appropriately. However, this is always null.
A (simplified) example of my unit test is as follows (understand I'm relatively new to proper unit testing):
<TestFixture()> _
Public Class CampusListPresenterTests
Dim _realSessionManager As ISessionManager
<TestFixtureSetUp()> _
Public Sub TestFixtureSetUp()
_realSessionManager = DefaultSessionManager.Instance
End Sub
Dim _view As ICampusListView
Dim _fakeSessionManager As ISessionManager
<SetUp()> _
Public Sub Setup()
_view = MockRepository.GenerateMock(Of ICampusListView)()
_fakeSessionManager = MockRepository.GenerateMock(Of ISessionManager)()
End Sub
<Test()> _
Public Sub NeedDataSource_UsingRealSession_DataSourceIsAssigned()
'Arrange
Dim realSession As ISession = _realSessionManager.OpenSession()
_fakeSessionManager.Expect(Function(sm) sm.OpenSession()).Return(realSession)
'Act
Dim presenter As New CampusListPresenter(_view)
presenter.SessionManager = _fakeSessionManager
presenter.NeedDataSource()
'Assert
_fakeSessionManager.VerifyAllExpectations()
Assert.AreEqual(_view.DataSource, realSession.Queryable(Of Campus)())
End Sub
End Class
I actually setup my unit tests to use an in memory SQLite database and populate/destroy data in the setup/teardown methods, but this has all been omitted from the above example for simplicty.
Basically, in this unit test I'm returning a real NHibernate ISession from a mocked session manager (a class used for session management - think Castle.Facilities.NHibernateIntegration) so that the LINQ-to-NHibernate can/will actually return valid enumerable results. Anyway in the presenter implementation I assign the views datasource (inside NeedDataSource), but when I do an assertion on this property the assigned value is always null.
Can anyone help me out?
Kind regards,
Ryan.
A: The mocked ICampusListView is unable to keep hold of the assigned datasource object. Here are two possible ways to fix this. First, you could use a stub instead of a mock (for more background info on the difference between mocks and stubs, see this post):
_view = MockRepository.GenerateStub(Of ICampusListView)()
If you do want to use mocks instead of stubs, use Expect and VerifyAllExpectations on the ICampusListView object in your test:
'Arrange
Dim realSession As ISession = _realSessionManager.OpenSession()
_fakeSessionManager.Expect(Function(sm) sm.OpenSession()).Return(realSession)
_view.Expect(Function(v) v.SetDataSource(Arg(Of DataSource).Is.Anything))
'Act
Dim presenter As New CampusListPresenter(_view)
presenter.SessionManager = _fakeSessionManager
presenter.NeedDataSource()
'Assert
_fakeSessionManager.VerifyAllExpectations()
_view.VerifyAllExpectations()
Assert.AreEqual(_view.DataSource, realSession.Queryable(Of Campus)())
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578237",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Playing audio file with Python I've seen most of the questions on this topic but almost all of them are outdated. (This is not a dupe)
My requirement is a preferably light weight library for simply playing audio files such as mp3,etc from Python (2.7)
These are the libraries that I've so far looked into and I'm listing what are the things that are stopping me from using each of them:
*
*PyMedia: it was last updated in Feb, 2006
*Mp3Play: supports only XP and was last updated in 2008.
I've also tried Pyglet but even this doesn't look good.
Also heard that wx has support for mp3 and I'm trying it. Any comments about the same?
Which reliable lightweight library do others use these days?
PS: please post one library only per answer
A: I'm not sure what your issue is with pyglet. Playing an mp3 using that couldn't be simpler:
import pyglet
sound = pyglet.media.load('mysound.mp3', streaming=False)
sound.play()
pyglet.app.run()
pyglet is well-maintained, cross-platform, and very small for a multimedia library.
A: I know this is late but anyway...
Try just_playback. It's a wrapper around miniaudio that can read multiple file formats including mp3 and provides playback control functionality like pausing, resuming, seeking and setting the playback volume.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578238",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: ICS Email Attachment Not Working for Exchange Users I am sending a meeting invitation as an email with an ICS attachment from a Java web application. Everything works fine when I send it to Outlook users who are not using an Exchange server. They get the appropriate Accept/Reject buttons and can add the meeting to their calendar.
Things are not working for users who are on an Exchange server, however. They get a meeting invite, but it lists themselves as the meeting organizer and they are unable to change any of the meeting details. They cannot accept or reject and cannot add it to their calendar.
It is almost like Exchange is altering or does not like the format of the ICS we are sending, but normal Outlook handles it just fine.
Here is the ICS we are sending. Does anyone know what we can change to make this work for Exchange users, in addition to Gmail and non-Exchange Outlook Users.
BEGIN:VCALENDAR
PRODID:-//fincrm//iCal4j 1.0//EN
VERSION:2.0
METHOD:REQUEST
BEGIN:VEVENT
UID:128
DTSTAMP:20110927T191127Z
DTSTART;VALUE=DATE-TIME:20110928T082000
DTEND;VALUE=DATE-TIME:20110928T085000
ACTION:DISPLAY
DESCRIPTION:Time is set to 8:20 AM
SEQUENCE:0
ORGANIZER:MAILTO:user1@ltest.com
LOCATION:Financial CRM Application
ATTENDEE:MAILTO:user2@test2.com
SUMMARY:CRM Task #128
END:VEVENT
END:VCALENDAR
I appreciate your suggestions.
A: I have figured out that sending the ICS as a Multipart MIME Message seems to work with both Gmail and Exchange. Here is some of the relevant Java code ("calendar" is the ICS string)
// Create an alternative Multipart
Multipart mp = new MimeMultipart("alternative")
BodyPart textPart = new MimeBodyPart();
textPart.setText(eventDescription);
BodyPart calPart = new MimeBodyPart();
calPart.addHeader("content-class", "urn:content-classes:calendarmessage")
calPart.setContent(calendar.toString(), "text/calendar;method=REQUEST")
mp.addBodyPart(textPart);
mp.addBodyPart(calPart);
A: I know that the is from a while ago, but you can solve this with the registry fix found here:
http://support.microsoft.com/kb/944094
I have tested this with Outlook 2010 running on Exchange 2010 and this allowed 3rd party events to be entered into the calendar when you are the organizer.
A: I have found that if the organizer is set to you, then Outlook 2011 on Mac will not offer to add the meeting to your Calendar. Removing the Organizer from the meeting seems to work well enough.
I have also found that if the ICS attachment is not the last item attached to a multipart message, it will be stripped.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578239",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: "PropertyAccessException: Invalid Cast" when trying to retrieve an enum property stored as an AnsiString I need to store my enums in the database as varchar instead of nvarchar, so I am using the "AnsiString" mapping as follows:
public class Document
{
public virtual int Id { get; set; }
public virtual string Content { get; set; }
public virtual DocType Type { get; set; }
}
public enum DocType
{
Word,
Excel
}
public class DocumentMap : ClassMap<Document>
{
public DocumentMap()
{
Id(d => d.Id);
Map(d => d.Content);
Map(d => d.Type).CustomType("AnsiString");
}
}
Saving to the database works fine, but when it comes to retrieval I receive an error:
NHibernate.PropertyAccessException: Invalid Cast (check your mapping for property type mismatches); setter of Core.Document
It works fine when I remove the CustomType("AnsiString") from the mapping.
Any suggestions?
Here's the hbm:
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class xmlns="urn:nhibernate-mapping-2.2" name="Core.Document, Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" table="`Document`">
<id name="Id" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<column name="Id" />
<generator class="identity" />
</id>
<property name="Content" type="System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<column name="Content" />
</property>
<property name="Type" type="AnsiString">
<column name="Type" />
</property>
</class>
</hibernate-mapping>
A: Essentially a duplicate of this question: How do you map an enum as string in fluent nhibernate?
The difference is that you're trying to use a Non-Unicode string (NVARCHAR in MSSQL) as the underlying data type.
So, what does the underlying mapping generated by FNH look like?
A: Using this did the trick (thanks @Firo):
Map(d => d.Type).CustomSqlType("varchar(50)");
Looking at the hbm (thanks @rbellamy for the suggestion) shows that using the custom sql type doesn't override the enum mapper from the mappings, so the resulting hbm looks like this:
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class xmlns="urn:nhibernate-mapping-2.2" name="Core.Document, Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" table="`Document`">
<id name="Id" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<column name="Id" />
<generator class="identity" />
</id>
<property name="Content" type="System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<column name="Content" />
</property>
<property name="Type" type="FluentNHibernate.Mapping.GenericEnumMapper`1[[Core.DocType, Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], FluentNHibernate, Version=1.3.0.717, Culture=neutral, PublicKeyToken=8aa435e3cb308880">
<column name="Type" sql-type="varchar(50)" />
</property>
</class>
</hibernate-mapping>
and all works as it should.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578241",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Variables upon submitting Paypal form <form>
<!--- paypal form --->
</form>
How to send data thru paypal when submitting?
For example:
*
*Upon submitting the form with an #ID value of "12345"
and after paying successfully.
*It will return back to my site ThankYou.php
Question: how will I get the value 12345?
or can I use
//ThankYou.php
<?php
echo $_REQUEST["#ID"];
?>
Thanks in advance!!
A: PayPal allows you to post custom values. You should be able to put a hidden form field value on your form that will make the trip back on return. Their documentation has all that information.
This may work:
<input type="hidden" name="custom" value="Id value" />
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578242",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Can you nest collection calls? MongoDB Can you nest collection calls in MongoDB?
db.collection 'one', (err, one) ->
one.#do stuff
db.collection 'two', (err, two) ->
two.#do stuff
A: Yes.
This is (as far as I am aware) the simplest way of doing things in MongoDB and Node.js.
In your example one will contain the results of the first query, and two the results of the second.
If you are doing a lot of nested queries, where the nested query does not depend on the results of the outer query, you could consider using the Async module (or an alternative) to parallelise the query.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578246",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how do you get the specific style altered with a CSS class? Quick one, not sure if its possible.
How can I get the specific style altered with a CSS class using jQuery/JS.
Example:
html looks like:
<tab>
<a class="anchor">a</a>
</tab>
CSS looks like:
a{border:1px}
.anchor{color:green}
So if i do something like :
$('.anchor').myReturnStyle() and it returns color or an array if there more styles in .anchor
$('.anchor').MyReturnStyleValue('color') returns 'green'
BUT
$('.anchor').returnStyleValue('border') returns false as this is not changed by .anchor Class
A: You can use jQuery's css(..) method to achieve this. Please note that:
Shorthand CSS properties (e.g. margin, background, border) are not supported.
Here is an example:
<div>
<a class="anchor">a</a>
</div>
<style type="text/css">
a { background-color: #000; }
.anchor{ color: green; }
</style>
<script type="text/javascript">
$(document).ready(function () {
alert($($('.anchor').get(0).nodeName).css('background-color'));
});
</script>
See the jsFiddle demo
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578254",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: C2DM registrationId handling -Best Practice? Here's the situation I'm struggling with. When a user installs my app and runs it for the first time, I register with C2DM and get the registrationID. I then send it to my server and notifications are sent to the app.
If the user uninstalls the app, then installs it again, a new registration is made to C2DM and I receive a new registrationID.
The problem is, the server now has two registrationID's for the same app and I get multiple/redundant notifications to onMessage.
What is the best practice way of avoiding this situation?
A: When we send the registrationId to our server we generate an identifier that can be constantly reproduced client side to identify the registrationId to the specific user. This also allows us to unregister the user if we wanted the option, as a plus it eliminates your issue.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578260",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to add default Widget in customised Android Home Screen? I use Launcher2 home screen as the basis for customised the home screen.
I wanted to customized Android Home Screen with default Widget.
But when I use this example, I get this error:
09-28 12:03:13.052: ERROR/Launcher.LauncherProvider(9187): Problem allocating appWidgetId
09-28 12:03:13.052: ERROR/Launcher.LauncherProvider(9187): java.lang.SecurityException: bindGagetId appWidgetId=68 provider=ComponentInfo{com.android.protips/com.android.protips.ProtipWidget}: User 10081 does not have android.permission.BIND_APPWIDGET.
09-28 12:03:13.052: ERROR/Launcher.LauncherProvider(9187): at android.os.Parcel.readException(Parcel.java:1322)
09-28 12:03:13.052: ERROR/Launcher.LauncherProvider(9187): at android.os.Parcel.readException(Parcel.java:1276)
09-28 12:03:13.052: ERROR/Launcher.LauncherProvider(9187): at com.android.internal.appwidget.IAppWidgetService$Stub$Proxy.bindAppWidgetId(IAppWidgetService.java:470)
09-28 12:03:13.052: ERROR/Launcher.LauncherProvider(9187): at android.appwidget.AppWidgetManager.bindAppWidgetId(AppWidgetManager.java:337)
09-28 12:03:13.052: ERROR/Launcher.LauncherProvider(9187): at com.android.launcher2.LauncherProvider$DatabaseHelper.addAppWidget(LauncherProvider.java:812)
09-28 12:03:13.052: ERROR/Launcher.LauncherProvider(9187): at com.android.launcher2.LauncherProvider$DatabaseHelper.addAppWidget(LauncherProvider.java:790)
09-28 12:03:13.052: ERROR/Launcher.LauncherProvider(9187): at com.android.launcher2.LauncherProvider$DatabaseHelper.loadFavorites(LauncherProvider.java:670)
09-28 12:03:13.052: ERROR/Launcher.LauncherProvider(9187): at com.android.launcher2.LauncherProvider$DatabaseHelper.onCreate(LauncherProvider.java:239)
09-28 12:03:13.052: ERROR/Launcher.LauncherProvider(9187): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:126)
09-28 12:03:13.052: ERROR/Launcher.LauncherProvider(9187): at com.android.launcher2.LauncherProvider.query(LauncherProvider.java:108)
09-28 12:03:13.052: ERROR/Launcher.LauncherProvider(9187): at android.content.ContentProvider$Transport.query(ContentProvider.java:187)
09-28 12:03:13.052: ERROR/Launcher.LauncherProvider(9187): at android.content.ContentResolver.query(ContentResolver.java:271)
09-28 12:03:13.052: ERROR/Launcher.LauncherProvider(9187): at com.android.launcher2.LauncherModel$Loader$LoaderThread.loadWorkspace(LauncherModel.java:711)
09-28 12:03:13.052: ERROR/Launcher.LauncherProvider(9187): at com.android.launcher2.LauncherModel$Loader$LoaderThread.loadAndBindWorkspace(LauncherModel.java:521)
09-28 12:03:13.052: ERROR/Launcher.LauncherProvider(9187): at com.android.launcher2.LauncherModel$Loader$LoaderThread.run(LauncherModel.java:588)
I've already added android.permission.BIND_APPWIDGET in my manifest, but it's still not working and my default widget is still missing.
Does anyone have any idea what could be the problem?
A: android.permission.BIND_APPWIDGET is not available for applications outside of system storage.
Without a full stack trace I cannot pinpoint the exact location of the error but this is what I expect is causing the problem.
void addAppWidget(Intent data) {
int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
AppWidgetProviderInfo appWidget = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
if (appWidget.configure != null) {
// Launch over to configure widget, if needed
Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE);
intent.setComponent(appWidget.configure);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
startActivityForResultSafely(intent, REQUEST_CREATE_APPWIDGET);
} else {
// Otherwise just add it
onActivityResult(REQUEST_CREATE_APPWIDGET, Activity.RESULT_OK, data);
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578262",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Error: expected a declaration So far all I have in my DecisionTree.h file is
namespace DecisionTree
{
public static double Entropy(int pos, int neg);
}
and Visual Studio is already highlighting the public and saying
Error: expected a declaration.
What am I missing?
A: public is an access specifier. Access specifiers are applicable only within class/struct body and not inside namespace. In C++ (unlike Java) it must be followed by a colon : inside the class body.
For example,
class DecisionTree { // <----- 'class' (not 'namespace')
public: // <------ access specifier
static double Entropy (int pos, int neg);
private:
int i;
};
A: It will definitely give an error, for you dint declared any class,struct, or enum and directly you have written a static function inside a namespace. So, first write a class definition inside a namespace and then a function.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578265",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Simulation of Real Network with the help of User Mode Linux or Virtual Machines/Switch I am a beginner in User Mode Linux Area, and recently started working on it, by reading material available in Internet e.g; http://user-mode-linux.sourceforge.net/source.html.
My Objective :
Currently I am performing some tests, On which I am using direct hardwares : e.g;
APs[Access Points]- Configured with different types of NAT [ Full Cone, Port Restricted,Symmetric etc] and Desktop's
Rather using such all hardwares Computers ,Desktops etc, I think I may use something like User Mode Linux which all together light-weight Linux's Virtual Instances, On that I can simulate my task e.g; Virtual Switch, Virtual light-weight Instances
I tried a lot by using several Virtual Machines (VMWare) on same machine to Simulate different networks , and networks supposed to be connected Virtual Switch (didn'y find any).
All together -
[1]. Is there any one who has such past experience , Where you have simulated real network with the help of either Virtual Machines(UML or Virtual Box or VMWARE) and Virtual Switch (I don't know any).
[2]. If yes, Is it require too much effort ? means do you feel configurations are not much complex ?
A: There is such a product.
It is called GNS3 VirtualBox Edition:
http://forum.gns3.net/topic3262.html
A: I've used vde to simulate a network in the past. It's great and lets you setup things like virtual switches (http://wiki.virtualsquare.org/wiki/index.php/VDE). What I simulated were 5 virtual machines (using qemu) connceted to a virtual switch (using vde).
I'm not sure what the state of affairs is with virtualization products, but somethign like VMWare might also allow you to create a virtual network but I doubt it would be as flexible as VDE.
A: User Mode Linux is like very old, I would suggest using VDE as suggest by sashang, but simulating networks can he helpful.... However it's purely simulation, real devices in the real world can behave differently and vice verse....
A: There are a number of open-source network simulators, which help automate the process of creating virtual machines and connecting them together, that you might find useful. I created a list of these tools, along with some tutorials, and posted it at: http://www.brianlinkletter.com/open-source-network-simulators.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578268",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Where did this Ruby parameter convention come from? There's a piece of Ruby middleware used by Rails and other frameworks to the parse the parameters you've sent to the server into a nested Hash object.
If you send these parameters to the server:
person[id] = 1
person[name] = Joe Blow
person[email] = joe.blow@test.com
person[address][street_address] = 123 Somewhere St.
person[address][city] = Chicago
person[address][zip] = 12345
person[other_field][] = 1
person[other_field][] = 2
person[other_field][] = 3
They get parsed to this:
{
:person => {
:id => "1",
:name => "Joe Blow",
:email => "joe.blow@test.com",
:address => {
:street_address => "123 Somewhere St.",
:city => "Chicago",
:state => "IL",
:zip => "12345"
},
:other_field => [ 1, 2, 3 ]
}
}
I believe this is supported by PHP as well. Can anybody tell me what this convention is called, where it came from, and what other languages support it? (Perl, Python, etc.)
A: Field research
I'm trying to find out if there's a name for this convention, but I can't find it yet.
Ruby
For what it's worth, the piece of middleware that does this in Ruby is Rack::Utils. See the source on Github.
There is some more information on the subject in the Ruby on Rails Guides.
And here is an interesting ticket about the code being moved from Rails to the Rack middleware.
PHP
I've done some digging in the PHP source, and it seems that all the magic there happens in the main/php_variables.c source file. The SAPI code calls the php_std_post_handler method defined here. This eventually calls the php_register_variable_ex method, which is 185 lines of complex string-parsing in C (I must admit that C isn't my forte).
The only name I could find here was the php_std_post_handler, the PHP standard POST handler.
Python
In Python, this format isn't supported by default. See this question here on stackoverflow.com on the subject.
Perl
The CGI library in Perl doesn't support this format either. It does give easy access to single or multiple values, but not nested values as in your example. See the documentation on feching the value or values of a single named parameter and fetching the parameter list as a hash.
Java
Check out the heated debate on the subject of query parameter parsing in this question. Java doesn't parse this 'nested format' of POST parameters into a data structure by default.
Conclusion
I've looked into this, and haven't found a single name for this way of parameter parsing. Of the languages that I've looked into, only Ruby and PHP support this format natively.
A: It's not called anything, AFAIK, other than "sending parameters". If anything, it's called "parameter [type] conversion", where Rails just "converts" it into a hash.
Other frameworks go further, using the parameter names as expressions used to create typed objects initialized with type-converted parameter values.
All parameters are is a string value with a name. Any/all structure is imposed by the language/framework in use on the server side; what it gets transformed to is 100% dependent on that language/framework, and what that conversion consists of would determine what it would be (reasonable) called.
A: that would be a JSON object, which is quite standard and supported by most languages/libraries these days.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578269",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: render tiny mce from javascript using innerHTML I have a javascript code like this.
after_add_content_for_popup = "<div><div><textarea name='notes' rows='10' cols='17' class='rich' id='parent_note_content'>"+notecontent+"</textarea></div><div style='float:right;margin-left:20px;padding-left:10px;'><input id='submitbutton' class='flat_btn' style='margin-top:5px;' type='button' title='Edit category note' value='Save' name='submitbutton' onclick=\"update_category_note('P','"+categoryid+"','"+noteidnew+"');\"></div></div>";
document.getElementById('parent_insert_div').innerHTML='';
document.getElementById('parent_insert_div').innerHTML = after_add_content_for_popup;
but it shows only the textarea not the tinymce editor.
A: You don't appear to be adding TinyMCE in the first place. Please look at the sample code on this page:
http://fiddle.tinymce.com/
Note the code used to add TinyMCE with various options:
tinyMCE.init
({
// General options
mode : "textareas",
theme : "advanced",
plugins : "autolink,lists,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,imagemanager,filemanager",
// Theme options
theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,spellchecker,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,blockquote,pagebreak,|,insertfile,insertimage",
theme_advanced_toolbar_location : "top",
theme_advanced_toolbar_align : "left",
theme_advanced_statusbar_location : "bottom",
theme_advanced_resizing : true,
width: "100%",
height: "400"
});
So, after including the TinyMCE JS files, you have to also initialize TinyMCE using the code above or something like it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578273",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to inject/resolve properties into an XML file with Guice to configure the persistence.xml file? I'm using guice-persist and I would like to know if there is any to inject or resolver properties from a Java property file into the persistence.xml file like I would do with Spring. For example:
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="WoloxShivaJPAUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.guidomb.MyClass</class>
<shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
<properties>
<property name="hibernate.connection.driver_class" value="${hibernate.connection.driver_class}">
<property name="hibernate.connection.url" value="${hibernate.connection.url}">
<property name="hibernate.connection.username" value="${hibernate.connection.username}">
<property name="hibernate.connection.password" value="${hibernate.connection.password}">
<property name="hibernate.dialect" value="${hibernate.dialect}">
<property name="hibernate.id.new_generator_mappings" value="true">
<property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.ImprovedNamingStrategy" />
</properties>
</persistence-unit>
</persistence>
If not how can I configure the EntityManager using the guice-persist libray so as to inject this properties from a property file?.
Thanks!
A: It looks like you can supply additional properties when creating JpaPersistModule:
JpaPersistModule jpa = new JpaPersistModule("myFirstJpaUnit");
jpa.properties(...);
Injector injector = Guice.createInjector(..., jpa);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578274",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: iphone app: how to deactivate and activate ipod app my voip app is configured to kAudioSessionCategory_PlayAndRecord category and kAudioSessionProperty_OverrideCategoryMixWithOthers audio session property.
During voip call, when voice playback and record is happening, ipod music is also mixing with voice.
How to make ipod music to deactive during voice call and re-active after completion of my voice call.
A: how about following:
[[MPMusicPlayerController iPodMusicPlayer] pause];
at the beginning of your voip call and
[[MPMusicPlayerController iPodMusicPlayer] play];
at the end of your voip call.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578275",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Retrieve 1 value that links to all values from database So I'm trying to display a list of all users in my database... each one with a link that will display their own information (in this case only displays user again and password), heres my code...
<?php
mysql_connect('localhost','user','password')or die ('Connection Failed: '.mysql_error());
mysql_select_db('name')or die ('Error to select database '.mysql_error());
$result = mysql_query("SELECT * FROM usuarios ORDER BY ID");
echo "<table border='0'>
<tr>
<th>UserName</th>
</tr>";
while ($row = mysql_fetch_array($result))
{
echo "<tr>";
echo '<td><a href="user.php?id='.$row['id'].'">' . $row['usuario'] . '</a></td>';
echo "</tr>";
}
echo "</table>";
?>
I get the ID of each user through the URL to be a new variable in my user.php page to recognize each one...
<?php
$numusu = $_GET['id'];
$result = mysql_query("SELECT * FROM usuarios WHERE id=`$numusu`");
while ($row = mysql_fetch_array($result))
{
echo "<table><tr>";
echo "<td>User:" . $row['usuario'] . "</td>";
echo "<td>Password:" . $row['password'] . "</td>";
echo "</tr></table>";
}
?>
But for some reason I'm not able to display anything in user.php, I get the ID value and all just missing the information I just get an error
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL
result resource in /site/test/test/test/login_php/user.php on line 15
What am I doing wrong? Please help me!
A: The query should be SELECT * FROM usuarios WHERE id='$numusu'. Backticks only work for table and database names.
When you get Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource, it usually means $result is null and/or mysql_query failed. If you change the query to
$result = mysql_query("...") or die(mysql_error());
It should tell you that something like Unknown column '1' in 'where clause'.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578278",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: iOS Cotains-based Predicate search only returns when exact match found I'm adding a search bar to a table view component of my iOS application that allows searching through an NSArray comprised of Dictionaries. The search bar does not work all the time, though - it successfully prints out a result if there is an exact match for my data, but not a partial match. For instance, it will print out "Turn off a light" as a result if that exact phrase is entered, but not if just "Turn" is entered. On a debugging array made only of strings, however, the search functionality worked exactly as expected.
My predicate code is here:
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[cd] %@", searchText];
self.searchResults = [allSearchableItems filteredArrayUsingPredicate:resultPredicate];
}
The test block that actually worked was written like this:
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[cd] %@", searchText];
NSArray *array = [NSArray arrayWithObjects:@"Miguel", @"Ben", @"Adam", @"Melissa", nil];
NSArray *moreStuff = [array filteredArrayUsingPredicate:resultPredicate];
NSLog(@"%@", moreStuff);
self.searchResults = [allSearchableItems filteredArrayUsingPredicate:resultPredicate];
}
In the above block of code, the NSArray "moreStuff" printed out and updated correctly, however in the first block the NSArray "searchResults" only returns a result when an exact match is entered. I'm at a complete loss here, so any help/recommendations will be super appreciated.
A: Because you are searching for a string in an object, I think you just need to dig a bit deeper in your predicate. A string within the object is only a partial match of that object. When you use SELF in the predicate, you're specifying to search within the object itself, which in your case is an NSDictionary. String fields in the NSDictionary are essentially objects within an object. So if you are looking for a field called 'Name' in your Dictionary, instead of having the predicate look in SELF, it should look in SELF.Name. You could try the following code to search the Name field of your NSDictionary.
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"SELF.Name CONTAINS[cd] %@", searchText];
self.searchResults = [allSearchableItems filteredArrayUsingPredicate:resultPredicate];
}
If you still need to check other fields contained within the object, you can create a compound predicate. Details on Predicates can be found in Apple's Predicate Programming Guide.
I hope this helps!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578281",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Is that possible to use SIP in LAN network? I don't know enough about SIP. As far as I know SIP can not be used in LAN. But it's features are very good. I want to use it for a LAN messenger (with video conference facilities).
Is there any way of using SIP in LAN network ?
A: The SIP protocol can be used over any reliable transport (TCP, XMPP, instant messaging channel, etc...) to a service (e.g. a server such as a SIP proxy) that knows how to route the SIP INVITE message from the caller to the callee. e.g. If you send an INVITE to bob@foobar.com, there's needs to be a service that knows how to find "bob" and deliver the message. Likewise, when Bob sends back his response messages back, the messages need to route back to the caller who sent the original INVITE.
And you can do SIP without a server - provided the computer already have a connection (direct or indirect) to the other computer intended for the call.
But SIP isn't anything special. If you were to invent your own video conferencing protocol, it would probably look a lot like SIP. SIP's primary job is for both sides of a call to exchange IP/port candidates for connecting directly in addition to codec and bandwidth negotiation data.
After the SIP messages are exchanged, ICE/STUN/TURN take over and RTP packets typically flow. SIP isn't used in the call except to end the call.
What are you really trying to do anyway?
A: Thread is Old but still I would like to contribute to this. There are various SIP server like http://www.officesip.com/index.html which works in LAN and can be connected to hardware phone too and soft client also.
Jitsi is open source cross platform SIP/xmpp client:https://jitsi.org/
And if you want to XMPP server Openfire is the best:http://www.igniterealtime.org/projects/openfire/
I hope this will definitely help someone..!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578282",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can I ignore irrelevant mergeinfo changes when scanning a log? Recently my scan for relevant changes has been including mergeinfo changes that are not relevant and I would like to ignore these revisions where the changes in the log item do not alter any items in the folder which I am iterating.
I can iterate through the svnChangeItems and check for the mergeinfo property but how do I tell if a ChangeItem was made to a file which was committed to the folder whose log items I am scanning. Similar to hide unrelated change paths except if I were to check this option in the log viewer It would not show some relevant revisions which include changes before the folder I was scanning moved. Any ideas?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578285",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What is the Scala syntax for summing a List of objects? For example
case class Blah(security: String, price: Double)
val myList = List(Blah("a", 2.0), Blah("b", 4.0))
val sum = myList.sum(_.price) // does not work
What is the syntax for obtaining the sum?
A: Try this:
val sum = myList.map(_.price).sum
Or alternately:
val sum = myList.foldLeft(0.0)(_ + _.price)
You appear to be trying to use this method:
def sum [B >: A] (implicit num: Numeric[B]): B
and the compiler can't figure out how the function you're providing is an instance of Numeric, because it isn't.
A: As an alternative to missingfaktor's Scalaz example, if you really want to sum a list of objects (as opposed to mapping each of them to a number and then summing those numbers), scalaz supports this as well.
This depends on the class in question having an instance of Monoid defined for it (which in practice means that it must have a Zero and a Semigroup defined). The monoid can be considered a weaker generalisation of core scala's Numeric trait specifically for summing; after all, if you can define a zero element and a way to add/combine two elements, then you have everything you need to get the sum of multiple objects.
Scalaz' logic is exactly the same as the way you'd sum integers manually - list.foldLeft(0) { _ + _ } - except that the Zero provides the initial zero element, and the Semigroup provides the implementation of + (called append).
It might look something like this:
import scalaz._
import Scalaz._
// Define Monoid for Blah
object Blah {
implicit def zero4Blah: Zero[Blah] = zero(Blah("", 0))
implicit def semigroup4Blah: Semigroup[Blah] = semigroup { (a, b) =>
// Decide how to combine security names - just append them here
Blah(a.security + b.security, a.price + b.price)
}
}
// Now later in your class
val myList = List(Blah("a", 2.0), Blah("b", 4.0))
val mySum = myList.asMA.sum
In this case mySum will actually be an instance of Blah equal to Blah("ab", 6.0), rather than just being a Double.
OK, for this particular example you don't really gain that much because getting a "sum" of the security names isn't very useful. But for other classes (e.g. if you had a quantity as well as a price, or multiple relevant properties) this can be very useful. Fundamentally it's great that if you can define some way of adding two instances of your class together, you can tell scalaz about it (by defining a Semigroup); and if you can define a zero element too, you can use that definition to easily sum collections of your class.
A: Scalaz has this method under a name foldMap. The signature is:
def M[A].foldMap[B](f: A => B)(implicit f: Foldable[M], m: Monoid[B]): B
Usage:
scala> case class Blah(security: String, price: Double)
defined class Blah
scala> val myList = List(Blah("a", 2.0), Blah("b", 4.0))
myList: List[Blah] = List(Blah(a,2.0), Blah(b,4.0))
scala> myList.foldMap(_.price)
res11: Double = 6.0
B here doesn't have to be a numeric type. It can be any monoid. Example:
scala> myList.foldMap(_.security)
res12: String = ab
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578287",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
}
|
Q: Does any Framework Support User to draw "candle graph" on the iPhone? iPhone sdk :Does any Framework Support User to draw "candle graph" in iphone sdk?
I have tried following framework:
*
*MIMChart-Library
*CorePlot
But it seems not example to show that how to draw Candle Graph......
Or user need to customize by ourself?
Because i am trying to draw candle graph by some framework,
i understand that i has not much Framework support draw candle graph , because it is little bit hard to draw...
A: Core Plot can draw candlestick plots. The Plot Gallery example app includes one.
A: everyone.
I just found that there has a example code in CorePlot named "AAPLot"
It seems like the Candlestick plots we are looking at in Stock Market....
Hope this reference can help you guys. :]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578291",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Any value of separating a MySQL query into $query and $result? I always see MySQL queries structured like this, even with the simplest of queries:
$query = "SELECT * FROM table_name WHERE id = '1'";
$result = mysql_query($query);
Is there any value, time or otherwise in doing the above over a simple one line query such as?
$result = mysql_query("SELECT * FROM table_name WHERE id = '1'";
I've always used the former, as when I started using PHP I thought it best to simply copy everyone else, however now that I'm working on a fairly large (relative to my other work) application, I could cut out a significant amount of arbitrary coding if there's really no difference.
A: With the first, it's easier to log the SQL in case something went wrong (and it's easier to spot typos, like a missing bracket).
A: Generally, I like separating them because I can easily do print $query; when I'm trying to figure out why my query won't work. It's mostly a matter of personal preference.
A: Actually there is no difference at all except for one thing. If you put your query in seperate variable then you can reuse that. If any changes occur in query you just need to edit the query in variable
A: You can always create a custom function that takes in a query and runs it, and pass additional optional arguments in case you want it to return the query, or log the query to track any issues etc.
A:
Is there any value, time or otherwise in doing the above over a simple one line query such as?
sure, as MSpreij said, you can examine your query in case of error.
I always see MySQL queries structured like this, even with the simplest of queries:
$query = "SELECT * FROM table_name WHERE id = '1'";
$result = mysql_query($query) or trigger_error(mysql_error()." ".$query);
this simple construct will save you a dozen whines in stackoverflow "what does it mean mysql_fetch_array(): supplied argument is not a valid MySQL result"
notice the additional part. This is called programming.
It will print your query automatically, in case of error, along with mysql error message. Or log it into error log in a live server with appropriate settings.
Without writing print $query; manually.
However, both methods are ugly as hell.
One should never use raw API functions at all.
It's ugly, unmaintainable, bloated and repetitive.
One should develop a library, a function to make a call more intelligent and less repetitive
$data = mydb_get_row("SELECT * FROM table_name WHERE id = 1");
having all the processing inside. with error handling, query logging, parameter checking and api functions calling.
yet as a true one-liner, not a silly one you were trying to achieve.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578304",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Looking to pipe incoming mail with a script and grab contents and store them as variables Users will send a text message/email to text@domain.com in the form of #### killed #### and we need to take the first #### and store it as a variable, and then take the second #### and store it as another variable.
I can't seem t find any relevant information online that shows what the context of a message looks like if the script were to read it. Any help would be greatly appreciated!
A: If you are trying to parse a message in a given format with PHP, you could try the following:
$text = "abc killed 123";
$tokens = explode(' killed ', $text);
print_r($tokens); // Prints [0] => abc, [1] => 123
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578307",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ruby on rails flash messages - :alert :error :notice and :success? In several of my controllers, I have redirects/flash messages
redirect_to products_url, :notice => "message here",
redirect_to states_url, :error => "oops!" etc...
In my sessions controller, however, upon successful authentication, I have
flash[:success] = "welcome!"
redirect_to user
I'd like to be able in my other controllers to do something like
:success => "yay!"
This is mostly for cosmetic/consistency purposes, but are :notice, :alert and :error the only flash-types available / can I add additional types? Am I making sense?
Thanks!
A: I believe without changes, this is as close as you'll get:
redirect_to user_path(@user), :flash => { :success => "Message" }
Here's some additional notes regarding the friendly flash syntax addition.
A: I just found out that in Rails 4 you can register custom types in app controller:
class ApplicationController
...
add_flash_types :error, :another_custom_type
end
# app/controllers/users_controller.rb
class UsersController < ApplicationController
def create
...
redirect_to home_path,
error: "An error message for the user"
end
end
# app/views/home/index
<%= error %>
The merit goes to http://blog.remarkablelabs.com/2012/12/register-your-own-flash-types-rails-4-countdown-to-2013
A: If you want to access different types of flash messages styles based on bootstrap alert (success and warning), in you controller:
flash[:success] = "This works!"
And in your layout (most probably application.html.erb)
<% if success.present? %>
<p class="alert alert-success"><%= success %></p>
<% end %>
Same thing with warning and other bootstrap alert styles.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578310",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "29"
}
|
Q: Automatically Appending Comments to Auto-Inserted Curly Braces in Netbeans I really appreciate how NetBeans automatically enters closing brackets to the code I'm working on. Would it happen to be possible for it to further streamline the development of code that looks like this?:
public class Test
{
public static void main(String[] Args)
{
//Some code here
while(true)
{
//Some more code here
}//end while
}//end main
}//end class
A: Unfortunately there doesn't seem to be a way to customize what is generated when NetBeans adds the closing bracket: there is just a checkbox for whether to do this or not in Tools->Options->Editor->Code Completion.
Here is the next best solution:
NetBeans features "code templates", which are snippets of predefined code that are automatically generated when you type some predefined abbreviation and then hit tab. For example, if you type if and hit tab, your editor should generate the following code:
if (true) {
}
You can modify these code templates to your needs or create new ones of your own. Go to Tools->Options->Editor->Code Templates. You will see an extensive list of templates, each matching an abbreviation, and a small edit box to change them. If you scroll down to "if" you'll see this definition:
if (${EXP instanceof="boolean" default="true"}) {
${selection}${cursor}
}
All you need to do is modify it to generate what you desire:
if (${EXP instanceof="boolean" default="true"}) {
${selection}${cursor}
}//end if
You can do something similar for other statements such as while. You'll notice there often are multiple templates per statement based on different patterns, so this could get tedious depending on how thorough you want to be.
This solution also works well for the main method, since there is a template defined for it - typing psvm and tabbing generates it. For other arbitrary methods, there is a template with the abbreviation m.
Achieving this effect for a top-level class will be different. Go to Tools->Templates. Here you'll see another set of templates which you can explore and modify. The difference is that these are for files rather than code snippets. Expand Java and open the Java Class template file. You'll see the following:
<#assign licenseFirst = "/*">
<#assign licensePrefix = " * ">
<#assign licenseLast = " */">
<#include "../Licenses/license-${project.license}.txt">
<#if package?? && package != "">
package ${package};
</#if>
/**
*
* @author ${user}
*/
public class ${name} {
}
Once again, you can modify this template to your needs:
public class ${name} {
}//end class
Or even:
public class ${name} {
}//end {$name}
which will put //end Foo for a class named Foo
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578311",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to select jquery tabs if errorLable display im up to apply jquery UI tabs to my application and im going to apply jquery validation class on that. my problem is if i got error in some div that div should selected and display the error to user when click on the save button .
i tried
$('#tabs > div').each(function(i){
if($('.errortd', this).not(':hidden').length>0){
$("#tabs").tabs('select', i);
});
});
But i have no luck any help thanks lot
my tabs div
<div id="tabs">
<ul>
<li><a href="#editEmployeeDIV"><?php echo __("View/Edit employees") ?></a></li>
<li><a href="#addEmployeeDIV"><?php echo __("Assign new employees") ?></a></li>
</ul>
<div id="editEmployeeDIV">
</div>
<div id="editEmployeeDIV">
</div>
</div>
my error lables having class errortd
<label for="txtAmount_146" generated="true" class="errortd" style="display: none; ">This field is required.</label>
A: You have a few problems.
The first is a stray ); in your code:
if($('.errortd', this).not(':hidden').length>0){
$("#tabs").tabs('select', i);
}); // <------ Right here
Then you're using :hidden when you shouldn't be. From the fine manual:
Elements can be considered hidden for several reasons:
[...]
*
*An ancestor element is hidden, so the element is not shown on the page.
That means that the <label> will always be considered hidden if it is in a non-current tab.
You could do something like this:
var $shown = $(this).find('.errortd').filter(function() {
var dpy = $(this).css('display');
return !dpy || dpy != 'none';
});
if($shown.length > 0)
$("#tabs").tabs('select', i);
Demo: http://jsfiddle.net/ambiguous/agrCe/
Or, add a class to the <label> elements that hides them instead of manually hiding them. You have a bit of CSS like this:
.no-error {
display: none;
}
And then:
if($(this).find('.errortd:not(.no-error)').length > 0)
$("#tabs").tabs('select', i);
Demo: http://jsfiddle.net/ambiguous/Z4D2A/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578312",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to save the prawn pdf on rails root without rendering Here my code rendering pdf is ok .But I don't want render directly save to the rails folder how?
Help me please
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @claim }
format.report { render_report }
format.xls { render_report }
format.pdf { render :layout => false }
end
A: I'm not sure if I understood well... if you want to have downloadable pdf, you could do something like this:
format.pdf {send_data your_pdf, :type => 'application/pdf'}
You didn't say which version of rails are you using, but in general methods send_data and send_file could be usefull for you (links are to v 2.3.8, but of course those methods exist in newer versions).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578317",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Implementing join function in a user level thread library I am trying to implement a user level thread library as part of a project. My focus is on the join function. Lets say that Thread1 calls join function on Thread2. What i need to do is get the return value/argument supplied to pthread_exit() from Thread2 and store it in the memory location specified in join function argument.
But, how do i get the return value of another thread?
Any help will be appreciated. Thanks
A: Here is an example taken from the GnuPth(pth_lib.c) user-level threading library, which shows the implementation of the exit and join functions, respectively. I simplified the code to highlight the return value handling.
void pth_exit(void *value)
{
pth_debug2("pth_exit: marking thread \"%s\" as dead", pth_current->name);
/* the main thread is special, because its termination
would terminate the whole process, so we have to delay
its termination until it is really the last thread */
/* execute cleanups */
/*
* Now mark the current thread as dead, explicitly switch into the
* scheduler and let it reap the current thread structure; we can't
* free it here, or we'd be running on a stack which malloc() regards
* as free memory, which would be a somewhat perilous situation.
*/
pth_current->join_arg = value;
pth_current->state = PTH_STATE_DEAD;
pth_debug2("pth_exit: switching from thread \"%s\" to scheduler", pth_current->name);
//return (for ever) to the scheduler
}
and the corresponding pth_join:
/* waits for the termination of the specified thread */
int pth_join(pth_t tid, void **value)
{
//Validate thread situation.
//wait until thread death
//save returned value for the caller
if (value != NULL)
*value = tid->join_arg;
//remove thread from the thread queue
//free its memory space
return TRUE;
}
A: You could create storage for the return value in the application or process context, initialized when your threads library initializes. Your pthread_exit would fill the value and your join would use the threadid to retrieve it - I think this will only work for non-dynamically allocated return values though.
A: I'm interesting about the meta-info for individual thread in you implementation. Return value could be one of items stored in that of a thread, besides ID, stack pointer and so on.
When pthread_exit() is called, such information should be dumped to one or more data structures by scheduler, so that other thread can consult them when needed.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578318",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is there any API from Bing like Google Places? Anyone knows whether Bing provides any API similar to Google Places?
Thanks!
A: You can use Bing API with Phonebook source type to retieve information about businesses:
*
*general information about the Phonebook source type API is available here
*JSON-based implementation example available here
A: The Bing Services Location API might be what you are looking for.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578319",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Cassandra Client - examining columns as Strings I am new to Cassandra & I am using the Hector Java Client for writing/reading from it.
I've the following code to insert values -
Mutator<String> mutator = HFactory.createMutator(keyspaceOperator, StringSerializer.get());
mutator.insert("jsmith", stdColumnDefinition, HFactory.createStringColumn("first", "John"));
Now, when I get the values back via the Hector client - it works cleanly -
columnQuery.setColumnFamily(stdColumnDefinition).setKey("jsmith").setName("first");
QueryResult<HColumn<String, String>> result = columnQuery.execute();
However, when I try to get the values from the command line cassandra client, I get the data in bytes, rather than human readable String format. Is there a way for me to fix this so that I can use the cassandra client to spit out Strings -
here is the sample output
[default@keyspaceUno] list StandardUno ;
Using default limit of 100
RowKey: 6a736d697468
=> (column=6669727374, value=4a6f686e, timestamp=1317183324576000)
=> (column=6c617374, value=536d697468, timestamp=1317183324606000)
1 Row Returned.
Thanks.
A: You can either modify the schema so that Cassandra interprets the column as a string by default, or you can tell the CLI how to interpret the data, either on a one-shot basis, or for the rest of the session, using the "assume" command.
See http://www.datastax.com/docs/0.8/dml/using_cli#reading-rows-and-columns for examples.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578322",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Get all dates (not days) between two NSDates How can I get all the dates that come in between 2 dates?
For example:
Start date = 2011/01/25
End date = 2011/02/03
A: 1) Find the no of days between two dates. Then,
for(i=0;i<noofdays;i++)
{
//Find the next date
//add to the array
}
To find number of days
To find next date
A: NSCalendarUnit serves for defining the step between the dates & taking care of the dates being normalized.
iOS 8 API, Swift 2.0
func generateDates(calendarUnit: NSCalendarUnit, startDate: NSDate, endDate: NSDate) -> [NSDate] {
let calendar = NSCalendar.currentCalendar()
let normalizedStartDate = calendar.startOfDayForDate(startDate)
let normalizedEndDate = calendar.startOfDayForDate(endDate)
var dates = [normalizedStartDate]
var currentDate = normalizedStartDate
repeat {
currentDate = calendar.dateByAddingUnit(calendarUnit, value: 1, toDate: currentDate, options: NSCalendarOptions.MatchNextTime)!
dates.append(currentDate)
} while !calendar.isDate(currentDate, inSameDayAsDate: normalizedEndDate)
return dates
}
A: To find all days between two NSDates:
- (void)cerateDaysArray{
_daysArray = [NSMutableArray new];
NSCalendar *calendar = [[NSCalendaralloc]initWithCalendarIdentifier:NSGregorianCalendar];
[calendar setTimeZone:[NSTimeZone systemTimeZone]];
NSDate *startDate = [_minDate copy];
NSDateComponents *deltaDays = [NSDateComponents new];
[deltaDays setDay:1];
[_daysArray addObject:startDate];
while ([startDate compare:_maxDate] == NSOrderedAscending) {
startDate = [calendar dateByAddingComponents:deltaDays toDate:startDate options:0];
[_daysArray addObject:startDate];
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578323",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Cocoa TDD and singletons I'm doing TDD with Cocoa and I wanted to ask - what is the correct way of testing a singleton class? I'm curious about the initialization and retrieval part.
I'm thinking of doing something similar to this:
MySingleton *singleton1 = [MySingleton sharedInstance];
MySingleton *singleton2 = [[MySingleton alloc] init];
STAssertEqualObjects(singleton1, singleton2, @"Objects were not equal: %@ and %@", singleton1, singleton2);
Anything else I should test for? Should I even try to test the behavior under possible race conditions (test the @synchronize statement)?
A: If your singleton has no writable state, then you don't have to worry about this at all.
If your singleton has writable state, then it probably shouldn't be a singleton at all.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578325",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Where to #import on Objective-C My project has been increasing in size and I'm a little confused about where should I #import header files.
There are 3 main locations where I can import headers:
*
*The .pch file (prefix)
*The .h file (header)
*the .m file (implementation)
I don't care if the compiler takes more time to compile the files, all I care is that the end product is as fast as possible and uses the least amount of memory.
So, my questions are:
*
*If most files need a specific header, is it ok to add it to the .pch file, or is it more efficient to add it to just the required files?
*Should imports be done in the .h or .m file? I know I must add it to the .h file if i'm going to declare it there, but if I don't need to declare it in the .h file is there a problem of leaving the import there?
A: *
*No, it is not ok to include it into the .pch file. This file is precompiled to every module in the project. Read about it here.
*Read this question and answer.
A: Put your imports in your .m whenever you can. If you are using a class in your .h use @class to forward the declaration, then #import in your .m. The only time you should import in your .h are protocols that you implement or superclasses.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578330",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: element remove() not working in second remove I Have code like below :
<tbody>
<tr name="a02323232">
<tr name="j03543434">
</tbody>
first i want to remove element with :
$("tr[name='a02323232']").hide("slow");
second then i want to remove
$("tr[name='j03543434']").hide("slow");
in first try , its successfull to remove but in the second try its not working , then i trace that the mistake is the jquery still do remove() like the first try . so only just element in the first try is removed .
Maybe i wrong ? please help me .
A: If you use legal HTML, it seems to work for me here: http://jsfiddle.net/jfriend00/V8LCK/.
<table>
<tbody>
<tr name="a02323232"><td>1</td></tr>
<tr name="j03543434"><td>2</td></tr>
</tbody>
</table>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578341",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Unresponsive Fade-In Fade-Out in Jquery I am implementing a twitter-style follow/unfollow functionality with the following jquery.
$(function() {
$(".follow").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$("#loading").html('<img src="loader.gif" >');
$.ajax({
type: "POST",
url: "follow.php",
data: info,
success: function(){
$("#loading").ajaxComplete(function(){}).slideUp();
$('#follow'+I).fadeOut(200).hide();
$('#remove'+I).fadeIn(200).show();
}
});
return false;
});
});
I have a similar unfollow function. However i have the following problem:
When I have N items {1,2..i.N} each with id = followi and I click on the follow button. I find that some of the items respond while others do not. I suspect it is a pure javascript issue...otherwise i figure none of the buttons would respond at all.
Is it a timing issue...all help is appreciated. Also i'd appreciate it if you could point me to a simpler method.
Thanks!
A: Well you are doing the UI update in your ajax success handler, so the reaction time for the UI updated is based on the speed of the Ajax response. And if the server doesn't return successfully, the UI update won't happen at all.
A simpler method with instant response:
$(function() {
$(document.body).delegate(".follow","click",function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$("#loading").html('<img src="loader.gif"/>');
$('#follow'+I).fadeOut(200); // act instantly since we assume it will go well
$('#remove'+I).fadeIn(200); // act instantly since we assume it will go well
$.ajax({
type: "POST",
url: "follow.php",
data: info,
complete: function(){ //always remove the loader no matter if it goes well or not
$("#loading").slideUp();
},
error: function() {
//handle error
$('#follow'+I).fadeIn(200); // correct mistake
$('#remove'+I).fadeOut(200); // correct mistake
}
});
return false;
});
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578343",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Ordering records by frequency with Arel How do I retrieve a set of records, ordered by count in Arel? I have a model which tracks how many views a product get. I want to find the X most frequently viewed products over the last Y days.
This problem has cropped up while migrating to PostgreSQL from MySQL, due to MySQL being a bit forgiving in what it will accept. This code, from the View model, works with MySQL, but not PostgreSQL due to non-aggregated columns being included in the output.
scope :popular, lambda { |time_ago, freq|
where("created_on > ?", time_ago).group('product_id').
order('count(*) desc').limit(freq).includes(:product)
}
Here's what I've got so far:
View.select("id, count(id) as freq").where('created_on > ?', 5.days.ago).
order('freq').group('id').limit(5)
However, this returns the single ID of the model, not the actual model.
Update
I went with:
select("product_id, count(id) as freq").
where('created_on > ?', time_ago).
order('freq desc').
group('product_id').
limit(freq)
On reflection, it's not really logical to expect a complete model when the results are made up of GROUP BY and aggregate functions results, as returned data will (most likely) match no actual model (row).
A: you have to extend your select clause with all column you wish to retrieve. or
select("views.*, count(id) as freq")
A: SQL would be:
SELECT product_id, product, count(*) as freq
WHERE created_on > '$5_days_ago'::timestamp
GROUP BY product_id, product
ORDER BY count(*) DESC, product
LIMIT 5;
Extrapolating from your example, it should be:
View.select("product_id, product, count(*) as freq").where('created_on > ?', 5.days.ago).
order("count(*) DESC" ).group('product_id, product').limit(5)
Disclaimer: Ruby syntax is a foreign language to me.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to encode for a dict I have the following dict:
dict = {"es-ES": "Capítulo "}.
However, when I try to use the dict, I get the following error:
SyntaxError: Non-ASCII character '\xc3' in file..
I looked into the massive Python unicode docs ( http://docs.python.org/howto/unicode.html ), but haven't been able to figure this out yet. How would I 'encode' the dict so I could call dict['es-ES']? Thank you.
A: Add the following line:
# -*- coding: utf-8 -*-
(Assuming you are using UTF-8), to the top of your Python file and you will be able to use Unicode without issue. See the Python docs on unicode.
* Also, don't use dict as a variable name - you'll shadow the built-in type of the same name
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578347",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: fwrite not writing $fp = fopen('log.txt', 'w');
fwrite($fp, 'Missing gallery image for: ' . $row['toolbar_id'] . '\n');
The code above is not writing to the file. the $row['toolbar_id'] is a value from a for each loop. Any suggestions? There is no PHP error, as the file does open as I have debugged that part.
A: Try this for extra surety
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$fp = fopen('log.txt', 'ab');
if (false === $fp) {
throw new RuntimeException('Unable to open log file for writing');
}
$bytes = fwrite($fp, 'Missing gallery image for: ' . $row['toolbar_id'] . PHP_EOL);
printf('Wrote %d bytes to %s', $bytes, realpath('log.txt'));
fclose($fp);
Edit: Changed the "write" flag (w) to "append" (a) as truncating a log file doesn't sound like a great idea
A: https://bugs.php.net/bug.php?id=48607
there is a php bug with fwrite and ftp which means the last chunks of files sometimes dont get written when fclose is called directly after fwrite
putting a sleep(1); before fclose fixes the issue, or in your case logging to a file before fclose can also stop it
posting for future reference!
A: <?php
$filename = 'log.txt';
$somecontent = "Missing gallery image for: ";
if($row['toolbar_id'] != "")
{
$somecontent .= $row['toolbar_id'];
}
if (is_writable($filename)) {
if (!$handle = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
exit;
}
if (fwrite($handle, $somecontent) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
echo "Success, wrote ($somecontent) to file ($filename)";
fclose($handle);
} else {
echo "The file $filename is not writable";
}
?>
Try this code... !!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578350",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to create Search Box without using plug-ins? I'm new to this and doing some research on how to create a Search Box from scratch (without using plug-ins like Google, etc).
The idea is to search within a particular website NOT all websites like Google does. Search results need to be displayed on that particular website.
Preferably using JS and PHP.
Please advise. Thanks.
A: its pretty simple.
from javascript/DOM you need: onkeypress or onkeyup.
plus ajax technology to send it while user is on your page ( without redirects. but I think its better to not use ajax in this subject )
from php you need an "handler" script which
will get your requests from your search field ( input type=text ) and search data in your DB using simple SELECT (you can use LIKE option).
and then you fetch all results form your request to your result page.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578351",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to increment the Identity column I am using identity columns as a primary key in my tables.
In some situations I need to work with primary keys before inserting a new row.
For example, in Oracle I use : select <sequence_name>.nextval into <variable> from dual
and I was sure that no one will insert any row with the same ID while my sp was executing.
As for SQL Server I can read the current identity value and it's increment, but there is no way to increment it without inserting a row.
Updated: The question is - how can I accomplish my task to work with ID (as identity column) in SQL Server before inserting a row and be sure that it will be unique at the end of my stored procedure.
Updated:I have a table with HierarchyId column.The way to form the first level of hierarchy,in my case, is to insert the hierarchyId column, according to indentity column. That is how I'v done it now:
begin transaction
insert into [dbo].[Group](GroupTypeId,CompanyOwnerId,GroupHierarchyId)
values(@GroupTypeId,@HeaderCompanyId,null)
update [dbo].[Group]
set GroupHierarcyId=hierarchyid::GetRoot().GetDescendant(cast ('/'+cast(@NewGroupId as varchar)+'/' as hierarchyid),null)
where GroupId=scope_identity()
commit
A: You can put an exclusive lock on the table, get the maximum ID, add 1 to it. That will be your next ID. Insert your data, the unlock the table.
HOWEVER,
I cannot fathom why you would want to work with a value before it is created. Can yo post a bit more information on that?
A: If you need a key that would be unique across databases and database servers, then the GUID's (Global Unique Identifier) certainly fulfills this need.
If you want to generate a new GUID server the you can simply use the NEWID() function
SELECT NEWID()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578352",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Can a character array be used as expression for switch statement? void main()
{
char name[20];
printf("\n enter Your Name: ");
gets(name);
switch(name)
{
default : printf( "Invalid" );
}
getch();
}
So my question: is a char array OR Simple array valid in expression for switch and, if it is valid, then what are the case values?
A: The switch statement is using the address of the character array as the parameter. So no it won't work as you expect it to.
It follows the same reason why you can't throw strings into a switch and expect it to work. (and same with string comparisons)
A: No, the standard says
The controlling expression of a switch statement shall have integer
type.
in your case the address of the string would be taken which is not considered to be an integer in that respect.
A: No you cannot. You will need to create an array of character arrays (strings). Search them to convert to and integer (index into that array) and use that instead.
A: I'm afraid not. To compare strings/char-arrays, you have to use some other functions such as 'strcmp'.
If you really want to use the switch-case structure, you can map each of your strings to distinct integers and switch by it. Here is a DEMO.
A: If you ask about its validity, yes it's valid and the compiler would be happy to compile. However, the compiler won't compare the content (the characters in the string), instead the pointer value would be compared.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578353",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Buggy Comments Code with Rails App So for some reason my code seems to have a mind of its own and will work at some points and then other times will throw an error saying undefined name method when trying to run this code in the view
<%= div_for comment do %>
<p>
<big><%= h(comment.body) %> - <%= link_to comment.user.name, comment.user %> </big><br />
Posted <%= time_ago_in_words(comment.created_at) %> ago
</p>
<% end %>
The code for my comments controller looks like this
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.build(params[:comment])
@comment.user_id = current_user.id
@comment.save
respond_to do |format|
format.html { redirect_to @post}
format.js
format.json { render :json => @comments }
end
end
Like I said sometimes this code works fine and sometimes it doesn't. I'm not sure whats causing the problem, whats even more weird is that in my localhost its working fine but when I push the code to my domain it doesn't work. Before you say it may be a domain rails version mismatch you should know this problem has occurred on my localhost as well before and then resolved itself magically without me changing any code. If anyone could help me it would be greatly appreciated.
Edit: Here is the error log you requested
Completed 500 Internal Server Error in 286ms
ActionView::Template::Error (undefined method `name' for nil:NilClass):
1: <%= div_for comment do %>
2: <p>
3: <big><%= h(comment.body) %> - <%= link_to comment.user.name, comment.user.name %></big><br />
4: Posted <%= time_ago_in_words(comment.created_at) %> ago
5: </p>
6: <% end %>
app/views/comments/_comment.html.erb:3:in `block in _app_views_comments__comment_html_erb___3516162043769402279_2170426440__2165839557434581766'
app/views/comments/_comment.html.erb:1:in `_app_views_comments__comment_html_erb___3516162043769402279_2170426440__2165839557434581766 '
app/views/posts/show.html.erb:14:in `_app_views_posts_show_html_erb__667623582898069867_2171134300_136023206927572946'
app/controllers/posts_controller.rb:23:in `show'
A: You may checkout the value of comment.user when the error occurs. It seems that comment.user is not an object User as you expect. Checkout your database, maybe some comments are not associated with users or associated with non-existant users.
You can try to debug like this when you'll have the error again:
<% comments.each do |comment| %>
<%= debug comment %> // Or comment.user
<% end %>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578354",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: google android market search result I submitted my first app to the android market about 3 months ago. Since then I've been getting on average about 10 to 20 downloads a day.
A couple of weeks ago Google released their new market new look and since then my app hasn't been downloaded not even once and I didn't even know why until a few days ago I made search for it using the app title and even though the Android market said that there was over 400 returns for that keyword it only showed about 20 of them and my app wasn't even there.
Does anyone have any information about this issue?
A: Check the spelling, it might have autocorrected your application name.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578357",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Error on driving IE using Watir-Webdriver : Unable to find element with xpath I'm new on Watir-webdriver.
I have tried running watir-webdriver using Firefox on http://bit.ly/watir-example
I tried on Internet Exploerer (IE ver 8), but it doesn't work.
I also have set protected value on IE with the same value.
My code is simple as this:
browser = Watir::Browser.new :ie
browser.goto 'http://bit.ly/watir-example'
sleep 5
browser.text_field(:name => 'entry.0.single').set 'My Name'
The error message that I get is like this:
C:/Ruby192/lib/ruby/gems/1.9.1/gems/selenium-webdriver-2.6.0/lib/selenium/webdriver/remote/response.rb:45:in
`assert_ok': Unable to find element with xpath == .//input[(not(@type)
or (@type!="file" and @type!="radio" and @type!="checkbox" and
@type!="submit" and @type!="reset" and @type!="image" and
@type!="button" and @type!="hidden" and @type!="datetime" and
@type!="date" and @type!="month" and @type!="week" and @type!="time"
and @type!="datetime-local" and @type!="range" and @type!="color"))
and @name='entry.0.single'] | .//textarea[@name='entry.0.single']
(Selenium::WebDriver::Error::UnexpectedJavascriptError)
Can anyone help me please?
Thank you.
A: Use irb to provide you with some more information about your problem
eg.
> irb
> require 'watir-webdriver'
> browser = Watir::Browser.new :ie
> browser.goto 'http://bit.ly/watir-example'
> puts browser.title
> puts browser.text_fields.count
> browser.text_field.set 'hello'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578363",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: ASIHTTPRequest startSynchronous callback not showing/hiding MBProgressHUD before/after data is received I'm trying to simply create a MBProgressHUD, show it, start a synch or asynch request, push a new controller on UINavigationController, and remove said MBProgressHUD. However, the HUD does not appear until the data is received. There is only a flicker of the HUD. I tried doing this asynchronously, but that did the exact same thing. Any ideas?
ASIFormDataRequest* request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:@"occ_get_images_by_tag" forKey:@"action"];
[request setPostValue:[NSString stringWithFormat:@"%@", tag_id] forKey:@"tag_id"];
//HUD is a property of the UIViewController
HUD = [[MBProgressHUD alloc] initWithView:self.view];
[self.view addSubview:HUD];
HUD.delegate = self;
//Tried messing with this, making a message and changing onTarget: to self
//didn't work
[HUD showWhileExecuting:@selector(startSynchronous) onTarget:request withObject:nil animated:YES];
[request startSynchronous];
NSError* error = [request error];
if(!error){
NSArray* tempArr = [[request responseString] objectFromJSONString];
// Do some stuff
[self.navigationController pushViewController:imtv animated:YES];
[HUD removeFromSuperview];
}else{
NSLog(@"%@", [error description]);
}
My understanding of how ASIHTTPRequest works is that things that happen before startSynchronous will actually happen before that message is called. Then, anything inside the if(!error) will happen after data is received and ready to be processed. It just seems like the callback isn't working at all.
Also if it's of any help, this all happens in tableView:didSelectRowAtIndexPath:.
A: You will not be able to use MBProgressHUD on the main thread of the application. If you want to get this working in your sample code, use the delegates of the ASIHTTPRequest and you will be able to see the MBProgressHUD
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578367",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: XDT Config Transforms - ReplaceAll? I've got a custom section in my web.config file similar to this structure:
<Messages>
<Message id="1'>
<Property Name="foo" value="bar" />
</Message>
<Message id="2'>
<Property Name="foo" value="bar2" />
</Message>
</Messages>
I want to apply a custom transformation on this such that I can change the value of ALL instances of the Property element with Name="foo" - but I cant seem to get it to work.
I've tried:
<Messages>
<Message>
<Property Name="foo" value="updated" xdt:Locator=Match(Name) xdt:Transform="Replace" />
</Message>
</Mesasges>
I can remove all the elements by replacing the Transform=Replace with a Transform=RemoveAll - any ideas how I can achieve something similar to replace all the values?
A: It seems like Transform:Replace only replaces the first matched element from the documentation on msdn: ...If more than one element is selected, only the first selected element is replaced. I solved this issue by using a combination of Match-Conditions and SetAttributes, something like:
<Messages>
<Message>
<Property value="updated" xdt:Locator=Condition(@Name='foo') xdt:Transform="SetAttributes(value)" />
</Message>
</Messages>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578369",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Is it possible to show the dock icon when a new Window is called? I have an app that's shown as a Menu on the Status Bar, so I switched the "Application is agent (UIElement)" in plist to YES (because I dont want an icon on the dock just for a Menu on the Status Bar), but when I click an Item on the Menu a new window is called, is it possible to make a dock icon appear for that window? and disappear when the window is closed?
A: You will need to create a separate application binary/bundle to display that window. There is no supported way for an application to cause a Dock icon to be displayed on anything other than a per-process basis, or to dynamically hide/show the Dock icon while it's running.
A: You can show and hide the Dock icon of an application with NSRunningApplication+DockIcon but beware, this code uses undocumented APIs.
A: To set your application to be a foreground application, which causes its icon to appear in the Dock, and the app to appear in the Cmd+Tab list:
ProcessSerialNumber processSerialNumber = {0, kCurrentProcess};
TransformProcessType(&processSerialNumber, kProcessTransformToForegroundApplication);
And to change it back again:
ProcessSerialNumber processSerialNumber = {0, kCurrentProcess};
TransformProcessType(&processSerialNumber, kProcessTransformToUIElementApplication);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578370",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Managing state with scalatra I understand that Scalatra is a lightweight framework. However, I'm wondering if there are any tricks for managing small amounts of state. I have a form with a textarea and a few checkboxes. For example, suppose the textarea contains a math equation and the checkboxes some additional options. When I submit (method=POST), I would like to display a result beneath the form, but maintain the same options (same text in the textarea, same checkboxes checked).
Is there a good way to accomplish this? Or do I need to manually set the values when generating the HTML? I'm presently generating HTML using Jade.
A: Do it server side with a resource returning JSON, and call it dynamically using JavaScript XHR.
No need of state! Go away Evil State!
EDIT
~A bit more explanation~
*
*You create a webservice that take computation parameter as input (using ?= in url with GET, or better using JSON payload with POST), then the service do the computation and return a JSON representation of the result
*You call that scalatra webservice using AJAX from your web application and you update the content of the webpage using the JSON result returned by the web server
If you don't already know much about AJAX, read tutorials and I think you will understand better what I mean. You can too search for example of Scalatra resource that return JSON representation (using lift-json i.e.)
As a side note, you can take a look at Bowler: http://www.bowlerframework.org
which make REST development on scalatra easier.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578372",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How can i change layout when orientation is change I want to change my blackberry screen GUI When i go from portrait to landscape mode.
protected void sublayout(int width, int height) {
// TODO Auto-generated method stub
if(Display.getOrientation()==Display.DIRECTION_PORTRAIT)
{
label.setText("Portrait");
}
else
{
label.setText("Landscape");
}
super.sublayout(width, height);
}
any help would be appreciated
A: Override sublayout on your screen, this is called whenever the orientation changes so you can use it to add/remove/change fields.
You can also use Display.getOrientation() to check the current orientation. You should also track the previous orientation within your application in case sublayout was called for a different reason.
A: You need to handle it manually. Whenever orientation changes in blackberry it calls the subLayout() method. There you can call invalidate method which will refresh your screen. But make sure that you are using relative layout instead of absolute layouts. It will automatically arrange the UI elements in your screen.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578379",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: SmartPhone(Iphone): Section not visible but visible in Desktop browser We have a ASP.Net application that we use for SmartPhone devices. One of the screens has a section that is visible in a desktop browser but not on a smartphone browser(Iphone Safari browser). I have marked the section and
Would we know why?Any pointers would be welcome.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta content="yes" name="apple-mobile-web-app-capable" /><meta content="text/html; charset=iso-8859-1" http-equiv="Content-Type" /><meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=1;" /><link href="styles/StyleSheet.css" rel="stylesheet" type="text/css" /><title>
Floor Plan Details
</title>
<script type="application/x-javascript">
if (navigator.userAgent.indexOf('iPhone') != -1) {
addEventListener("load", function() {
setTimeout(hideURLbar, 0);
}, false);
}
function hideURLbar() {
window.scrollTo(0, 1);
}
</script>
<script type="text/javascript">
function ColapseDetails() {
var elem2 = document.getElementById('divButton');
var details = document.getElementById('divDetails');
elem2.className = 'Show';
details.style.display = 'none';
}
function ExpandDetails() {
var elem2 = document.getElementById('divButton');
var details = document.getElementById('divDetails');
elem2.className = 'Hide';
details.style.display = 'block';
}
</script>
<style type="text/css">
a, .hdrGreen, .TxtAccent2, .itemList ul li
{
color: #b5985a;
}
#HeaderBar, #ftrCopyright
{
background-color: #f8cb30 !important;
}
#FtrNav, #HdrNav, .Separate, .SeparateSR, .smSeparate, .Button
{
background-color: #0068b3 !important;
}
a:hover, .hdrBlue, .TxtAccent1
{
color: #0068b3;
}
.Links a, .contents a
{
color: #b5985a !important;
}
.TitleLink
{
color: #0068b3 !important;
}
.PropGalThumb, .LargePhoto, .PhotoFrame
{
border-color: #f8cb30 !important;
}
</style>
<link href="/WebResource.axd?d=rYllaDxVV86L8uK7fm716DHtvUx7jEZl07Ni1bAwaCFyy83QnKp58MjumhwHTm3k5DeaG8uKyMP-a7NwOtgW5HQ2pq4UHdVEXH7SniWIwg9RO4oFHQ9Ox82H1rrwkiQS3YslSA2&t=634487606568630000" type="text/css" rel="stylesheet" class="Telerik_stylesheet" /><link href="/WebResource.axd?d=t9YDm8fMtH0CC5asMtMI4fYQLHf0MgrFPIjAybzYl__rRvUM4FsPvrIk2Je7ADAX9h_Y7xc4-kfkfmXrbForHb-JW0HpLzZPt9DexdRer9z0PQom39lb0-brKgkmrYByRaOt9nXhQsatKXhpIL2qfjQhGT81&t=634487606568630000" type="text/css" rel="stylesheet" class="Telerik_stylesheet" /><link href="/WebResource.axd?d=HnZfSQ00Unw9sodb1ZENEb8OCaQNYLMOL7UEoEroy1WahkY5iq6Kb-y9ve7XIVzS9OaCT9LmBYi7u4NjAWkkpgeFHkBbBszYstomcGDOiKzlHBwMuZmZNFVDxXkoO5fUAN-Z_w2&t=634487606568630000" type="text/css" rel="stylesheet" class="Telerik_stylesheet" /></head>
<body>
<form name="aspnetForm" method="post" action="FloorPlanDetails.aspx" id="aspnetForm">
<div>
<input type="hidden" name="ctl00_RadScriptManager1_TSM" id="ctl00_RadScriptManager1_TSM" value="" />
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPaA8FDzhjZTRiODM4M2EyMzRhNhgBBR5fX0NvbnRyb2xzUmVxdWlyZVBvc3RCYWNrS2V5X18WAgUdY3RsMDAkY3BoQ29udGVudCR0c0Zsb29ycGxhbnMFHmN0bDAwJGNwaENvbnRlbnQkbXB2Rmxvb3JwbGFuc9fXJq/1CrDWuJv8X3Ex07QdyIjs" />
</div>
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['aspnetForm'];
if (!theForm) {
theForm = document.aspnetForm;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
<script src="/WebResource.axd?d=UvkWM5HwgcL8L6uzzv8ClbaUMj56sSlOI0ToE3UrzfY6Jb13eC2SwwgMrrnYyKCI9Eh_8mDefDtQl4hVuuGtgtYRDWo1&t=634515435604257574" type="text/javascript"></script>
<script src="/Telerik.Web.UI.WebResource.axd?_TSM_HiddenField_=ctl00_RadScriptManager1_TSM&compress=1&_TSM_CombinedScripts_=%3b%3bSystem.Web.Extensions%2c+Version%3d3.5.0.0%2c+Culture%3dneutral%2c+PublicKeyToken%3d31bf3856ad364e35%3aen-US%3afec40ae8-2c1f-4db6-96ca-d6c61af2dc7f%3aea597d4b%3ab25378d2%3bTelerik.Web.UI%2c+Version%3d2010.3.1109.20%2c+Culture%3dneutral%2c+PublicKeyToken%3d121fae78165ba3d4%3aen-US%3a0b207b76-976c-4925-ba92-57c3001b0b77%3a16e4e7cd%3af7645509%3a24ee1bba%3ae330518b%3a1e771326%3a8e6f0d33%3a6a6d718d" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
if (typeof(Sys) === 'undefined') throw new Error('ASP.NET Ajax client-side framework failed to load.');
//]]>
</script>
<script type="text/javascript">
//<![CDATA[
Sys.WebForms.PageRequestManager._initialize('ctl00$RadScriptManager1', document.getElementById('aspnetForm'));
Sys.WebForms.PageRequestManager.getInstance()._updateControls([], [], [], 90);
//]]>
</script>
<div id="HeaderBar">
<div id="ctl00_Header1_Phlogo" class="Phlogo">
<img id="ctl00_Header1_imgLogo" src="http://crossfiremedia.realpage.com/palisadesatjaguarcity/logos/lg1029_h50.png" alt="Logo" style="border-width:0px;" />
</div>
</div>
<div id="HdrNav">
<a id="ctl00_Header1_hlApartmentSearch" class="item" href="Default.aspx">Property website</a>
<a id="ctl00_Header1_hlResidentLogin" class="item" href="https://property.onesite.realpage.com/mobile/login.aspx?w=palisadesatjaguarcity">Resident Login</a>
</div>
<div class="hdrGrad">
</div>
<div id="content">
<script type="text/javascript">
function showdetails() {
if (document.getElementById) {
var elemlbl = document.getElementById('divButton');
if (elemlbl.className == 'Hide') {
ColapseDetails();
}
else if (elemlbl.className == 'Show') {
ExpandDetails();
}
}
}
</script>
<ul class="pageitem">
<li class="PropInfo Details">
<span id="ctl00_cphContent_PropDetailHeader_lblPropName" class="hdrBlue" style="font-size:12pt;font-weight:bold;">The Palisades at Jaguar City</span>
</li>
<li class="Details">
<div style="float: left;">
<span id="ctl00_cphContent_PropDetailHeader_lblPhone" class="hdrGreen" style="font-size:12pt;font-weight:bold;">(866) 936-5544 (Phone)</span>
</div>
</li>
</ul>
<!--Not visible:Start-->
<ul class="pageitem">
<li class="Details">
</li>
<li class="Details">
<div class="SeparateSR"/>
</li>
<li class="Details">
<div class="BoldText TxtAccent1">
<span id="ctl00_cphContent_lblModel"></span>
</div>
</li>
<li class="Details">
</li>
<li class="paddedBox"><span class="BoldText">Bedrooms:
<span id="ctl00_cphContent_lblBeds">1</span></span><br />
<span class="BoldText">Bathrooms:
<span id="ctl00_cphContent_lblBaths">1</span></span>
<br />
<span class="BoldText">Sq/Ft: </span>
<span id="ctl00_cphContent_lblSqft">544</span>
<br />
<span class="BoldText">Price: </span>
<span id="ctl00_cphContent_lblRent">$779 - $779</span><br />
<span class="BoldText">Deposit: </span>
<span id="ctl00_cphContent_lblDeposit">$150</span><br />
</li>
<li class="Details">
<div id="ctl00_cphContent_tsFloorplans" class="RadTabStrip RadTabStrip_Default RadTabStripTop_Default">
<!-- 2010.3.1109.20 --><div class="rtsLevel rtsLevel1">
<ul class="rtsUL"><li class="rtsLI rtsFirst"><a class="rtsLink rtsBefore" href="#"><span class="rtsOut"><span class="rtsIn"><span class="rtsTxt">Amenities</span></span></span></a></li><li class="rtsLI rtsLast"><a class="rtsLink rtsSelected" href="#"><span class="rtsOut"><span class="rtsIn"><span class="rtsTxt">2D View</span></span></span></a></li></ul>
</div><input id="ctl00_cphContent_tsFloorplans_ClientState" name="ctl00_cphContent_tsFloorplans_ClientState" type="hidden" />
</div>
</li>
<li class="Details" style="margin-top: -1px;">
<div id="ctl00_cphContent_mpvFloorplans" style="border-color:#848284;border-width:1px;border-style:Solid;">
<div id="ctl00_cphContent_pvAmenities" class="rmpHiddenView">
<div class="paddedBox itemList">
<span class="TxtAccent2 BoldText ">Features</span>
<ul> <li><span> Private Bedrooms </span></li> <li><span> Fully-equipped Kitchen with Breakfast Bar </span></li> <li><span> Full-Sized Washer / Dryer </span></li> <li><span> Spacious Living Room </span></li> <li><span> High Speed Internet Connections in Each Bedroom </span></li> </ul>
</div>
</div><div id="ctl00_cphContent_pv2d">
<img id="ctl00_cphContent_img2DFP" src="http://crossfiremedia.realpage.com/palisadesatjaguarcity/floorplans/fp1014_w240.jpg" alt="2D Floorplan" style="border-width:0px;" />
</div><input id="ctl00_cphContent_mpvFloorplans_ClientState" name="ctl00_cphContent_mpvFloorplans_ClientState" type="hidden" />
</div>
</li>
</ul>
<!--Not visible:End-->
</div>
<ul id="ctl00_ctl06_ulFooterList" class="pageitem PropFooter">
<li class="Details"><a href="/(S(dpggqf452ctwmt45nycnfnah))/FloorPlans.aspx">Floor Plans</a></li>
<li class="Details"><a href="/(S(dpggqf452ctwmt45nycnfnah))/Default.aspx">About our Community</a></li>
<li class="Details"><a href="/(S(dpggqf452ctwmt45nycnfnah))/ContactUs.aspx">Contact Us</a></li>
<li class="Details"><a href="/(S(dpggqf452ctwmt45nycnfnah))/PhotoGallery.aspx">Photos & Videos</a></li>
<li class="Details"><a href="/(S(dpggqf452ctwmt45nycnfnah))/Amenities.aspx">Amenities & Pet Policies</a></li>
<li id="ctl00_ctl06_listNeighbor" class="Details"><a href="/(S(dpggqf452ctwmt45nycnfnah))/Neighborhood.aspx">Local Businesses</a></li>
</ul>
<div id="footer">
<div class="ftrGrad">
</div>
<div id="FtrNav">
<span class="item" style=" padding-top: 0;padding-right:0;">
<img id="ctl00_Footer1_imgDisability" src="images/disa_btn.png" alt="Handicap Accessible" style="border-width:0px;" />
<img id="ctl00_Footer1_imgEHO" src="images/eoh_btn.png" alt="Equal Housing Oportunity" style="border-width:0px;" /></span>
<div class="item ">
<span>©
2011
RealPage </span>
</div>
</div>
</div>
<script type="text/javascript">
//<![CDATA[
Sys.Application.initialize();
Sys.Application.add_init(function() {
$create(Telerik.Web.UI.RadTabStrip, {"_selectedIndex":1,"_skin":"Default","clientStateFieldID":"ctl00_cphContent_tsFloorplans_ClientState","multiPageID":"ctl00_cphContent_mpvFloorplans","selectedIndexes":["1"],"tabData":[{"pageViewID":"ctl00_cphContent_pvAmenities"},{"pageViewID":"ctl00_cphContent_pv2d"}]}, null, null, $get("ctl00_cphContent_tsFloorplans"));
});
Sys.Application.add_init(function() {
$create(Telerik.Web.UI.RadMultiPage, {"clientStateFieldID":"ctl00_cphContent_mpvFloorplans_ClientState","pageViewData":[{"id":"ctl00_cphContent_pvAmenities"},{"id":"ctl00_cphContent_pv2d"}],"selectedIndex":1}, null, null, $get("ctl00_cphContent_mpvFloorplans"));
});
//]]>
</script>
</form>
</body>
</html>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578383",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Get Current Google Map How do I get the current Google Map that is already initialized on the page with the Javascript V3 api, so I can reset a marker?
A: declare the map object in javascript as global then you get the anywhere in javascript
A: If you have a marker and you want to reference the map that it relates to you can simply call getMap() on the marker.
var myMap = myMarker.getMap();
When called from an object it returns the map on which the object is rendered/displayed.
This is true for most objects in the google.maps namespace (Marker, Polyline, Rectangle, etc).
If you take a look through the reference page you can see which objects getMap() is an available method for.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578385",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Problem in getting the Latitude and Longitude value using gps at different location I used the following code to find the longitude and latitude for my android application
public double[] getlocation() {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
List<String> providers = lm.getProviders(true);
Location l = null;
for (int i = 0; i < providers.size(); i++) {
l = lm.getLastKnownLocation(providers.get(i));
if (l != null)
break;
}
double[] gps = new double[2];
if (l != null) {
gps[0] = l.getLatitude();
gps[1] = l.getLongitude();
}
return gps;
}
I got the accurate or exact latitude and longitude first time when i run the application after i tried to get the new co-ordinates from one miles away from my first location but i got the same latitude and longitude.
so please can you suggest me how this problem occurs. what is the solution for this ?
A: .getLastKnownLocation() will be inaccurate. You need to use a LocationListener to get accurate and up to date location updates. See this link. You generally ONLY want to use getLastKnownLocation ONCE upon starting to get a quick fix, then register a LocationListener to get more accurate, constant updates.
Also be aware that sitting in your house attempting to test will not work very well. You might need to go outside and walk around some.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578388",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Changing theme calls UserControl_Loaded event I am not getting why behavior of WPF user control and Windows forms user control is different . I added window loaded event which just shows message box as :
private void Window_Loaded(object sender, RoutedEventArgs e)
{
MessageBox.Show("Main Window Loaded","WPF");
}
Also I created one user control and added loaded event as :
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
MessageBox.Show("User Control Loaded.","WPF");
}
I have put this user control in main window.
When i launch this , I get both message box, User controls as well as windows.
Now , When i change my theme from Aero to any High contrast then user control's message box is shown again.
Why this is happening ? Why this is different from Windows form ? What should I do to avoid showing it multiple times ?
Wajeed
A: You could have a boolean field which stores the state of whether the dialog was shown yet or not. If you change the theme the UI-elements will reload so naturally the event will fire again.
if (!_diagWasShown)
{
_diagWasShown = true;
//Show dialogue
}
A: you can create bool variable, which will indicate if MessageBox was shown.
bool isUserMessageBoxShown = false;
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
if (!isUserMessageBoxShown)
{
MessageBox.Show("User Control Loaded.","WPF");
isUserMessageBoxShown = true;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578397",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to avoid overusing design patterns? I know that design patterns are time tested solution to a particular type of software problems.
But how would I know that I am overusing a design pattern?
How much is too much ?
What things should I keep in mind while using design patterns to avoid overusing?
A: The only possible way I can think of is to get a real grip on the design pattern before you even think of using it.Before using the design pattern you must know what exactly it is meant for? What may be the advantages/ disadvantages of using it ? Start with your own idea and see if the design patterns fits along the way. You can even make slight modifications in the pattern if it makes your code better.If you are a beginner just don't worry to make some mistakes because it is the way we all learn.
Design patterns are really great but can make your code unnecessarily complex and bulky if not used wisely.
Hope this helps.
A: I would give you some analogy. Every pattern has a certain boundaries it enforces on your software architecture. You can think of geometrical shape. One pattern adds a triangular shape to your pattern, other more square-like, the third one might be a hexagon. it makes no sense to try inscirbe a square inside a line but it makes more sense to inscribe it inside some hexagon but the ideal way is to inscribe it only into squares.
I totally aggree with @EMM. The understanding of these boundaries comes with studying what it is meant for, advantages/disadvantages of it, etc. But you should never NEVER force an unsuitable pattern onto your software because it is like forcing an ellipse inside a square or even worse. Pattern should be added only if it is real natural place.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578399",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Adding menu in wordpress but it should not be a page I have used add_menu_page() which adds a menu and also creates a submenu with that name.
The syntax is:
add_menu_page($pagetitle,$menutitle,$capability,$menu_slug,$function,$icon-url,$position);
For example:
add_menu_page('ABCD','ABCD','read','r121_abcd','callMe','','4');
This creates a menu in my administration screen but it also creates a submenu with same name ABCD.
I don't want that name for my submenu I want it as PQRST or I don't want any page associated with that menu. And then I can add pages using add_submenu_page().
So there should be ABCD(Menu) -> PQRST(submenu). No ABCD(menu) -> ABCD(submenu).
I am not able to figure out that .
A: Try using:
add_menu_page('','ABCD','read','ABCD_slug','','','4');
add_submenu_page('ABCD_slug','PQRST','PQRST','read','ABCD_slug',array($this,'myFunction'));
remove_submenu_page('ABCD_slug', 'ABCD_slug');
worked for me.
A: //Format - > add_menu_page($pagetitle,$menutitle,$capability,$menu_slug,$function,$icon-url,$position);
add_menu_page('','ABCD','read','ABCD_slug','','','4');
//Format - >
add_submenu_page($parent_slug,$page_title,$menu_title,$capability,$menu_slug,$function);
add_submenu_page('ABCD_slug','PQRST','PQRST','read','ABCD_slug',array($this,'myFunction'));
This does the thing, i.e. giving the same menu_slug.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578400",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: NSTimezone how to set CST to nsdateformater all
I'm new to ios programming.
I want to set CST in the method
[dateFormatter setTimeZone:]
I have created a sample project to get all known timezones
Code is here:
NSArray *timeZoneNames = [NSTimeZone knownTimeZoneNames];
for (NSTimeZone *timezon in timeZoneNames) {
NSLog(@"%@",timezon);
}
It gives the following result:
[Session started at 2011-09-28 09:50:28 +0530.]
2011-09-28 09:50:29.535 Timezonetest[10352:207] Africa/Abidjan
2011-09-28 09:50:29.537 Timezonetest[10352:207] Africa/Accra
2011-09-28 09:50:29.537 Timezonetest[10352:207] Africa/Addis_Ababa
2011-09-28 09:50:29.538 Timezonetest[10352:207] Africa/Algiers
........................
........................
........................
........................
2011-09-28 09:50:29.765 Timezonetest[10352:207] Pacific/Pago_Pago
2011-09-28 09:50:29.766 Timezonetest[10352:207] Pacific/Palau
2011-09-28 09:50:29.766 Timezonetest[10352:207] Pacific/Pitcairn
2011-09-28 09:50:29.767 Timezonetest[10352:207] Pacific/Pohnpei
2011-09-28 09:50:29.768 Timezonetest[10352:207] Pacific/Ponape
2011-09-28 09:50:29.769 Timezonetest[10352:207] Pacific/Port_Moresby
2011-09-28 09:50:29.773 Timezonetest[10352:207] Pacific/Rarotonga
2011-09-28 09:50:29.775 Timezonetest[10352:207] Pacific/Saipan
2011-09-28 09:50:29.775 Timezonetest[10352:207] Pacific/Tahiti
2011-09-28 09:50:29.776 Timezonetest[10352:207] Pacific/Tarawa
2011-09-28 09:50:29.776 Timezonetest[10352:207] Pacific/Tongatapu
2011-09-28 09:50:29.777 Timezonetest[10352:207] Pacific/Truk
2011-09-28 09:50:29.778 Timezonetest[10352:207] Pacific/Wake
2011-09-28 09:50:29.778 Timezonetest[10352:207] Pacific/Wallis
Anyone can say which is the name for CST(central Standard timezone) in the above list
Thanks in Advance
A: try this by first method u got all time zone after that wat u want u set by key value.
NSLog(@"%@",[NSTimeZone abbreviationDictionary]);
[dateFormater setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"CST"]];
A: Just use the following code,
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"CST"]];
A: Try this:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss";
NSTimeZone *cst = [NSTimeZone timeZoneWithAbbreviation:@"GMT-06:00"];
[dateFormatter setTimeZone:cst];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578404",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: rack-cache not found in any of the sources error I'm new to creating a rails application. I'm going through this tutorial, and running into the issue when launching rails server. When I execute the commands (rails server or bundle exec rails server) I get the following error:
←[31mCould not find rack-cache-1.0.3 in any of the sources←[0m
←[33mRun `bundle install` to install missing gems.←[0m
I'm not sure why this is happening, because rack-cache is installed. I've already run bundle install, but that doesn't fix anything.
This is my gemfile
source 'http://rubygems.org'
gem 'rails', '3.1.0'
# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'
gem 'sqlite3'
gem 'json'
# Gems used only for assets and not required
# in production environments by default.
group :assets do
gem 'sass-rails', " ~> 3.1.0"
gem 'coffee-rails', "~> 3.1.0"
gem 'uglifier'
end
gem 'jquery-rails'
# Use unicorn as the web server
# gem 'unicorn'
# Deploy with Capistrano
# gem 'capistrano'
# To use debugger
# gem 'ruby-debug'
my gem list is:
abstract (1.0.0)
actionmailer (3.1.0, 3.0.0)
actionpack (3.1.0, 3.0.0)
activemodel (3.1.0, 3.0.0)
activerecord (3.1.0, 3.0.0)
activeresource (3.1.0, 3.0.0)
activesupport (3.1.0, 3.0.9, 3.0.0)
arel (2.2.1, 1.0.1)
bcrypt-ruby (3.0.1 x86-mingw32)
builder (3.0.0, 2.1.2)
bundler (1.0.18)
childprocess (0.2.2)
coffee-rails (3.1.1)
coffee-script (2.2.0)
coffee-script-source (1.1.2)
commonwatir (2.0.2, 1.9.2)
diff-lcs (1.1.2)
erubis (2.7.0, 2.6.6)
execjs (1.2.9)
ffi (1.0.9 x86-mingw32)
firewatir (1.9.4, 1.9.2)
hike (1.2.1)
hoe (2.10.0)
i18n (0.6.0, 0.4.2)
jquery-rails (1.0.14)
mail (2.3.0, 2.2.19)
metaclass (0.0.1)
mime-types (1.16)
mocha (0.9.12)
multi_json (1.0.3)
nokogiri (1.5.0 x86-mingw32)
polyglot (0.3.2)
rack (1.3.3, 1.2.4)
rack-cache (1.1)
rack-mount (0.8.3, 0.6.14)
rack-ssl (1.3.2)
rack-test (0.6.1, 0.5.7)
rails (3.1.0, 3.0.0)
railties (3.1.0, 3.0.0)
rake (0.9.2)
rautomation (0.6.3)
rdoc (3.9.4)
rspec (2.6.0)
rspec-core (2.6.4)
rspec-expectations (2.6.0)
rspec-mocks (2.6.0)
rubigen (1.5.6)
rubyzip (0.9.4)
s4t-utils (1.0.4)
sass (3.1.7)
sass-rails (3.1.2)
selenium-webdriver (2.6.0)
sprockets (2.0.0)
sqlite3 (1.3.4 x86-mingw32)
taglob (1.1.2)
taza (0.8.7)
term-ansicolor (1.0.6)
thor (0.14.6)
treetop (1.4.10)
tzinfo (0.3.29)
uglifier (1.0.3)
user-choices (1.1.6.1)
watir (2.0.2, 1.9.2)
watir-webdriver (0.3.3)
win32-api (1.4.8 x86-mingw32)
win32-process (0.6.5)
win32console (1.3.0 x86-mingw32)
windows-api (0.4.0)
windows-pr (1.2.0)
xml-simple (1.1.0)
A: Make sure you are not getting any of these:
Invalid gemspec in [/var/lib/gems/1.8/specifications/rack-cache-1.0.3.gemspec]: invalid date format in specification: "2011-08-27 00:00:00.000000000Z"
If so, edit the gemspec file and change the dates to "2011-08-27" removing 00:00:00.000000000Z
This is the same for any of the gems, not just rack-cache.
A: It looks like rack-cache 1.1 is being loaded but Rails is looking for 1.0.3. Since your Gemfile.lock list lost its indentation it's not clear which gem is requiring it but you might try putting gem 'rack-cache', '1.0.3' or gem 'rack-cache', '~> 1.0.3' at the top of your Gemfile (after gem 'rails').
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578405",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do i remove multiple array elements in PHP? I have an array
$rules = array(
'name' => array(
'isRequired' => array(
'message' => 'Name Required'
),
'isBetween' => array(
'value' => array(5,15),
'message' => 'Between 5 to 15 characters'
),
'isAlphaLower' => array(
'message' => 'Should be Alpha lower'
),
'isLength' => array(
'value' => 20,
'message' => 'Length should be 20 chracters'
)
),
'email' => array(
'isEmail' => array(
'message' => 'Email should be valid'
),
'isRequired' => array(
'message' => 'Email Required'
),
),
'pPhone' => array(
'isNumber' => array(
'message' => 'Only Numbers'
)
)
);
I need to remove all array element with key name message. how do i do that?
thank you..
A: Nested foreach, by reference.
foreach( $rules as $field => &$fieldrules ) {
foreach( $fieldrules as $rulename => &$rulesettings ) {
unset( $rulesettings['message'] );
}
}
A: If you are tring to remove all key/value pairs where the key is 'message' three levels deep, you could try the following:
foreach ($rules as $k1 => $arr) {
foreach ($arr as $k2 => $arr2) {
foreach ($arr2 as $k3 => $arr3) {
if ($k3 == 'message') {
unset($rules[$k1][$k2][$k3]);
}
}
}
}
A: Use unset() within a nested foreach loop:
foreach($rules as &$fieldrules)
foreach($fieldrules as &$ruleparams)
if(isset($ruleparams['message'])) // E_STRICT
unset($ruleparams['message']);
Note the & before the variables. This is a pass by reference. It's important to do so here so that we modify the actual array and not a copy.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578414",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Analysing C# source with Irony This is what my team and I chose to do for our school project. Well, actually we haven't decided on how to parse the C# source files yet.
What we are aiming to achieve is, perform a full analysis on a C# source file, and produce up a report.
In which the report is going to contain stuff that happening in the codes.
The report only has to contain:
*
*string literals
*method names
*variable names
*field names
*etc
I'm in charge of looking into this Irony library. To be honest, I don't know the best way to sort the data out into a clean readable report. I am using the C# grammar class packed with the zip.
Is there any step where I can properly identify each node children? (eg: using directives, namespace declaration, class declaration etc, method body)
Any help or advice would be very much appreciated. Thanks.
EDIT: Sorry I forgot to say we need to analysis the method calls too.
A: I'm not sure this is what you need but you could use the CodeDom and CodeDom.Compiler namespaces to compile the C# code, and than analyze the results using Reflection, something like:
// Create assamblly in Memory
CodeSnippetCompileUnit code = new CodeSnippetCompileUnit(classCode);
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerResults results = provider.CompileAssemblyFromDom(compileParams, code);
foreach(var type in results.CompiledAssembly)
{
// Your analysis go here
}
Update: In VS2015 you could use the new C# compiler (AKA Roslyn) to do the same, for example:
var root = (CompilationUnitSyntax)tree.GetRoot();
var compilation = CSharpCompilation.Create("HelloTDN")
.AddReferences(references: new[] { MetadataReference.CreateFromAssembly(typeof(object).Assembly) })
.AddSyntaxTrees(tree);
var model = compilation.GetSemanticModel(tree);
var nameInfo = model.GetSymbolInfo(root.Usings[0].Name);
var systemSymbol = (INamespaceSymbol)nameInfo.Symbol;
foreach (var ns in systemSymbol.GetNamespaceMembers())
{
Console.WriteLine(ns.Name);
}
A: Your main goal is to master the basics of formal languages. A good start-up might be found here. This article describes the way to use Irony on the sample of a grammar of a simple numeric calculator.
Suppose you want to parse a certain file containing C# code the path to which you know:
private void ParseForLongMethods(string path)
{
_parser = new Parser(new CSharpGrammar());
if (_parser == null || !_parser.Language.CanParse()) return;
_parseTree = null;
GC.Collect(); //to avoid disruption of perf times with occasional collections
_parser.Context.SetOption(ParseOptions.TraceParser, true);
try
{
string contents = File.ReadAllText(path);
_parser.Parse(contents);//, "<source>");
}
catch (Exception ex)
{
}
finally
{
_parseTree = _parser.Context.CurrentParseTree;
TraverseParseTree();
}
}
And here is the traversal method itself with counting some info in the nodes. Actually this code counts the number of statements in every method of the class. If you have any question you are always welcome to ask me
private void TraverseParseTree()
{
if (_parseTree == null) return;
ParseNodeRec(_parseTree.Root);
}
private void ParseNodeRec(ParseTreeNode node)
{
if (node == null) return;
string functionName = "";
if (node.ToString().CompareTo("class_declaration") == 0)
{
ParseTreeNode tmpNode = node.ChildNodes[2];
currentClass = tmpNode.AstNode.ToString();
}
if (node.ToString().CompareTo("method_declaration") == 0)
{
foreach (var child in node.ChildNodes)
{
if (child.ToString().CompareTo("qual_name_with_targs") == 0)
{
ParseTreeNode tmpNode = child.ChildNodes[0];
while (tmpNode.ChildNodes.Count != 0)
{ tmpNode = tmpNode.ChildNodes[0]; }
functionName = tmpNode.AstNode.ToString();
}
if (child.ToString().CompareTo("method_body") == 0) //method_declaration
{
int statementsCount = FindStatements(child);
//Register bad smell
if (statementsCount>(((LongMethodsOptions)this.Options).MaxMethodLength))
{
//function.StartPoint.Line
int functionLine = GetLine(functionName);
foundSmells.Add(new BadSmellRegistry(name, functionLine,currentFile,currentProject,currentSolution,false));
}
}
}
}
foreach (var child in node.ChildNodes)
{ ParseNodeRec(child); }
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578419",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: JSTL continue, break inside foreach I want to insert "continue" inside foreach in JSTL. Please let me know if there is a way to achieve this.
<c:forEach
var="List"
items="${requestScope.DetailList}"
varStatus="counter"
begin="0">
<c:if test="${List.someType == 'aaa' || 'AAA'}">
<<<continue>>>
</c:if>
I want to insert the "continue" inside the if condition.
A: Or you can use EL choose statement
<c:forEach
var="List"
items="${requestScope.DetailList}"
varStatus="counter"
begin="0">
<c:choose>
<c:when test="${List.someType == 'aaa' || 'AAA'}">
<!-- continue -->
</c:when>
<c:otherwise>
Do something...
</c:otherwise>
</c:choose>
</c:forEach>
A: I solved it using Set at the end of my executable code and inside of the loop
<c:set var="continueExecuting" scope="request" value="false"/>
then I used that variable to skip the execution of the code in the next iteration using
<c:if test="${continueExecuting}">
you can set it back to true at any time...
<c:set var="continueExecuting" scope="request" value="true"/>
more on this tag at: JSTL Core Tag
enjoy!
A: There's no such thing. Just do the inverse for the content you actually want to display. So don't do
<c:forEach items="${requestScope.DetailList}" var="list">
<c:if test="${list.someType eq 'aaa' or list.someType eq 'AAA'}">
<<<continue>>>
</c:if>
<p>someType is not aaa or AAA</p>
</c:forEach>
but rather do
<c:forEach items="${requestScope.DetailList}" var="list">
<c:if test="${not (list.someType eq 'aaa' or list.someType eq 'AAA')}">
<p>someType is not aaa or AAA</p>
</c:if>
</c:forEach>
or
<c:forEach items="${requestScope.DetailList}" var="list">
<c:if test="${list.someType ne 'aaa' and list.someType ne 'AAA'}">
<p>someType is not aaa or AAA</p>
</c:if>
</c:forEach>
Please note that I fixed an EL syntax error in your code as well.
A: I like this idea of having the variable on the foreach, and setting it to the end of the loop to exit with a c:set ... if you structure a begin and an end for loop.
https://www.codesenior.com/en/tutorial/How-To-Break-Foreach-Loop-in-JSP
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578420",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
}
|
Q: Move Minute hand in Android clock I am trying to write a simple proof of concept app that allows a user to rotate minute hand of a clock. I am having hard time coming up with the right logic for OnTouchEvent.
So far I have the following code:
public boolean onTouchEvent(MotionEvent e) {
float x = e.getX();
float y = e.getY();
switch (e.getAction()) {
case MotionEvent.ACTION_MOVE:
//find an approximate angle between them.
float dx = x-cx;
float dy = y-cy;
double a=Math.atan2(dy,dx);
this.degree = Math.toDegrees(a);
this.invalidate();
}
return true;
}
protected void onDraw(Canvas canvas) {
super .onDraw(canvas);
boolean changed = mChanged;
if (changed) {
mChanged = false;
}
int availableWidth = getRight() - getLeft();
int availableHeight = getBottom() - getTop();
int x = availableWidth / 2;
int y = availableHeight / 2;
cx = x;
cy = y;
final Drawable dial = mDial;
int w = dial.getIntrinsicWidth() + 100;
int h = dial.getIntrinsicHeight() + 100;
boolean scaled = false;
if (availableWidth < w || availableHeight < h) {
scaled = true;
float scale = Math.min((float) availableWidth / (float) w, (float) availableHeight / (float) h);
canvas.save();
canvas.scale(scale, scale, x, y);
}
if (changed)
{
dial.setBounds(x - (w / 2), y - (h / 2), x + (w / 2), y + (h / 2));
}
dial.draw(canvas);
canvas.save();
float hour = mHour / 12.0f * 360.0f;
canvas.rotate(hour, x, y);
final Drawable hourHand = mHourHand;
if (changed) {
w = hourHand.getIntrinsicWidth() + 30;
h = hourHand.getIntrinsicHeight() + 30;
hourHand.setBounds(x - (w / 2), y - (h / 2), x + (w / 2), y + (h / 2));
}
hourHand.draw(canvas);
canvas.restore();
canvas.save();
float minute = mMinutes / 60.0f * 360.0f;
if (bearing == 0)
{
canvas.rotate(minute, x, y);
}
else
{
canvas.rotate((float)bearing, x, y);
}
final Drawable minuteHand = mMinuteHand;
if (changed) {
w = minuteHand.getIntrinsicWidth() + 30;
h = minuteHand.getIntrinsicHeight() + 30;
minuteHand.setBounds(x - w, y - h, x + w, y + h);
}
minuteHand.draw(canvas);
canvas.restore();
if (scaled) {
canvas.restore();
}
}
Then based on that, my OnDraw method rotates the minute hand to the specified "this.degree"(just calls canvas.rotate). I am assuming my math is off here. I tried to follow the example here: Calculate angle for rotation in Pie Chart, but that's still not rotating the minute hand correctly. Any help would be appreciated.
A: The math looks correct. Your calculations should give you the angle of the touch event, where a touch that is to the exact right of the center point should give you 0 degrees.
A few things to watch out for
*
*Make sure that you're rotating in the correct direction. It is hard to keep this straight, and thus easy to screw it up
*Make sure that you're taking into account that a value of 0 means that the minute hand should be pointing to the right. For example, if you start out with a minute hand that is pointing upwards, you would have to add/subtract 90 degrees to the result of your calculation (depending on the direction of rotation - not sure which is correct offhand)
*Make sure that (cx, cy) is the center point around which you want to calculate the angle
*When rotating, you'll need to either use the 3 arg Canvas.rotate(float, float, float) method, or add an additional translation seperately, to make sure that you are rotating around the correct point. Without any translation, it will rotate around (0,0) (the top left corner of the view)
More on rotation:
Rotation always happens around the "current" (0,0) point. By "current", I mean the (0,0) point after the current matrix has been applied. When you first enter onDraw, the (0,0) point should be the upper-left corner of the view. Whenever you apply a translation/scaling/etc, you will potentially change where the (0,0) point is, relative to the view.
I think something like the following should work, in regards to setting the correct center of rotation:
//first we save the initial matrix, so we can easily get
//back to this state after we're done rotating
canvas.save();
//I *think* you need to negate the center offsets here,
//because you are conceptually moving the canvas, rather
//than moving the center directly
canvas.translate(-cx, -cy);
//<perform the rotation and draw the clock hand>
//...
//and now restore the matrix back to the initial state
canvas.restore();
A:
Your calculation is good for measuring angle for minutes hand to
rotate in corresponding quadrants in analog clock... here with little
bit changes can make either minutes or hours hand to rotate at the
touch position....call the below method in onTouch() method for action move
public float getRotationAngle(float x, float y) {
float dx = x - cx;
float dy = y - cy;
double a = Math.atan2(dy, dx);
double degree = Math.toDegrees(a)+90;
if(angle<0){
degree=degree+360;
}
return (float) degree;
}
i have this approach with as vectors concept for calculating the angle but if little bit more than your code if u want i will give that logic....
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578422",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Manage source and javadoc for Grails automatic dependencies in IntelliJ IDEA? How do I attach source and javadoc to libraries in IntelliJ IDEA that are linked automatically by Grails dependency resolution and are not explicitly listed in the IDEA project settings?
For example in
BuildConfig.groovy:
grails.project.dependency.resolution = {
repositories {
mavenRepo "http://oss.sonatype.org/content/repositories/releases/"
}
dependencies {
runtime 'org.elasticsearch:elasticsearch:0.17.7'
}
}
Is there a method to have IDEA automatically pick up the source and javadoc from the Maven repository?
A: IDEA attached the source automatically to the project plugin module. The JavaDoc can be manually attached to the plugin module in the project structure interface at:
File -> Project Structure -> Project Settings -> Modules -> project name-grailsPlugins -> Paths -> JavaDoc
A: not an answer, but an idea:
you might hook into the 'grails integrate-with' gant script and add this functionality yourself. $GRAILS_HOME/scripts/IntegrateWith.groovy uses some templates for .ipr and .iml file that could be modified.
At some point in future it is excepted that gradle will be used for building Grails projects but there's still a long way to go.
A: IDEA 11 will be ably to search and download sources for any jar.
The search is performed using https://oss.sonatype.org/ by artifactId and version got from name of jar.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578423",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Aligning sub-heading "just right" beneath the Heading I'm very confused about how things like this should be done. I am able to layout a whole site with html and css, but when it comes to things like this, I begin to doubt whether i'm doing it the right way or not.
Can somebody please help me? I am trying to have a H1 and a H3 (or H2) laid out (as shown below) somewhere inside a div that is 25% wide?
Any help is much appreciated, and thank you!
http://tinypic.com/r/2wd5bfl/7
P.S.
I was kinda thinking something like this?:
<div class="yipeee">
<h1 style="float:left; position:absolute; top:2; left:2;">This is a pretty awesome heading</h1>
<h3 style="float:right; position:absolute; bottom:2; right:2;"><i>if only it were better than this sub-heading...</i></h3>
</div>
A: Not sure if this is what you're asking for, but here's a solution for the given example:
<h1 id="heading">This is a pretty awesome heading</h1>
<h2 id="subheading">If only it were better than this subheading</h2>
<style type="text/css">
h1#heading { font-size: 36px; font-weight: bold; }
h2#subheading {
margin-left: 25%;
font-style: italic;
}
</style>
See the jsFiddle example at http://jsfiddle.net/fausak/WmuRf/
A: Here you go, this is almost exactly the same as the picture:
Here is the example: http://jsfiddle.net/MarkKramer/WmuRf/2/
I used your jsfiddle and edited it and now it is almost exactly like the picture (just the font has to be changed)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578432",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to create mapping file dynamically in hibernate? I have situation where table is created dynamically,i don't know the table name it comes dynamically so i want to know that how can i am able to create mapping file(.cfg.xml) dynamically,it is possible or not?
Thanks
A: Yes, it's possible.
I do something like that:
String xml = generate(data, dialect);
Configuration configuration = new Configuration();
configuration.addXML(xml);
public static String generate(Data pData, Dialect pDialect) {
StringBuilder sb = new StringBuilder();
sb.append("<?xml version='1.0' encoding='UTF-8'?>");
sb.append("<!DOCTYPE hibernate-mapping PUBLIC '-//Hibernate/Hibernate Mapping DTD//EN' "
+ "'http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd'>");
sb.append("<hibernate-mapping>");
sb.append(String.format("<class name='dummy' table='%s'>", pData.getTable()));
final IMyColumn primaryKeyColumn = pData.getPrimaryKey().get(0);
sb.append(addItem(pData, primaryKeyColumn, "id", pDialect));
for (IMyColumn column : pData.getColumns()) {
if (!column.equals(primaryKeyColumn)) {
sb.append(addItem(column, PROPERTY, pDialect));
}
}
sb.append("</class>");
sb.append("</hibernate-mapping>");
final String xml = sb.toString();
//System.out.println(xml);
return xml;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578435",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Log-in control if username is not found the label text should answer username not found got a few question here. As you all know ive created a class wherein ill just instantiate it on my .aspx page.On my .aspx page ive got a logincontrol named login1. Now im getting error when user.UserName = Nothing and stop on this user.UserName = Nothing saying Object reference not set to an instance of an object..Could you help me debug the problem. All i want is that if the username is not on the database the lblmessage should say Error Username is invalid and if it is correct then it will check on the password. Please do help. Thanks and more power guys.
Aspx page
Protected Sub LoginButton_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim user As New User
Dim userDAL As New UserDAL
user = userDAL.SelectByUsername(Login1.UserName)
If user.UserName = Nothing Then
Login1.FailureText = "Invalid Username"
Else
If Login1.Password <> user.Password Then
Login1.FailureText = "Invalid password"
Else
Login1.FailureText = "success"
End If
End If
End Sub
UserDAL.vb
Public Function SelectByUsername(ByVal userName As String) As User
Try
'select * from User where Username = 'userName'
Dim sqlConn As New SqlConnection(_connString)
sqlConn.Open()
Dim sqlCmd As New SqlCommand("select * from [Users] where Username = '" & userName & "'", sqlConn)
Dim dr As SqlDataReader = sqlCmd.ExecuteReader()
'Create user collection
Dim user As User = Nothing
While dr.Read()
'Create User object
user = New User
user.UserName = dr("UserName").ToString
user.Password = dr("Password").ToString
user.FirstName = dr("FirstName").ToString
user.Surname = dr("Surname").ToString
End While
dr.Close()
Return user
Finally
If _sqlConn IsNot Nothing Then
If _sqlConn.State = Data.ConnectionState.Open Then
_sqlConn.Close()
End If
End If
End Try
Return Nothing
End Function
A: Instead of comparing with user.Username, first you compare with only user i.e.,
If user Is Nothing Then
Why Bcoz in your SelectByUsername function you are returning Nothing if it is invalid username. Try it and reply.
A: I would go with the simplest answer on this. Add a validation Summary to your control that returns the required value ("Username Not Valid") and then in your code to validate do a
if(Page.IsValid) (This is C# code but VB should be very close to this)
That should solve your problem.
Here's a quick snippet
<asp:TextBox id="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ErrorMessage="User Name Not Valid" ControlToValidate="TextBox1"></asp:RequiredFieldValidator>
Now of note this error message would display to the right of the text box, however you can style it or even set it to a validation group.
The required field validator or validation group with a validation summary forces client side validation with ASP.NET for postback so when the submit button fires it will run a test and determine if Page.IsValid == true or false;
http://msdn.microsoft.com/en-us/library/aa479013.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578441",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: google maps multi marker info window not working I'm using Google Maps API on my web page. I'm try to add multiple markers to the page with info windows. The markers get added ok, but the info windows all have the info for the last marker. any ideas?
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="http://testserver/se1/WebServices/ShelterWebService.asmx" />
</Services>
</asp:ScriptManager>
<asp:LinkButton ID="BtnHome" runat="server" onclick="BtnHome_Click">Home</asp:LinkButton>
<div id="map_canvas"></div>
<script type="text/javascript">
var geocoder;
var map;
var addresses;
function GetShelters() {
ShelterExpress.WebServices.ShelterWebService.GetShelters('', OnGetSheltersComplete);
}
function OnGetSheltersComplete(retValue) {
addresses = new Array();
for (x in retValue) {
addresses.push(retValue[x]["Address"]);
}
GenerateMap();
}
function GenerateMap() {
/* Create the geocoder */
geocoder = new google.maps.Geocoder();
/* Some initial data for the map */
mapOptions = {
zoom: 10
, center: new google.maps.LatLng(0, 0)
, mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
//var infowindow = new google.maps.InfoWindow();
var marker, i;
if (geocoder) {
for (var item in addresses){
geocoder.geocode({ 'address': addresses[item] }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
/* Position the map */
map.panTo(results[0].geometry.location);
/* Put a marker */
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: addresses[item]
});
var infowindow = new google.maps.InfoWindow({ content: addresses[item] });
infowindow.open(map, marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
}
});
}
}
}
$(document).ready(function() {
GetShelters();
});
A: I'm guessing that you've copied an object or an array. You'll need to provide more information on addresses[item]
In javascript, copying something like a string or a boolean gives an actual copy, but copying an object or an array only gives a reference.
var foo = [1, 2, 3];
var bar = foo;
bar[1] = 5;
alert(foo[1]);
// alerts 5
EDIT FOR NEW INFORMATION: If you have jQuery loaded, a quick way to clone JS objects is to use $.extend()
// Shallow copy
var newObject = jQuery.extend({}, oldObject);
// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);
for an array you could just use javascript's slice()
a = [1];
b = a.slice();
It will depend on what retValue[x]["Address"] IS and which libraries you have loaded.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578446",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Cannot find SenTestingKit when using Kiwi Xcode 4.0.2.
New project, include Tests.
Drag Kiwi folder in.
Cannot find SenTestCase, cannot find #import
Searched in the framework add list and didn't see it there, either. What am I missing?
A: Had the targets set wrong. SenTesting is only available to the test target.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578448",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Java RMI between 2 PCs I've successfully implemented the single server-client example here on two different physical machines. I would like to try out this scenario between 2 or more machines :
*
*Machine A sends parameters of operation to be performed on machine B to machine B.
*Machine B executes it and returns status of operation to machine A.
Do I proceed by:
*
*Implement identical copies of my initial program on both machines?
*How does Machine A know that it has to send the request to machine B and not to other machines? B knows A's IP. But I'm concerned about how it sends the request to B only.
*Right now, I'm not concerned about any race condition between the 'clients' while they return status.
Any code/online tutorial would be of great help.
A:
Implement identical copies of my initial program on both machines?
No, you need a client program and a server program.
How does Machine A know that it has to send the request to machine
B and not to other machines?
Because you tell it. You have to tell the client (A) where the server B is.
B knows A's IP.
B doesn't need to know A's IP. It will get that when A connects, not that it needs it at all: all it needs is the connection, to write the response to. It is A that needs to know B's IP.
But I'm concerned about how it sends the request to B only.
Because you program it that way. I don't understand your concern.
Right now, I'm not concerned about any race condition between the
'clients' while they return status.
You really must sort out your terminology. Your 'clients' are really servers and vice versa.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578449",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to overcome this problem with using more listviews in a layout I'm using 4 listviews in my layout and if i use scrollview , i cannot scroll into my listview. If i remove scrollview in my xml, then the last list is been hiddden. How to overcome this problem?
My code goes below:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout android:id="@id/LinearLayout01" android:layout_width="fill_parent" android:layout_height="42.0dip">
<Button android:textSize="23.0dip" android:onClick="newtodo_Click" android:textStyle="bold" android:textColor="#ffffffff" android:gravity="center" android:id="@id/btnNewTodo" android:background="@drawable/new_todo" android:layout_width="fill_parent" android:layout_height="wrap_content" />
</LinearLayout>
<TextView android:textColor="#000000" android:layout_height="wrap_content" android:background="#FF0000" android:layout_width="match_parent" android:text="High Priority" android:id="@+id/textView1"></TextView>
<ListView android:id="@+id/lvhigh" android:cacheColorHint="#00000000" android:background="#000000" android:layout_width="match_parent" android:layout_height="175px"></ListView>
<TextView android:background="#ffff01" android:textColor="#000000" android:layout_height="wrap_content" android:layout_width="match_parent" android:text="Medium Priority" android:id="@+id/textView2"></TextView>
<ListView android:id="@+id/lvmed" android:layout_width="match_parent" android:layout_height="175px"></ListView>
<TextView android:background="#00ff01" android:textColor="#000000" android:layout_height="wrap_content" android:layout_width="match_parent" android:text="Low Priority" android:id="@+id/textView3"></TextView>
<ListView android:id="@+id/lvlow" android:layout_width="match_parent" android:layout_height="175px"></ListView>
<TextView android:background="#cccccc" android:textColor="#000000" android:layout_height="wrap_content" android:layout_width="match_parent" android:text="Incomplete Tasks" android:id="@+id/textView4"></TextView>
<ListView android:id="@+id/lvinc" android:layout_width="match_parent" android:layout_height="175px"></ListView>
</LinearLayout>
</ScrollView>
Any Help is really appreciated and thanks in advance...
A: In you layout there is textview and after that listview so why you not used expandable listVIew.It will help you in your problem.
Here is example of Expandable listview
Expandable Listview
Expandable Listview example
Click Here
Click Here
A: To overcome, try re-factoring your UI to not include multiple scrollable objects inside of another scrollable object. This will not be reliable and will produce unexpected results (as you have found).
As the100rabh said, this is generally bad design. Normally an application will present a list of some sort to a user. Four lists for a screen that is 2-5 (~10 for tablets) inches is three too many.
A: please set your listview as a non scrolling container By using
ls_edu.setScrollContainer(false);
it may help to scroll the list view.
A: An simple workaround is to
*
*Remove ScrollView
*Set height of all ListView to 0
*Set layout_weight property of all child to 1
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578450",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Cannot connect to Oracle Database 10g using a C++ CGI with httpd 2.2 I am writing a CGI program in C++. It is supposed to run on version 2.2 of the Apache HTTP Server and it needs to connect to Oracle Database 10g.
I tried to run this CGI program without httpd and it could connect to the Oracle database successfully, but once I ran it through the httpd server it wrote the following message in error_log.
Error while trying to retrieve text for error ORA-12546
How can I solve this problem?
A: That generally means that you have encountered an ORA-12546 error, but that your client library doesn't have the actual error messages installed. That's not a problem, you can search for the error numbers here. In your case, it's "TNS:Permission denied".
Does your CGI user have permission to access tnsnames.ora?
A: Just a guess, but a common cause for this type of thing is that the ORACLE_HOME environment is not set for your CGI program. Apache usually starts up at boot time ans so skips all the /etc/profile type stuff.
You will need to ensure both ORACLE_HOME is set, and depending on your system setup you may also need LD_LIBRARY_PATH updated to include $ORACLE_HOME/lib. You either need your program to set the environment, or have a SetEnv directive in your apache config. Bet way to see if this is the issue is just write a test CGI which dumps all the environment variables.
Now if the CGI is running under mod_perl its a bit trickier because mod_perl tends to be pretty anal about environment security. Think we ended up using the Perl*Something*Require directive to set it up within the perl. Sorry for being vague, was years ago....
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578451",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Loading animation appears with delay Using following code to show loading animation (and hide whole page loading process with it) if js enabled
<script>
document.getElementsByTagName('body')[0].innerHTML = '<div id="loading"><img src="core/design/img/load/load.gif" /></div>';
</script>
And fading out with following code
$(window).load(function(){
$('#loading').fadeOut(600);
});
But the loading div appears only after big delay:when whole page loaded it appears for 1-2 seconds. How -to fix hat problem? The loading div must appear at first
here is the page that i'm talking about http://aquastyle.az/?lang=en
A: try to change
<script>
document.getElementsByTagName('body')[0].innerHTML = '<div id="loading"><img src="core/design/img/load/load.gif" /></div>';
</script>
to
<script>
$(function(){
$(document.body).html('<div id="loading"><img src="core/design/img/load/load.gif" /></div>');
});
</script>
and see if that doesn't work better for you.
A: Try one thing
Make that loader div visible at start
style="display:block;"
and after page load make it disappear
$(document).load(function(){ $("#loaderdiv").css("display","none") })
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578452",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Subquery having clause error, what am I missing? Why am I getting this error?
SELECT unitCode
FROM Enrolment
WHERE count(studentID) >
(SELECT AVG(Students) AS avgstudents
FROM (SELECT COUNT(*) AS Students
FROM Enrolment AS Enrolment_1
GROUP BY unitCode) AS a))
A: Looks like there's an extra paren at the end. I don't know much SQL so I couldn't say if there's anything wrong otherwise (or whether the paren is an issue at all).
A: In where clause we can't use aggregate functions. You can use the count(studentID) function in HAVING clause.
Check this sample,
SELECT department, SUM(sales) as "Total sales"
FROM order_details
GROUP BY department
HAVING SUM(sales) > 1000;
A: David check this,
select count(*),unicode from Enrolement
having count(StudentID) > (select avg(Students) ad avgstudents,unitCode
from table_Name where Enrolement = "some of ur condtion"
group by unitCode)
Need to change your query of the formatted syntax.. check your query businees accordingly.
A: Try this:
select unitCode
from Enrolment
group by unitCode
having count(*) > (select avg(c.c) from (select count(*) as c from Enrolment group by unitCode) c);
With due deference to:
TSQL: Cannot perform an aggregate function AVG on COUNT(*) to find busiest hours of day
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578454",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to call a function based on string value in C# I want to convert a string to specific type based on the value of other string
Suppose I have two strings str1, str2.
If str2 is double then I want to call convert.ToDouble(str1) and return the Double value. Is there any way to accomplish this?
I tried using reflections (using methodInfo object to invoke)
But still it returns again an object for which I need to convert.
Please help..
A: Use the double.TryParse Method.
The method attempts to convert a string to a double and if it fails it returns false.
If I'm understanding you correctly, this is what you want:
private static double ConditionalConvertToDouble(string str1, string str2) {
double converted;
if (double.TryParse(str2, out converted)) {
// str2 can be converted to a double, so return str1 converted to a double.
return Convert.ToDouble(str1);
} else {
// I'm throwing an exception here if str1 cannot be converted to a double; you
// might want to do something different.
throw new ArgumentException("str1 cannot be converted to a double");
}
}
Call the method like this:
var d = ConditionalConvertToDouble("11", "22");
A: double result;
Double.TryParse(str1, out result);
if str1 is double, result will have its value, otherwise result will have 0. It will not throw any exception.
Hope it helps.
A: The following method will attempt to get the double value from "str1" if and only if "str2" also represents a double. If either of the numbers are not doubles, it will return double.NaN.
This method avoids throwing exceptions, but still allows you to check if you have a valid number.
public double GetFirstDoubleIfSecond(string str1, string str2)
{
double myDouble;
if(double.TryParse(str2, out myVal) && double.TryParse(str1, out myVal))
{
return myDouble
}
return double.NaN;
}
If you are expecting NaN values in your string, then you can use the following method, which will throw an exception if either of the strings are not doubles. Otherwise, it will return the string value represented in "str1".
public double GetFirstDoubleIfSecondWithExceptions(string str1, string str2)
{
double.Parse(str2);
return double.Parse(str1);
}
A: I think that switch-case operator should help to you. You should to specify some cases depending on one of your input string and make right decision. Your method should return object, if you really don't know which type exactly will return your method.
public object MyMethod(string str1, string str2)
{
switch(something)
{
case 1:
case 2:
return double.Parse(str1);
break;
case 3:
case 4:
return int.Parse(str1);
break;
default
return null;
}
}
where something is the criterion you should to specify.
After that System.Object.GetType() method can help you to detirmine which type was returned by your method.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578456",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Create a string array with Characters in C When I do this
char *paths[10];
paths[0] = "123456";
printf(1,"%s\n",paths[0]);
printf(1,"%c\n",paths[0][2]);
Output:
123456
3
But when I you do this
char *paths[10];
paths[0][0]='1';
paths[0][1]='2';
paths[0][2]='3';
paths[0][3]='4';
paths[0][4]='5';
paths[0][5]='6';
printf(1,"%s\n",paths[0]);
printf(1,"%c\n",paths[0][2]);
Output:
(null)
3
Why it is null in this case?
How to create a string array using characters in C? I am a bit new to C and feeling some difficulties to program in C
A: You have a lot of options provided by various answers, I'm just adding a few points.
You can create a string array as follows:
I. You can create an array of read only strings as follows:
char *string_array0[] = {"Hello", "World", "!" };
This will create array of 3 read-only strings. You cannot modify the characters of the string in this case i.e. string_array0[0][0]='R'; is illegal.
II. You can declare array of pointers & use them as you need.
char *string_array1[2]; /* Array of pointers */
string_array1[0] = "Hey there"; /* This creates a read-only string */
/* string_array1[0][0] = 'R';*/ /* This is illegal, don't do this */
string_array1[1] = malloc(3); /* Allocate memory for 2 character string + 1 NULL char*/
if(NULL == string_array1[1])
{
/* Handle memory allocation failure*/
}
string_array1[1][0] = 'H';
string_array1[1][1] = 'i';
string_array1[1][2] = '\0'; /* This is important. You can use 0 or NULL as well*/
...
/* Use string_array1*/
...
free(string_array1[1]); /* Don't forget to free memory after usage */
III. You can declare a two dimensional character array.
char string_array2[2][4]; /* 2 strings of atmost 3 characters can be stored */
string_array2[0][0] = 'O';
string_array2[0][1] = 'l';
string_array2[0][2] = 'a';
string_array2[0][3] = '\0';
string_array2[1][0] = 'H';
string_array2[1][1] = 'i';
string_array2[1][2] = '\0'; /* NUL terminated, thus string of length of 2 */
IV. You can use pointer to pointer.
char ** string_array3;
int i;
string_array3 = malloc(2*sizeof(char*)); /* 2 strings */
if(NULL == string_array3)
{
/* Memory allocation failure handling*/
}
for( i = 0; i < 2; i++ )
{
string_array3[i] = malloc(3); /* String can hold at most 2 characters */
if(NULL == string_array3[i])
{
/* Memory allocation failure handling*/
}
}
strcpy(string_array3[0], "Hi");
string_array3[1][0]='I';
string_array3[1][1]='T';
string_array3[1][2]='\0';
/*Use string_array3*/
for( i = 0; i < 2; i++ )
{
free(string_array3[i]);
}
free(string_array3);
Points to remember:
*
*If you are creating read-only string, you cannot change the character
in the string.
*If you are filling the character array, make sure you have
memory to accommodate NUL character & make sure you terminate your
string data with NUL character.
*If you are using pointers &
allocating memory, make sure you check if memory allocation is done
correctly & free the memory after use.
*Use string functions from
string.h for string manipulation.
Hope this helps!
P.S.: printf(1,"%s\n",paths[0]); looks shady
A: paths is an array of 10 pointers to char. However, the initial elements are pointers which can not be dereferenced. These are either wild (for an array in a function) or NULL for a static array. A wild pointer is an uninitialized one.
I would guess yours is static, since paths[0] is NULL. However, it could be a coincidence.
When you dereference a NULL or uninitialized pointer, you're reading or writing to memory you don't own. This causes undefined behavior, which can include crashing your program.
You're actually lucky it doesn't crash. This is probably because the compiler sees you're writing a constant to paths[0][2], and changes your printf to print the constant directly. You can not rely on this.
If you want to have a pointer you're allowed to write to, do:
paths[0] = malloc(string_length + 1);
string_length is the number of characters you can write. The 1 gives you room for a NUL. When you're done, you have to free it.
A: char *paths[10];
paths[0][0]='1';
paths is an array of pointers. paths is not initialized to anything. So, it has garbage values. You need to use allocate memory using malloc. You just got unlucky that this program actually worked silently. Think of what address location would paths[0][0] would yield to assign 1 to it.
On the other hand, this worked because -
char *paths[10];
paths[0] = "123456";
"123456" is a string literal residing in the reading only location. So, it returns the starting address of that location which paths[0] is holding. To declare correctly -
const char* paths[10];
A: For your second example, if you know the size of each string you can write e.g.
char paths[10][6];
paths[0][0]='1';
...
paths[0][5]='6';
This way you have 10 strings of length 6 (and use only the first string so far).
A: You can define the string yourself, right after
#inlcude <stdio.h>
like this
typedef char string[];
and in main you can do this
string paths = "123456";
printf("%s\n", paths);
return 0;
so your code would look like this
#include <stdio.h>
typedef char string[];
int main() {
string paths = "123456";
printf("%s", paths);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578458",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Exclude attribute in @BadgerFish in RESTEasy I am going to make one WebApplication which is RESTful. I am using RESTEasy API for that. I am using @BadgerFish annotation for mapping with POJO in POST request. But I have some attributes which should not allow to come in parameter. So my problem is how can i exclude those attributes or how to prevent @BadgerFish to set those values come in parameter?
For instance:
My DataBase info:
Table Name: user
Fields : name->String, loginCoung->int
My POJO:
@BadgerFish
public class POJO{
private Stirng name;
private int loginCount = 0;
public String getName() {
return name;
}
public void setName(String nm) {
this.name= nm;
}
public int getLoginCount() {
return loginCount;
}
public void setLoginCount(int loginCount) {
this.loginCount = loginCount;
}
}
My RESTFul code:
@POST
@Path("/user")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response postUser(@BadgerFish POJO p) {
System.out.println("post req.....");
return Response.status(200).entity("sucess"+p.getLoginCount()).build();
}
JSON Data comes in POST Request:
Case 1: if JSON is -> {"name":"abc"}
Response will be 0 (Works as expected)
Case 2: if JSON is -> {"name":"abc","loginCount":"12"}. It should not set the value of loginCount in POJO obj. and Response should be 0.
A: How about just overriding 'setLoginCount()' to take whatever action is needed (like setting a secondary flag or such)?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578459",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: combining multiple msi installer into single installer In My application there are 4 msi installers.one which installs web project,other one installs web services and two installers for installing windows service.
I want to combine all 4 into one.Is there a way to do that without using wix,installshield or any third party products.
A: A simple approach is to add 3 of your installers as a prerequisite to the fourth one. You can read more about prerequisites here:
*
*http://msdn.microsoft.com/en-us/library/77z6b8tz(VS.80).aspx
*http://msdn.microsoft.com/en-us/library/ms165429.aspx
*http://msdn.microsoft.com/en-us/library/ms165429(VS.80).aspx
You can then add the EXE bootstrapper and MSI files into a single EXE self-extract archive which executes the bootstrapper when extracted.
If an EXE is not acceptable and you want to combine them in an MSI, you will need a third party setup authoring tool.
A: No, there's no way to combine 4 MSIs into a single one. Whilst there are some ways of compositing components together (see Merge Modules, but they're not that popular these days), these have to be specially constructed, and are consumed whilst constructing the MSI into which they're added.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578466",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: mvc advice needed on create/new view that is assigned to a model? I'm pretty new in setting up mvc, please be patient..
So I have these two models
public class Promoter
{
public int Id {get; set;}
public string Name {get;set;}
public ICollection<Event> AllEvents {get;set;}
}
public class Event
{
public int Id {get;set;}
public string Name {get;set;}
public date Date {get;set;}
public int PromoterId {get; set;}
public virtual Promoter Promoter {get;set;}
}
And I have a controller Events
public class EventsController : Controller
{
public ActionResult New()
{
return View()
}
[HttpPost]
public ActionResult New(Model model)
{
// do stuff to save the new Event related to Promotion
}
}
so my problem is that, on the New Action, how do I make sure that the New View will be able to have an identifier on which Promoter it will be related to? I'm thinking hiddenfor that has the PromotionId so that when the Post gets called the Id will be there, but I will have to pass the Promoter Id when I call the New action?
Or do you think I should store the Promoter details in a cookie before going to that page?
Another thing to take note, the user will be authenticated and will need to be logged in to be able to access the Promotion controller (not shown in this thread) and then on that controller user can go to the said Event Controller which will have the New Action...
I hope that makes sense.
Need some advice, thoughts / ideas is very much appreciated.
THanks,
G
A: You're thinking right, you need to pass promotionId to the new action and action needs to pass it to the view. It is also possible through cookie, but I think action parameter is more convenient - because action parameter will be in url, so user can even bookmark it, send to another user, etc.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578482",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Optimizing unnecessary string copying in vector Presenting the minimal code to describe the problem:
struct A {
vector<string> v;
// ... other data and methods
};
A obj;
ifstream file("some_file.txt");
char buffer[BIG_SIZE];
while( <big loop> ) {
file.getline(buffer, BIG_SIZE-1);
// process buffer; which may change its size
obj.v.push_back(buffer); // <------- can be optimized ??
}
...
Here 2 times string creation happens; 1st time to create the actual string object and 2nd time while copy constructing it for the vector. Demo
The push_back() operation happens millions of times and I am paying for one extra allocation those many times which is of no use for me.
Is there a way to optimize this ? I am open for any suitable change. (not categorizing this as premature optimization because push_back() happens so many times throughout the code).
A: You can try a couple of things. The first is obviously to enable optimization on the compiler. If you can declare it as a vector<const string> that may help.
Otherwise you might try something like:
obj.v.resize(obj.v.size()+1);
obj.v.back().swap(string(buffer));
A: Well, you get two allocations, but not both of them are of the string: one of them creates the string, while the other creates just a pointer inside of the vector (note that this depends on the compiler: some compilers/settings might indeed create two strings, but most won't). Look at this code for the demo.
One way to optimize it would be using the char* instead of the string as the template parameter (don't forget to manually delete it before killing the vector!). This way you'll get rid of one (biggest) of the allocations. Alternatively, just use your own implementation of vector: you'll be able to control every aspect of memory allocation then.
A: Instead of having buffer on the stack - put it onto the heap. Then use a vector of pointers. Only one
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578487",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Are there any cross platform Java packages that can play, seek, and pitch shift MP3, WAV, OGG, MOD, S3M, IT, XM, and MIDI? Or if not all of those, at least MP3, WAV, OGG, and MIDI, and preferably noarch (works on 32 bit and 64 bit builds) I tried using Audiere's Java bindings, but they are 32 bit, and it would be a pain to have to compile it in all builds and platforms (plus I'm not familiar with compiling)
A: Try JavaZoom. With them you can handle MP3 and OGG files. I thought Java by default should be able to handle WAV file (as they are not compressed in any way), but I'm not sure since I've never used Java to play WAV files (only MP3 files). Not certain about MIDI though.
There's also the JMF (Java Media Framework), but that requires you to install the framework on client computers before you can use it's features. With JavaZoom, all you need to do is to include their jars in your project. I've been looking high and low for alternative projects which deals with playback of MP3 files, but it seems like JavaZoom and JMF are the only decent alternatives out there.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578488",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: ActionScript3 interface implementation without public accessor? In C#, it's possible implementing interface methods without making implementing method as public. For example,
void ITest.SomeMethod()
{
// ...
}
Is there equivalent for ActionScript3?
A: In ActionScript, there is no way to add access level qualifiers; however, this question has been asked here, leveraging inheritance of interfaces:
How to expose a method in an interface without making it public to all classes
Perhaps an internal class may be another approach; although, not recommended.
But directly no, all members of ActionScript interfaces are public.
A: Nope. From the AS3 Language Spec:
Classes that implement an interface method must use the public attribute to implement all interface methods.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578494",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to add underline of a text in HTML5 I am using HTML5, when I use <u></u> tag for underline, it says that it is unsupported by HTML5. What can I use in place of this for underlining?
A: You are looking for the text-decoration directive in CSS. As underlined text is a matter of styling and not of layout, it is better relegated to a stylesheet.
Which can be use as such, which will apply the style to all <td> elements on the page
td {
text-decoration: underline;
}
In CSS if you want a more targeted method of apply style, one way to go about this is with the class attribute of a tag <td class="className">. In CSS classes are defined with a leading full-stop.
.className {
/* relevant style */
}
so in the case of underlining you specific <td> tags. A method would be:
.underline {
text-decoration: underline;
}
<td class="underline">Here be underline</td><td>Here not be underline</td> ...
Further information on the form and ussage of CSS can he found at Css Basics
A: One approch to this
<td><span class='underline'>${user.status}</span></td>
<td><u>${user.action}</u></td>
In css create a class
.underline {
text-decoration: underline;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578495",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.