text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: How to get response from web API call I have an API that I want to call and get the response back. Then I want to assign that response to a variable.
I have an API like:
http://example.org/Webservicesms_get_userbalance.aspx?user=xxxx&passwd=xxxx
When I run this URL in a browser, it prints an SMS balance. I want this SMS balance as a response and then assign it to a variable in my page.
A: You may also use WebRequest class.
WebRequest request = WebRequest.Create ("http://domainname/Webservicesms_get_userbalance.aspx?user=xxxx&passwd=xxxx");
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse ();
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream ();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader (dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd ();
// Display the content.
Console.WriteLine (responseFromServer);
// Cleanup the streams and the response.
reader.Close ();
dataStream.Close ();
response.Close ();
Of course, you can change Console.WriteLine to whatever you want to do with response.
A: Your service is an .aspx page which just returns text (the sms balance) and no html?
If so you can 'scrape it'
string urlData = String.Empty;
WebClient wc = new WebClient();
urlData = wc.DownloadString("http://domainname/Webservicesms_get_userbalance.aspx?user=xxxx&passwd=xxxx");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608527",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Where is the infinite loop? Hello this is my first message in overflow(Sorry if the question is too long) and im also junior at java and english.
I've recently read a mind game. Question was something like this:
There is four women,and their names: kirmizi - yesil -sari -mavi
(these are colour names in Turkish) Each woman wears a skirt in one these colours. For example;
mavi woman wears sari skirt
but there are two rules:
None of the women's skirt colour should not be same as their name
also the length of their names and skirts cant be equal. For example, mavi woman can't wear sari skirt. But she can wear kirmizi and yesil.
Can you find each woman's skirt colour?
And I've tried to solve it but it goes into infinite loop
Colour=renk
name=isim in turkish:)
Edit: I've just found out new clues. Miss kirmizi and sari can't wear mavi and yesil skirts. Also their skirts are different colour. I can write the answer if you want but I believe this is a good problem for beginners like me :)
package ana;
class Ana {
static boolean birtobir=false;
static boolean ikitoiki=false;
static boolean uctouc=false;
static boolean dorttodort=false;
String renk;
String isim;
public static void main(String[] args) {
String[] isimler={"bir","iki","uc","dort"};
String[] renkler={"kirmizi","sari","yesil","mavi"};
Ana bir = new Ana();
bir.isim = "kirmizi";
bir.renk="kirmizi";
Ana iki = new Ana();
iki.isim = "sari";
iki.renk="sari";
Ana uc = new Ana();
uc.isim = "yesil";
uc.renk="yesil";
Ana dort = new Ana();
dort.isim = "mavi";
dort.renk="mavi";
while ( birtobir=true && bir.renk.matches(bir.isim))
while( ikitoiki=true && iki.renk.matches(iki.isim) )
while( uctouc=true && uc.renk.matches(uc.isim) )
while( dorttodort=true && dort.renk.matches(dort.isim)) {
for (int a=0;a<renkler.length;a++) {
bir.renk=renkler[a];
if(bir.renk.length()==bir.isim.length()) {
boolean birtobir=true;
}
for (int b=0;b<renkler.length;b++) {
iki.renk=renkler[b];
if(iki.renk.length()==iki.isim.length()) {
boolean ikitoiki=true;
}
for (int c=0;c<renkler.length;c++) {
uc.renk=renkler[c];
if(uc.renk.length()==uc.isim.length()) {
boolean uctouc=true;
for (int d=0;d<renkler.length;d++) {
dort.renk=renkler[d];
}
if(dort.renk.length()==dort.isim.length()){
boolean dorttodort=true;
}
}
}
}
}
}
System.out.println(bir.isim+"="+bir.renk);
System.out.println(iki.isim+"="+iki.renk);
System.out.println(uc.isim+"="+uc.renk);
System.out.println(dort.isim+"="+dort.renk);
}
}
A: It's just a guess, but in here:
while ( birtobir=true && bir.renk.matches(bir.isim))
while( ikitoiki=true && iki.renk.matches(iki.isim) )
while( uctouc=true && uc.renk.matches(uc.isim) )
while( dorttodort=true && dort.renk.matches(dort.isim)){
most likely you want: birtobir==true && .. ikitoiki==true && ... uctouc==true && ... dorttodort==true [use operator== instead of the operator=]
birtobir=true sets birtobir to be true, while birtobir==true checks if the variable is true.
more details on operators in java
If it is not a bug, and you actually want to set the vaeriable - it's a bad styling and you should refactor your code.
EDIT:
One more thing I can notice:
if(bir.renk.length()==bir.isim.length()){
boolean birtobir=true;
}
In here, you create a new variable named birtobir, and set it to true. This variable is NOT the variable checked [or supposed to be checked] in the while loop. I assume you actually want to set the class member to true. To do so, replace boolean birtobir=true; with birtobir=true;
A: A single = assigns a value to a variable, while == checks for equality. This means you should change the conditions in your while loop to check for equality instead of assigning a value.
I.E.
while ( birtobir=true && bir.renk.matches(bir.isim)) is effectively the same as while (bir.renk.matches(bir.isim)).
It should therefore be changed into while ( birtobir==true && bir.renk.matches(bir.isim))
edit: what amit says..
A: Here's my rendition. If I understand correctly you want to print all the valid combinations?
public class Colours
{
private static String[] names = new String[]{"kirmizi","yesil", "sari", "mavi"};
private static String[] colors = new String[]{"kirmizi","yesil", "sari", "mavi"};
public static void main(String[] args)
{
for (int i = 0; i < names.length; i++)
{
for (int j = 0; j < colors.length; j++)
{
if(allowed(names[i], colors[j])) {
System.out.println(names[i] + " may wear " + colors[j]);
}
}
}
}
private static boolean allowed(String name, String color) {
return (!name.equals(color)) && (name.length() != color.length());
}
}
A: Can't tell for sure what's going on, but you seem to have to many cycles.
I'd try to start with a naive but simple algorithm:
for (person in persons) {
for (color in skirtColors) {
if (person.name != color && person.name.lenght != color.lenght) {
person.skirtColor = color;
} else {
person.skirtColor = "";
}
}
if (allPersonsHaveSkirts(persons)) {
// a more complete check should be done
// to make sure they all have different colored skirts
printSolution();
}
}
By using 2 simple, finite for loops, you guarantee that no infinite loops happen.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608528",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Create a user profile upon registration add profile form fields to devise registrations#new form I have a rails 3.1 app with devise:
*
*User has_one profile
*Profile belongs_to user
*Overruled the devise registration_controller
*Custom registration views all working fine, registration works fine
Now I could like to add this:
*
*On the registration page I want to add fields from the profile, like first name, lastname
*There is no user yet, that is going to be created when submitting the form
*I need the profile to be created with this first name,last
How would I do this? I tried several ideas, also from stack overflow but cannot seem to get it working. I tried nested attributes wich is not working the way to do this would to create a profile record in the db at the moment the user registers wich inserts the first name and last name
My registrations#new view:
= simple_form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f|
= devise_error_messages!
= f.input :username, :label => 'Username'
= f.input :email, :label => 'Email'
= f.input :password, :label => 'Password'
= f.input :password_confirmation, :label => 'Password confirm'
// start fields for profile
= f.fields_for :profile do |f|
= f.label :bod_day
= f.text_field :bod_day
// end fields for profile
= f.button :submit, t(:submit, :scope => :register)
In my user model i have this:
accepts_nested_attributes_for :profile
A: I think the problem is that no profile exists on that user when the form is rendered, a simple way to get round this might be to build it in memory before rendering the fields like so:
= simple_form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f|
= devise_error_messages!
= f.input :username, :label => 'Username'
= f.input :email, :label => 'Email'
= f.input :password, :label => 'Password'
= f.input :password_confirmation, :label => 'Password confirm'
// make a new profile in memory
= resource.build_profile
// start fields for profile
= f.fields_for :profile do |f|
= f.label :bod_day
= f.text_field :bod_day
// end fields for profile
= f.button :submit, t(:submit, :scope => :register)
A: In addition to Nesbitt's solution, add this to your model
attr_accessible ..., :profile_attributes
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608532",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Passing multiple parameters using single input control in JasperServer I have created jasper report in ireport. I am trying to execute it using jasper server. I want to pass two input parameters to report using single Input Control. This input control is a drop down. It has text and Id. I want to pass both id as well as text to report. Is there any way I can achieve this??
A: In order to create a report with input parameters you have to pass them through a HashMap. This is where you put any number of values you like and pass them to JasperReport:
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("shopName", shopName);
map.put("month", Integer.parseInt(jComboBox2.getSelectedItem().toString()));
map.put("Value2", jComboBox2.getSelectedIndex());
URL reportFileURL = getClass().getResource("../ireports/MyReport.jrxml");
File reportFile = new File(reportFileURL.toURI());
JasperDesign jasperDesign = JRXmlLoader.load(reportFile);
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, map, con);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608540",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SQL JOIN INNER or OUTER I have two tables:
users: id username clan
clans: id clan crest
I trying to do the search by username with output the clan of username.
Query:
SELECT `users`.`id`, `users`.`username`,`users`.`clan`, `clans`.`crest` FROM `users` JOIN `clans` ON `users`.`username` LIKE '%gu%'
Output:
id username clan crest
2 gusar 26_760.gif
3 gusar11 Tong 26_760.gif
If clan is empty crest will be empty.. But ... (
I want following result:
id username clan crest
2 gusar
3 gusar11 Tong 26_760.gif
A: If you want results from the first table, even when there are NO matches in the second table, you want to use a LEFT OUTER JOIN.
A: You're joining from one table to another using a LIKE, typically there is little reason why you would do this. Instead you likely want that in a WHERE clause, and you should be joining between the table using a foreign key.
You want to use a LEFT OUTER JOIN (or LEFT JOIN for short) to attempt to match all of the rows in the second table, but to show NULL values if there was no match:
SELECT `users`.`id`, `users`.`username`,`users`.`clan`, `clans`.`crest`
FROM `users`
LEFT JOIN `clans` ON `users`.`clan` = `clans`.`clan`
WHERE `users`.`username` LIKE '%gu%'
Mind you, in your users table, ideally you should hold the clan id and not the clan title. You would then use this query to perform your search:
SELECT `users`.`id`, `users`.`username`,`users`.`clan`, `clans`.`crest`
FROM `users`
LEFT JOIN `clans` ON `users`.`clanid` = `clans`.`id`
WHERE `users`.`username` LIKE '%gu%'
A: Try
SELECT `users`.`id`, `users`.`username`,`users`.`clan`, `clans`.`crest` FROM `users` LEFT JOIN `clans` ON `users`.`username` LIKE '%gu%'
A: You need to join the table using some condition. You're using an ON where you should use a WHERE. I assume users.clan relates to clans.clans? Try this:
SELECT `users`.`id`, `users`.`username`,`users`.`clan`, `clans`.`crest` FROM `users` LEFT JOIN `clans` ON `users`.`clan` = `clans`.`clan` WHERE `users`.`username` LIKE '%gu%'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608547",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Implement IDispatch::Invoke to be called by a WebBrowser control I'm trying to do what they explain on this article in the Controlling Download and Execution section. I understand the Web Browser Control in that context is not .NET's WebBrowser.
What I'm trying to do is to gain control over what the WebBrowser control downloads. I've been searching for this a lot and always en up in the csEXWB, which has a huge code that I just cannot decipher.
What I've done so far is inherit .NET's WebBrowser, make my inherited class com visible by using the [ComVisible(true)] attribute, add this method to my class (taken from csEXWB):
[DispId(HTMLDispIDs.DISPID_AMBIENT_DLCONTROL)]
public int Idispatch_AmbiantDlControl_Invoke_Handler()
{
return (int)m_DLCtlFlags;
}
And then call this line of code, where Browser is an instance of my derived class:
IfacesEnumsStructsClasses.IOleControl oleControl = Browser.ActiveXInstance as IfacesEnumsStructsClasses.IOleControl;
oleControl.OnAmbientPropertyChange(IfacesEnumsStructsClasses.HTMLDispIDs.DISPID_AMBIENT_DLCONTROL);
So what I'm hoping is that the oleControl will call my Idispatch_AmbiantDlControl_Invoke_Handler method, which it doesn't. I don't know how, and this is probably what my code is missing, is the oleControl supposed to know on which object to call my Idispatch_AmbiantDlControl_Invoke_Handler method.
What the article I linked above says is it will call your IDispatch::Invoke. What does it mean by your. How do I tell oleControl which object is my IDispatch. Hope I'm making any sense.
A: Here is a customized WebBrowser that allows you to change the DLCONTROL flags.
This is an example code:
public partial class Form1 : Form
{
private MyWebBrowser _webBrowser;
public Form1()
{
InitializeComponent();
_webBrowser = new MyWebBrowser();
_webBrowser.Dock = DockStyle.Fill;
Controls.Add(_webBrowser);
}
private void button1_Click(object sender, EventArgs e)
{
_webBrowser.DownloadControlFlags = (int)WebBrowserDownloadControlFlags.DOWNLOADONLY;
_webBrowser.Navigate("http://mysamplewebsite");
}
}
And the customized WebBrowser code:
public class MyWebBrowser : WebBrowser
{
private const int DISPID_AMBIENT_DLCONTROL = -5512;
private int _downloadControlFlags;
// we want our site class, not the default one
protected override WebBrowserSiteBase CreateWebBrowserSiteBase()
{
return new MyWebBrowserSite(this);
}
[DispId(DISPID_AMBIENT_DLCONTROL)]
public int DownloadControlFlags
{
get
{
return _downloadControlFlags;
}
set
{
if (_downloadControlFlags == value)
return;
_downloadControlFlags = value;
IOleControl ctl = (IOleControl)ActiveXInstance;
ctl.OnAmbientPropertyChange(DISPID_AMBIENT_DLCONTROL);
}
}
protected class MyWebBrowserSite : WebBrowserSite, IReflect
{
private Dictionary<int, PropertyInfo> _dispidCache;
private MyWebBrowser _host;
public MyWebBrowserSite(MyWebBrowser host)
: base(host)
{
_host = host;
}
object IReflect.InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters)
{
object ret = null;
// Check direct IDispatch call using a dispid (see http://msdn.microsoft.com/en-us/library/de3dhzwy.aspx)
const string dispidToken = "[DISPID=";
if (name.StartsWith(dispidToken))
{
int dispid = int.Parse(name.Substring(dispidToken.Length, name.Length - dispidToken.Length - 1));
if (_dispidCache == null)
{
// WebBrowser has many properties, so we build a dispid cache on it
_dispidCache = new Dictionary<int, PropertyInfo>();
foreach (PropertyInfo pi in _host.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
if ((!pi.CanRead) || (pi.GetIndexParameters().Length > 0))
continue;
object[] atts = pi.GetCustomAttributes(typeof(DispIdAttribute), true);
if ((atts != null) && (atts.Length > 0))
{
DispIdAttribute da = (DispIdAttribute)atts[0];
_dispidCache[da.Value] = pi;
}
}
}
PropertyInfo property;
if (_dispidCache.TryGetValue(dispid, out property))
{
ret = property.GetValue(_host, null);
}
}
return ret;
}
FieldInfo[] IReflect.GetFields(BindingFlags bindingAttr)
{
return GetType().GetFields(bindingAttr);
}
MethodInfo[] IReflect.GetMethods(BindingFlags bindingAttr)
{
return GetType().GetMethods(bindingAttr);
}
PropertyInfo[] IReflect.GetProperties(BindingFlags bindingAttr)
{
return GetType().GetProperties(bindingAttr);
}
FieldInfo IReflect.GetField(string name, BindingFlags bindingAttr)
{
throw new NotImplementedException();
}
MemberInfo[] IReflect.GetMember(string name, BindingFlags bindingAttr)
{
throw new NotImplementedException();
}
MemberInfo[] IReflect.GetMembers(BindingFlags bindingAttr)
{
throw new NotImplementedException();
}
MethodInfo IReflect.GetMethod(string name, BindingFlags bindingAttr)
{
throw new NotImplementedException();
}
MethodInfo IReflect.GetMethod(string name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers)
{
throw new NotImplementedException();
}
PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)
{
throw new NotImplementedException();
}
PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr)
{
throw new NotImplementedException();
}
Type IReflect.UnderlyingSystemType
{
get { throw new NotImplementedException(); }
}
}
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("B196B288-BAB4-101A-B69C-00AA00341D07")]
internal interface IOleControl
{
void Reserved0();
void Reserved1();
void OnAmbientPropertyChange(int dispID);
void Reserved2();
}
}
[Flags]
public enum WebBrowserDownloadControlFlags: uint
{
DLIMAGES = 0x00000010,
VIDEOS = 0x00000020,
BGSOUNDS = 0x00000040,
NO_SCRIPTS = 0x00000080,
NO_JAVA = 0x00000100,
NO_RUNACTIVEXCTLS = 0x00000200,
NO_DLACTIVEXCTLS = 0x00000400,
DOWNLOADONLY = 0x00000800,
NO_FRAMEDOWNLOAD = 0x00001000,
RESYNCHRONIZE = 0x00002000,
PRAGMA_NO_CACHE = 0x00004000,
NO_BEHAVIORS = 0x00008000,
NO_METACHARSET = 0x00010000,
URL_ENCODING_DISABLE_UTF8 = 0x00020000,
URL_ENCODING_ENABLE_UTF8 = 0x00040000,
NOFRAMES = 0x00080000,
FORCEOFFLINE = 0x10000000,
NO_CLIENTPULL = 0x20000000,
SILENT = 0x40000000,
OFFLINEIFNOTCONNECTED = 0x80000000,
OFFLINE = OFFLINEIFNOTCONNECTED,
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608550",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: How to create custom ToolStripProgressBar in C# Windows forms? How to create custom ToolStripProgressBar in C# Windows forms?
I want to create a progressbar with the style as continuos but in windows xp it is not possible..
So how can I set owner draw for this control ?
A: I can give you more Information on the ToolStripControlHost, I created a ProgressBar using this with the following code
public class ToolStripProgressBarC : ToolStripControlHost
{
// Call the base constructor passing in a ProgressBar instance.
public ToolStripProgressBarC() : base(new ProgressBar())
{
((ProgressBar)Control).Style = ProgressBarStyle.Continuous;
}
public ProgressBar ProgressBarControl
{
get
{
return Control as ProgressBar;
}
}
// Expose the ProgressBar.Value as a property.
public int Value
{
get
{
return ProgressBarControl.Value;
}
set { ProgressBarControl.Value = value; }
}
}
I then added it to my tool strip like so.
ToolStripProgressBarC tsp = new ToolStripProgressBarC();
tsp.Value = 90;
toolStrip1.Items.Add(tsp);
You should be able to do any extra overriding that you want by adding extra functions to the "ToolStripProgressBarC" class.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608556",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Getting sunshine data from latitude and longitude in php I am working on a site which requires sunshine (hours of sun in a day )data of a location.
I have the laitude and longitude of the location but now i have to determine the hours of the sun per day on that location.For example say i have a location 'NewYork'.now i need to know
number of hours of suns in a day in a month .So i have to determine the followimng data
january-8 hours
fabruary-6 hours
means in newyork in january there is 8 hours of sun and so on.
Is some one know from where i can get that data . i am using php
A: Who'd've thunk, PHP has a function for that!
http://php.net/manual/en/function.date-sun-info.php
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608557",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Parsing time string with SimpleDateFormat I have a problem parsing just the time string from my database
private static final String TIME_FORMAT = "HH:mm:ss";
public static final SimpleDateFormat timeFormat = new SimpleDateFormat(TIME_FORMAT, Locale.getDefault());
And following the output:
String time = "17:17:57";
Date myParsedDate = timeFormat.parse(time); //forget the exception thing
//output of myParsedDate.toString = "Thu Jan 01 16:47:57 GMT+08:00 1970"
It seems as though theres a problem with the locale or something.. just a simple string.. Why is this so? i just want the date to be the having the time i need for my time picker.. gee..
Edit
Because i am using a static time format i decided to use my little helper method
public static Date getTimeFromTimeString(String timeString)
{
String[] splitStrings = timeString.split(":");
Date timeDate = new Date();
timeDate.setHours(Integer.parseInt(splitStrings[0]));
timeDate.setMinutes(Integer.parseInt(splitStrings[1]));
timeDate.setSeconds(Integer.parseInt(splitStrings[2]));
return timeDate;
}
Thanks for the help Jon Skeet.. I believe it is the TimeZone offset that is causing this.. .. ill just stick to my little method..
A: The problem is you're printing out the result of Date.toString() - which always shows the results in the system time zone. That's probably not what you want.
The Date itself has no concept of a time zone - it's just an instant in time.
I would suggest you use Joda Time if at all possible. That has a LocalTime which actually represents what you're parsing here.
EDIT: Just to reiterate what's in the comment... I suspect that the time zone in your DateFormat is not the same as the time zone used by Date.toString. For simplicity, it's probably worth setting the DateFormat's time zone to UTC, and then if you want to convert to a Calendar you should set that time zone to UTC as well before calling setTime(date).
A: Just do this:
Calendar c = Calendar.getInstance();
c.setTime(myParsedDate);
int hours = c.get(Calendar.HOUR);
int mins = c.get(Calendar.MINUTE);
int seconds = c.get(Calendar.SECOND);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608562",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Using NSLog to print navigationType I have the following paragraph:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType *)navigationType {
NSURL * url = [request URL];
NSRegularExpression* regex = [[NSRegularExpression alloc] initWithPattern:@"loggedout" options:(NSRegularExpressionOptions)NSCaseInsensitiveSearch error:NULL];
NSString *urlString = [url absoluteString];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:urlString options:0 range:NSMakeRange(0, [urlString length])];
[regex release];
if (numberOfMatches > 0) {
// NSLog(@"%@", url);
// NSLog(@"%i", numberOfMatches);
[self.navigationController popViewControllerAnimated:YES];
return NO;
}
if (UIWebViewNavigationTypeLinkClicked == navigationType)
{
[[UIApplication sharedApplication] openURL:url];
return NO;
}
return YES;
}
I would like to print the "navigationType" variable with NSLog, but I am unable to find a format specifier (e.g.: @"%@" or @"%d") that is compatible with the variable or does not cause the app to crash. Can anyone advise?
A: Try NSLog(@"NavigationType: %i", navigationType);
A: UIWebViewNavigationTypeLinkClicked is typedef on NSUInteger.
Use %lu format specifier to print out the value.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608565",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Django url pattern with or without as path to view? I'm new to Django and been reading the http://djangobook.com and finds that the following two patterns work the same way with no hiccups for project named mysite and views.py on the project root with a function named hello.
(r'^hello/$', 'mysite.views.hello')
(r'^hello/$', 'views.hello)
May I know what's the practice like? with or without the proceeding Project namespace? And if I may, why?
'' is the prefix for these patterns.
A: the fisrt one is because the mysite dir is in your python path;
the second one is because when your run the project, the current path will add to python path.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608576",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: exception: current-continuation-marks: no corresponding prompt in the continuation: # why do i get exception on (redirect/get) in this program
#lang web-server
(require web-server/formlets web-server/page) (struct app (nm) #:mutable)
(define (start req) (render-main-page req))
this function is to be used by most pages and generates comlete page xexpr by calling each given piece of page generator functions, each of which may embed their urls
(define (render-page embed/url a-title blocks)
(response/xexpr `(html (head (title ,a-title)
(body ,@(map (lambda (block) (block embed/url)) blocks))))))
this is piece of first page generator function
(define (render-action-panel embed/url action)
`(a ([href ,(embed/url action)]) "New"))
this is first page
(define/page (render-main-page)
(local [(define (new-handler req) (render-app-page req (app "new value")))
(define (panel-block embed/url) (render-action-panel embed/url new-handler))]
(render-page embed/url "Title" (list panel-block))))
this is piece of second page generator function (represents form)
(define (add-app-formlet an-app) (formlet (#%# ,{=> input-string nm}) nm))
(define (render-app-form embed/url an-app save-handler)
`(div (form ([action ,(embed/url save-handler)][method "POST"])
(span ,@(formlet-display (add-app-formlet an-app) ))
(span (input ([type "submit"][value "Save"]))))));)
the second form,
save handler throws exception when trying do post-redirect-get
(define/page (render-app-page an-app)
(local [(define (save-handler req)
(render-app-page
(redirect/get)
(set-app-nm! an-app (formlet-process (add-app-formlet an-app) req))))
(define (form-block embed/url)
(render-app-form embed/url an-app save-handler ))
]
(render-page embed/url "Title - form: " (list form-block))))
(require web-server/servlet-env)
(serve/servlet start)
A: Which redirect/get are you using?
The one from web-server/lang/servlet (which should be used with #lang web-server) is different than the one from web-server/servlet (which should be used with #lang racket (and friends))
This error message means that you are using the one from web-server/servlet.
FWIW, web-server/page cannot be used with #lang web-server because it is just a simple macro over the send/suspend/dispatch from web-server/servlet.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608577",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to make UIButton always on top, and change able to change the subviews? I am using two views that are UIScrollView and UITextView. When program runs, UIScrollView displays. User can scroll it horizontally and paging enabled. If he taps on it the UITextView (which was at back side) comes forward in flip animation. To go back he needs to press back button (at navigation bar) then UIscrollView Comes forward. I am doing this just by detecting the superview and put the back view at front. All things are working good. Now, I have been asked to put next previous button at UIScrollView by pressing using can move left or right. The buttons will be clear colored background and an image at forground. So that looks like arrow.
I was thinking for it an got the idea to put UIButton at always on top and make flip in it.
I dont know that it will work or not.
Please tell me any idea if you think different or any sample/tutorial code to achieve this.
Thanks in advance
A: I'm not sure I understand what you want to do, but you can adjust Z position of views using those functions :
- (void)insertSubview:(UIView *)view belowSubview:(UIView *)siblingSubview;
- (void)insertSubview:(UIView *)view aboveSubview:(UIView *)siblingSubview;
- (void)bringSubviewToFront:(UIView *)view;
- (void)sendSubviewToBack:(UIView *)view;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608580",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Update a JAR file on UNIX system I have a JAR file on a UNIX system for which owner is a different user.
Is there a way in which I can add or update a .class file present in the JAR archive?
A: If you have permission to write to the file then yes, like this:
jar uf foo.jar foo.class
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608581",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Apart from MySQL concurrent connection limit, does PHP/Apache play any role on dropping connections? If MySQL is dropping connections in a PHP application, and MySQL connection limit is set above the number of concurrent users in the application, which other factors can contribute to this behavior? Also, analyzing moodle logs (the only app running at these servers), yesterday I had 4 times more activity and it didn't drop anything, but today there were times where it was frustrating the number of dropped connections.
My main question here is why the database is rejecting connections when it didn't before with 4 times more activity (and everything it's the same, I didn't change anything in between).
Some background: I've got 2 servers contracted at my hosting:
*
*shared server running Debian Linux/PHP 5.3 (FastCGI)
*VPS running Debian Linux/MySQL 5.1.39
On this environment I'm running only moodle 1.9.12 (for the database connection using adoDB and persistent connections), php part on the shared server, database on the VPS. I suspect that, by PHP running on a shared server, other hosting accounts are affecting me (the database rejecting connections I mean, I really don't care about RAM/CPU).
Reading about the issue I've seen in places that persistent connections don't work well with PHP as CGI/FastCGI and that if both servers are in the local lan it really doesn't matter using persistent or not persistent connections because of the connection is going to be quick anyway. So now I'm using not persistent connections. I guess that may be part of the problem, but I fail to understand why it worked with more load. Which PHP/Apache settings are involved here?
A: Since your database and web server are on two different machines, there are two other possible causes: the network in between, and the network layer of the operating system.
If you did not change anything in your configuration and it worked with higher loads before, it is more likely to be an issue with the network connectivity between the two machines. Since the database machine is a VPS you also don't know how much real network load it is handling. If your ISP has competent support personnel (which unfortunately isn't always the case) it can't hurt to ask them if they have an explanation.
The same goes for your "shared" web-server. While it is unlikely, it is not impossible that it is a an issue of too many connections on that machine.
It would also help to know how exactly you are measuring dropped connections. If you are looking at the aborted-connections counter of mySQL, it is not necessarily a measure of an actual problem: http://dev.mysql.com/doc/refman/5.1/en/communication-errors.html. A user aborting a page load already may increase this counter.
If PHP throws an error, because it could not connect to the server or lost connection to the server during a query, then it is an issue.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608582",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What formatting can RSS readers reliably interprete? Im making a normal RSS feed for my website. I need to include simple html formatting in the description eg paragraphs, line breaks, lists, etc. To do this I need to wrap the description content as CDATA.
The issue with this is that when I validate my feed the content of the CDATA is ignored. So although the feed validates, I dont actually know if everything is ok or not.
How can I find out what markup will likely be read ok by the various RSS readers?
Can I use whatever markup I would happily put in a website? How about inline styles? Or is more like designing html emails? Thanks
A: RSS files are XML Formatted plain text, I think that's the only standard you can rely upon.
I think most Syndicators look like they're handling HTML in RSS as they simply download the linked article when you choose the header.
If you're looking to embed rich content, then you may well be better investigating Atom instead of RSS.
Have a look at this S/O question: Which is better for encoding HTML for RSS?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608593",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: .net MVC 2 controller inheritance I have i little problem with inheritance of my controllers for example :
public class AController: Controller {
public ActionResult Index(long id)
{
return Index(id, isComposite);
}
}
public class BController : AController {
}
when i click on ../B/Index/12 i get following exception : the view 'Index' or its master was not found. The following locations were searched: ~/Views/B/Index.aspx
I can copy Index.aspx into "Shared" map but may be there is other workaround ?
Thanks .
A: You could put it in ~/Views/Shared/Index.aspx but in ASP.NET MVC it is better to avoid such type of controller inheritance.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608597",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Style of Select element behaviors different between IE 8 and FF I have a select element, and want to change select itself as black background, white fore color, but have options be while background, black fore color.
It works fine in FF, but in IE, select element 'inherits' its option's style.
I worked out the snippet at here http://jsfiddle.net/qc8gV/1/
You maybe want to open it in FF and IE to see what it looks different in the two browsers.
Is there anyone know how to solve it? Thanks.
A: Styling form controls is a tricky business, as the browser has control over them.
In many cases, leaving it up to the browser is a good idea, as the user of the browser is used to having the controls looking as they do.
456bereastreet have a very good write up about stylying form controls and what you can achive in what broswer: http://www.456bereastreet.com/archive/200409/styling_form_controls/
That link is a little out of date, so here is a more up to date one (thought notably still quite old, its still useful): http://www.456bereastreet.com/archive/200701/styling_form_controls_with_css_revisited/
I hope this helps
Alex.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608600",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jQuery Template Ignores String.Empty Values I have an ASP .Net Webservice which returns a System.Data.DataTable like object (contains rows and columns, with the cell values being strings) which is serialised to JSON.
I want use this data table JSON result to populate an HTML table using jQuery Template.
If a row contains an empty cell (String.Empty) I still want it to print <td></td> else my table structure will get messed up. jQuery template seems to be treating String.Empty as null and skipping it rather than including an empty table cell.
Example of my JSON row
{"ItemArray":["Job 1 Status","Completed","","Active","Failed","Completed"]}]}
Example of my templates
<script id="tableRowTemplate" type="text/x-jquery-tmpl">
<tr>{{tmpl(ItemArray) "#tableRowCellTemplate"}}</tr>
</script>
<script id="tableRowCellTemplate" type="text/x-jquery-tmpl">
<td>${}</td>
</script>
I am using jQuery 1.6.4 and jQuery template 1.0.0pre. I could quite easily replace String.Empty with a pending status and then check for this in my template, but I would rather not do a workaround.
Update: The jQuery template project has been abandoned in its current form.
A: This question seems to have become active again—unlike this jQuery template project.
The jQuery template project is dead and never made it out of beta, so the answer is that there is no solution.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608601",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Importance of constant class If I put constant variable values directly in classes, its panic when this value get changes.
If i make a constant class to keep such constants it helps to do changes in one class only. But again I need to identify all the classes which are using these constants. Because recompilation is required.
then what is the need of separate constant class?
suggest me another way to manage constants, if better.
A: Use property file instead of making constant class
A: I would NEVER use a class for all of my constants.
I would also NEVER use a class for all my integers, or for all strings, or one class for all final variables and another class for all static variables, etc.
Group your members by function, not by a language feature.
If i make a constant class to keep such constants it helps to do changes in one class only.
Following that logic, you could put your whole project in a single class.
A: I'm pretty new to JAVA and not sure to understand your question very well, but what about something like a file Points.java (for the example, but you can make this for Strings, int, Objects... or any types) where you have :
package classes;
import java.awt.Point;
public enum Points {
FIRST_POSITION(0,50,50),SECOND_POSITION(1,150,200),THIRD_POSITION(2,175,200),FOURTH_POSITION(3,175,200);
private int index;
private Point point;
private Points(int index,int x, int y){
this.index = index;
this.point = new Point(x, y);
}
public int getIndex() {
return index;
}
public Point getPoint() {
return point;
}
}
You may use multiple constructors for different properties (but I'm not sure that this last possibility could be a good technique since certain getters may differ in names...)
And you can retrieve values everywhere like :
System.out.println(Points.FIRST_POSITION + ", index[" + Points.FIRST_POSITION.getIndex() + "]" + ", position:" + Points.FIRST_POSITION.getPoint());
System.out.println(Points.SECOND_POSITION + ", index[" + Points.SECOND_POSITION.getIndex() + "]" + ", position:" + Points.SECOND_POSITION.getPoint());
System.out.println(Points.THIRD_POSITION + ", index[" + Points.THIRD_POSITION.getIndex() + "]" + ", position:" + Points.THIRD_POSITION.getPoint());
System.out.println(Points.FOURTH_POSITION + ", index[" + Points.FOURTH_POSITION.getIndex() + "]" + ", position:" + Points.FOURTH_POSITION.getPoint());
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608607",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: IEWC Treeview refreshing to top of page on click I am using an IEWC webcontrol in ASPX/C# page and whenever a treeview element is clicked, it will refresh to the top of the page. Is there any way to stop this?
It now works fine in IE with the addition of Autopostback and Viewstate set to True. Just not in Chrome.
(Note: I am well aware that IE web controls were never meant to work 100% outside IE)
A: This was fixed by adding in a piece of jQUery that searches for the element's parent ID and removes the HREF on the nodes.
Alternatively, you can set a session parameter that remembers the scrollX and re-set this on page load
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608613",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Use Library with JNI in NetBeans WebApp I have developed a WebApp with Java-NetBeans. Now I have a library (List&Label from combit) what I want to use in it. I have all to use it in Java-Desktop-Application (JNI-Dll, Definitions). Now, I would ask, if there is a way to use it with WebApp (in a Servlet) and how to do this.
A: I have solved my problem. I have only to integrate the Declarations and Load the Dll with loadLibrary and all is working.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608614",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: PHPUnit Integration into NetBeans 7 I am trying to get PHPUnit working in Netbeans. I was using 3.4.9 but that refused to work and it was suggested to upgrade to the latest version. I have now upgraded to 3.5.15 and when I run it I get the following message:
unrecognized option --log-xml
I understand that this is not a valid logging option, however I do not know where this is being set or how to change it. My phpunit.xml file is:
<phpunit bootstrap="./application/bootstrap.php" colors="true">
<testsuite name="Personal Development">
<directory>./</directory>
</testsuite>
<filter>
<whitelist>
<directory suffix=".php">../application/</directory>
<exclude>
<file>../application/Bootstrap.php</file>
<file>../application/controllers/ErrorController.php</file>
<directory suffix=".phtml">../application/</directory>
</exclude>
</whitelist>
</filter>
<logging>
<log type="coverage-html" target="./log/report" charset="UTF-8"
yui="true" highlight="true" lowUpperBound="50" highLowerBound="80"/>
<log type="testdox-html" target="./log/testdox.html" />
</logging>
</phpunit>
How do I fix this error?
A: In order to force PHPUnit to use the correct files, I had to right click on the project name, Set Configuration, Customize, PHPUnit, then specify implicitly where the bootstrap and XML Config files were.
A: I encountered a similar problem using XAMPP, PHPUnit 3.5 and NetBeans 7. The problem is, that NetBeans for some reason always passes the option "--log-xml" to phpunit.bat, but this option does not exist in PHPUnit 3.5 any more.
My solution was to edit the PHPUnit configuration XML file:
C:\xampp\php\PEAR\tests\MIME_Type\tests\phpunit.xml
(Note that the file path depends on the path your PEAR or PHPUnit installation is located!)
I had to append a new node, "logging":
<?xml version="1.0" encoding="utf-8"?>
<phpunit strict="true" colors="true"
bootstrap="bootstrap.php"
>
<filter>
<whitelist>
<directory suffix=".php">../MIME/</directory>
</whitelist>
</filter>
<logging>
<log type="junit" target="c:/xampp/tmp/logfile.xml" logIncompleteSkipped="false"/>
</logging>
</phpunit>
After this change, NetBeans does not pass the "--log-xml" option anymore, but the "--log-junit" option, which is valid for PHPUnit 3.5. MyTests do now validate again. :-)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608615",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Submit automatically an RSS feed to RSS Feeds directory How can I submit an RSS Feed automatically to a list of RSS Feeds directory?
A: You'd probably be better off by using an existing service, such as Ping-o-matic. Wordpress also lists several other XML-RPC ping services in their Codex.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608616",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: is possible to have accent sensitive and case insensitive utf8 collation in mysql? How can I perform accent-sensitive but case-insensitive utf8 search in mysql? Utf8_bin is case sensitive, and utf8_general_ci is accent insensitive.
A: If you want to differ "café" from "cafe"
You may use :
Select word from table_words WHERE Hex(word) LIKE Hex("café");
This way it will return 'café'.
Otherwise if you use :
Select word from table_words WHERE Hex(word) LIKE Hex("cafe");
it will return café.
I'm using the latin1_german2_ci Collation.
A: There doesn't seem to be one because case sensitivity is tough to do in Unicode.
There is a utf8_general_cs collation but it seems to be experimental, and according to this bug report, doesn't do what it's expected to when using LIKE.
If your data consists of western umlauts only (ie. umlauts that are included in ISO-8859-1), you might be able to collate your search operation to latin1_german2_ci or create a separate search column with it (that specific collation is accent sensitive according to this page; latin1_general_ci might be as well, I don't know and can't test right now).
A: You can use "hex" to make the search accent-sensitive. Then simply add lcase to make it case insensitive again. So that would give:
SELECT name FROM people WHERE HEX(LCASE(name)) = HEX(LCASE("René"))
You do throw all your indexes out of the window like that. If you want to avoid having to do a full table scan and you have an index on "name", also search for the same thing without the hex and lcase:
SELECT name FROM people WHERE name = "René" and HEX(LCASE(name)) = HEX(LCASE("René"))
This way the index on "name" will be used to find for example only the rows "René" and "Rene" and then the comparison with the "hex" needs to be done only on those two rows instead of on the complete table.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608617",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Make hit test visible property different for grid rows I have a grid that contains 3 rows, one of which contains a TextBox thats can be edited. The grid sits inside a paretn that provides drag functionality to enable it to moved around a canvas. In order to enable this, i need to set IsHitTestVisible to false, in order to allow the mouse click to passed through to the parent object.
The problem is, when i do this, i cant select the textbox in the grid, even if the hit test visible is set to True;
<Grid Background="{StaticResource NodeBackground}" IsHitTestVisible="True">
<Grid.RowDefinitions>
<RowDefinition Height="2*"/>
<RowDefinition Height="1*"/>
<RowDefinition Height="2*"/>
</Grid.RowDefinitions>
<TextBox Text="{Binding Data}" Foreground="White" Background="Transparent" FontFamily="Consolas" FontSize="15" TextAlignment="Center" Grid.Row="1" BorderThickness="0" />
</Grid>
Is it possible to set the hit test property on a per-row basis, so if either of the two empty rows were hit, they would continue to pass the click onto the parent container, but still be able to select the textbox in the middle row?
Cheers.
A: I'm not certain your Drag/Drop code, but perhaps you can use a Trigger, where IsHitTestVisible is False only if you are dragging an item, and the rest of the time it's True.
As a side note, I've had issues in the past using WPF's built-in DragDrop functionality and hit testing. I find it much simpler to use MouseEvents instead, such as tracking MouseEnter/MouseLeave events for dragging
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608618",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Optimistic concurrency with Entity Framework and MySQL I'm currently developing an app using Entity Framework 4.1 and MySQL. I want to use optimistic concurrency and therefore need to create a table structure which allows EF to detect concurrency issues. My goal is something similar to this: http://blogs.msdn.com/b/alexj/archive/2009/05/20/tip-19-how-to-use-optimistic-concurrency-in-the-entity-framework.aspx.
My problem is that the timestamp-type is different in MySQL compared to MS SQL Server. In addition to that neither timestamp nor datetime offer sub-second precision in MySQL (http://feedblog.org/2007/05/26/why-doesnt-mysql-support-millisecond-datetime-resolution/). These types would therefore be quite bad in detecting concurrency-problems.
What other data-type could I use to solve this? I was thinking of maybe using a Guid. There are two potential problems with this approach though: 1. MySQL stores Guids as char(36) making them very inefficient. 2. I'm not sure if the EF requires the row-version to be strictly increasing or if it's enough that it's unique.
A: Big caveat: NOT TESTED - just thinking aloud.
EF supports override of SaveChanges, so perhaps one option is to define an interface such as:
interface IVersionedRow {
int RowVersion {get;set;}
}
and add an int RowVersion property/field to both your model class(es) and the database table(s), and use partial class to implement this interface (using implicit interface implementation):
partial class Customer : IVersionedRow {}
partial class Order : IVersionedRow {}
...
Then override SaveChanges, something like:
public override int SaveChanges(SaveOptions options)
{
foreach (ObjectStateEntry entry in
ObjectStateManager.GetObjectStateEntries(EntityState.Modified))
{
var v = entry.Entity as IVersionedRow;
if(v != null) v.RowVersion++;
}
return base.SaveChanges(options);
}
that should then function (in theory - untested) as a manually implemented row-version counter. Leave change-validation enabled for RowVersion, and that should serve.
A: This is tested solution (for EF6 and above).
Here what you have to do in your model:
[Table("some_table")]
public class SomeEntity : IVersionedRow //define an interface as described previously and replace int type to long
{
...
[Column("row_version")]
public long RowVersion { get; set; }
}
Then in your context:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<SomeEntity>()
.Property(p => p.RowVersion).IsConcurrencyToken();
base.OnModelCreating(modelBuilder);
}
public override int SaveChanges()
{
var objectContextAdapter = this as IObjectContextAdapter;
if (objectContextAdapter != null) {
objectContextAdapter.ObjectContext.DetectChanges();
foreach (ObjectStateEntry entry in objectContextAdapter.ObjectContext.ObjectStateManager.GetObjectStateEntries(EntityState.Modified)) {
var v = entry.Entity as IVersionedRow;
if (v != null)
v.RowVersion++;
}
}
return base.SaveChanges();
}
Now when you do update or delete operation don't forget to include DbUpdateConcurrencyException . It works perfect for me.
A: I have just submitted a PR to MySQL .NET Connector v6.9.10 that provides a solution for this issue that provides optimistic locking between EF and non-EF applications. See https://stackoverflow.com/a/50147396/365261 for details.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608619",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: RadGrid Double Click with Single Click I have a requirement to fire a client side event on Telerik RadGrid Row Double Click, and an update fetching from server on single click. But Double click event doesn't work. If I remove "EnablePostBackOnRowClick" option, then it works fine. How can I use both? Here is my code
<ClientSettings AllowGroupExpandCollapse="True" ReorderColumnsOnClient="false" AllowDragToGroup="false"
AllowColumnsReorder="false" EnablePostBackOnRowClick="true" >
<ClientEvents OnRowDblClick="RowDblClick" />
</ClientSettings>
A: One technique is to separate the low-level 'click handler' from 'single-click' and 'double-click' logic, and set window.setTimeout() initially to fire the 'single-click' logic.
If the low-level click handler is invoked again before the timer has fired, then it is is a double-click; and the timer is cancelled.
See Jayesh's example on this forum:
http://www.telerik.com/forums/how-to-detect-single-and-double-click-in-itemcommand-of-radgrid
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608627",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: shifting controller function to library in codeigniter I am trying to put this function ((click_add)) in library so that i can call it from all the controllers. I already have get_ads() function in library. I tried various ways to shift the click_add(id) function to library and call it to view along with get_ads but doesn't work. Please help
function __construct() {
parent::__construct();
$this->load->library('ads');
$this->load->model('MGlobal');
}
public function index(){
$data['banner']= $this->ads->get_ads();
$this->load->view('test',$data);
}
//i want this in library but no luck
public function click_add($ads_id){
$ads_site = $this->MGlobal->getAds($ads_id);
$this->MGlobal->add_ads_view();
redirect($ads_site['url']);
}
//and views is like this
foreach($banner as $k=>$list){
echo anchor('test/click_add/'.$list['bannerid'],'<img src="'. $list['image']. '"/>');
}
please suggest me how do i achieve that with library
A: It's also important to remember the role of each part of the MVC pattern. In your click_add() method, it looks like you're rendering a view and causing a redirect. These are two things best suited for a controller rather than a library. Rendering views and redirecting are two things that must be a controller's responsibility, and indeed, you won't be able to access them through the URL, which is what you're trying to do here.
If you want to reuse this method across multiple controllers in your site, try creating a MY_Controller core class and extending your controllers from that. That way, any methods you define in the MY_Controller will be available in any controller you subclass from.
Without any specific error messages or a more verbose description of the problem you're having, I'm afraid there's little more help I can give you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608628",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I get the current version of my iOS project in code? I would like to be able to get the current version of my iOS project/app as an NSString object without having to define a constant in a file somewhere. I don't want to change my version value in 2 places.
The value needs to be updated when I bump my version in the Project target summary.
A: You can get the version and build numbers as follows:
let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
let build = Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as! String
or in Objective-C
NSString * version = [[NSBundle mainBundle] objectForInfoDictionaryKey: @"CFBundleShortVersionString"];
NSString * build = [[NSBundle mainBundle] objectForInfoDictionaryKey: (NSString *)kCFBundleVersionKey];
I have the following methods in a category on UIApplication:
extension UIApplication {
static var appVersion: String {
return Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
}
static var appBuild: String {
return Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as! String
}
static var versionBuild: String {
let version = appVersion, build = appBuild
return version == build ? "v\(version)" : "v\(version)(\(build))"
}
}
Gist: https://gist.github.com/ashleymills/6ec9fce6d7ec2a11af9b
Here's the equivalent in Objective-C:
+ (NSString *) appVersion
{
return [[NSBundle mainBundle] objectForInfoDictionaryKey: @"CFBundleShortVersionString"];
}
+ (NSString *) build
{
return [[NSBundle mainBundle] objectForInfoDictionaryKey: (NSString *)kCFBundleVersionKey];
}
+ (NSString *) versionBuild
{
NSString * version = [self appVersion];
NSString * build = [self build];
NSString * versionBuild = [NSString stringWithFormat: @"v%@", version];
if (![version isEqualToString: build]) {
versionBuild = [NSString stringWithFormat: @"%@(%@)", versionBuild, build];
}
return versionBuild;
}
Gist: https://gist.github.com/ashleymills/c37efb46c9dbef73d5dd
A: In Objective C:
1)For getting App version you have to use a:
NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
2)For getting Build version you have to use a:
NSString *buildVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
A: [Swift version: 5.2]
All iOS apps must store an app version number in their Info.plist file, but there’s no build-in way to get that as a string you can use in your code.
I have created one small extension to UIApplication that reads the Info.plist file and returns a version number automatically.
Here’s the code:
extension UIApplication {
static var appVersion: String? {
return Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String
}
}
Inside Your Controller
@IBOutlet weak var tv_version: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
//Display Version
setUpCurrentVersion()
}
func setUpCurrentVersion(){
tv_version.text = "v" + UIApplication.appVersion!
}
A: Here's what worked on Xcode 8, Swift 3:
let gAppVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") ?? "0"
let gAppBuild = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") ?? "0"
print("Version: \(gAppVersion)")
print("Build: \(gAppBuild)")
A: In Swift, you can get bundle version by using:
let info:NSDictionary = NSBundle.mainBundle().infoDictionary!
let version:String = info.objectForKey("CFBundleShortVersionString") as! String
versionLabel.text = "Version:" + version
A: An open source project of mine, App Update Tracker, offers this functionality (and more) in the form of class methods:
*
*+ (NSString *)getShortVersionString
*+ (NSString *)getLongVersionString
You would use it like so:
#import "AppUpdateTracker.h"
NSLog(@"short version: %@", [AppUpdateTracker getShortVersionString]);
NSLog(@"long version: %@", [AppUpdateTracker getLongVersionString]);
A: So heres a Swift version for both of these separately:
let versionNumber = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String
let buildNumber = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleVersion") as! String
Its included in this repo, check it out:
https://github.com/goktugyil/EZSwiftExtensions
A: Just for note
To obtain localized value of any key you should use CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(), "CFBundleShortVersionString" as CFString)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608632",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "163"
}
|
Q: Error in insert query of sqlite I am making an iphone app, in which I am using sqlite. In one class when I tried to insert a string it get crash and giving the following error
-[CFString UTF8String]: message sent to deallocated instance 0xe555220
I don't know Why it is happening.
Following is the insert query which I am implementing.
-(void)againinsert
{
sqlite3_stmt *addStmt = nil;
if(addStmt == nil)
{
NSString *str = @"don't know";
const char *sql = "insert into medicationdetail1(doctorname, emailid, medicationname, status) values (?,?,?,?)";
if(sqlite3_prepare_v2(database, sql , -1, &addStmt, NULL) != SQLITE_OK)
{
NSAssert1(0, @"Error while creating add statement. '%s'", sqlite3_errmsg(database));
}
sqlite3_bind_text(addStmt, 1, [comparedoctorname UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStmt, 2, [globalemail UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStmt, 4, [comparemedic UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStmt, 7, [str UTF8String], -1, SQLITE_TRANSIENT);
if(SQLITE_DONE != sqlite3_step(addStmt))
{
NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database));
}
}
}
When the breakpoint moves from second to third statement it get crash.
Please provide the solution.
Thanku very much.
A: use this one
sqlite3_bind_text(addStmt, 3, [comparemedic UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStmt, 4, [str UTF8String], -1, SQLITE_TRANSIENT);
A: USE
sqlite3_bind_text(addStmt, 1, [comparedoctorname UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStmt, 2, [globalemail UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStmt, 3, [comparemedic UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStmt, 4, [str UTF8String], -1, SQLITE_TRANSIENT);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608635",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to convert UTF8 characters to numeric character entities in PHP Is a translation of the below code at all possible using PHP?
The code below is written in JavaScript. It returns html with numeric character references where needed. Ex. smslån -> smslån
I have been unsuccessful at creating a translation. This script looked like it may work, but returns å for å instead of å as the javascript below does.
function toEntity() {
var aa = document.form.utf.value;
var bb = '';
for(i=0; i<aa.length; i++)
{
if(aa.charCodeAt(i)>127)
{
bb += '&#' + aa.charCodeAt(i) + ';';
}
else
{
bb += aa.charAt(i);
}
}
document.form.entity.value = bb;
}
PHP's ord function sounds like it does the same thing as charCodeAt, but it does not. I get 195 for å using ord and 229 using charCodeAt. That, or I am having some incredibly difficult encoding problems.
A: Use mb_encode_numericentity:
$convmap = array(0x80, 0xffff, 0, 0xffff);
echo mb_encode_numericentity($utf8Str, $convmap, 'UTF-8');
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608643",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: SCSS Support in Aptana 3.0.4 Eclipse Plugin? Is there a full scss support in the apatana eclipse plugin 3.0.4?
The editor assigns the sass-editor, but there seems to be no coloring available. source format also don't make anything.
A: The basic SCSS support - syntax coloring, folding - is there in 3.0.4; if you see any issues around those areas, please file a ticket at http://jira.appcelerator.org/browse/APSTUD. Formatting and outline are not available yet. You could also add feature request for each specific feature at JIRA.
Hope this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608644",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: while loop within foreach I've got a form with questions which gets answered. Then on the following page I'm trying to validate the questions to see if the answer is correct or not because eventually I must work out a percentage for the test.
$tid1 = $_SESSION['tid'];
$departmentid = $_SESSION['deptid'];
$userid = $_SESSION['userid'];
foreach($_POST['question'] as $key => $answer) {
include 'datalogin.php';
mysql_query("INSERT INTO ex_answer (id,class_name,testname,name,percentage,qnr,answer_chosen,points_scored,result)
VALUES ('0','$departmentid','$tid1','$userid','0','$key','$answer[0] $answer[1] $answer[2] $answer[3] $answer[4] $answer[5] $answer[6] $answer[7] $answer[8]','0','0')");
$sql1="SELECT * FROM ex_question WHERE test_name = '$tid1' AND q_nr = '$key'";
$result1=mysql_query($sql1);
while($row1 = mysql_fetch_array($result1)) {
$q_nr=$row1['q_nr'];
echo $q_nr;
}
}
The problem is (I think) that it is not selecting the question number q_nr = '$key' correctly from the table because echo $q_nr gives no output
A: Use mysql_fetch_assoc to be able to use column name indexes on returned array.
A: If you are getting a valid result (Test the sql in your Database client ) then you should just use the following to access it as an associative array:
mysql_fetch_assoc($result1);
instead of the mysql_fetch_array() or use
mysql_fetch_array($result1, MYSQL_ASSOC)
Test what is being returned to you, comment out your while loop and then do:
$row1 = mysql_fetch_array($result1);
print_r($row1);
before you while loop add the following for validation:
if (!$result1) {
die('Could not query:' . mysql_error());
}
A: You can also output the SQL and test it on the DB, that will show that you are getting the expected results
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608645",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Anything to attend when changing values in a multidimensional foreach() loop? I got a site that executes the following code
$keywords = ($_SESSION[$_POST['ts']]);
print_r($keywords);
foreach ($keywords as $keyword) {
foreach ($keyword['whitelist'] as $entry) {
foreach ($_POST as $key => $value) {
if ($key == $entry['encoded_url']) {
$entry['ignore'] = $value;
$decodedURL = $this->base64->url_decode($entry['encoded_url']);
if ($value == 'noignore') {
echo "found!<br />";
$this->blacklist_model->remove($decodedURL);
$html = $this->analyse->getHTML($decodedURL);
$entry['html'] = $html[0];
$entry['loading_time'] = $html[1];
}
if($value == 'alwaysignore') {
$this->blacklist_model->add($decodedURL);
}
}
}
}
}
print_r($keywords);
The output looks like this:
http://pastebin.com/B3PtrqjB
So, as you see, there are several "found!"s in the output, so the if clause actually gets executed a few times and I expected the second array to contain new data like 'html', but, as you see, nothing changes. Is there anything to attend when changing values in multidimensional foreach() loops?
A: foreach creates a copy of the array and loops through that. Modifying values doesn't work.
You can get around this, though, by using references.
foreach ($keywords as &$keyword) {
foreach ($keyword['whitelist'] as &$entry) {
foreach ($_POST as $key => &$value) {
...
}
}
}
With that you can modify $value and it WILL affect the original array.
A: You suppose to change the Original array.
$entry is just an instance / unconnected node.
you need to change $keywords, and not its on the fly created nodes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608651",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SNMP4j vs JMX? what to choose for myapplication Regarding applications administration, I think SNMP4j and JMX are the most used standards. Looking to the documentation of each one, I got confused and not able to choose one or the other. So, I decided to get post and get some feedback from people who already have experience with the topic.
What I want to do is to consult and change the configuration of some elements and also get some statistics.. I would consider the efficiency, easiness of use and availability of documentation..
Thanks for your help
A: You can go for JMX. As the documentation for JMX is good enough to create a JMX interface for you application but on the other side SNMP4J is lagging with respect to the documentation. If you have any doubt please let me know.
Regards,
Raghav
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608657",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Long running query on a self joined table I try to improve the performance of a query which updates a coloumn on each row of a table, by comparing the actual row's values with all other rows in the same table. Here is the query:
update F set
PartOfPairRC = 1
from RangeChange F
where Reject=0
and exists(
select 1 from RangeChange S
where F.StoreID = S.StoreID
and F.ItemNo = S.ItemNo
and F.Reject = S.Reject
and F.ChangeDateEnd = S.ChangeDate - 1)
The query's performance degrades rapidly as the number of rows in the table increases. I have 50 millon rows in the table.
Is there a better way to do this? Would SSIS be able to handle such an operation better?
Any help much appreciated, thanks Robert
A: You can try to create a index on that table:
create index idx_test on RangeChange(StoreID, ItemNo, Reject, ChangeDateEnd) where reject = 0
--when you are not using the SQL enterprise get rid of the where condition in the index and put the reject column as included column in the index
--make sure you have a clustered index already on the table (when not you can create the index above as clustered)
-- I would write the query as a join:
update F set
F.PartOfPairRC = 1
from RangeChange F
join RangeChange S
on F.StoreID = S.StoreID
and F.ItemNo = S.ItemNo
and F.Reject = S.Reject
and F.ChangeDateEnd = S.ChangeDate - 1
where F.Reject=0 and S.Reject = 0
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can I get eclipse gwt devmode to always recompile all my modules I have two modules, the Main module and the Included module.
If I start the Main module it will show an interface with an iFrame which contains the Included module with some additional controls around it. I can also start the Included module separately.
I have solved this by having two separate .gwt.xml files and two separate entrypoints and the result is then placed in the same war folder.
If I use GWT Compile in eclipse I can add both my entrypoints to the list and it will compile both modules and everything will work correctly.
However if I click the "Run" button in eclipse to have my application run in devmode, then it will only recompile the entrypoint that I access in my browser. If I access the Main entrypoint then I will get a popup saying "gwt module may need to be recompiled" and devmode will not automatically recompile my Include entrypoint.
Is there someway that I can get devmode in eclipse to -always- recompile all of my modules?
A: As I understand it, you use an IFrame that contains the host page of a secondary GWT module. This frame's content must also be loaded using the gwt.codesvr=127.0.0.1:9997 parameter, or it would just load the latest compiled version of the GWT javascript without using the devmode server.
You should also make sure the debug configuration in Eclipse contains both modules. You can verify that by not clicking the button directly, but using the menu to open the "Debug Configurations" menu. Assuming you clicked on the "Debug" button before, you should find an existing GWT debug configuration there. Make sure that both modules are listed in the "GWT" tab.
If you have your modules in two different projects, you might have to use two instances of the dev mode server. (remember to use different ports)
A: Add you included module to your main module.
You can do this by adding
<inherits name="fully qualified name of your module"/>
this code in your main.gwt.xml file.
A: I would contend that this is more of a "project setup" problem, than "how can I get Eclipse to compile all my modules" problem. The reason I say this is, I have yet to see a GWT project where two entry points were necessary/made sense. The main reason to have separate entry points is for reuse (Dev Guide, Dividing code into multiple modules).
The way I would approach the problem is to have your Main module, which includes the controls and iFrame (and have it inherit your Included module), so the same as you are now. Where I would differ is I would set up the Included module to not have an entry point. Instead, if you have a reason to run it separately from the Main module, I would create a "drive"/"launcher" module that also inherits the Included module. However, instead of controls and an iFrame like the Main module, this driver module would consist merely of an entry point and a place to attach your Included module.
You might also check out this question for more discussion in this same vein: Multiple Entry Points in GWT.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608659",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What SQL indexes should I add for this bloated query? I'm wondering if indexes will speed this query up. It takes 9 seconds last time I checked. The traffic table has about 300k rows, listings and users 5k rows. I'm open to ridicule/humiliation too, if this is just a crappy query altogether. I wrote it long ago.
It's supposed to get the listings with the most page views (traffic). Let me know if the explanation is lacking.
SELECT traffic_listingid AS listing_id,
COUNT(traffic_listingid) AS genuine_hits,
COUNT(DISTINCT traffic_ipaddress) AS distinct_ips,
users.username,
listings.listing_address,
listings.datetime_created,
DATEDIFF(NOW(), listings.datetime_created) AS listing_age_days
FROM traffic
LEFT JOIN listings
ON traffic.traffic_listingid = listings.listing_id
LEFT JOIN users
ON users.id = listings.seller_id
WHERE traffic_genuine = 1
AND listing_id IS NOT NULL
AND username IS NOT NULL
AND DATEDIFF(NOW(), traffic_timestamp) < 24
GROUP BY traffic_listingid
ORDER BY distinct_ips DESC
LIMIT 10
P.S.
ENGINE=MyISAM /
MySQL Server 4.3
A: Sidenotes:
1.You have
LEFT JOIN listings
ON traffic.traffic_listingid = listings.listing_id
...
WHERE ...
AND listing_id IS NOT NULL
This condition cancels the LEFT JOIN. Change your query into:
INNER JOIN listings
ON traffic.traffic_listingid = listings.listing_id
and remove the listing_id IS NOT NULL from the WHERE conditions.
The same thing applies to LEFT JOIN user and username IS NOT NULL.
2.The check on traffic_timestamp:
DATEDIFF(NOW(), traffic_timestamp) < 24
makes it difficult for the index to be used. Change it into something like this that can use an index
(and check that my version is equivalent, I may have mistakes):
traffic_timestamp >= CURRENT_DATE() - INTERVAL 23 DAY
3.The COUNT(non-nullable-column) is equivalent to COUNT(*). Change the:
COUNT(traffic_listingid) AS genuine_hits,
to:
COUNT(*) AS genuine_hits,
because it's bit faster in MySQL (although I'm not sure about that for version 4.3)
For the index question, you should have at least an index on every column that is used for joining. Adding one more for the traffic_timestamp will probably help, too.
If you tell us in which tables the traffic_ipaddress and traffic_timestamp are, and what the EXPLAIN EXTENDED shows, someone may have a better idea.
Reading again the query, it seems that it's actually a GROUP BY only in table traffic and the other 2 tables are used to get refrence data. So, the query is equivalent to a (traffic group by)-join-listing-join-user. Not sure if that helps in your MySQL old version but it may be good to have both versions of the query and test if one query runs faster in your system.
A: Indexes should always be put on columns you use in the where clause.
In this case the listingid looks like a good option, as well as the users.id, seller_id and traffic_timestamp.
Use a EXPLAIN EXTENDED in front of your query to see what MySQL recommends you (It shows how many rows are touched, and what indexes it uses)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608661",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to validate the Access Token and get new one if it's invalid? My app is working just fine and everything is OK but when the user logged-out or come back after two hours or change his password or remove the app then try to add it again I get an error like this with the reason of each error :
Fatal error: Uncaught OAuthException: Error validating access token: The session is invalid because the user logged out. thrown in /home/user/public_html/new_fb_app/src/base_facebook.php on line 1028
Also, if I tried to refresh after this error came up the app will work just fine. So I guess it has something to do with the app tried to work with the last access token (which was invalid).
This is my code :
<?php
$user = null; //facebook user uid
try{
include_once "src/facebook.php";
}
catch(Exception $o){
echo '<pre>';
print_r($o);
echo '</pre>';
}
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'my appId',
'secret' => 'my app secret',
'fileUpload' => true
));
// Get User ID
$user = $facebook->getUser();
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'read_stream, publish_stream, photo_upload, user_photos'
)
);
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$access_token = $facebook->getAccessToken();
} catch (FacebookApiException $e) {
//you should use error_log($e); instead of printing the info on browser
d($e); // d is a debug function defined at the end of this file
$user = null;
}
}
if (!$user) {
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}
function d($d){
echo '<pre>';
print_r($d);
echo '</pre>';
}
?>
A: Empty the cookies or sessions when the user logs out?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608662",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Mysql (innodb) index decision for better perfomence I have a simple table with 1,000,000 rows.
this row has a datetime field that I am always quering where statement on it.
SELECT * from my_table WHERE date_time = 'blabla';
Is it reccomened to put index on it for that reason only (where statement)?
A: Definitely yes. Without it, MySQL will have to do a full table scan (go row by row comparing the date_time to the provided value.)
A: Yes, put an index on fields in the where clause.
Just take a look at the EXPLAIN EXTENDED (put it in front of your query) and see what the query actually touches.
Also note: Do not use SELECT *, but always the fields you actually use
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608663",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: put textbox content on span or li after doing space Is there an easy way to do something like the tag editor at the bottom of the question area in stackoverflow.
I need a list of strings. So, I planned to do a textbox and on pressing the space key, the content is pushed in to a span or a li tag, and the textbox is emptied and ready to enter new content to be pushed.
A: Demo here
HTML
<div id="container">
<input type="text" id="tags"/>
</div>
CSS
#container{
border: 1px solid #FF7800;
padding:10px 0 10px 5px;
}
#tags{
border:none;
}
.mytag{
background:#FF7800;
color:#fff;
padding:5px;
margin-right:5px;
}
jQuery
$("#tags").keyup(function(event) {
//alert(event.keyCode);
if(event.keyCode=='32'){
var tagname= $(this).val();
if(tagname!=" "){
var newtag= $("<span class='mytag'>"+tagname+"</span>");
$(this).before(newtag);
}
$(this).val("");
}
});
Demo here I hope you wanted this behaviour
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608665",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: wxpython event not triggering I'm following the example given in http://www.blog.pythonlibrary.org/2010/05/22/wxpython-and-threads/
I have a thread which is checking an sftp server for new files every 30 seconds. If it finds files, it uploads them to a db, and then it should trigger an update of certain GUI elements which will reload from the db.
The custom event code:
EVT_RESULT_ID = wx.NewId()
def EVT_RESULT(win, func):
"""Define Result Event."""
win.Connect(-1, -1, EVT_RESULT_ID, func)
class ResultEvent(wx.PyEvent):
"""Simple event to carry arbitrary result data."""
def __init__(self, data):
"""Init Result Event."""
wx.PyEvent.__init__(self)
self.SetEventType(EVT_RESULT_ID)
self.data = data
The ftp thread:
class FTPThread(threading.Thread):
def __init__(self,wxObject):
"""Init Worker Thread Class."""
threading.Thread.__init__(self)
self.wxObject = wxObject
self._stop = threading.Event()
self._stop.set()
self.start() # start the thread
def run(self):
while True:
time.sleep(30)
if not self._stop.isSet():
wx.CallAfter(self.parseFTP)
def stop(self):
self._stop.set()
def resume(self):
self._stop.clear()
def parseFTP(self):
#connect to db
...
#connect to sftp site
...
files_found=False
#process each file and delete
for file in dirlist:
files_found=True
...#process into db
sftp.remove(file)
sftp.close()
t.close()
#trigger update event if files found
if files_found==True:
wx.PostEvent(self.wxObject, ResultEvent("Files found"))
One of the GUI elements:
class MyGrid(wx.grid.Grid):
def __init__(self, parent):
wx.grid.Grid.__init__(self, parent,-1,style=wx.EXPAND)
self.parent=parent
...
self.update()
EVT_RESULT(self, self.updateFromEvent)
def updateFromEvent(self,event):
self.update()
def update(self):
...
Following debugging, the wx.PostEvent is being created, but not triggering any response in the grid.
The only difference I can find between the example and my code is that in the example the EVT_RESULT is in the main Frame, and not a GUI element - is this required?
A: Events don't propagate to its children so if MyGrid is a child of your main frame, events posted in the main won't make it through to MyGrid. What you can do instead is bind the event handler directly to your function within the instance of MyGrid like so:
"""from MainWindow"""
self._workerthread = FtpThread(...)
self._mygrid = MyGrid(...)
# Bind event
EVT_RESULT(self, self._mygrid.updateFromEvent)
I'm not too familiar with this kind of binding as I typically use wx.Bind.
A: I'm not sure, but that example was based on something in the wiki: http://wiki.wxpython.org/LongRunningTasks
I suspect that since it says "win" as an argument, it is probably referring to a Top Level Window, so the wx.Frame is probably required. You can still update the grid from the frame though.
EDIT: Manny has a good point. That would probably work too. And pubsub rocks!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608666",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Added preferences dynamically that will last over sessions I have preference defined in xml, and I do this addPreferencesFromResource(R.xml.preferences1); to create the pref activity. But in code (dynamically) at runtime somethimes(depends on busyness logic) I add more items like this
CheckBoxPreference c=new CheckBoxPreference(this);
c.setKey("asdasd");
c.setTitle("asd");
getPreferenceScreen().addPreference(c);
This works great and everything is fine(the state is saved corectlly and it stays persistent) until I restart the phone. When I restart the phone this newly added item is lost. And only items from the xml file are shown in the prefereceActivity.
My question is what should I do to have this items even when the user restart the phone.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608667",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Android Custom Alert Dialog Display Error after changing the Build Version I am developing a simple demo . Here in this demo, I am just creating one simple custom alert dialog . It works fine.
It shows me the perfect result when i build application in 1.6, but when i change the android version from 1.6 to 2.2, it shows the unexpected result. It doesn't show the background screen on which i display the custom alert dialog.
Here is my xml file. Custom Dialog Theme File
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="CustomDialogTheme" parent="@android:style/AlertDialog">
<item name="android:windowFrame">@null</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:backgroundDimEnabled">true</item>
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowAnimationStyle">@android:style/Theme.Dialog</item>
</style>
</resources>
Here is My CustomConfirmOkDialog Class
package com.utility.org;
import android.app.Activity;
import android.app.Dialog;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class CustomConfirmOkDialog extends Dialog implements OnClickListener
{
private Button okButton = null;
private TextView infoText=null,confirmBody=null;
private int errorMessage=0;
@SuppressWarnings("unused")
private Activity activity;
public CustomConfirmOkDialog(Activity context,int customdialogtheme,int errorMessage)
{
super(context,customdialogtheme);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.confirm_ok);
this.errorMessage = errorMessage;
this.activity = context;
initControls();
}
private void initControls()
{
okButton = (Button) findViewById(R.id.ok_button);
okButton.setOnClickListener(this);
infoText = (TextView)findViewById(R.id.infoText);
confirmBody = (TextView)findViewById(R.id.confirmBody);
switch (this.errorMessage)
{
case Utility.INVALID_USERNAME_PASSWORD:
try
{
infoText.setText(R.string.signIn);
confirmBody.setText(R.string.invalidUsernameAndPassword);
}
catch (Exception e)
{
e.printStackTrace();
}
break;
default:
break;
}
}
public void onClick(View v)
{
dismiss();
}
}
Calling this class from my main activity using the below code.
CustomConfirmOkDialog dialog = new CustomConfirmOkDialog(MainActivity.this, R.style.CustomDialogTheme, Utility.INVALID_USERNAME_PASSWORD);
dialog.show();
Here you can clearly notice that 1st image shows the background . Its build in android 1.6 version while 2nd image doesn't shows the background . It shows the entire black screen. Its build in android version 2.2 . I am very thankful if anyone can solve this issue.
Can anyone help me to solve this simple and silly issue ?
Thanks in Advance.
A: It resolved my problem by changing the following code in Custom Dialog Theme xml file.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="CustomDialogTheme" parent="@android:style/Theme.Translucent.NoTitleBar">
<item name="android:windowFrame">@null</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:backgroundDimEnabled">true</item>
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowNoTitle">true</item>
</style>
</resources>
A: I also faced the same problem. the problem is when I called constructor of Dialog class
Dialog(Context context, int themeId)
it will hide the background activity. The only solution that i found is don't call this constructor, instead only call
Dialog(Context context)
and set your style in the layout file.
So in your code, only write
super(context)
instead of
super(context, themeid);
A: Apparently, this is a known issue.
This only happens when you try inheriting from the framework themes.
Using @android:style directly will still treat them as non-
fullscreen, which punches through the black background as expected.
One workaround is to start with a nearly-blank theme (like Panel or
Translucent) and then render what you need in your own layout (such as
dialog edges, etc).
Thought, I still don't fully understand this solution myself yet.
And actually, I'm no longer sure they're talking about the exact same bug you've seen, since they're talking about it not working for an older version of the sdk (not a newer one like yours). See the bug report.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608668",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: switch on / off flash light programmatically on android smartphones (without using the camera) I saw your question about How to turn on camera flash light programmatically in Android?"How Turn on only Camera flash light programmatically in android?".
I'm trying to do the same.
The links you used to solve your problem seem to be out of order: http://code.google.com/p/quick-settings/
Could you share your solution ?
I have another question: is there a way to see in the emulator whether the flash light is on or off ?
Thank you for your help.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608670",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Postgresql database shared across multiple geographic locations I'm working on a project where a Postgresql database needs to be shared across several physical locations. Each location has limited connectivity, and may only have access to the outside world once or twice a day. So the database has to be available locally at each location, but must also synchronize with the master database when possible.
I am not yet familiar with replication or clustering. Are these good solutions? Or is there a better way of doing it? I would appreciate some advice on this. :)
NOTE: clashing of primary keys from different locations would not be an issue, this has been taken care of.
A: If the remote locations require read-only access to the data, you can set up asynchronous replication fairly easily using log shipping, which is a built-in feature of PostgreSQL. In this configuration, the master server drops WAL (write-ahead log) files to a shared location where the remote servers can periodically connect and read the logs to bring themselves up to date.
If all servers are performing writes independently, what you're looking for is asynchronous multi-master replication. The Postgres docs mention Bucardo and rubyrep as options for accomplishing this. According to the docs, both are limited to master-to-master replication (or master to multiple slaves), but Bucardo supposedly has true multi-master replication planned for version 5.0, and rubyrep mentions a method for keeping multiple servers synchronized.
(I have servers using PostgreSQL's log shipping and streaming replication features, but I have no direct experience with Bucardo or rubyrep.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608673",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to identify leaks objects using Leaks in XCode 4? Can any one guide me that how to use and identify the variables that are leaking the memory?
I took the snap as following, but yet no idea to understand it
A: Open the right utility area (click third button next to the status info in the top bar).
when you then klick on a leaked block (and on the arrow next to the address), you can see the code blocks responsible for the steps
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608675",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why does git ignore all files in a directory except one? I know there are many questions on how to ignore directories, and I usually haven't had any problem until now, but now I'm stuck with something I don't understand.
Here is my directory structure:
/src
/war
com.example.MyProject/
WEB-INF/
classes/
deploy/
lib/
I want to ignore content of directories classes/, deploy/ and com.example.MyProject/, and here is my .gitignore file:
*.log
war/WEB-INF/classes/
war/WEB-INF/deploy/
com.example.MyProject/
Files under com.example.MyProject/ are automatically generated, and git ignores all of them except for a file named com.example.MyProject.nocache.js. In fact, when I do git status I get:
# On branch myBranch
# Changed but not updated:
# (use "git add <file>..." to update what will be committed)
#
# modified: .gitignore
# ......
# modified: war/com.example.MyProject/com.example.MyProject.nocache.js
Why does git refuse to ignore that single file in that directory? What am I doing wrong?
A: If a file is already being tracked by Git, adding the file to .gitignore won't stop Git from tracking it. You’ll need to do git rm --cached <file> to keep the file in your tree and then ignore it
A: If the file has already been added to the index, it will still stay in there, even though you add it to the .gitignore file.
Try removing the file from the git index:
git rm --cached war/com.example.MyProject/com.example.MyProject.nocache.js
The --cached option makes sure that the file stays in your folder and just gets removed from the index
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608676",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How to load user's file in Flash? I would like to load a user's file right after the app is inicialized. I have this code:
fll = new FileReference();
fll.browse([new FileFilter("Text *.txt", "*.txt")]);
It works fine when some button is pressed, but when i just put it inside the frame's code, it doesnt work. How can i do it?
A: This function works only on user interaction (mouse click, key press etc) for security reasons, so it won't work when you paste it in regular frame script.
A: Try this code, hopefully this will work for you:
import flash.text.*;
import flash.net.FileReference;
var tf:TextField = new TextField();
tf.width = 350
tf.height = 350
tf.multiline=true;
tf.border = true
addChild(tf);
var fileReference:FileReference = new FileReference();
var fileFilter:FileFilter=new FileFilter("Images","*.txt");
fileReference.addEventListener(Event.SELECT, onSelectFile);
fileReference.addEventListener(Event.COMPLETE,onFileComplete);
bBrowse.addEventListener(MouseEvent.MOUSE_DOWN, browseFile);
function onFileComplete(event:Event):void
{
tf.htmlText = "opening: "+fileReference.name+"<br>"
var bytes:ByteArray=fileReference.data;
var newtext:String=fileReference.data.readMultiByte(fileReference.data.length,"gb2312");
//var newtext:String = fileReference.data.readUTFBytes(fileReference.data.length)
tf.appendText(newtext);
}
function browseFile(e:MouseEvent)
{
fileReference.browse([fileFilter]);
}
function onSelectFile(event:Event):void
{
fileReference.load();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608678",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: rails how to give data to ajax in a secure way? In order to use some AJAX calls, we use often some input type="hidden". But these values can be easily changed. So, is it a builtin rails feature than permit to send date to AJAX, withouth being usable by user, or than can't be changed by user ?
In my current rails apps, i'm using filters for discard all malicious actions on my controllers. I am not building a public API, so i don't really need more powerful checks.
But for examples, i have an apotomo widget displaying some data, using some input hidden. But if you change it, you can access to another data set. In my case, it's not really an issue, cause all these users have the right to access these data sets anyway.
But is it some manner to give datas to ajax call, in a secure way ? Or the only security, is about rights management ?
A: All input that comes from the user is insecure as you do not have control over it! Users even do not need a webbrowser but can use some other program (like curl or wget) to send manipulated data.
As you state, using a whitelist (not a blacklist as you can never be sure of all bad, but of all good!) is a good way to start.
To make sure the hidden fields have not been changed you can use some kind of checksum that is calculated on server side using a fixed secret. This secret must never be exposed to your visitors!
hash = md5(field_1 + field_2 + field_3 + my_secret)
When these four hidden fields (field_1..3, hash) arrive in your form you can recalculate the hash and compare it with the params[:hash] in order to be sure the field_1 to field_3 have not been changed.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608680",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Refactor recursive algorithm into an iterative one? I have following recursive algorithm needed to redactor into iterative process.
CvSeq is a tree structure.Where contour->h_next gives the next node in the same level.
contour->v_next gives the next contour in level below.(child node)
void helperParseCurves(CvSeq* contour, int level) {
if(contour->h_next != NULL) {
helperParseCurves(contour->h_next, level);
}
if(contour->v_next != NULL) {
helperParseCurves(contour->v_next, level+1);
}
//Process the nodes in contour
for(int i=0; i<contour->total; i++){
CvPoint* p = CV_GET_SEQ_ELEM(CvPoint, contour, i);
//Paint the point p
}
}
I want to refactor this logic into iterative algorithm.
Any tips on this?
A: To traverse nodes w/o recursion you will need stack for saving previous states. [Recursion is actually using of stack as well...] :
struct StackData
{
CvSeq* contour;
int level;
int traversed;
};
const int traversed_l = (1 << 0);
const int traversed_r = (1 << 1);
const int stack_size = 50; // should be at leas max depth
StackData stack[stack_size];
int stack_p = 0;
void helperParseCurves(CvSeq* contour, int level) {
int traversed = 0;
while(contour)
{
if(contour->h_next != NULL && !(traversed & traversed_l)) { // down to left
assert(stack_p < stack_size); // and save current state
traversed |= traversed_l;
stack[stack_p].contour = contour;
stack[stack_p].level = level;
stack[stack_p].traversed = traversed;
++stack_p;
contour = contour->h_next;
traversed = 0;
continue;
}
if(contour->h_next != NULL && !(traversed & traversed_r)) { // down to right
assert(stack_p < stack_p); // and save current state
traversed |= traversed_r;
stack[stack_p].contour = contour;
stack[stack_p].level = level;
stack[stack_p].traversed = traversed;
++stack_p;
contour = contour->v_next;
level = level+1;
traversed = 0;
continue;
}
//Process the nodes in contour
for(int i=0; i<contour->total; i++){
CvPoint* p = CV_GET_SEQ_ELEM(CvPoint, contour, i);
//Paint the point p
}
// move up because either left and right nodes are NULL or already traversed
if(!stack_p) break; // we are at the top
contour = stack[stack_p].contour;
level = stack[stack_p].level;
traversed = stack[stack_p].traversed;
--stack_p;
}
}
A: Have an empty vector/array/queue of CvSeq*'s. Have an index/pointer into it, at first pointing to its beginning (where the very first element will be).
Start with the tree's root and add its h_next and v_next to the vector.
Then while the index is less than the number of pointers in the vector - 1, take vector[index]'s h_next and v_next, add them at the end of the vector and do ++index.
You end up with pointers to all tree nodes in that vector/array/whatever.
Then you just iterate over it, painting things and whatnot.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608682",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Bad Exception on dealloc? I having a problem with a Bad Exception that I could not locate at first, but now have it pinned down on a [super dealloc];, but I have no idea why this happens.
Here is my code :
EditingViewController.h
@interface EditingViewController : UIViewController
{
NSManagedObject *editedObject;
NSString *editedFieldKey;
NSString *editedFieldName;
}
@property (nonatomic, retain) NSManagedObject *editedObject;
@property (nonatomic, retain) NSString *editedFieldKey;
@property (nonatomic, retain) NSString *editedFieldName;
- (IBAction)cancel;
- (IBAction)save;
@end
EditingViewController.m
#import "EditingViewController.h"
@implementation EditingViewController
@synthesize editedObject, editedFieldKey, editedFieldName;
#pragma mark -
#pragma mark View lifecycle
- (void)viewDidLoad
{
self.title = NSLocalizedString(editedFieldName, nil);
// Configure the save and cancel buttons.
UIBarButtonItem *saveButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(save)];
self.navigationItem.rightBarButtonItem = saveButton;
[saveButton release];
UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancel)];
self.navigationItem.leftBarButtonItem = cancelButton;
[cancelButton release];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (IBAction)save
{
[self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)cancel
{
// Don't pass current value to the edited object, just pop.
[self.navigationController popViewControllerAnimated:YES];
}
- (void)dealloc
{
[editedObject release];
[editedFieldKey release];
[editedFieldName release];
//[super dealloc];
}
@end
As you can see, I commented the [super dealloc];, which is causing the Bad Exception, but this is obviously not a good solution.
Any idea what I am doing wrong ?
Thanks
A: The properties might have never been used, so they haven't been initialized in any way
- (void)dealloc
{
self.editedObject = nil;
self.editedFieldKey = nil;
self.editedFieldName = nil;
[super dealloc];
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608683",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I index duplicate items in an array? Starting with the following array (of hashes):
[
{:name=>"site a", :url=>"http://example.org/site/1/"},
{:name=>"site b", :url=>"http://example.org/site/2/"},
{:name=>"site c", :url=>"http://example.org/site/3/"},
{:name=>"site d", :url=>"http://example.org/site/1/"},
{:name=>"site e", :url=>"http://example.org/site/2/"},
{:name=>"site f", :url=>"http://example.org/site/6/"},
{:name=>"site g", :url=>"http://example.org/site/1/"}
]
How can I add an index of the duplicate urls like so:
[
{:name=>"site a", :url=>"http://example.org/site/1/", :index => 1},
{:name=>"site b", :url=>"http://example.org/site/2/", :index => 1},
{:name=>"site c", :url=>"http://example.org/site/3/", :index => 1},
{:name=>"site d", :url=>"http://example.org/site/1/", :index => 2},
{:name=>"site e", :url=>"http://example.org/site/2/", :index => 2},
{:name=>"site f", :url=>"http://example.org/site/6/", :index => 1},
{:name=>"site g", :url=>"http://example.org/site/1/", :index => 3}
]
A: I would use a hash for keeping track of the indices.
Scanning the previous entries again and again seems inefficient
counts = Hash.new(0)
array.each { | hash |
hash[:index] = counts[hash[:url]] = counts[hash[:url]] + 1
}
or a bit cleaner
array.each_with_object(Hash.new(0)) { | hash, counts |
hash[:index] = counts[hash[:url]] = counts[hash[:url]] + 1
}
A: array = [
{:name=>"site a", :url=>"http://example.org/site/1/"},
{:name=>"site b", :url=>"http://example.org/site/2/"},
{:name=>"site c", :url=>"http://example.org/site/3/"},
{:name=>"site d", :url=>"http://example.org/site/1/"},
{:name=>"site e", :url=>"http://example.org/site/2/"},
{:name=>"site f", :url=>"http://example.org/site/6/"},
{:name=>"site g", :url=>"http://example.org/site/1/"}
]
array.inject([]) { |ar, it|
count_so_far = ar.count{|i| i[:url] == it[:url]}
it[:index] = count_so_far+1
ar << it
}
#=>
[
{:name=>"site a", :url=>"http://example.org/site/1/", :index=>1},
{:name=>"site b", :url=>"http://example.org/site/2/", :index=>1},
{:name=>"site c", :url=>"http://example.org/site/3/", :index=>1},
{:name=>"site d", :url=>"http://example.org/site/1/", :index=>2},
{:name=>"site e", :url=>"http://example.org/site/2/", :index=>2},
{:name=>"site f", :url=>"http://example.org/site/6/", :index=>1},
{:name=>"site g", :url=>"http://example.org/site/1/", :index=>3}
]
A: If I wanted it to be efficient, I'd write:
items_with_index = items.inject([[], {}]) do |(output, counts), h|
new_count = (counts[h[:url]] || 0) + 1
[output << h.merge(:index => new_count), counts.update(h[:url] => new_count)]
end[0]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Any problems with putting DAOs and Gateways in Application.cfc? Is it ok to put DAOs and Gateways that will be called many times but only need to be instantiated once in the Application scope?
Thanks
A: Yes, absolutely.
Another option is to use an IOC framework such as ColdSpring or some other bean factory. The bean factory can then be stored in the application scope and instantiated onApplicationStart() (effectively achieving the same thing but possibly with more control).
A: That's the perfect place to put them ;-).
Add them into onApplicationStart() as application.myDAO = xxxx & application.myGateway = xxxx and you're good to go!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608689",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Can we use HttpResponse object only to keep session management between server and device in Android? Can we use only HttpResponse object to keep all session management between server and device?
A: I'm not sure if that would work as the session id needs to be sent back to the server from the device (the client) upon subsequent communications. You would get the session ID from the server upon the initial communication (login?) and this would be passed back to the device in the HttpResponse in the form of JSON, XML, Etc. Then, you'll want to pass that session ID to the server with all your HTTP requests. This can be done in the header of the response. You can have the server check that the session is still alive and respond with an error code if it is not.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608690",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Session Should not expire I have 2 application,
*
*1 as A application and
*2 as B application.
Now from A , I am navigating to b application, there I will spend some time. And In B I have a log off button, if user clicks on that, it should come back to application A, with session intact.
I am using J2EE and Weblogic server, Here servers of a and b are also different.
Can any one please help me, I need to complete this work by today eveining.
Thank you for your help in advance.
A: Here is one way of doing it
*
*Assume that a user is on application A with valid session.
*When you click a link (or post some data) to go on application B, pass some token in query string. (This token may encrypted (username+password+salt)).
*Application B receives the query string data, decrypts it and authenticates the user.
*When user clicks log off in application B, the log off handler in application B (it could be a servlet/JSP/Controller/Action etc), does s response.sendRedirect() to the application A.
*which will still have its session intact (provided session has not timed out i.e. the time user spent on application B is less than the session timeout of application A).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608691",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Multiple get methods in single Resource class with Restlet here is my code :
this is my application class >>>
import org.restlet.Application;
import org.restlet.Restlet;
import org.restlet.routing.Router;
import firstSteps.UserResource;
public class FirstStepsApplication extends Application {
@Override
public synchronized Restlet createRoot() {
Router router = new Router(getContext());
router.attach("/hello", UserResource.class);
router.attach("/isuserloggedin",UserResource.class);
return router;
}
}
this is resource class >>>
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;
/**
* Resource which has only one representation.
*
*/
public class UserResource extends ServerResource {
@Get
public String userLogin() {
return "This is userLogin method";
}
@Get
public boolean isUserLoggedIn(){
return false;
}
}
/hello & /isuserloggedin are mapped to same to resource class but
what i want is : when there is /hello then userLogin method should be called
and when there is /isuserloggedin then isUserLoggedIn must be called .
is this possible ??
or am i going wrong?
if this is not possible then any one can tell me any other alternative ?
A: In Restlet 2.1 (try M7 or above), it is possible to dispatch two HTTP GET calls to two Java methods in the same resource class. This is done by leveraging query parameters like this:
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;
/**
* Resource which has only one representation.
*
*/
public class UserResource extends ServerResource {
@Get
public String userLogin() {
return "This is userLogin method";
}
@Get("?loggedIn")
public boolean isUserLoggedIn(){
return false;
}
}
However, as pointed already, you would be better off using a separate resource class.
A: Some time has passed since my last experience with Restlet, anyway, if you are implementing a fully REST API, I would expect the two to be separate resources if they really need to be. Otherwise, a resource should be mapped to exactly one representation, IMHO.
What is the benefit of having two URIs mapped to one resource class, instead of having two, each implementing the GET method? It seems to add a bit of ambiguity there, with no benefit.
I would return the status (logged or not) information in the user representation.
Now, for sake of completeness, I find a bit difficult to understand your API semantics: can I ask for the logged status of any user, or just mine? It's not very clear, but I understand that it was not the main point.
Just as a nice reading, you may want to have a look at some popular REST api to see how they manage issues similar to yours, ie. I like Github Users' API particularly.
Hope it helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608694",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Out String Parameter Not Returned From COM Interop I have a ATL COM component method which has an [out] BSTR* parameter. I have create a reference to this component from my .NET application which treats the parameter as an out String type. The COM component allocates this string like this:
USES_CONVERSION;
*sText = SysAllocString(T2OLE(psText));
where psText is a char*
However, when the method call returns, the .NET code still has an empty string. Can anyone see what is wrong?
A: The code isn't wrong but the .Net runtime may be too stupid to parse the indirection. You might want to rephrase your IDL from:
HRESULT DoSomething([in] BSTR arg, [out] BSTR *result);
to:
HRESULT DoSomething([in] BSTR arg, [out, retval] BSTR *result);
The first syntax will yield in C#:
string result;
void DoSomething(string arg, out result);
2nd:
string result = DoSomething(arg);
Any 8-bit to 16-bit Unicode conversion must go through SysAllocString, since both out and out, retval require the caller to free the string. However, the .Net-runtime might get better results if it is told that this is the return value;
A: If your ATL COM component is compiled with the UNICODE flag, T2OLE will do nothing. If psText is really a char *, you must use A2OLE to be sure the string is converted to UNICODE.
.NET marshaling code doesn't support 'binary BSTR', that is BSTR with non UNICODE characters.
A: You would not have the CHAR/WCHAR issues if you replaced your
*sText = SysAllocString(T2OLE(psText));
with
*sText = CComBSTR(psText).Detach();
CComBSTR constructor would apply conversion automatically.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608699",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Understanding 'parse_str' in PHP I'm a PHP newbie trying to find a way to use parse_str to parse a number of URLs from a database (note: not from the request, they are already stored in a database, don't ask... so _GET won't work)
So I'm trying this:
$parts = parse_url('http://www.jobrapido.se/?w=teknikinformat%C3%B6r&l=malm%C3%B6&r=auto');
parse_str($parts['query'], $query);
return $query['w'];
Please note that here I am just supplying an example URL, in the real application the URL will be passed in as a parameter from the database. And if I do this it works fine. However, I don't understand how to use this function properly, and how to avoid errors.
First of all, here I used "w" as the index to return, because I could clearly see it was in the query. But how do these things work? Is there a set of specific values I can use to get the entire query string? I mean, if I look further, I can see "l" and "r" here as well...
Sure I could extract those too and concatenate the result, but will these value names be arbitrary, or is there a way to know exactly which ones to extract? Of course there's the "q" value, which I originally thought would be the only one I would need, but apparently not. It's not even in the example URL, although I know it's in lots of others.
So how do I do this? Here's what I want:
*
*Extract all parts of the query string that gives me a readable output of the search string part of the URL (so in the above it would be "teknikinformatör Malmö auto". Note that I would need to translate the URL encoding to Swedish characters, any easy way to do that in PHP?)
*Handle errors so that if the above doesn't work for some reason, the method should only return an empty string, thus not breaking the code. Because at this point, if I were to use the above with an actual parameter, $url, passed in instead of the example URL, I would get errors, because many of the URLs do not have the "w" parameter, some may be empty fields in the database, some may be malformed, etc. So how can I handle such errors stably, and just return a value if the parsing works, and return empty string otherwise?
There seems to be a very strange problem that occurs that I cannot see during debugging. I put this test code in just to see what is going on:
function getQuery($url)
{
try
{
$parts = parse_url($url);
parse_str($parts['query'], $query);
if (isset($query['q'])) {
/* return $query['q']; */
return '';
}
} catch (Exception $e) {
return '';
}
}
Now, obviously in the real code I would want something like the commented out part to be returned. However, the puzzling thing is this:
With this code, as far as I see, every path should lead to returning an empty string. But this does not work - it gives me a completely empty grid in the result page. No errors or anything during debugging, and objects look fine when I step through them during debugging.
However, if I remove everything from this method except return ''; then it works fine - of course the field in the grid where the query is supposed to be is empty, but all the other fields have all the information as they should. So this was just a test. But how is it possible that code that should only be able to return an empty string does not work, while the one that only returns an empty string and does nothing else does work? I'm thoroughly confused...
A: The meaning of the query parameters is entirely up to the application that handles the URL, so there is no "right" parameter - it might be w, q, or searchquery. You can heuristically search for the most common variables (=guess), or return an array of all arguments. It depends on what you're trying to achieve.
parse_str already decodes urlencoding. Note that urlencoding is a way to encode bytes, not characters. It depends on what encoding the application expects. Usually (and in this example query), that should be UTF-8 everywhere, so you should be covered on 1.
Test whether the value exists, and if not, return the empty string, like this:
$heuristicFields = array('q', 'w', 'searchquery');
foreach ($heuristicFields as $hf) {
if (isset($query[$hf])) return $query[$hf];
}
return '';
The function returns null if the input is valid, and runs into errors (i.e., displays warning messages) when the URL is obviously invalid. The try...catch block has no effect.
A: It turned out the problem was with Swedish characters - if I used utf8_encode() on the value before returning it, it worked fine.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: java generate class file at runtime I need to generate class at runtime, each class is mapped to a database table. Such class is model class used in ORM.
When client specify a database table to work with, my application check for existence of corresponding model class , if it does not exist, generate it and load it for use and save it, so next time we don't need to generate this class again
my question is:
*
*Is that possible?
*What open source library to use for generating class at runtime ?
some example code that illustrating how to generate simple POJO class is welcome!
best regards!
A: Yes, this is possible. And you don't need an external lib. The JDK provides everything you need:
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
int compilationResult = compiler.run(null, null, null, fileToCompile);
if (compilationResult == 0) {
System.out.println("Compilation is successful");
} else {
System.out.println("Compilation Failed");
}
Check out the JavaCompiler docs.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608704",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How to access request scoped bean in controller? I'm trying to understand the request scoped beans. Suppose I have a controller and I have a request scoped bean instantiated using spring config xml
<bean id="loginAction" class="com.foo.LoginAction" scope="request"/>
Do I need to add it as a dependency in controller to access it or I can access it directly from request object doing request.getAttribute("loginAction")
I just wanted to know how would I access this request scoped bean.
Thanks.
A: Use @Autowired annotation for this case.
@Autowired
private LoginAction loginAction;
and then add package for this bean as candidate for autowiring:
<context:annotation-config />
<context:component-scan base-package="com.foo"></context:component-scan>
and don't forget to mark this class as @Component or @Service.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608707",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Android: findViewById returning NULL - couldn't find out whats wrong? I have the following layout.
When i create WebView and GestureOverlayView objects in my MainActivity class, it returns null for both of the objects.
GestureOverlayView gesturesView = (GestureOverlayView) findViewById(R.id.gestures);
WebView webView = (WebView) findViewById(R.id.webview);
My Layout :
<?xml version="1.0" encoding="utf-8"?>
<android.gesture.GestureOverlayView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gestures"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<WebView
android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
</android.gesture.GestureOverlayView>
When i change the above layout to the following( i moved android.gesture.GestureOverlayView inside LinearLayout) , it is working fine.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<android.gesture.GestureOverlayView
android:id="@+id/gestures"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<WebView
android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</android.gesture.GestureOverlayView>
</LinearLayout>
I couldnot figure out what's wrong with my previous layout.
Please someone explain this.
A: Cleaning the project solved the problem.
A: Many of the problems revolving around resources in Android can be solved by cleaning and rebuilding the project.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608708",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: CSS url() function: Browser support I have seen in the comments of Is quoting the value of url() really necessary? and CSS background-image - What is the correct usage? that Mac IE 5 does not support quotation marks inside the url() function.
Also PPK's CSS page does not mention the url() function at all:
http://www.quirksmode.org/css/contents.html
So I would like to know what browser support is like for this function. What browsers recognise the value, which ones require what quotation marks, whitespace, and so on.
I realise that everything released in the past five years probably support all syntaxes. It's the older browsers I am thinking of.
A: Mac IE5? Serious? :) I think this browser is seriously outdated and not being used anymore :)
Anyhow, according to W3C, it's
body {background-image:url('paper.gif');}
And it works for all (older) browsers. For who are you developing if you need support for this kind of ancient browsers?
A: I have never ever had any issues with background-image for any browser type.
Unless of course you are putting it as a div with no content and not specifying the width and hight of the element...
example usage of background/background-image
#body {background-image:url('mylovelybg.jpg');}
or the long hand (to allow for color and repeating factors
#body {background:url ('mylovelybg.jpg') repeat-x #fff;}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608709",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Working with relations in ORM What is the best/common solution (best practices) to working with relationships in ORM (from long-life project view)?
1) E.g. I have Oracle HR schema. Is it ok to create relations between every objects (entities) where it is possible or only between objects where I really need now (and change in future)?
@Entity
public class Employee {
@Id
private long employeeId;
@ManyToOne((fetch = FetchType.LAZY)
private Job job;
}
@Entity
public class Job {
@Id
private String jobId;
@OneToMany(fetch = FetchType.LAZY)
private List<Employee> employeeList;
}
2) How should I store/set new Employee with existing or new Job? We have Employee entity with String jobId and also created relation Job job variable:
@Entity
public class Employee {
@Id
private long employeeId;
private String jobId;
@ManyToOne((fetch = FetchType.LAZY)
private Job job;
}
The worst solutions is set both parameters everytime:
Job job = new Job();
job.setJobId("JOB_01");
Employee employee = new Employee();
employee.setEmployeeId(1L)
employee.setJobId(job.getJobId());
A little bit better solutions is re-implement setJobId() method in Employee class (there should be also some code to find out if mentioned Job exist or not):
public void setJobId(String jobId) {
if (getJob() == null) {
this.jobId = jobId;
job = new Job();
job.setJobId(jobId);
} else {
this.jobId = getJob().getJobId();
}
}
A: If you don't need an association, then you don't need to add it. Note however that even if it's not used in Java code directly, an association might still be useful just to be able to traverse it in JPQL or criteria queries.
Regarding your jobId field, it should just be removed from the Employee entity. An employee has a job, and you can access its job ID using employee.getJob().getId(). You shouldn't be able to set the job ID of an employee. Instead, you should get or create a job (in the service layer), and set the employee's job using setJob(job).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608712",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why is my pointer not null after free? void getFree(void *ptr)
{
if(ptr != NULL)
{
free(ptr);
ptr = NULL;
}
return;
}
int main()
{
char *a;
a=malloc(10);
getFree(a);
if(a==NULL)
printf("it is null");
else
printf("not null");
}
Why is the output of this program not NULL?
A: Because the getFree() function takes a copy of the pointer. ptr and c are both pointers, but they are different variables. It's the same reason why this function will output "6":
void Magic(int x)
{
x = 1;
}
void main()
{
int a = 6;
Magic(a);
printf("%d", a);
}
A: You are passing pointer a by value, so it is not modified by function. It's only a copy of pointer modified within function, the original variable value is not affected.
Update:
If you wanted to make your life easier by replacing freeing + nulling a variable with a single line of code, you need either a macro:
#define MYFREE(x) free(x); x = NULL;
or a function with pointer to pointer argument:
void myfree(void** pp) { free(*pp); *pp = NULL; }
A: Pointers are stored as integers somewhere in memory.
When you do a = malloc(10);, a has some value, say 0x1.
When you call getFree(a);, the function copies a into void *ptr.
Now a=0x1 and ptr=0x1.
When you do ptr=NULL, only ptr is changed to NULL, but a is still 0x1..
A: Because the pointer is copied by value to your function. You are assigning NULL to the local copy of the variable (ptr). This does not assign it to the original copy.
The memory will still be freed, so you can no longer safely access it, but your original pointer will not be NULL.
This the same as if you were passing an int to a function instead. You wouldn't expect the original int to be edited by that function, unless you were passing a pointer to it.
void setInt(int someValue) {
someValue = 5;
}
int main() {
int someOtherValue = 7;
setInt(someOtherValue);
printf("%i\n", someOtherValue); // You'd expect this to print 7, not 5...
return 0;
}
If you want to null the original pointer, you'll have to pass a pointer-to-pointer:
void getFree(void** ptr) {
/* Note we are dereferencing the outer pointer,
so we're directly editing the original pointer */
if (*ptr != NULL) {
/* The C standard guarantees that free() safely handles NULL,
but I'm leaving the NULL check to make the example more clear.
Remove the "if" check above, in your own code */
free(*ptr);
*ptr = NULL;
}
return;
}
int main() {
char *a;
a = malloc(10);
getFree(&a); /* Pass a pointer-to-pointer */
if (a == NULL) {
printf("it is null");
} else {
printf("not null");
}
return 0;
}
A: You are passing the pointer By value.. (By default C passes the argument by value) which means you are updating the copy only ..not the real location..for that you might need to use pointer to pointer in C
void getFree(void **ptr)
{
if(*ptr != NULL)
{
free(*ptr);
*ptr = NULL;
}
return;
}
A: The question has already been answered but if it helps, I can explain it graphically.
You are doing this --> the pointer is copied by value to your function so it points to the array
but instead you want this -->point to the original pointer
As Merlyn Morgan-Graham already said, the way to solve it is to add operators * and &.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: Gmail / yahoo threading email including attachment Is there a way to force gmail / yahoo in threading emails with the same subject?
Here's what happened with the email that i sent.
Yahoo - the second email is combined with the first email including the attachment.
Gmail - The second email is empty and no attachment. The body was replaced with "Important mainly because of the people in the conversation."
I am not sure if threading is causing this problem. is there any way to fix this?
A: Yahoo and Gmail detect if the e-mail is in the same context. So a similar body, and same subject.
if you make an e-mail more specific (different contents) it should not make it a thread.
But Threading should not cause the loosing attachment problem. You should dig deeper on that, by looking to your own code.
A: It is not possible that your contents go away just like that. In Gmail you can disable threaded view in settings, and I am not sure about yahoo, but it should have options for that
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Best way to add two row list for CMS (wordpress) What is the best way for me to add a two row list with employees to a Wordpress CMS?
Like this: live example
| picture | personal data |
In the example above I've used a table, but this would properly work better created as CSS.
I need a way for the client to add new employees without writing ANY code. I've considered using the image caption (but I can't style it the way I want) or create a list UL - LI
I've also looked at some table plugins, but it isn't exactly working as I need. Perhaps I need to write such a plugin?
Any ideas as to how I can solve this problem?
A: I've solved the problem :-D
I simply have to add new user profiles as 'subscriber' and install the 'user photo' plugin. Then I can display the user data the way I want.
This is what I ended up using:
<div class="personale_table">
<?php
$wp_user_search = $wpdb->get_results("SELECT ID, display_name FROM $wpdb->users ORDER BY ID");
foreach ( $wp_user_search as $userid ) {
$user_id = (int) $userid->ID;
$user_login = stripslashes($userid->user_login);
$display_name = stripslashes($userid->display_name);
$user_info = get_userdata($user_id);
?>
<?php
echo('<div class="personale_thumb personale_ramme">' . get_avatar($user_id) . '</div>');
echo('<div class="personale_data"><div class="personale_linje personale_title">' . $user_info->first_name . ' ' . $user_info->last_name . '</div>');
echo('<div class="personale_linje personale_stilling">' . $user_info->aim . '</div><div class="personale_linje">' . $user_info->yim. '</div><div class="personale_linje"><a href="mailto:' . $user_info->user_email . '">' . $user_info->user_email . '</a></div><div class="personale_linje">' . $user_info->jabber . '</div></div>');
}
?>
</div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608721",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to use NSCursor to display custom cursor I am trying to use custom cursor in my game using nscursor. I use following code
//While initializing openglview
mCustomCursor = [[NSCursor alloc] initWithImage:image hotSpot:NSZeroPoint];
[image release];
[mCustomCursor set]
I am setting cursor rect in resetcursorrect method
- (void)resetCursorRects
{
[self addCursorRect:currentViewPortRect cursor:[NSCursor currentCursor]];
}
Custom cursor appears, It is not consistent, at times it switches back to system cursor (for alerts), some times it comes back and sometime not. It is so confusing. I am not sure if I should use 'setOnMouseEntered', 'pop'. What is the standard way to use nscursor and change it dynamically.
A: You're changing the cursor to the current cursor, which isn't changing it at all. To display your own custom cursor, you must pass your custom cursor when creating the cursor rect.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608733",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Attaching a jQuery plugin on-the-fly for better performance Recently I needed to attach a large number of a jQuery color picker plugin on a page. With color inputs for borders, shades, gradients, and so on, that quickly became a lot of color pickes. Since the tool was loaded repeatedly for 50+ elements, the page would instantiate 500+ color pickers. Needless to say, the browser suffered big time.
So first, I spend some time trying out different methods for having all the inputs share a single instance of the color picker. It seems to me that that would be the soundest way of doing it. But the project situation didn't allow me to spend enough time for finding a way of doing that, so I had to come up with an alternative technique.
I did, and I would like to hear what you think about the technique I came up with, and if anyone sees any problems with it?
The idea is, that instead of attaching all the instances of the plugin when the page loads, you wait, and attach just the instances you need – just when you need them.
Here is how I implemented that.
First I had some html with lots and lots of inputs like this one:
<input class="color">
Then, to assign the jQuery color picker plugin to these inputs, I'd normally do something like this:
jQuery(function($) {
$('input.color').myColorPicker();
});
But that would result in a number of color picker objects being instantiated right away, one for each matched element, each ready to do its stuff when its input is clicked. This normally works fine, but if there are lots of elements, it can make the browser unresponsive.
So instead, here's how I now attach a color picker to an input on-the-fly if the user actually click on it.
jQuery(function($) {
/* Color pickers*/
$('input.color').live('focus', function(event){
// attach a colorpicker on an as needed basis,
// and only if it is not already attached
if(!$(this).hasClass('haspicker')){
$(this).myColorPicker().addClass('haspicker');
}
});
When The page loads no color pickers are attached. When the user clicks an input field with the 'color' class, it first receives focus, and the picker plugin gets attached, and the element gets an ectra class that is used to prevent subsequent double binding, then the click event fires and triggers the color picker to show up.
It works fine, but I'm not sure if it's a good practice, or if there could be potential problems with this approach that I haven't thought of.
So I'd just like to hear what you think?
A: Sounds reasonable. Another try would be to have just one picker instance onload, and then attach it to the element in focus (I assume the user never needs two parallel pickers).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608736",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: tinymce editor using opa import stdlib.core.web.resource
Editor = {{
base_url = Resource.base_url?""
load = <script type="text/javascript" src="{base_url}/tinymce/jscripts/tiny_mce/tiny_mce.js"></script>
@client init()=
((%% editor.init %%)())
@client getContent(dom : string)=
((%% editor.getContent %%)(dom))
tiny_mce = @static_resource_directory("tinymce")
}}
while running this above code I'm getting below error
Error
File "editor.opa", line 20, characters 6-25, (20:6-20:25 | 339-358)
Unable to type bypass
editor_init.
can anyone help me please?
A: I think you had not created the bypass before.
First use :
opa-plugin-builder editor.js
With a file "editor.js" like that :
##register init: -> void
##args()
{
tinyMCE.init({
mode: "textareas",
theme: "advanced"
});
}
##register getContent: string -> string
##args(a)
{
return tinyMCE.get(a).getContent();
}
And then you must get a folder named editor.opp
And now to compile editor.opa, you must call editor.opp
ex :
opa editor.opp editor.opa
Hope it helps :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608738",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: C++11 Template function that takes a std::function which depends of template parameters I am trying to write a template function that accepts a std::function which depends on the template arguments. Unfortunately the compiler is not capable of correctly deucing the arguments to the std::function. Here some simple example code:
#include <iostream>
#include <functional>
using namespace std;
void DoSomething( unsigned ident, unsigned param )
{
cout << "DoSomething called, ident = " << ident << ", param = " << param << "\n";
}
template < typename Ident, typename Param >
void CallFunc( Ident ident, Param param, std::function< void ( Ident, Param ) > op )
{
op( ident, param );
}
int main()
{
unsigned id(1);
unsigned param(1);
// The following fails to compile
// CallFunc( id, param, DoSomething );
// this is ok
std::function< void ( unsigned, unsigned ) > func( DoSomething );
CallFunc( id, param, func );
return 0;
}
If I call the template with the following:
CallFunc( id, param, DoSomething );
I get the following errors:
function-tpl.cpp:25: error: no matching function for call to CallFunc(unsigned int&, unsigned int&, void (&)(unsigned int, unsigned int))
If I explicitly create a std::function of the correct type (or cast it) the problem goes away:
std::function< void ( unsigned, unsigned ) > func( DoSomething );
CallFunc( id, param, func );
How would I code this so that the explicit temporary is not needed?
A: You need to make the third function parameter a non-deduced context for the template parameters therein. Then the compiler will not compare the argument type against the parameter type without also considering all implicit conversions (the Standard says, and C++0x clarified this further, that for a function parameter where there are no template parameters in deducing positions, all implicit conversions are allowed in bridging a difference).
template < typename T > struct id { typedef T type; };
template < typename Ident, typename Param >
void CallFunc( Ident ident, Param param,
typename id<std::function< void ( Ident, Param ) >>::type op )
{
op( ident, param );
}
Instead of id you can use boost::identity. In C++0x and compilers that support it, you can have a more readable edition using alias templates
template < typename T > using nondeduced = typename id<T>::type;
Then your code becomes simply
template < typename Ident, typename Param >
void CallFunc( Ident ident, Param param,
std::function< nondeduced<void ( Ident, Param )> > op )
{
op( ident, param );
}
However GCC does not yet support alias templates.
A: If you are using templates, you can avoid std::function entirely, unless for some reason you want to specifically restrict the function to take std::function:
template < typename Ident, typename Param, typename Func >
void CallFunc( Ident ident, Param param, Func op )
{
op( ident, param );
}
A: You can do the conversion inline or use bind. Neither is particularly pretty, but they get the job done:
CallFunc(id, param, std::function<void(unsigned, unsigned)>(DoSomething));
CallFunc(id, param, std::bind(DoSomething, std::placeholders::_1, std::placeholders::_2));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608741",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: update favourite list in realtime iphone My app has two tabs, one of which is a table view, in the other tab I can add the current object to the core data storage, and I wish the table view could be up-to-date anytime I am done adding and switch back to that tab (table view). Currently, the table view only refreshes when my app relaunches which is understandable, because I am getting the data in the viewDidLoad method in that viewController. When I switch back and forth between these two tabs, their views are already loaded, so how can I update the table view in realtime? Any advice would be appreciated.
Update:
A good example is the contact app on iphone, but I don't know how to do that...
Here is some code in the table view controller.
- (void)viewDidLoad {
[super viewDidLoad];
bList = [[NSMutableArray alloc] init];
self.navigationItem.leftBarButtonItem = self.editButtonItem;
//some code to get data from core data storage and put them in the bList array.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(receiveAddNotification:)
name:@"AddNotification"
object:nil];
}
-(void) receiveAddNotification: (NSNotification *)notification{
if ([[notification name] isEqualToString:@"AddNotification"]){
NSLog (@"Successfully received the add notification!");
}
}
Code in the other tab's view controller.
-(IBAction) addSomething {
[[NSNotificationCenter defaultCenter] postNotificationName:@"AddNotification" object:self];
//some code to store an object in core data.
}
The console can output the message "Successfully received the add notification!", which means the notification works fine, but the table view didn't get refreshed when I switch back to the table view tab from edit tab. I'm assuming the newly added object in addSomething method should be updated to the receiveAddNotification: method either.
A: Hi Michael as I understand your question, You can use notifications concept. Start notification service in the table view controller and when you are done with adding the things you can post the notification so that, that will update the table view automatically.
Look in to the NSNotificationCenter.
Let me explain with an example.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(receiveTestNotification:)
name:@"TestNotification"
object:nil];
add the above statement in the table view controller. Then you just define the "receiveTestNotification:" function with [tableview reload];
And in the editing view controller when user taps the done button you post the notification
[[NSNotificationCenter defaultCenter] postNotificationName:@"TestNotification" object:self];
So it will call the "receiveTestNotification:" method and run the code what ever you gave in that method.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608752",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Drag element from sortable list and drop to non-sortable block Drag an element from a sortable list and drop it to a block where elements are non-sortable but draggable.
Is there anyone know how to achieve this effect in Jquery?
<div id="viewpot">
<div id="sortable">
<div class="draggable">A</div>
<div class="draggable">B</div>
<div class="draggable">C</div>
<div class="draggable">D</div>
</div>
<div id="dropArea">
</div>
</div>
A: use the jquery draggable ui
A: You will want to make one list draggable and the target sortable.
Markup:
<ul>
<li id="draggable" class="ui-state-highlight">Drag me down</li>
</ul>
<ul id="sortable">
<li class="ui-state-default">Item 1</li>
<li class="ui-state-default">Item 2</li>
<li class="ui-state-default">Item 3</li>
<li class="ui-state-default">Item 4</li>
<li class="ui-state-default">Item 5</li>
</ul>
JavaScript:
$(function() {
$( "#sortable" ).sortable({
revert: true
});
$( "#draggable" ).draggable({
connectToSortable: "#sortable",
helper: "clone",
revert: "invalid"
});
$( "ul, li" ).disableSelection();
});
Happy coding!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608753",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Tabular view in Win32 API I am a newbie in win32 API and I'm trying to write an app that will calculate the md5sum of a file selected through the menu or dragged and dropped in the window. I want the window to have 3 columns so that it can display the filename, path and md5sum respectively. Can someone please give me a sample code as to how to make my window look like this?
Also can someone please add the code to create the window as listbox while the menu and drag-drop options are retained?
LRESULT CALLBACK WndProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam)
{
OPENFILENAME ofn;
char szFileName[MAX_PATH] = "";
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(OPENFILENAME); // SEE NOTE BELOW
ofn.hwndOwner = hwnd;
ofn.lpstrFilter = L"Text Files (*.txt)\0*.txt\0All Files (*.*)\0*.*\0";
wchar_t dest[255];
mbstowcs(dest,szFileName,255);
ofn.lpstrFile = dest;
ofn.nMaxFile = MAX_PATH;
ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
ofn.lpstrDefExt = L"txt";
SendDlgItemMessage(hwnd, IDC_LIST, LB_ADDSTRING, 0, (LPARAM)"Hi there!");
if(Message == WM_DROPFILES)
{
HDROP hDropInfo = (HDROP)wParam;
char sItem[MAX_PATH];
for(int i = 0; DragQueryFileA(hDropInfo, i, (LPSTR)sItem, sizeof(sItem)); i++)
{
if(GetFileAttributesA(sItem) &FILE_ATTRIBUTE_DIRECTORY)
{
MessageBox(hwnd, L"Attemt to calculate md5 of a directory!", L"Error",
MB_OK | MB_ICONINFORMATION);
}
else
{
mbstowcs(dest,sItem,260);
LoadFileToGetMD5(hwnd,dest);
}
}
}
switch(Message)
{
case WM_COMMAND:
switch(LOWORD(wParam))
{
case ID_FILE_OPEN:
{
if(GetOpenFileName(&ofn))
{
MessageBox(hwnd, dest, L"Notice",
MB_OK | MB_ICONINFORMATION);
LoadFileToGetMD5(hwnd,dest);
}
else
{
MessageBoxA(hwnd, "File Cannot be opened!", "Error",
MB_OK | MB_ICONINFORMATION);
}
}
break;
case ID_FILE_EXIT:
PostMessageA(hwnd, WM_CLOSE, 0, 0);
break;
case ID_STUFF_ABOUT:
{
DialogBox(GetModuleHandle(NULL),
MAKEINTRESOURCE(IDD_ABOUT), hwnd, AboutDlgProc);
}
break;
}
break;
case WM_CLOSE:
DestroyWindow(hwnd);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProcA(hwnd, Message, wParam, lParam);
}
return 0;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow)
{
WNDCLASSEX wc;
HWND hwnd;
MSG Msg;
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = 0;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = NULL;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wc.lpszMenuName = MAKEINTRESOURCE(ID_MENU);
wchar_t dest[25];
mbstowcs(dest,g_szClassName,25);
wc.lpszClassName = dest;
wc.hIconSm = NULL;
char name[10]="md5sum";
if(!RegisterClassEx(&wc))
{
MessageBoxA(NULL, "Window Registration Failed!", "Error!",
MB_ICONEXCLAMATION | MB_OK);
return 0;
}
hwnd = CreateWindowExA(
WS_EX_ACCEPTFILES,
g_szClassName,
"md5sum",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, 240, 120,
NULL, NULL ,hInstance, NULL);
if(hwnd == NULL)
{
MessageBoxA(NULL, "Window Creation Failed!", "Error!",
MB_ICONEXCLAMATION | MB_OK);
return 0;
}
ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);
while(GetMessage(&Msg, NULL, 0, 0) > 0)
{
if(!IsDialogMessage(g_hToolbar, &Msg))
{
TranslateMessage(&Msg);
DispatchMessage(&Msg);
}
}
return Msg.wParam;
}
A: you should search google for "listview in winapi"
btw,here is a code http://www.win32apicode.com/listview.php
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608755",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: using htk for non-digit recognizing I have been trying to use HTk coupled with sphinx4 for a speech recognition application. I am providing my input as a wav file and i am using the sphinx provided "Transcriber demo' and the 'Lattice Demo" however the output was pretty much unacceptable. So i decided to introduce HTK with Sphinx4. But the resultant output seems miles away. i am sure the configuration can be tweaked further.. than what i am doing. I have searched well for finding out if there is a ny tutorial related using htk and sphinx4 . Apart from this amazing blog (http://nsh.nexiwave.com/2009/09/using-htk-models-in-sphinx4.html) i have not found out anything else. Can anyone please help me out over here to improve my recognition accuracy..
My config file is sphinx is as follows :
<?xml version="1.0" encoding="UTF-8"?>
<!--
Sphinx-4 Configuration file
-->
<!-- ******************************************************** -->
<!-- an4 configuration file -->
<!-- ******************************************************** -->
<config>
<!-- ******************************************************** -->
<!-- frequently tuned properties -->
<!-- ******************************************************** -->
<property name="logLevel" value="WARNING"/>
<property name="absoluteBeamWidth" value="-1"/>
<property name="relativeBeamWidth" value="1E-80"/>
<property name="wordInsertionProbability" value="1E-36"/>
<property name="languageWeight" value="8"/>
<property name="frontend" value="epFrontEnd"/>
<property name="recognizer" value="recognizer"/>
<property name="showCreations" value="false"/>
<!-- ******************************************************** -->
<!-- word recognizer configuration -->
<!-- ******************************************************** -->
<component name="recognizer" type="edu.cmu.sphinx.recognizer.Recognizer">
<property name="decoder" value="decoder"/>
<propertylist name="monitors">
<item>accuracyTracker </item>
<item>speedTracker </item>
<item>memoryTracker </item>
</propertylist>
</component>
<!-- ******************************************************** -->
<!-- The Decoder configuration -->
<!-- ******************************************************** -->
<component name="decoder" type="edu.cmu.sphinx.decoder.Decoder">
<property name="searchManager" value="searchManager"/>
</component>
<!-- <component name="searchManager"
type="edu.cmu.sphinx.decoder.search.SimpleBreadthFirstSearchManager">
<property name="logMath" value="logMath"/>
<property name="linguist" value="lexTreeLinguist"/>
<property name="pruner" value="trivialPruner"/>
<property name="scorer" value="threadedScorer"/>
<property name="activeListFactory" value="activeList"/>
</component>
<component name="activeList"
type="edu.cmu.sphinx.decoder.search.PartitionActiveListFactory">
<property name="logMath" value="logMath"/>
<property name="absoluteBeamWidth" value="${absoluteBeamWidth}"/>
<property name="relativeBeamWidth" value="${relativeBeamWidth}"/>
</component>
-->
<component name="searchManager"
type="edu.cmu.sphinx.decoder.search.WordPruningBreadthFirstSearchManager">
<property name="logMath" value="logMath"/>
<property name="linguist" value="lexTreeLinguist"/>
<property name="pruner" value="trivialPruner"/>
<property name="scorer" value="threadedScorer"/>
<property name="activeListManager" value="activeListManager"/>
<property name="activeListFactory" value="activeList"/>
<property name="growSkipInterval" value="0"/>
<property name="checkStateOrder" value="false"/>
<property name="buildWordLattice" value="false"/>
<property name="acousticLookaheadFrames" value="1.7"/>
<property name="relativeBeamWidth" value="${relativeBeamWidth}"/>
</component>
<component name="trivialPruner"
type="edu.cmu.sphinx.decoder.pruner.SimplePruner"/>
<component name="threadedScorer"
type="edu.cmu.sphinx.decoder.scorer.ThreadedAcousticScorer">
<property name="frontend" value="${frontend}"/>
</component>
<component name="activeListManager"
type="edu.cmu.sphinx.decoder.search.SimpleActiveListManager">
<propertylist name="activeListFactories">
<item>standardActiveListFactory</item>
<item>wordActiveListFactory</item>
<item>wordActiveListFactory</item>
<item>standardActiveListFactory</item>
<item>standardActiveListFactory</item>
<item>standardActiveListFactory</item>
</propertylist>
</component>
<component name="standardActiveListFactory"
type="edu.cmu.sphinx.decoder.search.PartitionActiveListFactory">
<property name="logMath" value="logMath"/>
<property name="absoluteBeamWidth" value="${absoluteBeamWidth}"/>
<property name="relativeBeamWidth" value="${relativeBeamWidth}"/>
</component>
<component name="wordActiveListFactory"
type="edu.cmu.sphinx.decoder.search.PartitionActiveListFactory">
<property name="logMath" value="logMath"/>
<property name="absoluteBeamWidth" value="${absoluteWordBeamWidth}"/>
<property name="relativeBeamWidth" value="${relativeWordBeamWidth}"/>
</component>
<!-- ******************************************************** -->
<!-- The linguist configuration -->
<!-- ******************************************************** -->
<component name="flatLinguist"
type="edu.cmu.sphinx.linguist.flat.FlatLinguist">
<property name="logMath" value="logMath"/>
<property name="grammar" value="jsgfGrammar"/>
<property name="acousticModel" value="wsj"/>
<property name="wordInsertionProbability"
value="${wordInsertionProbability}"/>
<property name="languageWeight" value="${languageWeight}"/>
<property name="unitManager" value="unitManager"/>
</component>
<!-- ******************************************************** -->
<!-- The Grammar configuration -->
<!-- ******************************************************** -->
<component name="jsgfGrammar" type="edu.cmu.sphinx.jsgf.JSGFGrammar">
<property name="dictionary" value="dictionary"/>
<property name="grammarLocation"
value="resource:/edu/cmu/sphinx/demo/transcriber/"/>
<property name="grammarName" value="digits"/>
<property name="logMath" value="logMath"/>
</component>
<!-- ******************************************************** -->
<!-- The Dictionary configuration
<component name="dictionary"
type="edu.cmu.sphinx.linguist.dictionary.FastDictionary">
<property name="dictionaryPath"
value="resource:/WSJ_8gau_13dCep_16k_40mel_130Hz_6800Hz/dict/cmudict.0.6d"/>
<property name="fillerPath"
value="resource:/WSJ_8gau_13dCep_16k_40mel_130Hz_6800Hz/noisedict"/>
<property name="addSilEndingPronunciation" value="false"/>
<property name="wordReplacement" value="<sil>"/>
<property name="unitManager" value="unitManager"/>
</component> -->
<!-- ******************************************************** -->
<!-- ******************************************************** -->
<!-- The Dictionary configuration -->
<!-- ******************************************************** -->
<component name="dictionary"
type="edu.cmu.sphinx.linguist.dictionary.FastDictionary">
<property name="dictionaryPath"
value="file:C:\Raveesh\Softwares\apache-tomcat-6.0.32\apache-tomcat-6.0.32\bin\models\language\wsj\5100.dic"/>
<property name="fillerPath"
value="resource:/WSJ_8gau_13dCep_16k_40mel_130Hz_6800Hz/noisedict"/>
<property name="addSilEndingPronunciation" value="false"/>
<property name="wordReplacement" value="<sil>"/>
<property name="unitManager" value="unitManager"/>
</component>
<!-- ******************************************************** -->
<!-- The acoustic model configuration -->
<!-- ******************************************************** -->
<component name="wsj"
type="edu.cmu.sphinx.linguist.acoustic.tiedstate.TiedStateAcousticModel">
<property name="loader" value="wsjLoader"/>
<property name="unitManager" value="unitManager"/>
</component>
<component name="wsjLoader" type="edu.cmu.sphinx.linguist.acoustic.tiedstate.HTKLoader">
<property name="logMath" value="logMath"/>
<property name="modelDefinition" value="hmmdefs"/>
<property name="unitManager" value="unitManager"/>
</component>
<!--
<component name="wsjLoader" type="edu.cmu.sphinx.linguist.acoustic.tiedstate.Sphinx3Loader">
<property name="logMath" value="logMath"/>
<property name="unitManager" value="unitManager"/>
<property name="location" value="resource:/WSJ_8gau_13dCep_16k_40mel_130Hz_6800Hz"/>
</component>
-->
<!-- ******************************************************** -->
<!-- The unit manager configuration -->
<!-- ******************************************************** -->
<component name="unitManager"
type="edu.cmu.sphinx.linguist.acoustic.UnitManager"/>
<!-- ******************************************************** -->
<!-- The live frontend configuration -->
<!-- ******************************************************** -->
<!--
<component name="epFrontEnd" type="edu.cmu.sphinx.frontend.FrontEnd">
<propertylist name="pipeline">
<item>audioFileDataSource </item>
<item>dataBlocker </item>
<item>speechClassifier </item>
<item>speechMarker </item>
<item>nonSpeechDataFilter </item>
<item>preemphasizer </item>
<item>windower </item>
<item>fft </item>
<item>melFilterBank </item>
<item>dct </item>
<item>liveCMN </item>
<item>featureExtraction </item>
</propertylist>
</component>
-->
<!-- the front end configuration using the HTK loader.. -->
<component name="epFrontEnd" type="edu.cmu.sphinx.frontend.FrontEnd">
<propertylist name="pipeline">
<item>streamHTKSource</item>
</propertylist>
</component>
<component name="streamHTKSource" type="edu.cmu.sphinx.frontend.util.StreamHTKCepstrum">
<property name="cepstrumLength" value="39"/>
</component>
<!-- ******************************************************** -->
<!-- The frontend pipelines -->
<!-- ******************************************************** -->
<component name="audioFileDataSource" type="edu.cmu.sphinx.frontend.util.AudioFileDataSource"/>
<component name="dataBlocker" type="edu.cmu.sphinx.frontend.DataBlocker"/>
<component name="speechClassifier" type="edu.cmu.sphinx.frontend.endpoint.SpeechClassifier"/>
<component name="nonSpeechDataFilter"
type="edu.cmu.sphinx.frontend.endpoint.NonSpeechDataFilter"/>
<component name="speechMarker" type="edu.cmu.sphinx.frontend.endpoint.SpeechMarker" />
<component name="preemphasizer"
type="edu.cmu.sphinx.frontend.filter.Preemphasizer"/>
<component name="windower"
type="edu.cmu.sphinx.frontend.window.RaisedCosineWindower">
</component>
<component name="fft"
type="edu.cmu.sphinx.frontend.transform.DiscreteFourierTransform">
</component>
<component name="melFilterBank"
type="edu.cmu.sphinx.frontend.frequencywarp.MelFrequencyFilterBank">
</component>
<component name="dct"
type="edu.cmu.sphinx.frontend.transform.DiscreteCosineTransform"/>
<component name="liveCMN"
type="edu.cmu.sphinx.frontend.feature.LiveCMN"/>
<component name="featureExtraction"
type="edu.cmu.sphinx.frontend.feature.DeltasFeatureExtractor"/>
<!-- Newly Added.. -->
<component name="streamDataSource"
type="edu.cmu.sphinx.frontend.util.StreamDataSource">
<property name="sampleRate" value="16000"/>
<property name="bigEndianData" value="false"/>
</component>
<!-- ******************************************************* -->
<!-- monitors -->
<!-- ******************************************************* -->
<component name="accuracyTracker"
type="edu.cmu.sphinx.instrumentation.BestPathAccuracyTracker">
<property name="recognizer" value="${recognizer}"/>
<property name="showAlignedResults" value="true"/>
<property name="showRawResults" value="true"/>
</component>
<component name="memoryTracker"
type="edu.cmu.sphinx.instrumentation.MemoryTracker">
<property name="recognizer" value="${recognizer}"/>
<property name="showSummary" value="false"/>
<property name="showDetails" value="false"/>
</component>
<component name="speedTracker"
type="edu.cmu.sphinx.instrumentation.SpeedTracker">
<property name="recognizer" value="${recognizer}"/>
<property name="frontend" value="${frontend}"/>
<property name="showSummary" value="true"/>
<property name="showDetails" value="false"/>
</component>
<!-- ******************************************************* -->
<!-- Miscellaneous components -->
<!-- ******************************************************* -->
<component name="logMath" type="edu.cmu.sphinx.util.LogMath">
<property name="logBase" value="1.0001"/>
<property name="useAddTable" value="true"/>
</component>
<!-- ******************************************************** -->
<!-- The linguist configuration -->
<!-- ******************************************************** -->
<component name="lexTreeLinguist"
type="edu.cmu.sphinx.linguist.lextree.LexTreeLinguist">
<property name="logMath" value="logMath"/>
<property name="acousticModel" value="wsj"/>
<property name="languageModel" value="trigramModel"/>
<property name="dictionary" value="dictionary"/>
<property name="addFillerWords" value="false"/>
<property name="fillerInsertionProbability" value="1E-10"/>
<property name="generateUnitStates" value="false"/>
<property name="wantUnigramSmear" value="true"/>
<property name="unigramSmearWeight" value="1"/>
<property name="wordInsertionProbability"
value="${wordInsertionProbability}"/>
<property name="silenceInsertionProbability"
value="${silenceInsertionProbability}"/>
<property name="languageWeight" value="${languageWeight}"/>
<property name="unitManager" value="unitManager"/>
</component>
<!-- ******************************************************** -->
<!-- The Language Model configuration -->
<!-- ******************************************************** -->
<component name="trigramModel"
type="edu.cmu.sphinx.linguist.language.ngram.SimpleNGramModel">
<property name="location"
value="file:C:\Raveesh\Softwares\apache-tomcat-6.0.32\apache-tomcat-6.0.32\bin\models\language\wsj\5100.lm"/>
<property name="logMath" value="logMath"/>
<property name="dictionary" value="dictionary"/>
<property name="maxDepth" value="3"/>
<property name="unigramWeight" value=".7"/>
</component>
</config>
Any help would be really appreciated
A: Decoding from audio streams with HTK models is not supported yet in sphinx4. The HTK frontend configuration needs to be different. You can only decode mfc files extracted with HTK as described in the blog. The details on frontend issues are described in the blog comments too.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608756",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Image Effect on Hover w jQuery A few months ago, i ran accross a jQuery plugin which gave me a great effect once you moved your mouse over a thumbnail.
Actually, it made the image slide out in 4 pieces leaving some html content on it's place..here's a simple example image of what I'm looking for...
http://i.stack.imgur.com/B25dA.jpg
please, if you now what it is, let me know!
thanks in advance,
Tamas
A: http://www.queness.com/resources/html/slicing/index.html
Is this what you are looking for?
A: I think you're looking for jQuery UI Explode:
UI/Effects/Explode
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608757",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: iOS application's orientation remember? I have several view controllers, which maintains only landscape mode and one view controller with all interface orientations(for example, slideshow). "Splash screen" can only in landscape mode. After "slideshow" is in portrait mode and I fully terminate application(from task bar too), application starts a "splash screen"(what should in landscape mode) unexpectly in portrait. But why it happens, if splash screen is actually not rotates in portrait if device rotated? And how to resolve this problem? Thanks.
A: In your SplashScreenViewController write:-
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return (interfaceOrientation == UIInterfaceOrientationLandscapeRight || interfaceOrientation == UIInterfaceOrientationLandscapeLeft);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608758",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: frame.Eval(script) not returning the results in WatiN string result = frame.Eval(javaScriptCode) not returning the results in WatiN.
But it is working fine for browser.Eval(javaScriptCode)
A: If the page in your iframe has linked to another domain, you cannot execute javascript code for that frame. That is restricted by your browser to prevent CSS (Cross site scripting).
If you try to execute javascript code in such an iframe, you probably get "permis
To get more details about CSS, read this wiki
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608760",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Change value in first of two arrays (multidimensional) PHP I want to change the number in the first array in a multidimensional array. I have a code that outputs the value to an array and there is no chance for it to start counting from one - in my code. So my idea is to change the value starting from one - after it has been declared. My array look like this:
Array
(
[53] => Array
(
[name] => Volkswagen
[regularePrice] => 2139.00
)
[54] => Array
(
[name] => BMW
[regularePrice] => 2219.00
)
[55] => Array
(
[name] => Chrysler
[regularePrice] => 2399.00
)
)
I want - through a while or for - go through the array and change the values 53 to 1, 54 to 2, 55 to 3 and so on depending on how long the array is.
How do I accomplish this?
A: The answer is:
array_values($arr);
A: did you try:
$array = array_values($array);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608761",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I get App_Themes location in a html file using javascript I am looking for a solution in javascript, where I can get the location to App_themes\Theme folder which contains theme files in asp.net. For example why this isn't so easy is because
when the virtual directory has been mapped directly to domain name then it would be domainname\App_Themes\themename\default.css but if virtual directory has been mapped to something else then how will I differentiate between the name and it could also be directory name?
A: If your app is in the same virtual directory as the theme file, then you can just use relative path.
If your app is in a different virtual directory, then no way to auto change the path when the virtual directory changed.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608762",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: When executing JAR, get ExceptionInInitializerError: version.properties not found I've been writing a small project in Eclipse which runs perfectly within the IDE. Then I've build a runnable .jar file through Eclipse (which should include every dependency library inside the jar itself).
I use 3 library in my project:
*
*derby.jar
*qtjambi-4.7.1.jar
*qtjambi-win32-msvc2008-4.7.1.jar
Then I use this command (in windows):
java -jar prova.jar
And I get this:
Connected to database
Exception in thread "main" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoa
der.java:58)
Caused by: java.lang.ExceptionInInitializerError: version.properties not found!
at com.trolltech.qt.Utilities.<clinit>(Unknown Source)
at com.trolltech.qt.QtJambi_LibraryInitializer.<clinit>(Unknown Source)
at com.trolltech.qt.QtJambiObject.<clinit>(Unknown Source)
at WAAAGH.main(WAAAGH.java:52)
... 5 more
As you can see the derby.jar is working as expected ("Connected to database"), but there's an error with Qt-Jambi that I can't understand. Any idea?
EDIT: WAAAGH is the class containing the main method, line 52 consists in:
QApplication.initialize(args);
A: How is QtJambiObject getting loaded? Have you packeged it inside your prova.jar? The missing file version.properties should be part of the same jar at top level (not in any subdir). It seems you have not packaged it inside prova.jar at top level. See this for explanation of how it is loaded.
You might be better off specifying all jars and main class on command line:
java -classpath prova.jar;derby.jar;qtjambi-4.7.1.jar;qtjambi-win32-msvc2008-4.7.1.jar <your main class>
replace ; with : if you are running on *nix
A: FWIW the location of version.properties has recently been changed to be inside the package namespace of the bundles com/trolltech/qt/version.properties. The old location was a poor design choice and that has now been corrected. The issue is that if you have another JAR in your classpath that also has a toplevel file then the ClassLoader is entitled to think that the JAR with that file is authorative for the package and it does not need to search another JAR for the file. A package is a minimum deployable unit in Java, only specialist ClassLoaders (such as those use in OSGi) have features to work around this part of the Java design.
Usually your toplevel (application JAR) will be first in the list and I bet in that JAR you have one or more files like /log4j.properties /commons-logging.properties etc... it is because one or more file exists it then masks (hides) the file in the qtjambi-X.Y.Z.jar from being seen at runtime. Which is why the problem might not exist when you test a certain scenario but then appear when you try another (when you changed ClassPath in some way).
My commit to the project at http://qt.gitorious.org/qt-jambi/qtjambi-community/commit/f18ce5da3e30b43424bf94e49adf8c4cac0d9862 better explains in code the very recent change to make life better.
It should never have been the case that you have to copy the version.properties file from the QtJambi redistributable JARs into some other part of the Class Path (like the toplevel project prova.jar in your case) this is a bug that has been corrected for the next release. It is the long term intention to remove the need for the file completely and I am 80% there with that goal, as part of that work making multiple native JARs co-exist in the same Class Path will greatly simplify deployment and getting started guides; as well as making them play with OSGi and Eclipse nicely out-the-box.
However no releases have been made yet to include this change but I am very close (within 30 days of doing so for Qt 4.7.4).
Open Source plug alert: Please consider joining the mailing list at http://lists.qt.nokia.com/pipermail/qt-jambi-interest/ from http://lists.qt.nokia.com/mailman/listinfo for announcements.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608765",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Bash programming with filesystem functions I have been busy this week trying to wrap my head around a little Bash program to migrate a CMS from one server to another. The reasopn for this is because I have more tha 40 of these to do, and need to get it done in a timely manner, thus the Bash idea.
Needless to say, I have run into a couple of problems so far, but one of them has halted my development completetly, directory checking.
No I have tried a couple of methods and none of them seem to work really. The catch is that I have to check the folder on a remote server via ssh. Here my example:
ExSshRsa=~/.ssh/id_rsa
ExSshPort=22
ExSshHost=localhost
ExRoot=/var/www/
echo -n "Verifying Root access $ExRoot..."
SSHRoot='ssh -i $ExSshRsa -p $ExSshPort $ExSshHost [ -d $ExRoot ] || exit 1 '
echo $SSHRoot
if [ "$SSHRoot" -eq 0 ]
then
echo "OK"
else
echo "FAIL"
fi
I get the Error: [: : integer expression expected
Does the [ or test not resturn a 0 which is numerical. ?
A: change the shebang to #!/bin/bash -x and look at the output...
*
*you are storing a string in variable SSHRoot using single quotes, meaning that no variables will be expanded, i.e. a $ is still a $. Use double quotes instead, i.e. "
*to store the output from a command in bash, use
var=$(cmd)
*the exist status of a command is stored in the variable $?. Do a check on that after the ssh-command
*you are never executing the ssh-command in your code
Great link here for bash-programming
A: Try the following:
ExSshRsa=~/.ssh/id_rsa
ExSshPort=22
ExSshHost=localhost
ExRoot=/var/www/
echo -n "Verifying Root access $ExRoot..."
cmd="bash -c \"[ -d $ExRoot ] || exit 1\""
SSHRoot="ssh -i $ExSshRsa -p $ExSshPort $ExSshHost ${cmd}"
$SSHRoot
if [ $? -eq 0 ]
then
echo "OK"
else
echo "FAIL"
fi
The variables weren't being replaced in your SSHRoot variable as it's in single quotes. Also, you weren't passing an executable command, so that's why I use bash -c above. It will run the bash commands inside the quoted string.
$? stores the exit value of the last command, in this case the SSHRoot one.
A: Passing strings as arguments to a remote host is not trivial; you need to use arrays. A test example:
declare -a cmd=(touch "file name with spaces")
printf -v escaped_cmd_str '%q ' "${cmd[@]}"
ssh localhost $escaped_cmd
ssh localhost ls # Should return "file name with spaces" on a separate line
So your case should be:
ExSshRsa=~/.ssh/id_rsa
ExSshPort=22
ExSshHost=localhost
ExRoot=/var/www/
echo -n "Verifying Root access $ExRoot..."
declare -a cmd=( '[' -d "$ExRoot" ']' ) # Need to quote "[" since it's a Bash-specific symbol
printf -v escaped_cmd_str '%q ' "${cmd[@]}"
if ssh -i "$ExSshRsa" -p "$ExSshPort" "$ExSshHost" $escaped_cmd
then
echo "OK"
else
echo "FAIL"
fi
This is a rare case where using unquoted variable expansion is perfectly fine.
A: #!/bin/bash
ExSshRsa=~/.ssh/id_rsa
ExSshPort=22
ExSshHost=localhost
ExBase='/tmp/'
ExRoot='one space/'
declare -a AExRoot
for argR in "${ExRoot[@]}"
do
ExRoot+=($(printf %q "$argR"))
done
clear
FRoot=( $ExBase${ExRoot[@]} )
echo -n "Verifying Root access $FRoot..."
SSHRootTest="bash -c \"[ -d $FRoot ] && echo 0 && exit 0 || echo 1 && exit 1\""
SSHRoot=$( ssh -i $ExSshRsa -p $ExSshPort $ExSshHost ${SSHRootTest})
if [ $? -eq 0 ]
then
echo -en "\e[1;32mOK\e[0;37;m..."
else
echo -en "\e[1;31mFAIL\e[0;37;m..."
fi
sleep 1
if [ -w $FRoot ]
then
echo -e "\e[1;32mwritable\e[0;37;m"
else
echo -e "\e[1;31mNOT writeable\e[0;37;m"
fi
echo -e "\e[0;m"
exit 0
So I have incorporated all of the suggestions so far and have one last problem, the FRoot is not getting populated by the complete array values. Other than that I think it now has the subjective approach as suggested @john-keyes, the proper expansion @frederik and the crazy space escapes @l0b0
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608766",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: phonegap iphone : Documents Directory Absolute path I am new to PhoneGap and I am using it with Xcode.
Can anybody tell me how to get to the absolute path of the Documents Directory in the index.html?
A: function success(fileSystem) {
var path = fileSystem.root.fullPath;
}
// request the persistent file system
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, success, null);
path should point to /Documents.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608767",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: template error message c++ I have the following header file:
#ifndef DATABASE_H
#define DATABASE_H
#include <vector>
#include <iostream>
#include <string>
#include "record.h"
using namespace std;
template <class value>
class Database {
public:
void write (ostream& out, DBScope scope) const;
Database <value>() {};
~Database();
private:
vector <Record<value> > records;
};
#include "database.tem"
#endif
database.tem:
template <class value>
void Database<value>::write (ostream& out, DBScope scope) const {
class vector <Record <value> >::iterator itr = records.begin();
switch (scope) {
case AllRecords:
for (; itr != records.end(); itr++) out << itr;
break;
case SelectedRecords:
for (; itr != records.end(); itr++) {
if (itr.isSelected) out << itr;
}
break;
}
}
I was running this header a long with another file and produced this error message, noting that in my header file I have another file called database.tem which is #include "database.tem" into my database.h file:
database.tem: In member function 'void Database<value>::write (std:: ostream&, DBScope) const [with value = int]':
database.tem: In member function 'void Database<value>::write(std::ostream&, DBScope) const [with value = int]':
interactive.cpp:285: instantiated from 'bool WriteCommand(Database<value>&) [with value = int]'
interactive.cpp:127: instantiated from 'bool DispatchCommand(CommandT, Database<value>&) [with value = int]'
interactive.cpp:74: instantiated from 'void MainLoop(Database<value>&) [with value = int]'
interactive.cpp:99: instantiated from here
database.tem:6: error: conversion from '__gnu_cxx::__normal_iterator<const Record<int>*, std::vector<Record<int>, std::allocator<Record<int> > > >' to non-scalar type '__gnu_cxx::__normal_iterator<Record<int>*, std::vector<Record<int>, std::allocator<Record<int> > > >' requested
interactive.cpp:285: instantiated from 'bool WriteCommand(Database<value>&) [with value = int]'
interactive.cpp:127: instantiated from 'bool DispatchCommand(CommandT, Database<value>&) [with value = int]'
interactive.cpp:74: instantiated from 'void MainLoop(Database<value>&) [with value = int]'
interactive.cpp:99: instantiated from here
database.tem:11: error: no match for 'operator<<' in 'out << itr'
I have no idea what this messsage is talking about, can someone help me
A: The first error has to do that the method is const, hence records is const, and reconds.begin() returns a const_iterator.
template <class value>
void Database<value>::write (ostream& out, DBScope scope) const {
vector <Record <value> >::const_iterator itr = records.begin();
The second error means that you probably meant to dereference the iterator:
for (; itr != records.end(); itr++) out << *itr;
A: It looks like you have only posted a partial error message but the error is probably that you need to write itr->isSelected rather than itr.isSelected.
Also it's preferable to use ++itr instead of itr++ when using iterators.
A: What you are trying to print is iterator object, not the value it refer to:
out << itr;
Replace that with
out << *itr;
Also make sure that class Record has either method or function defined:
ostream& out operator <<(ostream& out); // method
ostream& out operator <<(ostream& out, const Record &); //function
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608775",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Simple TCPSocket server in Ruby exhibits a HTTP header issue I'm benchmarking some simple HTTP server implementations in Ruby (no threads, threaded, fibers and eventmachine) but this simple piece of code fails using threads:
#!/usr/bin/env ruby
require 'socket'
server = TCPServer.new("127.0.0.1", 8080)
puts "Listening on 127.0.0.1:8080"
while true
Thread.new(server.accept) do |client|
msg = client.readline
headers = [
"",
"HTTP/1.1 200 OK",
"Date: Fri, 30 Sep 2011 08:11:27 GMT",
"Server: TCP socket test",
"Content-Type: text/html; charset=iso-8859-1",
"Content-Length: #{msg.length}\r\n\r\n"].join("\r\n")
client.write headers
client.write ">>> Data sent:\n #{msg}"
client.close
end
end
A simple curl http://localhost:8080/ works fine, when the first element in the array is "" or other String, but not the "HTTP/1.1 200 OK" response directly. Why is this?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608779",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Reset HTML5 invalid input state The inputs with a validation are initially not marked as invalid until the value changes. How do I restore this initial state?
My problem in detail: I have a simple order form. If the user clicks the "add item" button, I clone the first item and empty the input fields. But since I'm using html5 validation, the emptying makes them invalid.
This is what happens after clicking "Add Product", even if the first set of fields is valid:
Demo: http://jsfiddle.net/WEHdp/ (view in Firefox):
<form action="/orders/preview" method="post">
<div class="orderData">
<input name="order[order_items_attributes][0][articleno]" pattern="[0-9]{4}" required /> /
<input name="order[order_items_attributes][0][colorno]" pattern="[0-9]{3}" required />
<div>
<a href="#" class="removeOrder">Remove product</a>
<a href="#" class="addOrder">Add product</a>
</div>
</div>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.js"></script>
<script>
$(document).ready(function() {
$(".addOrder").live("click", function (event) {
event.preventDefault();
// Clone div
$('.orderData:first').clone().insertAfter(".orderData:last");
// Empty the fields
$('.orderData:last input').val("");
});
$(".removeOrder").live("click", function (event) {
event.preventDefault();
if($('.orderData').size() > 1){
$(this).parents('.orderData').remove();
}
});
});
</script>
A: Clone the row on page ready, then you will always have a reference to the row in its default state.
Like so:
$(document).ready(function() {
var firstCopy = $('.orderData:first').clone();
$(".addOrder").live("click", function (event) {
event.preventDefault();
// Clone div
firstCopy.clone().insertAfter(".orderData:last");
// Empty the fields
$('.orderData:last input').val("");
});
$(".removeOrder").live("click", function (event) {
event.preventDefault();
if($('.orderData').size() > 1){
$(this).parents('.orderData').remove();
}
});
});
A: Html 5 validation marks the field as invalid because you have a required attribute on them.
Strip that and the marking will disappear when the field is empty. This is because empty states are valid for non-required fields, while it renders reqiured fields invalid (hence the marking).
No need for hacks. Just logic :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608780",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Query to return certain row always Can you suggest a query where a condition will be executed always . Say :
if($country == 'hong-kong')
{
$cond = "AND country = 'china'";
}
$q = "
SELECT
*
FROM
tbl_people
WHERE
region = 'asia'
$cond
ORDER BY RAND()
LIMIT 0,15
";
Now suppose $country = 'hong-kong' and it has total 4 members . What I want to know is is there any way so that if $country = 'hong-kong' I wll have 15 members in result set including the 4 members from hong-kong ?
A: If I understand the question correctly, you want 15 random results from a larger set, but you want to be sure that all of the results matching country = 'hong-kong' are included in those 15.
I think you're going to want two queries, because the number of records returned by the first one (country = 'hong-kong') will dictate the limit you put on the second query. E.g.:
SELECT
*
FROM
tbl_people
WHERE
country = 'hong-kong'
ORDER BY RAND()
LIMIT 0,15
Then
SELECT
*
FROM
tbl_people
WHERE
region = 'asia' AND country <> 'hong-kong'
ORDER BY RAND()
LIMIT 0,X
...where X is 15 - N, where N is how many rows were returned by your first query.
Then of course, you have to combine them in some kind of randomizing way (unless you want the Hong Kong results to be at the top/bottom/whatever of the list).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608786",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to filter a boolean column on ActiveAdmin? This question is related to the ActiveAdmin gem. I'm trying to filter a column that has a boolean type but with no success: filter :column_name and filter :column_name, :as => :boolean don't work.
Any idea?
Thanks!
A: filter :column_name, :as => :select will create a drop down with values "Any", "True", "False"
A: As of ActiveAdmin 0.6.2, using filter :column_name, as: :select now has the horrible side effect of doing a complete table scan. Plus, its options are now "Any", "true", "false".
For example, if I have a District model with the boolean column enabled then filter :enabled, as: :select generates the query SELECT DISTINCT "districts"."enabled" FROM "districts" ORDER BY enabled asc to obtain the 3 values. My districts table is quite large, so this is clearly not what I want.
OTOH, while I can now use filter :column_name, as: :boolean, it uses a checkbox that defaults to not being checked, which is again not what I want.
To restore the pre-0.6.2 behavior, I had to do this: filter :enabled, as: :select, collection: [["Yes", true], ["No", false]]. ActiveAdmin drops in the "Any" value for me.
A: Similarly, if you need to use checkboxes, do:
filter :column_name, as: :check_boxes
This will create checkboxes with the names Yes and No, whose values are true and false respectively.
If you want to customise the names, and maybe even the label? Then do:
filter :column_name, label: "Custom Column Name", as: :check_boxes, collection: [["Paid", true], ["Not paid", false]]
Though you can use checkboxes(it works!), I recommend using as::select as it 'remembers' the chosen value (on the UI) after page refresh. Checkboxes don't yet have this feature as of activeadmin version 1.2.1
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: open html file on sdcard with phonegap and jquery mobile i have some HTML files that users can download in runtime to sdcard. Now i want to create a link in my app to open those files. The problem is, i do not know what i should write in href property of the link tags to open the HTML files on sdcard
can anyone help me?
A: In the congif.xml file from my Blackberry app project locate on:
C:\Dev\phonegap\BlackBerry-WebWorks\<project_folder>\www
there are this lines:
<!-- PhoneGap API -->
<access subdomains="true" uri="file:///store/home" />
<access subdomains="true" uri="file:///SDCard" />
That config is granting access to those URI/resources, i think you can play around with that.
I have no idea how will be this URI on other plataforms, but is a good point to start the testing,
Good Luck!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608789",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: creating a hierarchical dropdownlist in asp.net i am working on eCommerce site in asp.net 3.5.in that i have to create categories.The categories is Stored as hierarchical order based on parent Id.Because the level can increase.
my problem is in add/Edit Categories page.in that categories has to display in hierarchy.
i was searching in Google for any help to create a hierarchical drop down list in asp.net.but i didn't get it.instead i found http://www.givainc.com/labs/mcdropdown_jquery_plugin.htm.
i am confused if i used the list instead of dropdownlist.
how can i get the value of selected item in code behind while saving.and how to select the item on category edit.
please help to sort out this.
A: for this you have to use recursion once I created it you can check my code. You can modify according to your requirement.
public void FillDDLOfParentCat()
{
DataTable dt = new DataTable();
dt = dal.GetDataTable("SELECT * FROM Category_Master WHERE Parent='0' ORDER BY Name");
ddl_category.Items.Add("--Select category--");
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
ListItem li = new ListItem(dt.Rows[i]["Name"].ToString(), dt.Rows[i]["PK_ID"].ToString());
ddl_category.Items.Add(li);
PrintChild(Convert.ToInt32(dt.Rows[i]["PK_ID"].ToString()), "----");
}
}
}
public void PrintChild(int pk_id, string Space)
{
DataTable dt = new DataTable();
dt = dal.GetDataTable("SELECT * FROM Category_Master WHERE Parent='" + pk_id + "' ORDER BY Name");
string sp = new string(Space.ToCharArray());
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
ListItem li = new ListItem(sp + dt.Rows[i]["Name"].ToString(), dt.Rows[i]["PK_ID"].ToString());
ddl_category.Items.Add(li);
PrintChild(Convert.ToInt32(dt.Rows[i]["PK_ID"].ToString()), "----" + sp);
}
}
}
A: I'm not sure whether this is an option for you, but the RadComboBox from Telerik is extremely flexible. Here's an example where I embedded a tree view in a RadComboBox:
<telerik:RadComboBox ID="DropDownList1" runat="server" CausesValidation="false" Skin="Sunset" AutoPostBack="true" Width="500" Font-Size="12px" Font-Names="Verdana" OnClientDropDownOpened="onDropDownOpened">
<ItemTemplate>
<div style="padding:0px 0px 5px 5px;">
<telerik:RadTreeView ID="TreeView1" runat="server" CausesValidation="false" Skin="Sunset" Font-Size="12px" Font-Names="Verdana" OnNodeClick="TreeView1_NodeClick" PersistLoadOnDemandNodes="true" ShowLineImages="true" OnClientNodeClicking="onTreeNodeClicking" />
</div>
</ItemTemplate>
<Items>
<telerik:RadComboBoxItem Text="" />
</Items>
</telerik:RadComboBox>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608791",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can DBI statement handles use cached calls to execute()? I have an application where the database rarely changes, and the application requires many reads from the database that is slowing down the performance quite significantly. Many of these reads are exactly the same. So I want to get DBI to cache the results of a database read.
For example,
$sth = $dbh->prepare('SELECT a, b FROM a_table WHERE c = ?');
$sth->execute(5);
$sth->execute(2);
$sth->execute(5); # this call loads the cached result set
I first thought this is what prepare_cached does, but I realised that it only caches the statement handle itself and not actual executions of the statement handle.
I suppose I could achieve what I want by wrapping the statement execution inside a memoized sub. But I'm just seeing if there is a shortcut within DBI itself.
A: as you said, the prepare_cached is related to the statement handle, and you need to cache the results of the execution. Memoize is good, but probably you need invalidate the cache from time to time, and re-execute the query to get a fresh copy from database.
I'd use the Cache (http://search.cpan.org/perldoc?Cache) module. I've just copied this fragment from the introduction:
use Cache::File;
my $cache = Cache::File->new( cache_root => '/tmp/cacheroot' );
my $customer = $cache->get( $name );
unless ($customer) {
$customer = get_customer_from_db( $name );
$cache->set( $name, $customer, '10 minutes' );
}
return $customer;
You can use in memory cache instead of File. This example uses the $customer value from cache if exists and it's valid, otherwise gets a fresh value and store at cache (with 10 minutes of life).
Hope this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608799",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: how to use C# variable inside of javascript block variable using Razor? I have a view file(.cshtml) with this C# block in top of file:
@{
List<string> selectedCategories = new List<string>();
}
well I want to use the selectedCategories list in the following javascript block
@section scripts{
<script src="../../Scripts/jquery-1.6.4-vsdoc.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#list-all-categories").selectable({
stop: function () {
var result = $("#selectedCategories").empty();
@selectedCategories.Clear()
$(".ui-selected", this).each(function () {
var Mytext = $(this).text();
@selectedCategories.Add(Mytext.toString());
});
}
});
});
</script>
}
SO, it's does not work!... at all!!!
I have some errors like this:
-Conditional compilation is turned off
-The name 'Mytext' does not exist in the current context
-...
what should I do?!
help me please!
A: *
*Javascript is run in the browser.
*Razor code is run in the webserver
You can't mix them like that.
You need to create form elements by using jQuery only and then post them back to the sevrer.
<script type="text/javascript">
$(document).ready(function () {
$("#list-all-categories").selectable({
stop: function () {
$(".selectedItems").remove();
$(".ui-selected", this).each(function () {
var Mytext = $(this).text();
$('#myform').append('<input type="hidden" name="selectedCategory" value="' + MyText + '" class="selectedItems" />');
});
});
});
</script>
change "myform" to the form that is posted.
And then you get the items as:
public ActionResult YourAction(string[] selectedCategory)
{
}
A: The problem is that razor expressions are compiled server-side, before the web page reaches web browser. But the JavaScript is interpreted at "run time", at client-side. Therefore you cannot add stuff to a c#-list from JavaScript like that.
Perhaps, if you need to maintain a c#-list in the backend, you could make an action on the controller that you can send items to via Ajax.
A: The Razor code is run by the web server as it's building text, at which point the Javascript is just plain text.
Razor just makes this stuff easier to read, but really it's just combining server execution with blocks of string text.
Your example is actually doing this:
Response.Write(@"
<script src=""../../Scripts/jquery-1.6.4-vsdoc.js"" type=""text/javascript""></script>
<script type=""text/javascript"">
$(document).ready(function () {
$(""#list-all-categories"").selectable({
stop: function () {
var result = $(""#selectedCategories"").empty();");
Response.Write( selectedCategories.Clear() );
Response.Write(@"$("".ui-selected"", this).each(function () {
var Mytext = $(this).text();");
Response.Write( selectedCategories.Add(Mytext.ToString()));
Response.Write(@"});
}
});
});
</script>");
So you get a compilation exception on Mytext because it doesn't exist server side - all that Javascript is just text strings to the server side .Net code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608800",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Viewstate invalid length error I've been trying to get to the bottom of the old Invalid length for a Base-64 char array and Invalid character in a Base-64 string.
It's a large ViewState, as I'm storing a big chunk of data in there that I don't want the user requesting from the database every three seconds. Because it was so large (4 meg in some cases), I'm compressing it with Gzip, and overriding LoadPageStateFromPersistenceMedium() and SavePageStateToPersistenceMedium(ByVal pageViewState As Object) and creating a custom viewstate.
Problem is, every now and then the above error is occurring. I'm trying to get to the bottom of this, and so store in Session the initial View state length when calling SavePageStateToPersistenceMedium, and compare it with the new viewstate length in LoadPageStateFromPersistenceMedium. What I've noticed is that the Viewstate length has been severely cut, and I'm wondering what could be causing this.
I have also noticed + characters appearing in the second string (I was taking the rightmost 10 of each to see if anything was being added initially). It's also definitely happening more for one user than others, which either indicates issues with the data he deals with, or with his physical connection to the system (speed, software, browser etc).
Does anyone have any ideas? We also have a number of blades servicing the users, so I was wondering if it might be as a user to pushed from one to the other, but I need to check this.
I had also heard that it could be to do with rendering, but I thought viewstate was loaded before render?
A: As suggested in my comment above you should analyse, understand and decide if that amount of data really needs to be sent back and forth at every page load; if it belongs to the page and is used by some user controls or if it's only used by you in the code behind in some kind of hand made caching mechanism.
I don't repeat all articles you can find online, the alternatives are ViewState for small amount of data only relevant in that page and per request, Session as per user cache and Cache as per application cache.
Read this article for more details: How to Choose From Viewstate, Session, Application, Cache, and Cookies
A: First of all, you shouldn't be storing large chunks of data in ViewState. That's not what the ViewState was designed for, and it will kill the performance of your page.
You should always try limit the number of hits to the database, but not at the expense of everything else. You're putting an enormous amount of stress on the web server by forcing it to post and serve 5MB pages every request.
If the data is user-specific then store it in session. If the data is not user-specific, then it might be a good fit for caching. Whatever the case, do not put it in ViewState. Moving the data to Session should solve the problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608810",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to get the exact mouse down coordinate? Why my code does not work? I would like to show something at the mouse down place, I tried to use :
$('#my-graph').mousedown(function(evt){
// show object at:
var x= evt.screenX, y=evt.screenY;
//or show object at:
var x2=evt.pageX, y2=evt.pageY;
//code to render object at (x,y) and (x2,y2)
......
});
But neither of the above (x, y) and (x2,y2) place the rendered object at the mouse clicked place, and show the object some distance away from mouse down place, why?
I render the object with a position attributes, the position is relative to the #my-graph div, left up most corner of the div is supposed to be the origin point(0,0)
A: You seem to want offsetX and offsetY: http://jsfiddle.net/f52Gg/.
$("div").mousedown(function(e){
alert(e.offsetX + " " + e.offsetY);
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608814",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Periodic failure when editing or creating in SQL using PHP I have a problem which I can't really figure out. I am tranfering information from a form, via JSON, to a PHP file which is handling the database call.
When trying it on my apache server it works aprox 75% of the time. The last 25% nothing happens. The form-window will close as ment to, and the page will reload, but the information hasn't been put into the DB.
When trying it at my domain, nothing happens at all. Same code though (I have another DB_connection file, with domain info, which works other places).
I'd like to have my code reviewed, to see if I have made a major mistake. Would love to have it 100% working.
As I said I have both a creation and an edit. I will post the edit form + php content here. If you need to see the creation, please tell me.
Javascript function, called when pushing the edit key (a test will be performed on the form fields before):
function xmlHTTPEdit() {
var product_ID = document.forms["addForm"]["product_ID"].value;
var product_Name = document.forms["addForm"]["product_Name"].value;
var product_Price = parseInt(document.forms["addForm"]["product_Price"].value);
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("POST", "../db/productEdit.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("createID=" + product_ID + "&createName=" + product_Name + "&createPrice=" + product_Price);
}
My php-file, updating DB, using the new data:
<?php
include('DB_Connect.php');
$product_ID = trim($_POST['createID']);
$product_Name = trim($_POST['createName']);
$product_Price = trim($_POST['createPrice']);
$sql = "UPDATE products SET productName = '$product_Name', productPrice = '$product_Price' WHERE productID = '$product_ID'";
mysql_query($sql);
?>
I really hope some of you can help me finding this flaw in my code and maybe help me with an explanation, why it works sometimes at localhost and never at my domain.
Thanks.
/Pyracell
A: The fact that it works sometimes makes me think there's something MySQL is unhappy about. Since PHP no longer throws MySQL errors as exceptions, you'll need to manually fetch the error.
Calling and echoing `mysql_error immediately after the query will display any resulting error, though a more appropriate solution for production would be to have it log to file rather than output to the user.
A: Try writing the data to a file rather than the database. Ajax is less solid than a database connection. I'd look there first. But isolate the two from each other for testing.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608815",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Open Document/file on client with impersonation I have an ASP.NET/c# web application.
There is a link on the page that i want to be able to click, open that file from a share, enable the user to edit it and then save it back to the share.
The share directory is locked down and can only be accessed via a seperate account, hence the need for impersonation.
I have tried many ways to do this, but have only managed to open the document on the client. (they are not able to save it directly back to the share without a seperate upload function)
Essentially, i would like to start a process on the client with impersonation so they can click save and will save directly back to the share.
Thanks
A: Register your own protocol handler on the client machine by first asking them to install your software.
On your ASP.NET web app you'll give link to the file but protocol will be your own instead of http:// or file:// this way your application will be invoked instead of windows trying to open it directly. Your app can impersonate the specific user that has access, open the file in a program and when the program exits it can exit.
See the following:
*
*Registering an Application to a URL Protocol
*A small C# Class for impersonating a User
*Process.WaitForExit Method
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608816",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to make Json lib generate such string: \/Date(1317375052044)\/ My target is to generate such json string: {"EndTime": "\/Date(1309737600000)\/"}
I define a HashMap to generate the string
If I define the string value as "\\/Date(1317375052044)\\/" then the result is "\\\\/Date(1317375052044)\\\\/".
If I define the string as "/Date(1317375052044)/" then the result is "/Date(1317375052044)/".
How I can generate the result "\/Date(1309737600000)\/"?
A: Duplicated from How should I escape strings in JSON? . Following this response try defining the string as "\\\\/Date(1317375052044)\\\\/" because in Java String '\' is also a escape character!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608819",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is it possible to set autosizing in interface builder for rotatable bg image? I'm designing the UI with IB with a lot of images, and the default design orientation is landscape. However, I need to shrink the whole view to fit in portrait mode, by shrinking to the maximum allowed width and maintaining same aspect ratio for the view with it's inner images. The best way to imagine what I want to achieve is to imagine some landscape photo. When you rotate that to portrait it shrinks to the maximum width, centers vertically, but maintains the same aspect ratio. In my case, I want to shrink a view with its all inner subviews.
First, I'm manually resizing view frame to required size in viewWillApppear, and also calling setAutoresizesSubviews to resize all it's inner views. Those inner views - images are with "Aspect Fit" and all autosizing options set (to fill the available area on resized view). However, inner views pops out of the container: some images jumps to the top, text view expands to full portrait height. Is possible to set some kind of "view-container", then say - "view resize to size X and resize all your but only inside view-container area?
A: When you design in IB you must check several things. First of all the "view container" properties, that is the view that contains all subview. In order to behave properly on rotation this view must be setup with right IB Autosizing properties, that is with the autosize lines (springs) and border lines (structs) correctly set. In your case you want your container to be exactly fit with the main view so enable the "structs" at the four sides and enable the "springs" inside. Play with this values and look at the "Example" displayed by IB.
Then you must instruct this container to properly behave with its subviews. So check in IB that "Autoresize subviews" and the content mode, if needed, (= "Mode") has the wished setting.
At this point you check in the device or the simulator if your view is rotating and rising properly.
Then you must take care of the content of this view, which is a UIImageView. This must be centered, so remove the structs, and autoresized, so set the springs. Then set the content mode to Aspect Fit or Aspect Fill at your wish.
These settings should work. For more complex stuff, you must programmatically set things.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608824",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to remote events in .NET Remoting? I have a class for remoting which contains events. But when I am trying to set handler for those events on the client side I receive exception. My code looks like:
//In common library
class RemoteClass : MarshalByRefObject
{
public event EventHandler SomeEvent = null;
public void SomeMethod () {}
}
//On client-side
RemoteClass r = (RemoteClass) RemotingServer.Connect (typeof(RemoteClass), "myURL");
r.SomeMethod (); //Everything is OK here.
r.SomeEvent += delegate (object o, EventArgs e) { }; //Exception:Type
System.DelegateSerializationHolder and the types derived from it (such as System.DelegateSerializationHolder) are not permitted to be deserialized at this security level.
What do I do wrong?
A: https://web.archive.org/web/20141009214120/http://msdn.microsoft.com/en-us/library/61w7kz4b(v=vs.80).aspx
In the .NET Framework, the default security level for distributed communication (remoting) is low. This affects passing the user-defined object type to remote methods. You might need to adjust the default security level to full in some cases to allow serialization of objects.
If you're in ASP.Net, here's how to set the security (trust) level:
http://msdn.microsoft.com/en-us/library/ff648344.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608826",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.