text
stringlengths 8
267k
| meta
dict |
---|---|
Q: Get current pathname using JavaScript I'm using the following JavaScript to get the pathname to show a link is selected:
var pathname = window.location.pathname;
$(document).ready(function ()
{
$('ul#ui-ajax-tabs li a').each(function()
{
if ($(this).attr('href') == pathname)
{
$(this).parents('li').addClass('selected');
}
});
});
However it has problems if that URL has extra parameters such as / on the end of the url or additional parameters (see examples below) Is it possible to check if the link matches part of the url so for example:
The Link is: /Organisations/Journal/
And the Current page is: /Organisations/Journal/Edit/21
This would class as being selected as it matches part of the url!
A: window.location.pathname.match('^/Organisations/Journal/');
The ^ character matches the beginning of the string.
A: You can probably use indexOf to check if the pathname starts with the value of the href attribute:
if (pathname.indexOf($(this).attr('href')) == 0) {
...
}
See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/indexOf for more information on the indexOf method.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619585",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Life of a Blobstore on the development server I found this question, which appears to describe the problem I am currently having, i.e. blobstore files do not persist after a restart.
Blobstore Images Disappearing on Google App Engine Development Server
However, I believe the question is referring to the python server, and I am running java. I have used the help flag and searched the docs, but dont see mention of the --blobstore_path command line argument. Is there an equivalent for the java server?
A: As you may or may not be aware, a bug report was filed for this:
Issue 5449: Blobstore objects not accessible after development-server restarts
This was fixed on Feb 9, 2012 so upgrading to the latest version of the App Engine SDK should resolve this for you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619586",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Access Master page variables in child page in ASP.NET Here is my master page file. I need to pass strName, id, url, starttime, etc. to my Child page. I know we can write this logic in our Child page, but, I would like to access this Master Page variable in my Child page only.
I cannot write this logic in each set/get method. While accessing these variable in the Child page, I am getting null values. basically here the master pageload calls after the child pageload calls over:
*
*MASTER PAGE NAME: MyMasterPage
public partial class MyMasterPage: MasterPage
{
public string strName = string.Empty;
public string id= string.Empty;
public string url = string.Empty;
public string startTime = string.Empty;
public string endTime = string.Empty;
public string remoteUrl = string.empty;
public void Page_Load(object sender, EventArgs e)
{
DataTable dtEventTable = DataAccessManager.GetEventInfo(Connection);
if (dtEventTable.Rows.Count > 0)
{
strName = dtEventTable.Rows[0]["NAME"].ToString();
id = dtEventTable.Rows[0]["ID"].ToString();
url= dtEventTable.Rows[0]["URL"].ToString();
starttime = dtEventTable.Rows[0]["starttime"].ToString();
endtime = dtEventTable.Rows[0]["endtime"].ToString();
remotelive = dtEventTable.Rows[0]["remotelive"].ToString();
// assume that strName = "TCG",id=5, startime=20111001 etc.
}
}
}
A: Found this by Ramesh T on https://forums.asp.net/post/5557778.aspx
U better create a strongly typed reference to ur master page by adding
a @ MasterType directive in ur content (aspx page) as shown below
<%@ MasterType virtualPath="~/MasterPage1.master"%>
and access its members in your aspx page or code behind (aspx.cs) as
below
var test1Text = Master.test1;
This way you don't need to cast.
A: This would work, as Muhammad Hasan and Pete suggested:
string name = ((MyMasterPage)this.Master).strName;
Or:
<%@ MasterType virtualPath="~/MasterPage1.master"%>
var test1Text = Master.test1;
however, consider that code inside Page_Load event at master page, is executed after Page_Load in your content page.
So if you set the value of your variable in master page, and then try to get in content page, you will get null value.
you will find here more information: https://msdn.microsoft.com/en-us/library/dct97kc3.aspx
A: string name = ((MyMasterPage)this.Master).strName;
Read Working with ASP.NET Master Pages Programmatically
A: You can use Session[] object for reaching variables from another page.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619591",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: Write a file and check if a file exists I would like to write a .txt file to a local disk (and prompt the user to scan a document) after which the script should halt/loop until it finds a certain .pdf file on the local disc.
EDIT:
I have heard that HTML5 packs a new JavaScript API called "FILE API", and I KNOW that what I'm trying to do IS possible. I just have no idea how to do it.
A: It s not possible to access to the local drive via the browser / javascript
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619592",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Why Rijndael encryption code is not working for large file? I use the following Rijndael code to do encryption without fail for many times. But why it can not encrypt an ISO file with 4.2 GB? In fact my computer has 16GB memory and it should not be a memory problem. I use Windows 7 Ultimate. The code is compiled as winform (.Net 4) using Visual Studio 2010 (a VB.NET project).
I have checked that the ISO file is OK and can be mounted as virtual drive and even can be burnt to DVD rom. So it is not the ISO file problem.
My question: Why the following code cannot encrypt an ISO file with size of 4.2GB? Is that caused by the limitation of Windows/.NET 4 implementation?
Private Sub DecryptData(inName As String, outName As String, rijnKey() As Byte, rijnIV() As Byte)
'Create the file streams to handle the input and output files.
Dim fin As New IO.FileStream(inName, System.IO.FileMode.Open, System.IO.FileAccess.Read)
Dim fout As New IO.FileStream(outName, System.IO.FileMode.OpenOrCreate,
System.IO.FileAccess.Write)
fout.SetLength(0)
'Create variables to help with read and write.
Dim bin(100) As Byte 'This is intermediate storage for the encryption.
Dim rdlen As Long = 0 'This is the total number of bytes written.
Dim totlen As Long = fin.Length 'Total length of the input file.
Dim len As Integer 'This is the number of bytes to be written at a time.
'Creates the default implementation, which is RijndaelManaged.
Dim rijn As New Security.Cryptography.RijndaelManaged
Dim encStream As New Security.Cryptography.CryptoStream(fout,
rijn.CreateDecryptor(rijnKey, rijnIV), Security.Cryptography.CryptoStreamMode.Write)
'Read from the input file, then encrypt and write to the output file.
While rdlen < totlen
len = fin.Read(bin, 0, 100)
encStream.Write(bin, 0, len)
rdlen = Convert.ToInt32(rdlen + len)
End While
encStream.Close()
fout.Close()
fin.Close()
End Sub
A: rdlen = Convert.ToInt32(rdlen + len)
Int32 can represent signed integers with values that range from negative 2,147,483,648 to positive 2,147,483,647 and since 4.2GB is about twice that I guess rdlen never will get bigger than totlen and thus you got yourself a never ending loop.
If VB.NET works anything like C# (and I suspect it does) you simply remove the convert
rdlen = rdlen + len
The result of a Long+Int will be a Long. Where Long is a 64 bit signed integer and Int a 32 bit signed integer.
A: Try to change from this:
rdlen = Convert.ToInt32(rdlen + len)
to this:
rdlen = Convert.ToInt64(rdlen + len)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619593",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Expected ')' before error in objective-c protocol declaration In WebServiceAPI.h, which I referred in the code below, i declared a protocol with a required metod -(void) apiFinished:(WebServiceAPI *)api. When compiling the code i get this error: WebServiceAPI.h:13: error: expected ')' before 'WebServiceAPI' (line 13 is where the method of the protocol is declared). where am I doing wrong?
#import <Foundation/Foundation.h>
@protocol WebServiceAPIDelegate
@required
-(void) apiFinished:(WebServiceAPI *)api;
@end
@interface WebServiceAPI : NSObject{
NSString *address;
NSMutableData *dataWebService;
}
@property (nonatomic, assign) id <WebServiceAPIDelegate>delegate;
@property(nonatomic, retain) NSString *address;
@property(nonatomic, retain) NSMutableData *dataWebService;
@end
A: The problem is that WebServiceAPIDelegate doesn't know about the class WebServiceAPI when it is defined. Add a @class directive before you create WebServiceAPIDelegate @protocol declaration.
// Add the following line to let the compiler stop worrying about
// the existance of class WebServiceAPI
@class WebServiceAPI;
@protocol WebServiceAPIDelegate
@required
-(void) apiFinished:(WebServiceAPI *)api;
@end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619594",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JavaScript select() method What does the select() method in JavaScript do? When should we use it?
A: Note: .select() is a jQuery function.
This method is a shortcut for .bind('select', handler) in the first two variations, and .trigger('select') in the third.
The select event is sent to an element when the user makes a text selection inside it. This event is limited to <input type="text"> fields and <textarea> boxes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619599",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
} |
Q: Display all the images in thumbnail view from a database table(SQL Server) in VB 2010 We are doing a project using VB2010 as front end SQL server 2008R2 as backend.We need the code to display all the images in thumbnail view in VB when we open a database table.
A: Create a thumbnail using Image.GetThumbnailImage Method.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619603",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android Screen Sizes and Densities I am considering to drop support for small screens in my app.
Recently I have stumbled upon Screen Sizes and Densities and currently (2011-10-01) it says that 3.5 percent of the active devices fall into the small/hdpi category. I wonder what device actually has a small screen with high pixel density?
I know of the HTC Wildfire which has 240 x 320 pixels, 3.2 inches (~125 ppi pixel density). If I understand correctly that would be an ldpi device. For my app the Wildfire has a share of somewhere around 2 percent.
So first, why does Screen Sizes and Densities not list anything under small/ldpi? And second, what would be an example of a small/hdpi device?
A: There are some device from Dell like Aero which comes under small/hdpi.
HTC Tattoo can be considered under small/ldpi
A: Just to add to Basavraj's answer, Guessing the screen size is not that simple. Like Galaxy note has 1200 X 800 screen dimensions but it's screen size falls in large(and not in extra-large) category.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619606",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How portable is linking executables against loadable modules? I have a project on my hand with some libraries that are compiled as loadable modules, i.e. linked with libtool's -module flag. These libraries are supposed to contain all the necessary functions in themselves or their dependencies, that is, they should yield a complete program when linked with a simple main() function that simply calls all functions of the module interface for my program.
Since I had issues with incomplete and thus unusable modules before, I have a few simple check programs that do just contain a main() and are linked against the modules. When a function is missing, the linker croaks with appropriate warnings, so all good there. However, libtool gives me one warning:
*** Warning: Linking the executable checkplugin_locprec against the loadable module
*** liblocprec.so is not portable!
I understand the purpose and intent of this warning (don't link a program against a library built with -module), however not its severity, and that's my question:
How severe is this warning? Am I just lucky that this works on the platforms I am compiling for (i386/x86_64 Linux and MinGW) or is this warning just relevant for some obscure backwood platform I can safely ignore?
A: The main platform were this doesn't work is Mac OS X. On other platforms, it should generally work, but might fail depending on other build options you use. If you used libtool, then you are probably safe on other platforms.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619607",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Date picker format for Blackberry webworks? I am unable to change format in Blackberry web works application.
I used this code for date picker
<input type="date" name="from_date" id="from_date" />
Here it displays date like yyyy-mm-dd but I need dd-mm-yyyy.
A: Seeing that Blackberry supports the input type=date, seems that it is not possible to change the date format yet.
(Which was also stated on this SO Question)
I suggest you do one of these things instead :
*
*Create a custom date picker using jQuery UI
*If you want to have the Blackberry feel, create a java extension for the date picker.
*Let the current input type date format on your app and just build the dd-mm-yyyy format on your javascript using the Date functions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619612",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to change the file upload folder in apache tomcat? Tomcat 6.29 creates a folder under temp folder in apache tomcat, and when I uploaded a file with the path req.getSession().getServletContext() + specified folder but when the application is redeployed another application folder is again created so the previously uploaded files stay at the older deployed application. I want to upload files under webapp folder/app_name but at that time I take the specified doesn't exist. I wonder if it is possible to upload and retrieve the files under the webapp/app_name.
Note: application is developed with spring+hibernate and deployed with maven.
A: Yes. Just use a relative path in your file handler code. Go up with ../../.. etc. Or you can make a direct server request against the old app from within your handler - servlet to servlet, for example.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619614",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Objective-C :: How to use NSAutoreleasePool for NSMutableRequest - asynchronous request? In a view controller I am doing a lot of NSMutableRequest calls asynchronously. In call back method I am handling the response. These all requests are autoreleased. Here, I want to know how to use NSAutoReleasePool to release these autoreleased objects. Can you please clarify on this?
Thanks in advance.
A: Autoreleased object means that it's being released for you (auto standing for self in latin (I think)). The release of these objects is being managed by NSAutoreleasePool in main.m file's main function. You don't need to do anything if you're not retaining or copying them explicitly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619623",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Hadoop, Mahout real-time processing alternative I intended to use hadoop as "computation cluster" in my project. However then I read that Hadoop is not inteded for real-time systems because of overhead connected with start of a job. I'm looking for solution which could be use this way - jobs which could can be easly scaled into multiple machines but which does not require much input data. What is more I want to use machine learning jobs e.g. using created before neural network in real-time.
What libraries/technologies I can use for this purposes?
A: Given the fact that you want a real-time response in de "seconds" area I recommend something like this:
*
*Setup a batched processing model for pre-computing as much as possible. Essentially try to do everything that does not depend on the "last second" data. Here you can use a regular Hadoop/Mahout setup and run these batches daily or (if needed) every hour or even 15 minutes.
*Use a real-time system to do the last few things that cannot be precomputed.
For this you should look at either using the mentioned s4 or the recently announced twitter storm.
Sometimes it pays to go really simple and store the precomputed values all in memory and simply do the last aggregation/filter/sorting/... steps in memory. If you can do that you can really scale because each node can run completely independently of all others.
Perhaps having a NoSQL backend for your realtime component helps.
There are lot's of those available: mongodb, redis, riak, cassandra, hbase, couchdb, ...
It all depends on your real application.
A: Also try S4, initially released by Yahoo! and its now Apache Incubator project. It has been around for a while, and I found it to be good for some basic stuff when I did a proof of concept. Haven't used it extensively though.
A: You are right, Hadoop is designed for batch-type processing.
Reading the question, I though about the Storm framework very recently open sourced by Twitter, which can be considered as "Hadoop for real-time processing".
Storm makes it easy to write and scale complex realtime computations on a cluster of computers, doing for realtime processing what Hadoop did for batch processing. Storm guarantees that every message will be processed. And it's fast — you can process millions of messages per second with a small cluster. Best of all, you can write Storm topologies using any programming language.
(from: InfoQ post)
However, I have not worked with it yet, so I really cannot say much about it in practice.
Twitter Engineering Blog Post: http://engineering.twitter.com/2011/08/storm-is-coming-more-details-and-plans.html
Github: https://github.com/nathanmarz/storm
A: What you're trying to do would be a better fit for HPCC as it has both, the back end data processing engine (equivalent to Hadoop) and the front-end real-time data delivery engine, eliminating the need to increase complexity through third party components. And a nice thing of HPCC is that both components are programmed using the same exact language and programming paradigms.
Check them out at: http://hpccsystems.com
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619629",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: How to delete all files that were recently created in a directory in linux? I untarred something into a directory that already contained a lot of things. I wanted to untar into a separate directory instead. Now there are too many files to distinguish between. However the files that I have untarred have been created just now (right ?) and the original files haven’t been modified for long (at least a day). Is there a way to delete just these untarred files based on their creation information ?
A: Tar usually restores file timestamps, so filtering by time is not likely to work.
If you still have the tar file, you can use it to delete what you unpacked with something like:
tar tf file.tar --quoting-style=shell-always |xargs rm -i
The above will work in most cases, but not all (filenames that have a carriage return in them will break it), so be careful.
You could remove the directories by adding -r to that, but it's probably safer to just remove the toplevel directories manually.
A: find . -mtime -1 -type f | xargs rm
but test first with
find . -mtime -1 -type f | xargs echo
A: There are several different answers to this question in order of increasing complexity.
First, if this is a one off, and in this particular instance you are absolutely sure that there are no weird characters in your filenames (spaces are OK, but not tabs, newlines or other control characters, nor unicode characters) this will work:
tar -tf file.tar | egrep '^(\./)?[^/]+(/)?$' | egrep -v '^\./$' | tr '\n' '\0' | xargs -0 rm -r
All that egrepping is to skip out on all the subdirectories of the subdirectories.
Another way to do this that works with funky filenames is this:
mkdir foodir
cd foodir
tar -xf ../file.tar
for file in *; do rm -rf ../"$file"; done
That will create a directory in which your archive has been expanded, but it sounds like you wanted that already anyway. It also will not handle any files who's names start with ..
To make that method work with files that start with ., do this:
mkdir foodir
cd foodir
tar -xf ../file.tar
find . -mindepth 1 -maxdepth 1 -print0 | xargs -0 sh -c 'for file in "$@"; do rm -rf ../"$file"; done' junk
Lastly, taking from Mat's answer, you can do this and it will work for any filename and not require you to untar the directory again:
tar -tf file.tar | egrep '^(\./)?[^/]+(/)?$' | grep -v '^\./$' | tr '\n' '\0' | xargs -0 bash -c 'for fname in "$@"; do fname="$(echo -ne "$fname")"; echo -n "$fname"; echo -ne "\0"; done' junk | xargs -0 rm -r
A: You can handle files and directories in one pass with:
tar -tf ../test/bob.tar --quoting-style=shell-always | sed -e "s/^\(.*\/\)'$/rmdir \1'/; t; s/^\(.*\)$/rm \1/;" | sort | bash
You can see what is going to happen leave off the pipe to 'bash'
tar -tf ../test/bob.tar --quoting-style=shell-always | sed -e "s/^\(.*\/\)'$/rmdir \1'/; t; s/^\(.*\)$/rm \1/;" | sort
to handle filenames with linefeeds you need more processing.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Allignmet and the duration of the Toast? I want to show the toast always in my application and want to custom alignment of the toast ?
A:
want to custom alignment of the toast ?
For changing the alignment you should look at android's official documentation of Toasts : Custom Toasts or AndroidPeople--Custom Toasts
I want to show the toast always in my application
For changing the duration of Toast you should look at Think Android--Indefinite Toast Hack
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619631",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: 'Server Not Found' error when using sfDomainRoutePlugin with Symfony I am trying to create a site with subdomains, using the sfDomainRoutePlugin plugin. I am using SF version 1.4.12 on Linux, with Apache as the web server.
I am following the online instructions and have created the following routing file:
homepage:
url: /
class: sfDomainRoute
param: { module: foo, action: index }
requirements:
sf_host: [portal.localhost]
#Sample route limited to one subdomain
blog:
url: /
class: sfDomainRoute
param: { module: foo, action: foo1 }
requirements:
sf_host: blog.portal.localhost
#Sample route that will capture the subdomain name as a parameter
user_page:
url: /
class: sfDomainRoute
param: { module: foo, action: foo2 }
#Sample route that will not receive a subdomain and will default to www.greenanysite.com
install:
url: /install
class: sfDomainRoute
param: { module: foo, action: foo3 }
My foo module code has the methods foo1, foo2 and foo3 implemented as stub functions, and each have their template which simply contains text confirming which method was executed (e.g. 'foo::Foo1 was called') etc.
The template for the index method (in the foo module) looks like this:
<html>
<head><title>Test subdomains</title></head>
<body>
<ul>
<li><?php echo link_to('homepage', '@homepage'); ?></li>
<li><?php echo link_to('blog', '@blog'); ?></li>
<li><?php echo link_to('zzzrbyte', '@user_page?subdomain=zzzrbyte'); ?></li>
<li><?php echo link_to('install', '@install'); ?></li>
</ul>
</body>
</html>
The urls are generated correctly (i.e. with subdomains as specified in the routing.yml file), however when I click on the 'blog' or 'zzzrbyte' link, I get the error message: 'Server Not Found'
For example, I got this message:
Server not found Firefox can't find the server at
blog.portal.localhost.
AFAICT, I am following the online instructions exactly, so I can't see where I am going wrong. Can anyone spot what is likely to be causing this problem?.
[[UPDATE]]
I just realized that by adding the subdomain to my hosts file, this seems to get rid of the problem. I am not sure if this is the fix or simply a temporary workaround. If this is the way to do things, I wonder why such a vital piece of information was left out of the notes?
If this is the way to get things to work, it means that subdomains will have to be known before hand (i.e. not generated dynamically and resolved at run time), also - I am not sure how such a solution works for a remote server, since I am running multiple websites (as virtual servers) on one physical machine and I am not using a hosts file on the server.
Any help will be much appreciated.
A: Adding the subdomain to the hosts is the correct way to solve this issue
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619639",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: emacs + latex + yasnippet: Why are newlines inserted after a snippet? Everytime I insert a snippet (with yasnippet) in a .tex document, I obtain a newline after the snippet. This is quite annoying for small snippets that are typically used in text style. How can I avoid that?
I read a bit about the problem (http://code.google.com/p/yasnippet/issues/detail?id=115 or http://yasnippet.googlecode.com/svn/trunk/doc/faq.html) but couldn't find a solution. Reproduce it as follows (I work with Aquamacs 2.3a on Mac OS X 10.6.8 with yasnippet version 0.6.1c):
*
*Define ~/Library/Preferences/Aquamacs Emacs/Preferences.el to be:
(require 'yasnippet)
(yas/initialize)
(yas/load-directory "~/Library/Preferences/Aquamacs Emacs/plugins/yasnippet-0.6.1c/snippets")
*define the following snippet (call it "bm.yasnippet" [bm = boldmath]; the star * symbolizes where the cursor ends -- note that there is no newline after the snippet)
# name: \bm{}{}
# key: bm
# --
\bm{$1}*
*restart Aquamacs and open a .tex file and type in bm + Tab [this should insert the snippet]
*A newline is added after the snippet. This is quite inconvenient since \bm{foo} is typically used in text style, so for example in "The vector \bm{x} is not the null vector". A typical cause of this is that the snippet ends with a newline which is then inserted, too. However, I specifically obtain this behavior even the snippet does not end with a newline.
A: I can't repro it with plain Emacs. In fact, I had this exact issue, but my problem is I had require-final-newline set to t. So Emacs was adding a newline at the end of my template.
My setup is a little more complicated but the solution for you is probably to set mode-require-final-newline to nil and restart Emacs.
To verify this is the problem, open up the template and check for the final newline.
A: Thanks to the answers in Temporarly disable adding of newlines in Emacs, I'm using a function to only temporarily disable the adding of final newlines in the current buffer:
(defun disable-final-newline ()
(interactive)
(set (make-local-variable 'require-final-newline) nil))
A: the reason why u got a new line is that your snippet has space or tab at the end.
Ctrl+e and Ctrl+k to kill them will make it works, nearly 1 hour to figure it out...
A: I had a similar issue with a few snippets, one of that was \frac{}{} which I use quite often.
The snippet version of frac that I use is not the one bundled with yasnippets.
The issue was that I edited some of the snippets in VIM and when you save the file, VIM automatically appends a newline to it.
To resolve it I had to remove the newline in a different editor e.g. emacs.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619640",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: consume items from a scala Iterator I'm confused about behavior of method take in trait Iterator. It seems that it doesn't consume items. Here is an example:
scala> Iterator(1,2,3)
res0: Iterator[Int] = non-empty iterator
scala> res0 take 2 toArray
res1: Array[Int] = Array(1, 2)
scala> res0.next
res2: Int = 1
Apparently step 2 consumes two items, but in step 3 the Iterator is still at first item. Looking at the implementation, I can't see any kind of copying or buffering, just a new Iterator which delegates to the underlying one. How could it be possible? How can I manage to really consume n items?
A: Thanks guys.
This is my solution to consume bunches of items from an Iterator:
implicit def consumable(i: Iterator[_]) = new {
def next(n: Int) = {
(for (_ <- 1 to n) yield i.next()).iterator
}
def skip(n: Int) {
(1 to n).foreach(_ => i.next())
}
}
any comments will be welcome.
A: The iterator in question is defined in IndexedSeqLike#Elements (source). A ticket was recently filed about the the inconsistent behaviour of take across different iterator implementations.
To really consume N items, call Iterator#next N times.
You might want to consider using Stream, which is a lazy (like Iterator), but is also immutable (unlike Iterator).
scala> val s = Stream(1, 2, 3)
s: scala.collection.immutable.Stream[Int] = Stream(1, ?)
scala> s.take(2).toList
res43: List[Int] = List(1, 2)
scala> s.take(2).toList
res44: List[Int] = List(1, 2)
scala> s.drop(2).toList
res45: List[Int] = List(3)
scala> {val (s1, s2) = s.splitAt(2); (s1.toList, s2.toList)}
res46: (List[Int], List[Int]) = (List(1, 2),List(3))
A: You want to consume the items, drop them. Note that most methods called on an Iterator will make that Iterator useless for further use -- useless in the sense that behavior is undefined and subject to change.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: How to implement backend of api with multiple versions I'm using Django to implement a private rest-like API and I'm unsure of how to handle different versions of the API on the backend.
Meaning, if I have 2 versions of the API what does my code look like? Should I have different apps that handle different version? Should different functions handle different versions? Or should I just use if statements for when one version differs from another?
I plan on stating the version in the Header.
Thanks
A: You do not need to version REST APIs. With REST, versioning happens at runtime either through what one might call 'must-ignore payload extension rules' or through content negotiation.
'must-ignore payload extension rules' refer to an aspect you build into the design of your messages. 'Must-ignore' means that a piece of software that processes a message of the given format must ignore any unknown syntactical constructs. This is what we all know from HTML and what makes it possible to insert all sorts of fancy tags into an HTML page without the parser choking.
'Must-ignore' allows you to evolve the capabilities of your service by adding stuff to what you send already without considering clients that only understand the older versions.
Content-negotiation refers to the HTTP-built-in mechanism of negotiating the actual representation the server sends to a given client at runtime. The typical scenario is this: Clients send the Accept header in the request to advertise what they are capable of and servers pick the representation to send back based on these capabilities. But there are also variations of this theme (see here for details: http://www.w3.org/Protocols/rfc2616/rfc2616-sec12.html ).
Content negotiation allows for incompatible changes, meaning that I can evolve my service to being able to send incompatible old and new versions and based on the Accept header my service will send the appropriate one.
Bottom line: with both approaches, your API remains as it is. No need to do any versioning at the API level - especially not the often suggested (but totally wrong) inclusion of version identifiers in the URIs (remember, you are doing REST here, not SOAP!)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619645",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Does pthread_detach free up the stack allocated to the child thread, after the child thread as exited I have used pthread_detach inorder to free up the stack allocated to the child thread, but this is not working, I guess it does not free up the memory.....
I don't want to use pthread_join. I know join assures me of freeing up the stack for child, but, I don't want the parent to hang up until the child thread terminates, I want my parent to do some other work in the mean time. So, I have used detach, as it will not block the parent thread.
Please, help me. I have been stuck..
A: YES - according to http://cursuri.cs.pub.ro/~apc/2003/resources/pthreads/uguide/users-16.htm it frees memory either when the thread ends or immediately if the thread has already ended...
As you don't provide any clue as how you determine that the memory is not freed up I can only assume that the method you use to determine it is not sufficient...
A:
this is not working
Yes it is. You are likely mis-interpreting your observations.
I want my parent to do some other work in the mean time
That's usually the reason to create threads in the first place, and you can do that:
pthread_create(...);
do_some_work(); // both current and new threads work in parallel
pthread_join(...); // wait for both threads to finish
report_results();
I don't want to use pthread_join. I know join assures me of freeing up the stack for child
Above statement is false: it assures no such thing. A common implementation will cache the now available child stack for reuse (in case you'll create another thread shortly).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619648",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: RIA Services : expose services when entities are in a different project from EDMX? My Visual Studio solution has the following architecture :
*
*a "DataAccess" project, containing one EDMX with his "object context" class (but without any generated business class)
*an "Entities" project, containing the business entities generated from the EDMX. (ex : Customer class, Order class, Product class, etc).
*a "Web" project containing the ASP.Net GUI.
Now I want to add a small Silverlight area in my existing application, with RIA Services.
I don't succeed in creating the domain Service : the "Add new domain service class" wizard contains my ObjectContext but itself contains no entities. It seems that it's because the EDMX is NOT in the same assembly as my entities.
Now I don't want to rebuild my existing application with a new architecture by merging the 2 projects (actual architecture seems clean for me).
How can I make this %$$$! wizard see my entities ? Should I construct the domain service class manually ? How ?
Thanks !
EDIT : I'm using C# (4), EF 4, Silverlight4
EDIT 2 : my entities are generated with the "ADO.NET POCO Entity Generator".
A:
Should I construct the domain service class manually ?
I reckon so. It's the same using EF 5 with POCOs, the wizard doesn't pick up the entities. There are some helpful snippets on Colin Blair's site for creating the CRUD methods over the DbContext.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619652",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Issue moving new item to newly added list until I do page refresh I am using a jquery template for dynamically creating a list (columns) which has different items (they are also added dynamically) and also created a plugin which helps moving items from one list to 2nd or 3rd i.e. using jquery ui drag & drop, but having a problem while dropping the item to the newly added list.
Scenario: When I click add list button, it creates list on the page. So I added a list named 'list1' and each list have a button to add items on the list so by pressing it twice I added 2 items on 'list1'. And items are moveable/draggable/dropable. Now added a 2nd list named 'list2'. So if I try to move an item from 'list1' to 'list2' it doesn't do that instead the item moves to 'list1'. This is happening without page reload, but if I refresh the page and do the same action now the item can be moved to 'list2'. Here is the code that I am using the for drag and drop purposes is here (the following code is placed in my jquery plugin):
var id = $('.' + options.dropID);
var id0 = options.dropID;
$('.' + options.dropID).sortable({
helper: "clone",
revert: "invalid", // go back to original droppable when drop outside drop area
connectWith: '.' + options.dropID,
over: function (event, ui) {
// may be usefull
var sortableElement = this;
var dataToSave = {
name: ui.item.text(),
objid: ui.item.attr('title'), // id has changed for array so use original id stored in title
thisID: $(sortableElement).attr('id'),
array: $(sortableElement).sortable("serialize")
};
// save the new data
saveData(dataToSave);
}
});
so I noticed a behaviour that the different behaviour is here:
- added an item and no page load, it add following div
<div id="337" class="cardItem droppable"> </div>
so if i try to add item here it doesn't allow me.
*
*after page load, it modify the above div to:
it adds ui-sortable to class attribute. So I try to search how or when this ui-sortable is added, it is done by jquery's sortable method.
and on page load I am calling the plugin like this:
<script type="text/javascript">
$(window).bind("load", function () {
$('.laneList').ListDragandDrop();
});
</script>
I also calling the ListDragandDrop() after adding the new list or item but it doesn't add ui-sortable to the div, and I have to refresh the page so it can make 'list2' dropable. Can you tell me what I am doing wrong or what should I modify to make it work.
A: JQuery sortables seems to have been fixed in the latest version for items added after the creation. If you're still seeing this problem, please add a jsfiddle so we can help with debugging.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619653",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: SimpleXML fetch tag incl. all child-elements I would like to parse an rss-file with simplexml. If I print a specific tag, direct content is selected only - no children and "sub"-tags are included. How can I access a tag incl. children-tag names and their content?
//load rss into $xml
foreach ($this->xml->channel->item as $item) {
echo "<h3>{$this->out($item->title)}</h3>",
$this->out($item->description);
}
A: You can use $this->xml->children() to get child nodes, and then use that recursively. I recently wrote a method to copy one XML block recursively into another - which should show you the techniques you can use.
protected function copyXml(SimpleXMLElement $from, SimpleXMLElement $to)
{
// Create a new branch in the target, as per the source
$fromValue = (string) $from;
if ($fromValue)
{
$toChild = $to->addChild($from->getName(), (string) $from);
}
else
{
$toChild = $to->addChild($from->getName());
}
// Copy attributes across
foreach ($from->attributes() as $name => $value)
{
$toChild->addAttribute($name, $value);
}
// Copy any children across, recursively
foreach ($from->children() as $fromChild)
{
$this->copyXml($fromChild, $toChild);
}
}
HTH.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Could not open property database I am using Windows XP , i want to have a repository , so i created it using Apache Server
Inside my Apache server , why i am getting this error ??
I have used this to create my repository under httpd-dav.conf
Alias /sites "C:/Program Files/Apache Software Foundation/Apache2.2/sites"
<Directory "C:/Program Files/Apache Software Foundation/Apache2.2/sites">
Dav On
Order Allow,Deny
Allow from all
AuthType Digest
AuthName DAV-upload
Options Indexes
AuthUserFile "C:/Program Files/Apache Software Foundation/Apache2.2/user.passwd"
AuthDigestProvider file
# Allow universal read-access, but writes are restricted
# to the admin user.
<LimitExcept GET OPTIONS>
require user admin
</LimitExcept>
</Directory>
[Sat Oct 01 15:44:07 2011] [error] [client 127.0.0.1] Could not open property database. [500, #1]
[Sat Oct 01 15:44:07 2011] [error] [client 127.0.0.1] The locks could not be queried for verification against a possible "If:" header. [500, #0]
[Sat Oct 01 15:44:07 2011] [error] [client 127.0.0.1] Could not open the lock database. [500, #400]
[Sat Oct 01 15:44:07 2011] [error] [client 127.0.0.1] Could not open property database. [500, #1]
[Sat Oct 01 15:44:07 2011] [error] [client 127.0.0.1] The locks could not be queried for verification against a possible "If:" header. [500, #0]
[Sat Oct 01 15:44:07 2011] [error] [client 127.0.0.1] Could not open the lock database. [500, #400]
[Sat Oct 01 15:44:07 2011] [error] [client 127.0.0.1] Could not open property database. [500, #1]
[Sat Oct 01 15:44:07 2011] [error] [client 127.0.0.1] The locks could not be queried for verification against a possible "If:" header. [500, #0]
[Sat Oct 01 15:44:07 2011] [error] [client 127.0.0.1] Could not open the lock database. [500, #400]
[Sat Oct 01 15:44:07 2011] [error] [client 127.0.0.1] Could not open property database. [500, #1]
[Sat Oct 01 15:44:07 2011] [error] [client 127.0.0.1] The locks could not be queried for verification against a possible "If:" header. [500, #0]
[Sat Oct 01 15:44:07 2011] [error] [client 127.0.0.1] Could not open the lock database. [500, #400]
[Sat Oct 01 15:44:07 2011] [error] [client 127.0.0.1] Could not open property database. [500, #1]
please tell me how to resolve this ??
A: I am using Window 2008.
What I found was that the default entry for the DavLockDB in the \conf\extra folder was:
/Apache Software Foundation/Apache2.2/var/DavLock
However, there was no var directory created under the Windows install.
Creating the var directory seemed to solve it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Rotate image to point I have the following:
CGPoint pos //center of an image
CGPoint target //a point, somewhere in the coordinate system
float rotation //the current rotation of the image to the x-axis, clockwise, so "right" would be 90°
Now I want the image to rotate around it's centerpoint (pos) so that it looks directly towards the targetpoint.
My idea was: Calculate the angle corresponding to the x-axis, subtract rotation, and then rotate it.
Two things:
1.) I fail at calculating the angle. (Yes, I know it's all in rad...)
2.) What's best for rotating?
*
*CGAffineTransform? But then I'd need an imageView
*Or: save context, set origin to center of image, rotate context, draw image, restore context? More complicated, but no imageview neeeded...
A: Draw it on a CALayer, and move the layer around anyway you like.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619669",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: hide a header of a column with binding data in asp.net would it be possible to do it like this?
<asp:TemplateField HeaderText="Export" Visible='<%# Bind("isExported") %>'>
</asp:TemplateField>
I tried it and I got this problem:
The TemplateField control with a two-way databinding to field deviceExport must have an ID
A: You should use <%# Eval("isExported")%> instead of <%# Bind("isExported")%>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619670",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can I rename an implemented method in Java? I have a class which is implementing an interface, and one of the methods is called onClick. Is there a way to implement the onClick that the interface wants but name it something else? Something like (and I'm making this up):
public void AnyMethodNameIWant() implements Interface1.onClick
Three reasons I'm asking are:
*
*It would be nice to look at an method signature and know that it's
coming from an interface
*To avoid 'generic' names like onClick that an interface may require me to have
*To distinguish between the same method names in many interfaces
Apologies if this is a fundamentally 'bad' question as I am new to Java.
A: No, you can't. Interfaces have to be implemented by a method of the same name in Java.
You can use the @Override annotation with interface implementations (as of Java 6) though, which helps to clarify that this is a method which can't just be renamed arbitrarily.
One option for your second issue might be to create an implementation class just for the purpose of forwarding on the call to a more specific method. You might want to do this as a nested or even anonymous class. I'm not sure I'd usually do this though.
EDIT: Having seen the third question - no, if you have two interfaces with the same method signature in Java, you can only provide one implementation :( Oh, and if you've got two interfaces with the same signature but different return types, it's even worse. You could always write a method of Interface1 getInterface1() which returns an instance of an anonymous inner class proxying the Interface1 methods onto the "main" class.
A: Nope.
The only thing you could do is add a shadow method that implements the interface and calls your method.
public class MyClass implements Interface1 {
public void AnyMethodNameIWant() { ...; }
public void onClick() { AnyMethodNameIWant(); }
}
A: Those two points
*
*To avoid 'generic' names like onClick that an interface may require me to have
*To distinguish between the same method names in many interfaces
are usually solved by using the Adapter Pattern.
interface IFoo {
void onClick();
void onChange();
}
class MyImpl {
void doSomething(){
// real code for onClick
}
void doSomethingElse(){
// real code for onChange
}
IFoo getFooAdapter(){
return new IFoo() {
@Override
public void onClick() {
doSomething();
}
@Override
public void onChange() {
doSomethingElse();
}
};
}
}
Basically you create an intermediate step which forwards all calls to any interface method to the real implementation.
Naming and signatures can vary. You can also offer different adapters for different interfaces if you want (or must if both interfaces have competing method with different behaviour).
There are quite some possibilities how to hand out the adapter instance - creating a new one every time might not be wise in certain circumstances.
Of course this pattern is nothing you implement just for fun or just for minimal and clean code. But it can solve real problems.
A: You can't rename the method, but you could define both methods (onClick and anyMethodNameIWant) and have onClick just simply call your other method.
@Override
public void onClick() {
anyOtherMethodNameIWant();
}
A: You of course can have additional methods with different names that point to the same implementation to get the naming you desire.
public void interfaceMethodA(){
// some implementation here
}
public void AnyMethodNameIWant(){
interfaceMethodA();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619671",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Jquery Dialog is throwing error I am getting this error while I am using
Microsoft JScript runtime error: Object doesn't support this property or method.
I am using Jquery Dialog.
Thanks in advance
Javascript
function showQnsLogic(hdfLogicID) {
var qnsString = document.getElementById(hdfLogicID).innerHTML;
var distance = 10;
var time = 250;
var hideDelay = 500;
var hideDelayTimer = null;
var beingShown = false;
var shown = false;
var info = $('#divqnsLogic');
var windowWidth = document.documentElement.clientWidth;
var windowHeight = document.documentElement.clientHeight;
var popupHeight = $("#popupContact").height();
var popupWidth = $("#popupContact").width();
$("#divqnsLogic").dialog();
$('#divqnsLogic').html(qnsString);
}
HTML
<div class="demo">
<div id="dialog-modal" title="Basic modal dialog">
<div id="divqnsProp" class="popupNew">
<table width="100%;" id="tblContent">
<tr>
<td>
<div id="divProperties" style="font: Arial; font-size: 11px; overflow: auto">
<div class="descriptionPanelHeader">
Question Properties </div>
</div>
</td>
</tr>
</table>
</div>
</div>
</div>
A: This error happen sometimes if you don't have the jquery dialog library well included.
And could you give us more details on the error.
thanks
A: The error "Object doesn't support this property or method" indicates that the dialog() method of $("#divqnsLogic") could NOT be found.
Since this method is included in JQuery UI, rather than JQuery core, at a guess you've only included the core libraries and need to add a reference to JQuery UI.
e.g. If you reference does it solve the problem?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619674",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
} |
Q: hibernate3-maven: JDBC Driver not found in child project when compiling from parent project Problem:
12:03:10,126 ERROR org.hibernate.tool.hbm2ddl.SchemaExport - schema export unsuccessful org.hibernate.HibernateException: JDBC Driver class not found: com.mysql.jdbc.Driver
I have a project divided into modules: ParentProject and ChildModule. When I try to compile pom.xml of ChildModule everything works fine, maven successfully connects to the database an creates the tables. However, when compiling from ParentProject I got error mentioned above (while executing hbm2ddl). Any ideas what is the problem?
Here are my pom.xml files:
ParentProject pom.xml:
<project ... >
<build>
<plugins>
<plugin>
<!-- JDK version used to compile project -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.0.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>hibernate3-maven-plugin</artifactId>
<version>2.2</version>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>JBOSS</id>
<name>JBoss Repository</name>
<url>http://repository.jboss.org/maven2/</url>
</repository>
<repository>
<id>Codehaus Snapshots</id>
<url>http://snapshots.repository.codehaus.org/</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
<releases>
<enabled>false</enabled>
</releases>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>Codehaus Snapshots</id>
<url>http://snapshots.repository.codehaus.org/</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
<releases>
<enabled>true</enabled>
</releases>
</pluginRepository>
</pluginRepositories>
<dependencyManagement>
<dependencies>
...
</dependencies>
</dependencyManagement>
<modules>
<module>../ChildModule</module>
</modules>
</project>
ChildModule pom.xml:
<project ... >
<parent>
<groupId>com.somepackage</groupId>
<artifactId>ChildModule</artifactId>
<version>0.1</version>
<relativePath>../ParentProject/pom.xml</relativePath>
</parent>
...
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>hibernate3-maven-plugin</artifactId>
<executions>
<execution>
<id>generate-entities</id>
<phase>generate-sources</phase>
<goals>
<goal>hbm2java</goal>
</goals>
<configuration>
<components>
<component>
<name>hbm2java</name>
<implementation>configuration</implementation>
<outputDirectory>${generated-source-dir}</outputDirectory>
</component>
</components>
<componentProperties>
<configurationFile>src/main/resources/hibernate.cfg.xml</configurationFile>
<jdk5>true</jdk5>
</componentProperties>
</configuration>
</execution>
<execution>
<id>generate-schema</id>
<phase>process-classes</phase>
<goals>
<goal>hbm2ddl</goal>
</goals>
<configuration>
<componentProperties>
<outputfilename>schema.ddl</outputfilename>
<drop>true</drop>
<ejb3>false</ejb3>
</componentProperties>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.17</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>2.2.2</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
<dependencies>
...
</dependencies>
<properties>
<generated-source-dir>generated-sources/hibernate3</generated-source-dir>
<generated-resource-dir>generated-resources/hibernate3</generated-resource-dir>
</properties>
</project>
A: Your parent's plugin doesn't have dependencies to mysql-connector-java, which child has. I suggest to add (or even move) this dependencies to parent's plugin.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619676",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to get calendar events by date? I am inserting data in my device calendar by this code.
i want those events by date.
if i pass date and i want to get event name.
thanks in advance.
A: For that you need to use EventKit/EventKitUI framework.
please refer code provided by Apple : Here This sample shows how to use EventKit and EventKitUI frameworks to access and edit calendar data in the Calendar database.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619682",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Is Javascript any better than before as mentioned in the O'Reilly Javascript Patterns book for closures and anonymous functions? This is a quote from the O'Reilly Javascript Patterns book:
JavaScript is also an unusual language. It doesn’t have classes, and
functions are first class objects used for many tasks. Initially the
language was considered deficient by many developers, but in more
recent years these sentiments have changed. Interestingly, languages
such as Java and PHP started adding features such as closures and
anonymous functions, which JavaScript developers have been enjoying
and taking for granted for a while.
and that's it. I really don't understand how Javascript was considered "deficient" before, and now is not, because other languages like Java or PHP has added closures and anonymous functions? Aren't they just generic computing concepts? Aren't they available in other languages like Ruby? So I don't really know how Javascript is now not "deficient" because Java and PHP added closures and anonymous functions as their features? Why is that?
A: I think what it's referring to is that in the past many developers considered JavaScript as a 'toy' language and only used it to do quick Web UI tasks like validation etc. without bothering to understand how the language really worked.
In recent years the 'hidden' features of JavaScript such as closures, prototypal inheritance etc. have come to the fore and people are now taking JavaScript much more seriously as a 'real' language.
So JavaScript was never really "deficient" but people may have thought that it was due to their misconceptions about the language.
A: I personally think it's a poor editing job.
The paragraph should have read (bold addition is mine and is just a suggestion on how
to read it):
JavaScript is also an unusual language. It doesn’t have classes, and
functions are first class objects used for many tasks. Initially the
language was considered deficient by many developers, but in more
recent years these sentiments have changed due to a better and more uniform browser support, extensive work done by various ECMA editions and evolution of various JavaScript frameworks. All, or much, of that change is a direct result of ever-expanding movement of software products to the Web and growing demand for a lightweight language for mobile applications (this one can be somewhat argued).
Interestingly, languages such as Java and PHP started adding features
such as closures and anonymous functions, which JavaScript developers
have been enjoying and taking for granted for a while.
A: For years, JavaScript has been known to only be a browser language, for (simple) features that required more dynamic and/or flexibility than offered by HTML and CSS.
For several years now, JavaScript evolved as a language and as platform, offering powerful libraries, which also removed certain cross-browser incompatibilities. With rise of these libraries, community actually only started to learn how to use some powerful concepts of JavaScript, such as closures and prototypal inheritance.
They have not been widely used nor known even to JavaScript developers before, since JavaScript is in its basics very simple language, and most developers didn't even have to learn it as you'd learn Python, C or Java - all they had to look at were tutorials and many of them didn't include these language features.
Duo to the increase in popularity, JavaScript (officially ECMAScript) has received several 'editions', where features have been added to the language itself. Latest edition (still under development) will introduce some radical novelties (considered are classes, module system, iterators, algebraic types among others), so JS will become even better, more structured and more easily maintainable language.
JavaScript is raising in popularity on server side also (node.js), and proves to be easy, fast and enough powerful language to do (almost) any kind of work. Node widely 'abuses' probably its best feature - asynchronous nature of JavaScript. That is not new, many languages have async libraries, but as Ryan Dahl said in one of his earliest speeches on node, JS is perfect for it. And mainly because of the closures and other concepts built into it.
So final answer would be the author of the book you're quoting has poorly expressed his thoughts or is simply wrong. It was a toy language and didn't mean to be used for such variety of use cases as it is today. But it evolved, just as Java or PHP did (don't forget PHP didn't have OOP support that seems so obvious now until v5). Other languages are just picking up goodies that JavaScript proved to be more efficient for certain use cases. Overall, my thoughts are that JavaScript hasn't been used properly from the start, and that's the case it had been called 'deficient'. Now developers got chance to explore its magnificence.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619685",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Automatically saving doc file after 20 secs i am doing a php program which requires doc file to be saved after every 10 secs.msword should not ask the path to be saved. actually i have written a program which opens a doc file. the file should be auto saved to the exact location from where the file is opened.
A: If I understand you correctly, what you want to do is not possible (sadly).
There is no standard or protocol for live editing of remote files that have been downloaded from a web page in a browser. The file will be downloaded to a temporary location and opened from there.
Hence, any notion of providing an auto-save mechanism from PHP or JavaScript is completely impossible. The client application will have to do that.
If you want to upload the downloaded and locally edited file back to the web site, you will need to provide an upload form for the user to do it manually. (Which is a shame and completely unintuitive, but that's the way technology is at the moment.)
A: Not possible due to security reason in web technology.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619686",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
} |
Q: button should fire the action until I keep the button down I have UIscrollview in which I have placed images.I use the buttons(touch down) to move the position of the images by 5pixels inside the scroll view…..Button fires the action only if I repeatedly touches the buttons ( it moves the images to 5pixels if I touches the button again and again) I want my button to fire the action until I keep the button down (it should moves the images until I release the button)…
Is there any possibility to scroll the UIscrollview by means of button click?
A: You'll have to listen to the TouchDown and TouchUp events. When a TouchDown event is fired you start a timer (or other) that periodically calls a method, and when you receive a TouchUp event you stop it.
It might looks something like that:
-(IBAction)touchDownAction:(id)sender
{
self.yourtimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(aselector) userInfo:nil repeats:YES];
}
-(IBAction)touchUpAction:(id)sender
{
if ([yourtimer isValid])
{
[yourtimer invalidate];
}
}
(You just have to link your button with these methods via IB)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619690",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Creating strings in D without allocating memory? Is there any typesafe way to create a string in D, using information only available at runtime, without allocating memory?
A simple example of what I might want to do:
void renderText(string text) { ... }
void renderScore(int score)
{
char[16] text;
int n = sprintf(text.ptr, "Score: %d", score);
renderText(text[0..n]); // ERROR
}
Using this, you'd get an error because the slice of text is not immutable, and is therefore not a string (i.e. immutable(char)[])
I can only think of three ways around this:
*
*Cast the slice to a string. It works, but is ugly.
*Allocate a new string using the slice. This works, but I'd rather not have to allocate memory.
*Change renderText to take a const(char)[]. This works here, but (a) it's ugly, and (b) many functions in Phobos require string, so if I want to use those in the same manner then this doesn't work.
None of these are particularly nice. Am I missing something? How does everyone else get around this problem?
A: You have static array of char. You want to pass it to a function that takes immutable(char)[]. The only way to do that without any allocation is to cast. Think about it. What you want is one type to act like it's another. That's what casting does. You could choose to use assumeUnique to do it, since that does exactly the cast that you're looking for, but whether that really gains you anything is debatable. Its main purpose is to document that what you're doing by the cast is to make the value being cast be treated as immutable and that there are no other references to it. Looking at your example, that's essentially true, since it's the last thing in the function, but whether you want to do that in general is up to you. Given that it's a static array which risks memory problems if you screw up and you pass it to a function that allows a reference to it to leak, I'm not sure that assumeUnique is the best choice. But again, it's up to you.
Regardless, if you're doing a cast (be it explicitly or with assumeUnique), you need to be certain that the function that you're passing it to is not going to leak references to the data that you're passing to it. If it does, then you're asking for trouble.
The other solution, of course, is to change the function so that it takes const(char)[], but that still runs the risk of leaking references to the data that you're passing in. So, you still need to be certain of what the function is actually going to do. If it's pure, doesn't return const(char)[] (or anything that could contain a const(char)[]), and there's no way that it could leak through any of the function's other arguments, then you're safe, but if any of those aren't true, then you're going to have to be careful. So, ultimately, I believe that all that using const(char)[] instead of casting to string really buys you is that you don't have to cast. That's still better, since it avoids the risk of screwing up the cast (and it's just better in general to avoid casting when you can), but you still have all of the same things to worry about with regards to escaping references.
Of course, that also requires that you be able to change the function to have the signature that you want. If you can't do that, then you're going to have to cast. I believe that at this point, most of Phobos' string-based functions have been changed so that they're templated on the string type. So, this should be less of a problem now with Phobos than it used to be. Some functions (in particular, those in std.file), still need to be templatized, but ultimately, functions in Phobos that require string specifically should be fairly rare and will have a good reason for requiring it.
Ultimately however, the problem is that you're trying to treat a static array as if it were a dynamic array, and while D definitely lets you do that, you're taking a definite risk in doing so, and you need to be certain that the functions that you're using don't leak any references to the local data that you're passing to them.
A: Check out assumeUnique from std.exception Jonathan's answer.
A: No, you cannot create a string without allocation. Did you mean access? To avoid allocation, you have to either use slice or pointer to access a previously created string. Not sure about cast though, it may or may not allocate new memory space for the new string.
A: One way to get around this would be to copy the mutable chars into a new immutable version then slice that:
void renderScore(int score)
{
char[16] text;
int n = sprintf(text.ptr, "Score: %d", score);
immutable(char)[16] itext = text;
renderText(itext[0..n]);
}
However:
*
*DMD currently doesn't allow this due to a bug.
*You're creating an unnecessary copy (better than a GC allocation, but still not great).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619691",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: How to make my home page very fast? It works and I want to make it super fast. The index page is very static, doesn't really change for days unless date updates or a map updates. So it should be possible to optimize to very fast since it doesn't change much. I recently migrated to HRD and my URI is montaoproject.appspot.com I rewrote this so that it is only python and django / html (no data layer trip.) Memcache? Other options? Reduce javascript? I first made sure that data layer isn't touched:
def get(self):
logo = ''
if get_host().find('.br') > 0:
cookie_django_language = 'pt-br'
logo = 'montao'
elif get_host().find('allt') > 0 and not self.request.get('hl'):
logo = ''
cookie_django_language = 'sv'
elif get_host().find('gralumo') > 0 \
and not self.request.get('hl'):
cookie_django_language = 'es_AR' # learn
else:
logo = ''
cookie_django_language = self.request.get('hl', '') # edit
if cookie_django_language:
if cookie_django_language == 'unset':
del self.request.COOKIES['django_language']
else:
self.request.COOKIES['django_language'] = \
cookie_django_language
translation.activate(cookie_django_language)
loginmsg = ''
user = users.get_current_user()
twittername = None
client = OAuthClient('twitter', self)
if client.get_cookie():
info = client.get('/account/verify_credentials')
twittername = info['screen_name']
# seconds_valid = 8600
# self.response.headers['Cache-Control'] = "public, max-age=%d" % seconds_valid
if logo == 'montao':
self.render(
u'montao',
host=get_host(),
twittername=twittername,
continue_url=get_host(),
loginmsg=loginmsg,
form_url=blobstore.create_upload_url('/fileupload'),
user_url=(api.users.create_logout_url(self.request.uri) if api.users.get_current_user() else api.users.create_login_url(self.request.uri)),
admin=users.is_current_user_admin(),
user=(users.get_current_user() if users.get_current_user() else ''
),
logo=logo,
)
else:
self.render(
u'home',
host=get_host(),
twittername=twittername,
continue_url=get_host(),
loginmsg=loginmsg,
form_url=blobstore.create_upload_url('/fileupload'),
latest=Ad.all().filter('published =',
True).order('-modified').get(),
user_url=(api.users.create_logout_url(self.request.uri) if api.users.get_current_user() else api.users.create_login_url(self.request.uri)),
admin=users.is_current_user_admin(),
guser=(users.get_current_user() if users.get_current_user() else ''
),
logo=logo,
)
A: I don't know python, but if it doesn't change for days I am sure you could write something to convert the above into HTML (say every hour), and then just serve the HTML version. That will give you one of the largest optimisations possible, since your home page then doesn't have to be processed by a script engine at all.
A: Normally, I'd recommend inverting the page, putting index.html out as a static-file, as well as css and js files, then making an AJAX request to the server to fill in dynamic bits. Static files load really fast.
You might still be able to pull that off, by using client-side JavaScript to figure out which logo and such to use, but getting the file upload form rendered is going to be slower, since the create_upload_url needs to happen server side.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619695",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Broadcast Receiver for ACTION_USER_PRESENT,ACTION_SCREEN_ON,ACTION_BOOT_COMPLETED I am creating a class which uses broadcast receiver. I want to receive the broadcast on unlocking of the phone. But there is some issue. Please help me out.
My Manifest.xml is :-
<receiver android:name=".MyReciever">
<intent-filter>
<intent-filter>
<action android:name="android.intent.action.ACTION_USER_PRESENT" />
<action android:name="android.intent.action.ACTION_BOOT_COMPLETED" />
<action android:name="android.intent.action.ACTION_SCREEN_ON" />
</intent-filter>
</intent-filter>
</receiver>
and my Broadcast reciever class :-
public class MyReiever extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("My Reciever","is intent null => " + (intent == null));
Log.d("My Reciever",intent.getAction()+"");
}
}
Though other application and services are receiving broadcast for "Screen_on" and "USer_Present" eg. WifiService.
A: Although the Java constants are android.content.intent.ACTION_USER_PRESENT, android.content.intent.ACTION_BOOT_COMPLETED, and android.content.intent.ACTION_SCREEN_ON, the values of those constants are android.intent.action.USER_PRESENT, android.intent.action.BOOT_COMPLETED, and android.intent.action.SCREEN_ON. It is those values which need to appear in your manifest.
Note, however, that a receiver for ACTION_SCREEN_ON can not be declared in a manifest but must be registered by Java code, see for example this question.
A: Since implicit broadcast receivers are not working as of Android 8.0, you must register your receiver by code and also in the manifest.
Do these steps:
*
*Add manifest tag
<receiver android:name=".MyReciever">
<intent-filter>
<intent-filter>
<action android:name="android.intent.action.ACTION_USER_PRESENT" />
<action android:name="android.intent.action.ACTION_BOOT_COMPLETED" />
<action android:name="android.intent.action.ACTION_SCREEN_ON" />
</intent-filter>
</intent-filter>
</receiver>
*
*Create a receiver class and add your codes
public class MyReciever extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("My Reciever","is intent null => " + (intent == null));
Log.d("My Reciever",intent.getAction()+"");
}
}
*
*Create a service and register the receiver in it
public class MyService extends Service {
MyReceiver receiver = new MyReceiver();
@Override
public IBinder onBind(Intent intent) { return null; }
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
registerReceiver(receiver);
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}
}
*
*Don't forget to define the service in manifest
<service android:name=".MyService"/>
To make your broadcast work, you have to register it in service. And to keep your service alive you can use tools like alarm managers, jobs, etc which is not related to this question.
A: Check your Class name, that is extending BroadcastReceiver. It should be "MyReciever" not "MyReiever"
A: Beside Typo that mentioned in earlier answers and the fact that the receiver class package name should be completely mentioned in receiver tag, I think the problem is that the code in question uses two nested intent filters. I believe this code will work correctly:
<receiver android:name=".MyReciever">
<intent-filter>
<action android:name="android.intent.action.ACTION_USER_PRESENT" />
<action android:name="android.intent.action.ACTION_BOOT_COMPLETED" />
<action android:name="android.intent.action.ACTION_SCREEN_ON" />
</intent-filter>
</receiver>
A: I can only give you a quick tip as i have gone through that path you are following with much less success. Try to read logcat using java.util.logging so that you will not require permission to read logs. And in log view create listener for the one containing "system disable" as its header. it fires up both at lock and unlock. check for the one that gives access to system.android not the other screen.
Hope it helps. Best of luck
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619696",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: 10 fold cross validation In k fold we have this:
you divide the data into k subsets of
(approximately) equal size. You train the net k times, each time leaving
out one of the subsets from training, but using only the omitted subset to
compute whatever error criterion interests you. If k equals the sample
size, this is called "leave-one-out" cross-validation. "Leave-v-out" is a
more elaborate and expensive version of cross-validation that involves
leaving out all possible subsets of v cases.
what the Term training and testing mean?I can't understand.
would you please tell me some references where I can learn this algorithm with an example?
Train classifier on folds: 2 3 4 5 6 7 8 9 10; Test against fold: 1
Train classifier on folds: 1 3 4 5 6 7 8 9 10; Test against fold: 2
Train classifier on folds: 1 2 4 5 6 7 8 9 10; Test against fold: 3
Train classifier on folds: 1 2 3 5 6 7 8 9 10; Test against fold: 4
Train classifier on folds: 1 2 3 4 6 7 8 9 10; Test against fold: 5
Train classifier on folds: 1 2 3 4 5 7 8 9 10; Test against fold: 6
Train classifier on folds: 1 2 3 4 5 6 8 9 10; Test against fold: 7
Train classifier on folds: 1 2 3 4 5 6 7 9 10; Test against fold: 8
Train classifier on folds: 1 2 3 4 5 6 7 8 10; Test against fold: 9
Train classifier on folds: 1 2 3 4 5 6 7 8 9; Test against fold: 10
A: In short:
Training is the process of providing feedback to the algorithm in order to adjust the predictive power of the classifier(s) it produces.
Testing is the process of determining the realistic accuracy of the classifier(s) which were produced by the algorithm. During testing, the classifier(s) are given never-before-seen instances of data to do a final confirmation that the classifier's accuracy is not drastically different from that during training.
However, you're missing a key step in the middle: the validation (which is what you're referring to in the 10-fold/k-fold cross validation).
Validation is (usually) performed after each training step and it is performed in order to help determine if the classifier is being overfitted. The validation step does not provide any feedback to the algorithm in order to adjust the classifier, but it helps determine if overfitting is occurring and it signals when the training should be terminated.
Think about the process in the following manner:
1. Train on the training data set.
2. Validate on the validation data set.
if(change in validation accuracy > 0)
3. repeat step 1 and 2
else
3. stop training
4. Test on the testing data set.
A: In k-fold method, you have to divide the data into k segments, k-1 of them are used for training, while one is left out and used for testing. It is done k times, first time, the first segment is used for testing, and remaining are used for training, then the second segment is used for testing, and remaining are used for training, and so on. It is clear from your example of 10 fold, so it should be simple, read again.
Now about what training is and what testing is:
Training in classification is the part where a classification model is created, using some algorithm, popular algorithms for creating training models are ID3, C4.5 etc.
Testing means to evaluate the classification model by running the model over the test data, and then creating a confusion matrix and then calculating the accuracy and error rate of the model.
In K-fold method, k models are created (as clear from the description above) and the most accurate model for classification is the selected.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Why does edit text and the spinner UI's corner get destorted? I make an XML layout and when I run it on big screen emulator or mobile, its UI is looking good, but when I check it on a small screen the edit text corner gets distorted and the user interface is not looking good. Why?
Is this a density problem or some other? My XML is listed below. Check it on "qvga" target 4.
<?xml version="1.0" encoding="utf-8"?>
</RelativeLayout>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
</ScrollView>
</LinearLayout>
A: I got the same problem. I solved it by changing the skin built in to HVGA... The procedure is as follows.
In Eclipse SDK, go to Window --> Android SDK and AVD Manager --> Virtual devices. Select your Android Virtual Device and click on Edit. Change the Skin Built-in to HVGA and Click on Edit AVD.
If you are already using HVGA, go for a higher version. I changed it from QVGA to HVGA. I hope this is an alternative to solve the problem on the emulator.
A: If you want that your UI should be adjusted according to the mobile device screen, you can assign a weightSum to the layout and layout_weight to widgets and it will display properly in all the screens.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619703",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Is there a way to make PhpStorm's autocomplete "go deeper"? In PhpStorm, if I create an object, then I have all auto complete on that object working fine:
$object = new MyClass();
$object->getNa...
Will auto complete to
$object->getName();
So far so good, but if I get returned an object through the first method, then the auto complete will not work on that.
$car->getDriver()->getNam...
Will show an empty list.
The getDriver method has its PHPDoc @return tag set to 'Driver' though and in some other IDEs, this therefore works to get the correct auto complete.
Wondering if there's a setting that I missed somewhere or if PhpStorm doesn't offer this kind of advanced auto complete yet?
A: The function getDriver() needs appropriate type-hints for the return value (function's docblock):
* @return classOrInterfaceName
This is normally enough to have a IDE "go deeper". I'm pretty sure Phpstorm supports that, but I'm not a Phpstorm user.
Take care the file with the interface/class is within the project or referenced to it.
As a work around you can assign the return value to a variable and type-hint that variable. Might not be that comfortable but can help.
A: Please ensure that only one definition of class Driver exists across all your project files. This is crucial for current versions of PhpStorm
see http://youtrack.jetbrains.net/issue/WI-2202 and http://youtrack.jetbrains.net/issue/WI-2760
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619709",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Apache mod_proxy_balancer dynamically stop forwarding requests to time-outing member Apache mod_proxy_balancer
I'm trying to gonfigure apache mod_proxy_balancer to act as HTTP VIP and represent 2 IIS servers behind it.
This how the VIP configured:
<Proxy balancer://appcluster>
BalancerMember http://IP-IIS1:80 route=iis1 max=160 timeout=60
BalancerMember http://IP-IIS2:80 route=iis2 max=160 timeout=60
ProxySet stickysession=SERVERID
Order Allow,Deny
Allow from all
Deny from XXX.XXX.XXX.XXX
Deny from XXX.XXX.XXX.XXX
</Proxy>
Sometimes I have scheduled task that executed on one of the IIS servers. It could be any one of them. Since I can't bind it to one of the servers it can start on any IIS, and here comes the problem:
When the task been executed it causes to one of the servers to be very slow on incoming requests serving so it takes it very long time to serve the requests that forwarded to it by the Apache, more that the timeout configured in Apache 60 sec.
Is there any way to make mod_proxy_balancer to recognize such condition and stop forwarding the requests to the slow server, e.g dynamicaly take it out from the balancing pool?
A:
This module requires the service of mod_status. Balancer manager
enables dynamic update of balancer members. You can use balancer
manager to change the balance factor or a particular member, or put it
in the off line mode.
Thus, in order to get the ability of load balancer management,
mod_status and mod_proxy_balancer have to be present in the server.
To enable load balancer management for browsers from the example.com
domain add this code to your httpd.conf configuration file
SetHandler balancer-manager
Order Deny,Allow Deny from all Allow from .example.com
You can now access load balancer manager by using a Web browser to
access the page http://your.server.name/balancer-manager
-> http://ceviri.belgeler.gen.tr/apache/htdocs/2.2/mod/mod_proxy_balancer.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619710",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Codeigniter - multiple database connections I have a problem with multiple db connections at Codeigniter. At my database.php i configured two databases.
$active_group = 'cms';
$active_record = FALSE;
$db['cms']['hostname'] = 'localhost';
$db['cms']['username'] = 'yoloo_cms';
$db['cms']['password'] = 'password';
$db['cms']['database'] = 'yoloo_cms';
$db['cms']['dbdriver'] = 'mysql';
$db['cms']['dbprefix'] = '';
$db['cms']['pconnect'] = TRUE;
$db['cms']['db_debug'] = TRUE;
$db['cms']['cache_on'] = FALSE;
$db['cms']['cachedir'] = '';
$db['cms']['char_set'] = 'utf8';
$db['cms']['dbcollat'] = 'utf8_general_ci';
$db['cms']['swap_pre'] = '';
$db['cms']['autoinit'] = TRUE;
$db['cms']['stricton'] = FALSE;
$db['hazeleger']['hostname'] = 'localhost';
$db['hazeleger']['username'] = 'yoloo_websites';
$db['hazeleger']['password'] = 'password2';
$db['hazeleger']['database'] = 'yoloo_hazeleger';
$db['hazeleger']['dbdriver'] = 'mysql';
$db['hazeleger']['dbprefix'] = '';
$db['hazeleger']['pconnect'] = TRUE;
$db['hazeleger']['db_debug'] = TRUE;
$db['hazeleger']['cache_on'] = FALSE;
$db['hazeleger']['cachedir'] = '';
$db['hazeleger']['char_set'] = 'utf8';
$db['hazeleger']['dbcollat'] = 'utf8_general_ci';
$db['hazeleger']['swap_pre'] = '';
$db['hazeleger']['autoinit'] = TRUE;
$db['hazeleger']['stricton'] = FALSE;
At my model i use this when i want to connect to a other db than the usual one:
function __construct()
{
parent::__construct();
$this->load->database('hazeleger',TRUE);
}
But at all time codeigniter connects to cms. When i remove
$active_group = 'cms';
$active_record = FALSE;
Codeingiter gives an error. When i tried this
function __construct()
{
parent::__construct();
$db2 = $this->load->database('hazeleger',TRUE);
}
function test()
{
$query = "SELECT * FROM cms_modules";
$result = $db2->db->query($query);
return $db2->result();
}
It gives an error. Variabele db2 does not exist.
I just want to choose, at every model, wich db i want to connect to.
But is doesn,t work. Does somebody know, how i can work with different databases
at models.
Thank you very much!!
A: You have to save the variable $db2 as a class field. The you can access $this->db2 ...
A: This happens because you have most probably set in /application/config/autoload.php
that the database library is automatically loaded/created.
Open autoload.php and look for this line:
$autoload['libraries'] = array('database');
Remove 'database' from the array and save. Now it should be working in your controllers as intended.
A: for future visitors' reference, the load would be along these lines:
$this->db2 = $this->load->database('hazeleger',true);
A: You have to change db2 class
$query = "SELECT * FROM cms_modules";
$result = $this->db2->query($query);
return result();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619711",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Pause download in Java? I'm using this code to download a file, and I was wondering if its possible to pause the download and then resume it later, and if so how?:
URL url = new URL(URL);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
lenghtOfFile /= 100;
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(Path + FileName);
byte data[] = new byte[1024];
long total = 0;
int count = 0;
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
total += count;
}
output.flush();
output.close();
input.close();
A: This is only possible if the server supports HTTP range headers (introduced in HTTP 1.1)
See this question for examples in Java: how to use the HTTP range header in J2ME?.
"Pausing" could just mean reading some of the stream and writing it to disk. When resuming you would have to use the headers to specify what is left to download.
A: I think the support for the resume is at the server side, the clients cannot direct it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619717",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Sharepoint silverlight webpart - Problems I need to show a silverlight webpart in sharepoint 2010.
This is my code, to show silverlight control
protected override void CreateChildControls()
{
Silverlight sl = new Silverlight();
sl.ID = "CustomWebPart1SL";
sl.Source = "/Silverlight/CustomWebPart.xap";
this.Controls.Add(sl);
}
In Silverlight I just hotcoded the data so the chart is rendering correctly in Sharepoint page.
The problem is I couldn't access Sharepoint list from silverlight application.
How to access the list and property-bag from silverlight application. Or how can I pass those datas as DataTable to silverlight from WebPart code.
And silverlight not supporting DataTable object. What is the reason.
A: For SilverLight I should suggest using of Client Object Model for SharePoint. For good starting point you should visit: this
A: Silverlight applicatons run on the client machine, Sharepoint on the a server.
The only way a Silverlight application can access Sharepoint lists is by Client Object Model (if you are running on Sharepoint 2010) or consuming Sharepoint web services (on Sharepoint 2007 or previous).
There are many out-of-the-box services in the /_vti_bin/ folder useful for reading and writing anything.
Alternatively you can save an xml file containing your data in a document library and read it from the Silverlight application.
But this means that you have to update the xml content everytime the source list is updated (with event receivers or using a scheduled job).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619723",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: BIRT 3.7 runtime. Customizing of PDF fonts and jdbc drivers are not possible anymore? I'm trying to upgrade BIRT to the latest runtime 3.7.
Looks like that it's impossible to customize PDF fonts! In previous versions it were done in org.eclipse.birt.report.engine.fonts*/fontsConfig*.xml files.
In 3.7 fontsConfig*.xml files are embedded in BIRT runtime jar file(in my case it's org.eclipse.birt.runtime_3.7.1.v20110913-1734.jar). The jar file is signed, think it's necessary for OSGI. So if you change anything in jar, JRE throw checksum error on loading the file. If you remove the signing info, OSGI will not load it (NPE).
Any ideas how could I customize my pdf fonts without rebuilding BIRT runtime?
By the way, I suspect that the same issue presents for jdbc drivers. Above mentioned jar file contains drivers folder. Suspect that it's a stub for jdbc drivers from plugin org.eclipse.birt.report.data.oda.jdbc*.
Several years ago I asked a question regarding adding PDF fonts from BIRT runtime. It's still unanswered BIRT: pdf emitter, load/use fonts from relative path or from jar files
UPDATE:
*
*regarding pdf fonts, found open bug unresolved in 3.7.1 - https://bugs.eclipse.org/bugs/show_bug.cgi?id=347431
*According to http://wiki.eclipse.org/Birt_3.7_Migration_Guide#JDBC_Drivers, jdbc drivres must be in classpath
A: It's not the cleanest way to go, but it's possible to edit them inside the jar file. You can remove the signature by deleting META-INF/ECLIPSEF.SF and removing everything from META-INF/MANIFEST.MF that goes after it's main section (filenames and digests...alternatively, remove just sections of the config files). It's not required to have the jar signed (I suppose it depends on security manager's settings, but under default settings it runs fine).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619727",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Too many programs spawned with Expect I am using expect module for performing a task.
This is sample of my code
foreach temp $list {
spawn -X $temp
while {1} {
expect {
eof {break}
"password {send "password\r"}
"\]" {send "exit\r"}
}
}
}
The script is getting break after 1071 counter. with the error
too many programs spawned? could not create pipe: too many file open
while executing
"spawn ssh -X ..."
A: There's a relatively low limit on the number of simultaneous programs that can be spawned at once (it depends on how many virtual terminals your system supports; I'm actually surprised that you got to over 1000 there…) so you need reap those old programs once you're done with them (Expect does reap everything on exit, but here it matters because you're running out much sooner than that). What's more, the limit will depend on what else is going on on your system, as virtual terminals are actually a system-global resource…
To reap the old program once you're done with it, add wait to the end of your loop (assuming you don't want the subprocess to continue past the end of the loop, of course) to get this:
foreach temp $list {
spawn -X $temp
while {1} {
expect {
eof {break}
"password" {send "password\r"}
"\]" {send "exit\r"}
}
}
wait ;#### <<<<<----- THIS!!!
}
You might also want to take a look at exp_continue, as that lets you rewrite to get rid of the explicit while (and also the need to explicitly handle the EOF condition) and overall make your code simpler:
foreach temp $list {
spawn -X $temp
expect {
"password" {send "password\r"; exp_continue}
"\]" {send "exit\r" ; exp_continue}
}
wait
}
A: Sounds like a similar problem I am having.
Have you tried ulimit -a and checked either processes or files?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619731",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Modify each char of a c string I've been wracking my brain for awhile, I've gotten it all done in Google Go easily. But now I need to get something written in C to do this too.
Take a simple string and modify the code of each char in the string, then make a new string from the now encrypted string. All I want to do is make it so I can easily edit each char code. Is it possible that someone can give me a quick example?
For instance:
"Hello World"->encrypter->"hlkj34%^%$"
I don't want anyone to do the work for me, but if possible just show me how I can edit the char code of each.
A: char *change_each_char(char const *str)
{
char *copy = strdup(str);
if (copy != NULL)
for (size_t i=0; copy[i]; i++)
copy[i] = SOME_OPERATION_ON(copy[i]);
return copy;
}
Since strdup is not in the ISO C standard, here's its definition for non-POSIX platforms:
char *strdup(char const *str)
{
char *copy = malloc(strlen(str) + 1);
if (copy) strcpy(copy, str);
return copy;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619732",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to append/prepend/create a text node with jQuery
Possible Duplicate:
Escaping text with jQuery append?
My HTML is somewhat like this:
<div id="selector">Hello World</div>
Now I'd like to append some text to this div. I know that I could simply use
$('#selector').append(text);
but this wouldn't escape any special characters in text. Another way is to wrap the text in a span:
$('#selector').append( $('<span>').text(text) );
But this is ugly, because it creates unnecessary markup. So my current solution is to manually create a TextNode:
$('#selector').append( document.createTextNode(text) );
I was wondering whether there is any jQuery-style way to do this?
A: The createTextNode approach is probably the best way to go. If you want to have a jQuery-ish syntax, you could make a plugin.
$.fn.appendText = function(text) {
return this.each(function() {
var textNode = document.createTextNode(text);
$(this).append(textNode);
});
};
A: $.text() accepts also a function as parameter. This function will receive an index and the current text. The return value of the function will be set as the new text.
.text( function )
function
Type: Function( Integer index, String text ) => String
A function returning the text content to set. Receives the index position of the element in the set and the old text value as arguments.
$("li").text(function(idx, txt) {
return txt + " <item>";
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
A: You can use;
$.extend({
urlEncode: function(value) {
var encodedValue = encodeURIComponent(value);
encodedValue = encodedValue.replace("+", "%2B");
encodedValue = encodedValue.replace("/", "%2F");
return encodedValue;
},
urlDecode: function(value) {
var decodedValue = decodeURIComponent(value);
decodedValue = decodedValue.replace("%2B", "+");
decodedValue = decodedValue.replace("%2F", "/");
return decodedValue;
}
});
to escape HTML characters before you append to the DOM.
Use it like; $.urlEncode(value)
Using it; $('#selector').append($.urlEncode(text));
Update #1
You could this $('#selector').html($('#selector').html() + text);
I suspected this was what you wanted.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619739",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "33"
} |
Q: MySQL statements -- Pattern Matching etc
display all rows where the hiredate is before april 1, 1981 and the
employee name is from A to S
This is the code that I have done and it doesn't work. :( When I tried to put AND between '%A' and '%S' it doesn't work either. :( When I deleted the '%S' it worked but it will only retrieve the record with a name starting with letter A. :(
Can you guys help? I really don't know what to do. :(
SELECT *
FROM tblEmployee
WHERE HIREDATE < '1981-04-1'
AND ENAME LIKE '%A' '%S'
Thanks. ^^
A: You were close. I guess you want names starting from A, B, C, ... S (not ending in A-S). Right?
If yes, try this:
SELECT *
FROM tblEmployee
WHERE HIREDATE < '1981-04-01' --- notice the -01
AND ENAME >= 'A'
AND ENAME < 'T'
A: Use
SELECT * FROM tblEmployee WHERE HIREDATE < '1981-04-01' AND SUBSTR ( ENAME, 1, 1 ) BETWEEN 'A' AND 'S'
A: TRY
SELECT * FROM tblEmployee WHERE HIREDATE < '1981-04-1' AND ENAME REGEXP '^[a-s]+$'
REFERENCE
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619740",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there any way to configure php to always set $_SERVER['CONTENT_LENGTH']? I'm working on carddav client. As server i use davical v. 0.9.9.6. I don't understand why i'm getting invalid content-type error when http headers contains correct value. I look into source code and found this condition:
if ( isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['CONTENT_LENGTH'] > 7) {...
After little research I found php set $_SERVER['CONTENT_LENGTH'] only with POST method and uploading file. Is there any way to configure php to always set $_SERVER['CONTENT_LENGTH']?
I'm asking generally, not only for this case...
//EDIT
I'm doing HTTP PUT request to davical server (using php curl).
PUT /caldav.php/testuser/contacts/newc.vcf HTTP/1.1
Host: davical
Content-Type: text/vcard;
BEGIN:VCARD
VERSION:3.0
FN:ME
...
On davical side is condition testing CONTENT_LENGTH which is not set. So it's a davical bug?
//EDIT 2
Finally I figure it out!
PUT request with calback readfunc requires set INFILE_SIZE via curl_setopt(...)
There is none auto value and put Content-Length field manualy into header is also wrong.
Example (incorrect):
// PUT REQUEST
curl_setopt($ch,CURLOPT_HTTPHEADER,"Content-Length: $length"); //mistake
curl_setopt($ch,CURLOPT_PUT,true);
curl_setopt($ch,CURLOPT_READFUNCTION,array($this,'readfunc'));
....
--------------------------------------------------------------
// WIRESHARK TCP STREAM DUMP
PUT /caldav.php/testuser/contacts/novy.vcf HTTP/1.1
Authorization: Basic xxxxxxxxxxxxxxx
Host: davical
Accept: */*
Content-Type: text/vcard
Content-Length: xxx
Expect: 100-continue
HTTP/1.1 100 Continue
155
BEGIN:VCARD
VERSION:3.0
...
END:VCARD
0
HTTP/1.1 200 OK
----------------------------------------------------------------
// On server side
isset($_SERVER['CONTENT_LENGTH'])==false
Second (correct) example
// PUT REQUEST
curl_setopt($ch,CURLOPT_INFILESIZE,$length);
curl_setopt($ch,CURLOPT_PUT,true);
curl_setopt($ch,CURLOPT_READFUNCTION,array($this,'readfunc'));
....
--------------------------------------------------------------
// WIRESHARK TCP STREAM DUMP
PUT /caldav.php/testuser/contacts/novy.vcf HTTP/1.1
Authorization: Basic xxxxxxxxxxxxxxx
Host: davical
Accept: */*
Content-Type: text/vcard
Content-Length: xxx
Expect: 100-continue
HTTP/1.1 100 Continue
BEGIN:VCARD
VERSION:3.0
...
END:VCARD
HTTP/1.1 200 OK
----------------------------------------------------------------
// On server side
isset($_SERVER['CONTENT_LENGTH'])==true
A: Although i have never used CONTENT_LENGHT i can tell you why this is probably happening:
In a request, you don't have to set the Content-Lenght header... IT IS NOT MANDATORY. Except for specific situations. If your POSTed content is of type "multipart/form-data" it becomes necessary to use content-lenght for each part because each part is seperated by a boundary and each part will have its own headers...
For example:
Content-Type: MultiPart/Form-Data
Boundary: @FGJ4823024562DGGRT3455
MyData=1&Username=Blabla&Password=Blue
@FGJ4823024562DGGRT3455==
Content-Type: image/jpef:base64
Content-Lenght: 256
HNSIFRTGNOHVDFNSIAH$5346twSADVni56hntgsIGHFNR$Iasdf==
So here this is a crude example of what a multi part request works, you see that the second part has a content-lenght. This is why sometimes the content-lenght is set and sometimes not, because you need to read X bytes before finding another boundary and extract the correct data.
It doesn't mean your server will never send it in in other cases, but my 2 cents are this is the case right now. Its because you are not in POST, but in some other modes.
A: Only requests that have a request body have a content length request header (or at least only then it makes sense) and so therefore the $_SERVER variable is set.
If you need it to be always set (which I think is bogus), you can do this yourself on the very beginning of your script:
isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['CONTENT_LENGTH'] = 0;
Assuming that if it is not set, it's of zero length. See as well Improved handling of HTTP requests in PHP.
A: You could probably set them by yourself. Why do you need that this values are set? And what should they set to?
Maybe you're missing information on $_SERVER['CONTENT_TYPE'] or
$_SERVER['CONTENT_LENGTH'] as I did. On POST-requests these are
available in addition to those listed above.
-> http://www.php.net/manual/en/reserved.variables.server.php#86495
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619742",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Very Odd situation with CrystalReport and/or Visual studio 2010 I don't know maybe .Net Framework I faced a very odd problem It seems very funny looks like some stuffs having a fun with me.
I'm using Crystal-Report Version 13.0.2000.0 and Visual Studio 2010. Number of days ago I got a error related with my Crystal-Report, that was :
Could not load file or assembly 'file:///C:\Program Files (x86)\SAP BusinessObjects\Crystal Reports for .NET Framework 4.0\Common\SAP BusinessObjects Enterprise XI 4.0\win32_x86\dotnet1\crdb_adoplus.dll' or one of its dependencies. The system cannot find the file specified.
After googling I found solution, Then I added the following code to app.config file and It worked well, I had no error, no exception.
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime Version="v4.0" sku=".NETFramework, Version=v4.0" />
</startup>
Today when I wanted to use same solution in my other project it showed the message that I should download .NetFrwamework 4.0 and It causes project to not run. I thought I missed something in configuration so I went to look exactly what configurations I did in previous project. Interesting point is here when I opened the project it shows me same message to download .NetFramework 4.0, while It worked very well number of days ago and I don't have any problem with that. But now .... .
I don't know what is the problem.
Any advice will be helpful.
A: After spent many hours, I solved my problem, I don't have any idea how ?!! but It doesn't throw any exception anymore.
Things I've done :
*
*I delete app.config.
*I changed framework to 3.5 then compile it.
*Delete all related files with project in AppData/Local/Temp/ folder (Windows 7).
*I changed it back to 4.0 (It generated app.config) then compile it, It automatically added following code:
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime Version="v4.0" sku=".NETFramework, Version=v4.0" />
</startup>
I ran my application without any error and exception. I don't know what was the problem but by doing these steps I fixed my issues.
A: Just one thing, maybe useful for someone: for use Crystal Reports in VS 2010, you have to use Framewok 4.0 (not Framewok 4.0 Client Profile)
A: You can create a folder called "dotnet1" in C:\Program Files (x86)\SAP BusinessObjects\Crystal Reports for .NET Framework 4.0\Common\SAP BusinessObjects Enterprise XI 4.0\win32_x86 and copy the dll crdb_adoplus.dll in it. this solution worked for me.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619745",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Assigning variable in shell script #!/bin/sh
SUCCESS=0
java -jar sbc.jar &
while [ true ];
do
echo "sleeping"
sleep 5
echo "again"
tail -1 ~/NetBeansProjects/xyz/dist/newlog.log | grep -q "[INFO ] - Stream closed"
if [ $? = 1 ]
then
echo " entered if "
java -jar sbc.jar &
else
echo " did not if "
fi
done
I want to use a better variable than $? to store the result of the previous line because I may need it more than once. The script is intended to check the last line of the file newlog.log for a particualr string and then start sbc.jar again because the string confirms that the program has stopped.
A: Store it in another variable:
...
tail -1 ~/NetBeansProjects/xyz/dist/newlog.log | grep -q "[INFO ] - Stream closed"
RES=$?
if [ $RES = 1 ]
...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619748",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I check if the 'destructive' button was pressed (UIActionSheet - iPhone)? I'm trying to work out the line of code I need to use in order to determine if the 'destructive' button has been press in a UIActionSheet.
I've had a look around and found the delegate method...
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
.. and I've also managed to find [myActionSheet destructiveButtonIndex], I'm just not sure how to put the two together. This is what I have tried so far with no success:
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == destructiveButtonIndex)
{
// Do something...
}
}
A: You were very close with your code. The implementation you're looking for is:
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == actionSheet.destructiveButtonIndex)
{
// Do something...
}
}
A: You have to check like below
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0)
{
// Do something...
}
else if (buttonIndex == 1)
{
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619755",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Mapping class to a table without a table name I have many tables in my DB with exactly the same structure: same columns names and types.
The only difference between these tables is the their names (which I can only know in runtime).
I would like to create a mapping of a class to a table but giving the name of the table only during runtime (no static @Table annotation).
Is it possible?
Is there any other way to achieve my goal?
A: Directly - no. Because this is not a regular use-case. Normally you should not have dynamcally-generated tables. It is a valid use when you move some records to an archive table (or tables), but otherwise avoid it.
Anyway, you can make that work: make a native query, and map the result to your non-entity object. You will be able to select from any table and transform the result to an object. However, you can't insert or update that way.
A: Don't think associating or changing the table mapped to an entity dynamically is possible.
You can check @MappedSuperClass, which will allow you to define all fields in a class once and inherit them, so that there is no repetition and entities are empty class with mappings.
http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/#d0e1168
If you know the table name dynamically you can always instantiate the mapped class accordingly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619759",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Display literal text in HTML I need to display some literal text in my HTML page (it's automatically generated by an application. I wrote in C#.)
<TR>
<TD VALIGN="center" ALIGN="center"><B>398</B></TD>
<TD VALIGN="center">Name: <B>' an image.jpg</B></TD>
<TD><IMG SRC="Images/' an image.jpg"ALT=' an image.jpg></TD>
</TR>
The " ' " character causes the problem, because it's a HTML escape character. (There are also other escape characters used in file names.) I can't change the file names. So how can I display the literal text in my HTML page?
A: EDIT: in case of Windows Forms, you can use:
System.Web.HttpUtility.HtmlEncode(yourString);
It is necessary to add a reference to System.Web.dll in your project. Remember that in HTML the attributes should be enclosed with the quote char " and not with apex, '.
You can simply use the
HttpServerUtility.HtmlEncode
method; moreover, the ' is not the problem, maybe it can be the quote, ", or < and > characters.
The following example encodes a string for transmission by HTTP. It encodes the string named TestString, which contains the text "This is a <Test String>.", and copies it into the string named EncodedString as "This is a <Test String>.".
C#:
String TestString = "This is a <Test String>.";
String EncodedString = Server.HtmlEncode(TestString);
A: Use
'
instead.
Here is reference to HTML Entities and Codings (http://www.zytrax.com/tech/web/entities.html)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619764",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Cross-activity background music / detecting if an app is active or not I am building an android game which consists of several activities. While the app is running some background music is playing. The background music consists of several loops which are played one after another.
So my problem is how to detect when to stop the background music. The music should stop if the user exits the app, turns off the screen or switches to another app and it should be turned back on when the user returns to my game.
My current approach is to notify a SoundManager class which keeps track on the active activity. Every time a new activity starts (onResume) and every time an activity is ended (onStop) the SoundManager increases an internal counter. If the counter is 0 the sound is stopped and if the counter is > 0 the sound is started (if it is not already playing).
Additionally the SoundManager listenes for ACTION_SCREEN_OFF / ACTION_SCREEN_ON events to turn the sound off/on depending on the screen state.
This approach works quite well except for one case: If I turn off the screen sometimes (I'd say with a 50% chance) the sound starts again because apparently onResume is invoked on the activity which was active before the screen was turned off. I wonder why that happens.
So my questions are:
- Is there is a less fragile approach to know when to stop the background sound?
- or is there is a workaround for the screen on/off issue.
Thanks for your help!
A: I've encountered such problem when I tried to show rating dialog on the 20th activization of application. Unfortunately, Android hasn't iOS-like "applicationDidEnterBackground", so I've tried this way.
I extended Application class and added methods onResume() and onPause() (for application)
In every activity I've overrided method onKeyDown() and when KeyEvent was "Home", I've called method onPause() of custom application class. In method onPostResume of every activity I've checked, was application visible (by flag) or not, if yes, I've called method onResume() of custom application class.
As I can see, your method is better. But maybe it will help you or give any clue.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619767",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Copy part of file in C++ I'm currently busy with a project in which I have to copy a part from a file to another file, so I made a code for that using fread and fwrite. But I came across a problem: for testing purposes I made a code which should copy a whole file, but somehow the code creates copies that are larger than the original file. See the code I made below
FILE *base_file;
FILE *new_file;
fpos_t curpos;
int tmp;
// Open the base file
fopen_s(&base_file, "C:/base.dat", "rb");
// Open the file which should contain the copy
fopen_s(&new_file, "C:/new.dat", "w");
// Get the filesize
fseek(base_file, 0, SEEK_END);
fgetpos(base_file, &curpos);
fseek(base_file, 0, SEEK_SET);
//Read and copy (it seems to go wrong here)
for(int i = 0; i < curpos; i++){
fread (&tmp, 1, 1, base_file);
fwrite(&tmp, 1, 1, new_file);
}
fclose(base_file);
fclose(new_file);
The base file is 525 kb, and the newfile is 527kb. As far as I could see the parts where this problem occurs is after parts where there are 7 nullbytes, and the copy somehow has added a '0D'(in Hex) after these parts. In ascii the '0D' character is a 'carriage return'. I was wondering what could be the reason that my copy code adds carriage returns into the file? As far as I know this script should just work as I just read the basefile, and directly copy it to the newfile, and the basefile doesn't contain these carriage returns.
A: You're opening the destination file in text mode, instead of binary mode, so the newline translation happens behind your back. Change the mode to "wb".
Other notes:
*
*Use streams rather than stdio.
*Don't write byte-for-byte. Use a larger buffer, your method will take forever for larger files.
A: Will "wb" instead of "w" fix it?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619770",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Creating an ASP.NET User Control With a Javascript API I'm basically trying to figure out a good/clean way to organize controls that would have a public API like this:
<script>
function buttonClicked() {
var myUserControl = SomehowGetReferenceToThisUserControl("UserControl");
myUserControl.AjaxReload();
}
</script>
<a href="javascript:buttonClicked()">Refresh the User Control!</a>
<myControls:MyUserControl ID="UserControl" runat="server" />
I've seen some 3rd party controls that our team uses such as Telerik and DevExpress that have similar functionality, but I have no idea how it is implemented. Can anyone provide some insight on a good/clean way to accomplish this?
A: It is recommended to create / initialize data unique in the WebUserControl’s content (to avoid issues with the use multiple instances of this WebUserControl):
Register the startup script to create the javascript programmatic object (see the validating asp.net textBox using Javascript thread) to instantiate WebUserControl reference (like DevExpress recommends in the www.devexpress.com/kb=K18373 KB).
A: I had same problem and fortunately I'd found interesting blog post - Dynamically create ASP.NET user control using ASP.NET Ajax and Web Service.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619773",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to create a Notification cancel dialog? I have a notification which tells the user that its downloading a file with its progress..
I want to make a dialog with some textviews displaying some info and 2 buttons which are Close and Stop (stops the download).
How can I do this?
A: you can use the AlertDialog Class
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
alertbox.setMessage("Downloading");
alertbox.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
..... //cancel code
}
});
alertbox.setNegativeButton("Pause", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
.... //pause code
}
});
// display box
alertbox.show();
A: you can use a custom dialog where your text views are defined in xml and you can use your xml to set as view in your custom dialog box.
you can code like this:-
@Override
protected Dialog onCreateDialog(int id) {
LayoutInflater factory = null;
factory = LayoutInflater.from(this);
dialogView = factory.inflate(R.layout.yourXml, null);
return new AlertDialog.Builder(yourActivity.this)
.setTitle(R.string.rate_title)
.setView(dialogView)
.setPositiveButton("Stop", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Add your stop code here
}
})
.setNegativeButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// dismiss dialog here
}
})
.create();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619774",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How Static methods are mocked in any Mocking Framework like JMockit,PowerMocks? I learnt that we can mock static methods using core java library with PowerMock?Jmockit.Want to understand how it is doing it internally in brief?
My Understanding:- As we define the mock class in the test case itself(Though there are different ways to create mock class in every framework like using expectation syntax in Jmockit), these framework must be defining custom classloader thru which they must be looking for that class definition inside the testcase itself.Its a Guess. Not sure if it is correct? But even if i am right, preference of classloader hirerchy is boootstraploader then applicationclassloader than customerclassloader. So how does it pick from customerclassloader instead of applicationclassloader ?
A: JMockit and other newer frameworks are based on the Java 1.5 Instrumentation framework. This allows you to redefine private, static and final methods. Even no-arg constructors can be redefined.
These frameworks use Java agent which is a pluggable library that runs embedded in a JVM and intercepts the classloading process and can help to instrument the bytecode of the classes.
You can check Java instrumentation in deep and http://jmockit.googlecode.com/svn/trunk/www/about.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619778",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: codeigniter mysql query to multidimensional array(nested list) Ok here is what I am struggling with.
I have drop down menu on my site which is basically a nested list. It gets its information from my database. Now I have made this work as a procedural piece of code but I am now trying to separate it out for a MVC framework. Now my thinking is that if I use the model to get the information from the table pass that on to the controller as an multidimensional array and the pass it out to the view where I will then access the array to fill out the list. I need (or think I do) do it this way so that when I create another view for mobile devices I can reformat it to suit.
Down to the nitty gritty.
*table 'sch_cat'*
sch_cat_uid (primery{parent id}),
sch_cat_id,
sch_cat_order,
sch_cat_name.
table sch_subcat
sch_subcat_uid,
sch_subcat_order,
sch_subcat_name,
sch_subcat_href.
sch_subcat_parent (reference 'shc_cat_uid' from table 'sch_cat' )
The main focus here is putting the information to the array but I really don'y know where to begin here so any and pointers appreciated oh and if I am well of base don't feel shy in calling me a plumb!.
Cheers
Troy
A: Have you looked into using CodeIgniters Active Record class?
As for querying data from a database with the class, you can easily make it come back the way you're looking for, I believe the particular function you're looking for is result_array().
Regarding the MVC practice, it's sufficient to have the querying of these items be in a model, that the controller grabs and passes to the proper view.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619779",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: Many to many query with filter I have following issue. There are two tables - groups and students and third pivot table group_student.
Query to get students from specific groups (id:1,8) is clear...
SELECT DISTINCT s.*
FROM students AS s
Inner Join group_student AS gs ON gs.student_id = s.id
Inner Join groups AS g ON g.id = gs.group_id
WHERE g.id IN ("1","8")
It works. But, how to query, if I want to select just segment of students of group id 1. For example s.name = "john". So the result should be: all students from group id 8 + all students with name "john" from group id 1.
Thanx for posts :-)
A: Try this:
SELECT DISTINCT s.*
FROM students AS s
Inner Join group_student AS gs ON gs.student_id = s.id
Inner Join groups AS g ON g.id = gs.group_id
WHERE g.id ="8" or (g.id="1" and s.name = "john")
A: you can use UNION too
SELECT DISTINCT s.*
FROM students AS s
Inner Join group_student AS gs ON gs.student_id = s.id
Inner Join groups AS g ON g.id = gs.group_id
WHERE g.id = 8
UNION
SELECT DISTINCT s.*
FROM students AS s
Inner Join group_student AS gs ON gs.student_id = s.id
Inner Join groups AS g ON g.id = gs.group_id
WHERE gp.id="1" and s.name = "john"
A: One more option, avoiding DISTINCT and the (probably unneeded) join to groups:
SELECT s.*
FROM students AS s
WHERE EXISTS
( SELECT *
FROM group_student AS gs
WHERE gs.student_id = s.id
AND ( gs.group_id = 8
OR (gs.group_id, s.name) = (1, 'john')
)
)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619780",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Wrapping C library I have a private.h, public.h and the file.c, and I need to wrap it into Cython.
How do I wrap the function Person_ptr Person_create(const char* name);?
private.h:
#ifndef __PERSON_PRIVATE_H__
#define __PERSON_PRIVATE_H__
#include "Person.h"
typedef struct Person_TAG {
char* name;
int age;
} Person;
void person_init(Person_ptr self, const char* name);
# endif /* __PERSON_PRIVATE_H__ */
public.h
#ifndef __PERSON_H__
#define __PERSON_H__
#include <assert.h>
typedef struct Person_TAG* Person_ptr;
#define PERSON(x) \
((Person_ptr) (x))
#define PERSON_CHECK_INSTANCE(x) \
assert(PERSON(x) != PERSON(NULL))
/* public interface */
Person_ptr Person_create(const char* name);
void Person_destroy(Person_ptr self);
const char* Person_get_name(const Person_ptr self);
int Person_get_age(const Person_ptr self);
void Person_birthday(Person_ptr self);
# endif /* __PERSON_H__ */
And this is file.c:
#include "Person.h"
#include "Person_private.h"
#include <stdlib.h>
#include <string.h>
#include <assert.h>
Person_ptr Person_create(const char* name)
{
Person_ptr self = PERSON(malloc(sizeof(Person)));
PERSON_CHECK_INSTANCE(self);
person_init(self, name);
return self;
}
void Person_destroy(Person_ptr self)
{
PERSON_CHECK_INSTANCE(self);
if (NULL != self->name) free(self->name);
}
/* Do not free not change the returned string! */
const char* Person_get_name(const Person_ptr self)
{
PERSON_CHECK_INSTANCE(self);
return self->name;
}
int Person_get_age(const Person_ptr self)
{
PERSON_CHECK_INSTANCE(self);
return self->age;
}
void Person_birthday(Person_ptr self)
{
PERSON_CHECK_INSTANCE(self);
++self->age;
}
/* private/protected methods */
void person_init(Person_ptr self, const char* name)
{
self->name = malloc(sizeof(char) * (strlen(name) + 1));
assert(NULL != self->name);
strcpy(self->name, name);
self->age = 0;
}
What I have tried to do is file.pyx:
from ctypes import *
cdef extern from "Person.h":
ctypedef struct Person_ptr:
pass
Person_ptr Person_create "P_create" (char *name)
cdef class Person:
cdef Person P_create(p_name):
return Person_create(p_name)
It's not right - it compiles in Cython but then it gives me a lot of errors in GCC.
How can I fix this problem?
A: cperson.pxd:
cdef extern from "Person.h":
cdef struct Person_TAG:
pass
ctypedef Person_TAG* Person_ptr
Person_ptr Person_create(char* name)
void Person_destroy(Person_ptr self)
char* Person_get_name(Person_ptr self)
person.pyx:
from cperson cimport Person_ptr, Person_create, Person_destroy, Person_get_name
cdef class Person:
cdef Person_ptr thisptr
def __cinit__(self, char* name):
self.thisptr = Person_create(name)
if self.thisptr is NULL:
raise MemoryError
def __dealloc__(self):
if self.thisptr is not NULL:
Person_destroy(self.thisptr)
property name:
def __get__(self):
return Person_get_name(self.thisptr)
person.pyxbld:
import os
from distutils.extension import Extension
dirname = os.path.dirname(__file__)
def make_ext(modname, pyxfilename):
return Extension(name=modname,
sources=[pyxfilename, "Person.c"],
include_dirs=[dirname],
# or libraries=["person"], if you compile Person.c separately
)
test_person.py:
import pyximport; pyximport.install()
from person import Person
p = Person('Garry')
print p.name
Example
$ python test_person.py
Garry
A: In general, it doesn't make sense to do this kind of thing by hand, unless you have some very special requirements. Instead, use SWIG to generate the wrappers for you. You don't need to struggle to get these details right, and as a bonus when the C code changes, it's trivial to regenerate new wrappers to match.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619785",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Can I import a class into ClassWizard in VS2010 Is there a way in VS2010 to import a class from a .h and .cpp file into ClassWizard such that I can use ClassWizard to manipulate it (e.g. add variables etc...) Quite a number of the files that I brought into the project when I moved over from VS2008 do not seem to be available to ClassWizard. Back in VS6, I could do this by manually editing the CLW file, but this is no longer available. See related question
I'm guessing the file that stores this information is MyProjectName.sdf, which is listed as a SQL Server Compact Edition Database File by explorer, but I'm not sure if there are any tools available that would let me edit it.
A: Figured a workaround. My hunch was that VS2010 was reading the //{{AFX_DATA(CMyClass) comments when existing files are added into a project, so I did the following;
*
*Edit the files to include a set of AFX... comments copied from
another class
*Replace the class name with the correct class
*Remove the .h and .cpp files from the project
*Add the .h files and .cpp files back to the project
*The class is now available to ClassWizard.
A bit too much work to be of much benefit on anything other than regularly used classes, might just put together a routine to do this en-masse, i.e. search for project files with classes based on known MFC classes, search for absence of AFX comments and add them if not present, say ten hail marys and fire up ClassWizard.
Also posted on MSDN here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Play music in the background using AVAudioplayer I want to play music even if the app goes in background. I checked all stackoverflow links but none of them worked. Please help need to do it today.
I had used following code:-
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"Day At The Beach" ofType: @"mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
NSError *error;
playerTemp = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error];
playerTemp.numberOfLoops = 0;
AudioSessionSetActive(true);
[playerTemp play];
A: I had solved this question by referring iOS Application Background tasks
and make some changes in .plist file of our application..
Update
write this code in your controller's view did load method like this
- (void)viewDidLoad
{
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"in-the-storm" ofType:@"mp3"]];
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[audioPlayer play];
[super viewDidLoad];
}
A: You need to set 'audio' as one of your UIBackgroundModes in Info.plist. Apple has documentation on the issue.
A: Write this line in to plist for background run...
<key>UIBackgroundModes</key>
<array>
<string>audio</string>
</array>
Write this code Where you want to use
AVAudioPlayer* audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:self.urlForConevW error:&error];
audioPlayer.delegate = self;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
audioPlayer.numberOfLoops = 1;
[audioPlayer play];
A: I just wanted to add a note to Mehul's answer. This line:
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
is actually very important. I used other tutorials to get my AVAudioPlayer up and running. Everything worked fine except my audio would not START if the app was in the background. To clarify, my audio was fine if it was already playing when the app went into the background...but it would not start if the app was already in the background.
Adding the above line of code made it so my audio would start even if the app was in the background.
A: You can use MPMoviePlayerController even to play solo-audio movies. If you like it, read this detailed Apple Library Technical Q&A:
iOS Developer Library Technical Q&A QA1668
A: Also important here if you are using MPMusicPlayerController:
You must use:
[MPMusicPlayerController iPodMusicPlayer]
And Not
[MPMusicPlayerController applicationMusicPlayer]
Also if you don't want your app to stop music which was playing when your app is started, look here:
AVAudioPlayer turns off iPod - how to work around?
A: Step1
Make the following changes in info.plist
*
*Application does not run in background : NO
*Required background modes
item0 :App plays audio or streams audio/video using AirPlay
Step 2
Don't forget to add the following things in MainViewController.h file
*
*#import <'AVFoundation/AVAudioPlayer.h>
*@interface MainViewController:<'AVAudioPlayerDelegate>
*AVAudioPlayer *H_audio_player;
Step 3
Add the following code inside the play action of your MainViewController class.
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%d-%d",C_CID, C_SID] ofType:@"mp3"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
H_audio_player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
H_audio_player.delegate = self;
H_audio_player.numberOfLoops = -1;
A: If even after setting audio as one of your UIBackgroundModes in the plist the audio stops when going to background, try setting your application's audio session to media playback.
Here's the related reference:
https://developer.apple.com/library/ios/documentation/Audio/Conceptual/AudioSessionProgrammingGuide/Introduction/Introduction.html
Here's about what the code's gonna look like:
NSError *activationError = nil;
[[AVAudioSession sharedInstance] setActive: YES error: &activationError];
NSError*setCategoryError = nil;
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: &setCategoryError];
A: I use the below code. It work for me, and call on the button click of audio player instance method.
NSError *error; NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"music" ofType:@"mp3"]];
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&error];
[[AVAudioSession sharedInstance] setActive:YES error: &error];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self.player prepareToPlay];
A: From all answers is missing this code to control the player when user is waking the device:
- (BOOL)canBecomeFirstResponder {
return YES;
}
- (void)remoteControlReceivedWithEvent:(UIEvent *)event {
switch (event.subtype) {
case UIEventSubtypeRemoteControlPlay:
[_audioPlayer play];
break;
case UIEventSubtypeRemoteControlPause:
[_audioPlayer pause];
break;
default:
break;
}
}
And you have all these options:
UIEventSubtypeRemoteControlPlay = 100,
UIEventSubtypeRemoteControlPause = 101,
UIEventSubtypeRemoteControlStop = 102,
UIEventSubtypeRemoteControlTogglePlayPause = 103,
UIEventSubtypeRemoteControlNextTrack = 104,
UIEventSubtypeRemoteControlPreviousTrack = 105,
UIEventSubtypeRemoteControlBeginSeekingBackward = 106,
UIEventSubtypeRemoteControlEndSeekingBackward = 107,
UIEventSubtypeRemoteControlBeginSeekingForward = 108,
UIEventSubtypeRemoteControlEndSeekingForward = 109,
A: To play your audio in background
Step 1 :Just add in your info.plistmake an array
step2 :
- (void)applicationDidEnterBackground:(UIApplication *)application
{
__block UIBackgroundTaskIdentifier task = 0;
task=[application beginBackgroundTaskWithExpirationHandler:^{
NSLog(@"Expiration handler called %f",[application backgroundTimeRemaining]);
[application endBackgroundTask:task];
task=UIBackgroundTaskInvalid;
}];
}
step3 :
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"iNamokar" ofType:@"mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:soundFilePath];
AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[player prepareToPlay];
[self.player play];
A: From Apple's sample code: Audio Mixer (MixerHost)
// If using a nonmixable audio session category, as this app does, you must activate reception of
// remote-control events to allow reactivation of the audio session when running in the background.
// Also, to receive remote-control events, the app must be eligible to become the first responder.
- (void) viewDidAppear: (BOOL) animated {
[super viewDidAppear: animated];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
}
I think remote control events are not needed for the following case:
AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryMixWithOthers,
sizeof(value), &value);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619794",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "40"
} |
Q: Nunit test config file being overwritten I have an Nunit test assembly called Tests. The associated configuration file is called Tests.dll.config. In VS2008 I have the Test.dll.config set "copy always". The problem is when I build the solution the Tests.dll.config file in the Debug or Release directory contains only this:
<?xml version="1.0"?>
<configuration>
<startup><supportedRuntime version="v2.0.50727"/></startup></configuration>
The Tests.dll.config that has my settings in is not copied across.
A: This seemed to fix it. I added the following post-build event.
copy /Y “$(ProjectDir)Tests.dll.config” “$(TargetDir)$(TargetFileName).config”
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619797",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Cast char* to std::vector Is there a fast (CPU) way to cast a char array into a std::vector<char>?
My function looks like this:
void someFunction(char* data, int size)
{
// Now here I need to make the std::vector<char>
// using the data and size.
}
A: The general rule with STL containers is that they make copies of their contents. With C++11, there are special ways of moving elements into a container (for example, the emplace_back() member function of std::vector), but in your example, the elements are char objects, so you are still going to copy each of the size char objects.
Think of a std::vector as a wrapper of a pointer to an array together with the length of the array. The closest equivalent of "casting a char * to a std::vector<char>" is to swap out the vector's pointer and length with a given pointer and length however the length is specified (two possibilities are a pointer to one past the end element or a size_t value). There is no standard member function of std::vector that you can use to swap its internal data with a given pointer and length.
This is for good reason, though. std::vector implements ownership semantics for every element that it contains. Its underlying array is allocated with some allocator (the second template parameter), which is std::allocator by default. If you were allowed to swap out the internal members, then you would need to ensure that the same set of heap allocation routines were used. Also, your STL implementation would need to fix the method of storing "length" of the vector rather than leaving this detail unspecified. In the world of OOP, specifying more details than necessary is generally frowned upon because it can lead to higher coupling.
But, assume that such a member function exists for your STL implementation. In your example, you simply do not know how data was allocated, so you could inadvertently give a std::vector a pointer to heap memory that was not allocated with the expected allocator. For example, data could have been allocated with malloc whereas the vector could be freeing the memory with delete. Using mismatched allocation and deallocation routines leads to Undefined Behavior. You might require that someFunction() only accept data allocated with a particular allocation routine, but this is specifying more details than necessary again.
Hopefully I have made my case that a std::vector member function that swaps out the internal data members is not a good idea. If you really need a std::vector<char> from data and size, you should construct one with:
std::vector<char> vec(data, data + size);
A: You can't "cast" anything here, but you can easily construct a vector from the C string:
std::vector<char> v(data, data + size);
This will create a copy though.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619806",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Can I scale a View in Android? Can I take a view that has been rendered by the Android framework and rescale it to some other size?
A: You need API 11 or above to scale a view. Here is how:
float scalingFactor = 0.5f; // scale down to half the size
view.setScaleX(scalingFactor);
view.setScaleY(scalingFactor);
A: For scale, I resize the width and height of the view to make it affect the area and position another view.
If you don't want it affect the area and position, use answer of @Gadzair and @Taiti
private void resize(View view, float scaleX, float scaleY) {
ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
layoutParams.width = (int) (view.getWidth() * scaleX);
layoutParams.height = (int) (view.getHeight() * scaleY);
view.setLayoutParams(layoutParams);
}
Example using
resize(view, 0.5f, 0.8f);
Result
Demo
A: In your XML
android:scaleX="0.5"
android:scaleY="0.5"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619807",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "30"
} |
Q: Android set Image Bitmap issue I'm working on a project which communicate with web server and download some photos. I want these photos to be shown on a listview after the download,but it's throwing me a NullPointerException. Here is the code I'm using :
private ArrayList <HashMap<String, Object>> items;
private static final String NAMEKEY = "bookname";
private static final String INFOKEY = "bookprice";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mystampii_layout);
}
});
ListView listView = (ListView)findViewById(R.id.mystampii_listview);
items = new ArrayList<HashMap<String,Object>>();
HashMap<String, Object> hm;
final Bitmap b = BitmapFactory.decodeFile("/sdcard/MediaCard2a44bb1f782925923195ee546e7ef395.jpg", null);
ImageView brum = (ImageView) findViewById(R.id.main_img);
brum.setImageBitmap(b);
hm = new HashMap<String, Object>();
hm.put(NAMEKEY, "Moto GP 2010");
hm.put(INFOKEY, "98 Stampii");
items.add(hm);
// Define SimpleAdapter and Map the values with Row view R.layout.listbox
SimpleAdapter adapter = new SimpleAdapter(this, items, R.layout.main_listview,
new String[]{NAMEKEY,INFOKEY}, new int[]{R.id.main_img,R.id.main_name, R.id.main_info});
listView.setAdapter(adapter);
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
I know, why I'm getting NullPointerException : because my ImageView brum is placed in R.layout.main_listview and I'm setting as Content on this activity R.layout.mystampii_layout. I really can get the idea how to set the Image from SDCard to a ImageView from another layout.
Any suggestions how can I do that, or how can I show the downloaded image from SDCard in listview.
Thanks really for any kind of help!!!
A: Try simple code ::
ImageView image = (ImageView) findViewById(R.id.test_image);
FileInputStream in;
BufferedInputStream buf;
try {
in = new FileInputStream("/sdcard/test2.png");
buf = new BufferedInputStream(in);
Bitmap bMap = BitmapFactory.decodeStream(buf);
image.setImageBitmap(bMap);
if (in != null) {
in.close();
}
if (buf != null) {
buf.close();
}
} catch (Exception e) {
Log.e("Error reading file", e.toString());
}
A: Best way to achieve what you need, is to implement you custom adapter and in Adapter.getView() inflate R.layout.main_listview
A: Create your custom Adapter like this :
import java.util.ArrayList;
import com.stampii.stampii.R;
import com.stampii.stampii.comm.rpc.CollectionRPCPacket;
import com.stampii.stampii.comm.rpc.UserDatabaseHelper;
import android.app.Activity;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class MyArrayAdapter extends ArrayAdapter<String> {
private final Activity context;
private final String[] names;
CollectionRPCPacket rpcPacket;
Cursor cursor;
String title;
public MyArrayAdapter(Activity context, String[] names) {
super(context, R.layout.main_listview, names);
this.context = context;
this.names = names;
}
// static to save the reference to the outer class and to avoid access to
// any members of the containing class
static class ViewHolder {
public ImageView imageView;
public TextView textView,textView2;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// ViewHolder will buffer the assess to the individual fields of the row
// layout
ViewHolder holder;
// Recycle existing view if passed as parameter
// This will save memory and time on Android
// This only works if the base layout for all classes are the same
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = context.getLayoutInflater();
rowView = inflater.inflate(R.layout.main_listview, null, true);
holder = new ViewHolder();
holder.textView = (TextView) rowView.findViewById(R.id.main_name);
holder.textView2 = (TextView) rowView.findViewById(R.id.main_info);
holder.imageView = (ImageView) rowView.findViewById(R.id.main_img);
rowView.setTag(holder);
} else {
holder = (ViewHolder) rowView.getTag();
}
final Bitmap b = BitmapFactory.decodeFile("/sdcard/MediaCard2a44bb1f782925923195ee546e7ef395.jpg", null);
holder.textView.setText();
holder.textView2.setText("");
holder.imageView.setImageBitmap(b);
return rowView;
}
}
And you can use it like this on your activity :
ListView lv1 = (ListView)findViewById(R.id.listViewOne);
String[] names = new String[] { "ONE", "TWO", "THREE"};
lv1.setAdapter(new MyArrayAdapter(this, names));
Hope it helps!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619810",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: catch error and return in method result I have my own wcf service class which should as result return string with "Everything Save Saccesfully" if ok save data. Otherwise I need to return in this string exception.
string SaveData(Stream stream)
{
string error = "";
try
{
//do saving data
error+="Everything Save Saccefully";
return error;
}
catch(Exception ex)
{
throw ex;
}
finally
{
}
}
It is possible to catch errors occurs in try block and return it in error variable ?
A: Well, the traditional way that you express the error is simply via an exception - not a return value. Lack of exception should imply "everything went correctly". That's the normal idiomatic way of working.
Now, occasionally it's worth having a method which doesn't throw an exception, but instead returns a success status and potentially a separate result via an out parameter. But that's relatively rare - it's usually for things like parsing, where it's entirely normal for it to fail in hard-to-predict ways when nothing's really wrong other than the input data.
In your case, it looks like this should be a void method which simply throws an exception on error.
A: Try this :
string SaveData(Stream stream)
{
string error;
try
{
//do saving data
error ="Everything saved Successfully";
}
catch(Exception ex)
{
error = ex.Message;
}
return error;
}
A: Normally I would do as suggested by Jon, but if you really don't want to allow any exceptions to bubble up from your service you could encapsulate your success and (any) failure error information in a class structure like this
public class ErrorInfo
{
public string Message {get; set;}
// TODO: Maybe add in other information about the error?
}
public class SaveResult
{
public bool Success { get; set; }
/// <summary>
/// Set to contain error information if Success = false
/// </summary>
public ErrorInfo ErrorInfo { get; set; }
}
And then...
public SaveResult SaveData(Stream stream)
{
SaveResult saveResult = new SaveResult();
string error = "";
try
{
//do saving data
saveResult.Success = true;
}
catch (Exception ex)
{
saveResult.ErrorInfo = new ErrorInfo { Message = ex.Message };
}
}
The downside of this approach is that your caller must check the Success value after calling SaveData. Failure to do so can result in a bug in your code that will only manifest itself if the save fails.
Alternatively, if you don't handle the exception you get to benefit from one of the useful things about structured exception handling: If the caller forgets to explicitly handle any exception then it will bubble up the call stack and either crash the app or get caught by some higher-level error handling code.
Not necessarily ideal, but generally better than your code silently assuming that something succeeded, when in fact it didn't.
A: You should use Faults for exceptional results in WCF. I do not see idea why you would need exception in string. But if you absolutely need this, just move return statement to the end and set its value in catch block too.
string SaveData(Stream stream)
{
string error = "";
try
{
//do saving data
error+="Everything Save Saccefully";
}
catch(Exception ex)
{
//throw ex; Do not throw, just return its string representation
error+=ex.ToString();
}
finally
{
}
return error;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619831",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Override li style with class in my site I created this html/css
li
{
float: left;
...
}
.myclass
{
float: right;
...
}
<ul>
<li>test 1</li>
<li class="myclass">test 2</li>
</ul>
The two list elements have the same style but the second doesn't use the class to override the left float. Why?
EDIT:
it seems that if I use
li.myclass
{
float: right;
...
}
it works but I'm using myclass also in divs because it's a common style class. How can I fix the problem without use li.?
A: As your post says, you're able to overwrite the float-property if you use a more "specific" selector, such as li.myclass. So you could list the two selectors in a comma-seperated list.
.myclass, li.myclass {
float: right;
}
Or you can use !important to overwrite the property.
.myclass {
float: right !important;
}
Also, it plays a role at which position in your CSS the property shows up. Properties that are located lower in the file can overwrite properties which are above.
A: Coming from your comment, I think you should use a table, as it seems pretty much like becoming one. Tables are not evil as long as they aren't getting used to to design-work.
Or if you really want to avoid tables, just do two lists and align the 's with float.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619834",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: libmms linking error i have downoaded the wunder radio project, i have copy the MMS project in my workspace.
if i try to use mms_connect Xcode4 give me this error:
Ld
/Users/Alex/Library/Developer/Xcode/DerivedData/test1-gevnovbiecnctxguaabsznvdybxa/Build/Products/Debug-iphonesimulator/test1.app/test1
normal i386
cd /Users/Alex/Source/test1
setenv MACOSX_DEPLOYMENT_TARGET 10.6
setenv PATH
"/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/llvm-gcc-4.2
-arch i386 -isysroot
/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.3.sdk
-L/Users/Alex/Library/Developer/Xcode/DerivedData/test1-gevnovbiecnctxguaabsznvdybxa/Build/Products/Debug-iphonesimulator
-F/Users/Alex/Library/Developer/Xcode/DerivedData/test1-gevnovbiecnctxguaabsznvdybxa/Build/Products/Debug-iphonesimulator
-filelist
/Users/Alex/Library/Developer/Xcode/DerivedData/test1-gevnovbiecnctxguaabsznvdybxa/Build/Intermediates/test1.build/Debug-iphonesimulator/test1.build/Objects-normal/i386/test1.LinkFileList
-mmacosx-version-min=10.6 -Xlinker -objc_abi_version -Xlinker 2 -lz.1
-framework UIKit -framework Foundation -framework CoreGraphics -o
/Users/Alex/Library/Developer/Xcode/DerivedData/test1-gevnovbiecnctxguaabsznvdybxa/Build/Products/Debug-iphonesimulator/test1.app/test1
Undefined symbols for architecture i386: "_mms_connect", referenced
from:
-[test1AppDelegate application:didFinishLaunchingWithOptions:]
in test1AppDelegate.o ld: symbol(s) not found for architecture i386
collect2: ld returned 1 exit status
have any idea to resolve it?
A: It looks like the linker is failing to link to libmms because it is of the wrong architecture. The project you are building appears to be for the iPhone simulator. Since the simulator runs on your computer it's architecture is i386 (or perhaps x86_64 depending upon the machine you are using). So basically you are compiling using i386 but when the linker tried to link to libmms it did not find that libmms had been compiled using the same architecture.
Since iOS devices use armv6 or armv7 architectures and the simulator uses i386, it can be quite difficult to switch back and forth between building for the actual device or building for the simulator since any external static libraries need to be built for all 3 architectures.
You'll likely need to rebuild libmms using the i386 architecture.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619838",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to sort/filter observable collection and get back observable collection not IEnumerable Can any one please guide me which is best way to sort/filter observable collection and get back observable collection not IEnumerable ?
A: Probably for the sort you can convert it to a List and then call Sort(), providing a comparison delegate. Something like:-
my_collection.ToList().Sort((left, right) => left == right ? 0 : (left > right ? -1 : 1));
A: If the result of sorting/filtering is IEnumerable<T> then you can just create another ObservableCollection and pass result as a parameter to constructor
See this question
A: You may have a look at my ObservableView implementation which wraps an observable collection (or other list) and provides "live" ordering and filtering:
https://mytoolkit.codeplex.com/wikipage?title=ObservableView
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Extracting keywords from GOLD-Parser CGT-File i have defined a grammar with many rules, that uses many keywords. imagine it like this (just with more of these rules and more keywords):
<keyword> ::= 'public' | 'protected' | 'private'
the gold-parser-system is generating a compiled grammar table (CGT) file, which is used by the several engines, in my case the calitha-engine for c#.
in order to realize some syntax-highlighting for my sourcecode which i want to parse, i want to get all the keywords of a range of rules. how do i extract them?
A: Apart from generating "cgt" output file, Gold Builder has also XML output capability.
If you feel comfortable with XML processing, I suggest you to extract the keywords using XML as one possible solution (See documentation).
Here is a sample grammar XML file :
<?GOLDParserTables version="1.0"?>
<Tables>
<Parameters>
<Parameter Name="Name" Value="(Untitled)"/>
<Parameter Name="Author" Value="(Unknown)"/>
<Parameter Name="Version" Value="(Not Specified)"/>
<Parameter Name="About" Value=""/>
<Parameter Name="Case Sensitive" Value="True"/>
<Parameter Name="Start Symbol" Value="8"/>
</Parameters>
<SymbolTable Count="12">
<Symbol Index="0" Name="EOF" Kind="3"/>
<Symbol Index="1" Name="Error" Kind="7"/>
<Symbol Index="2" Name="Whitespace" Kind="2"/>
<Symbol Index="3" Name="Comment End" Kind="5"/>
<Symbol Index="4" Name="Comment Line" Kind="6"/>
<Symbol Index="5" Name="Comment Start" Kind="4"/>
<Symbol Index="6" Name="Number" Kind="1"/>
<Symbol Index="7" Name="Word" Kind="1"/>
<Symbol Index="8" Name="Main" Kind="0"/>
<Symbol Index="9" Name="Number" Kind="0"/>
<Symbol Index="10" Name="Value" Kind="0"/>
<Symbol Index="11" Name="Word" Kind="0"/>
</SymbolTable>
<RuleTable Count="6">
<Rule Index="0" NonTerminalIndex="9" SymbolCount="1">
<RuleSymbol SymbolIndex="6"/>
</Rule>
<Rule Index="1" NonTerminalIndex="11" SymbolCount="1">
<RuleSymbol SymbolIndex="7"/>
</Rule>
<Rule Index="2" NonTerminalIndex="8" SymbolCount="2">
<RuleSymbol SymbolIndex="10"/>
<RuleSymbol SymbolIndex="8"/>
</Rule>
<Rule Index="3" NonTerminalIndex="8" SymbolCount="1">
<RuleSymbol SymbolIndex="10"/>
</Rule>
<Rule Index="4" NonTerminalIndex="10" SymbolCount="1">
<RuleSymbol SymbolIndex="11"/>
</Rule>
<Rule Index="5" NonTerminalIndex="10" SymbolCount="1">
<RuleSymbol SymbolIndex="9"/>
</Rule>
</RuleTable>
<CharSetTable Count="6">
<CharSet Index="0" Count="7">
<Char UnicodeIndex="9"/>
<Char UnicodeIndex="10"/>
<Char UnicodeIndex="11"/>
<Char UnicodeIndex="12"/>
<Char UnicodeIndex="13"/>
<Char UnicodeIndex="32"/>
<Char UnicodeIndex="160"/>
</CharSet>
<CharSet Index="1" Count="1">
<Char UnicodeIndex="42"/>
</CharSet>
<CharSet Index="2" Count="1">
<Char UnicodeIndex="59"/>
</CharSet>
<CharSet Index="3" Count="1">
<Char UnicodeIndex="47"/>
</CharSet>
<CharSet Index="4" Count="10">
<Char UnicodeIndex="48"/>
<Char UnicodeIndex="49"/>
<Char UnicodeIndex="50"/>
<Char UnicodeIndex="51"/>
<Char UnicodeIndex="52"/>
<Char UnicodeIndex="53"/>
<Char UnicodeIndex="54"/>
<Char UnicodeIndex="55"/>
<Char UnicodeIndex="56"/>
<Char UnicodeIndex="57"/>
</CharSet>
<CharSet Index="5" Count="52">
<Char UnicodeIndex="65"/>
<Char UnicodeIndex="66"/>
<Char UnicodeIndex="67"/>
<Char UnicodeIndex="68"/>
<Char UnicodeIndex="69"/>
<Char UnicodeIndex="70"/>
<Char UnicodeIndex="71"/>
<Char UnicodeIndex="72"/>
<Char UnicodeIndex="73"/>
<Char UnicodeIndex="74"/>
<Char UnicodeIndex="75"/>
<Char UnicodeIndex="76"/>
<Char UnicodeIndex="77"/>
<Char UnicodeIndex="78"/>
<Char UnicodeIndex="79"/>
<Char UnicodeIndex="80"/>
<Char UnicodeIndex="81"/>
<Char UnicodeIndex="82"/>
<Char UnicodeIndex="83"/>
<Char UnicodeIndex="84"/>
<Char UnicodeIndex="85"/>
<Char UnicodeIndex="86"/>
<Char UnicodeIndex="87"/>
<Char UnicodeIndex="88"/>
<Char UnicodeIndex="89"/>
<Char UnicodeIndex="90"/>
<Char UnicodeIndex="97"/>
<Char UnicodeIndex="98"/>
<Char UnicodeIndex="99"/>
<Char UnicodeIndex="100"/>
<Char UnicodeIndex="101"/>
<Char UnicodeIndex="102"/>
<Char UnicodeIndex="103"/>
<Char UnicodeIndex="104"/>
<Char UnicodeIndex="105"/>
<Char UnicodeIndex="106"/>
<Char UnicodeIndex="107"/>
<Char UnicodeIndex="108"/>
<Char UnicodeIndex="109"/>
<Char UnicodeIndex="110"/>
<Char UnicodeIndex="111"/>
<Char UnicodeIndex="112"/>
<Char UnicodeIndex="113"/>
<Char UnicodeIndex="114"/>
<Char UnicodeIndex="115"/>
<Char UnicodeIndex="116"/>
<Char UnicodeIndex="117"/>
<Char UnicodeIndex="118"/>
<Char UnicodeIndex="119"/>
<Char UnicodeIndex="120"/>
<Char UnicodeIndex="121"/>
<Char UnicodeIndex="122"/>
</CharSet>
</CharSetTable>
<DFATable Count="11" InitialState="0">
<DFAState Index="0" EdgeCount="6" AcceptSymbol="-1">
<DFAEdge CharSetIndex="0" Target="1"/>
<DFAEdge CharSetIndex="1" Target="2"/>
<DFAEdge CharSetIndex="2" Target="4"/>
<DFAEdge CharSetIndex="3" Target="5"/>
<DFAEdge CharSetIndex="4" Target="7"/>
<DFAEdge CharSetIndex="5" Target="8"/>
</DFAState>
<DFAState Index="1" EdgeCount="1" AcceptSymbol="2">
<DFAEdge CharSetIndex="0" Target="1"/>
</DFAState>
<DFAState Index="2" EdgeCount="1" AcceptSymbol="-1">
<DFAEdge CharSetIndex="3" Target="3"/>
</DFAState>
<DFAState Index="3" EdgeCount="0" AcceptSymbol="3">
</DFAState>
<DFAState Index="4" EdgeCount="0" AcceptSymbol="4">
</DFAState>
<DFAState Index="5" EdgeCount="1" AcceptSymbol="-1">
<DFAEdge CharSetIndex="1" Target="6"/>
</DFAState>
<DFAState Index="6" EdgeCount="0" AcceptSymbol="5">
</DFAState>
<DFAState Index="7" EdgeCount="1" AcceptSymbol="6">
<DFAEdge CharSetIndex="4" Target="7"/>
</DFAState>
<DFAState Index="8" EdgeCount="2" AcceptSymbol="-1">
<DFAEdge CharSetIndex="5" Target="9"/>
<DFAEdge CharSetIndex="4" Target="10"/>
</DFAState>
<DFAState Index="9" EdgeCount="2" AcceptSymbol="7">
<DFAEdge CharSetIndex="5" Target="9"/>
<DFAEdge CharSetIndex="4" Target="10"/>
</DFAState>
<DFAState Index="10" EdgeCount="2" AcceptSymbol="7">
<DFAEdge CharSetIndex="5" Target="9"/>
<DFAEdge CharSetIndex="4" Target="10"/>
</DFAState>
</DFATable>
<LALRTable Count="8" InitialState="0">
<LALRState Index="0" ActionCount="6">
<LALRAction SymbolIndex="6" Action="1" Value="1"/>
<LALRAction SymbolIndex="7" Action="1" Value="2"/>
<LALRAction SymbolIndex="8" Action="3" Value="3"/>
<LALRAction SymbolIndex="9" Action="3" Value="4"/>
<LALRAction SymbolIndex="10" Action="3" Value="5"/>
<LALRAction SymbolIndex="11" Action="3" Value="6"/>
</LALRState>
<LALRState Index="1" ActionCount="3">
<LALRAction SymbolIndex="0" Action="2" Value="0"/>
<LALRAction SymbolIndex="6" Action="2" Value="0"/>
<LALRAction SymbolIndex="7" Action="2" Value="0"/>
</LALRState>
<LALRState Index="2" ActionCount="3">
<LALRAction SymbolIndex="0" Action="2" Value="1"/>
<LALRAction SymbolIndex="6" Action="2" Value="1"/>
<LALRAction SymbolIndex="7" Action="2" Value="1"/>
</LALRState>
<LALRState Index="3" ActionCount="1">
<LALRAction SymbolIndex="0" Action="4" Value="0"/>
</LALRState>
<LALRState Index="4" ActionCount="3">
<LALRAction SymbolIndex="0" Action="2" Value="5"/>
<LALRAction SymbolIndex="6" Action="2" Value="5"/>
<LALRAction SymbolIndex="7" Action="2" Value="5"/>
</LALRState>
<LALRState Index="5" ActionCount="7">
<LALRAction SymbolIndex="6" Action="1" Value="1"/>
<LALRAction SymbolIndex="7" Action="1" Value="2"/>
<LALRAction SymbolIndex="8" Action="3" Value="7"/>
<LALRAction SymbolIndex="9" Action="3" Value="4"/>
<LALRAction SymbolIndex="10" Action="3" Value="5"/>
<LALRAction SymbolIndex="11" Action="3" Value="6"/>
<LALRAction SymbolIndex="0" Action="2" Value="3"/>
</LALRState>
<LALRState Index="6" ActionCount="3">
<LALRAction SymbolIndex="0" Action="2" Value="4"/>
<LALRAction SymbolIndex="6" Action="2" Value="4"/>
<LALRAction SymbolIndex="7" Action="2" Value="4"/>
</LALRState>
<LALRState Index="7" ActionCount="1">
<LALRAction SymbolIndex="0" Action="2" Value="2"/>
</LALRState>
</LALRTable>
</Tables>
XML as human readable format is self explanatory, you have access to all tables : Symbol, Rule, DFA and LALR and that's it.
Of course, cooking a "pgt" file (program template) is the usual way to process "cgt" or even write some extract utility for the purpose on top of a Gold Engine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619842",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: php preg_replace_call : extract specific values for later reinsertion For the sake of brevity...
I want to take items out of a string, put them into a separate array, replace the values extracted from the string with ID'd tokens, parse the string, then put the extracted items back in their original positions (in the correct order).
(If that makes sense, then skip the rest :D)
I have the following string;
"my sentence contains URLs to [url] and [url] which makes my life difficult."
For various reasons, I would like to remove the URLs.
But I need to keep their place, and reinsert them later (after manipulating the rest of the string).
Thus I would like;
"my sentence contains URLs to [url] and [url] which makes my life difficult."
to become;
"my sentence contains URLs to [token1fortheURL] and [token2fortheURL] which makes my life difficult."
I've tried doing this several times, various ways.
All I do is hit brickwalls and invent new swear words!
I use the following code to setup with;
$mystring = 'my sentence contains URLs to http://www.google.com/this.html and http://www.yahoo.com which makes my life difficult.';
$myregex = '/(((?:https?|ftps?)\:\/\/)?([a-zA-Z0-9:]*[@])?([a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}|([0-9]+))([a-zA-Z0-9-._?,\'\/\+&%\$#\=~:]+)?)/';
$myextractions = array();
I then do a preg_replace_callback;
$matches = preg_replace_callback($myregex,'myfunction',$mystring);
And I have my function as follows;
function myfunction ($matches) {}
And it's here that the brickwalls start happening.
I can put stuff into the blank extraction array - but they are nto available outside the function. I can update the string with tokens, but I lose access to the URLs that are replaced.
I cannot seem to add additional values to the function call within the preg_replace_callback.
I'm hoping someone can help, as this is driving me nuts.
UPDATE:
Based on the solution suggested by @Lepidosteus,
I think I have the following working?
$mystring = 'my sentence contains URLs to http://www.google.com/this.html and http://www.yahoo.com which makes my life difficult.';
$myregex = '/(((?:https?|ftps?)\:\/\/)?([a-zA-Z0-9:]*[@])?([a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}|([0-9]+))([a-zA-Z0-9-._?,\'\/\+&%\$#\=~:]+)?)/';
$tokenstart = ":URL:";
$tokenend = ":";
function extraction ($myregex, $mystring, $mymatches, $tokenstart, $tokenend) {
$test1 = preg_match_all($myregex,$mystring,$mymatches);
$mymatches = array_slice($mymatches, 0, 1);
$thematches = array();
foreach ($mymatches as $match) {
foreach ($match as $key=>$match2) {
$thematches[] = array($match2, $tokenstart.$key.$tokenend);
}
}
return $thematches;
}
$matches = extraction ($myregex, $mystring, $mymatches, $tokenstart, $tokenend);
echo "1) ".$mystring."<br/>";
// 1) my sentence contains URLs to http://www.google.com/this.html and http://www.yahoo.com which makes my life difficult.
function substitute($matches,$mystring) {
foreach ($matches as $match) {
$mystring = str_replace($match[0], $match[1], $mystring);
}
return $mystring;
}
$mystring = substitute($matches,$mystring);
echo "2) ".$mystring."<br/>";
// 2) my sentence contains URLs to :URL:0: and :URL:1: which makes my life difficult.
function reinsert($matches,$mystring) {
foreach ($matches as $match) {
$mystring = str_replace($match[1], $match[0], $mystring);
}
return $mystring;
}
$mystring = reinsert($matches,$mystring);
echo "3) ".$mystring."<br/>";
// 3) my sentence contains URLs to http://www.google.com/this.html and http://www.yahoo.com which makes my life difficult.
That appears to work?
A: The key to solving your problem here is to store the urls list in an outside container than can be accessed by your callbacks and by your main code to do the changes you need on them. To remember your urls positions, we will use a custom token in the string.
Note that to access the container I use closures, if you can't use php 5.3 for some reason you will need to replace them with another way to access the $url_tokens container from within the callback, which shouldn't be a problem.
<?php
// the string you start with
$string = "my sentence contains URLs to http://stackoverflow.com/questions/7619843/php-preg-replace-call-extract-specific-values-for-later-reinsertion and http://www.google.com/ which makes my life difficult.";
// the url container, you will store the urls found here
$url_tokens = array();
// the callback for the first replace, will take all urls, store them in $url_tokens, then replace them with [[URL::X]] with X being an unique number for each url
//
// note that the closure use $url_token by reference, so that we can add entries to it from inside the function
$callback = function ($matches) use (&$url_tokens) {
static $token_iteration = 0;
$token = '[[URL::'.$token_iteration.']]';
$url_tokens[$token_iteration] = $matches;
$token_iteration++;
return $token;
};
// replace our urls with our callback
$pattern = '/(((?:https?|ftps?)\:\/\/)?([a-zA-Z0-9:]*[@])?([a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}|([0-9]+))([a-zA-Z0-9-._?,\'\/\+&%\$#\=~:]+)?)/';
$string = preg_replace_callback($pattern, $callback, $string);
// some debug code to check what we have at this point
var_dump($url_tokens);
var_dump($string);
// you can do changes to the url you found in $url_tokens here
// now we will replace our previous tokens with a specific string, just as an exemple of how to re-replace them when you're done
$callback_2 = function ($matches) use ($url_tokens) {
$token = $matches[0];
$token_iteration = $matches[1];
if (!isset($url_tokens[$token_iteration])) {
// if we don't know what this token is, leave it untouched
return $token;
}
return '- there was an url to '.$url_tokens[$token_iteration][4].' here -';
};
$string = preg_replace_callback('/\[\[URL::([0-9]+)\]\]/', $callback_2, $string);
var_dump($string);
Which give this result when executed:
// the $url_tokens array after the first preg_replace_callback
array(2) {
[0]=>
array(7) {
[0]=>
string(110) "http://stackoverflow.com/questions/7619843/php-preg-replace-call-extract-specific-values-for-later-reinsertion"
[1]=>
string(110) "http://stackoverflow.com/questions/7619843/php-preg-replace-call-extract-specific-values-for-later-reinsertion"
[2]=>
string(7) "http://"
[3]=>
string(0) ""
[4]=>
string(17) "stackoverflow.com"
[5]=>
string(0) ""
[6]=>
string(86) "/questions/7619843/php-preg-replace-call-extract-specific-values-for-later-reinsertion"
}
[1]=>
array(7) {
[0]=>
string(22) "http://www.google.com/"
[1]=>
string(22) "http://www.google.com/"
[2]=>
string(7) "http://"
[3]=>
string(0) ""
[4]=>
string(14) "www.google.com"
[5]=>
string(0) ""
[6]=>
string(1) "/"
}
}
// the $string after the first preg_replace_callback
string(85) "my sentence contains URLs to [[URL::0]] and [[URL::1]] which makes my life difficult."
// the $string after the second replace
string(154) "my sentence contains URLs to - there was an url to stackoverflow.com here - and - there was an url to www.google.com here - which makes my life difficult."
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619843",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to pass a C++ callback function to a VB.NET program? I'm trying to pass a callback function from a C++ dll to a VB.NET application.
Here is my current C++ code :
void DLL_EXPORT registerEvent( void (*callBackFunction)(string str),string str)
{
callBackFunction(str);
}
void test(string str)
{
MessageBoxA(0,str.c_str(), "",MB_OK);
}
LRESULT CALLBACK keyHandler(int nCode, WPARAM wParam, LPARAM lParam)
{
...
registerEvent(&test, txt); //txt = the text received after user input with some additions
return CallNextHookEx(hookHandle, nCode,
wParam, lParam);
}
This is working inside the C++ dll (the messagebox is called with the correct text)
But i'd like to "trigger" the test procedure in the VB application with the text to use the VB Messagebox for example.
Here is my current VB.NET code :
Public Delegate Sub Callback(ByVal str As String)
Private Declare Sub registerEvent Lib "path\mycppdll.dll" _
(ByVal cb As Callback, ByVal str As String)
Dim cb As New Callback(AddressOf CallBackFunc)
Public Sub CallBackFunc(ByVal str As String)
'this should be the equivalent of the "test" proc in c++ but it's not triggered
End Sub
I think i'm missing something ??!
Any help will be appreciated !
A: The C++ code must have extern C linkage or the VB code won't be able to see it. Wrap the relevant declarations in the header with
extern "C" {
// declarations here
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Why if I create a varchar(65535), I get a mediumtext? Does a mediumtext and a varchar(65535) are the same thing ?
What I mean here is do they both store the data directly in the table or do the mediumtext type is storing a pointer ?
I'm asking this because if I try to create a varchar(65535) it is automatically transform into a mediumtext (if the length is bigger than 21811 actually).
I've got another related question which is:
I've got some fields in a table that I want to be able to store a lot of characters (around 10'000). But in reality, it will almost all the time store no more than 10 characters.
So my question is, do I need to use a text or a varchar(10000) type for best performance ?
I believe a varchar type is more appropriate for this case.
Thanks in advance for your answers.
Edit
The thing I don't understand is why they say that since mysql 5.0.3, we can create a varchar(65535) but when we try to do this, it convert it to a mediumtext. For me the difference between varchar and text (mediumtext include) is the way how they are store (using a pointer or not).
So why do they say that we can create varchar with a length of 65535 if we can't?
A: According to mysql.com the length of mediumtext is L + 3 bytes. To me this means that if you have an empty field it will be 3 bytes. If you have an empty varchar the length of this field will be 1 byte.
Here is clearly mentioned
Prior to MySQL 5.0.3, a VARCHAR column with a length specification
greater than 255 is converted to the smallest TEXT type that can hold
values of the given length. For example, VARCHAR(500) is converted to
TEXT, and VARCHAR(200000) is converted to MEDIUMTEXT. However, this
conversion affects trailing-space removal.
A: I'm answering to my own question:
That's because I'm using a multi-byte character. If you use an utf-8 collation, you will not be able to create a varchar with about more than 21000 chars. But if you use ascii, you will.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619846",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: Retrieving OpenID data of a Steam account, returning null? I'm using Light-OpenID for PHP to authenticate and retrieve data.
For my OpenID provider URL I am using http://steamcommunity.com/openid/, as documented here-
Steam OpenID Provider Steam can act as an OpenID provider. This allows
your application to authenticate a user's SteamID without requiring
them to enter their Steam username or password on your site (which
would be a violation of the API Terms of Use.) Just download an OpenID
library for your language and platform of choice and use
http://steamcommunity.com/openid as the provider. The returned Claimed
ID will contain the user's 64-bit SteamID. The Claimed ID format is:
http://steamcommunity.com/openid/id/
I have specified my required array of data that I am requesting as such -
$openid->required = array(
'namePerson',
'namePerson/first',
'namePerson/last',
'namePerson/friendly',
'contact/email',
'email');
I have made sure my code works, have tested it with other providers such as Google and Yahoo.
I try to login using Steam, I am authenticated, yet when I want to retrieve data about the user using $openid->getAttributes(); the array returns empty.
I have investigated more, and it appears Steam also serves data through its Web API using GetPlayerSummaries. I suppose I could use the 64BIT Steam ID from the authorization of the OpenID account to request the data, but this would require an API key, and parsing the data in PHP.
Is there a way to request this data using OpenID? Or do I have to manually parse everything through Steam's API?
A:
Steam can act as an OpenID provider. This allows your application to authenticate a user's SteamID without requiring them to enter their Steam username or password on your site (which would be a violation of the API Terms of Use.)
This answers a part of your question?
They use openId only for authentication - nothing more. In answer on other part i should say - yes you should obtain service key from steam and use GetPlayerSummaries method to get what you want. The parsing will be not problem because they support much formats for return (i would use JSON).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619848",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Google Analytics SDK for iOS I'm trying to integrate Google Analytics SDK with my iPhone app.
As it's described in the docs, before I began using the SDK, I've first created a free account at www.google.com/analytics and created a new website profile in that account using a fake but descriptive website URL.
For the created profile tracking status is always "Tracking Not Installed".
So, my question is, will it cause a problem to send tracking requests from my iPhone application? If yes, please advice me what to do then.
Thanks a lot.
A: Ok, I have found the answer...When I run the my app in Simulator, it is not sending trucking requests, but everything is fine, when I run it on the device.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619851",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Issue in playing youtube video in iphone I am trying to play youtube video within my application. Here is the code I am using
- (void)embedYouTube:(NSString*)url frame:(CGRect)frame {
NSString* embedHTML = @"\
<html><head>\
<style type=\"text/css\">\
body {\
background-color: transparent;\
color: white;\
}\
</style>\
</head><body style=\"margin:0\">\
<embed id=\"yt\" src=\"%@\" type=\"application/x-shockwave-flash\" \
width=\"%0.0f\" height=\"%0.0f\"></embed>\
</body></html>";
NSString* html = [NSString stringWithFormat:embedHTML, url, frame.size.width, frame.size.height];
if(videoView == nil) {
videoView = [[UIWebView alloc] initWithFrame:frame];
[self.view addSubview:videoView];
}
[videoView loadHTMLString:html baseURL:nil];
}
Video is getting played nicely. But after video is played
*
*I am taken back to the root view controller not to the view from
which the above function is called.
*Also in the root view controller the view is not active. I cant
click any buttons in that view.
*Also I can see a empty space of 20px at the bottom of view,it seems
like the view is occupying the space of status bar
How can I do it properly in ios?
Thanks
A: I have same problem before.
Just make custom class for Uiwebview without .xib file and implement your code.
And just make object of custom class in view you want to play video.
But don't add it to that view just make object and pass video url.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619857",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Testing in-app billing I've read quite a lot about in-app billing and testing but I still didn't find the answer to few questions:
How can I test real purchases on draft (unpublished) version of the app? The products/items need to be published => app need to be published. Is there a way to publish items without publishing the app?
The whole testing process is quite unfriendly to developers, shame on Google :(
I successfully tested my application using test static responses, now I need to test it on real items without publishing the application. The only way I can think of now is to publish the app for e.g. Kenya, publish the items, test and then un-publish the app.
Any ideas will be very appreciated. Thanks.
A: So I think I figured it out. All I needed to do was publish the app and then unpublish. After this I was be able to publish items and test real end-to-end purchases on these items. Very intuitive and developer-friendly :)
A: No that'll be like selling stuff (your items) that you don't have the license to sell. (For e.g you need a pharmacy to sell drugs.)
I'm sure the people who wrote this article must have considered your use case. From the article:
You do not need to publish your application to do end-to-end testing. You only need to upload your application as a draft application to perform end-to-end testing.
Also I read this here:
An item's publishing state can be Published or Unpublished . To be visible to a user during checkout, an item's publishing state must be set to Published and the item's application must be published on Android Market.
.
Note: This is not true for test accounts. An item is visible to a test account if the application is not published and the item is published. See Testing In-app Billing for more information.
A: The products become published as soon as you publish the app.
And your app doesn't have to be published to do the real testing, just upload as "draft".
The app must be signed.
The whole testing process is quite unfriendly to developers, shame on Google :(
Luckily there are libraries that can help with testing, for example android test billing. This library is the In-App billing implementation for the emulator, which was tested in the application Horer horaires de RER.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619858",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: JDO Batch PUT from Memcache In an effort to reduce the number of datastore PUTs I am consuming I
wish to use the memcache much more frequently. The idea being to store
entities in the memcache for n minutes before writing all entities to
the datastore and clearing the cache.
I have two questions:
Is there a way to batch PUT every entity in the cache? I believe
makePersistentAll() is not really batch saving but rather saving each
individually is it not?
Secondly is there a "callback" function you can place on entities as
you place them in the memcache? I.e. If I add an entity to the cache
(with a 2 minute expiration delta) can I tell AppEngine to save the
entity to the datastore when it is evicted?
Thanks!
A: makePersistentAll does indeed do a batch PUT, which the log ought to tell you clear enough
A: There's no way to fetch the entire contents of memcache in App Engine. In any case, this is a bad idea - items can be evicted from memcache at any time, including between when you inserted them and when you tried to write the data to the datastore. Instead, use memcache as a read cache, and write data to the datastore immediately (using batch operations when possible).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619862",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How to animate TextView's weight property I have a TextView, and I want to change its size, so I use its layout_weight property. When I set it:
textView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, 0, newWeight));
It works well. However, I want to animate the change. Can I do this (without using a thread that will change it every so and so millis), using the animation classes?
A: Property animations are only possible in Honeycomb as of now. A way to handle your requirement would be to use a scale animation. The tricky part is to calculate the scale factor. But it should be possible. You can add the scale animation to your view. And if you add the an animation listener to the animation object you can set the layout params on the animation end event so that the view actually re sizes.
A: No, you cannot change the weight of a view using Android animations.
You can use Handler to do a postDelayed event, where the view weight can be changed until some limit.
Handler hdlr = new Handler() {
onMessage(Message msg) {
}
};
hndlr.postDelayed(new Runnable() {
void run() {
// change the weight and post another delayed messge if required.
}
};
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619866",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Data mapper and zend framework I am implementing the Data Mapper design pattern in my Zend Framework web application, and everything goes well, I am really enjoying working with the data mapper in Zend and not applying only the Row Gateway pattern, but I am having a problem regarding my architecture. I am not sure how to reference and work with foreign key constraints in a OOP fashion with my data mapper.
So I am having my Model class, my DbTable class and my Mapper class. Should I put all the foreign keys relations in my DbTable class and in this way I can retrieve in my mapper using findDependentRowset() function, or a better approach would be to instantiate the dependent class in my mapper. What is the best OOP practice in mapping foreign keys using the Data Mapper pattern?
A: I'd go for the DataMapper as the other two shoudln't be aware of the ID per se althought it's always necessary for the relationship callers.
Model
- Property accessors and private property data holders
- Functions regarding correct usage of model
- Relatioship callers (calls relationship fetches in the DbTable to get parents or children rows)or returns cached data
DbTable
- Provides all static functions used to query data and instanciate the related Models such as :getById, getByName, getByComplexSearch, etc
- Provides all static relationship loaders such as: getParents, getChildrens and any other version you need
DataMapper
- Does the real meat and provides the getObjects method which accepts either a query part or a full query and loads the data into the ModelObjects and reads it back into a update, insert, delete query when needed
- Datamapper should be in charge of checking for relationship faults when inserting, updating or deleting using transactions if in InnoDB.
Does that make any sense?
A: I used to have findDependentRowset on my systems. But not anymore! It's a waste of resources in most cases. Table joins should be on your SQL statement.
See my answer here: Hand made queries vs findDependentRowset
I'm still far away from use Doctrine or Propel (I've never needed it). Maybe some day. (Now using Doctrine 2. So... I suggest you the same now)
OLD ANSWER
After a couple of years working with Zend Framework, I come across with the following architecture:
1) I have an abstract mapper which all my mappers extends: Zf_Model_DbTable_Mapper
2) I have an abstract model (domain object) too, similar to the Row Data Gateway, with the exception that it is not a gateway. It's a generic domain object: Zf_Model
3) When populating object graphs (SQL joins) one mapper delegates to the other mappers that are responsible for the given object.
Example
This method is from the abstract mapper:
public function getById($id)
{
$tableGateway = $this->getTable();
$row = $tableGateway->fetchRow('id =' . (int) $id);
if (!$row)
retur null;
$row = $row->toArray();
$objectName = $this->getDomainObjectName();
$object = new $objectName($row['id']);
$object->populate($row);
return $object;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619867",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Python list comprehension - simple I have a list and I want to use a certain function only on those entries of it that fulfills a certain condition - leaving the other entries unmodified.
Example: Say I want to multiply by 2 only those elements who are even.
a_list = [1, 2, 3, 4, 5]
Wanted result:
a_list => [1, 4, 3, 8, 5]
But [elem * 2 for elem in a_list if elem %2 == 0] yields [4, 8] (it acted as a filter in addition).
What is the correct way to go about it?
A: a_list = [1, 2, 3, 4, 5]
print [elem*2 if elem%2==0 else elem for elem in a_list ]
or, if you have a very long list that you want to modify in place:
a_list = [1, 2, 3, 4, 5]
for i,elem in enumerate(a_list):
if elem%2==0:
a_list[i] = elem*2
so, only the even elements are modified
A: Use a conditional expression:
[x * 2 if x % 2 == 0 else x
for x in a_list]
(Math geek's note: you can also solve this particular case with
[x * (2 - x % 2) for x in a_list]
but I'd prefer the first option anyway ;)
A: You could use lambda:
>>> a_list = [1, 2, 3, 4, 5]
>>> f = lambda x: x%2 and x or x*2
>>> a_list = [f(i) for i in a_list]
>>> a_list
[1, 4, 3, 8, 5]
Edit - Thinking about agf's remark I made a 2nd version of my code:
>>> a_list = [1, 2, 3, 4, 5]
>>> f = lambda x: x if x%2 else x*2
>>> a_list = [f(i) for i in a_list]
>>> a_list
[1, 4, 3, 8, 5]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619868",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: How to make boost.build use a specific compiler installation? I am trying to build boost 1.45 using a local GCC compiler installation. I can't make it use a different compiler command that the default "g++". Here what happened so far:
In boost_1_45_0 source directory:
./bootstrap.sh --with-toolset=gcc --prefix=$INSTALL/boost-$TYPE
Then added the following line to "projct-config.jam":
using gcc : 4.4.6 : [absolute path]/install/gcc-4.4.6/bin/g++ : ;
./bjam install --prefix=$INSTALL/boost-$TYPE
When bringing up the process list during building, I can see that the system's default compiler command g++ gets used.
A: That should be toolset=gcc-4.4.6 rather than --with-toolset=gcc (features are not specified with leading dashes).
A: The problem was a previous definition of using which got in the way. This solves the problem:
project-config.jam:
if ! gcc in [ feature.values <toolset> ]
{
using gcc : 4.4.6 : [absolute path]/install/gcc-4.4.6/bin/g++ : -L[absolute path]/install/gcc-4.4.6/lib64 -I[absolute path]/install/gcc-4.4.6/include ;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619874",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Search button - Twitter Search API I'm trying to create a button that takes a subject you've typed in and pulls the relevant tweets using the Twitter Search API.
I've seen something similar with the jTwitter plugin, but I'm not sure on how to do it myself, and can't seem to find any documentation on it.
Here's the jQuery:
twitterUrl = "http://search.twitter.com/search.json?"+ q +"&rpp=1500&page=2&result_type=recent&callback=?";
twitterList = $( "<ul />" );
twitterFunction = function( data ) {
$.each( data.results, function( i, item ) {
$( "<li />", { "text" : item.text } )
.appendTo( twitterList );
});
$( "#twit" ).fadeOut( "fast", function(){
$( this ).empty()
.append( twitterList )
.fadeIn( "slow" );
});
};
$.getJSON( twitterUrl, twitterFunction );
And the HTML:
<article>
<form>
<input type="text" id="subject" name="q" placeholder="subject..." >
<input type="button" id="start" value="start" >
</form>
<div id="twit"></div>
</article>
And a working jsFiddle.
Thanks for your help.
A: Check the implementation @ http://jsfiddle.net/Jayendra/reVy7/10/
Customize the results handling.
A: I'll suggest you to use jQuery Twitter Search Plugin
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619877",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can't install Ruby or Rails using RVM : ERROR: There has been an error while running configure. Halting the installation Here is what I ran:
rvm install ruby-1.9.2-p290
I have xCode 4 installed. And I am running OSX 10.6.7
Here is the error I get
ruby-1.9.2-p290 - #configuring
ERROR: Error running ' ./configure --prefix=/Users/jac/.rvm/rubies/ruby-1.9.2-p290 --enable-shared --disable-install-doc --with-libyaml-dir=/Users/jac/.rvm/usr ', please read /Users/jac/.rvm/log/ruby-1.9.2-p290/configure.log
ERROR: There has been an error while running configure. Halting the installation.
Here are the last parts of the log file
checking for working volatile... yes
checking whether right shift preserve sign bit... yes
checking read count field in FILE structures... _r
checking read buffer ptr field in FILE structures... _p
checking size of struct stat.st_ino... SIZEOF_LONG
checking whether _SC_CLK_TCK is supported... yes
checking stack growing direction on i386... -1
checking for backtrace... yes
checking whether ELF binaries are produced... no
checking whether OS depend dynamic link works... yes
checking for strip... strip
configure: error: thread model is missing
I'll tell ya I never post question anywhere because I can usually figure stuff out eventually. But I am not seeing anyone having this specific error anywhere. I see similar things about not having XCode... But I have that.
EDIT:
I ran into this problem because I thought I had everything set up but when I tried to make a new project I ran into this:
rails new demo
/Library/Ruby/Site/1.8/rubygems/dependency.rb:247:in to_specs': Could not find rails (>= 0) amongst [rake-0.8.7, rake-0.8.7] (Gem::LoadError)
from /Library/Ruby/Site/1.8/rubygems/dependency.rb:256:into_spec'
from /Library/Ruby/Site/1.8/rubygems.rb:1195:in `gem'
from /usr/bin/rails:18
A: Are you missing /usr/include/pthread.h on your system?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619878",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Wireshark TCP Dup ACK - strange I have run Wireshark on the server's computer and I have such a strange transmission:
Client (X: src port 65509) connects to my server (Y: dst port 9999).
1) There is normal TCP handshake
15:47:41.921228 XXX.XXX.XXX.XXX 65509 YYY.YYY.YYY.YYY 9999 65509 > distinct [SYN] Seq=0 Win=8688 Len=0 MSS=1460 WS=0 SACK_PERM=1 TSV=66344090 TSER=0
15:47:41.921308 YYY.YYY.YYY.YYY 9999 XXX.XXX.XXX.XXX 65509 distinct > 65509 [SYN, ACK] Seq=0 Ack=1 Win=8192 Len=0 MSS=1460 SACK_PERM=1 TSV=69754693 TSER=66344090
15:47:42.176823 XXX.XXX.XXX.XXX 65509 YYY.YYY.YYY.YYY 9999 65509 > distinct [ACK] Seq=1 Ack=1 Win=8688 Len=0 TSV=66344350 TSER=69754693
2) Server sends an encryption key to the client and client ACKs receiving it:
15:47:42.180755 YYY.YYY.YYY.YYY 9999 XXX.XXX.XXX.XXX 65509 distinct > 65509 [PSH, ACK] Seq=1 Ack=1 Win=65160 Len=24 TSV=69754719 TSER=66344350
15:47:42.452606 XXX.XXX.XXX.XXX 65509 YYY.YYY.YYY.YYY 9999 65509 > distinct [ACK] Seq=1 Ack=25 Win=8664 Len=0 TSV=66344630 TSER=69754719
3) Suddenly panel Resets the connection for some reason
15:47:42.948618 XXX.XXX.XXX.XXX 65509 YYY.YYY.YYY.YYY 9999 65509 > distinct [RST] Seq=28 Win=0 Len=0
4) But the strange thing to me goes here. Server sends TCP Dup ACK. What can be the reason for that? I thought this message can be sent only after retransmission or sth. I've never seen it to be sent after RST.
15:47:42.948654 YYY.YYY.YYY.YYY 9999 XXX.XXX.XXX.XXX 65509 [TCP Dup ACK 5856#1] distinct > 65509 [ACK] Seq=25 Ack=1 Win=65160 Len=0 TSV=69754796 TSER=66344630**
5) Client sends RST again.
15:47:43.227269 XXX.XXX.XXX.XXX 65509 YYY.YYY.YYY.YYY 9999 65509 > distinct [RST] Seq=1 Win=0 Len=0
Thanks for any suggestions.
A: The Dup-ACK from server in step(4) is caused by the Seq 28 in step(3):
65509 > distinct [RST] Seq=28 Win=0 Len=0
Because server is expecting Seq#25 but received #28. This happens when seq 25~27 is lost in the network. The Dup-ACK notifies the client to re-transmit lost data before the RST; however, in step(5), we see the client, in response to server's dup-ack, reset again. So client data #25~27 never reached the server and is gone.
You can verify this by doing packet capture on both server and client.
For details, read some TCP re-transmission document.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619883",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Feed Dialog not working on some browsers Hi guys I have a weird problem with de feed dialog.
It works pefect on Firefox, but when I try to use it on IE or Chrome I got this error "An error occurred. Please try later"
I have tried to fix it but I can't. Can you help me please.
This is the code i'm using to call the dialog.
<div id='fb-root'></div>
<script src='http://connect.facebook.net/en_GB/all.js'></script>
<a href="#" onclick='postToFeed(); return false;'>Post Feed</a>
<script>
FB.init({appId: "xxxx", status: true, cookie: true});
function postToFeed() {
// calling the API ...
var obj = {
method: 'feed',
link: 'http://apps.facebook.com/xxxx',
picture: 'xxxx',
name: 'xxxx',
caption: 'xxxxx',
description: 'xxxxx',
properties: [{text: 'xx', href: 'xx'},],
actions: [{name: 'xx', link: 'xx'}],
};
function callback(response) {
document.getElementById('msg').innerHTML = "Well Done!!";
}
FB.ui(obj, callback);
}
</script>
</script>
A: A couple of things to try:
1: It could possibly be as simple as the rogue comma in your code here after actions:
actions: [{name: 'xx', link: 'xx'}],
Try removing that, however Chrome should better handle that, but that would have caused an issue with IE!
2: Use the Console to see if any errors are thrown.
3: Add oauth: true to your init statement like so:
FB.init({appId: "xxxx", status: true, cookie: true, oauth: true});
4: Remove the parameters in the call, and add them back in one by one after testing it works with each addition: start with:
var obj = {
method: 'feed',
link: 'http://apps.facebook.com/xxxx',
picture: 'xxxx',
name: 'xxxx',
caption: 'xxxxx',
description: 'xxxxx'
};
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619889",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Wordpress. List pages except certain pages I am using this code to display the pages in a menu:
wp_list_pages('title_li=&');
There are a few pages that I would like to exclude from the list.
How would I do this please?
Note: I am using friendly URL's so the id's are actually names not numbers.
A: You can write
wp_list_pages('title_li'=>'&', 'exclude'=> '1,5,7');
where 1,5,7 is id of pages you want to exclude from list. comma separated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619893",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: rounded border around img doesnt show
as u can see the border is missing from the corners (red one). if i make it 4+ px thick then its ok but i need it 1px thin. why it is a problem? ist this property behaves by design like this?
the html
<div class="win" >
<img class="rounded" src='red.jpg' />
</div>
and the css
.win{width:188px;float:left;margin:0 30px 25px 0;}
.win .rounded {
overflow: hidden;
behavior: url(PIE.htc);
border:1px solid #000;
-moz-border-radius: 7px; /* Firefox */
-webkit-border-radius: 7px; /* Safari and Chrome */
border-radius: 7px; /* Opera 10.5+, future browsers, and now also Internet Explorer 6+ using IE-CSS3 */
}
/EDIT/
finally i have found a solution which makes exactly what i needed. i share the link maybe someone else has the the same problem:
http://webdesignerwall.com/tutorials/css3-rounded-image-with-jquery
A: You should have a look at the background-clip css property. Try background-clip: padding-box. You should also add -webkit-background-clip and -moz-background-clip to support older browsers.
A: There is an issue using border-radius with images in most/all browsers. There are a number of online articles about this but I've not paid attention to them. You should Google for those.
A: If you want good rounded borders that will work with a large number of browsers, you could use image as a background for a div with needed css-properties.
Example (only border, nothing else):
html
<div class="card" style="background:url(image.jpg) no-repeat center center; width:150px; height:150px;"></div>
css
.card {
border:1px solid #000;
-webkit-border-radius: 1px;
-moz-border-radius: 1px;
border-radius: 1px;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619896",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Breakout game ( When im out, i want the ball again to hit the remaining bricks) Im new to java programming. Im learning to develop a game similar to the one called breakout. Here's how it works
you have a set of bricks to hit using a ball and the paddle
Im caught in a situation here,
Whenever i miss the ball, itl take me to the else loop where im sending "Game over" message.
Instead i want the ball back again, and the other left over bricks to hit.
Here's the snippet
Java Code:
public void paint(Graphics g) {
super.paint(g);
if (ingame) {
g.drawImage(ball.getImage(), ball.getX(), ball.getY(),
ball.getWidth(), ball.getHeight(), this);
g.drawImage(paddle.getImage(), paddle.getX(), paddle.getY(),
paddle.getWidth(), paddle.getHeight(), this);
for (int i = 0; i < 30; i++) {
if (!bricks[i].isDestroyed())
g.drawImage(bricks[i].getImage(), bricks[i].getX(),
bricks[i].getY(), bricks[i].getWidth(),
bricks[i].getHeight(), this);
}
} else {
Font font = new Font("Verdana", Font.BOLD, 18);
FontMetrics metr = this.getFontMetrics(font);
g.setColor(Color.BLACK);
g.setFont(font);
g.drawString(message,
(Commons.WIDTH - metr.stringWidth(message)) / 2,
Commons.WIDTH / 2);
}
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
Thanks in advance :)
A: 1) Use paintComponent()
2) Don't destry the Graphics passed as argument
3) The code should be equal to the start code; move the ball inside the playfield and start again.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619898",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: php email and smtp i've got a php function which sends emails fine but I want it to use the smtp server i have specified in the ini.set function.
if i delete these 3 lines of code the email still sends fine.
the reason i want to use the smtp server is because sometimes this does not work to certain mail hosts.
connect();
$username = mysql_real_escape_string($_POST['username']);
$result = mysql_query("SELECT email FROM members WHERE username = '$_POST[username]'")
or die ("Error - Something went wrong.");
$row = mysql_fetch_array($result);
$useremail = $row['email'];
$name = "name";
$mail_from = "[email protected]";
$mail_to = "$useremail";
$mail_body = "Hello. Thank you for registering. Please click the link below to confirm your email address. ";
$mail_subject = "Confirm you registration".$name;
$mail_header = "From: ".$name." <".$mail_from.">\r\n";
ini_set ("SMTP", "ssl://serveraddress");
ini_set("smtp_port","465");
ini_set("sendmail_from","[email protected]");
$sendmail = mail($mail_to, $mail_subject, $mail_body, $mail_header);
if($sendmail == true) { mail("[email protected]", "email sent ok", "email sent to '$_POST[email]'", "yea sent ok");}
Else { mail("[email protected]", "email ERROR", "email not sent to '$_POST[email]'", "yea we got a problem");}
}
A: If you are serious about sending mass mailing in your web application, i'd look at the SwiftMailer library, its free and relatively easy to setup and you can set your own SMTP transporter live.
Else than that, i have had issues with sending mail to hotmail and yahoo before where the email just doesn't get there when you use the "mail()" function. Keep in mind that the web email clients are very picky about headers, structure and security and may refuse emails not written by real clients easily.
If you want to test out something like that, just use a local-address@your-domain email, this will usually not filter it out. Now if the mail doesn't get there, you know it's something else.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619900",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Adding "options" menu in Google Chrome extension How do I add the options menu on right-clicking the icon of a Google Chrome extension?
I have made a file named options.html; now how do i link it up so it works? I thought it would be automatic.
A: Google Chrome populates the right-click menu automatically, so to have an Options item there your extension needs to actually provide an options page. As you've figured out already, designating options.html as your options page is done by adding the following line to manifest.json:
"options_page": "options.html",
See documentation of this feature.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619902",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How can i change UI of my page after async call? I am having async call on my page,
This takes about 1 minute.
I need to change UI after call completes.
Sample code is give below.
protected void Unnamed1_Click(object sender, EventArgs e)
{
apicasystemWPMCheckStatsService.CheckStatsServiceClient obj = new apicasystemWPMCheckStatsService.CheckStatsServiceClient();
string xmlOptionForGetCheckStats = "<options><mostrecent count='1'/><dataformat>xml</dataformat><timeformat>tz</timeformat></options>";
string checkId = "";
TextBox1.Text = TextBox1.Text + "test" + "\r\n";
obj.BeginGetCheckStats("admin@azuremonitoring", "Cu4snfPSGr8=", "PD6B685A0-006A-4405-951E-B24BB51E7966",
checkId, xmlOptionForGetCheckStats, new AsyncCallback(ONEndGetCheckStats), null);
TextBox1.Text = TextBox1.Text + "testdone" + "\r\n";
}
public void ONEndGetCheckStats(IAsyncResult asyncResult)
{
System.Threading.Thread.Sleep(3000);
TextBox1.Text = TextBox1.Text + "testcomplete" + "\r\n";
}
The question is that how can i get "testcomplete" in my textbox. as my page is not getting posted back after this async call....
My current O/P :
test
testdone
Expected:
test
testdone
testcomplet
A: Simple answer: You can not do it like that. Because once the ASPX page is sent to the client there is no somple way for the server to communicate with that page.
You can do this however with AJAX. In your Unnamed1_Click set up a "flag" in Session that signals that an async operation is pending. In your ONEndGetCheckStats set that "flag" to signal that the operation has completed.
Add an ASP.NET page method (Quick Tutorial) to your code-behind that:
*
*Checks whether the operation is pending and returns null wehen it is
*When operation is finished removes everything from Session and returns the text that you need
On your ASPX page wire up a client-side event on the Unamed1 (a poor name for a button btw) button that starts a client-side loop checking the status using that PageMethod. When status is not null anymore Javascript to change the TextBox1 text.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619903",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Checking how much memory is readable in other process Is there a way to know how much memory I can read from another process using ReadProcessMemory?
If I try to read too much memory from a specific address, it will return error code 299, and will read 0 bytes.
I'm guessing it's because I'm trying to read beyond the allocated buffer of the process.
A: As far as I know, the only way is trying to read it. ReadProcessMemory will return 0 if the memory block you want to read is not fully accessible in the process, e.g., part of it is not allocated.
Use a smaller nSize(1024 or 512 or even 1) is a workaround.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619907",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: PHP - parsing txt file i'd like to parse this file:
Case Given Predicted
No Class Class
1 ? 0 [0.80]
2 ? 0 [0.80]
3 ? 0 [0.80]
4 ? 1 [0.75]
5 ? 0 [0.80]
6 ? 0 [0.80]
7 ? 1 [0.75]
8 ? 0 [0.80]
9 ? 0 [0.80]
10 ? 0 [0.80]
11 ? 1 [0.75]
12 ? 0 [0.80]
13 ? 0 [0.80]
14 ? 0 [0.80]
15 ? 0 [0.80]
16 ? 0 [0.80]
17 ? 0 [0.80]
18 ? 0 [0.80]
19 ? 0 [0.80]
20 ? 0 [0.80]
Especially, i want to take values from third column ("Predicted class").I open file thanks to:
$txt_file = file_get_contents('simone.result');
$array = explode("\n", $txt_file);
array_shift($array);
array_shift($array);
array_shift($array);
And I have this:
Array ( [0] => 1 ? 0 [0.80] [1] => 2 ? 0 [0.80]
Ok this is correct. But I want only the third value ("0" or "1") in each key of this array. Does anyone can help me please?
Thank you so much!
A: Why not just simply explode your string by a space and use the value you want?
A: Something like this?
foreach( $array as $key => $value ) {
$split = explode( " ", $value );
$array[$key] = $split[2];
}
A: $lines = file('simone.result');
$column3 = array();
for( $i = 2, $ilen = count( $lines ); $i < $ilen; $i++ )
{
$columns = preg_split( '/\s+/', $lines[ $i ] );
$column3[] = $columns[ 2 ];
}
var_dump( $column3 );
A: retrieve all the lines of the file
$lines = file($txt_file);
then loop on them:
foreach($lines as $line )
{
list($v1,$v2,$v3,$v4) = explode("\n", trim($line)); //assuming separator is a space \t for tab
//take the values you need here
$tmp[] = $v3;
}
print_r($tmp);
as well this work if the file is well written :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619911",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Should I just use a single table? I have an entity Order.
The order has information on date, client, associate who handled order etc.
Now the order also needs to store a state i.e. differentiate between won orders and lost orders.
The idea is that a customer may submit an order to the company, but could eventually back out.
(As domain info, the order is not of items. It is a services company that tries to handle clients and makes offers on when they can deliver an order and at what price etc. So the customer may find a better burgain and back up and stop the ordering process from the company).
The company wants data on both won orders and lost orders and the difference between a won order and a lost order is just a couple of more attributes e.g. ReasonLost which could be Price or Time.
My question is, what would be the best representation of the Order?
I was thinking of using a single table and just have for the orders won, the ReasonLost as null.
Does it make sense to create separate tables for WonOrder and LostOrder if the difference of these new entities is not significant?
What would be the best model for this case?
A: Use one table. Add an OrderState Field.
Caveat: If you are doing millions of transactions per day, then decisions like this need much more attention and analysis.
A: There is another alternative design that you might consider. In this alternative you keep a second table for the order lost reason and relate it to your order table as an optional 1:1. Note that this is effectively an implementation of a supertype/subtype pattern where the lost order subtype has one additional attribute.
It looks like this:
This alternative might be attractive under any of the following circumstances:
*
*You lose very few orders.
*Your order table isn't wide enough to hold a long enough lost order reason.
*Your lost order reason is very, very big (even BLOB).
*You have an aesthetic objection to maintaining a lost order reason in your order table.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619915",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to get context in android Service class I am getting the following error when i try to read a XML file from the memory and into an object. Seems like problem with getting the Context. Can anyone tell me whats wrong with my code?
Code:
public class WifiScanning extends Service {
private static final String TAG = "WifiScanning";
private Timer timer;
public int refreshRate;
public WifiScanning() {
super();
Configuration config = new Configuration();
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp;
XMLReader xr = null;
DataHandler dataHandler = null;
try {
sp = spf.newSAXParser();
xr = sp.getXMLReader();
dataHandler = new DataHandler();
xr.setContentHandler(dataHandler);
xr.parse(new InputSource(this.openFileInput("config.xml")));
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
config = dataHandler.getConfig();
refreshRate = Integer.parseInt(config.getMapRefreshRate());
// TODO Auto-generated constructor stub
}
private TimerTask updateTask = new TimerTask() {
@Override
public void run() {
Log.i(TAG, "Timer task doing work");
}
};
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Service creating");
timer = new Timer("TweetCollectorTimer");
Log.i(TAG, "Refresh Rate: "+ String.valueOf(refreshRate));
timer.schedule(updateTask, 0, 3000L);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "Service destroying");
if (timer != null){
timer.cancel();
timer.purge();
timer = null;
}
}
public void onStop() {
Log.i(TAG, "Service destroying");
if (timer != null){
timer.cancel();
timer.purge();
timer = null;
}
}
}
LogCat:
10-01 11:08:49.804: ERROR/AndroidRuntime(21514): java.lang.RuntimeException: Unable to instantiate service android.wps.WifiScanning: java.lang.NullPointerException
10-01 11:08:49.804: ERROR/AndroidRuntime(21514): at android.app.ActivityThread.handleCreateService(ActivityThread.java:2764)
10-01 11:08:49.804: ERROR/AndroidRuntime(21514): at android.app.ActivityThread.access$3200(ActivityThread.java:119)
10-01 11:08:49.804: ERROR/AndroidRuntime(21514): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1917)
10-01 11:08:49.804: ERROR/AndroidRuntime(21514): at android.os.Handler.dispatchMessage(Handler.java:99)
10-01 11:08:49.804: ERROR/AndroidRuntime(21514): at android.os.Looper.loop(Looper.java:123)
10-01 11:08:49.804: ERROR/AndroidRuntime(21514): at android.app.ActivityThread.main(ActivityThread.java:4363)
10-01 11:08:49.804: ERROR/AndroidRuntime(21514): at java.lang.reflect.Method.invokeNative(Native Method)
10-01 11:08:49.804: ERROR/AndroidRuntime(21514): at java.lang.reflect.Method.invoke(Method.java:521)
10-01 11:08:49.804: ERROR/AndroidRuntime(21514): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
10-01 11:08:49.804: ERROR/AndroidRuntime(21514): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
10-01 11:08:49.804: ERROR/AndroidRuntime(21514): at dalvik.system.NativeStart.main(Native Method)
10-01 11:08:49.804: ERROR/AndroidRuntime(21514): Caused by: java.lang.NullPointerException
10-01 11:08:49.804: ERROR/AndroidRuntime(21514): at android.content.ContextWrapper.openFileInput(ContextWrapper.java:152)
10-01 11:08:49.804: ERROR/AndroidRuntime(21514): at android.wps.WifiScanning.<init>(WifiScanning.java:52)
10-01 11:08:49.804: ERROR/AndroidRuntime(21514): at java.lang.Class.newInstanceImpl(Native Method)
10-01 11:08:49.804: ERROR/AndroidRuntime(21514): at java.lang.Class.newInstance(Class.java:1479)
10-01 11:08:49.804: ERROR/AndroidRuntime(21514): at android.app.ActivityThread.handleCreateService(ActivityThread.java:2761)
10-01 11:08:49.804: ERROR/AndroidRuntime(21514): ... 10 more
A: You should do this not in the constructor, but only between (inclusive) onCreate() and onDestroy().
A: If you are using a service you are supposed to write that code in onStartCommand, not in the constructor
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619917",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.