text stringlengths 8 267k | meta dict |
|---|---|
Q: How do I link to the App Store reviews for an application on the iPad? I want to put a "rate/review this app" feature into my iPad app. As described in this similar question, I can use code like the following:
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=449581298&onlyLatestVersion=true&pageNumber=0&sortOrdering=1&type=Purple+Software"]];
to open the App Store to the appropriate section on iPhone.
However, this method does not work on the iPad. Is there a means of doing the same thing that still functions on the iPad?
A: This is the method I have used on my app, which is out for all iOS devices. We have an iPad 2 that we use for testing, works great. Perhaps it is a bug? Have you tried upgrading the iOS?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510939",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: mod_rewrite: adding a rule causes it to break (error 500) I have the following mod_rewrite rules:
RewriteRule ^stats/$ stats/index.php
RewriteRule ^adm/$ adm/index.php
RewriteRule ^iphone/$ iphone/index.php
RewriteRule ^android/$ android/index.php
RewriteRule ^([^/\.]+)/?$ index.php?page=$1
RewriteRule ^([^/\.]+)/([0-9]+)/$ index.php?page=$1&pn=$2
RewriteRule ^categories/([^/\.]+)/([0-9]+)/$ index.php?cat_name=$1&pn=$2
RewriteRule ^([^/\.]+)/([^/\.]+)/$ index.php?app_name=$2
RewriteRule ^([^/\.]+)/([a-zA-Z]+)-([^/\.]+)/$ index.php?app_name=$2-$3
RewriteRule ^news/([^/\.]+).(html|htm)$ index.php?news_url=$1
However, when I add the following line:
RewriteRule ^faq/([^/\.]+)/?$ index.php?page=$1 [L]
it breaks, I assumed it's because a conflict between rule 5, so I added it before that, but still - no go... can anyone shed some light on how to incorporate this rule in my htaccess?
Edit:
When looking at the error logs (took a while, cause had to set up a subdomain to not hurt the main site):
[Thu Sep 22 01:04:06 2011] [alert] [client 212.199.198.140] /home/my71/*/.htaccess: RewriteRule: bad flag delimiters
Edit 2: don't have access to my htpdconfig, but the htaccess:
#WWW TO NON WWW
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteCond %{REQUEST_URI} [A-Z]
RewriteMap lc int:tolower
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
RewriteRule (.*) ${lc:$1} [R=301,L]
#URL REWRITES
RewriteRule ^stats/$ stats/index.php
RewriteRule ^adm/$ adm/index.php
RewriteRule ^iphone/$ iphone/index.php
RewriteRule ^android/$ android/index.php
RewriteRule ^([^/\.]+)/+$ index.php?page=$1
RewriteRule ^([^/\.]+)/([0-9]+)/$ index.php?page=$1&pn=$2
RewriteRule ^categories/([^/\.]+)/([0-9]+)/$ index.php?cat_name=$1&pn=$2
RewriteRule ^(?!.*faq)([^\/.]+)\/([^\/.]+)\/$ index.php?app_name=$2
RewriteRule ^news/([^/\.]+).(html)$ index.php?news_url=$1
# compress text, html, javascript, css, xml:
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
# Or, compress certain file types by extension:
<Files *.html>
SetOutputFilter DEFLATE
</Files>
Thanks, Itai
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510941",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: calling asmx from c# server side: endpoint element matching this contract could be found in the client element I wrote an asmx webSerivce on srv1.
I wrote a bll project of an asp.net (original text: an asp.net) project on srv2.
Both are hosted under the same web domain
I want to call the asmx from the bll project of the asp.net (original text: asp.net(c#) code behind).
1) I added a web reference, but couldn't find any tutorial how to really call the referenced service.
I have tried:
private void GetTemplateComponentsData()
{
var service = new ServiceReference.GetTemplateParamSoapClient();
TemplateParamsKeyValue[] responsArray = service.GetTemplatesParamsPerId(id);
foreach (var pair in responsArray)
{
TemplateComponentsData.Add(pair.Key, pair.Value);
}
}
but get the following error when executing the first line:
Could not find default endpoint element that references contract 'ServiceReference.GetTemplateParamSoap' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element.
What am I missing?
2) I plane to migrate the asp.net proj and asmx together from one domain to another.
Is there any way to reference this webservice relatively ?
A: OK, let me try to rephrase your scenario to make sure I got it right:
*
*You have an ASMX web service hosted on some domain.
*You have an ASP.NET application hosted on the same or a different domain (it doesn't really matter) from which you want to to consume this ASMX web service using a WCF client (svcutil).
The first step is to add a Service Reference to the ASP.NET application by pointing to the WSDL of the ASMX service:
This will do 2 things:
*
*It will add a ServiceReference to your web application
*
*It will modify your web.config and include the client endpoints:
<client>
<endpoint address="http://ws.cdyne.com/NotifyWS/phonenotify.asmx"
binding="basicHttpBinding" bindingConfiguration="PhoneNotifySoap"
contract="ServiceReference1.PhoneNotifySoap" name="PhoneNotifySoap" />
<endpoint address="http://ws.cdyne.com/NotifyWS/phonenotify.asmx"
binding="customBinding" bindingConfiguration="PhoneNotifySoap12"
contract="ServiceReference1.PhoneNotifySoap" name="PhoneNotifySoap12" />
</client>
Now when you want to invoke this service from your application you will have to choose the endpoint you want to use:
using (var client = new ServiceReference1.PhoneNotifySoapClient("PhoneNotifySoap"))
{
var result = client.GetVersion();
}
Now simply replace my code snippets with your actual service names.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510953",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: Redirect the standard input and output of .net program I am writing a test script for a C/S system in python. And right now, we only have a test client written in C#. It is a command line based client. I want to control the input and get the output of the client in my python script. How could I make it?
Thanks!
A: Use the subprocess module as follows:
import subprocess
proc = subprocess.Popen("cat", stdin = subprocess.PIPE, stdout = subprocess.PIPE)
out, err = proc.communicate(input)
The process ends after the last call. If you want to do some input iteratively, you can use proc.stdin.write, but you have to call communicate(None) at the end to finish the process.
A: Use subprocess.Popen.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510959",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Initialize struct in class constructor How can we initailize a struct pointer in constructor of a class.
Example:
struct my_struct{
int i;
char* name;
};
class my_class{
my_struct* s1;
my_class() {
// here i want to make s1->i = 10; and s1->name = "anyname" ;
// should i assign it like s1->i= 10; and call new for s1->name and strcpy(s1->name "anyname");
// it compiles in g++ without any warning/error but gives seg fault at run time
}
};
A: When you create an instance of my_class, the s1 pointer doesn't point to anything. You have to allocate memory for it like so:
myclass() {
s1 = new my_struct;
// initialize variables
}
You will also have to create a destructor for it:
~myclass() {
// delete variables
delete s1;
}
Also, since this is C++, I recommend you use std::string instead of char*s.
A: Since this is C++, use std::string instead of char*:
struct my_struct{
int i;
std::string name;
};
class my_class{
my_struct* s1;
my_class() {
s1 = new my_struct;
s1->i = 10;
s1->name = "anyname";
}
};
The reason your original code segfaulted was that you failed to allocate memory for s1 and also failed to allocate memory for s1->name. I've fixed the former with the new and the latter by using std::string. If for some reason you can't use std::string, use strdup where you were trying to use strcpy.
Lastly, don't forget to provide a destructor for my_class that'll delete s1 (and will free s1->name if you opt for char* and strdup).
A: I'm surprised that no-one has suggested the following...
struct my_struct
{
int i;
std::string name;
my_struct(int argI, std::string const& argName) : i(argI), name(argName) {}
};
class my_class
{
my_struct s1; // no need for pointers!
my_class() : s1(1, std::string("test name")) {} // construct s1 using the two argument constructor, can also default construct as well.
};
With this approach, you don't need to worry about cleaning up s1, it's automatic...
A: I'm pretty sure you can use an initialization list, and new+init the struct directly. Also, you can't forget that you have to delete the pointer when you're done:
struct my_struct{
int i;
char* name;
};
class my_class{
my_struct* s1;
my_class() : s1(new my_struct) {
s1->i = 2;
s1->name = "Something";
}
~my_class() { delete s1; }
};
Also, make sure you're using a char* for a reason, otherwise a std::string will most often be better.
A: If the structure is inside the class, you can use the structure constructor:
struct my_struct
{
int i;
std::string name;
my_struct()
{
i = 10;
name = "anyname";
};
};
If it's global, you first need to create the object and then initialize it:
class my_class
{
my_struct * s1;
my_class() : s1(new my_struct())
{
s1->i = 10;
s1->name = "anyname";
}
};
A: my_class() {
s1 = new (my_struct);
s1->i = 10;
s1->name = (char *) malloc(strlen("anyname"));
s1->name = "anyname";
// here i want to make s1->i = 10; and s1->name = "anyname" ;
// should i assign it like s1->i= 10; and call new for s1->name and strcpy(s1->name "anyname");
// it compiles in g++ without any warning/error but gives seg fault at run time
}
~my_class(){
free(s1->name);
delete s1;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510967",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to control my app's version? I want to control my customer's app's version. If the application is not update ,i want to show them an alert message that "your app isn't update would you like to update ?" how can i control this in android?
A: You can host your new version apk file in web page with a text file with version information.Then palce a text file in assest with current version information. When you application starts, read current version from assest, download the version information using HTTP methods and compare the version. If you require update then download latest apk from web using HTTP method and install using following code..
Intent apk_installer = new Intent(Intent.ACTION_VIEW);
apk_installer.setDataAndType(Uri.fromFile(apkFilePath),"application/vnd.android.package-archive");
startActivityForResult(apk_installer,0);
A: You can get current apk/Programm version by:
PackageInfo info = getPackageManager().getPackageInfo(PACKAGE_NAME, 0);
currentVersion = info.versionCode;
currentName = info.versionName;
So you don't really need a local text file with version information.
Greetings Ralf
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510970",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Getting NullReferenceException in Code What is wrong with this code?
public partial class MainForm : Form
{
private Dictionary<String , PropertyInfo[]> types;
public MainForm()
{
//OpenAccountStruct is in the scope
types.Add("OpenAccount", new OpenAccountStruct().GetType().GetProperties());
}
}
Why am I getting NullReferenceException?
A: You didn't make an instance of types (your Dictionary).
try
types = new Dictionary<String , PropertyInfo[]>();
A: The types variable is not initialized.
Use types = new Dictionary<String , PropertyInfo[]>();
A: private Dictionary<String , PropertyInfo[]> types =
new Dictionary<String , PropertyInfo[]>();
A: Obviously, your types field is not initialized,
public partial class MainForm : Form
{
private Dictionary<String , PropertyInfo[]> types = new Dictionary<String , PropertyInfo[]>();
public MainForm()
{
//OpenAccountStruct is in the scope
types.Add("OpenAccount", new OpenAccountStruct().GetType().GetProperties());
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510971",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: why 'remoteCertificate' parameter is empty in LocalCertificateSelectionCallback method? i wanna setup a SSL connection, but really don't know everything about SSL handshake rules and life cycle. i wrote a code
void main()
{
TcpClient client = new TcpClient("192.168.1.160", 4113);
SslStream sslStream = new SslStream(
client.GetStream(),
false,
new RemoteCertificateValidationCallback(ValidateServerCertificate),
new LocalCertificateSelectionCallback(localCertSelection)
);
sslStream.AuthenticateAsClient(serverName);
}
public X509Certificate localCertSelection(object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers)
{// why here 'remoteCertificate' parameter is empty? 'acceptableIssuers' and 'localCertificates' too
string cert = "MIIEwjCCA6qgAwIBAgIBADANBgkqhkiG9w...";
X509Certificate clientCert = new X509Certificate(System.Text.Encoding.ASCII.GetBytes(cert));
return clientCert;
}
public bool ValidateServerCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
// 'certificate' has data now. it has come from server
if (sslPolicyErrors == SslPolicyErrors.None)
return true;
Console.WriteLine("Certificate error: {0}", sslPolicyErrors);
// Do not allow this client to communicate with unauthenticated servers.
return false;
}
when i run the code, program flow first goes to 'localCertSelection' method and then goes to 'ValidateServerCertificate' method.
in 'localCertSelection' method 'remoteCertificate' is empty , but in 'ValidateServerCertificate' method 'certificate' has data. it has come from server, but why
'sslPolicyErrors' is 'RemoteCertificateNameMismatch | RemoteCertificateChainErrors' ?
what's wrong? what i have to do?
A: The RemoteCertificateNameMismatch error may occur if your "servername" are wrong. I mean that servername in
sslStream.AuthenticateAsClient(serverName);
must be "192.168.1.160", the same as in
TcpClient client = new TcpClient("192.168.1.160", 4113);
The RemoteCertificateChainErrors happen if something wrong with your root certificate. When you create certificate you have to put appropriate host in CN,
CN=192.168.1.160. And don't forget import your root certificate to "Trusted Root Certification Authorities".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510979",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Insert a record in Main table & several into sub table SQL 2008:
I have 2 tables TableMain & TableSub. The 2 tables are related via the MainID
When I insert 1 records in TableMain, it creates a MainID automatically.
I have to use the MainID & then insert several records into the TableSub.
TableMain has 16 parameters.
TableSub has 4 parameters for each record not including the MainID.
I am using ASP.NET with SQLDatasource.
If I had a few records in TableSub, I could have used a stored procedure inserted all the records at the same time. Since there will be at least 10+ records, no. of parameters will become unmanageable. Also the no. of records in TableSub wil be variable.
What will be the best approach to accomplish this?
EDIT: ASP.NEt 3.5
If I do go with ObjectDatasource (NO DAL - .XSD file) how do I design my Business Logic Layer/DataAccess Class?
*
*Should I have 2 Data Access Classes - One for Main & the other for Sub?
*The Main - Insert() should return the ID & using that I should call the Sub-Insert() - Should this be a part of the Main -Insert() code or should it be explicitly be called from the file that class the Main-Insert()?
*Tutorial with Object Data Source using the scenario with Main & Sub Table will be much appreciated.
A: I'd like to suggest you to use EntityFramework in order to solve your problems.
PS: Never use SQLDataSource. (and I'm sure that you will never get desired result with SqlDatasource)
A: I used ObjectDatasource with DAL(.cs class) . Did not use the XSD file. No BLL as I felt it was a overkill. But I did code with SQLDatasource & got my queries working & just dropped them into the DAL. Setting up SQLDatasorce was easy with the wizard.
I do have 2 DAL classes one for main & one for Sub.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510990",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to extract selected item from ListView? I have a Listview that can only select one item. When that item gets clicks, it runs an AsyncTask. In the onPostExecute(), an AlertBox Dialog pops up. But what I'm trying to do is get the selected item to display inside the alertBox and I've tried everything I could think of. Any help would be appreciated, and thank you in advance.
Here is my ListView setup.
Public class MyClass extends Activity
{
list.setAdapter(new ArrayAdapter<String>(this, R.layout.vacation_tracks, vacation_menu));
list.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
for(int i = 0; i<vacation_menu.length; i++)
{
if(((TextView) view).getText().equals(vacation_menu[i]))
{
Sizes work = new Sizes();
work.execute(tempLink);
}
}
});
}
And this is my AsyncTask class. My goal is to get the selected item (or text from TextView associated with selected item) in the Title() method in the onPostExecute().
Private Class Sizes extends AsyncTask<URL, Void, Float>
{
protected float doInBackground(URL...urls)
{
//gets url.getContentLength();
}
protected void onPostExecute(Float result)
{
AlertDialog.Builder alertbox = new AlertDialog.Builder(Vacation.this);
alertbox.setMessage( Title( ITEM FROM LISTVIEW ) );
alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
}
});
alertbox.setNegativeButton("No", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
}
});
alertbox.show();
}
}
Thank you again for any help!
A: You could use the position argument of your onItemClick listener to fetch the clicked item from your data source, then pass this data to the AsyncTask object, and consume it there (display it in the Alert box)
A: If your Task is defined within the scope of your Activity, you can use the final keyword:
final String alertBoxTitle = vacation_menu[i];
Sizes work = new Sizes();
work.execute(tempLink);
and
alertbox.setMessage(alertBoxTitle);
If your Task is not within the scope of your Activity you could pass the title as an argument or via a setter. Setter seems easier in your case.
Within your Task:
String title;
public void setTitle(String title) {
this.title = title;
}
protected void onPostExecute(Float result) {
AlertDialog.Builder alertbox = new AlertDialog.Builder(Vacation.this);
alertbox.setMessage(title);
// ...
}
Use it like this:
Sizes work = new Sizes();
work.setTitle(vacation_menu[i]);
work.execute(tempLink);
A: If the AsynTask is inner to your activity then you can access the listview member and get the selected item. Call
mListView.getSelectedItem(); // returns the object associated with this item.
Or
You can pass the object to the AsyncTask through the parameters.
Pass the title string to the Size constructor. Like this
Sizes work = new Sizes(mListView.getSelectedItem().getTitle());
work.execute(tempLink);
A: if you just want to create an alert dialog you don't need the AsyncTask..
Just add the code getSelectedItem in your onListItemClick and create an alert from that..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510993",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ASP .NET MVC with ADO .NET causing issues? I'm new to both ADO .NET and MVC, and I am trying to do something simple where I am editting a "DailyReport", which is basically representing a work-report.
Here's my relevant controller pattern:
//
// GET: /DailyReport/Edit/5
public ActionResult Edit(int id, int weeklyReportID, int day)
{
WeeklyReport weeklyReport = (
from WeeklyReport wr in db.WeeklyReports
where wr.Id == weeklyReportID select wr)
.FirstOrDefault();
ViewBag.Week = weeklyReport.Week;
ViewBag.Day = day;
return View();
}
//
// POST: /DailyReport/Edit/5
[HttpPost]
public ActionResult Edit(DailyReport dailyReport, int weeklyReportID, int day)
{
if (ModelState.IsValid)
{
db.SaveChanges();
if (dailyReport == null)
{
dailyReport = new DailyReport();
dailyReport.StartTime = new TimeSpan(7, 0, 0);
dailyReport.EndTime = new TimeSpan(7 + 8, 0, 0);
dailyReport.Day = day;
db.DailyReports.AddObject(dailyReport);
db.SaveChanges();
}
WeeklyReport weeklyReport = (
from WeeklyReport wr in db.WeeklyReports
where wr.Id == weeklyReportID select wr)
.FirstOrDefault();
if (!weeklyReport.DailyReport.Any(dr => dr.Id == dailyReport.Id))
{
weeklyReport.DailyReport.Add(dailyReport);
}
dailyReport.WeeklyReport = weeklyReport;
db.SaveChanges();
return RedirectToAction("Edit",
"WeeklyReport",
new {
id = weeklyReportID,
week = weeklyReport.Week,
year = weeklyReport.Year
});
}
return View(dailyReport);
}
When I am editting the datetime value, it doesn't get saved. In the HttpPost section when I debug it, the object is indeed changed to reflect these changes, but calling db.SaveChanges() doesn't commit it to the database.
Edit "db" in this case is my ADO .NET context, declared in the following way:
ActivesEntities db = new ActivesEntities();
ActivesEntities has this declaration:
public partial class ActivesEntities : ObjectContext { ... }
A: First of all, I would recommend you to not call the db.SaveChanges until you really need to save an Entity object in the middle of the series of Transactional Steps..
Because Entity Framework support saving all the EntityContext object in a single shot !
And I think you may try changing the code like this,
[HttpPost]
public ActionResult Edit(DailyReport dailyReport, int weeklyReportID, int day)
{
if (ModelState.IsValid)
{
if (dailyReport == null)
{
dailyReport = new DailyReport();
dailyReport.StartTime = new TimeSpan(7, 0, 0);
dailyReport.EndTime = new TimeSpan(7 + 8, 0, 0);
dailyReport.Day = day;
db.DailyReports.AddObject(dailyReport);
}
WeeklyReport weeklyReport = (from WeeklyReport wr in db.WeeklyReports where wr.Id == weeklyReportID select wr).SingleOrDefault();
if (!weeklyReport.DailyReport.Any(dr => dr.Id == dailyReport.Id))
{
weeklyReport.DailyReport.Add(dailyReport);
}
dailyReport.WeeklyReport = weeklyReport;
db.SaveChanges();
return RedirectToAction("Edit", "WeeklyReport", new { id = weeklyReportID, week = weeklyReport.Week, year = weeklyReport.Year });
}
I think using if you are Updating the entity object then you need to call SingleOrDefault and not FirstOrDefault. I do it like this on Linq2Sql..
A: you are using entity framework right? it's a bit different from ADO.NET (it uses it but those are not 100% same thing), we should add the tag EF to the question.
said so, why do you call db.SaveChanges twice? I would not call it at the top of your Edit method.
also, as I see in some EF examples, you can use Add and not AddObject.
check this one:
How to: Add, Modify, and Delete Objects
last thing, your StartTime and EndTime properties of the object are of type TimeSpan and not datetime?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510997",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there a way to stop scrollbars from affecting the box model measurements? I have made a table in the way described at imaputz.com, but with alternating colors for the rows. Because of these colors there is a distinct difference in the row color and the color surrounding the table, and that makes the table look bad when there is to few rows to need the scrollbar since the right edge of the tbody does not line up with the right edge of the thead (which also has a color distinct from the surrounding background).
My idea now is:
If I could somehow stop the sidebar from affecting the layout of its containing elements (so that the scrollbar overlaps some of its containing elements, potentially), I could then pad the rows a bit to make sure that the scrollbar never overlaps something important.
Is there a way to achieve this scroll bar behaviour, preferably without Javascript?
Example:
<div id="list">
<table>
<thead>
<tr>
<th>
DATUM
</th>
<th>
TID
</th>
<th>
TEMPERATUR
</th>
<th>
STATUS
</th>
<th>
ÅTGÄRD
</th>
</tr>
</thead>
<tbody>
<tr class="odd row0">
<td>
2011 09 22
</td>
<td>
04:39
</td>
<td>
-264.2
</td>
<td>
</td>
<td>
Antibiotika behandling
</td>
</tr>
<tr class="even row1">
<td>
2011 09 22
</td>
<td>
04:36
</td>
<td>
-264.2
</td>
<td>
</td>
<td>
Under behandling
</td>
</tr>
<tr class="odd row2">
<td>
2011 09 21
</td>
<td>
19:29
</td>
<td>
-264.2
</td>
<td>
Förhöjd
</td>
<td>
</td>
</tr>
<tr class="even row3">
<td>
2011 09 21
</td>
<td>
19:29
</td>
<td>
-273.2
</td>
<td>
Förhöjd
</td>
<td>
</td>
</tr>
<tr class="odd row4">
<td>
2011 09 21
</td>
<td>
19:29
</td>
<td>
-270.2
</td>
<td>
Förhöjd
</td>
<td>
</td>
</tr>
<!-- Uncomment to get scrollbars
<tr class="even row5">
<td>
2011 09 21
</td>
<td>
19:29
</td>
<td>
-273.2
</td>
<td>
Förhöjd
</td>
<td>
</td>
</tr>
<tr class="odd row6">
<td>
2011 09 21
</td>
<td>
19:29
</td>
<td>
-270.2
</td>
<td>
Förhöjd
</td>
<td>
</td>
</tr>
<tr class="even row7">
<td>
2011 09 21
</td>
<td>
19:29
</td>
<td>
-273.2
</td>
<td>
Förhöjd
</td>
<td>
</td>
</tr>
<tr class="odd row8">
<td>
2011 09 21
</td>
<td>
19:28
</td>
<td>
-272.2
</td>
<td>
Förhöjd
</td>
<td>
</td>
</tr>
<tr class="even row9">
<td>
2011 09 21
</td>
<td>
19:28
</td>
<td>
-262.2
</td>
<td>
Förhöjd
</td>
<td>
</td>
</tr>
<tr class="odd row10">
<td>
2011 09 21
</td>
<td>
19:28
</td>
<td>
-268.2
</td>
<td>
Förhöjd
</td>
<td>
</td>
</tr>
<tr class="even row11">
<td>
2011 09 21
</td>
<td>
19:28
</td>
<td>
-273.2
</td>
<td>
Förhöjd
</td>
<td>
</td>
</tr>
<tr class="odd row12">
<td>
2011 09 21
</td>
<td>
19:28
</td>
<td>
-269.2
</td>
<td>
Förhöjd
</td>
<td>
</td>
</tr>
<tr class="even row13">
<td>
2011 09 21
</td>
<td>
19:27
</td>
<td>
-270.2
</td>
<td>
Förhöjd
</td>
<td>
</td>
</tr>
-->
</tbody>
<tfoot>
</tfoot>
</table>
</div>
Css:
#list {
width:60%;
float:left;
}
#list table {
font-weight:normal;
border-collapse:collapse;
text-align:center;
font-size:smaller;
}
#list table thead tr {
display:block;
position:relative;
}
#list table, #list th, #list td
{
border:1px solid white;
}
#list table tr td,
#list table tr th
{
width:65px;
}
#list table tr td + td,
#list table tr th + th
{
width:40px;
}
#list table tr td + td + td,
#list table tr th + th + th
{
width:100px;
}
#list table tr td + td + td + td,
#list table tr th + th + th + th
{
width:80px;
}
#list table tbody tr td + td + td + td + td
{
width:150px;
}
/* The last column header is a special case, to compensate for
the scrollbar's width, which would otherwise offset the
columns a bit to the left. */
#list table thead tr th + th + th + th + th
{
width:166px;
}
#list th {
background-color:#E5E5E5;
}
#list .odd
{
background-color:#E5E5E5;
}
#list .even
{
background-color:#CBCBCB;
}
#list table tbody {
display:block;
overflow:auto;
height:206px;
}
The example got a little large, sorry about that.
A: Original code jsfiddle: http://jsfiddle.net/ZhSK6/
This seems to solve it:
http://jsfiddle.net/ZhSK6/1/
#list table thead tr th + th + th + th + th
{
width:166px;
}
Update on the secondary problem: http://jsfiddle.net/lollero/ZhSK6/15/
and a little more plain example: http://jsfiddle.net/lollero/ZhSK6/14/
Edit: Updated my examples. ( Changed the jquery version up so that it can actually be found from google servers...for a while at least. )
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511002",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to replace entity in LQC? I have Lazy Query Container (LQC) + hibernate connected to table. I don't want to display some collections at the table so some collections are lazy loaded.
When user select item (row) in table I want to open edit form with all data available. I have to initialize selected item - I get entity from Item, merge it back to context and call hibernate.initialize. it works fine, collections are initialized. But it is another instace then instance in container (because merge returns new instance)
*
*How can I replace non-initialzied item with this new one?
*Or how can I refresh the container and the table (how to select
previously selected row in table after refresh?)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511005",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Don't understand the output of this C program Here's the code:
#include <stdio.h>
int main (void)
{
int value[10];
int index;
value[0] = 197;
value[2] = -100;
value[5] = 350;
value[3] = value[0] + value[5];
value[9] = value[5] / 10;
--value[2];
for(index = 0; index < 10; ++index)
printf("value[%i] = %i\n", index, value[index]);
return 0;
}
Here's the output when compile:
value[0] = 197
value[1] = 0
value[2] = -101
value[3] = 547
value[4] = 0
value[5] = 350
value[6] = 0
value[7] = 0
value[8] = 1784505816
value[9] = 35
I don't understand why value[8] returns 1784505816?
Isn't value[8] supposed be = value[6] = value[7] = 0? By the way, I compile the code via gcc under Mac OS X Lion.
A: Objects with automatic storage duration declared without an initializer have indeterminate values until they are assigned to. Technically, it causes undefined behavior to use the value (e.g. printing int) of an object which has an indeterminate value.
If you want the array to be initialized to zero you need to provide an initializer. E.g.
int value[10] = {0};
A: value[8] was never initialized, therefore its contents are undefined and can be anything.
Same applies to value[1], value[4], value[6], and value[7]. But they just happened to be zero.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511008",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Is it considered readable to call methods inside the IF condition? Is this way of writing IF conditions considered good coding style in Java and C# languages or not?
if (checkIfIdInFirstRange()){
//call Range1 handling method
}else if(checkIfIdInSecondRange()){
//call Range2 handling method
}else{
//call error handling method
}
I'm wondering about the method inside the IF condition itself, or would it be better to make it like:
int idInRange = getIdInRange();
//handle isInRange
A: I think this is fine.
Even better is if you phrase your methods like a question, or flows with the if statement
if (thisConditionIsTrue()){
// Do this
}elseif(anotherConditionIsTrue()){
// Do this instead
}elseif(isThisParameterOkay(someParameter)){
// Yeh do this
}
Some hardcore purists will even say that if you have > 3 levels of indentation, your method is too nested and should be split into smaller methods.
A: Doing this is IMHO good coding practice as long as the method calls don't have any side effects.
e.g.
if checkIfIdInFirstRange() this is OK:
private bool checkIfIdInFirstRange()
{
return firstRange.Contains(ID);
}
But doing this might create confusion:
private bool checkIfIdInFirstRange()
{
SomeStringProperty = "totally new value that no caller would ever expect after a call to this method";
return firstRange.Contains(ID);
}
Another possible solution - depending on the actual type of your problem at hand - could be to define an interface / base class and use polymorphism.
example:
internal abstract class A
{
public void DoSomething(int ID)
{
if(IsInRange(ID))
DoSomethingProtected(ID);
}
protected abstract bool IsInRange(int ID);
protected abstract void DoSomethingProtected(int ID);
}
internal class B : A
{
private List<int> firstRange = new List<int> { 42, 23, 5};
protected override bool IsInRange(int ID)
{
return firstRange.Contains(ID);
}
protected override void DoSomethingProtected(int ID)
{
Console.WriteLine("{0}", ID);
}
}
public class Program
{
public static void Main(string[] args)
{
B foo = new B();
foo.DoSomething(3);
foo.DoSomething(42);
}
}
CAUTION: code written without IDE to hand.
A: Yes. It would be much more readable if you used just a little whitespace. Bunching it up like that makes it hard to tell where things begin and end and makes else if() look like a function call.
if ( checkIfIdInFirstRange() ) {
//call Range1 handling method
}
else if ( checkIfIdInSecondRange() ) {
//call Range2 handling method
}
else {
//call error handling method
}
Making the extra variable is likely to make code harder to read since you have to define them all before the if/else stack. However, it all depends on the case. Sometimes it might be better to use a variable if you will be using an expensive function many times or if you can make the variable have a more descriptive name than the function.
A: Actually it is also required if you want to test multiple methods and use short-circuit evaluation.
For instance, this is safe:
if (isResourceAvailable() && isResourceValid()) {
...
}
while this may no be:
bool resAvailable = isResourceAvailable();
bool resValid = isResourceValid(); // can you call that alone?
if (resAvailable && resValid ) {
...
}
A: It is good style as long as the methods you call don't just do something that would be clearer if it was coded in place:
if ( a > 0 && a < 10 ) doSomething();
is better than
if ( isInRange(a, 0, 10) ) doSomething();
A: Eh, it's mostly up to the coder but declaring the int is a bit more readable.
A: It's OK to write methods in the IF condition statement. But if the method will be used more than one time, you should first use a local variable to store the return value and use the variable as the IF condition
A: You can aim at writing function / method names that will make the code more readable where they are used. Like:
if (idInFirstRange()){
//call Range1 handling method
}else if(idInSecondRange()){
//call Range2 handling method
}else{
Also, usual convention for functions returning bool is that they start with is - isIdInFirstRange
Lastly, try avoiding such if-else ( and switch ) ladder. Try to use Dictionaries in such cases. ( https://stackoverflow.com/questions/6506340/if-if-else-or-switch-case/6506403#6506403 )
A: Although this practice is not wrong or condemned by any best practices guidelines, if you have more than one call within if condition it can be a bit difficult to know which call refused to enter if statement during a debug session.
if (idInFirstRange() && idInSecondRange()){
//call Range handling method
//if didn't reach this point, who was the responsible (idInFirstRange or idInSecondRange)?
}else if(idInSecondRange()){
//call Range2 handling method
}else{
//call something else
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511015",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How use TDataset and Dll with Delphi I'd like create a dll to import data from a file (different format, for example csv, txt, xls, ...). My idea is this: the dll load the data with her "engine" then send this data to my application so my application can show them inside a grid.
This is my second DLL so I have some problems/questions.
I think my DLL should send the data to a TDataset on my application but how can I call a DLL with a TDataset as argument?
Any suggestions?
What is the easiest way to accomplish what I have in mind? (if possible)
A: If you are the creator of those DLL's, then consider to use packages instead of DLL. This will avoid the problems, like dublicate Delphi RTTI, plain DLL API. Then you will need to properly split classes between packages, load packages statically or dynamically, get reference to a class implementing import engine, and call the corresponding method with a dataset reference as a parameter value.
A: Easier way for you would be to store the data directly into database in DLL. And after import you just refresh your TDataset.
BTW, you don't "call DLL", you call some method that is public in DLL and there you can use arguments as in normal methods.
EDIT: For more generic DLLs that don't require data components just send data in struct
TMyData
{ int ID;
String Value;
};
int MyDataImport(TMyData & data)
{
...
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511022",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to add homepage URL to SAP business partner? I'm working on a program witch creates Business Partners in SAP IS-U system. For the creation of business partners I use function module BAPI_ISUPARTNER_CREATEFROMDATA
I have to add homepage URL too, any idea how to do it?
Thanks!
A: The homepage URL is part of the business partner's communication data, which can either be part of the address data or address-independent communication.
Look at function modules BAPI_BUPA_ADDRESS_ADD/BAPI_BUPA_ADDRESS_CHANGE for updating it with address data (table parameter BAPIADURI) or function modules BAPI_BUPA_CREATE_FROM_DATA/BAPI_BUPA_CENTRAL_CHANGE for address-independent communication, table parameter URIADDRESSDATANONADDRESS.
Unfortunately I do not have access to function BAPI_ISUPARTNER_CREATEFROMDATA to see if it has similar parameters.
Whether or not it must be stored as address-dependent or independent data is a business decision.
As an alternative, you should see whether you can update/create BPs via the BOL.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511024",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Postgres xmlelement encoding My postgres database in UTF-8 and client in UTF-8 too.
When i try to:
select xmlelement(name pampam, xmlattributes('русский' as "top"));
I get back:
<pampam top="русский"/>`
But i want get back attribute as is( i.e. in Russian UTF-8), not as р....
How i can do this?
This is not solve problem, I use xmleliment to construct xml from data get back by queries.
And i can't find another way to do this...
A: This doesn't appear to be possible. The values to print are passed to libxml, and that's how it chooses to print it.
A: Probably it is not the best solution but this works for me:
SELECT xmlparse(CONTENT '<element attribute=''áéíóú´ñÇ`''>value</element>')
I get back:
<element attribute='áéíóú´ñÇ`'>value</element>
A: I have just created a character entity to character conversion function, entity2char:
select
xmlparse(content
entity2char((
xmlelement(name pampam, xmlattributes('русский' as "top"))
)::text)
);
xmlparse
-------------------------
<pampam top="русский"/>
A: I used plpythonu to write function using lxml
CREATE OR REPLACE FUNCTION xmlelementpy (
nodename_in varchar,
nodetext_in text,
attrname_in varchar [],
attrvalue_in varchar []
)
RETURNS xml AS
$body$
from lxml import etree
noattr = 0
isxml = 1
if (attrname_in is None) or (attrname_in is None):
noattr = 1
elif len(attrname_in) <> len(attrvalue_in):
return None;
newnode = etree.Element(nodename_in)
if nodetext_in is not None:
try:
schema = etree.fromstring(nodetext_in)
except:
newnode.text = nodetext_in
isxml = 0
if isxml <> 0:
newnode.append(etree.XML(nodetext_in))
if noattr <> 1:
for i in range(len(attrname_in)):
if (attrvalue_in[i] is not None):
attrvalue = attrvalue_in[i].decode('UTF-8')
newnode.set(attrname_in[i], attrvalue)
return etree.tounicode(newnode, pretty_print=True)
$body$
LANGUAGE 'plpythonu'
VOLATILE
CALLED ON NULL INPUT
SECURITY INVOKER
COST 100;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511027",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: ScrollView steals focus when scrolling I am trying to make a chatting window.
There's a TextView wrapped in a ScrollView in the upper side of the screen; and a EditText in the bottom of the screen.
I use following code to make the ScrollView scroll automatically when the new message is out of view.
scroll.post(new Runnable(){
@Override
public void run() {
scroll.fullScroll(View.FOCUS_DOWN);
}
});
Something annoying is when the ScrollView scrolls, it steals my focus from the EditText.
I can't input my message when the ScrollView is scrolling.
Can anybody give me some light? Thanks a lot : )
A: I know a workaround. Call requestFocus on the view that should keep the focus.
It would be nice to know if you solved it in a better way.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511028",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: NSDictionaryController and image I am referring to this example code. I am trying to display image in the first column at where lastName is displaying, but unfortunately I can't.
A: I think you can do it in two ways-
*
*The data-source - peopleList array contains dictionary which does not have any NSImage object. You can try adding a NSImage object to the dictionary and then display it through bindings.
*You can use - tableView:willDisplayCell:forTableColumn:row: in NSTableViewDelegate and for the lastName tablecolumn identifier, set appropriate image to the cell.
Also, since you are a beginner, I would like to refer a simpler example to you : http://dl.dropbox.com/u/9999259/SimpleTable.zip
Hope this helps !
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511029",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Getting remainding lines in a CSV I have a script here which will get all the lines in a csv and insert them into a database (FileMaker to be exact), and I want it to count to 100 lines, break the loop, then tell me the remainding lines which are left. My code is below, Please see and any help would be greatly appreciated.
public function insertTimesheet() {
//Get the public variables
$fm = $this->fm;
$timesheet = $this->data['timesheets'];
$total = count($timesheet);
$fm = $this->fm;
$count = 0;
$total = count($timesheet);
//Loop through the data items in the array
foreach ($timesheet as $element) {
//Checks each key value in the array
for ($i = 0; $i < count($timesheet); ++$i) {
if($i == 100){
printf('%d Timesheets added', $i);
break;
// Return which timesheets have not been added //
}
//Prevents duplicate entries
$count++;
//Manually add some data to the array
$timesheet[$i]['Created_By_Staff_ID'] = $_SESSION["user"]->staff_id;
$timesheet[$i]['Key_Staff_ID'] = $_SESSION["user"]->staff_id;
$timesheet[$i]['Timesheet_Type'] = 'CSV_UPLOAD';
$timesheet[$i]['Resource_ID'] = 'N/A At this time [CSV UPLOAD]';
//Convert the dates to USA dates (FileMaker Format)
$timesheet[$i]['Date_From'] = $this->convertDate($timesheet[$i]['Date_From']);
$timesheet[$i]['Date_To'] = $this->convertDate($timesheet[$i]['Date_To']);
//Insert the data into the Database
$addReq = & $fm->createRecord('Web_Staff_Timesheet', $timesheet[$i]);
$result = $addReq->commit();
//Checks for filemaker errors
if (!FileMaker::isError($result)) {
$return['error'] = false;
$return['msg'] = 'Timesheet added successfully';
$strOut = sprintf('<br />Working on %d of %d timesheets', $count, $total);
//return true;
} else {
$return['error'] = true;
$return['errorCode'] = $result->code;
$return['msg'] = 'Unable to add Timesheet';
$strOut = sprintf('<br />Sorry, we could not add your time sheet, FileMaker Produced this error: %s <br /> Failed to insert the following timesheets [Line number]: ', $return['errorCode'], $count);
return false;
}
}
break;
}
//Clear the array to prevent duplicates
unset($timesheet, $element, $this->data);
return $strOut;
}
A: Just FYI guys, I've sorted it out now. Thanks for your time anyways!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511031",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using jQuery .ajax for a voting script. How do I update MySQL DB after successful vote? I'm assuming I have to put something in the success option. However what I have isn't working.
I declare this JS function on the page:
<script type="text/javascript">
function performAjaxSubmission() {
$.ajax({
url: 'addvotetotable.php',
method: 'POST',
data: {
},
success: function() {
}
});
}
</script>
Then in the ajax call which is working properly I declare this for the success:
success: function(data) {
performAjaxSubmission();
},
addvotetotable.php looks like:
<
?php
// If user submitted vote give the user points and increment points counter
require_once("models/config.php");
//Check to see if there is a logged in user
if(isUserLoggedIn()) {
$username_loggedin = $loggedInUser->display_username;
}
if (strlen($username_loggedin)) {
include_once "scripts/connect_to_mysql.php";
$query = mysql_query("SELECT vote FROM points_settings WHERE id=1")or die (mysql_error());
while($info = mysql_fetch_array($query)){
$points_value=$info['vote'];
}
include_once "scripts/connect_to_mysql.php";
$query = mysql_query("INSERT INTO points (id,username,action,points) VALUES ('','$username_loggedin','vote','$points_value')")or die (mysql_error
());
include_once "scripts/connect_to_mysql.php";
$query = mysql_query("UPDATE userCake_Users SET points=points + $points_value WHERE Username='$username_loggedin'")or die (mysql_error());
}
?>
A: You have to provide a value that you want to store in your database in the "data" of the ajax-request. Than you can use this in your php-code using $_POST["something"], check if it's valid... and return f.e. html or json which you than handle in the success-function.
<script type="text/javascript">
function onSubmitVote()
{
$.ajax({
url: 'addvotetotable.php',
method: 'POST',
data: "theVoteValue=" + <read_your_vote_value_here>,
success: function(result) {
>>>return something in your addvotetotable.php which indicate success and show a message whether the vote was successful or not.<<<
}
});
return false; // prevent submit if it is a submit-type button.
}
</script>
What this does is post data of the vote (it's value) to the php-file. There you can read it with $_POST["theVoteValue"] and put it in the database. You check if the value is valid and may insert, else you return an error-message or something so that in javascript you can notify the user of it's failure.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511047",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: set view text align at center in spinner in android view-text-in-the-center-of-the-spinner-when-select-from-the-drop-down-list
I want to align the view text of spinner to center. I google it but didn't find anything, does anybody knows about this? any help or suggestion are appreciated
A: Create a adapter for your spinner like this,
ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, R.layout.my_spinner_style,array_of_values) {
public View getView(int position, View convertView,ViewGroup parent) {
View v = super.getView(position, convertView, parent);
((TextView) v).setTextSize(16);
return v;
}
public View getDropDownView(int position, View convertView,ViewGroup parent) {
View v = super.getDropDownView(position, convertView,parent);
((TextView) v).setGravity(Gravity.CENTER);
return v;
}
};
Now your layout R.layout.my_spinner_style,
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+android:id/text1"
style="?android:attr/spinnerItemStyle"
android:singleLine="true"
android:textColor="#ffffff"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee" />
Now set this adapter to your spinner,
spinner.setAdapter(adapter);
A: This works without layout changes
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
((TextView) adapterView.getChildAt(0)).setGravity(Gravity.CENTER);
}
});
A: You need to set your own layout for spinner item.
SpinnerAdapter adap = new ArrayAdapter<String>(this, R.layout.spinner_item, new String[]{"A", "B", "C"});
spriner.setAdapter(adap);
Where R.layout.spinner_item is a layout with content:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:gravity="center"
android:textColor="#000000"
android:text="Sample Text"
android:paddingBottom="5dp"
android:paddingTop="5dp"></TextView>
A: Add this line in Spinner
android:textAlignment="center"
Voila!
A: Late to the game, but I wanted to add this for future users just because I found it a simple solution for my problem. It allowed me to center simple text without creating a custom layout. The way I did this was using padding
<Spinner
android:id="@+id/example_spinner"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="2dp"
android:paddingBottom="2dp" />
I was successful in centering my text within my spinner using this method. This will likely only work for simple cases, but you would probably want to use a custom layout for more complex cases anyway. This is just to keep your xml files down and avoid having to use a custom layout just to center a simple spinner.
A: This is very simple. Just create a xml file named as, for example, spinner_item.xml with content as
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#111111"
android:padding="10dp"
android:textAlignment="center"
/>
Now in your Java class, instead of adding Android's default view resource add your custom view resource as
ArrayAdapter<String> adapter= new ArrayAdapter<String>(context, R.layout.spinner_item, myList);
adapter.setDropDownViewResource(R.layout.spinner_item);
The textAlignment line will do the trick.
A: Setting textAlignment to center will place the text in center.
android:textAlignment="center"
<android.support.v7.widget.AppCompatSpinner
android:id="@+id/spinner_areas"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:visibility="visible"
android:gravity="center"
android:textAlignment="center"/>
A: Simple as this!
<Spinner
android:textAlignment="center"
/>
A: I found it slightly easier to edit the theme than to create an adapter. In my fragment_first.xml I have my spinner
<Spinner
android:theme="@style/mySpinnerStyle"
android:id="@+id/spnnr"
android:layout_width="350dp"
android:layout_height="75dp"
android:layout_marginBottom="32dp"
android:spinnerMode="dropdown"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0" />
I then created a new @style resource in values (recommended by Kotlin).
<style name="mySpinnerStyle" parent="@android:style/Widget.Holo.DropDownItem.Spinner">
<item name="android:textSize">@dimen/ssp</item>
<item name="android:textAlignment">center</item>
</style>
<dimen name="ssp">24sp</dimen>
points to Farid here for pointing me along. https://stackoverflow.com/a/64193198/15078702
A: Let me complete answer. It is also important to make space in Spinner.
Wrong:
<Spinner
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
Right:
<Spinner
android:id="@+id/spinner"
android:layout_width="100dp"
android:layout_height="wrap_content"
/>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511049",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "45"
} |
Q: Codeigniter sorting array values after array_unique I'm trying to use sort function for an array after array_unique function but I'm getting below error:
A PHP Error was encountered
Severity: Warning
Message: implode() [function.implode]: Invalid arguments passed
Filename: controllers/admin.php
Line Number: 250
Below is my loop function. How can I sort by value ascending?
foreach ($bars as $bar){
$explode = explode(',',$bar->date_id);
$i = 0;
$b = array();
foreach($explode as $bars){
$bars = intval($bars);
@$b[$i] .= $bars;
$i++;
}
$date_id = array_unique($b);
$date_id = sort($date_id);
echo "<pre>";
print_r($date_id);
echo "</pre>";
$date_id = implode(',',$date_id);
echo "<pre>";
print_r($date_id);
echo "</pre>";
}
A: Among other things that look awry with your code, sort() returns TRUE or FALSE, not the sorted array.
Instead of this:
$date_id = array_unique($b);
$date_id = sort($date_id);
Use this:
$date_id = array_unique($b);
sort($date_id);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511053",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Package versioning policy - Harmless type changes? The package versioning policy specifies that changing the type of any entity makes a change of the B number in A.B.C necessary.
However, it seems to me that some type changes don't break dependent code. In particular, consider the following example, where I drop a Typeable class constraint:
- foo :: Typeable a => AddHandler a -> NetworkDescription (Event a)
+ foo :: AddHandler a -> NetworkDescription (Event a)
So, my question is:
Can removing a type class constraint on a function break dependent code? Should I change the B number or just the C in version A.B.C when introducing this change?
A: I have replied on -cafe, but I’ll also put my answer here:
You should bump the C number. The PVP, rule 2, specifies that an API addition implies that the C part of the version is to be increased. Removing a constraint behaves like adding a new function: Code that worked before continues to work, but code written against the new API might not work against the old one.
So if a programmer develops code against version 0.1.2 of foo, he’d specify foo >= 0.1.2 && < 0.2 as the requirement. He does not expect his code to work against foo-0.1.1. This works fine with removing the constraint.
A:
Can removing a type class constraint on a function break dependent code?
No, I don't believe so. Here's my reasoning. It's common to think of constraints as an additional function argument: a typeclass dictionary which is passed implicitly. You can think slightly more general than that, and imagine that constraints are a record of evidences which is passed implicitly. Thus, the type Foo can be thought of as {} -> Foo, where {} indicates an empty record of implicit evidences. It is irrelevant whether Foo itself is a function or not.
Now, suppose that our API promises to deliver something of type
{SomeConstraint} -> Foo
But what we actually deliver is
{} -> Foo
Well, record subtyping tells us that
{SomeConstraint} <: {}
therefore function subtyping tells us that
({} -> Foo) <: ({SomeConstraint} -> Foo)
therefore, anywhere in someone's program that we find a hole with the shape {SomeConstraint} -> Foo, we can plug in a {} -> Foo. In other words, nothing breaks. The user gives us evidence that SomeConstraint is satisfied, and we just ignore it.
At first I thought that weird corner cases in type inference might cause problems, but I cannot think of any examples where this is actually the case. So this thought was proven wrong by exhaustion of imagination.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511060",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: How to pass the value into the view I writed a plugin that start from the file,
I want to pass the file context into a view,
Anybody can tell me how to pass the context into the view?
A: Normally you pass the objects between editors using 'EditorInput'. Create a POJO class extending EditorInput and then pass it as a parameter when you opening a new editor:
protected void openSingleObjectEditor(final IEditorInput input,final String editorID){
IWorkbenchPage page;
page = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
.getActivePage();
try {
page.openEditor(input, editorID);
} catch (PartInitException e) {
e.printStackTrace();
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511062",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PostgreSQL - Aliases column and HAVING SELECT
CASE WHEN SUM(X.Count)*3600 is null THEN '0'
ELSE
SUM(X.Count)*3600
END AS PJZ,
X.Mass
FROM X
WHERE X.Mass > 2000
HAVING ((X.Mass / PJZ * 100) - 100) >= 10;
Getting: ERROR: Column »pjz« doesn't exists.
How can I do something like this?
A: Other option is to surround query by WITH statement - for example:
WITH x as (
SELECT coalesce(SUM(X.Count)*3600, 0) AS PJZ, X.Mass
FROM X
WHERE X.Mass > 2000
)
SELECT * from X WHERE PJZ >=10
It is far better then code duplication in my opinion
A: Wrap it into a derived table:
SELECT CASE
WHEN PJZ = 0 THEN 100
ELSE PJZ
END as PJZ,
mass
FROM (
SELECT CASE
WHEN SUM(X.Count)*3600 is null THEN '0'
ELSE SUM(X.Count)*3600
END AS PJZ,
X.Mass
FROM X
WHERE X.Mass > 2000
GROUP BY X.mass
) t
WHERE PJZ = 0
OR ((X.Mass / PJZ * 100) - 100) >= 10;
(Note that I added the missing group by as otherwise the query would not be valid)
A: You can't use aliases in a having, and have to duplicate the statement in the having cluause. Since you only want to check for null, you could do this:
SELECT coalesce(SUM(X.Count)*3600, 0) AS PJZ, X.Mass
FROM X
WHERE X.Mass > 2000
HAVING ((X.Mass / coalesce(SUM(X.Count)*3600, 0) * 100) - 100) >= 10;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511064",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: setting session or php variable in javascript? i am doing a simple html form for two languages(English & Hindi) so i show the link for both language for ex <a href="#"> English </a> / <a href="#">Hindi after that i need to display the form with corresponding language what user clicked one of the hyperlink. so here how do i find out which language link is clicked?
<a href="#"> English </a> / <a href="#">Hindi
<? if($_SESSION['language']=='English'){ ?>
<form action="" method="post" name="englishform">
......
</form>
<? } else { ?>
<form action="" method="post" name="hindiform">
......
</form>
<? } ?>
A: You can not change PHP code with java script. As PHP code is run on server. Sent to client and then a java script can be run on the result. So you have two options:
Either send both forms. Use css to hide both. An onclick show the corresponding form.
Or the AJAX soltion. Then the user clicks on the link. Use java script to fetch the form from the server (an other URL) and show in in the page.
A: You could add a hidden field to both forms, containing the selected language.
<form action="" method="post" name="englishform">
<input type="hidden" name="language" value="en" />
...
</form>
<form action="" method="post" name="hindiform">
<input type="hidden" name="language" value="hi" />
...
</form>
A: Well, assuming you just want to hide or show a different form based on the hyperlink:
<a class="switcher" rel="englishform" href="#"> English </a> / <a class="switcher" rel="hindiform" href="#">Hindi</a>
<form action="" method="post" id="englishform" style="display:none">
......
</form>
<form action="" method="post" id="hindiform" style="display:none">
......
</form>
<script>
$("a.switcher").click(function(e){
var name = $(this).attr("rel");
$("#" + name).show();
e.preventDefault();
});
</script>
A: I don't know javascript well enough, but if you get jQuery you can do the following:
<a href="en">English</a> / <a href="hi">Hindi</a>
<form action="" method="post" data-lang="en">
...
</form>
<form action="" method="post" data-lang="hi">
...
</form>
jQuery: (needs to be specified more on your actual page or it will target all links and forms)
$('a').click(function(e){
e.preventDefault();
$('form').hide();
$('form[data-lang="'+$(this).attr('href')+'"]').show();
});
Or without jQuery:
<? if(!$_GET['lang'] || ($_GET['lang'] != "en" && $_GET['lang'] != "hi")){ ?>
<a href="form.php?lang=en">English</a> / <a href="form.php?lang=hi">Hindi</a>
<? }elseif($_GET['lang'] == "en"){ ?>
<form action="" method="post">
...
</form>
<? }elseif($_GET['lang'] == "hi"){ ?>
<form action="" method="post" data-lang="hi">
...
</form>
<?
}
?>
A: <html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.js"></script>
<script type="text/javascript">
$(function() {
$("#showEnglishForm").click(function()
{
$("#hindiFormDiv").hide();
$("#englishFormDiv").show();
});
$("#showHindiForm").click(function()
{
$("#hindiFormDiv").show();
$("#englishFormDiv").hide();
});
});
</script>
</head>
<body>
<a href="#" id="showEnglishForm">show English form</a>
<a href="#" id="showHindiForm">show Hindi form</a>
<div id="englishFormDiv" style="display:none;">
<h3>English form</h3>
<form action="" method="post" name="englishForm">
...
</form>
</div>
<div id="hindiFormDiv" style="display:none;">
<h3>Hindi form</h3>
<form action="" method="post" name="hindiForm">
...
</form>
</div>
</body>
</html>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511069",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Add or Update object from a form GAE python I try to create a class which will add data from a form to a db.model, but my problem is that when I will try to add an existing book, I want to update the copies and not to add a new object. I really try to find an answer, I read books for programming in GAE, but I find nothing for my problem.
Thank you in advance and I will really appreciate if someone answer with a sample code and not with just a command ( eg try get_by_id()).
Here is a part of my source
class Book(db.Model):
book_id = db.IntegerProperty()
title = db.StringProperty()
author = db.StringProperty()
copies = db.IntegerProperty()
isbn = db.IntegerProperty()
copyright_date = db.StringProperty()
category = db.StringProperty()
comments = db.StringProperty()
class Add(webapp.RequestHandler): #Form to input data
def get(self):
self.response.out.write("""
<html>
<body>
<form action="/sign" method="post">
<table border="0">
<tr>
<td>ISBN:</td> <td><input type="text" name="isbn"</td>
</tr>
<tr>
<td>Title:</td> <td><input type="text" name="title"</td>
</tr>
<tr>
<td>Author:</td> <td><input type="text" name="author"</td>
</tr>
<tr>
<td>Copies:</td> <td><input type="text" name="copies"</td>
</tr>
<tr>
<td>Copyright Date:</td> <td><input type="text" name="copyright_date"</td>
</tr>
<tr>
<td><div>Category:</td> <td><select>
<option name="category" value="adventure">Adventure</option>
<option name="category" value="comedy">Comedy</option>
<option name="category" value="dramatic">Dramatic</option>
<option name="category" value="mystery">Mystery</option>
<option name="category" value="science_fiction">Science Fiction</option></select></td>
</tr>
<tr><td>Comments:</td></tr></table>
<div><textarea name="comments" rows="5" cols="40" value="Add your comments here"></textarea></div>
<div><input type="submit" value="Add Book">
<input type="reset" value="Reset"></div>
</form>
</body>
</html>""")
class Guestbook(webapp.RequestHandler):
def post(self):
book = Book()
book.isbn = int(self.request.get('isbn'))
book.title = self.request.get('title')
book.author = self.request.get('author')
book.category = self.request.get('category')
book.copies = int(self.request.get('copies'))
book.copyright_date = self.request.get('copyright_date')
book.put()
class Stock(webapp.RequestHandler):
def get(self): #Retrieve all data from DataBase (Here is the StockHouse)
Book = db.GqlQuery("SELECT * FROM Book ")
for book in Book:
print book.book_id, book.isbn, book.title, book.author, book.category, book.copyright_date, book.copies, book.comments
A: in order to update an existing entry you'll need a different handler that will take the post arguments as well as the id or key of the entity to update. Usually this is in the url, e.g:
POST /updateentity/id
and then in the handler:
def get(self, id):
existing = Model.get_by_id(long(id))
model.field = self.request.get("field")
model.put()
A: You can use get_or_insert Model method. Also see this question.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511071",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JSF/JSP - Beginner Question I've recently dipped my toes into JBoss Seam and naturally have ton to learn but having had a hands on approach so far with looking at code and trying to write my own seam applications I've looking for understanding on below:
I've come across the following peace of code which i cannot see what it is trying to do which is triggered is called when user clicks a button:
<h:commandButton value="Save" type="button" onclick="return userAction(this);" title="User Actions">
<f:param value="#{user.codePk}" name="userCode"/>
<h:inputHidden value="#{user.codePk}" id="code"/>
</h:commandButton>
which calls a javascript function that open a window to display stock on hand:
var pk = document.getElementById("product:code").value;
window.open('<%=basePath1%>jsp/stockOnHand.faces?Code='+pk,"abcd");
I know that stockOnHand.faces is just stockOnHand.jsp and that stockOnHand.jsp contains has a table where stock on hand of a given product is shown in all stores.
I don't get how the part from ?Code='+pk,"abcd" works. Is it similar to how it is done in Java where you can pass parameters to a function matching its signature for example
foo(int v, string s);
I hope this isn't too ambiguous.
A: It is just a string concatenation. The JS window.open function has the following signature:
open (URL, windowName[, windowFeatures])
The first argument URL in your example is a concatenation of the given string and the variable pk. The second argument windowName is abcd.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511072",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Passing Params to a page in key-value pair in CodeIgniter I am using CodeIgniter, and I am new to it.
I came to know that I can pass parameters to another page like http://example.com/users/list/param1/param2/param3/.... and so on.
Now on the destination php script, I can get it as $this->uri->segment(2) , but I must know that which location it is in the uri. Say I am getting param2 , I must know that it is uri segment 4. This is a great pain for me. I previously worked with ZEND , where we send parameters like
http://examples.com/controller/action/key/value/key/value , Now in this case I can always dynamic number of parameters and I don't need to know their location in the uri, but I just need to know the key.
Qestion : Is there a way where I can pass parameters using GET in key-value pairs in codeigniter, like the one ZEND do?
A: Take a look at the function $this->uri->uri_to_assoc(n) in the URI class. It will take in your url segments as an associative array. You could then check whether the keys are present in it or not.
Example and full explanation in the user guide.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511075",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: variable not passed to predicate method in ANTLR The java code generated from ANTLR is one rule, one method in most times. But for the following rule:
switchBlockLabels[ITdcsEntity _entity,TdcsMethod _method,List<IStmt> _preStmts]
: ^(SWITCH_BLOCK_LABEL_LIST switchCaseLabel[_entity, _method, _preStmts]* switchDefaultLabel? switchCaseLabel*)
;
it generates a submethod named synpred125_TreeParserStage3_fragment(), in which mehod switchCaseLabel(_entity, _method, _preStmts) is called:
synpred125_TreeParserStage3_fragment(){
......
switchCaseLabel(_entity, _method, _preStmts);//variable not found error
......
}
switchBlockLabels(ITdcsEntity _entity,TdcsMethod _method,List<IStmt> _preStmts){
......
synpred125_TreeParserStage3_fragment();
......
}
The problem is switchCaseLabel has parameters and the parameters come from the parameters of switchBlockLabels() method, so "variable not found error" occurs.
How can I solve this problem?
A: My guess is that you've enabled global backtracking in your grammar like this:
options {
backtrack=true;
}
in which case you can't pass parameters to ambiguous rules. In order to communicate between ambiguous rules when you have enabled global backtracking, you must use rule scopes. The "predicate-methods" do have access to rule scopes variables.
A demo
Let's say we have this ambiguous grammar:
grammar Scope;
options {
backtrack=true;
}
parse
: atom+ EOF
;
atom
: numberOrName+
;
numberOrName
: Number
| Name
;
Number : '0'..'9'+;
Name : ('a'..'z' | 'A'..'Z')+;
Space : ' ' {skip();};
(for the record, the atom+ and numberOrName+ make it ambiguous)
If you now want to pass information between the parse and numberOrName rule, say an integer n, something like this will fail (which is the way you tried it):
grammar Scope;
options {
backtrack=true;
}
parse
@init{int n = 0;}
: (atom[++n])+ EOF
;
atom[int n]
: (numberOrName[n])+
;
numberOrName[int n]
: Number {System.out.println(n + " = " + $Number.text);}
| Name {System.out.println(n + " = " + $Name.text);}
;
Number : '0'..'9'+;
Name : ('a'..'z' | 'A'..'Z')+;
Space : ' ' {skip();};
In order to do this using rule scopes, you could do it like this:
grammar Scope;
options {
backtrack=true;
}
parse
scope{int n; /* define the scoped variable */ }
@init{$parse::n = 0; /* important: initialize the variable! */ }
: atom+ EOF
;
atom
: numberOrName+
;
numberOrName /* increment and print the scoped variable from the parse rule */
: Number {System.out.println(++$parse::n + " = " + $Number.text);}
| Name {System.out.println(++$parse::n + " = " + $Name.text);}
;
Number : '0'..'9'+;
Name : ('a'..'z' | 'A'..'Z')+;
Space : ' ' {skip();};
Test
If you now run the following class:
import org.antlr.runtime.*;
public class Main {
public static void main(String[] args) throws Exception {
String src = "foo 42 Bar 666";
ScopeLexer lexer = new ScopeLexer(new ANTLRStringStream(src));
ScopeParser parser = new ScopeParser(new CommonTokenStream(lexer));
parser.parse();
}
}
you will see the following being printed to the console:
1 = foo
2 = 42
3 = Bar
4 = 666
P.S.
I don't know what language you're parsing, but enabling global backtracking is usually overkill and can have quite an impact on the performance of your parser. Computer languages often are ambiguous in just a few cases. Instead of enabling global backtracking, you really should look into adding syntactic predicates, or enabling backtracking on those rules that are ambiguous. See The Definitive ANTLR Reference for more info.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511077",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Set Label control on BezierSegment path I understand the concept of drawing the path using BezierSegment.
However, can I set label control position onto the path? Thks!!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511082",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Conditional MySQL INSERT if record number is set at specific number I'm creating a simple session based app in PHP/MySQL. I'm storing a session for each user connected to app in mysql table with their associated session_id. What I want to do is stop recording once a certain specified number of records are inserted in table. Is it possible in MySQL?
Below is a sample query that I thought would work, but it doesn't.
$dbSessionQ = "INSERT INTO `connSessions` (`sessID`, `expiry`) VALUES ('" . session_id() . "', '3600')";
$dbSessionQ .= "WHERE (SELECT COUNT(`sessID`) FROM `connSessions` < 5001) LIMIT 1";
A: I don't think INSERT has a WHERE clause.
To start with, you can first query for the count and then do the insert. (Split the SELECT and the INSERT statements). Once you've figured that out, use a simple transaction to eliminate race conditions.
A: You could use INSERT...SELECT for this. Something like
INSERT INTO `connSessions` (`sessID`, `expiry`)
SELECT '" . session_id() . "', '3600' FROM `connSessions`
WHERE (SELECT COUNT(`sessID`) FROM `connSessions`) < 5001
But since you are not selecting something from connSessions I do not really see what you want to do here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511085",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Difference between No-Interface View and Interface View in EJB What is difference between No-Interface View and Interface View in EJB?
Advantages and disadvantages of both of them.
A: AFAIK EJB 3.1 no-interface view means that the local interface or proxy is implicitly generated by the container, i.e. all public methods of the bean are exposed.
In contrast, providing an explicit interface allows you to specify which methods are actually exposed and how the interface is named.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511086",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Composite key in Hibernate Annotations confusion I have two tables say 'A' and 'B'. A third table 'C' has two columns that directly refer to 'A' and 'B' i.e. 'C' contains 'A_id' and 'B_id' that refer to A's id and B's id respectively. There is unique key defined on 'A_id' and 'B_id'. But there is no id column in 'C'. How can I go about defining the model class for 'C' without altering the schema for 'C'. I am very new to using Hibernate annotations so please help me out. 'A' and 'B' have other columns as well and have their model classes already defined.
A: It looks to me like C is just a join table. There is no need to map C explicitly. You can map relation from A to B or vice versa using @JoinTable annotation. Please take a look at the example at One To Many Join Table Setup. There is no mapping for EMP_PHONE, it is just a join table between phone and employee.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511092",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: java .lang.IllegalArgumentException: PWC1430: Unable to add listener of type How do you make sense of exceptions like this? It doesn't add up because the CatalogFacade does compile fine, and By the way, I do implement the classes they ask for. "Any of" seems like it's not needed to have all of them.
Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: java.lang.IllegalArgumentException: java.lang.IllegalArgumentException:
Which is Inside this surrounding error message, that seems a bit vague:
[exec] remote failure: Error occurred during deployment: Exception while lo
ading the app : java.lang.IllegalStateException: ContainerBase.addChild: start:
org.apache.catalina.LifecycleException: java.lang.IllegalArgumentException: java
.lang.IllegalArgumentException: PWC1430: Unable to add listener of type: com.sun
.javaee.blueprints.petstore.model.CatalogFacade, because it does not implement a
ny of the required ServletContextListener, ServletContextAttributeListener, Serv
letRequestListener, ServletRequestAttributeListener, HttpSessionListener, or Htt
pSessionAttributeListener interfaces. Please see server.log for more details.
[exec] Command deploy failed.
BUILD FAILED
C:\LatestPS\trunk\ws\bp-project\app-server-ant.xml:379: exec returned: 1
I've been trying things all night . It's not clear.
By the way, to the best of my knowledge..there's nothing significant at app-server-ant.xml:379..
Here's the Full log(I know it's quite big):
Some more of files are here : http://www.adelazzam.com/so.html
A: The problem is there in the error-message. The <listener> you specify in your web.xml, CatalogFacade does not implement the required Listener interface, specified by the servlet specification.
Check the implementation of your CatalogFacade. Depending on what type of listener it should be (that is, what lifecycle events should it be notified of) it must implement one of ServletContextListener, ServletContextAttributeListener, ServletRequestListener, ServletRequestAttributeListener, HttpSessionListener, or HttpSessionAttributeListener.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511097",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Loading images only one time per spring webapp I need to load a bunch of images into my Spring webapp. For performance reasons this should only be done after starting the webapp. The images should be saved in a singleton to access from multiple users, sessions etc
I already build a Java Bean with an initalizer that loads the images, in my controller I inject this bean and get the images. Works, but injecting isn't the right thing for this.
How can I build a singleton bean to hold the images and only load the images one time per webapp?
A: Have you considered using EhCache built-in web caching? Just add it to your web.xml:
<filter>
<filter-name>pageCachingFilter</filter-name>
<filter-class>net.sf.ehcache.constructs.web.filter.SimpleCachingHeadersPageCachingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>pageCachingFilter</filter-name>
<url-pattern>*.htm</url-pattern>
<url-pattern>*.js</url-pattern>
<url-pattern>*.png</url-pattern>
<url-pattern>*.gif</url-pattern>
<url-pattern>*.jpg</url-pattern>
<url-pattern>*.css</url-pattern>
</filter-mapping>
And configure SimplePageCachingFilter cache in your ehcache.xml:
<cache name="SimplePageCachingFilter"
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="31536000"
timeToLiveSeconds="31536000"
overflowToDisk="false"
memoryStoreEvictionPolicy="LRU"
statistics="true"
/>
EhCache will now intercept all client-side requests for static resources, read them once, put them in cache and return to the user. To make it even better, it will even add HTTP Expiry headeres so the client won't call you again for the same resource.
Isn't this approach better compared to manually-written loading and caching in a singleton?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511098",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: DOMDocument escaping end chars in PHP I have a problem with class DOMDocument. I use this php class to edit a html template. I have in this template this meta tag:
<meta http-equiv="Content-type" content="text/html;charset=UTF-8"/>
But after editing, although I was not editing this tag, it escapes the end char "/" and it doesn't work.
This is the script:
$textValue = $company.'<br />'.$firstName.' '.$lastName.'<br />'.$adress;
$values = array($company, $firstName.' '.$lastName, $adress);
$document = new DOMDocument;
$document->loadHTMLFile($dir.'temp/OEBPS/signature.html');
$dom = $document->getElementById('body');
for ($i = 0; $i < count($values); $i++) {
$dom->appendChild($document->createElement('p', $values[$i]));
}
$document->saveHTMLFile($dir.'temp/OEBPS/signature.html');
echo 'signature added <br />';
A: Please see the answer provided by this question: Why doesn't PHP DOM include slash on self closing tags?
In short, DOMDocument->saveHTMLFile() outputs its internal structure as regular old HTML instead of XHTML. If you absolutely need XHTML, you can use DOMDocument->saveXMLFile() which will use self-closing tags. The only problem with this method is some HTML tags cannot use self-closing tags like <script> and <style> so you have to put a space in their content so that they don't use self-closing tags.
I would recommend just ignoring the issue unless it is mandatory that you fix it. Self-closing tags are a relic of XHTML and are unused in HTML5.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511100",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Changing the underlying type of an enumeration to long
Possible Duplicate:
C# int, Int32 and enum's
C# allows you to set the underlying type of an enumeration to long. But, how would you explain the difference in behavior when you try to compile the following two statements:
public enum Colors : long
{
Blue = 512L,
Purple = 1024L
}
and
public enum Colors : System.Int64
{
Blue = 512L,
Purple = 1024L
}
The first one compiles oK (with : long), while the second (with : System.Int64) wont compile - you get an error: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected Note: Obviously, I understand the error message. What has me baffled is that I thought that "long" is more or less an alias for "Int64"
A: It is a limitation of the C# compiler and support for this on Enum will not be introduced. You will have to use long. Alex Turner (a Program Manager for Visual Basic and C#) at MSFT:
Posted by Microsoft on 6/25/2010 at 8:53 AM
Thanks for the suggestion for Visual Studio!
As you point out, we could enable support for saying Int16 instead of int here, but this would not provide any extra expressiveness to C# programs (and it's more characters to type!). We'd be unlikely to invest our resources to add this support to Enums.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511102",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Android: Unit Test: How can I create unit test with SensorManager? I have plain Jar Project that reference by android application.
Then, I have Functions.java for my common functions which I want to create unit test class.
Here are the sample functions inside the Functions.java:
public static double getAltitudeBySensor(float atmosphericPressure) {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD
&& atmosphericPressure > 0d) {
return SensorManager.getAltitude(SensorManager.PRESSURE_STANDARD_ATMOSPHERE, atmosphericPressure);
}
return 0d;
}
public static double toPixelX(double imageSize, android.location.Location upperLeft, android.location.Location lowerRight, android.location.Location target) {
double hypotenuse = upperLeft.distanceTo(target);
double bearing = upperLeft.bearingTo(target);
double currentDistanceX = Math.sin(bearing * Math.PI / OneEightyDeg) * hypotenuse;
// "percentage to mark the position"
double totalHypotenuse = upperLeft.distanceTo(lowerRight);
double totalDistanceX = totalHypotenuse * Math.sin(upperLeft.bearingTo(lowerRight) * Math.PI / OneEightyDeg);
double currentPixelX = currentDistanceX / totalDistanceX * imageSize;
return currentPixelX;
}
Any guidance on the right direction is appreciated.
A: Both methods have dependencies on external code so will be difficult to unit test.
If you really want to unit test just the logic then you'll need to refactor so they depend on interfaces and then build mocks that implement those interfaces so you can pass in known data and test if you receive the appropriate output
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511110",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What are all the possible languages to create a mobile phone application? I know j2me , Android for creating mobile phone applications. What are the other languages ?
A: Just about anything. There's frameworks and SDKs for Javascript (Phonegap, NimbleKit, Unity 3D), Flash, Lua, C/C++, and Objective-C (of course). There's many more projects to bring other languages to mobile platforms.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511112",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: maven scm:checkin error My maven script generates a laconic "error 1", and I am a bit at a loss as to how to extract the root cause from the huge output.
Could you help me in isolating said root cause for this error?
Here is the command I used:
mvn scm:checkin -Dmessage="check in"
error 1.
List item [DEBUG] Configuring mojo 'org.apache.maven.plugins:maven-scm-plugin:1.5:checkin' with basic configurator --> [DEBUG] (f)
basedir = E:\workspace\mtest [DEBUG] (f)
connectionType = developerConnection [DEBUG] (s)
connectionUrl = scm:svn:https://192.168.10.44/svn/FTMobileAdNetwork/trunk/personal/xuhuiw/mvntest/mtest/
[DEBUG] (f) developerConnectionUrl = scm:svn:https://192.168.10.44/svn/FTMobileAdNetwork/trunk/personal/xuhuiw/mvntest/mtest/
[DEBUG] (s) includes = src/*,pom.xml
[DEBUG] (f) message = check in my mtest [DEBUG] (f) password = wangxuhui [DEBUG] (f) pushChanges = true
[DEBUG] (f) settings = org.apache.maven.execution.SettingsAdapter@2d0479
[DEBUG] (f) username = xuhuiw
[DEBUG] (s) workingDirectory = E:\workspace\mtest [DEBUG] -- end configuration --
[INFO] Executing: cmd.exe /X /C "svn --username xuhuiw --password ***** --no-auth-cache --non-interactive commit --file C:\Users\xuhuiw\AppData\Local\Temp\maven-scm-2074558159.commit --targets C:\Users\xuhuiw\AppData\Local\Temp\maven-scm-5719724778329125171-targets"
[INFO] Working directory: E:\workspace\mtest
[ERROR] Provider message:
[ERROR] The svn command failed.
[ERROR] Command output:
[ERROR] svn: 'E:\workspace\mtest' is not a working copy
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-scm-plugin:1.5:checkin (default-cli) on project mtest: Command failed.The svn command failed. ->
[Help 1] org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-scm-plugin:1.5:checkin (default-cli) on project mtest: Command failed.
The svn command failed. at
org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:217) at
org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153) at
org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145) at
org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84) at
org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59) at
org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183) at
org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161) at
org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:319) at
org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156) at
org.apache.maven.cli.MavenCli.execute(MavenCli.java:537) at
org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196) at
org.apache.maven.cli.MavenCli.main(MavenCli.java:141) at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at
java.lang.reflect.Method.invoke(Method.java:597) at
org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290) at
org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230) at
org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409) at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352) Caused by:
org.apache.maven.plugin.MojoExecutionException: Command failed.The svn command failed. at
org.apache.maven.scm.plugin.AbstractScmMojo.checkResult(AbstractScmMojo.java:439) at
org.apache.maven.scm.plugin.CheckinMojo.execute(CheckinMojo.java:83) at
org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101) at
org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)
... 19 more
[ERROR]
[ERROR]
And here is my pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ftad.common.mtest</groupId>
<artifactId>mtest</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>mtest</name> <url>http://maven.apache.org</url>
<organization>
<name>众合广告</name>
</organization>
<properties>
<project.build.sourceEncoding>UTF-</project.build.sourceEncoding> </properties>
<scm>
<connection>scm:svn:https://192.168.10.44/svn/FTMobileAdNetwork/trunk/personal/xuhuiw/mvntest/mtest/</connection>
<developerConnection>scm:svn:https://192.168.10.44/svn/FTMobileAdNetwork/trunk/personal/xuhuiw/mvntest/mtest/</developerConnection>
</scm>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.7</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-scm-plugin</artifactId>
<version>1.5</version>
<configuration>
<password>wangxuhui</password>
<username>xuhuiw</username>
<basedir>./</basedir>
<exportDirectory>target</exportDirectory>
<includes>src/*,pom.xml</includes>
<workingDirectory>./</workingDirectory>
</configuration>
<executions>
<execution>
<id>pref-scm</id>
<configuration>
<includes>src/*,pom.xml</includes>
<checkoutDirectory>./</checkoutDirectory>
</configuration>
<goals>
<goal>checkin</goal>
<goal>checkout</goal>
<goal>update</goal>
<goal>add</goal>
<goal>validate</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
<distributionManagement>
<site>
<id>apache.website</id>
<url>scp://people.apache.org/www/maven.apache.org/scm/maven-scm-plugin</url>
</site>
<repository>
<id>releases</id>
<url>http://192.168.10.6:8081/nexus/content/repositories/releases</url>
</repository>
<snapshotRepository>
<id>snapshots</id>
<url>http://192.168.10.6:8081/nexus/content/repositories/snapshots</url>
</snapshotRepository>
</distributionManagement>
</project>
A: The important part is:
svn: 'E:\workspace\mtest' is not a working copy
So make sure your Maven task execute itself in an SVN working copy.
A: The directory you execute the scm:checkin from needs to be a svn working directory, which means you should have a ".svn" in that directory with the correct contents inside(the .svn is the svn admin directory which contains the pristine files downloaded).
Check if your .svn directory exists or if it's empty ( i found out that when I used "includes=*" in the checkout execution configuration, maven wipes out the .svn directory), which caused the subsequent scm:checkin to fail. And in your case, since you are using "includes=src/*,pom.xml", your .svn directory might not even exist.
To fix this, you can define execution for checkout in the maven-scm-plugin first (without using includes), then define a separate execution for add/check. And here's a pom.xml to do scm:checkout, curl download, then scm:checkin
http://mywallstreettechjob.blogspot.com/2015/06/maven-scm-plugin-pomxml-sample-for-svn.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511120",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android: dynamically choosing a launch activity doesn't always work I've read a few articles here (and other places) that describe how to dynamically choose which activity to show when launching an app. Below is my code:
AndroidManifest.xml
<activity android:name=".StartupActivity"
android:theme="@android:style/Theme.NoDisplay">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
StartupActivity.java
public class StartupActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent intent;
if (RandomClass.getSomeStaticBoolean())
{
intent = new Intent(this, ActivityOften.class);
}
else
{
intent = new Intent(this, ActivityRare.class);
}
startActivity(intent);
finish();
}
}
Both ActivityOften and ActivityRare are declared in the manifest (without the launcher category of course) and extend ListActivity and Activity respectively. 99% of the time the 1st activity to get shown is ActivityOften based on RandomClass.getSomeStaticBoolean().
So launching my app from the icon for the 1st time I break inside the StartupActivity.onCreate. The choice is properly made. But then any subsequent attempts to launch the app (from a shortcut or the apps menu) show the ActivityOften again. No further breaks occur inside the StartupActivity class. Despite the fact that I know that RandomClass.getSomeStaticBoolean() has changed value and that ActivityRare should appear, the 1st activity keeps popping up.
Any ideas?
Thanks, Merci, Gracias, Danke, Grazie!
Sean
A: It is happening because your application activity is loaded from the history stack.
Set android:noHistory=true in the manifest for both ActivityOften and ActivityRare. That should solve your problem.
A: Just as a suggestion, you could just have one activity instead of three by choosing the content View dynamically. i.e.
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
if (RandomClass.getSomeStaticBoolean())
{
setContentView(R.layout.Often);
// Set up often ....
}
else
{
setContentView(R.layout.Rare);
// Set up rare ....
}
}
This would mean that you would have to write setup code both views in on activity, which can get a bit messy.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511126",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to add a tag to currently opened page using Chrome extension? I want to add div tag to the currently open website when user clicks chrome extension Icon. This image should appear on the left top corner of the page. How can I achieve this goal?
The code below adds div tag to extension window.
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(function() {
$("#click").click(function(){
chrome.tabs.getSelected(null, function(tab){
var tabUrl = tab.url;
//alert(tabUrl);
document.querySelector('div#content').style.display = 'block';
});
//chrome.tabs.executeScript(null, {code: "document.body." + setAttribute("class",img)});
});
});
</script>
</head>
<body>
<div id="content"></div>
<div id="click">Click Here</div>
</body>
</html>
A: Presumably by icon you mean browserAction, the button on the right of the omnibox. Bind to the chrome.browserAction.onClicked event, and run executeScript on the current tab, injecting a script that adds a position: absolute; top: 0; left: 0; image to the DOM of the page.
Here's a good sample to get you started (changes the page color on clicking the browser action)
A: appending elements into DOM is fulfilled by content scripts, those scripts run after page load event. as you can see in the chrome extension documentations, so they won't affect already opened tabs.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511127",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it possible to somehow define a material or brush that completely ignores the current lighting? I have a model that looks good with lighting, but in that model I want to add a 3D-surface-graph that looks best if I turn lighting off. Does anyone know if it is possible to make the light affect only a selection of objects in my scene?
The best I have come up with so far is to combine a DiffuseMaterial and an EmissiveMaterial with the same color, but that results in some strange visual effects so it’s far from perfect.
A: If there are no lights you will not see the object.
If you want to have a different set of lights for a specific object just put the object in a separate Model3DGroup with its own lights.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511128",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: getting caller uid 10066 is different than the authenticator's uid I am using following code to add account into Account list
final AccountManager accountMgr = AccountManager.get(this.getApplicationContext());
Account ac = new Account("my.id","com.google");
try{
accountMgr.addAccountExplicitly(ac, "password", null);}
catch(Exception e){
String str = e.getLocalizedMessage();
Log.e("err",str);
}
but getting following error everytime:
'caller uid 10066 is different than the authenticator's uid'
A: The following stackoverflow question seems to deal with the issue:
SecurityException: caller uid XXXX is different than the authenticator's uid
The article it links to ( http://loganandandy.tumblr.com/post/613041897/caller-uid-is-different ) explains the whole thing, though it took me a minute to realise what part of my code the last xml snippet was referring to.
I ended up storing my account type and auth token type in my strings.xml and referencing them in the authenticator.xml and code as needed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511135",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: ASP.NET MVC3 in Visual Web Developer 2008 Express I've Visual Web Developer 2008 Express installed on my PC,
Does ASP.NET MVC3 works in visual web developer 2008 express?
How to create simple ASP.NET MVC3 site using simple text editor?
A: No, it doesn't work. ASP.NET MVC 3 requires .NET 4.0 and VS 2008 doesn't support .NET 4.0. You could use Visual Studio 2010 Express.
A: You can install Visual Studio 2010 Express alongside VS2008 - you do not need to uninstall VS2008, and it will not break your VS2008 configuration.
This will be your best option.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511136",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Truncate links with CakePHP How can I truncate links through the Html Helper in CakePHP?
the book only truncates text strings, but how the truncate a link like this?
$this->Html->link('This is a very long link that needs to be truncated', '/pages/home', array('class' => 'button', 'target' => '_blank'));
Thanks
A: Combine usage with the TextHelper::truncate method. Example:
$this->Html->link(
$this->Text->truncate('This is a very long link that needs to be truncated'),
'/pages/home',
array('class' => 'button', 'target' => '_blank')
);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511142",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Regexp to remove all special characters in URL i need to basicaly clean urls that have special characters in it, like so:
http://172.23.113.79/recherche/pages/Results.aspx?k=**cr%c3%83%c2%a9er***
I would like to replace **cr%c3%83%c2%a9er*** by **créer**
and more generally all characters like À Á Â à á â È É Ê è é ê
Ì Í Î ì í î Ò Ó Ô ò ó ô
Ù Ú Û ù ú û.
A: var u=decodeURI("http://172.23.113.79/recherche/pages/Results.aspx?k=cr%c3%83%c2%a9er*");
// u is "http://172.23.113.79/recherche/pages/Results.aspx?k=créer*"
var u=decodeURI("http://172.23.113.79/recherche/pages/Results.aspx?k=cr%C3%A9er*");
// u is "http://172.23.113.79/recherche/pages/Results.aspx?k=créer*"
var u=decodeURI("http://172.23.113.79/recherche/pages/Results.aspx?k=%C3%A9%C3%A8%C3%A0%C3%A7%C3%B9%C3%A2%C3%AA%C3%AE*");
// u is "http://172.23.113.79/recherche/pages/Results.aspx?k=éèàçùâêî*"
Read more:
MDN decodeURI: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/decodeURI
MDN decodeURIComponent: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/decodeURIComponent
var u=decodeURI("http://172.23.113.79/recherche/pages/Results.aspx?k=%C3%80%C3%81%C3%82%C3%A0%C3%A1%C3%A2%C3%88%C3%89%C3%8A%C3%A8%C3%A9%C3%AA%C3%8C%C3%8D%C3%8E%C3%AC%C3%AD%C3%AE%C3%92%C3%93%C3%94%C3%B2%C3%B3%C3%B4%C3%99%C3%9A%C3%9B%C3%B9%C3%BA%C3%BB*");
// u is "http://172.23.113.79/recherche/pages/Results.aspx?k=ÀÁÂàáâÈÉÊèéêÌÍÎìíîÒÓÔòóôÙÚÛùúû*"
A: If it's not something very generic and you have special characters and phrases that you want to replace, you could map your special characters/phrases to their replacements and then decode the string and replace each of them:
var replacements = {
"créer" : "créer", // this is a phrase
"Ã" : "é",
"Â" : "e",
"©" : ""
};
var url = "http://172.23.113.79/recherche/pages/Results.aspx?k=**cr%c3%83%c2%a9er***";
var decoded = unescape(url); // or decodeURI(url);
for(var key in replacements)
decoded = decoded.replace(key,replacements[key]);
A: to make it more general
if (jQuery.browser.msie) {
retStr = encodeURI(retStr);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511143",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Releasing an App for a client So I have just finished building an iOS app for a client and they want me to release it under their company developer account.
I am an admin for the account but not an agent.
I cant build the app for release because i don't have the Distribution certificate and key pair and they arn't smart enough to do it themselves.
How can i release this app to the app store?
ALSO: i have been over eery possible reference i could find so far but no one seems to have the answer.
A: For creating Provisional profile follow this step:
1)go to : developer.apple.com
2)then go to : member center and login
3)after login : iOS Provisioning Portal
4)and star with "Launch Assistant" and follow ahed steps are mention in new window are open.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511146",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Tag H3 inside UL tag
Possible Duplicate:
Is anything except LI's allowed in a UL?
I was doing something like that:
<ul>
<h3><a name="titlename">Title</a></h3>
<li>Text.</li>
<li>More text.</li>
<span><a href="/url">Click here</a> to go to some place.</span>
</ul>
But i get warnings in visual studio:
Warning Validation (HTML5): Element 'h3' cannot be nested within element 'ul'.
Warning Validation (HTML5): Element 'span' cannot be nested within element эul'.
I googled and found that looks like it is not a problem to have another tags but <li> inside <ul>ю
But anyway may be some one have any opinions on that. Could it break something? do put you <h> tags or any another tags inside <ul>? What is your experience with that?
A: <ul> denotes an unordered list, while <li> denotes a list item that belongs to that unordered list - so it only really makes sense to have <li> elements within a <ul> element. If you want to give the unordered list a title, do it outside of the list (this would be the more 'normal' way), or within an <li> element that is inside the list.
<h3>My List Title</h3>
<ul>
<li>List items in here...</li>
</ul>
A: It is invalid if your <h3> is a child of the <ul>. You can only have it inside a <li> but not directly in a <ul>.
A: You can put inside ot <UL> tag only <LI>. And then in LI you can put what you want.
<ul>
<li><h3><a name="titlename">Title</a></h3></li>
<li>Text.</li>
<li>More text.</li>
<li><span><a href="/url">Click here</a> to go to some place.</span></li>
</ul>
or
<h3><a name="titlename">Title</a></h3>
<ul>
<li>Text.</li>
<li>More text.</li>
</ul>
<span><a href="/url">Click here</a> to go to some place.</span>
Yes, you can put anything you want inside of UL, but it's not by W3C standarts (you can see the validation errors) and nobody will guarantie you that in all browsers it will be displayed properly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511148",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: android-failed-to-install--apk-on-real device-null-error I have similar problem to
Android Failed to install HelloWorld.apk on device (null) Error ,but I cannot start my app only on real device. On emulator all is OK. Maybe someone faced with this problem and found a good solution.
Thanks in advance.
A: Go to Settings > Applications> Development and uncheck "USB Debugging". Now check it again. This should solve your problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511149",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Is there a fast way to replace two map contents? In my code I have a map which holds a large amount of data (~100MB) I need to copy all that data from one map to another. currently I am doing this with swap but to my understanding, swap is a fancy way to do a copy. Is there a way to simply transfer the memory used by the two maps? I think that I can do this with pointers but I was hoping for a more elegant way.
A: 23.2.1 [container.requirements.general] of ISO/IEC 14882:2011 contains a list of general container requirements. For all standard containers the expressions a.swap(b) and swap(a, b) must exchange the contents of a and b and for all standard containers other than array both must have constant time. This effectively means that swapping maps cannot involve copying all the map elements.
A: Unless this came up in a profiler run as a bottleneck, you may be optimizing prematurely.
My compiler's std::map::swap() has the following comment, which indicates that a map swap is likely to be very fast:
/**
* This exchanges the elements between two maps in constant
* time. (It is only swapping a pointer, an integer, and an
* instance of the @c Compare type (which itself is often
* stateless and empty), so it should be quite fast.) Note
* that the global std::swap() function is specialized such
* that std::swap(m1,m2) will feed to this function.
*/
(g++ 4.4.5)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511150",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there a way to make the entire combobox clickable in a windows form? Instead of only the little tiny down arrow? Seems like there should be a property I can set or something, but I'm not seeing one... unless I'm blind.
A: Are you looking for
comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
maybe? That will make the combo box non-editable, i.e. it won't act like a text box with a button but just as a large button that will open the drop-down.
A: If the combobox DropDownStyle is set to DropDownList, it will be automatic
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511151",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Cache control in iPhone web app - ajax loaded pages Im looking for a guru on caching and ajax loaded pages :-)
I have read a lot of input about the subject but are still unsure what the best way is to cache ajax pages. I would like to be sure that Im doing all I can to make my iPhone web app as fast as possible to load and navigate on.
This is what I do and have:
Im developing a iPhone web app with jqtouch and phonegap.
Im including all js files,css files, index page, menu icons in the app when it is downloaded from the App Store. The js and css files are minified.
All my subpages is loaded with ajax from my dedicated server.
All subpages are .asp pages that gets its content from a mysql database every time a page is loaded.
Since the iPhone cache pages I have to delete all ajax pages when I have visited them, otherwise an update wouldnt be visible. This is not the best way of doing things.
Instead i would like to not delete the ajax pages and use the cache-controll.
This is how I think it should work:
Turn on cache-controll on the server(how is this done?)
In the app, check the Last-Modified date and if it is not changes - read from the cache.
If its changed - get the files from the server.
Is this the best way of doing things? E-tag instead?
I would like to know, how to set the windows 2008 server with IIS 7 with the right cache controll. How to write the correct header in the index files, and if I need to write som asp-read headers in my asp ajax pages?
I hope somebody now how to do this?
Any input appriciated, thanks!
A: It sounds strange to me that iPhone caches the pages locally and that you have to clean up the cache to get fresh content.
In fact there must be some HTTP cache headers which tell iPhone browser to do that.
It should not matter if the browser is Safari on iOS, or opera on Android, or Firefox on a windows, because all modern browser "should" conform to the HTTP 1.1 RFC, even the mobile ones.
Surely they might have some differences to save bandwidth, phone battery and phone cpu cycles, but definitely they should allow users to get fresh content from a website. So I agree with you, cleaning the visited pages is not the right way of doing things.
I definitely think that there is a problem somewhere. Try to call the API via a computer browser and inspect the requests via firebug, or the native debugging tool of chrome, to check the server response headers, and to see if the behavior is the same.
Normally I use a mix of max-age and if-modified-since cache validators.
I set the max-age of some of the images to an high value (in my case 365 days, most probably not suitable for you), for some others to a week, and a day of css and javascript.
Additionally I use the if-modified-since so I have a good balance between freshness of the content, server load and bandwidth usage. The ETAG is basically the same thing as if-modified-since, with the difference you can set it to a weak cache validator, and it is really useful if the clock of the server is not reliable. (see below on the extended answer for more info and references to docs)
To enable the cache, IIS7 makes it really easy for you with the output caching IIS module. Here is a good doc about it, on how to enable it, and the difference between kernel and user mode cache.
Unless you will need to do really particular stuff, I think you will not need to create code for it, and IIS will take care of everything. If that's not the case, then here is another good guide which will help you out.
If you really want a fast website then I would recommend you to enable compression, and to add a cache layer between the application and the database. So you will not execute queries to the DB on every requests.
Here are some more good performance guidelines for any web developer.
Extended Answer (maybe even too extended :) )
There are different ways of caching the content on the client side via HTTP 1.1.
The most commons, or at least the ones I used the most are:
*
*max-age
*last-modified
*etag
1) The max-age header is sent from the server, on the HTTP response headers, and basically tells the client's browser to store the content on its cache, for a period of time specified in seconds.
For instance, let's assume a server gives back a max-age=60 in response to a GET client http request of logo.jpg. The client's browser then stores the logo.jpg and for the next 60 seconds it will serve the image from its own cache.
In other words there will be no HTTP requests for this specific image for the next 60 seconds.
So with the max age the content is cached on the client side, and will not be requested or revalidated with the server for the amount of seconds specified in the max-age header.
There is however normally the possibility to force this revalidation/refresh by pressing CTRL-F5 on windows browser and CMD-R on mac browsers. On the mobile devices, normally the functionality is on the browser menu, and it is called refresh. This is the appropriate section of the RFC.
PROS
*
*there are no TCP connections, and HTTP requests to the server, therefore less workload on the server side (really useful if your app has a lot of users)
*the content is loaded locally, directly from the browser cache, therefore no latency on content loading
*no bandwidth usage (useful if the data center charges you for inbound and outbound bandwidth)
CONS
*
*if you have fresh content on the server, then the client will not be aware of 'till the cache on the client side expires, or the user force a browser refresh.
2) The last-modified server side http response header together with the client side http request header if-modified-since, is another good mechanism for speeding up the sites and to save some money. It basically works in this way.
A browser requests content for the first time to a server via a GET request.
The server responds with a 200 and gives back the content together with a last-modified header.
The last-modified header's value is nothing else than the actual date and time when the content has been modified last time. (date time must be in UTC because of the timezones)
At this point all the following HTTP requests for the same content coming from the client will have an additional header called: if-modified-since with the date and time received from the server as value.
The server when receives the following requests will check the if-modified-since header value and it will compare it with the last-modified date of the content.
If the data is the same, and therefore the content has not changed, the server will respond with a 304 and basically with no content. (most important part !)
The browser then knows it has to keep still the content on the cache and load it from it because it has not changed on the server side.
The process will continue till the content on the server changed and therefore the server will provide a new last-modified date and fresh content.
This as you can see, can save a lot of bandwidth, especially in the case of images, or JS or css, without giving up content freshness. Section 14.25 of the spec explains things much better than I did. :)
PROS
*
*Less bandwidth involved in the whole process, cause if the content has not changed then the server responds just with a 304.
*Revalidation of the content from the client side, so the client will always have the last fresh data
CONS
*
*the server has to handle the TCP connections and the HTTP requests, and check the last modified date and time of the file/content the client request.
3) The ETAG is a similar process like the if-modified-since, with a difference that the value of the header is normally an hash of the server side content, and the client on the http requests sends an header called: if-none-match.
The pros and cons are the same as the point 2.
You might now wonder than what is the main difference between point 2 and point 3.
The problem with point 2 is actually the server clock. In fact there could be problems serving back the last-modified date from the server if it has clock problems
The subject is quite deeper, cause the best practice is to send a weak and a strong validator. See section 13.3.4 for more information.
A: I have just found out additional info about safari cache interaction with the web app.
Here the link
It seems that the content you want to cache needs to be specified in the manifest file.
Additionally the link explains how to trigger cache invalidation and content refresh via javascript.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511153",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Given layer's object. How do i get the view of a layer in iPhone? I just want to access the view's object from the layer associated with it.I have searched in the CALayer properties for something like "view" but failed.any one have idea about this?
A: Since the view is normally the CALayer’s delegate, just use theLayer.delegate.
If for some reason that doesn’t work, I guess you could iterate all views and compare theView.layer.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511161",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Unable to show taskbar when focus on application I wrote a WPF application, and when it is opened and focused, I cannot show the taskbar when my cursor hovers on the bottom edge (the taskber is auto-hidden), regardless of whether the application is maximized or re-sized to a smaller dimension. I have to manually click the "Window" start button on the keyboard to show the taskbar (of course that also show the start menu as well).
I found a similar question being asked in SO - Auto hide taskbar not appearing - but in my case the taskbar still won't show even if it's not maximized, and I did not override the MINMAXINFO record. The XAML of application MainWindow is as simple as this:
<ribbon:RibbonWindow x:Class="MySoftware.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ribbon="clr-namespace:Microsoft.Windows.Controls.Ribbon;assembly=RibbonControlsLibrary"
Title="My Software" Icon="Images\myLogo.ico"
x:Name="MainWindow1" Background="#FFE8E8E8" WindowState="Maximized" WindowStyle="ThreeDBorderWindow">
A: Since you are using a RibbonWindow, the problem most probably lies there. I am doing something similar using a third-party control, and submitted a bug report, which was then later fixed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511163",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Object and Event Scope in XAML Frame I have a program which is made up of 5 "pages" and a main "page". How can events in one page trigger actions in other "pages"... or a control value set in one "page" be used in another "page"?
I have included the pages like this
<Frame Source="GeneratorPage.xaml" />
Which I believe is the correct way... but I have had no luck assessing controls from within this frame outside it.
public partial class MainWindow : Window
{
Model myModel;
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
myModel = new Model();
mainFrame.Navigate(new Uri(@"\myPage.xaml",UriKind.Relative));
}
As you can see here I create my model and navigate my frame to the page I wish to display. But how can my page access my model?
A: why not include the model in the constructor of your myPage class
mainFrame.Navigate(new myPage(myModel));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511166",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Send images from sdcard to server using multipart entry I am making an android app in which i am sending image to server from /mnt/sdcard/DCIM/Camera/IMG_20110922_124932.jpg to serverthrough multipart request .. Can anybody help me out....
Any help will be appreciated..
Thanks..
A: Here is a simple example of a multipart post that I use to send images to a server:
public void MultipartPost(){
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(url);
//Set Credentials
String auth = User + ":" + Pass;
byte[] bytes = auth.getBytes();
postRequest.setHeader("Authorization", "Basic " + new String(Base64.encodeBytes(bytes)));
try {
MultipartEntity mpC = new MultipartEntity();
//Create stringbody for the filename
StringBody sbPicID = new StringBody("123.jpg");
//get a file reference from the image on the SD card
File fle = new File("full path to the file");
//create a filebody from the file
FileBody fb = new FileBody(fle);
//Add the file name and filebody to the Multipart Entitiy
mpC.addPart("myImage", sbPicID);
mpC.addPart("myImage", fb);
//Set the entitiy of the post request to your Multipart
postRequest.setEntity(mpC);
HttpResponse res;
//execute the post request
Log.d(TAG,"Starting Send...");
res = httpClient.execute(postRequest);
Log.d(TAG, res.getStatusLine().getReasonPhrase());
Log.d(TAG, res.getStatusLine().getStatusCode());
res.getEntity().getContent().close();
Log.d(TAG,"After Close");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
}
A: See the accepted answer of [this question here][1] that I answered last week. It's very similar to the answer above but also includes some sample PHP code to get the image.
JSON and upload image to server
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511173",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CSS: text align error I am getting text-align error, as i want text align from Left but it starts from center. i have tried to fix but unable to do that. please take a look & correct me.
css
.text {
width: 100%;
height: 10%;
text-align: left;
font-weight: bold;
}
html
<div class="text"> ....sentence starts form center..... </div>
A: If this doesn't work you probably have some other css-code that is overriding this one. Check if other styles apply with higher priority or if this one is getting overridden.
Prove of concept: http://jsfiddle.net/jB7X3/
A: I have some suggestions:
*
*
You styled more than one.
Check if you style div.text many times. Sometimes you style one element both in external and internal files, and inline-CSS. (Note: inline-CSS is the strongest for styling)
*
Check your HTML syntax.
Closed tags, use quotations, doctype and typing correctly are important.
*
Maybe didn't link to the stylesheet.
If you are using one (or more) CSS files, you should check your <link/> tags that sourced correctly.
A: Please recheck your upper html syntax.
like close tag of div.
if not close tag of upper div,that div also work below.
A: try to use "!important" declaration:
text-align: left !important;
this should override any "text-align" previously defined (except for inline style)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511174",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I know client side which submit button causes submit when the submit button has been triggered? I'm using asp.net form. If a submit button is clicked I check his identity by doing
$('form').submit(function(e)
{
// VALIDAZIONE CAMPI LOGIN
if(e.originalEvent.explicitOriginalTarget.id
But.. It doesn't work if the submit button isn't clicked, but triggered.
In a few words..
How can I know which submit button causes submit when the submit button has been triggered?
<form>
<input type="submit" name="send1" value="Confirm" />
<input type="submit" name="send2" value="Confirm2" />
<input type="button" name="button2" />
</form>
$(function() {
$('input[name="button2"]').click(function() {
('input[name="send2"]').trigger('click');
});
$('form').submit(function(e) {
if (e...
"this is the point where I want to know which of the submit button has been triggered"
});
});
A: Your solution does work you just havent defined the id attribute on your submit button. If you do that this line of code should work
e.originalEvent.explicitOriginalTarget.id
and if you do not want to use the id attribute and the name instead change it to
e.originalEvent.explicitOriginalTarget.name
see example below
http://jsfiddle.net/VVgYK/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511179",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: dates calculation in bash I have a file full of dates with this format (2002-09-26 02:20:30),
I want to extract the last 5 days from the end of the file , here is what I wrote
END-DATE=tail -1 my file (which is 2002-09-26 02:20:30)
time=$(expr 60 * 60 * 24 * 5) ( counting 5days which is 432000)
up to know every thing is ok ! the problem is with next line,
START-DATE=`expr END-DATE - time`
seems it's wrong : expr: non-numeric argument
how should I convert this time to epoch time ?
A: EDATE is not defined, maybe you made a typo and it should be END-DATE?
A: You need to refer to the variable, EDATE vs $EDATE (did you really mean END-DATE ?)
START_DATE=`expr $EDATE - time`
(Note that you cannot have a - in shell variable names, so START-DATE and END-DATE are invalid. Name them START_DATE and END_DATE rather)
A: If you just want the date 5 days before a given timestamp and have GNU Coreutils installed, you could use date -d "$(tail -n 1 some/file.ext) 5 days ago"; if you want that in a particular format, try looking at the man page date(1) (that is, enter man 1 date).
A: I've written a bunch of tools (dateutils) to tackle exactly these kinds of problems, in particular dgrep might help:
Off the cuff, I'd go for
EDATE=$(tail -n1 MY_FILE)
THRES=$(dadd "${EDATE}" -5d)
dgrep ">=${THRES}" < MY_FILE
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511180",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to make SNMP query in Windows? Since I am a noob about SNMP I will have a little question for you. I have written a program in Java to make SNMP queries or normal command line operations etc. I have implemented all connections and functions but as I know I need something secial installed in my PC or something else to make a SNMP query. Can you please tell me what should I have , what should I use to make a SNMP query
Thank you all
A: I'm not sure if your problem is actually making the SNMP queries from Java, or that you want something on your PC to query for information.
If you want to make SNMP queries from Java, then you will want to use an SNMP library such as http://www.snmp4j.org/. That will allow you to make SNMP queries out to SNMP enabled equipment.
If you want to configure your Windows machine to respond to SNMP queries, then best refer to the document at http://technet.microsoft.com/en-us/library/bb726987.aspx which gives an introduction and instructions for configuring on Windows 2003 Server / Windows XP. There is also a link for later operating systems if you are using those.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511183",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Call/modify current activity on click of a button I have an activity "MyListActivity". I have an adapter associated with it "MyGridAdapter". It contains a grid of buttons (say 3). Each button has a "OnClickListner()".
On click of the 1st button, I would have to take the same action. So, instead of creating similar another activity, I decide to RE-USE the same page. Meaning: I need to call "MyListActivity" but with some modified parameters- increased number of buttons etc...
I tried to use, "invalidate()" on button click. But it re-loads the same page without any changes.
How to call the same activity from a function in the adapter?
My work around for the problem: I created another "tempActivity". in one of the function I am trying to start the previous activity.
code inside "MyGridAdapter":
TempActivity temp=new TempActivity();
temp.setIntentObj(<parameters>);
inside "TempActivity":
Intent intent=new Intent(this,ListActivity.class); //this gives a "NullPointerException"
startActivity(intent);
A: In the adapter class, we can start an activity using context.startActivity(intent) I did not know that we can access "start Activity" from adapter... but now it's working just fine!! Thanks a lot for your recommendation...
A: If I understand you correctly; you should update the List that is passed to the Adapter and then invoke adapter.notifyDataSetChanged(). (method name might be a bit different, I'm typing on my mobile and can't look it up).
The List you update must be the same List that the adapter was given so you'll have to keep a reference of it as a property of your class.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511184",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Displaying a list or Map in Visualforce page I have a controller which has a method which populates a list and map.
Public class A
{ public Map<string,Book__c> map1 {get;set;}
public List<String> Lst {get;set;}
public A()
{
..... do something...
}
public refresh()
{
Lst= new List<String>();
map1=new Map<string,Book__c>;
// Populating the map and List in this method
}
}
In my VF page
i am calling the refresh method on change of a inputfield, the method get called and the maps and Lists get populated. But they are not showing in the VF page
VF Code
<apex:pageblocksection id="tableApp" >
<table id="apppp">
<tr>
<th>Name</th>
</tr>
<apex:repeat var="d" value="{!Lst}">
<tr>
<td><apex:outputText value="{!d}"/></td>
</tr>
</apex:repeat>
</table>
</apex:pageblocksection>
Is there anything wrong in this code? I am rerendering the pageblocksection tableApp on change of the inputfield
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511190",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: REST Architecture for Multiple Deletes? I send a delete request to server as like:
@RequestMapping(value = "/user/{userId}", method = RequestMethod.DELETE)
for a single user delete. However what to do when multiple users wants to be deleted? I want to obey REST architecture but I want to see the another ways from sending multiple delete requests?
PS: Is this a suitable way:
@RequestMapping(value = "/user", method = RequestMethod.DELETE, headers = "Accept=application/json")
public void deleteUser(HttpServletResponse response, @RequestBody String users) throws IOException {
...
}
A: since rest is resource oriented arch.
try design a higher level domain object which represents 'multiple users' resource ,
do delete on that object.
maybe
@RequestMapping(value = "/users/expired", method = RequestMethod.Delete)
the great book 'restful web services cookbook' by Subbu Allamaraju , oreilly , talk about this topic:
*
*chapter 11.10, how to batch process similar resources;
*chapter 11.11, how to trigger batch operation;
*chapter 11.12, when to use post to merge multiple request ;
*chapter 11.13, how to support batch request
A: I'm familiar enough with REST to recognize that using a POST to achieve a DELETE is a deviation from REST compliance. I'm not able to put my finger on the precise reason that's a good rule.
I suspect it may have something to do with either the feasibility of API-agnostic tooling (e.g. a dev tool that makes so assumptions about the state of an implementation based on givens about the verb definitions without needing to be configured to understand what specific API methods do) or the inability to return fine grained errors in the event of a partially successful delete, but those are just guesses and not really central to this question.
Swanliu's answer refers to use of URLs that represent a grouping construct as the target of a delete, but the example given, "/users/expired", suggests a fixed (and possibly system-defined) grouping. The more user-oriented case of an arbitrary collection still requires an enumeration at some point to achieve.
Issuing N DELETEs for a group of size N is not attractive, both because of the compound latency and lack of atomicity, but a REST DELETE may only target a single resource.
I think the best-practice implied by Swanliu's response might be to define a POST operation capable of creating a resource that becomes the new containment parent of the objects to delete. A POST can return a body, so the system in question can create manufacture a unique identifier for this non-domain grouping resource and return it to the client, which can turn around and issue a second request to DELETE it. The resource created by the POST is short-lived, but purposeful--it's demise cascades to the domain objects that were the desired target of a bulk delete operation.
> POST /users/bulktarget/create
> uid=3474&uid=8424&uid=2715&uid=1842&uid=90210&uid=227&uid=66&uid=54&uid=8
> ...
< ...
< 200 OK
< ae8f2b00e
> DELETE /users/bulktarget/ae8f2b00e
> ...
< ...
< 200 OK
Granted, two network exchanges is less desirable than just one, but given that the smaller bulk delete is two objects and would require two DELETE operations to address without anyhow, it seems like a fair tradeoff--think of it like you're getting every object beyond the second one free.
A: My understanding of REST is that is exactly what you must do. If there is an alternative I would love to know too :)
If you don't want to send multiple delete requests, then you have to design a more coarse api. (this is why most APIs out there are RESTful, not REST)
Btw, I think you need RequestMethod.DELETE?
A: AFAIK the basic REST is for working with a single resource. I would go with a POST to the /user/ resource and a special deleteUsers body containing the IDs to delete.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511195",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: How to get website URLs from a sentence? I need to identify URLs (links) in a sentence using C#.Net Windows Form's TextBox.
e.g.: That is http://stackoverflow.com link.
that sentence is in the textbox.
I need to extract http://stackoverflow.com from this sentence.
How can i do that ?
Thanks you for your time.
A: Look up hyperlink regular expression - you can this plug in what you find into a Regex object and it will capture the url for you.
A: string str = "That is my url expression http://stackoverflow.com ";
string pattern = @"((https?|http):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)";
string[] arr = Regex.Split(str, pattern); Console.WriteLine(arr[1]);
A: You can use LinkLabel control. Provide text to the Text attribute and then in the proerty LinkArea define where only should be link. The only thing is that only one link per full LinkLabel text allowed.
A: Try:
detail = Core.URL.Replace(detail,
delegate(Match match)
{
// match.ToString() will contain http://stackoverflow.com in your case :)
return string.Format("<a target=\"_blank\" href=\"{0}\">{0}</a>", match.ToString());
});
With Core.URL.Replace defined as:
public static Regex URL = new Regex(@"(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])", RegexOptions.Compiled);
This code originally came from:
http://weblogs.asp.net/farazshahkhan/archive/2008/08/09/regex-to-find-url-within-text-and-make-them-as-link.aspx#7224581
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511198",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: System.ServiceModel.dll missing in references visual studio 2010 I want to use ChannelFactory<TChannel> Class I am trying to add reference to System.ServiceModel.dll but I not see it in the references .
I see there System.ServiceModel.web.dll but it is something different .
I am using VS 2010 .net 3.5.
Any idea what is the issue here ?
A: right click on the project in solution explorer, properties, then check again and select .NET Framework 3.5 and not client profile, all other info you might need are here, including a helpful screenshot: Where is System.ServiceModel.Web.dll?
A: Do:
*
*Add reference.
*Browse, "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.0\System.ServiceModel.dll
*Click OK
That worked for me
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511199",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: How to control my itemized overlay on map? I want to add new place when i long touch on the map, I can but the problem is when i add the overlay i can't move the map. The code is below.
public class CustomPinPointOverlay extends ItemizedOverlay<OverlayItem> {
private GeoPoint newMarkerLocation;
public CustomPinPointOverlay(GeoPoint newMarkerLocation,
Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
this.newMarkerLocation = newMarkerLocation;
populate();
}
@Override
protected OverlayItem createItem(int i) {
return new OverlayItem(this.newMarkerLocation, null, null);
}
public void draw(android.graphics.Canvas canvas, MapView mapView,
boolean shadow) {
super.draw(canvas, mapView, false);
}
@Override
public int size() {
return 1;
}
}
this is my overlay class which extends itemizedoverlay. other part of code is ;
public PMapView(Context context, AttributeSet attrs) {
super(context, attrs);
setOnTouchListener(new OnTouchListener() {
int x, y;
long start, stop;
@Override
public boolean onTouch(View v, MotionEvent e) {
if (e.getAction() == MotionEvent.ACTION_DOWN) {
start = e.getEventTime();
x = (int) e.getX();
y = (int) e.getY();
touchedPoint = map.getProjection().fromPixels(x, y);
}
if (e.getAction() == MotionEvent.ACTION_UP) {
stop = e.getEventTime();
}
if (stop - start > 1000) {
setEnabled(true);
Drawable myMarker = getResources().getDrawable(
R.drawable.yeni_pin);
getOverlays().add(
new CustomPinPointOverlay(touchedPoint, myMarker));
return false;
}
return true;
}
});
}
what's wrong with this code?
A: This answer is assuming that your PMapView extends MapView.
If the above statement is true you should try calling your superclass's onTouchEvent unless you handle it. For example (this is your code modified but I have not tested it)
@Override
public boolean onTouch(View v, MotionEvent e) {
boolean retValue = true;
if (e.getAction() == MotionEvent.ACTION_DOWN) {
start = e.getEventTime();
x = (int) e.getX();
y = (int) e.getY();
touchedPoint = map.getProjection().fromPixels(x, y);
}
if (e.getAction() == MotionEvent.ACTION_UP) {
stop = e.getEventTime();
}
if (stop - start > 1000) {
setEnabled(true);
Drawable myMarker = getResources().getDrawable(
R.drawable.yeni_pin);
getOverlays().add(
new CustomPinPointOverlay(touchedPoint, myMarker));
retValue = false;
}
if(!retValue)
super.onTouchEvent(e);
return retValue;
}
The above code will pass on actions that are not captured (your long click is captured) back to the parent so it can handle things like moving the map. This code has not been tested so it may give weird results. You may want to remove the if(!retValue) and just always call super.onTouchEvent(e).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511202",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ASP.NET MVC3 Entitiy Framework - The EntitySet 'x' specified as part of this MSL does not exist in MetadataWorkspace I'm making an reservation system.
The following query
Reservatie r = (from res in entities.Reservaties
where (res.datum == date && res.tijdslot == time)
select res).FirstOrDefault();
gives me the following error
Error 54 Error 2003: The EntitySet 'Reservaties'
specified as part of this MSL does not exist in MetadataWorkspace. ...\www\Models\xxx.edmx
It looks like it can 't find my table.
The edmx file is showing my database correctly, I worked several time like that already. I checked the MSL and saw nothing special. The problem is that I don't have any clue where to look for the problem.
Could my integrated N2CMS (dinamico package) have anything to do with this? (It's using nHibernate)
Any idea where to start?
Maybe the edmx is helpfull
<?xml version="1.0" encoding="utf-8"?>
<edmx:Edmx Version="2.0" xmlns:edmx="http://schemas.microsoft.com/ado/2008/10/edmx">
<!-- EF Runtime content -->
<edmx:Runtime>
<!-- SSDL content -->
<edmx:StorageModels>
<Schema Namespace="Model.Store" Alias="Self" Provider="MySql.Data.MySqlClient" ProviderManifestToken="5.1" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" xmlns="http://schemas.microsoft.com/ado/2009/02/edm/ssdl">
<EntityContainer Name="ModelStoreContainer">
<EntitySet Name="arrangementen" EntityType="Model.Store.arrangementen" store:Type="Tables" Schema="xxx" />
<EntitySet Name="complexen" EntityType="Model.Store.complexen" store:Type="Tables" Schema="xxx" />
<EntitySet Name="klanten" EntityType="Model.Store.klanten" store:Type="Tables" Schema="xxx" />
<EntitySet Name="reservaties" EntityType="Model.Store.reservaties" store:Type="Tables" Schema="xxx" />
<EntitySet Name="reservatiestatussen" EntityType="Model.Store.reservatiestatussen" store:Type="Tables" Schema="xxx" />
</EntityContainer>
<EntityType Name="arrangementen">
<Key>
<PropertyRef Name="arrangementId" />
</Key>
<Property Name="arrangementId" Type="int" Nullable="false" StoreGeneratedPattern="Identity" />
<Property Name="naam" Type="varchar" Nullable="false" MaxLength="255" />
<Property Name="beschrijving" Type="text" />
<Property Name="prijs" Type="decimal" Nullable="false" />
<Property Name="van" Type="int" />
<Property Name="tot" Type="int" />
<Property Name="toegelaten_statussen" Type="varchar" Nullable="false" MaxLength="50" />
</EntityType>
<EntityType Name="complexen">
<Key>
<PropertyRef Name="complexId" />
</Key>
<Property Name="complexId" Type="int" Nullable="false" StoreGeneratedPattern="Identity" />
<Property Name="naam" Type="varchar" Nullable="false" MaxLength="255" />
<Property Name="openingsuur" Type="int" Nullable="false" />
<Property Name="sluitingsuur" Type="int" Nullable="false" />
</EntityType>
<EntityType Name="klanten">
<Key>
<PropertyRef Name="KlantId" />
</Key>
<Property Name="KlantId" Type="bigint" Nullable="false" StoreGeneratedPattern="Identity" />
<Property Name="voornaam" Type="varchar" Nullable="false" MaxLength="100" />
<Property Name="achternaam" Type="varchar" Nullable="false" MaxLength="150" />
<Property Name="email" Type="varchar" Nullable="false" MaxLength="150" />
</EntityType>
<EntityType Name="reservaties">
<Key>
<PropertyRef Name="reservatieId" />
</Key>
<Property Name="reservatieId" Type="bigint" Nullable="false" StoreGeneratedPattern="Identity" />
<Property Name="klantId" Type="bigint" Nullable="false" />
<Property Name="datum" Type="date" Nullable="false" />
<Property Name="tijdslot" Type="int" Nullable="false" />
<Property Name="complexId" Type="int" Nullable="false" />
<Property Name="arrangementId" Type="int" />
<Property Name="statusId" Type="int" Nullable="false" />
<Property Name="recurringDaily" Type="bit" />
<Property Name="recurringWeekly" Type="bit" />
<Property Name="recurringMonthly" Type="bit" />
<Property Name="recurringYearly" Type="bit" />
</EntityType>
<EntityType Name="reservatiestatussen">
<Key>
<PropertyRef Name="statusId" />
</Key>
<Property Name="statusId" Type="int" Nullable="false" StoreGeneratedPattern="Identity" />
<Property Name="statusnaam" Type="varchar" Nullable="false" MaxLength="255" />
</EntityType>
</Schema>
</edmx:StorageModels>
<!-- CSDL content -->
<edmx:ConceptualModels>
<Schema Namespace="Model" Alias="Self" xmlns:annotation="http://schemas.microsoft.com/ado/2009/02/edm/annotation" xmlns="http://schemas.microsoft.com/ado/2008/09/edm">
<EntityContainer Name="ALEntities" annotation:LazyLoadingEnabled="true">
<EntitySet Name="Arrangementen" EntityType="Model.Arrangement" />
<EntitySet Name="Complexen" EntityType="Model.Complex" />
<EntitySet Name="Klanten" EntityType="Model.Klant" />
<EntitySet Name="Reservaties" EntityType="Model.Reservatie" />
<EntitySet Name="Reservatiestatussen" EntityType="Model.Reservatiestatus" />
</EntityContainer>
<EntityType Name="Arrangement">
<Key>
<PropertyRef Name="arrangementId" />
</Key>
<Property Name="arrangementId" Type="Int32" Nullable="false" annotation:StoreGeneratedPattern="Identity" />
<Property Name="naam" Type="String" Nullable="false" />
<Property Name="beschrijving" Type="String" />
<Property Name="prijs" Type="Decimal" Nullable="false" />
<Property Name="van" Type="Int32" />
<Property Name="tot" Type="Int32" />
<Property Name="toegelaten_statussen" Type="String" Nullable="false" />
</EntityType>
<EntityType Name="Complex">
<Key>
<PropertyRef Name="complexId" />
</Key>
<Property Name="complexId" Type="Int32" Nullable="false" annotation:StoreGeneratedPattern="Identity" />
<Property Name="naam" Type="String" Nullable="false" />
<Property Name="openingsuur" Type="Int32" Nullable="false" />
<Property Name="sluitingsuur" Type="Int32" Nullable="false" />
</EntityType>
<EntityType Name="Klant">
<Key>
<PropertyRef Name="KlantId" />
</Key>
<Property Name="KlantId" Type="Int64" Nullable="false" annotation:StoreGeneratedPattern="Identity" />
<Property Name="voornaam" Type="String" Nullable="false" />
<Property Name="achternaam" Type="String" Nullable="false" />
<Property Name="email" Type="String" Nullable="false" />
</EntityType>
<EntityType Name="Reservatie">
<Key>
<PropertyRef Name="reservatieId" />
</Key>
<Property Name="reservatieId" Type="Int64" Nullable="false" annotation:StoreGeneratedPattern="Identity" />
<Property Name="klantId" Type="Int64" Nullable="false" />
<Property Name="datum" Type="DateTime" Nullable="false" />
<Property Name="tijdslot" Type="Int32" Nullable="false" />
<Property Name="complexId" Type="Int32" Nullable="false" />
<Property Name="arrangementId" Type="Int32" />
<Property Name="statusId" Type="Int32" Nullable="false" />
<Property Name="recurringDaily" Type="Boolean" />
<Property Name="recurringWeekly" Type="Boolean" />
<Property Name="recurringMonthly" Type="Boolean" />
<Property Name="recurringYearly" Type="Boolean" />
</EntityType>
<EntityType Name="Reservatiestatus">
<Key>
<PropertyRef Name="statusId" />
</Key>
<Property Name="statusId" Type="Int32" Nullable="false" annotation:StoreGeneratedPattern="Identity" />
<Property Name="statusnaam" Type="String" Nullable="false" />
</EntityType>
</Schema>
</edmx:ConceptualModels>
<!-- C-S mapping content -->
<edmx:Mappings>
<Mapping Space="C-S" xmlns="http://schemas.microsoft.com/ado/2008/09/mapping/cs">
<EntityContainerMapping StorageEntityContainer="ModelStoreContainer" CdmEntityContainer="ALEntities">
<EntitySetMapping Name="Arrangementen"><EntityTypeMapping TypeName="Model.Arrangement"><MappingFragment StoreEntitySet="arrangementen">
<ScalarProperty Name="arrangementId" ColumnName="arrangementId" />
<ScalarProperty Name="naam" ColumnName="naam" />
<ScalarProperty Name="beschrijving" ColumnName="beschrijving" />
<ScalarProperty Name="prijs" ColumnName="prijs" />
<ScalarProperty Name="van" ColumnName="van" />
<ScalarProperty Name="tot" ColumnName="tot" />
<ScalarProperty Name="toegelaten_statussen" ColumnName="toegelaten_statussen" />
</MappingFragment></EntityTypeMapping></EntitySetMapping>
<EntitySetMapping Name="Complexen"><EntityTypeMapping TypeName="Model.Complex"><MappingFragment StoreEntitySet="complexen">
<ScalarProperty Name="complexId" ColumnName="complexId" />
<ScalarProperty Name="naam" ColumnName="naam" />
<ScalarProperty Name="openingsuur" ColumnName="openingsuur" />
<ScalarProperty Name="sluitingsuur" ColumnName="sluitingsuur" />
</MappingFragment></EntityTypeMapping></EntitySetMapping>
<EntitySetMapping Name="Klanten"><EntityTypeMapping TypeName="Model.Klant"><MappingFragment StoreEntitySet="klanten">
<ScalarProperty Name="KlantId" ColumnName="KlantId" />
<ScalarProperty Name="voornaam" ColumnName="voornaam" />
<ScalarProperty Name="achternaam" ColumnName="achternaam" />
<ScalarProperty Name="email" ColumnName="email" />
</MappingFragment></EntityTypeMapping></EntitySetMapping>
<EntitySetMapping Name="Reservaties"><EntityTypeMapping TypeName="Model.Reservatie"><MappingFragment StoreEntitySet="reservaties">
<ScalarProperty Name="reservatieId" ColumnName="reservatieId" />
<ScalarProperty Name="klantId" ColumnName="klantId" />
<ScalarProperty Name="datum" ColumnName="datum" />
<ScalarProperty Name="tijdslot" ColumnName="tijdslot" />
<ScalarProperty Name="complexId" ColumnName="complexId" />
<ScalarProperty Name="arrangementId" ColumnName="arrangementId" />
<ScalarProperty Name="statusId" ColumnName="statusId" />
<ScalarProperty Name="recurringDaily" ColumnName="recurringDaily" />
<ScalarProperty Name="recurringWeekly" ColumnName="recurringWeekly" />
<ScalarProperty Name="recurringMonthly" ColumnName="recurringMonthly" />
<ScalarProperty Name="recurringYearly" ColumnName="recurringYearly" />
</MappingFragment></EntityTypeMapping></EntitySetMapping>
<EntitySetMapping Name="Reservatiestatussen"><EntityTypeMapping TypeName="Model.Reservatiestatus"><MappingFragment StoreEntitySet="reservatiestatussen">
<ScalarProperty Name="statusId" ColumnName="statusId" />
<ScalarProperty Name="statusnaam" ColumnName="statusnaam" />
</MappingFragment></EntityTypeMapping></EntitySetMapping>
</EntityContainerMapping>
</Mapping>
</edmx:Mappings>
</edmx:Runtime>
<!-- EF Designer content (DO NOT EDIT MANUALLY BELOW HERE) -->
<Designer xmlns="http://schemas.microsoft.com/ado/2008/10/edmx">
<Connection>
<DesignerInfoPropertySet>
<DesignerProperty Name="MetadataArtifactProcessing" Value="EmbedInOutputAssembly" />
</DesignerInfoPropertySet>
</Connection>
<Options>
<DesignerInfoPropertySet>
<DesignerProperty Name="ValidateOnBuild" Value="true" />
<DesignerProperty Name="EnablePluralization" Value="False" />
<DesignerProperty Name="IncludeForeignKeysInModel" Value="False" />
</DesignerInfoPropertySet>
</Options>
<!-- Diagram content (shape and connector positions) -->
<Diagrams>
<Diagram Name="xxx">
<EntityTypeShape EntityType="Model.Arrangement" Width="1.5" PointX="0.75" PointY="0.75" Height="2.3648893229166665" IsExpanded="true" />
<EntityTypeShape EntityType="Model.Complex" Width="1.5" PointX="2.75" PointY="0.75" Height="1.7879850260416674" IsExpanded="true" />
<EntityTypeShape EntityType="Model.Klant" Width="1.5" PointX="2.75" PointY="3.75" Height="1.787985026041667" IsExpanded="true" />
<EntityTypeShape EntityType="Model.Reservatie" Width="1.5" PointX="4.75" PointY="0.75" Height="3.1340950520833335" IsExpanded="true" />
<EntityTypeShape EntityType="Model.Reservatiestatus" Width="1.5" PointX="4.75" PointY="4.75" Height="1.4033821614583317" IsExpanded="true" />
</Diagram>
</Diagrams>
</Designer>
</edmx:Edmx>
Everything under C-S mapping content is marked as error.
And I got "The EntitySet 'X' specified as part of this MSL does not exist in MetadataWorkspace." for all my tables.
I'm clueless...
A: Forgot to add a reference the MySql.Data.Entity dll...
A: You better check for the <edmx:ConceptualModels> <Schema Namespace="?????" ....... >, of the Complex type being used in the .EDMX file.
It should match to <ComplexTypeMapping TypeName="?????.ComplexTypeName" .... >
It resolved my issue...
A: In my case, I had forgotten to add the new entity that I had created in the
<EntityContainer Name="Entities" annotation:LazyLoadingEnabled="true">
<EntitySet Name="myNewEnt" EntityType="Self.myNewEnt" />
</EntityContainer>
section of the edmx file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511208",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: UITextField: backspace not working I have an issue with UITextField's validation. I want to validate the UITextField's text-length to be 5(fixed).
my code :
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(textField==codeTxt)
{
NSCharacterSet *unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS]invertedSet] ;
if ([[string componentsSeparatedByCharactersInSet:unacceptedInput] count] > 1)
return NO;
else if ([codeTxt.text length] >= 5])
return NO;
else
return YES;
}
}
this code works fine. It validates and ignores rest of the text(more thn 5).
my problem :
When I press Delete(Backspace), nothing happens !!! the text remains the same. delete(Backspace) does not work.
what could be the problem ?
Thanks...
A: put this condition at first statement in shouldChangeCharactersInRange method
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if([string length]==0)
{
return YES;
}
if(textField==codeTxt)
{
NSCharacterSet *unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS]invertedSet] ;
if ([[string componentsSeparatedByCharactersInSet:unacceptedInput] count] > 1)
return NO;
else if ([codeTxt.text length] >= 5])
return NO;
else
return YES;
}
}
A: Your only checking the length of the current text in the field. This method gets called before the text changes, so you need to check the replacementString's length first, then check the textField's text length.
Try this:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (textField == codeTxt) {
// NSCharacterSet *unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS] invertedSet];
// if ([[string componentsSeparatedByCharactersInSet:[unacceptedInput count]] > 1) {
if ([[string componentsSeparatedByCharactersInSet:[[[NSCharacterSet characterSetWithCharactersInString:NUMBERS] invertedSet] autorelease]] count] > 1) {
return NO;
} else if ([string length] < 5) {
return YES;
} else if ([codeTxt.text length] >= 5]) {
return NO;
} else {
return YES;
}
}
}
Edit:
Checking the textField's length probably isn't even necessary after doing [codeTxt.text length] >= 5] since this will prevent the textField's length from ever going above 4 anyway.
Actually, you would need to check it since the default is to return YES;.
Probably needs to be <= 5
} else if ([string length] <= 5) {
return YES;
}
Instead of < 5 too
} else if ([string length] < 5) {
return YES;
}
A: I got the solution
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(textField==codeTxt)
{
NSCharacterSet *unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS]invertedSet] ;
NSLog(@"textfield character validation method called");
NSLog(@"%d",[codeTxt.text length]);
if ([[string componentsSeparatedByCharactersInSet:unacceptedInput] count] > 1)
return NO;
else if ([codeTxt.text length] >= 5 && ![string isEqual:@""])
return NO;
else
return YES;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511210",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Address of Null pointer? I came across the macro below
#define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT))
I kind of not able to digest this because in c++, when I try to deference a null pointer, I expect an unexpected behaviour... but how come it can have an address? what does address of null mean?
A: #define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT))
is very similar to a fairly common definition of the standard offsetof() macro, defined in <stddef.h> (in C) or <cstddef> (in C++).
0 is a null pointer constant. Casting it to TYPE * yields a null pointer of type TYPE *. Note that the language doesn't guarantee (or even imply) that a null pointer has the value 0, though it very commonly does.
So (TYPE *)0 is notionally the address of an object of type TYPE located at whatever address the null pointer points to, and ((TYPE *)0)->ELEMENT)) is the ELEMENT member of that object.
The & operator takes the address of this ELEMENT member, and the cast converts that address to type size_t.
Now if a null pointer happens to point to address 0, then the (nonexistent) object of type TYPE object starts at address 0, and the address of the ELEMENT member of that object is at an address that's offset by some number of bytes from address 0. Assuming that the implementation-defined conversion from TYPE * to size_t behaves in a straightforward manner (something else that's not guaranteed by the language), the result of the entire expression is going to be the offset of the ELEMENT member within an object of type TYPE.
All this depends on several undefined or unspecified behaviors. On most modern systems, the null pointer is implemented as a pointer to address 0, addresses (pointer values) are represented as if they were integers specifying the index of a particular byte within a monolithic addressing space, and converting from a pointer to an integer of the same size just reinterprets the bits. On a system with such characteristics, the OFFSETOF macro is likely to work, and the implementation may choose to use a similar definition for the standard offsetof macro. (Code that's part of the implementation may take advantage of implementation-defined or undefined behavior; it's not required to be portable.)
On systems that don't have these characteristics, this OFFSETOF macro may not work -- and the implementation must use some other method to implement offsetof. That's why offsetof is part of the standard library; it can't be implemented portably, but it can always be implemented in some way for any system. And some implementations use compiler magic, like gcc's __builtin_offsetof.
In practice, it doesn't make much sense to define your own OFFSETOF macro like this, since any conforming C or C++ implementation will provide a working offsetof macro in its standard library.
A: This is not dereferencing a pointer, but returning the offset of the element in the structure.
for example for
typedef struct { char a; char b;} someStruct;
Calling OFFSETOF(someStruct, b) will return 1 (assuming its packed etc etc).
This is the same as doing this:
someStruct str;
offset = (size_t)&(str.b) - (size_t)&str;
except that with OFFSETOF you don't need to create a dummy variable.
This is needed when you need to find an offset of the class/struct/union member for whatever reason.
** Edit **
To all the hasty downvoters who think that "the standard doesn't allow this" - please read the standard again. The behavior is very well defined in this case.
** Another edit **
I believe none of the downvoters noticed that the first parameter is type. I'm sure that if you think a little bit more than the half a second it takes to downvote, you'll understand your mistake. If not - well, it won't be the first that a bunch of ignorant downvoters suppressed a correct answer.
A: The purpose of OFFSETOF is to return the distance between the address of a member and the address of the aggregate it belongs.
If the compiler doesn't change the object layout depending on its placement, that "distance" is constant and hence the address you start from is irrelevant. 0, in such case, it is just an address like any other.
According to C++ standard accessing an invalid address is "undefined behavior", but:
*
*If that's part of a compiler support library (this is the actual code of "OFFSETOF" in the CRT coming with VS2003!), that may be not so "undefined" (for a known compiler and platform, that behavior is known to the support library developer: of course, this must be considered "platform specific code", but different platform will probably have different library versions)
*In any case, you are not "acting" on the element (so no "access" is done), just doing some plain pointer arithmetic. Thnk as a general demontration like "If there is an object at location 0 its supposed ELEMENT member will start al location 6. hence 6 is the offset". The fact that there is no real such object is irrelevant.
*By the way, this macro fails (with a segmentation fault!) if the ELEMENT is inherited by TYPE by means of a virtual base, since, to locate the placement of avirtual base you need to access some runtime informations -usually part of an object v-table- whose location cannot be detected, being the object address not a "real" address.
That's the why the standard cautelatively says that "dereferencing an invalid pointer is undefined behavior".
TO DOWNVOTERS:
I provide platform specific information for a platform specific ansewr.
Before downvote, please provide a demonstration that what i said is false.
A: Dereferencing a null pointer (as this macro does) is undefined behavior.
It is not legal for you to write and use such a macro, unless the
implementation gives you some special, additional guarantee.
The C standard library defines a macro offsetof; many implementations
do use something similar to this. The implementation can do it because
it knows what the compiler actually generates in this case, and whether
it will cause problems or not. The implementation of the standard
library can use a lot of things you can't.
A: A. The action is valid, no exception will be thrown because you don't try to access the memory the pointer is pointing to.
B. null pointer - it's basically a normal pointer saying the object sits in address 0 (Address 0 by definition is a invalid address for real objects) but the pointer it self valid.
So this macro is mean: if an object of type TYPE is starting in address 0 where will his ELEMENT will be in memory? in other words what's is the offset from ELEMENT to the start of TYPE object.
A: That's one hell of a macro, piling up undefined behavior...
What it is attempting to do: getting the offset of a struct member.
How it tries to do it:
*
*Use a null pointer (value 0 in the code)
*Take the element (let the compiler compute the address of it, from 0)
*Take the address of the element (using &)
*Cast the address into a size_t
There are two issues:
*
*Dereferencing a null pointer is undefined behavior, so technically anything could happen
*Casting a pointer into a size_t is not something that should be done (the problem is that a pointer is not guaranteed to fit)
How it could be done:
*
*Use a real object
*Compute the difference of address
In code:
#define OFFSETOF(Object, Member) \
((diffptr_t)((char*)(&Object.Member) - (char*)(&Object))
However it requires an object, so might not be suitable for your purposes.
How it should be done:
#include <cstddef>
#define OFFSETOF(Struct, Member) offsetof(Struct, Member)
But there would be little point... right ?
For the curious, the definition can be something like: __builtin_offsetof(st, m) (from Wikipedia). Some compilers implement it with null dereferences, but they are the compilers, and thus know that they treat this case safely; this is not portable... and does not have to be since switching compiler, you also switch the C library implementation.
A: littleadv had the intent of the construct just right. Explaining a little bit: You cast a struct pointer pointing to address 0x0 and dereference on of its elements. The address you point to is now at 0x0 + whatever offset the element has. Now you cast this value to a size_t and get the offset of the element.
I'm not sure how portable this construct is, though.
A: For the purpose of the macro:
It assumes that there is an object of type TYPE at address 0 and returns the address of the member which is effectively the offset of the member in the structure.
This answer explains why this is undefined behaviour. I think that this is the most important quote:
If E1 has the type “pointer to class X,” then the expression E1->E2 is converted to the equivalent form (*(E1)).E2; *(E1) will result in
undefined behavior with a strict interpretation, and .E2 converts it
to an rvalue, making it undefined behavior for the weak
interpretation.
which is the case here. Although others think that this is valid. It is important to note that this will produce the correct result on many compilers though.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511211",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: How to get the processor number on linux I need to get the processor number in my program with C/C++ language. My code
like as follow:
#include <unistd.h>
int main()
{
int processorNum = sysconf(_SC_NPROCESSORS_CONF);
return 0;
}
when i compile it , it had two errors:
error: '_SC_NPROCESSORS_CONF' was not declared in this scope
error: 'sysconf' was not declared in this scope
so ,what should i do.
ps: my complier's version is gcc version 4.3.2 (Debian 4.3.2-1.1).should i link a library file
ps: Hi all, excuse me ,i made some mistakes. i forgot the head file.
A: 1、The most reliable way is to read /proc/cpuinfo file. like grep processor proc/cpuinfo
2、use command lscpu
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511213",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: What is the difference between and ? I have written one XSLT to transform xml to html. If input xml node contains only space then it inserts the space using following code.
<xsl:text> </xsl:text>
There is another numeric character which also does same thing as shown below.
<xsl:text> </xsl:text>
Is there any difference between these characters? Are there any examples where one of these will work and other will not?
Which one is recommended to add space?
Thanks,
Sambhaji
A:   is a non-breaking space ( ).
  is just the same, but in hexadecimal (in HTML entities, the x character shows that a hexadecimal number is coming). There is basically no difference, A0 and 160 are the same numbers in a different base.
You should decide whether you really need a non-breaking space, or a simple space would suffice.
A: It's the same. It's a numeric character reference.
A0 is the same number as 160. The first is in base 16 (hexadecimal) and the second is in base 10 (decimal, everyday base).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511214",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "26"
} |
Q: android how to finish an activity from other activity In my app i have 3 activities.
From 1st activity it goes to 2nd and from 2nd it goes to 3rd. From 3rd it is coming to 1st again. and if I press back key from the 1st then it should go to home screen (App will stop).
If I press back key of 1st its goes to 2nd activity again and if I press 2nd's back key, then it goes to the 1st . Then if I press back key of 1st then app stops.
What I want , when I am in 3rd activity and press the back button then it should go to 1st and simultaneously finish the 2nd activity.
How can I do that?
A: When you start your third activity you should call in your 2nd acitivity like this:
startActivityForResult(intent, 0)
When you finish your 3rd activity, you should include:
setResult(RESULT_OK);
finish();
It sends a signal from the 3rd activity to the 2nd.
In the 2nd put:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
finish();
}
It receives this signal and finishes the 2nd activity.
A: You should launch the 1st activity in 3rd activity with the cleartop flag when you need to finish the 2nd activity.
class ThirdActivity extends Activity {
....
if (somecondition) {
/* directly go to FirstActivity, finish all intermediate ones.*/
Intent intent = new Intent(this, FirstActivity.Class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
} else {
finish(); // to simply return to 2nd activity.
}
.....
....
}
A: just finish the second activity when you open third activity
suppose in second activity on some button click you are opening third activity using start activity;
startActivity(intent);
finish();//this will finish second activity and open third activity so when you press back from third activity it will open first activity.
if you want depended on some condition then on activity
setResult(123);
something code like this
now when override onActivityResult in second activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==123){
//finish
}
}
also make sure one thing you need to use startActivityForResult(intent, requestCode); for result in second activity to start third activity.
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Activity2 extends Activity{
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivityForResult(new Intent(new Intent(Activity2.this,Activity3.class)), 12);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode==123 && requestCode==12){
finish();
}
super.onActivityResult(requestCode, resultCode, data);
}
}
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Activity3 extends Activity{
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setResult(123);
}
});
}
}
A: Alternatively, you could set an intent flag called FLAG_ACTIVITY_NO_HISTORY on the 2nd Activity. This way it is not kept in the history stack so when you navigate back from the 3rd activity it will go straight to the 1st.
E.g.
Intent intent = new Intent(this, SecondActivity.Class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
This means that when you launch an activity from the SecondActivity the SecondActivity will be finished automatically.
A: Using this way: In your first activity, declare one Activity object like this,
public static Activity fa;
onCreate()
{
fa = this;
}
now use that object in another Activity to finish first-activity like this,
onCreate()
{
FirstActivity.fa.finish();
}
More information : Finish an activity from another activity
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511216",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: ExtJS4: Add field to form panel but not want it to be rendered by panel I have a static html form layout where i add extjs form fields using the "renderTo" config. In order to have form validation and simple submit methods i want to add the fields to a form panel. As the layout is managed by the html frame i don't want the form to be rendered by the panel (panel has html frame as contentEl and this should be used as is).
In extjs3 i could achieve this by adding the field not to the panel but to the BasicForm (formpanel.getForm().add(...)) but in extjs4 this method seems to be gone.
How can i do this using extjs4?
Thanks in advance.
A: Since you already have a Panel that uses the contentEl to render HTML into its body, I recommend to stick with this approach:
Replace the panel with an Ext.form.Panel instance - the configuration, particularly the contentEl config - can remain unchanged.
The code provided here will override a standard Ext class (Ext.layout.Layout) and introduce support for a 'renderItemTo' config property on child items of any Ext container or panel instance (including Ext.form.Panel).
The value of the config property should be the ID of an already rendered DOM node, e.g. a DIV element that is part of the HTML fragment used in as the contentEl of the parent container's body.
Ext.require(['Ext.layout.Layout'], function() {
Ext.override(Ext.layout.Layout, {
renderItem: function (item, target, position) {
if(item.renderItemTo) {
// render 'renderItemTo' components into the specified DOM element
item.render(item.renderItemTo, 1);
// don't allow container layout to seize the component
item.layoutManagedHeight = 2;
item.layoutManagedWidth = 2;
} else {
// just use standard Ext code for non-renderItemTo components
this.callOverridden(arguments);
}
},
isValidParent: function(item, target, position) {
// signal Ext that we are OK with were our 'renderItemTo' component is right now
// otherwise it would get moved during the layout process
return item.renderItemTo ? true : this.callOverridden(arguments);
}
});
});
Usage:
var panel = Ext.create('Ext.form.Panel', {
contentEl: 'form', // the DOM element ID that holds the HTML fragment for the body
title: 'My FormPanel with special FX',
items: [
{
xtype: 'textfield',
renderItemTo: 'text1', // the ID of a DOM element inside the HTML fragment
fieldLabel: 'Label 1',
},
{
xtype: 'textfield',
renderItemTo: 'text2', // the ID of a DOM element inside the HTML fragment
fieldLabel: 'Label 2'
}
]
});
I uploaded a working example to JSFiddle (note: resize the window if you experience a render problem - this is related to JSFiddle, not my override).
A: After digging through the layout system of ExtJS 4.1 i implemented a custom layout which moves the items after rendering to the desired position in the fixed markup. The result is the same as for the ExtJS 4.0.7 version from this thread. It seams to work for the ExtJS standard fields. I have some problems with my custom fields though.
Ext.define('Ext.ux.layout.Fixed', {
extend: 'Ext.layout.container.Auto',
alias: 'layout.uxfixed',
afterRenderItem: function(item) {
// move items with renderToFixedMarkup to desired position
if (item.renderToFixedMarkup) {
var target = Ext.getDom(item.renderToFixedMarkup);
this.moveItem(item, target);
}
},
isValidParent: function(item, target, position) {
// items with renderToFixedMarkup property are always positioned correctly
return (item.renderToFixedMarkup) ? true : this.callOverridden(arguments);
}
});
It can be used by setting "layout: 'uxfixed'" on the panel and the "renderToFixedMarkup" config on the items.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511217",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Storing global immutable data in static classes I have a WinForms project, which uses a lot of user controls. Some of these user controls use classes from business logic layer. These classes are mainly performing CRUD operation to a database (through data access layer) plus some additional validation and reporting.
The project uses some common objects (logged user, some controllers and validators), which are instantiated in main form and then injected into child user controls via initialization methods or public properties. This means, that I have a lot of code, which just passes these common objects from parent control to child controls.
In order to avoid this, I could create a static class (ApplicationContext for example) and save all common controls into it. This would happen in the main form and all other user controls or forms in the project could use it.
I see that this pattern is discouraged in general (storing some global data in static classes). But what if this data is immutable? Is this approach ever a good idea?
Or do you know any other approach, which could help me get rid of all the initialization code?
A: You can use an Inversion of Control container like Unity or Autofac and have it automatically wire up your object graph for you.
You can have each object that requires any one of the common objects define a dependency to their interfaces, either though a constructor argument, or as a public property, and the IoC container will wire the appropriate objects together.
Property injection example with Unity:
public class MyUserControl : UserControl
{
[Dependency]
public LoggedUserService UserService { get; set; }
public void Method()
{
// the IoC container will ensure that the UserService
// property has been set to an object
}
}
All you do in the main form is registering the common objects you want the IoC container to know about and then you ask for the root object. The object graph will be assembled magically for you and you don't have to to all the wire code nor care how it is done.
A: You can use a dependency injection / ioc container for maintaining your global objects.
I have made good experience with the autofac library but there are many other available.
When using setter injection, all of your controls get set dependent objects set automatically.
A: You'll want to use Singletons for this situation. Singletons will allow you to use the same instance of your object, more safe and flexible than static.
public sealed class Singleton
{
public object Property1 {get;set;}
public void Method1 (){}
static Singleton instance = null;
static readonly object padlock = new object();
Singleton()
{
}
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance==null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
then you can use it like you would static, but a bit different...
public class Main
{
public Main()
{
Singleton.Instance.Property1 = "somevalue";
Singleton.Instance.Method1();
}
}
A: You can use a static class to store some immutable data - no problem with this.
How ever if you want to store controls there it might not work as expected.
For example method like OnDataBinding and Render.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511219",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Website Rendering Problem: Safari 4 displays flash of content, then white screen I'm working on developing a rails application, and I'm getting word from Safari 4 users of a strange and irregular rendering error in which the page appears briefly, but quickly disappears and is replaced by a blank white page.
I have not been able to replicate the problem in Safari 5 on Lion, but I have encountered the problem a number of times on Safari 4 for iOS. Without access to Snow Leopard or Safari 4, I haven't been able to do any testing on that end.
Sometimes reloading the page allows the user to access the content, but sometimes it takes more than ten attempts before anything actually happens.
Also, in some instances, the page displays fine, but some partial HTML tags appear on the site. This may or may not be related, but I've only encountered the problem in iOS.
Right now my best guess is that the problem is being caused by some malfunction in the Data URI embedding of images or some other sort of scripting error, but beyond that I have no idea.
Access the website here — http://www.fairviewhs.org
from the the embedded ruby layout:
<head>
<%= include_stylesheets :screen, :media => 'screen, projection' %>
<%= include_stylesheets :print, :media => 'print' %>
<%= stylesheet_link_tag "event_calendar", :media => 'screen, projection, print' %>
<!--[if lt IE 8]>
<%= stylesheet_link_tag "compiled/ie", :media => 'screen, projection' %>
<![endif]-->
<link rel="stylesheet" href="/fancybox/jquery.fancybox-1.3.4.css" type="text/css" media="screen" />
<script src="<%= javascript_path "load" %>" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
head.js(
"https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js",
"http://gettopup.com/releases/latest/top_up-min.js",
"<%= javascript_path "rails" %>",
"<%= javascript_path "application" %>",
"<%= javascript_path "jquery.sap" %>",
"<%= javascript_path "sap" %>",
"<%= javascript_path "forms" %>",
"<%= javascript_path "nested_form" %>",
"<%= javascript_path "event_calendar" %>",
"<%= javascript_path "/fancybox/jquery.fancybox-1.3.4.pack.js" %>",
"<%= javascript_path "/fancybox/jquery.easing-1.3.pack.js" %>",
"<%= javascript_path "/fancybox/jquery.mousewheel-3.0.4.pack.js" %>",
"<%= javascript_path "midiswag" %>"
);
</script>
<%= csrf_meta_tag %>
<%= favicon_link_tag %>
<meta charset="utf-8" />
<%- if @title.blank? -%>
<title>Fairview High School</title>
<%- else -%>
<title>Fairview High School > <%= @title %></title>
<%- end -%>
</head>
A: I was able to find an old computer with Snow Leopard still on it—the problem was a scripting error in the file http://gettopup.com/releases/latest/top_up-min.js
I still have no idea why the problem occurred only in Safari 4/5 in Snow Leopard and iOS, but removing that line of code from the <head> certainly did the trick.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511221",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Help with structs im making a simple text game in c just for fun, but is having some problems with structs and/or Visual Studio 2010. I've started a empty C++ project, but my main main file is main.c.
Here is the code:
int main()
{
struct Player
{
char name[256];
int sum;
};
struct Player player;
strcpy(player.name, "John");
player.sum = 0;
struct Player cpu;
strcpy(cpu.name, "Bob");
cpu.sum = 0;
printf("\n\n\n");
system("PAUSE");
return 0;
}
Now, the compiler is complaining alot! One of them:
Syntax error: missing ; before type (struct Player cpu line)
Rest is related to that cpu is not a struct and therefor non of the members gets recon by the compiler.
What have i done wrong with my struct?
A: In C, you have to declare all of your local variables first, at the beginning of the scope. You should move the struct Player cpu; declaration on the line right after struct Player player;
A: In addition to @Didier, you can make a .cpp file instead of .c with the content you have and the compiler will run well
A: What you have written is valid C++ but not valid C. Change your filename to main.cpp and it should build just fine in Visual Studio.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511225",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to implement html5 in android I am new to HTML5 and phonegap. when i googled, i came to know that html5 can use in android but i dont know how to implement html5 for android application. Is there possible to use HTML5 with phonegap or can use html5 alone in android application. I am confused with using html5 and phoengap.
when i search how to use html5 in android i got code as
<html>
<head>
<title>Cupertino Streaming</title>
</head>
<body>
<video controls src="http://[wowza-address]:1935/vod/sample.mp4/playlist.m3u8">
</video>
</body>
</html>
all these code are in html5 format.with this how i use along with android application. if i need to implement whether i need to use phonegap? can anyone please help to startoff android application with html5.
Please provide some link and reference for learning html5 by myself.
Thanks in advance.
A: you dont need to do any specific implementation for android. just create a normal html5 page and android can read it.
see this site for sample implementation of html5 and css3.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511226",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: ASP.NET MVC: How to handle 400 bad request error when url end with % I am trying to handle all HTTP errors to my custom error pages, but I find that when there is a % at the end of url, i cannot use config setting or code to handle it,
for example: http://localhost/abc%
the response is:
Bad Request - Invalid URL
HTTP Error 400. The request URL is invalid.
So, can we use config setting or c# code to handle this error request?
A: Who said not possible?
Response.TrySkipIisCustomErrors = true;
OR
<configuration>
<system.webServer>
<httpErrors existingResponse="PassThrough" />
</system.webServer>
</configuration>
original post
A: See this 4 part series for configuring custom error pages within IIS: http://www.dotnetscraps.com/dotnetscraps/post/Did-you-know-Enable-Custom-Error-in-IIS-7-75.aspx.
I personally prefer to use Application_Error event to log the errors and redirect user to custom error pages. Note that you need to use integrated pipe-line in IIS to catch all errors otherwise IIS will show its own error page for resources that are not served by ASP.NET.
EDIT:
Sorry for the wrong answer. I have XP machine currently that shows 404 for % sign so couldn't verify above. Searching over internet, I found that it's simply not possible to display custom error page for 400 status code. See this question from server fault for more information.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511239",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: cakephp sms functionality not working $this->Email->to = '+91number@airtelmail.com';
$this->Email->subject = 'hi';
$this->Email->from = emailid;
$this->Email->template = null;
$this->Email->sendAs = 'text';
$text = "Device is down";
$this->Email->send($text);
With Above code, if I set $this->Email->sendAs = 'email';, email can be sent, but it is not working for SMS?
A: The sendAs property of the EmailComponent controls the format in which the e-mail is sent. That can be 'html', 'text' or 'both', which will send it as an HTML email with a plain text fallback.
So, I guess airtelmail will catch the emails sent to <number>@airtelmail.com and send them via SMS to <number>. However, that has nothing to do with the EmailComponent - the EmailComponent can only send emails.
You might wanna try to use a SMTP server for sending the mails out of your app - some providers classify emails sent by PHP as spam. See the here for details.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511245",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: javamail dir issues with windows I am using javamaildir to read e-mail messages from the physical folder on windows machine.
I am passing the url as "maildir:D:\\home\\test\\maildir". the direcotry maildir has the email message. I am able to connect to the store "maildir:D:\home\test\maildir", but when i am trying to getFolder("inbox"), I'm getting the exception saying 'folder 'INBOX' not found' is that folder named with inbox is by default for javamaildir?.
I need two clarifications:
*
*Am i approaching in the right way?
*There is a dot problem in accessing the folder using javamaildir on windows , can we hanlde it programatically...
Your suggetions will be helpful
Thanks in advance.........
A: I ran into a similar issue with reading the UNIX style maildir folders on Windows. These folders typically have a inbox folder named .INBOX which seems to cause issues on Windows. From what I could tell the javamaildir library expects the inbox folder to have the '.' in the name.
I don't really have a good solution, however I had a similar post here. Not sure if it would be much help. Good Luck!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511248",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Gtk Button inner-border I add a button to HBox, with expand equal to False, but I want the button to have more spacing between its label and border. I assume it is "inner-border" property, but it is read-only. How can I set it to e.g. 4px?
A: gtk.Label is a subclass of gtk.Misc which has the method set_padding. If you get the label out of the gtk.Button then you can just call set_padding on it.
You could do something like:
label = gtk.Label("Hello World")
button = gtk.Button()
/* Add 10 pixels border around the label */
label.set_padding(10, 10)
/* Add the label to the button */
button.add(label)
/* Show the label as the button will assume it is already shown */
label.show()
A: Wrong answer:
What you're looking for is called "padding". When you add your button to the container, for example by calling gtk.Box.pack_start, just set the padding parameter to a positive integer.
Update:
Seems I misread the question. In that case, my guess is that you're supposed to use gtk_widget_modify_style, as inner-border is a style property. You'll first get the style modifier you need by calling gtk_widget_get_modifier_style. You'll then be able to modify the style only for that button using the ressource styles matching rules.
A: you can use "inner-border" style property of gtk button.
here, small code snippets
In gtkrc file:
style "button_style"
{
GtkButton::inner-border = {10,10,10,10}
}
class "GtkButton" style "button_style"
In .py file:
gtk.rc_parse(rc_file_path + rc_file)
[Edit]
In gtkrc file:
style "button_style"
{
GtkButton::inner-border = {10,10,10,10}
}
widget "*.StyleButton" style "button_style" # apply style for specific name of widget
In .py file:
gtk.rc_parse(rc_file_path + rc_file)
#set name of button
self.style_button.set_name('StyleButton')
hope, it would be helpful.
A: I sometimes just add spaces in the label !
gtk.Button(" Label ")
to get some spacing.
Hope this could help you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511252",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Access or MySQL in a big company Since a month, i'm working for a big company in France. They asked me to make a application manage their plannings. I devellopped something not so bad using their existant Access database and VB.net.
The problem is that in a few months, the application will maybe be used by 70 workers while today only 10 use it.
So i did a lot of researches, and i read that Access could not support more that 20 connection in the same time.
Firts, is that true ? What do I risk with an Access database for 70 workers ?
And then, what do you think of MySQL in my case ? The application won't be connect on internet, only on intranet. I took a very long time to connect my application to MySQL, but now i don't know how to connect the application in intranet.
In fact i'm a bit lost with the choice of my SGDB.
I'm sorry for my English and my bad explanations but i'm french and i didn't find the answers to my questions in french forums.
Thanks to those who will help me.
A: Please, use MySQL.
There is almost no excuse to use Access backend.
Like you said, Access has very poor connection abilities (every time the database is open, a connection is created as long as the program is still opened). Also, it has poor backup options (do you really want to make copies of the file every day?).
Also, Access has a "repair and compress database" option (for MDB, not sure about the newer format). It has a poor record of data consistency from what I experience with MDBs daily.
MySQL gives you a reliable data store, connections can be pooled properly, it has transaction support, and you can also run proper backups on it.
You can have a MySQL backend, and use Access forms as a frontend. I expect this should be a good enough compromise, and lets you scale it easily.
A: MySql can handle very large projects, it's stable, updated and free, so I think you shouldn't think to go on with Access.
Connecting to MySql will be quite easy: include MySql.Data.dll and change db connection string, it's easy and you'll find a lot of examples on internet.
If your app should only talk with db in intranet, simply install MySql on a server and connect your app using server ip and port.
A: I have seen Access database have real poor security and which is terribly slow. If at all you intend to open your access database after a few days of running in production, you will see the how slow it can be.
Though it looks like you are new to MySQL, you will not need much of a learning curve to work with it. MySQL have lot of users that you will get a good support for you MySQL related questions also. And the best of all you will be able to learn MySQL, which i am sure you will use later for other applications you create.
A: If you are the one that has to maintain the application also in future then drop the idea of Access and change into MySQL.
Access is only for personal use (or maybe with some small number of co-users)
A: the number of users for your app shouldnt matter, u should use mysql simply because it's free. robust, can handle heavy traffic and very professional. it has pretty much clients for any programming language and there are tons of documentation in the internet.
i hope this will help
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511255",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: implementing TTThumbsViewController on a UIViewController? Im trying to implement add TTThumbsViewController as a subview of UIViewController but the app is crashing. Here you see the code-
.h file-
#import <UIKit/UIKit.h>
#import <Three20/Three20.h>
#import <Three20UI/UIViewAdditions.h>
#import "MockPhotoSource.h"
@interface photos : UIViewController <NSXMLParserDelegate, TTThumbsViewControllerDelegate>
{
TTThumbsViewController *photoSource;
...........
}
.m File-
- (void)viewDidLoad {
// parsing a feed
[self parseXMLFileAtURL:@"http://feed203.photobucket.com/albums/aa15/vikysaran/Worst%20Parents/feed.rss"];
NSMutableArray *arr = [[NSMutableArray alloc]init];
for (int i=0; i < [stories count];i++) {
[arr addObject:[[[MockPhoto alloc] initWithURL:[[stories objectAtIndex:i] objectForKey:@"fullimageurl"] smallURL:[[stories objectAtIndex:i] objectForKey:@"thumburl"]
size:CGSizeMake(960, 1280)] autorelease]];
}
photoSource = [[[MockPhotoSource alloc] initWithType:MockPhotoSourceNormal title:nil photos:[NSArray arrayWithArray:arr] photos2:nil]autorelease];
// till here the code is working fine if i am not using uiviewcontroller
NSLog(@"mockphoto%@", arr);
[self.view addSubview:photoSource.view];// adding to uiview
}
here is the error displays-
-[MockPhotoSource view]: unrecognized selector sent to instance 0x6924ca0
2011-09-22 13:07:07.375 JesonTerry[1969:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[MockPhotoSource view]: unrecognized selector sent to instance 0x6924ca0'
Please anybody help. i am totally confused where i am wrong...
A: your view controller has to be a type TTThumbsViewController and not a UIViewControler for starters.. Check the TTCatalog app in the samples folder
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511256",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Odd behavior when running bundle install I have a project where I used to have simple_captcha gem but no more. All traces removed. I even cleaned the directory and added a new project, even though the bundler installs all gems into a local path called simple_captcha. I have also uninstalled the gem from the system.
Anyone had this problem before?
A: It is possible that one of your other gems depends on simple_captcha.
Look into Gemfile.lock, there you can see which gem requires simple_captcha.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511262",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android phone and Tablet problem I know this is not a technical related question.But i do not have any idea.I am going to develop a project which should be supported in both phone and tablet.Is it possible having one project working for both tablet and phone ?
A: Yes. The only thing you need to keep in mind where you keep your graphics. Because it will cause different problems if you do not treat and handle them depending on the screen size. Only thing matters is the android version. If you deploy your app in any phone or a tablet where the version is newer or equal to the target version it works. But of course you cant take a call or some other mobile functionality from a tablet if its not supporting that features.
A: You can use drawable-hdpi,drawable-mdpi and drawable-ldpi for the graphics(images which use in project) and also use layout with multiple screen by custom layout like layout-480x320 , layout-600x1024 etc. in layout you can custom screen xml file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511271",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Sending data to RESTful web services from iOS app I am facing a challenge to upload & download data, to and from the server using RESTful web services.
Is it possible to use a RESTful service client, if possible any way to achieve that in an iOS app to send data to the service.
A: @Ajay: As Claus mentioned there are number of public frameworks/wrappers are there, you can use them for RESTful service interaction from your code. The one I frequently use is ASIHttpRequest, quite handy and easy to use. There are enough examples out there with ASIHttpRequestyou can use it as reference.
Let me know if that helps.
A: You question is not clear. Do you need to push data from the server to the iOS app using a REST service?
If so, REST does not provide an interface for push. (It only provides a client->server Create/Read/Update/Delete API).
A: Take a look at ASIHTTPRequest or use RestKit for some more advanced stuff!
RestKit works really nice!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511274",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Javascript a=b=c statements I searched through the internets but could not find a relevant search criteria so I thought this would be the best place to ask.
I have a JS statement saying
document.location.hash = this.slug = this.sliceHashFromHref(href)
How does this work??
A:
How does this work??
a = b can be seen as both a statement and an expression.
The result of the expression is b.
In other words,
a = b = c;
which can be written as
a = (b = c);
is equivalent to
b = c;
a = b;
Thus your code is equivalent to:
this.slug = this.sliceHashFromHref(href);
document.location.hash = this.slug;
A: Quite easy... It assigns the result from the call to this.sliceHashFromHref(href) to both document.location.hash and this.slug, so both properties (variables) contain the same value after the line has been executed.
A: In Javascript (and several other languages that derive their syntax from C) an assignment evaluates the item to the right of the = symbol and assigns it to the variable on the left. The item on the right can itself be an assignment with an = operator. What happens is the rightmost expression is evaluated, the value assigned to the middle variable, and then that value is assigned to the variable on the left.
In short, it's simply a way to assign a value to multiple variables at once.
A: Be aware of the variables scope!!
var A = B = C = 3; //A is local variable while B & C are global variables;
var A = 3 , B = 3, C = 3;// A B C are local variables;
A: Actually Ma Jerez's answer makes a very important point here. also this answer refers to this similar question:
this question involves a few things:
*
*hoist: variables are hoisted before block code execution;
*= assignment order: it goes from right to left;
*global context: in non-strict mode, when a variable isn't defined, it goes to the global context; but will throw in 'use strict' mode;
example1:
;(function Anonymous(){
var a = b = {};
console.log(a==b); //true
})();
*
*a was hoisted in the Anonymous execution scope.
*b is going to be assigned as {}, but because b is not defined, b is assigned to the global context window, then window.b is assigned {}; then window.b = {} returns {}.
*local variable a is assigned as {}.
Therefore, a few interesting things happen here: the local variable a and the global variable b both point to the same object {}, so they are == and ===; remember that {}=={} gives false otherwise.
Note: if in strict mode:
;(function Anonymous(){
'use strict'
var a = b = {}; //Uncaught ReferenceError: b is not defined
})();
this consecutive assignment won't work the same way...
A: It gets evaluted from right to left. i.e.
document.location.hash = this.slug = this.sliceHashFromHref(href)
means the output/value of this.sliceHashFromHref(href) is assigned to this.slug and then to document.location.hash.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511279",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "40"
} |
Q: I'm trying to export a runnable jar in Eclipse, but I need it to include some other files necessary for running my program Specifically, I am using JDBC libraries to work with databases in my Java program. When I perform "Export Runnable Jar" in Eclipse, it includes the referenced libraries but I am never given an option to include my assets folder (containing the databases) in the runnable jar file. If I try to export a regular jar file via Eclipse, I can add the assets folder, but the referenced libraries are not included.
What should I do here?
Thanks a lot.
A: Try using Ant scripts or maven script to do this.
Where you can import all the referenced jar and files to your desired location.
Personally i liked ant script, since it was easier and you will surely get lot of results for the same if you google.
A: It's been some time since I last generated a JAR file with Eclipse, and back in the day I remember the Fat-Jar Eclipse Plug-in to be quite useful.
A: Are your asset directories declared as Source Folders in Eclipse?
Right Click on the folder, choose Build Path->Use as Source Folder. Then retry the export.
In the longer term, you should really be looking at a build tool such as maven or ant, they are much more flexible, and they are less dependent on Eclipse, so changes in your project configuration in Eclipse won't affect the final build so much.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511288",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: facebook localhost development problem - works occasionally I am trying to integrate facebook login in my application and the development is on localhost...
problem is I get the login button sometimes when I open the site.
Most of the cases, I have to refresh the page again and again and still it does not appear.
Well the internet is up and running..
It works fine whenever the login button appears...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511290",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to avoid repetitive if statements in python dictionaries I am trying to create a new dictionary out of html form data that was submitted by the user. I end up writing repetitive if statements, checking if xyz key is in the dictionary in the form data. I know this is a quite suboptimal approach though I am not quite sure how to implement this using python.
This is the form data dictionary:
form_data = {
'urls': ['www.google.com', 'www.bing.com'],
'useremail': ['my@email.com'],
'emailfield': ['1'],
'addressfield': ['1'],
'addressfield_info':['Company'],
'addressfield_instruction': ['Please only if the company is a LLC'],
'phonefield': ['1'],
'phonefield_instruction': ['please include area code']
}
and I want to create a dictionary that looks like this:
new_dic = {
'urls': ['www.google.com', 'www.bing.com'],
'useremail': ['my@email.com'],
'infofield': [
{'field': 'email'},
{'field': 'address', 'info':'Company', 'instruction': 'Please only if the company is a LLC'},
{'field':'phone', 'instruction': 'please include area code'}
]
}
Important note: The 'xyzfield' is mandatory and the 'xyzfield_info' and 'xyzfield_instruction' are both optional. Also: the user can add more fields and create for instance an 'agefield', 'agefield_info' and 'agefield_instruction'.
The problem I have is about how to efficiently check if xyzfield (email, phone, etc) is in the dictionary. If it is in there, check also if any of the optional fields are in there as well. This looks currently something like this:
if 'emailfield' in form_data:
infofield = {'field': 'email'}
if 'emailfield_info' in form_data:
infofield['info'] = form_data['emailfield_info']
if 'emailfield_instruction' in form_data:
infofield['instruction'] = form_data['emailfield_instruction']
cleaned_data['infofields'].append(infofield)
...
and I do this for every field, hence I have 4-5 of this. Additional, I will not be able to process any of the fields that the user has created himself since I don't know the name upfront.
Long story short: How can I make this more efficient and dynamic?
A: The standard answer to how to avoid repeated code applies here --- extract the repeated code to a function:
def extract_field(form_data, clean, fieldname, optional=('info', 'instruction')):
if fieldname+'field' in form_data:
infofield = { 'field': fieldname }
for opt in optional:
optname = '{}field_{}'.format(fieldname, opt)
if optname in form_data:
infofield[opt] = form_data[optname]
clean.append(infofield)
extract_field(form_data, cleaned_data['infofields'], 'email')
extract_field(form_data, cleaned_data['infofields'], 'address')
extract_field(form_data, cleaned_data['infofields'], 'phone')
A: This assumes you just want to clean whatever is actually submitted. If you are looking for specific things to be there, I suggest making a list of things to look for, and iterating over the list and checking to see if the things are there.
form_data = {
'urls': ['www.google.com', 'www.bing.com'],
'useremail': ['my@email.com'],
'emailfield': ['1'],
'addressfield': ['1'],
'addressfield_info':['Company'],
'addressfield_instruction': ['Please only if the company is a LLC'],
'phonefield': ['1'],
'phonefield_instruction': ['please include area code']
}
def make_field_dict(form_data, base):
field_dict = {}
name_field = base + "field"
name_info = base + "field_info"
name_inst = base + "field_instruction"
if name_field not in form_data:
raise KeyError, "%s not found in form_data" % name_field
if form_data[name_field] != ['1']:
raise ValueError, "%s not valid in form_data" % name_field
field_dict["field"] = base
if name_info in form_data:
lst = form_data[name_info]
if len(lst) != 1:
raise ValueError, "%s not valid in form_data" % name_info
field_dict["info"] = lst[0]
if name_inst in form_data:
lst = form_data[name_inst]
if len(lst) != 1:
raise ValueError, "%s not valid in form_data" % name_inst
field_dict["instruction"] = lst[0]
return field_dict
def parse_form_data(form_data):
cleaned_data = {}
cleaned_data["infofield"] = []
seen = set()
for key, value in form_data.items():
if "field" not in key:
cleaned_data[key] = value
else:
base, _, tail = key.partition("field")
if base in seen:
continue
cleaned_data["infofield"].append(make_field_dict(form_data, base))
seen.add(base)
return cleaned_data
new_dic = {
'urls': ['www.google.com', 'www.bing.com'],
'useremail': ['my@email.com'],
'infofield': [
{'field': 'email'},
{'field': 'address', 'info':'Company', 'instruction': 'Please only if the company is a LLC'},
{'field':'phone', 'instruction': 'please include area code'}
]
}
clean_data = parse_form_data(form_data)
new_dic['infofield'].sort()
clean_data['infofield'].sort()
assert(new_dic == clean_data)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511294",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Node JS Express Boilerplate and rendering I am trying out node and it's Express framework via the Express boilerplate installation. It took me a while to figure out I need Redis installed (btw, if you're making a boilerplate either include all required software with it or warn about the requirement for certain software - Redis was never mentioned as required) and to get my way around the server.js file.
Right now I'm still a stranger to how I could build a site in this..
There is one problem that bugs me specifically - when I run the server.js file, it says it's all good. When I try to access it in the browser, it says 'transferring data from localhost' and never ends - it's like render doesn't finish sending and never sends the headers. No errors, no logs, no nothing - res.render('index') just hangs. The file exists, and the script finds it, but nothing ever happens. I don't have a callback in the render defined, so headers should get sent as usual.
If on the other hand I replace the render command with a simple write('Hello world'); and then do a res.end();, it works like a charm.
What am I doing wrong with rendering? I haven't changed a thing from the original installation btw. The file in question is index.ejs, it's in views/, and I even called app.register('.ejs', require('ejs')); just in case before the render itself. EJS is installed.
Also worth noting - if I do a res.render('index'); and then res.write('Hello'); immediately afterwards, followed by res.end();, I do get "Hello" on the screen, but the render never happens - it just hangs and says "Transferring data from localhost". So the application doesn't really die or hang, it just never finishes the render.
Edit: Interesting turn of events: if I define a callback in the render, the response does end. There is no more "Transferring data...", but the view is never rendered, neither is the layout. The source is completely empty upon inspection. There are no errors whatsoever, and no exceptions.
A: Problem fixed. It turns our render() has to be the absolute last command in a routing chain. Putting res.write('Hello'); and res.end(); after it was exactly what broke it.
I deleted everything and wrote simply res.render('index') and it worked like a charm. Learn from my fail, newbies - no outputting anything after rendering!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511299",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Multiple markers in google map I am scratching my head for google map integration please help me out.
I want multiple markers, but its taking only 11 markers not more than that.
Below is my code..
<script src="http://www.google.com/jsapi"></script>
<script type="text/javascript">google.load("jquery", "1");</script>
<script type="text/javascript"> google.load("maps", "3", {other_params:"sensor=false"});</script>
<script type="text/javascript">
var geocoder;
var map, cloud;
var counter = 0;
var markers = [];
var locations = [];
locations[0] = "Charleston, SC";
locations[1] = "Tuscon, AZ";
locations[2] = "Phoenix, AZ";
locations[3] = "San Diego, CA";
locations[4] = "Los Angeles, CA";
locations[5] = "Aliso Viejo, CA";
locations[6] = "Laguna Beach, CA";
locations[7] = "Coto de Caza, CA";
locations[8] = "Philadelphia, PA";
locations[9] = "Ladera Ranch, CA";
locations[10] = "Thousand Oaks, CA";
var image = new google.maps.MarkerImage(
'../images/marker.png',
new google.maps.Size(28,54),
new google.maps.Point(0,0),
new google.maps.Point(14,54)
);
function init()
{
//alert(locations.length);
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 4,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
for (var i = 0; i < locations.length; i++) {
makeMarker(locations[i]);
}
centerMap();
}
function centerMap()
{
map.setCenter(markers[markers.length-1].getPosition());
}
function makeMarker(location)
{
geocoder.geocode( { 'address': location}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
icon: image,
position: results[0].geometry.location
});
markers.push(marker);
alert(results[0].formatted_address);
var contentString = 'Content comes here';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'mouseover', function() {
infowindow.open(map,marker);
});
google.maps.event.addListener(marker, 'mouseout', function() {
infowindow.close(map,marker);
});
}
});
}
google.maps.event.addDomListener(window, 'load', init);
</script>
You can see practical example in: http://projects.pronixtech.net/kindcampaign/kind-country/
A: I think the problem is in "geocoder.geocode".
Look this code, with LatLong it works.
var geocoder;
var map, cloud;
var counter = 0;
var markers = [];
var locations = [];
locations[0] = new google.maps.LatLng(10.32522, 10.07002);
locations[1] = new google.maps.LatLng(20.32522, 10.07002);
locations[2] = new google.maps.LatLng(30.32522, 10.07002);
locations[3] = new google.maps.LatLng(10.32522, 20.07002);
locations[4] = new google.maps.LatLng(20.32522, 20.07002);
locations[5] = new google.maps.LatLng(30.32522, 20.07002);
locations[6] = new google.maps.LatLng(10.32522, 30.07002);
locations[7] = new google.maps.LatLng(20.32522, 30.07002);
locations[8] = new google.maps.LatLng(30.32522, 30.07002);
locations[9] = new google.maps.LatLng(10.32522, 40.07002);
locations[10] = new google.maps.LatLng(20.32522, 40.07002);
locations[11] = new google.maps.LatLng(30.32522, 40.07002);
locations[12] = new google.maps.LatLng(10.32522, 50.07002);
locations[13] = new google.maps.LatLng(20.32522, 50.07002);
locations[14] = new google.maps.LatLng(30.32522, 50.07002);
locations[15] = new google.maps.LatLng(10.32522, 60.07002);
locations[16] = new google.maps.LatLng(20.32522, 60.07002);
locations[17] = new google.maps.LatLng(30.32522, 60.07002);
var image = new google.maps.MarkerImage(
'http://www.bookyourparis.com/images-site/beachflag.png',
new google.maps.Size(28,54),
new google.maps.Point(0,0),
new google.maps.Point(14,54)
);
function init()
{
//alert(locations.length);
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 2,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
for (var i = 0; i < locations.length; i++) {
makeMarker(locations[i]);
}
centerMap();
}
function centerMap()
{
map.setCenter(markers[markers.length-1].getPosition());
}
function makeMarker(location)
{
//geocoder.geocode( { 'address': location}, function(results, status) {
// if (status == google.maps.GeocoderStatus.OK) {
//map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
icon: image,
position: location//results[0].geometry.location
});
markers.push(marker);
//alert(results[0].formatted_address);
var contentString = 'Content comes here';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'mouseover', function() {
infowindow.open(map,this);
});
google.maps.event.addListener(marker, 'mouseout', function() {
infowindow.close(map,this);
});
//}
//});
}
google.maps.event.addDomListener(window, 'load', init);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511310",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Change size of Android-Seekbar? I have a question concerning seekbars.
I tried several things but nothing helped.
I want to change the height of the seekbar, but not the complete seekbar, only the bar where you scroll over with your thumb. I tried several things e.g. setBackGroundDrawable and setProgressDrawable and made my own drawables, but the drawable-size is fixed to the size of the Standard-Android-Seekbar.
What can I do now?
A: You have to add some padding in all directions and than set the min and max height. Here are one example that I used:
<?xml version="1.0" encoding="utf-8"?>
<SeekBar xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:progressDrawable="@drawable/custom_player_seekbar_background"
android:paddingTop="10px"
android:paddingBottom="10px"
android:thumb="@drawable/bt_do_player"
android:paddingLeft="30px"
android:paddingRight="30px"
android:minHeight="6dip"
android:maxHeight="6dip"
android:layout_height="wrap_content"
android:layout_centerVertical="true"/>
A: For changing SeekBar size custom progressDrawable and custom thumb should be used. here is full implementation:
<SeekBar
android:layout_width="your desired width in dp"
android:layout_height="wrap_content"
android:minHeight="your desired height in dp"
android:maxHeight="as same as minHeight"
android:progressDrawable="@drawable/seekbar_drawable"
android:splitTrack="false"
android:thumb="@drawable/seekbar_thumb"
/>
===========================================================
create seekbar_drawable.xml file in res/drawable folder:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/seekbar_border" />
<item>
<clip android:drawable="@drawable/seekbar_progress"/>
</item>
</layer-list>
===========================================================
create seekbar_border.xml file in res/drawable folder:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="5dp" />
<solid android:color="#12000000" />
</shape>
===========================================================
create seekbar_progress.xml file in res/drawable folder:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="5dp" />
<solid android:color="#98F7DB" />
</shape>
===========================================================
and finally create seekbar_thumb.xml file in res/drawable folder:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="#FF60C2A5" />
<size
android:width="your desired height in dp"
android:height="as same as width" />
</shape>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511315",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Pass CurrentUICulture to Async Task in ASP.NET MVC 3.0 The active language is determined from the url and then set on the
Thread.CurrentThread.CurrentUICulture = cultureInfo;
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureInfo.Name);
That way the translations are retrieved from the correct resource files.
When using Async action on controllers, we have a background thread, where the Thread.CurrentThread.CurrentUICulture is set back to OS default. But also on the background thread we need the correct language.
I created a TaskFactory extension to pass the culture to the background thread and it looks like this:
public static Task StartNew(this TaskFactory taskFactory, Action action, CultureInfo cultureInfo)
{
return taskFactory.StartNew(() =>
{
Thread.CurrentThread.CurrentUICulture = cultureInfo;
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureInfo.Name);
action.Invoke();
});
}
This allows me to do the following in an action controller:
[HttpPost]
public void SearchAsync(ViewModel viewModel)
{
AsyncManager.OutstandingOperations.Increment();
AsyncManager.Parameters["task"] = Task.Factory.StartNew(() =>
{
try
{
//Do Stuff
AsyncManager.Parameters["viewModel"] = viewModel;
}
catch (Exception e)
{
ModelState.AddModelError(string.Empty, ResxErrors.TechnicalErrorMessage);
}
finally
{
AsyncManager.OutstandingOperations.Decrement();
}
}, Thread.CurrentThread.CurrentUICulture);
}
public ActionResult SearchCompleted(Task task, ViewModel viewModel)
{
//Wait for the main parent task to complete. Mainly to catch all exceptions.
try { task.Wait(); }
catch (AggregateException ae) { throw ae.InnerException; }
return View(viewModel);
}
This all works perfectly, but I do have some concerns.
Is this the correct way to extend an action by setting the culture before invoking the original action ?
Does anyone know of a different way to pass te CurrentUICulture to a background thread for ASP.NET MVC Async actions ?
*
*Session is not an option.
*I do was thinking of using the CallContext.
Any other comments on this code ?
Thanks
A: It seems the described way in the question is the answer.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511318",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: HTML5: Placing a canvas on a video with controls I want to draw things on HTML5 video. For that I am trying to place a canvas on the HTML5 video element.
But there is a problem when I place the canvas on the video element the video controls do not work. Since canvas getting all the mouseover and click events. Is there a way to delegate the events to video controls or show the controls in somewhere else?
Any help/idea would be great.
A: You can capture the click events in the canvas and calculate their position. Based on that, you could approximate which control was targeted and make the video changes your self.
I mean something like this :
canvas.onclick = function(e){
if(isOverPauseBtn(e))
video.pause();
//.. and so on
}
A: What you should do is implement your own controls (or use an existing set such as videojs)
You can read my answer to this question: Html5 video overlay architecture
A: Increase the z-index of canvas. z-index=10
Bring the video under the canvas.
Height of canvas = height of entire video - height of video controls.
You can cover only the video part with canvas and if hover on the bottom of the canvas, you will get the controls
A: If you don't need the canvas to receive any pointer events, then you can use the CSS pointer-events property on the canvas and set it to none.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511319",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Uploading base64 encoded Image to Amazon S3 via Node.js Yesterday I did a deep night coding session and created a small node.js/JS (well actually CoffeeScript, but CoffeeScript is just JavaScript so lets say JS) app.
what's the goal:
*
*client sends a canvas datauri (png) to server (via socket.io)
*server uploads image to amazon s3
step 1 is done.
the server now has a string a la
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACt...
my question is: what are my next steps to "stream"/upload this data to Amazon S3 and create an actual image there?
knox https://github.com/LearnBoost/knox seems like an awesome lib to PUT something to S3, but what I'm missing is the glue between the base64-encoded-image-string and actual upload action?
Any ideas, pointers and feedback welcome.
A: For people who are still struggling with this issue. Here is the approach I used with native aws-sdk :
var AWS = require('aws-sdk');
AWS.config.loadFromPath('./s3_config.json');
var s3Bucket = new AWS.S3( { params: {Bucket: 'myBucket'} } );
Inside your router method (ContentType should be set to the content type of the image file):
var buf = Buffer.from(req.body.imageBinary.replace(/^data:image\/\w+;base64,/, ""),'base64')
var data = {
Key: req.body.userId,
Body: buf,
ContentEncoding: 'base64',
ContentType: 'image/jpeg'
};
s3Bucket.putObject(data, function(err, data){
if (err) {
console.log(err);
console.log('Error uploading data: ', data);
} else {
console.log('successfully uploaded the image!');
}
});
s3_config.json file :
{
"accessKeyId":"xxxxxxxxxxxxxxxx",
"secretAccessKey":"xxxxxxxxxxxxxx",
"region":"us-east-1"
}
A: Here's the code from one article I came across, posting below:
const imageUpload = async (base64) => {
const AWS = require('aws-sdk');
const { ACCESS_KEY_ID, SECRET_ACCESS_KEY, AWS_REGION, S3_BUCKET } = process.env;
AWS.config.setPromisesDependency(require('bluebird'));
AWS.config.update({ accessKeyId: ACCESS_KEY_ID, secretAccessKey: SECRET_ACCESS_KEY, region: AWS_REGION });
const s3 = new AWS.S3();
const base64Data = new Buffer.from(base64.replace(/^data:image\/\w+;base64,/, ""), 'base64');
const type = base64.split(';')[0].split('/')[1];
const userId = 1;
const params = {
Bucket: S3_BUCKET,
Key: `${userId}.${type}`, // type is not required
Body: base64Data,
ACL: 'public-read',
ContentEncoding: 'base64', // required
ContentType: `image/${type}` // required. Notice the back ticks
}
let location = '';
let key = '';
try {
const { Location, Key } = await s3.upload(params).promise();
location = Location;
key = Key;
} catch (error) {
}
console.log(location, key);
return location;
}
module.exports = imageUpload;
Read more: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#upload-property
Credits: https://medium.com/@mayneweb/upload-a-base64-image-data-from-nodejs-to-aws-s3-bucket-6c1bd945420f
A: ok, this one is the answer how to save canvas data to file
basically it loos like this in my code
buf = new Buffer(data.dataurl.replace(/^data:image\/\w+;base64,/, ""),'base64')
req = knoxClient.put('/images/'+filename, {
'Content-Length': buf.length,
'Content-Type':'image/png'
})
req.on('response', (res) ->
if res.statusCode is 200
console.log('saved to %s', req.url)
socket.emit('upload success', imgurl: req.url)
else
console.log('error %d', req.statusCode)
)
req.end(buf)
A: The accepted answer works great but if someone needs to accept any file instead of just images this regexp works great:
/^data:.+;base64,/
A: For laravel developers this should work
/* upload the file */
$path = Storage::putFileAs($uploadfolder, $uploadFile, $fileName, "s3");
make sure to set your .env file property before calling this method
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7511321",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "142"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.