text stringlengths 8 267k | meta dict |
|---|---|
Q: How to find cookies which begin with string "word" and extract information from string with char # I have cookies with values in it, and between values I put # so I can later extract data from cookies.
Now I need a way to search for cookies which begin with some word let say "word", and when I find that cookies I want to extract word from it and as I sad char # is indicator for that and char % is indicator for last char.
var name = "word" + "" + n1 + "" + n2 + "" + n3;
var value = v1 + "#" + v2 + "#" + v3 + "#" + v4 + "%";
name is cookie name, and value is cookie value.
I need function which will look for all cookies which begin with "word" and when find it, from cookie value extract v1 v2 v3 and v4 in 4 different variables.
I have to look all cookies names and if cookie name begin with "word" like
"word and here is the rest of the string".
That is first part.
Second part is when we find cookies with that name, now from cookie value which is string separated with # we need to separate 4 variables.
Is it now clear what I need?
A: Two helper functions.
One that decodes the document.cookie string into an object with keys/values:
function decodeCookie() {
var cookieParts = document.cookie.split(";"),
cookies = {};
for (var i = 0; i < cookieParts.length; i++) {
var name_value = cookieParts[i],
equals_pos = name_value.indexOf("="),
name = unescape( name_value.slice(0, equals_pos) ).trim(),
value = unescape( name_value.slice(equals_pos + 1) );
cookies[":" + name] = value;
}
return cookies;
}
one that searches through this object and finds the first value that starts with a certain search word:
function findCookieByName(searchWord) {
var cookies = decodeCookie();
for (name in cookies) {
var value = cookies[name];
if (name.indexOf(":" + searchWord) == 0) {
return value;
}
}
}
So you can do:
var value = findCookieByName("word");
if (value) {
var pieces = value.split("#"); // > array of values
}
P.S.: I prepend the cookie name with ":" to prevent clashes with built-in properties of objects. For example: You can name your cookie __proto__ but that wouldn't work too well with JavaScript objects. Hence I store all cookie names with a prefix.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515222",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Describe the page rendering process in a browser? First of all, I am not interested in the entire request-response process as addressed by this question
What is the complete process from entering a url to the browser's address bar to get the rendered page in browser?
I want to know what goes on inside a browser, once it receives the html response from the server. The intent behind asking this question is to understand the inner details of client side scripting. Also it would be beneficial if you can explain in abstract concepts what a web browser comprises of. You may call them as CSS engine, javascript engine etc.The goal is to precisely visualize the web development I am doing.
Unfortunately, I did not find any web resources addressing this issue. Please forgive me if there are resources out there which explain these concepts. You may point to the resources (books, etc) if this question is too exhaustive to answer.
A: An excellent talk by Mozilla's David Baron discusses this in detail. It's a video entitled Faster HTML and CSS: Layout Engine Internals for Web Developers, and it walks you through the five steps of rendering a DOM tree to the screen:
*
*Construct the DOM
*Calculate styles
*Construct the rendering tree
*Compute layout
*Paint
A: Please go through below steps and you should be clear with request lifecycle and how response is rendered.
*
*You type an URL into address bar in your preferred browser.
*The browser parses the URL to find the protocol, host, port,and path.
*It forms a HTTP request (that was most likely the protocol)
*To reach the host, it first needs to translate the human readable host into an IP number, and it does this by doing a DNS lookup on the host
*Then a socket needs to be opened from the user’s computer to that IP number, on the port specified (most often port 80)
*When a connection is open, the HTTP request is sent to the host The host forwards the request to the server software (most often Apache) configured to listen on the specified port
*The server inspects the request (most often only the path), and launches the server plugin needed to handle the request (corresponding to the server language you use, PHP, Java, .NET, Python?)
*The plugin gets access to the full request, and starts to prepare a HTTP response.
*To construct the response a database is (most likely) accessed. A database search is made, based on parameters in the path (or data) of the request
*Data from the database, together with other information the plugin decides to add, is combined into a long string of text (probably HTML).
*The plugin combines that data with some meta data (in the form of HTTP headers), and sends the HTTP response back to the browser.
*The browser receives the response, and parses the HTML (which with 95% probability is broken) in the response
*A DOM tree is built out of the broken HTML
*New requests are made to the server for each new resource that is found in the HTML source (typically images, style sheets, and JavaScript files).
*Go back to step 3 and repeat for each resource.
*Stylesheets are parsed, and the rendering information in each gets attached to the matching node in the DOM tree
*JavaScript is parsed and executed, and DOM nodes are moved and style information is updated accordingly
*The browser renders the page on the screen according to the DOM tree and the style information for each node
*You see the page on the screen
*You get annoyed the whole process was too slow.
A: I will try to explain the page rendering process in depth. Kindly note that I am not focusing on the request-response process as the OP has asked in the question.
Once the server supplies the resources (HTML, CSS, JS, images, etc.) to the browser it undergoes the below process:
Parsing - HTML, CSS, JS
Rendering - Construct DOM Tree → Render Tree → Layout of Render Tree → Painting the render tree
*
*The rendering engine starts getting the contents of the requested document from the networking layer. This will usually be done in 8kB chunks.
*A DOM tree is built out of the broken response.
*New requests are made to the server for each new resource that is found in the HTML source (typically images, style sheets, and JavaScript files).
*At this stage the browser marks the document as interactive and starts parsing scripts that are in "deferred" mode: those that should be executed after the document is parsed. The document state is set to "complete" and a "load" event is fired.
*Each CSS file is parsed into a StyleSheet object, where each object contains CSS rules with selectors and objects corresponding CSS grammar. The tree built is called CSSCOM.
*On top of DOM and CSSOM, a rendering tree is created, which is a set of objects to be rendered. Each of the rendering objects contains its corresponding DOM object (or a text block) plus the calculated styles. In other words, the render tree describes the visual representation of a DOM.
*After the construction of the render tree it goes through a "layout" process. This means giving each node the exact coordinates where it should appear on the screen.
*The next stage is painting–the render tree will be traversed and each node will be painted using the UI backend layer.
*Repaint: When changing element styles which don't affect the element's position on a page (such as background-color, border-color, visibility), the browser just repaints the element again with the new styles applied (that means a "repaint" or "restyle" is happening).
*Reflow: When the changes affect document contents or structure, or element position, a reflow (or relayout) happens.
What is the internal structure of a web browser?
To understand the page rendering process explained in the above points we also need to understand the structure of a web browser.
User interface: The user interface includes the address bar, back/forward button, bookmarking menu, etc. Every part of the browser display except the window where you see the requested page.
Browser engine: The browser engine marshals actions between the UI and the rendering engine.
Rendering engine: The rendering engine is responsible for displaying requested content. For example if the requested content is HTML, the rendering engine parses HTML and CSS, and displays the parsed content on the screen.
Networking: The networking handles network calls such as HTTP requests, using different implementations for different platforms behind a platform-independent interface.
UI backend: The UI backend is used for drawing basic widgets like combo boxes and windows. This backend exposes a generic interface that is not platform specific. Underneath it uses operating system user interface methods.
JavaScript engine: The JavaScript engine is used to parse and execute JavaScript code.
Data storage: The data storage is a persistence layer. The browser may need to save all sorts of data locally, such as cookies. Browsers also support storage mechanisms such as localStorage, IndexedDB, WebSQL and FileSystem.
Note:
During the rendering process the graphical computing layers can use general purpose CPU or the graphical processor GPU as well.
When using GPU for graphical rendering computations the graphical software layers split the task into multiple pieces, so it can take advantage of GPU massive parallelism for float point calculations required for the rendering process.
Useful Links:
1. https://github.com/alex/what-happens-when
2. https://codeburst.io/how-browsers-work-6350a4234634
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515227",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "38"
} |
Q: VS debugger do not works as expected When I debug my ASP.NET app and execution breaks at break point I can't read type variable using Debug Watches. Why? I get error
type The name 'type' does not exist in the current context
The code works fine, the problem only in debugging, I can't read all variables while debugging.
var converterSubClasses = new List<Type>();
GetClassHierarhy(ref converterSubClasses, converterClass);
foreach (var type in converterSubClasses)
{
/* break point here */ var classProperties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
/* skip code */
}
A: Are you debugging code compiled in Release mode? Depending on the optimizations the compiler used the variable type may not actually be there. Confirm you're debugging against Debug compiled code and try then. (I've had loops not make sense and entire sections get jumped when trying to debug in release mode.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515228",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Is it better to give an NSMutableArray or to create an NSArray from it? This is a question that's been bothering me for a while.
I want to send some data in an NSArray to a viewController, and sometimes I need to create a NSMutableArray and populate it element by element.
If I send it to the viewController, it will be useless, as it only needs to read the array. So I'm wondering if it's more expensive to send an NSMutableArray, or to create a (maybe?) more lightweight NSArray, with the cost of memory allocation, and releasing the (maybe?) heavier NSMutableArray.
By the way, I know it's over optimization, but I'm curious.
A: This has nothing to do with optimization.
(Or, very very little and only in uncommon cases)
It has everything to do with how defensive you want your code to be.
You can always return a subclass of whatever a method declares it's return type to be. That just works.
The caller will only see it as a whatever the superclass is (NSArray in this case), unless they do something exceptionally dangerous by down casting to NSMutableArray and mutating the array.
When this happens, if you are still using that array as a backing store in your object, the caller will effectively be modifying your backing store out from under you.
By return [[mutArray copy] autorelease]; you are ensuring that such silliness can never happen. And, in fact, the AppKit suffered enough bugs from people casting and mucking with the arrays, that various methods have moved to return [[mutArray copy] autorelease];
There is also a threading implication; read-only Foundation types are generally thread safe. Read-write are not and that includes reading while something else is writing. Thus, if you return a reference to a mutable array, you cannot modify that array from another thread ever again unless you absolutely know that all external references are gone (which, btw, isn't knowable without poor design).
The performance implication of immutable vs. mutable on copy is only very rarely an issue.
A: You can build it as an NSMutableArray but then send it as an NSArray. This is valid, note the return type is NSArray but the object is NSMutableArray. You can do this because a NSMutableArray is a NSArray, it is a subclass of NSArray. In this example the caller gets an NSArray that they can't* modify.
-(NSArray*)buildArray
{
NSMutableArray* mutArray = [NSMutableArray arrayWithCapacity:50];
... fill the array...
return mutArray;
}
*not without casting
A: NSArray and NSMutableArray are both implemented with CFArray's so they should have the same performance at accessing element, if you took a look at the open-source-version but the closed-source you are using may differ (see comments).
The performance difference of using NSArray vs NSMutable array arises primarily when you copy the array. if you send -copy to an immutable array, it just bumps the retain count, but sending -copy to a mutable array will allocate heap memory.
A: If you are never going to use that particular array again, I would declare the return value to be an NSArray and just return the NSMutableArray you've just used to build it.
If you might use that array internally or return it later, I'd use [NSArray arrayWithArray:mutableArray] to "downgrade" it. Especially if you are creating a framework that others will be using.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515233",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to execute custom action in Alfresco before download a file? I want to store in the repository an unchanged file, but change its content on dowloading due to user's role.
To do this I just created my own action that changes content of the file, but found that Alfresco does not provide an appropriate rule to be executed on file downloading.
My action must execute on download using API (link) and using CIFS or WebDAV (copying from folder), so I have to use a rules engine to execute action.
How can I realize this?
A: While I can't think of a solution that preserves the dataflow you describe, especially since file server interfaces are involved, I would advise you not to transform the content upon user request, as it would require online (blocking) computations upon each and every user download. I also assume that the results of such transformations are "static" for a given role.
I would solve your use case by:
*
*creating an action that generates all the needed versions of the document
*such action should also set permissions accordingly, so that ReadPermission is granted only to the target role
*setup an inbound rule that triggers the action on all incoming documents
*(optionally) creates and setup a similar action/rule pair to cleanup all the renditions upon content deletion
This way whichever user or role accesses the given folder will be presented only content in the form he's expecting to have.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515238",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: which SWT component use to implement file browser/explorator in icons, not list, mode how to implement a file browser which has explorator windows/nautilus(Linux) like functionality. I'm looking for a concept which component I should use as a base to create something like right side of this application: http://www.vectorlight.net/silverlight/demos/local_file_explorer.aspx
I need to implement it in SWT, it should work on Windows and Linux at once.
A: If JFace is fine with you then have a look at these links (otherwise you can study the sample code to write the SWT version): (The below links are dead now)
*
*http://www.ibm.com/developerworks/library/os-ecgui1/
*http://www.ibm.com/developerworks/library/os-ecgui2/
The final output of the above tutorial looks like this:
Also have a look at the official examples from eclipse. There is a sample file explorer bundled with it. See the below image:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515239",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Unusual gaps while using JSeperator - Java I have been working on a Swing GUI and getting some unusual and unwanted gaps after adding JSeperator, Any idea how to remove them? Or any other option to how to achieve this nicely!
Visual Description
Gaps are apparent before JLabel "Speed" and after JSlider.
Related Code
control.setLayout(new BoxLayout(control, BoxLayout.X_AXIS));
...another code omitted...
control.add(orientation); //JLabel
control.add(norm); //JRadioButton
control.add(back); //JRadioButton
control.add(new JSeparator(SwingConstants.VERTICAL));
control.add(speedLabel); //JLabel
control.add(speed); //JSlider
control.add(new JSeparator(SwingConstants.VERTICAL));
control.add(turnOutLabel); //JLabel
control.add(right); //JRadioButton
control.add(straight); //JRadioButton
control.add(left); //JRadioButton
What I want is to Have have everything centred and separated by JSeperator,
Visual Description
Thank you.
A: Just replace new JSeparator(...) with the following lines (you can put them in a method if you want):
JSeparator separator = new JSeparator(JSeparator.VERTICAL);
Dimension size = new Dimension(
separator.getPreferredSize().width,
separator.getMaximumSize().height);
separator.setMaximumSize(size);
As @kleopatra explained, JSeparator has unbounded maximum size (in both directions), so the trick here is to limit the max width to the preferred width, but still keep the max height unchanged (because the preferred height is 0).
A: The reason BoxLayout is adding those gaps is that
*
*the width of your frame (panel) is greater than the total pref sizes of the children
*JSeparator and JSlider have an unbounded (practically, it's Short.Max) max width while all others have a content dependent max
*BoxLayout respects max sizes, so all excess gets distributed between those three
The reason FlowLayout doesn't show the separators at all,
*
*JSeparator has a pref height of 0
*FlowLayout gives every child its pref size
The easy way out is Howare's first suggestion: add the complete control to a panel with flowLayout. The more robust solution is to switch over to a more powerful LayoutManager :-)
(removed edit again, BorderLayout.south/north doesn't ;-)
A: change BoxLayout to new FlowLayout(FlowLayout.LEFT). This should work. Unfortunately I do not have a real explanation why BoxLayout does not work for you.
A: You may put your control into another panel with a FlowLayout.
Update: Unfortunately setting the control to flowlayout directly via
control.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
does not work, since the separator's preferred height is zero and the separators will disappear.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515241",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: iPhone if file exists issue From all of the examples I've seen, I do believe I'm doing this right. Here is my code:
NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES) objectAtIndex:0];
NSString* thisImage = [documentsPath stringByAppendingPathComponent:image_path];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:thisImage];
if (fileExists){
hotel_image = [UIImage imageNamed:image_path];
}else{
hotel_image = [UIImage imageNamed:@"hdrHotels.jpg"];
}
You can assume that "image_path" equals "images/hotels/thishotel.jpg".
Now first, so that everyone understands, "hdrHotels.jpg" is in the base directory. And "images/hotels/thishotel.jpg" are actual subdirectories (blue folers). I've also tried using:
NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *imagePath = [NSString stringWithFormat:@"/%@",image_path];
NSString* thisImage = [documentsPath stringByAppendingPathComponent:imagePath];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:thisImage];
Adding a leading "/" in front of "images/hotels/thishotel.jpg". What is happening in both of these cases is that the "if" statement is false whether the image exists or not. I'm not sure what I'm doing wrong at all. Any help would be greatly appreciated.
EDIT:
I changed:
NSString *imagePath = [NSString stringWithFormat:@"/%@",image_path];
to:
NSString *imagePath = [image_path stringByReplacingOccurrencesOfString:@"images/hotels/" withString:@""];
But that still didn't work.
I also tried:
NSFileManager* fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString* documentsDir = [paths objectAtIndex:0];
NSString* myFilePath = [NSString stringWithFormat:@"%@/%@", documentsDir, image_path];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:myFilePath];
with no luck.
---------------------------------- ANSWER --------------------------------
So yeah, I finally figured it out. I can't answer my own question since I don't have 100 rep yet, but here is the fix.
NSFileManager* fileManager = [NSFileManager defaultManager];
NSString *myFilePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:image_path];
BOOL fileExists = [fileManager fileExistsAtPath:myFilePath];
if (fileExists){
hotel_image = [UIImage imageNamed:image_path];
}else{
hotel_image = [UIImage imageNamed:@"hdrHotels.jpg"];
}
A: If you mean as "actual subdirectories (blue folders)" and "base directory" as the directories in Xcode, then all of the files will be placed in the bundle path and not in the documents directory.
Instead files in the documents directory are files that have been generated or copied or downloaded directly by the application during execution.
A: Adding a leading / to image_path and then adding that to documentPath results in "docDir//imagePath", the filesystem treats this as "docDir/imagePath". As viggio24 suggested, first search your images in the resourceDir, then in the docDir.
A: Here are four different ways (Temporary/Custom Path, Bundle Folder, Documents Folder and another form of access to Documents Folder)
// Temporary Path Folder (read/write files)
//
NSMutableString *tempPathFile = [[NSMutableString alloc] initWithCapacity:(NSUInteger)1024];
[tempPathFile setString:[NSTemporaryDirectory() stringByAppendingPathComponent:@"export.mov"]];
// Application Folder (read-only files)
//
NSString *systemDirectoryPath = [[NSString alloc] initWithString:[[NSBundle mainBundle] resourcePath]];
// Documents Folder (read/write files)
//
NSArray *filePaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [[NSString alloc] initWithString:[filePaths objectAtIndex:0]];
// Another way to access Documents Folder (read/write files)
//
NSMutableString *documentsPath = [[NSMutableString alloc] initWithCapacity:(NSUInteger)1024];
[documentsPath setString:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]];
Not certain of whats going on in the rest of your code but the autorelease of some of the class calls can get you so I generally alloc a mutable string for my own copy of folder paths
A: Now that I see this again I can finally answer it:
NSFileManager* fileManager = [NSFileManager defaultManager];
NSString *myFilePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:image_path];
BOOL fileExists = [fileManager fileExistsAtPath:myFilePath];
if (fileExists){
hotel_image = [UIImage imageNamed:image_path];
}else{
hotel_image = [UIImage imageNamed:@"hdrHotels.jpg"];
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515244",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PowerShell Select weirdness I have two select statements here. The "headings" from the first (message, username,timegenerated) are being used for the second (username,timegenerated).
Please look at the echo statement to see that the tables\outputs are being merged into one.
Can anyone explain why?
This needs to be run in a ps1 script to see the weirdness:
$before = get-date
$after = (get-date).AddDays(-1)
$a = Get-EventLog System -Before $before -After $after | ? {$_.Message -like "*start*"}
$a | select message, username,timegenerated
echo "----going through security----"
$b = Get-Eventlog security -Before $before -After $after |?{$_.category -match "Logon/Logoff" }
$b | select username,timegenerated
The output is this:
Message UserName TimeGenerated
------- -------- -------------
The Engine service was successfully sent a star... NT AUTHORITY\SYSTEM 22/09/2011 09:32:09
The Engine service was successfully sent a star... NT AUTHORITY\SYSTEM 21/09/2011 16:03:57
The Licensing Service service was successfu... DOMAIN\username 21/09/2011 15:58:12
----going through security----
DOMAIN\9876ABC$ 22/09/2011 14:05:41
DOMAIN\9876ABC$ 22/09/2011 14:04:58
DOMAIN\9876ABC$ 22/09/2011 14:03:40
DOMAIN\9876ABC$ 22/09/2011 14:02:57
NT AUTHORITY\LOCAL SERVICE 22/09/2011 14:01:59
A: Looks like a formatting issue, the following seems to work as expected though:
$before = get-date
$after = (get-date).AddDays(-1)
$a = Get-EventLog System -Before $before -After $after | ? {$_.Message -like "*start*"}
$a | select message, username,timegenerated | format-table -force
echo "----going through security----"
$b = Get-Eventlog security -Before $before -After $after |?{$_.category -match "Logon/Logoff" }
$b | select username,timegenerated | format-table -force
Additionally, this definitely looks like a bug concerning the output of multiple custom psobjects (created above as a result of doing the selects).
The following code explicitly creates a separate PSObject for each query result and returns the same results as your code (i.e. only one set of headings):
$before = get-date
$after = (get-date).AddDays(-1)
$a = Get-EventLog System -Before $before -After $after | ? {$_.Message -like "*start*"}
$a = $a | `
% {New-Object PSObject -Property `
@{Message = $_.message; Username = $_.username; Timegenerated = $_.timegenerated}
}
$a
echo "----going through security----"
$b = Get-Eventlog security -Before $before -After $after |?{$_.category -match "Logon/Logoff" }
$b = $b | `
% {New-Object PSObject -Property `
@{Username = $_.username; Timegenerated = $_.timegenerated}
}
$b
Run this in PS_ISE and execute:
$a | gm
$b | gm
You can see that they are distinct objects with different properties. Things get even weirder if you don't use the same key names between objects; look at the results returned if we change:
$b = $b | `
% {New-Object PSObject -Property `
@{Username = $_.username; Timegenerated = $_.timegenerated}
}
to:
$b = $b | `
% {New-Object PSObject -Property `
@{UsernameB = $_.username; TimegeneratedB = $_.timegenerated}
}
For those with no will to run this, it returns whitespace where the security result set should be. Running Get-Member again shows two custom objects, each with it's own properties.
It's probably worth logging this with Microsoft Connect although it looks like PSCustomObjects might be getting an overhaul in v3, see here.
A: This is a function of PowerShell's console output. When you output the first set of objects, you set the format for all subsequent objects. Everything following will be presented as a continuous stream of objects within the same table and publishing the same properties.
If you emit $a in one run and $b in a completely different run, you'll see you've really got two distinct sets of objects. You're just seeing a console formatting issue here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515245",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: C#: Retrieve output parameter of non-parametrized stored procedure query? I have this stored procedure
CREATE PROCEDURE [dbo].[TestProcedure]
@param1 int = 0
,@param2 int = 0
,@total_sales int = 5 OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SET @total_sales = @total_sales * 5
SELECT * FROM SomeTable
END
And this string in C#
string strSQL = @"
DECLARE @RC int
DECLARE @param1 int
DECLARE @param2 int
DECLARE @total_sales int
-- TODO: Set parameter values here.
SET @param1 = 1
SET @param2 = 2
EXECUTE @RC = [TestDB].[dbo].[TestProcedure]
@param1
,@param2
,@total_sales OUTPUT";
And now I want to retrieve the output value, but without parametrizing the input query !
I tried this:
using (System.Data.SqlClient.SqlCommand cmd = (System.Data.SqlClient.SqlCommand)idbConn.CreateCommand())
{
cmd.CommandText = strSQL;
cmd.Transaction = (System.Data.SqlClient.SqlTransaction)idbtTrans;
iAffected = cmd.ExecuteNonQuery();
idbtTrans.Commit();
string strOutputParameter = cmd.Parameters["@total_sales"].Value.ToString();
Console.WriteLine(strOutputParameter);
} // End Using IDbCommand
And this throws an exception (the parameter @total_sales is not in the parameter list).
How can I retrieve an output parameter in a non-parametrized stored-procedure call WITHOUT parametrizing the query ?
A: Short answer: You can't.
Long Answer: You need to use ADO.NET in a more standard way to enable you to leverage things such as output parameters.
A: Well, not sure if this will help, but the following is technically possible :
In your TSQL scripts, use RAISERROR to raise informational messages. You could use this to return information about the name and value of variables. e.g.
DECLARE @Msg NVARCHAR(200)
SET @Msg = 'totalsales=5' -- construct string of form : VariableName=ValueAsString
RAISERROR(@Msg, 10, 1)
In C#, use the SqlConnection.InfoMessage event to catch these messages. Parse the returned strings to extract the names and values. It would be a roundabout way to return parameter values, but it would work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515249",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Dynamic cell access My question may seem quite simple but I haven't found the answer yet.
In excel, I would like to access a cell with a dynamic row number.
Example 1 : cell A(1+2)
Example 2 : cell B(ROW(A1)*10)
What is the syntax for this ?
Thanks.
A: Use the INDIRECT function:
=INDIRECT("A" & (1+2))
=INDIRECT("B" & ROW(A1)*10)
A: If by
cell B(ROW(A1)*10)
you meant if A1 was 3 then return the value in B30 ,ie B(3*10)
then you want
=INDIRECT("B" &A1*10)
=INDIRECT("B" & ROW(A1)*10)
will always return cell B10
as ROW(A1) always =1
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515250",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "22"
} |
Q: Easiest way to compare two revisions of a single file - not a repository - in Mercurial history? I want to compare an individual file - not see all of the changes in one revision of a repository versus another revision.
The way I'm doing it now is
hg clone https://me@bitbucket.org/me/ C:\me.123 -r 123
Then I use a file comparison tool in Windows to compare the current version C:\me against C:\me.123.
So, okay, this is not an efficient way to do file comparisons for a single file since I have to pull the entire repository from bitbucket every time.
At the moment I just want to compare README.txt in C:\me against README.txt from revision 123.
How do I do that?
A: If the file you have locally is your working copy then you can just use the hg diff command and specifiy a revision
hg diff -r 123 filename
A: If you clone a repository, you have it's whole history. So you don't have to reclone from the source to get a particular revision, you could just clone from your existing copy. But, of course, that's still very inefficient for diffing a single file.
hg diff -r 123 README.txt
That command will do what you want when you're in C:\me.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515253",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Google Analytics _trackPageview AJAX requests 100% bounce rates I have a form (made up of a few stages) that is loaded via ajax, and as I move between stages I want to track it in Google Analytics as a PageView. I have this working ok, but I am getting an overall bounce rate below 100% (~30%), which is fine. But when I look at the individual pages, they all seem to have a bounce rate of 100%. I am not too sure if this is normal, or should I expect different bounce rates? I have included some snippets below.
Thanks
Andy
//Run at the start
_gat._createTracker('UA-xxxxxxxx-4', 'myTracker');
var _gaq = _gaq || [];
_gaq.push(['myTracker._setAccount', 'UA-xxxxxxxx-4']);
_gaq.push(['myTracker._setDomainName', 'www.testaccount.co.uk']);
//This is run when a stage loads up.
_gaq.push(['myTracker._trackPageview', '/form/stage[X]/']);
//This code is run within each stage to capture elements of the form being completed
_gaq.push(['myTracker._trackEvent', 'Test', "value"]);
A: Bounce rate issues like the one you are seeing are typically the result of cookie-domain issues. If you're trying to isolate the top-level www domain, I would try passing 'none' as the argument for _setDomainName. 'trackPageview' both creates and reads cookies, so I'm guessing it's creating duplicate sets of '_utm' cookies on your site.
Check out the documentation for '_setDomainName', specifically the section on isolating top-level domains, at: http://code.google.com/apis/analytics/docs/gaJS/gaJSApiDomainDirectory.html#_gat.GA_Tracker_._setDomainName
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515257",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Default setting for "Build Action" and "Copy to Output Directory"? I noticed when I'm making a new ASP.NET non-MVC2 Webapplication project. In the file properties for either .aspx or .cs files, there are 2 settings that I'm wondering what are defaults for. The reason I'm asking is because there's a couple of files I'm reusing from my last project and the settings were changed when I add the files into the project. For example all the aspx and .cs "Build Action" setting is set to "content" and all the "Copy to Output Directory" is set to "Do not copy"
A: I believe for Default.aspx the build Action shoud be Content and for Default.aspx.cs the build Action should be Compile.
Site.Master build action is Content but the Site.Master.cs is compile. Global.asax build action is Content but the Global.asax.cs is compile and finally web.config is content
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515260",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to put advertisement to my android application? I am new to integrating advertisement into my android application.
I don't know how it's going to work with Android Devices and how to integrate it into my Project.
But just because of the requirement, I have to put the advertisement to my project.
I would need details for the following.
*
*How to add advertisements to my project?
*How is it going to work?
*What steps do I have to follow to integrate it into my project?
It would be best if there is a simple demo project that can explain.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515263",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Rounding Problem with Python
Possible Duplicate:
Python rounding error with float numbers
I have a rounding Problem in Python. If i calculate
32.50 * 0.19 = 6.1749999999999998
But this should be 6.175. If i round 6.1749999999999998 with 2 decimal places it correctly shows 6.18. So i can live with that.
But if i calculate this:
32.50 * 0.19 * 3 = 18.524999999999999
This should be 18.525. If i round the value 18.524999999999999 with two decimal places it shows 18.52.
It should show me 18.53. What am i doing wrong and how can i fix it ?
A: What Every Computer Scientist Should Know About Floating-Point Arithmetic.
In short - you should not rely on precise values of float numbers because of the way they are stored in the memory.
See also python docs about it - Floating Point Arithmetic: Issues and Limitations. It contains the next passage:
For example, if you try to round the value 2.675 to two decimal places, you get this
>>> round(2.675, 2)
2.67
The documentation for the built-in round() function says that it
rounds to the nearest value, rounding ties away from zero. Since the
decimal fraction 2.675 is exactly halfway between 2.67 and 2.68, you
might expect the result here to be (a binary approximation to) 2.68.
It’s not, because when the decimal string 2.675 is converted to a
binary floating-point number, it’s again replaced with a binary
approximation, whose exact value is
2.67499999999999982236431605997495353221893310546875
Since this approximation is slightly closer to 2.67 than to 2.68, it’s
rounded down.
A: If you need exact arithmetic, you could use the decimal module:
import decimal
D=decimal.Decimal
x=D('32.50')*D('0.19')
print(x)
# 6.1750
print(x.quantize(D('0.01'),rounding=decimal.ROUND_UP))
# 6.18
y=D('32.50')*D('0.19')*D('3')
print(y)
# 18.5250
print(y.quantize(D('0.01'),rounding=decimal.ROUND_UP))
# 18.53
A: Use the Decimal Module from python to do accurate floating arithmatic
from decimal import Decimal, ROUND_UP
value = Decimal(32.50 * 0.19 * 3)
print (value.quantize(Decimal('.01'), rounding=ROUND_UP))
Output: 18.53
A: You're doing nothing wrong, and it isn't Python's fault either. Some decimal numbers just cannot be precisely represented as binary floats.
Just like you can't write 1/3 in decimal (0.33333....), you can't write decimal 0.1 in binary (0.0001100110011001100110011001100110011001100110011...).
Solution A:
Use print 32.5 * 0.19 - it will automatically round the result.
Solution B:
Use the Decimal module if you actually need this precision, for example when calculating with monetary values.
Solution C:
Use Python 3.2 or Python 2.7 which will automatically round the result in an interactive session.
Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 32.50 * 0.19
6.175
A: http://docs.python.org/library/functions.html#round
A: I don't think that is wrong. Take this from the Python interpreter:
>>> round(18.524999999999999,2)
18.52
>>> round(6.1749999999999998,2)
6.17
>>>
In both cases, the number being rounded was less than 5, so it rounded down. 18.52, and 6.17.
That is correct.
One thing I don't get is why you are getting 6.18, and I get 6.17. I am using Python 3.2.2 (the latest version)
A: You are not doing anything wrong. This is due to the internal representation of the numbers:
For example, try this:
0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1
If you need more precision use the decimal representation
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515266",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Action behaving like Func in VB.NET Today I've witnessed some very strange behavior in VB.NET. The code I am talking about is the following:
Option Strict On
Option Explicit On
Module Module1
Sub Main()
Dim thisShouldBeSet = False
DoSomething(Function() thisShouldBeSet = True)
If Not thisShouldBeSet Then
Throw New Exception()
End If
Console.WriteLine("yaay")
End Sub
Sub DoSomething(action As Action)
action.Invoke()
End Sub
End Module
I know that the code in itself is flawed because I must use :
DoSomething(Sub() thisShouldBeSet = True)
Instead of:
DoSomething(Function() thisShouldBeSet = True)
But I find it very odd that even with Option Strict and Option Explicit On the compile allows me to compile this code.
What is even stranger is that when running the code the Action actually behaves like a Func(of Boolean).
Can anyone provide me with a valid explanation to why this is allowed in VB.NET? Is this a compiler / runtime bug?
A: Why should it not allow you to compile the code? thisShouldBeSet = True is a valid comparison, returning the value False (because thisShouldBeSet <> True). Remember that = in VB can mean both = (assignment) and == (comparison) in C#, depending on the context.
To elaborate, Sub() thisShouldBeSet = True would be a shorthand for
Sub Anonymous()
thisShouldBeSet = True ' Assignment
End Sub
whereas Function() thisShouldBeSet = True is a shorthand for
Function Anonymous() As Boolean
Return thisShouldBeSet = True ' Comparison
End Sub
In VB, it is explicitly allowed to use a function with a return value as an Action. From the documentation of the System.Action delegate (highlighting by me):
In C#, the method must return void. In Visual Basic, it must be defined by the Sub…End Sub construct. It can also be a method that returns a value that is ignored.
A: What's going on here is that you are creating a closure.
Your lamdba method behaves like a function rather than a sub in both cases because you have captured/closed over the thisShouldBeSet variable from the Main method, and the thisShouldBeSet = True expression for the Sub interprets the = operator as an assignment rather a comparison.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515269",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Maintaining UserTransactions across session Working in a servlet, Websphere Application Server allows you to store UserTransaction objects in the HttpSession and retrieve it later, previously with a wrapper class, but now automatically:
http://publib.boulder.ibm.com/infocenter/wasinfo/v6r1/index.jsp?topic=%2Fcom.ibm.websphere.javadoc.doc%2Fpublic_html%2Fapi%2Fcom%2Fibm%2Fwebsphere%2Fservlet%2Fsession%2FUserTransactionWrapper.html
Yet when I begin a transaction, then retrieve it later and attempt to commit, I recieve the error that no transaction exists to commit. I assume the servlet is closing the transaction automatically when the http request finishes on each servlet call - what, then, is the purpose of being able to mantain this userTransaction across sessions?
Is there any way to achieve what I want (I'm using Java with WAS)?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515270",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there any way to find out mapped drive in Java? I want to find out a given drive path is mapped drive or normal drive in my Java code. Is there any API already available for that?
A: You could probably use WMI for this, either use a WMI library for Java, or call wmic.exe. Looks to be a fairly simple query, Select * From Win32_LogicalDisk Where DriveType = 4
As a reference: http://blogs.technet.com/b/heyscriptingguy/archive/2005/10/27/how-can-i-determine-which-drives-are-mapped-to-network-shares.aspx
A: If you're talking about drive letters, then there is no concept of that in Java. Java tries to be cross-platform, and most platforms have no concept of drive letters.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515275",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: get email ids from the given string using javascript I have a value (a) in my textbox. I want to get the email ids only from the given string using Javascript (I don't want to use any JS Frameworks).
(a) xxx@gmail.com (Blig fun), yyy@gmail.info (LOl)
I need the output like
xxx@gmail.com
yyy@gmail.info
A: Try -
var tbstring = '(a) xxx@gmail.com (Blig fun), yyy@gmail.info (LOl)';
result = tbstring.match(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/ig);
alert(result.join('\n'));
Demo - http://jsfiddle.net/ipr101/MM7Aa/
Email RegEx is taken from the RegEx Buddy library and comes with the following provisos -
Does not match email addresses using an IP address instead of a domain
name.
Does not match email addresses on new-fangled top-level domains with
more than 4 letters such as .museum. Including these increases the
risk of false positives when applying the regex to random documents.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515283",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Inner Join in mysql SELECT FirstName from tbl_User INNER JOIN tbl_Organisation
on tbl_user.tbl_organisation_OrganisationID=tbl_Organisation.OrganisationID
WHERE tbl_organisation_OrganisationID = '23'
I want to get a column(OrgName) from tbl_Organisation. how can I do that with the above code.
A: Simply with :
SELECT tu.FirstName, tor.OrgName from tbl_User tu INNER JOIN tbl_Organisation tor
on tbl_user.tbl_organisation_OrganisationID=tbl_Organisation.OrganisationID
WHERE tbl_organisation_OrganisationID = '23'
A: SELECT tbl_User.FirstName, tbl_Organisation.OrgName from tbl_User INNER JOIN tbl_Organisation
on tbl_user.tbl_organisation_OrganisationID=tbl_Organisation.OrganisationID
WHERE tbl_organisation_OrganisationID = '23'
A: Try this:
SELECT FirstName,tbl_organisation.OrgName
FROM tbl_User
INNER JOIN tbl_Organisation ON tbl_user.tbl_organisation_OrganisationID=tbl_Organisation.OrganisationID
WHERE tbl_organisation_OrganisationID = '23'
A: SELECT FirstName, tbl_Organisation.OrgName from tbl_User INNER JOIN tbl_Organisation
on tbl_user.tbl_organisation_OrganisationID=tbl_Organisation.OrganisationID
WHERE tbl_organisation_OrganisationID = '23'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515285",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: impossible to delete contacts I'm trying to delete all contacts by code in Android 3.0 using this code
private void wipeContacts(Context c){
int count = 0;
ContentResolver cr = c.getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext()) {
String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
cr.delete(uri, null, null);
count++;
}
Toast.makeText(c, " "+count+" Contacts deleted", Toast.LENGTH_LONG).show();
}
As I'm having trouble with the emulator (android 3.0) I'm not able to check if contacts are really deleted because it crashes when I try to launch "Contact" on the menu but each time I call wipeContacts() It tell me via Toast x Contacts deleted. So It's seems like it's not working. I'm I missing something? Thanks for help.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515286",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Programmatically set print page left, right, top, bottom margins How to programmatically set the printer (left, right, top, bottom) margins, paper size liek A4, A3 etc.. in asp.net web applications.
A: You cannot control a user's printer.
Printer settings are firmly in the domain of "user controlled".
If you want to decrease the margins you are out of luck.
If you want to increase the margins you can just add margins, since the margins of your application will be applied to the 'printable area' of your paper, i.e. 5% default margin from printer + 5% margin in code will be 10% margin.
A: This css rules are designed for that:
@page {
size: 210mm 297mm portrait;
margin: 0 0 0 0;
overflow: hidden;
}
Maybe useful links:
*
*http://www.tutorialspoint.com/css/css_paged_media.htm
*http://www.w3.org/TR/css3-page/#page-size
*Landscape printing from HTML
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515289",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What are self-calling functions in JavaScript? From what I have heard, the following is a "self-calling function":
func(){}();
How is it different from the following?
func(){} func();
A: I assume you meant what is the difference between (I):
function(){}();
and (II):
function func(){};
func();
or even (III):
var func = function(){};
func();
All three behave the same in regard to the results, however they have different naming and scoping consequences:
*
*I: this will not make the function available under any name, it is run once and forgotten. You can not reference it in the future
*II: func function is created and available in the whole enclosing function, even before it is defined (hoisting)
*III: func variable is defined pointing to a function. It won't be accessible before being defined.
Note that in II and III the function is referencable via func name and can be called again multiple times. This is not possible with self-calling function in I.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515293",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: What was used before Fragments? I wanted to use Fragments for displaying different activities on one screen on a tablet, but realised that my tablet's API level is only 8 while Fragments require API level 11.
My question is thus, what was used before Fragments were introduced?
My assumption is that each activity was simply displayed on its own screen and one navigated from one activity to the next by means of the menu button, context menus and back button.
This is what I wanted to achieve using fragments: I write information about three "actions" to three different xml files. My idea was to display the three different xml files in three different fragments on the tablet's screen. The one file is information about a patient, the second file is x, y and z values received from an accelerometer and the third file is observations recorded by a therapist. I wanted to display the patient's info on the left (like a left bar), a graph showing the patient's test results on the right and below that, the therapist's observations.
Is there a way that I can display these three xml files' info on one screen of the tablet? Or am I doomed to the use of menu buttons and three different screens - one for displaying each xml file?
Comments will be appreciated.
A: I am posting this as answer (removing the comment). You can use fragments even on Android 1.6, you have to download the "Android Compatibility package" - more info here and use it in your project (reference it as library). This way you don't need to build your own layout that would replicate fragments.
A: Yes,
You can provide three different xml files and load them into a fragment.
You will need to create a layout file that contains 3 fragments, or one fragment and two frames.
If you need further implementation of this let me know and i will be glad to help you out.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515294",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Remove/ignore white-space or ink from a symbol/it's glyph This symbol: ▴ (HTML code, ▴). Try selecting it, as you'll see, it as every other symbol has whitespace around.
Is there a way to remove this whitespace, so the symbol is simply like if it would've been a drawn image?
I tried using CSS's clip property, but didn't work.
Any possible ways with CSS only? Or a way to calculate where actual symbol starts with javascript and then apply with calculation to position this symbol according to it's real borders?
Intended to be used with a fixed font.
Thanks in advance!
A: You can make its line-height smaller than 1, like .5 or something (experiment a bit).
As for the clip property, it only works if the element is absolutely positioned.
A: as it's a symbol, its different depending on the font you're using. the easiest way would be to just search for and choose a font where there's no (or less) whitespace or play around and try this on your own.
EDIT:
at least, it might be easier to use an icon, even for such a simple symbol. if you want to keep it simple, thera are a lot of free B/W icon-sets out there in the www.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515304",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is it normal to throw an exception over soap webservice server to the client? I am writing a webservice server (c# soap) to my system and I wonder if it is ok to throw new RequestDataNotValidException("Email not valid") to the client?
*
*I know that c# and java clients will handle it very good, but PHP for example will not know how to catch this exception, should i?
*if so, is it acceptable to throw exception on data validation problem?
Thanks
A: Exceptions in SOAP are more or less handled using SOAP faults. In principle fault is just an alternative response message declared explicitly in WSDL. Faults are part of the SOAP messaging protocol and every SOAP-compliant client should handle them in some way.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515306",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What happens when new ClassName() is called..? I know that in simple words an Object is created. But i will better make it clear it with a scenario,
class A {
public A(String path){
}
}
class AB extends A{
public AB(String path){
super(path);
}
}
class B{
public void foo(){
AB a = new AB("myPath");
// now will constructor of class AB will run on another instance of
// AB or is there any other way "a" constructed.
}
}
I'm asking this because if constructor runs on another instance (in this case AB), then who will give it the String path required (and after all no default constructor is allowed here.)
A: There is no "another instance" in this code; there's just the one.
new AB("myPath") calls public AB(String path) which in turn calls public A(String path), all on the same instance.
An instance of AB is-an instance of A, which in turn is-an instance of Object.
A: The constructor will "run on" a newly created instance of AB. A reference to this instance is returned by the new expression and stored as value of a
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515307",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Widget for turning on/off camera flashlight in android I am developing a widget for turning on/off camera led of phone.
I have made a widget that can work like toggle button (on/off).
Behavior is like follows : Sometimes the led light remains on when i enable the widget.
But it doesnot turn on/off the camera led but it changes the icon.
I am not able to figure out whats the actual problem.
The same thing works fine in Activity (Torch Light Application).
Can anyone please explain me how can i solve my problem ?
Where i am going wrong ?
You can look at the code below that i have done so far
onUpdate method
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
//super.onUpdate(context, appWidgetManager, appWidgetIds);
remoteViews = new RemoteViews( context.getPackageName(), R.layout.widgetlayout);
watchWidget = new ComponentName( context, FlashLightWidget.class );
Intent intentClick = new Intent(context,FlashLightWidget.class);
intentClick.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, ""+appWidgetIds[0]);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, appWidgetIds[0],intentClick, 0);
remoteViews.setOnClickPendingIntent(R.id.myToggleWidget, pendingIntent);
appWidgetManager.updateAppWidget( watchWidget, remoteViews );
ctx=context;
}
onReceive method is as follows :
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
remoteViews = new RemoteViews( context.getPackageName(), R.layout.widgetlayout);
if (intent.getAction()==null) {
Bundle extras = intent.getExtras();
if(extras!=null) {
if(status)
{
status=false;
remoteViews.setImageViewResource(R.id.myToggleWidget, R.drawable.shutdown1);
processOnClick();
Toast.makeText(context,"Status==false-onclick",Toast.LENGTH_SHORT).show();
}
else
{
status = true;
remoteViews.setImageViewResource(R.id.myToggleWidget, R.drawable.shutdown2);
processOffClick();
Toast.makeText(context,"Status==true--Ofclick",Toast.LENGTH_SHORT).show();
}
}
watchWidget = new ComponentName( context, FlashLightWidget.class );
(AppWidgetManager.getInstance(context)).updateAppWidget( watchWidget, remoteViews );
}
}
}
processOffClick method
private void processOffClick() {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.setPreviewCallback(null);
mCamera.release();
mCamera = null;
}
}
processOnClick method
private void processOnClick() {
if(mCamera==null)
{
try {
mCamera = Camera.open();
} catch (Exception e) {
e.printStackTrace();
}
}
if (mCamera != null) {
Parameters params = mCamera.getParameters();
List<String> flashModes = params.getSupportedFlashModes();
if (flashModes == null) {
return;
} else {
params.setFlashMode(Parameters.FLASH_MODE_OFF);
mCamera.setParameters(params);
mCamera.startPreview();
String flashMode = params.getFlashMode();
if (!Parameters.FLASH_MODE_TORCH.equals(flashMode)) {
if (flashModes.contains(Parameters.FLASH_MODE_TORCH)) {
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
mCamera.setParameters(params);
}
}
}
} else if (mCamera == null) {
//Toast.makeText(ctx, "Camera not found", Toast.LENGTH_LONG).show();
return;
}
}
A: The best technique for handling clicks from a RemoteViews is to create a PendingIntent that calls a service, and perform the "stuff" you want in the service, including any additional RemoteViews updates for your widget. You can send along the relevant data in the intent extras. The service calls stopSelf() at the end, so it shuts off.
You cannot maintain any state in an BroadcastReceiver; the system runs those on any available thread, and doesn't maintain any reference to your instance after calling onReceive(). Your mCamera variable is not guaranteed to be maintained between invocations of your BroadcastReceiver.
If you really need to maintain state, you must do it in the service, and don't use stopSelf() (until an appropriate time).
You do not need a UI thread to use the Camera class, unless you are doing image preview, which requires a SurfaceHolder (and implies a UI). You must, however, have an event loop active, or Camera will not post callbacks to you, which is a problem since Camera is primarily asynchronous. You can do this within a service (see HandlerThread) and keep your service running until it's time to release() everything. Whichever thread calls Camera.open() will receive callbacks.
Did everyone actually read the section on App Widgets?
http://developer.android.com/guide/topics/appwidgets/index.html
Using the AppWidgetProvider Class section says pretty much what I am saying here.
A: After a long time, I got free to solve this problem.
Here is what I did.
FlashlightWidgetProvider class :
public class FlashlightWidgetProvider extends AppWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
Intent receiver = new Intent(context, FlashlightWidgetReceiver.class);
receiver.setAction("COM_FLASHLIGHT");
receiver.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, receiver, 0);
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.widget_layout);
views.setOnClickPendingIntent(R.id.button, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds, views);
}
}
and BroadcastReceiver for FlashlightWidgetReceiver :
public class FlashlightWidgetReceiver extends BroadcastReceiver {
private static boolean isLightOn = false;
private static Camera camera;
@Override
public void onReceive(Context context, Intent intent) {
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
if(isLightOn) {
views.setImageViewResource(R.id.button, R.drawable.off);
} else {
views.setImageViewResource(R.id.button, R.drawable.on);
}
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
appWidgetManager.updateAppWidget(new ComponentName(context, FlashlightWidgetProvider.class),
views);
if (isLightOn) {
if (camera != null) {
camera.stopPreview();
camera.release();
camera = null;
isLightOn = false;
}
} else {
// Open the default i.e. the first rear facing camera.
camera = Camera.open();
if(camera == null) {
Toast.makeText(context, R.string.no_camera, Toast.LENGTH_SHORT).show();
} else {
// Set the torch flash mode
Parameters param = camera.getParameters();
param.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
try {
camera.setParameters(param);
camera.startPreview();
isLightOn = true;
} catch (Exception e) {
Toast.makeText(context, R.string.no_flash, Toast.LENGTH_SHORT).show();
}
}
}
}
}
Permission required in Manifest.xml file :
<uses-permission android:name="android.permission.CAMERA"></uses-permission>
Also register receivers in Manifest.xml file :
<receiver android:name=".FlashlightWidgetProvider" android:icon="@drawable/on" android:label="@string/app_name">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data android:name="android.appwidget.provider"
android:resource="@xml/flashlight_appwidget_info" />
</receiver>
<receiver android:name="FlashlightWidgetReceiver">
<intent-filter>
<action android:name="COM_FLASHLIGHT"></action>
</intent-filter>
</receiver>
Important Note : This code works perfect if your phone has FLASH_MODE_TORCH supported.
I have tested in Samsung Galaxy Ace 2.2.1 & 2.3.3. The code is not working because that device has no FLASH_MODE_TORCH.
Works fine in HTC Salsa, Wildfire..
If anyone can test and post results here, it would be best.
A: I had a similar situation where I need to run certain android code on the UI thread ... which is only available in an Activity. My solution - an activity with a completely transparent layout. So you just see your home screen (albeit unresponsive) while you complete your actions, which in your case should be pretty quick.
A: I have one solution that is not great but works. Have the widget call an Activity, and in the Activity turn the flash on, and later close the Activity. The same to turn it off. If this works in the Activity then this solution will work. It's not elegant but works. I tried it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515309",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "37"
} |
Q: ZipArchive::filename, how is it supposed to work? I thought ZipArchive::filename would represent the path to the actual zip file, but for every zip file I open with ZipArchive::open(), ZipArchive::filename gives me an empty string.
Example:
$zip = new ZipArchive();
$zip->open( '/some/path/to/zipfile.zip' );
var_dump( $zip->filename );
// expecting:
string(25) "/some/path/to/zipfile.zip"
// but getting:
string(0) ""
Am I misunderstanding ZipArchive::filename, or using it incorrectly perhaps?
Using PHP 5.2.6 on Apache, Windows XP here.
A: in the changelog for 5.2.9 "Fixed zip filename property read."
try updating your php version
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515318",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Fire Parent event based upon child control event in WPF I have a user control that contains button as follows
<UserControl x:Class="MyNamespace.myuseercontrol>
<Button Name="uxRemove" Grid.Row="2" Grid.Column="5" VerticalAlignment="Center"
HorizontalAlignment="Right" Width="70" Content="Remove"
Click="uxRemove_Click"/>
</UserControl>
the main window is as follows:
<Window>
<stackpanel>
<local:MyUserControl x:Name="uxPanel1" />
</stackpanel>
</Window>
Requirements:
*
*I'd like to fire an event on the parent window when the event uxRemove_Click is fired at the usercontrl.
*I'd like to add property Isenabled to the stackpanel "Usercontrol container" that will be based upon My usercontrol.IsEnabled property.
A: The MDI-style solution may be a bit overcomplicated for what you are doing.
There is an example of raising events from child controls to a parent window here.
This is the basic gist:
*
*Declare a custom event type and a way to register handlers
*Raise the event in the child control wherever you need to
*Have a handler on the parent window that listens for the event
This is a much simpler solution for you than implementing an MDI style WPF application.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515325",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: NSmutableArray with dictionnarie value how to count specif value? I have a mutablearray with dictionnairies. i would like to count how many dictionnary have a specific value ?
NSDictionary *question = [self.tabQuestionnaire objectAtIndex:indexPath.row];
[question objectForKey:@"theme"]
A: -(NSInteger)countValue:( NSString * )value forKey: ( NSString * )key{
NSInteger result=0;
for (NSDictionary *question in self.tabQuestionnaire){
if ([value isEqualToString: [question objectForKey:key]]){
result++;
}
return result;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515331",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Enable auto-complete in Emacs minibuffer I'm trying to turn auto-complete in the minibuffer:
(add-hook 'minibuffer-setup-hook 'auto-complete-mode)
What I get is auto-complete working in the first instance of minibuffer, but no longer. That is the full minibuffer-setup-hook after loading:
(auto-complete-mode turn-on-visual-line-mode ido-minibuffer-setup rfn-eshadow-setup-minibuffer minibuffer-history-isearch-setup minibuffer-history-initialize)
How to turn auto-complete on persistently?
A: You rarely ever want to add a function symbol to a hook variable if that function acts as a toggle (which will be the case for most minor modes).
minibuffer-setup-hook runs "just after entry to minibuffer", which means that you would be enabling auto complete mode the first time you enter the minibuffer; disabling it the second time; enabling it the third time; etc...
Typically you would either look to see if there's a pre-defined turn-on-autocomplete-mode type of function, or define your own:
(defun my-turn-on-auto-complete-mode ()
(auto-complete-mode 1)) ;; an argument of 1 will enable most modes
(add-hook 'minibuffer-setup-hook 'my-turn-on-auto-complete-mode)
I can't test that, because you haven't linked to the autocomplete-mode you are using.
A: The creator of "auto-complete-mode" explicitly excludes the minibuffer for use with auto completion. The definition for the minor mode is:
(define-global-minor-mode global-auto-complete-mode
auto-complete-mode auto-complete-mode-maybe
:group 'auto-complete)
so the "turn mode on" function is "auto-complete-mode-maybe" - the definition of that function is:
(defun auto-complete-mode-maybe ()
"What buffer `auto-complete-mode' prefers."
(if (and (not (minibufferp (current-buffer)))
(memq major-mode ac-modes))
(auto-complete-mode 1)))
This function explicitly tests in the if statement if the current-buffer is the minibuffer and doesn't turn on the auto-complete-mode if it is.
If you want to use auto-complete-mode in the minibuffer, you should probably contact the maintainer of the mode and ask him why he excluded the minibuffer and what programming changes he feels are necessary to enable the mode in the minibuffer.
A: Zev called to my attention auto-complete-mode-maybe, and that is the required modifications (file auto-complete.el, all changes have comments):
;; Add this variable
(defcustom ac-in-minibuffer t
"Non-nil means expand in minibuffer."
:type 'boolean
:group 'auto-complete)
...
(defun ac-handle-post-command ()
(condition-case var
(when (and ac-triggered
(not (ido-active)) ;; Disable auto pop-up in ido mode
(or ac-auto-start
ac-completing)
(not isearch-mode))
(setq ac-last-point (point))
(ac-start :requires (unless ac-completing ac-auto-start))
(ac-inline-update))
(error (ac-error var))))
...
(defun auto-complete-mode-maybe ()
"What buffer `auto-complete-mode' prefers."
(if (or (and (minibufferp (current-buffer)) ac-in-minibuffer) ;; Changed
(memq major-mode ac-modes))
(auto-complete-mode 1)))
And .emacs:
(add-hook 'minibuffer-setup-hook 'auto-complete-mode)
Certainly, there are binding conflicts but it is possible to solve them.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515340",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: C# - How to generate a list of file names and sub directories in a directory with creation date I am trying to generate a list of all the files present in a directory and its sub-directories along with their creation date. The date and file name to be separated by "::"
I tried the below code but its taking time when the number of files are huge. Can anyone suggest me a better approach/ optimise the code??
I am even getting the "Access to the file denied" exception with the below approach, for some of the files in C Drive.
DirectoryInfo dir1 = new DirectoryInfo(path);
DirectoryInfo[] dir = dir1.GetDirectories();
StreamWriter write = new StreamWriter("Test.lst");
foreach (DirectoryInfo di in dir)
{
try
{
FileInfo[] file = di.GetFiles("*", SearchOption.AllDirectories);
foreach (var f in file)
{
write.WriteLine(f.FullName + "::" + f.CreationTime.ToShortDateString());
}
}
catch
{
}
}
write.Flush();
write.Close();
A: var dirinfo = new DirectoryInfo( "c:\path" );
var entries = dirinfo.GetFileSystemInfos( "*.*", SearchOption.AllDirectories )
.Select( t => string.Format( "{0}::{1}", t.FullName, t.CreationTime );
A: Or when you're just lookin for the path you can do
Directory.GetFiles("C:\\", "*", SearchOption.AllDirectories)
.ToList()
.ForEach(Console.WriteLine);
A: You really should use the new EnumerateFiles overloads in order to avoid getting the entire list in memory.
foreach (var f in di.EnumerateFiles("*", SearchOption.AllDirectories)) {
write.WriteLine(f.FullName + "::" + f.CreationTime.ToShortDateString());
}
You can further optimize your code by writing each line as it is enumerated over. You can avoid the stream manipulation all together. Your entire routine becomes just a few lines:
public static void GenerateList(String dirPath, String fileName) {
var dir1 = new DirectoryInfo(dirPath);
try {
var lines = from f in dir1.EnumerateFileSystemInfos("*", SearchOption.AllDirectories)
select f.FullName + "::" + f.CreationTime.ToShortDateString();
File.WriteAllLines(fileName, lines);
}
catch (Exception ex) {
Console.WriteLine(ex);
}
}
UPDATE
Ok, so not having .Net 4.0 is a bummer. However, you could write your own class to enumerate a file system without too much trouble. Here is one I just wrote that you can play with, and it only uses API calls that are already available to .Net 3.5
public class FileSystemInfoEnumerator: IEnumerator<FileSystemInfo>, IEnumerable<FileSystemInfo> {
private const string DefaultSearchPattern = "*.*";
private String InitialPath { get; set; }
private String SearchPattern { get; set; }
private SearchOption SearchOptions { get; set; }
private Stack<IEnumerator<FileSystemInfo>> EnumeratorStack { get; set; }
private Action<Exception> ErrorHandler { get; set; }
public FileSystemInfoEnumerator(String path, String pattern = DefaultSearchPattern, SearchOption searchOption = SearchOption.TopDirectoryOnly, Action<Exception> errorHandler = null) {
if (String.IsNullOrWhiteSpace(path))
throw new ArgumentException("path cannot be null or empty");
var dirInfo = new DirectoryInfo(path);
if(!dirInfo.Exists)
throw new InvalidOperationException(String.Format("File or Directory \"{0}\" does not exist", dirInfo.FullName));
InitialPath = dirInfo.FullName;
SearchOptions = searchOption;
if(String.IsNullOrWhiteSpace(pattern)) {
pattern = DefaultSearchPattern;
}
ErrorHandler = errorHandler ?? DefaultErrorHandler;
EnumeratorStack = new Stack<IEnumerator<FileSystemInfo>>();
SearchPattern = pattern;
EnumeratorStack.Push(GetDirectoryEnumerator(new DirectoryInfo(InitialPath)));
}
private void DefaultErrorHandler(Exception ex) {
throw ex;
}
private IEnumerator<FileSystemInfo> GetDirectoryEnumerator(DirectoryInfo directoryInfo) {
var infos = new List<FileSystemInfo>();
try {
if (directoryInfo != null) {
var info = directoryInfo.GetFileSystemInfos(SearchPattern);
infos.AddRange(info);
}
} catch (Exception ex) {
ErrorHandler(ex);
}
return infos.GetEnumerator();
}
public void Dispose() {
foreach (var enumerator in EnumeratorStack) {
enumerator.Reset();
enumerator.Dispose();
}
}
public bool MoveNext() {
var current = Current;
if (ShouldRecurse(current)) {
EnumeratorStack.Push(GetDirectoryEnumerator(current as DirectoryInfo));
}
var moveNextSuccess = TopEnumerator.MoveNext();
while(!moveNextSuccess && TopEnumerator != null) {
EnumeratorStack.Pop();
moveNextSuccess = TopEnumerator != null && TopEnumerator.MoveNext();
}
return moveNextSuccess;
}
public void Reset() {
EnumeratorStack.Clear();
EnumeratorStack.Push(GetDirectoryEnumerator(new DirectoryInfo(InitialPath)));
}
public FileSystemInfo Current {
get {
return TopEnumerator.Current;
}
}
object IEnumerator.Current {
get {
return Current;
}
}
public IEnumerator<FileSystemInfo> GetEnumerator() {
return this;
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
IEnumerator<FileSystemInfo> TopEnumerator {
get {
if(EnumeratorStack.Count > 0)
return EnumeratorStack.Peek();
return null;
}
}
private Boolean ShouldRecurse(FileSystemInfo current) {
return current != null &&
IsDirectory(current) &&
SearchOptions == SearchOption.AllDirectories;
}
private Boolean IsDirectory(FileSystemInfo fileSystemInfo) {
return fileSystemInfo != null &&
(fileSystemInfo.Attributes & FileAttributes.Directory) == FileAttributes.Directory;
}
}
Using it is pretty easy, just instantiate it with the options you want, and then use it like any IEnumerable.
var fileSystemEnumerator = new FileSystemInfoEnumerator("C:\\Dir",
searchOption: SearchOption.AllDirectories,
errorHandler: Console.WriteLine);
var lines = from f in fileSystemEnumerator
select f.FullName + "::" + f.CreationTime.ToShortDateString();
File.WriteAllLines("FileNames.txt", lines);
Now obviously this isn't as efficient as the .Net 4.0 one, but the memory footprint should be acceptable. I tested this on a directory with 50K+ files and it finished in about 5 seconds.
Hope this helps you out!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How can I connect to sftp using linux command from Perl #!/usr/local/bin/perl
use strict;
use warnings;
system("cd $PATH
/usr/bin/sftp mysite.com <<!EOF
put sample.txt
bye
!EPF");
When i complile tha application, it asking the pasword,
how to pass the user/password in the code itself,
what i want is, my script should not ask the password. i want to set the user/password in the code itself.
user command not working in sftp
How to make it.
A: With such a vague question its hard to give more of an answer…
Have you tried the Net::SFTP module?
EDIT:
Based on the edit to the question - try using Net::SFTP::Foreign
use Net::SFTP::Foreign;
use warnings;
use strict;
my $host = "xxx.xxx.xxx.xxx";
my $sftp = Net::SFTP::Foreign->new($host, user => 'user', password => 'pass');
$sftp->error and die "Something bad happened: " . $sftp->error;
$sftp->put("sample.txt", "/home/test/test") or die "put failed: " . $sftp->error;
You should get a more meaningful error message and you can take it from there.
A: You can try other modules, e.g Net::SFTP::Foreign or the SFTP functionality of Net::SSH2.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515348",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Glassfish Java error when deploying WAR I have two Java SDKs installed. How do I find out which one Glassfishv3 is using? I am getting several Java EE errors when I try to deploy WAR files.
Below is an example of an error when I try deploying a WAR:
Error occurred during deployment: Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.liferay.portal.spring.aop.ServiceBeanAutoProxyCreator#0' defined in class path resource [META-INF/base-spring.xml]:
A: Try putting this in your application somewhere, log (or otherwise get access to) the result:
System.out.println(System.getProperty("java.version"));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515351",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Configuring Keystore/Truststore for 2-way SSL Java RMI in sandbox started from javaws I'm trying to configure a Client/Server app after setting up 2-way SSL using the java SSLRMIClientSocketFactory and SSLRMIServerSocketFactory. I know that to set the keystore and truststore on the client I need to set -Djavax.net.ssl.trustStore and -Djavax.net.sslkeyStore.
The way I understand it Java web start downloads the jnlp and verifies the jar and launches the Client java application in a sandbox that then connects to the server application over RMI. The problem is that when the application is run in this sandbox, the default truststore and keystore is not the same as what java web start uses. Instead there is no default keystore and the default truststore is $JAVA_HOME/jre/lib/security/cacerts
Is there a way to use the same truststore and keystore that javaws uses? Ideally I would like to use the same trusted certs and client certs that the browser uses (and by extension javaws). This way If the users configure their certificate through the Java Control Panel, then the application will use the same certificates.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515353",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Optimal performing query for latest record for each N Here is the scenario I find myself in.
I have a reasonably big table that I need to query the latest records from. Here is the create for the essential columns for the query:
CREATE TABLE [dbo].[ChannelValue](
[ID] [bigint] IDENTITY(1,1) NOT NULL,
[UpdateRecord] [bit] NOT NULL,
[VehicleID] [int] NOT NULL,
[UnitID] [int] NOT NULL,
[RecordInsert] [datetime] NOT NULL,
[TimeStamp] [datetime] NOT NULL
) ON [PRIMARY]
GO
The ID column is a Primary Key and there is a non-Clustered index on VehicleID and TimeStamp
CREATE NONCLUSTERED INDEX [IX_ChannelValue_TimeStamp_VehicleID] ON [dbo].[ChannelValue]
(
[TimeStamp] ASC,
[VehicleID] ASC
)ON [PRIMARY]
GO
The table I'm working on to optimise my query is a little over 23 million rows and is only a 10th of the sizes the query needs to operate against.
I need to return the latest row for each VehicleID.
I've been looking through the responses to this question here on StackOverflow and I've done a fair bit of Googling and there seem to be 3 or 4 common ways of doing this on SQL Server 2005 and upwards.
So far the fastest method I've found is the following query:
SELECT cv.*
FROM ChannelValue cv
WHERE cv.TimeStamp = (
SELECT
MAX(TimeStamp)
FROM ChannelValue
WHERE ChannelValue.VehicleID = cv.VehicleID
)
With the current amount of data in the table it takes about 6s to execute which is within reasonable limits but with the amount of data the table will contain in the live environment the query begins to perform too slow.
Looking at the execution plan my concern is around what SQL Server is doing to return the rows.
I cannot post the execution plan image because my Reputation isn't high enough but the index scan is parsing every single row within the table which is slowing the query down so much.
I've tried rewriting the query with several different methods including using the SQL 2005 Partition method like this:
WITH cte
AS (
SELECT *,
ROW_NUMBER() OVER(PARTITION BY VehicleID ORDER BY TimeStamp DESC) AS seq
FROM ChannelValue
)
SELECT
VehicleID,
TimeStamp,
Col1
FROM cte
WHERE seq = 1
But the performance of that query is even worse by quite a large magnitude.
I've tried re-structuring the query like this but the result speed and query execution plan is nearly identical:
SELECT cv.*
FROM (
SELECT VehicleID
,MAX(TimeStamp) AS [TimeStamp]
FROM ChannelValue
GROUP BY VehicleID
) AS [q]
INNER JOIN ChannelValue cv
ON cv.VehicleID = q.VehicleID
AND cv.TimeStamp = q.TimeStamp
I have some flexibility available to me around the table structure (although to a limited degree) so I can add indexes, indexed views and so forth or even additional tables to the database.
I would greatly appreciate any help at all here.
Edit Added the link to the execution plan image.
A: Depends on your data (how many rows are there per group?) and your indexes.
See Optimizing TOP N Per Group Queries for some performance comparisons of 3 approaches.
In your case with millions of rows for only a small number of Vehicles I would add an index on VehicleID, Timestamp and do
SELECT CA.*
FROM Vehicles V
CROSS APPLY (SELECT TOP 1 *
FROM ChannelValue CV
WHERE CV.VehicleID = V.VehicleID
ORDER BY TimeStamp DESC) CA
A: If your records are inserted sequentially, replacing TimeStamp in your query with ID may make a difference.
As a side note, how many records is this returning? Your delay could be network overhead if you are getting hundreds of thousands of rows back.
A: Try this:
SELECT SequencedChannelValue.* -- Specify only the columns you need, exclude the SequencedChannelValue
FROM
(
SELECT
ChannelValue.*, -- Specify only the columns you need
SeqValue = ROW_NUMBER() OVER(PARTITION BY VehicleID ORDER BY TimeStamp DESC)
FROM ChannelValue
) AS SequencedChannelValue
WHERE SequencedChannelValue.SeqValue = 1
A table or index scan is expected, because you're not filtering data in any way. You're asking for the latest TimeStamp for all VehicleIDs - the query engine HAS to look at every row to find the latest TimeStamp.
You can help it out by narrowing the number of columns being returned (don't use SELECT *), and by providing an index that consists of VehicleID + TimeStamp.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515354",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: SlickGrid Columns - Difference between id and field A simple question i cant workout. In a column definition whats the difference between the field property and the id property...Fx..
columns.push({ id: "officeId", name: "Office Id", field: "officeId", width: 40 });
When would they be different/why two?
Thanks?
Tim
A: The id is just a unique identifier for the column. You can set it to anything you want. It's only use is to provide an identifier when you want to refer to your columns from code.
The field specifies how the column binds to the underlying data. Suppose your data looks like this:
data = [
{ firstName: "John", lastName: "Smith" },
{ firstName: "Fred", lastName: "Jones" }
];
When you define the column you can tell it which value you want to display from your data array.
columns.push({ id: "anythingyoulike", name: "Surname", field: "lastName", width: 40 });
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515355",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: In cassandra 0.8.2 sstableleader how to use -i or --ignore option? I am trying to load sstable with cassandra utility sstableloader
But they suggested running this with the -i or --ignore option to avoid some nodes.
While trying this option, I am getting a too many arguments error; has anybody tried this?
A: It's a bug (CASSANDRA-3247), sorry. It will be fixed for the 0.8.7 release and the upcoming 1.0.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515357",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Bindings not applied to dynamically-loaded xaml I'm using XamlReader successfully to load a xaml file and create a FrameworkElement to work with.
The xaml I'm loading has binding expressions in it such as:
<TextBlock Text="{Binding DataContextTextProperty}" />
If I place the FrameworkElement I get back from XamlReader.Load() into a WPF window, the binding all works fine.
However, in this case I'm using Laurent Bugnion's excellent article on creating PNGs from WPF/XAML. Since the result of XamlReader.Load() is written directly to a PNG via a VisualBrush, it seems the necessary mechanics of WPF to invoke binding expressions are bypassed.
This leads me to believe that the actual bindings aren't really being invoked just by calling XamlReader.Load(), or that they're not working because of something I don't know about to do with there not being a visual tree until you add the FrameworkElement to an existing visual tree or something.
Is there something I can do to ensure these bindings are invoked?
Many thanks in advance.
A: I FIXED IT!!
Ahem, allow me to explain...
I have no idea how I got to it now, but I found a helpful-sounding article on MSDN regarding Initialization for Objects Not in an Object Tree.
In it I found the following code example:
Button b = new Button();
b.BeginInit();
b.Background = Brushes.Blue;
b.Width = b.Height = 200;
b.EndInit();
b.Measure(paperSize);
b.Arrange(new Rect(paperSize));
b.UpdateLayout();
I looked at the (again, excellent) example from Laurent that I mentioned in the question above, and customised the use of XamlReader as follows:
var element = (FrameworkElement)XamlReader.Load(xamlInput);
element.BeginInit();
element.DataContext = dataContext;
...
element.Measure(renderingSize);
element.Arrange(renderingRectangle);
element.EndInit();
element.UpdateLayout();
I added the BeginInit(), EndInit() and UpdateLayout() (though by process of elimination I believe UpdateLayout() is the key) and now the binding expressions in my dynamically-loaded xaml are working correctly. Hurrah!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515360",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Jquery trigger key.Code event how to trigger keyboard specif key.Code event with jQuery?
I woul like to trigger specifically backspace keyboard event
A: var e = jQuery.Event("keydown");
e.which = 8; // some value (backspace = 8)
$("input").trigger(e);
A: <body onkeydown="return inspectKeyCode(event);">
function inspectKeyCode(event)
{
if(event.keyCode == 8){
//Do whatever
//For disabling return false;
}
}
By this you can cancel the backspace button.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515364",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: TapRecognizer in View and Scrollview (to drag and drop images in a view) Iphone-I created a view and a scrollview. The scrollbiew have images inside their view. I'd like to implement a method which makes it possible for the user to drag images on a view from scrollview list?
plz help me!
A: There is a very good example how to do it:
ScrollViewSuite
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515365",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android: How to set checked boxes when using CHOICE_MODE_NONE I have a listview with checkboxes that has type CHOICE_MODE_NONE, because I want to make each item tri-state.
It works fine using setChecked in onItemClick, to check and uncheck the items as required.
But when starting up the view, I want to set some items. The problem is that setItemChecked is only valid if CHOICE_MODE_SINGLE or CHOICE_MODE_MULTIPLE.
So how do I check an item?
I tried the following, but ck is null:
int totalItems = getListView().getCount();
if (totalItems > 0)
{
for (int position=0; position<totalItems; position++)
{
CheckedTextView ck = (CheckedTextView)(lv.getChildAt(position));
ck.setChecked(true);
}
}
what am I doing wrong?
A: got it, thanks to http://www.softwarepassion.com/android-series-custom-listview-items-and-adapters/
- overriding the arrayadapter gave me access to the view of each item on the list.
So I was able to write:
@Override
public View getView(int position, View v, ViewGroup parent)
{
if (v == null)
{
v = super.getView(position, v, parent);
}
CheckedTextView tv = (CheckedTextView) v;
tv.setChecked(passengers.get(position).isPassengerOnBoard());
return v;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515366",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to capture camera devices on Windows using Libav? Is there any way to capture frames from as many camera types as DirectShow do on Windows platform using Libav? I need to capture a camera output without using DirectShow filters and I want my application to work with many camera devices types.
I have searched the Internet about this capability of libav and found that it can be done via libav using special input format "vfwcap". Something like that (don't sure about code correctness - I wrote it by myself):
AVFormatParameters formatParams = NULL;
AVInputFormat* pInfmt = NULL;
pInFormatCtx* pInFormatCtx = NULL;
av_register_all();
//formatParams.device = NULL; //this was probably deprecated and then removed
formatParams.channel = 0;
formatParams.standard = "ntsc"; //deprecated too but still available
formatParams.width = 640;
formatParams.height = 480;
formatParams.time_base.num = 1000;
formatParams.time_base.den = 30000; //so we want 30000/1000 = 30 frames per second
formatParams.prealloced_context = 0;
pInfmt = av_find_input_format("vfwcap");
if( !pInfmt )
{
fprintf(stderr,"Unknown input format\n");
return -1;
}
// Open video file (formatParams can be NULL for autodetecting probably)
if (av_open_input_file(&pInFormatCtx, 0, pInfmt, 0, formatParams) < 0)
return -1; // Couldn't open device
/* Same as video4linux code*/
So another question is: how many devices are supported by Libav? All I have found about capture cameras output with libav on windows is advice to use DirectShow for this purpose because libav supports too few devices. Maybe situation has already changed now and it does support enough devices to use it in production applications?
If this isn't possible.. Well I hope my question won't be useless and this composed from different sources piece of code will help someone interested in this theme 'coz there are really too few information about it in the whole internet.
A: FFMPEG cannot capture video on Windows. Once I had to implement this myself, using DirectShow capturing
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515369",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Adding value to list stored in session and then using as datasource for repeater I have two repeaters on my page. The first repeater has a LinkButton in it, with a commandname and commandarguement. When the linkbutton is clicked the value of commandarguement is supposed to be stored in a Session containing List. Then I use the value of Session List to bind the second repeater.
I am having two problems:
1) I am binding the second repeater in the OnInit event. The event handler that is executed when the LinkButton in the first repeater is executed AFTER the init event - therefore when data binding takes place the new value has not been added to the session yet. I can't bind the data any later than the init event because the controls within the second repeater need to be maintained using viewstate (or other).
2) In the second repeater there are two dropdownlists. Both are databound in the repeaters itemdatabound event. When the first DDL is changed, I need to filter the values in the second DDL. But this just isnt happening.
For the purposes of a clearer example, I have stripped the code out of my application and created a very simple aspx page - all of the code is below. Thanks to Bobby who has already helped with this.
Really hope someone can help as I am stumped!
Markup:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Repeater-Viewstate.aspx.cs" Inherits="test_Repeater_Viewstate" ViewStateMode="Enabled" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>Repeater Test</h1>
<h2>Repeater 1</h2>
<asp:Repeater runat="server" Visible="true" ID="rptListItems">
<ItemTemplate>
Image ID: <asp:Literal ID="ImageID" runat="server" />
<asp:LinkButton runat="server" CommandName="SelectImage" Text="Add to list" ID="AddToListCommand" />
<hr />
</ItemTemplate>
</asp:Repeater>
<h2>Repeater 2</h2>
<asp:Repeater runat="server" Visible="true" ID="rptSelectedItems" ViewStateMode="Enabled">
<ItemTemplate>
The value of the item you selected is: <asp:TextBox runat="server" ID="ImageIDInput"/>
<asp:DropDownList runat="server" ID="OptionsInput" AppendDataBoundItems="true" AutoPostBack="true" >
<asp:ListItem Text="Please choose..." Value="0" />
</asp:DropDownList>
<asp:DropDownList runat="server" ID="AttributesInput" runat="server" AppendDataBoundItems="true">
<asp:ListItem Text="Please choose..." Value="0" />
</asp:DropDownList>
<hr style="clear: both;" />
</ItemTemplate>
</asp:Repeater>
<asp:Button runat="server" Text="Postback" />
</div>
</form>
</body>
</html>
Code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class test_Repeater_Viewstate : System.Web.UI.Page
{
//DUMMY Data for 1st Repeater
public class MyRepeaterDataSource {
public int ID { get; set; }
public string Title { get; set; }
}
private List<MyRepeaterDataSource> _items;
public List<MyRepeaterDataSource> Items {
get {
if (_items == null)
_items = new List<MyRepeaterDataSource>();
return _items;
}
set {
_items = value;
}
}
//END dummy data
//DUMMY data for 1st dropdownlist in second repeater
public class FirstDDLClass {
public int ID { get; set; }
public string Title { get; set; }
}
private List<FirstDDLClass> _firstDDLItems;
public List<FirstDDLClass> FirstDDLItems {
get {
if (_firstDDLItems == null)
_firstDDLItems = new List<FirstDDLClass>();
return _firstDDLItems;
}
set {
_firstDDLItems = value;
}
}
//DUMMY data for 2nd dropdownlist in second repeater
public class SecondDDLClass {
public int ID { get; set; }
public int ForeignKey { get; set; }
public string Title { get; set; }
}
private List<SecondDDLClass> _secondDDLItems;
public List<SecondDDLClass> SecondDDLItems {
get {
if (_secondDDLItems == null)
_secondDDLItems = new List<SecondDDLClass>();
return _secondDDLItems;
}
set {
_secondDDLItems = value;
}
}
public List<string> SelectedItems {
get {
if (Session["SelectedItems"] == null)
Session["SelectedItems"] = new List<string>();
return (List<string>)(Session["SelectedItems"]);
}
set {
Session["SelectedItems"] = value;
}
}
protected override void OnInit(EventArgs e) {
//register events
this.rptListItems.ItemDataBound += new RepeaterItemEventHandler(rptListItems_ItemDataBound);
this.rptListItems.ItemCommand += new RepeaterCommandEventHandler(rptListItems_ItemCommand);
this.rptSelectedItems.ItemDataBound += new RepeaterItemEventHandler(rptSelectedItems_ItemDataBound);
//create a dummy list to populate first repeater
MyRepeaterDataSource dataSource1 = new MyRepeaterDataSource();
dataSource1.ID = 1;
dataSource1.Title = "Item 1";
Items.Add(dataSource1);
MyRepeaterDataSource dataSource2 = new MyRepeaterDataSource();
dataSource2.ID = 2;
dataSource2.Title = "Item 2";
Items.Add(dataSource2);
MyRepeaterDataSource dataSource3 = new MyRepeaterDataSource();
dataSource3.ID = 3;
dataSource3.Title = "Item 3";
Items.Add(dataSource3);
MyRepeaterDataSource dataSource4 = new MyRepeaterDataSource();
dataSource4.ID = 4;
dataSource4.Title = "Item 4";
Items.Add(dataSource4);
//create a dummy list to populate the first dropdownlist in the second repeater
FirstDDLClass class1 = new FirstDDLClass();
class1.ID = 1;
class1.Title = "Option 1";
FirstDDLItems.Add(class1);
FirstDDLClass class2 = new FirstDDLClass();
class2.ID = 2;
class2.Title = "Option 2";
FirstDDLItems.Add(class2);
//create a dummy list to populate the second dropdownlist in the second repeater
SecondDDLClass class3 = new SecondDDLClass();
class3.ID = 1;
class3.ForeignKey = 1;
class3.Title = "Attribute 1";
SecondDDLItems.Add(class3);
SecondDDLClass class4 = new SecondDDLClass();
class4.ID = 1;
class4.ForeignKey = 1;
class4.Title = "Attribute 2";
SecondDDLItems.Add(class4);
SecondDDLClass class5 = new SecondDDLClass();
class5.ID = 1;
class5.ForeignKey = 2;
class5.Title = "Attribute 3";
SecondDDLItems.Add(class5);
if (!this.Page.IsPostBack) {
//bind 1st repeater
this.rptListItems.DataSource = Items;
this.rptListItems.DataBind();
}
//bind second repeater
this.rptSelectedItems.DataSource = SelectedItems;
this.rptSelectedItems.DataBind();
base.OnInit(e);
}
protected void Page_Load(object sender, EventArgs e)
{
}
void rptListItems_ItemDataBound(object sender, RepeaterItemEventArgs e) {
Literal imageIDLiteral = e.Item.FindControl("ImageID") as Literal;
if (imageIDLiteral is Literal) {
imageIDLiteral.Text = DataBinder.Eval(e.Item.DataItem, "ID").ToString();
}
LinkButton linkButton = e.Item.FindControl("AddToListCommand") as LinkButton;
if (linkButton is LinkButton) {
linkButton.CommandArgument = DataBinder.Eval(e.Item.DataItem, "ID").ToString();
}
}
void rptListItems_ItemCommand(object source, RepeaterCommandEventArgs e) {
switch (e.CommandName) {
case "SelectImage":
this.SelectedItems.Add(e.CommandArgument.ToString());
break;
}
}
void rptSelectedItems_ItemDataBound(object sender, RepeaterItemEventArgs e) {
switch (e.Item.ItemType) {
case ListItemType.AlternatingItem:
case ListItemType.Item:
TextBox textBox = e.Item.FindControl("ImageIDInput") as TextBox;
if (textBox is TextBox) {
textBox.Text = e.Item.DataItem.ToString();
}
DropDownList ddl1 = e.Item.FindControl("OptionsInput") as DropDownList;
if (ddl1 is DropDownList) {
ddl1.DataValueField = "ID";
ddl1.DataTextField = "Title";
ddl1.DataSource = this.FirstDDLItems;
ddl1.DataBind();
}
DropDownList ddl2 = e.Item.FindControl("AttributesInput") as DropDownList;
if (ddl2 is DropDownList) {
ddl2.DataValueField = "ID";
ddl2.DataTextField = "Title";
if (ddl1.SelectedIndex != 0) {
ddl2.DataSource = this.SecondDDLItems.Where(f => f.ForeignKey == Convert.ToInt32(ddl1.SelectedValue));
ddl2.DataBind();
}
}
break;
}
}
}
Thanks in advance guys
Al
A: If you add the following code:
protected void OptionsInput_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList optionsInput = sender as DropDownList;
DropDownList ddl2 = optionsInput.Parent.FindControl("AttributesInput") as DropDownList;
if (ddl2 is DropDownList)
{
ddl2.DataValueField = "ID";
ddl2.DataTextField = "Title";
if (optionsInput.SelectedIndex != 0)
{
ddl2.DataSource = this.SecondDDLItems.Where(f => f.ForeignKey == Convert.ToInt32(optionsInput.SelectedValue));
ddl2.DataBind();
}
}
}
And the following markup:
<asp:DropDownList runat="server" ID="OptionsInput" AppendDataBoundItems="true" AutoPostBack="true" OnSelectedIndexChanged="OptionsInput_SelectedIndexChanged" >
(Specifically, adding the OnSelectedIndexChanged="OptionsInput_SelectedIndexChanged")
It worked for me.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515371",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: How to sort an array with numbers in iphone? I need your help. I have stored selected indexpath values in an NSMutableArray from UITableView. I have stored these values in NSString type and i want to retrieve like NSString to int datatype. But, I want to sort this array by (0,1,2,3,4,5,6,7,8,9,10,11,12,13....)this way. Currently am getting by this format(0,1,10,11,12,2,3,4,5,6,7,8,9..) I dont know how to sort this array? Please any one help me friends? Thanks for spending your valuable time with me and read my poor english.
Thanks is advance.
A: Let' say your mutable array is called "myArray". Then you cannot simply sort its content using string comparator but you must convert strings to decimals and use the values to sort.
So the sorting call will be, using blocks:
[myArray sortUsingComparator: ^(id obj1, id obj2) {
if ([obj1 integerValue] > [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedDescending;
}
if ([obj1 integerValue] < [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515374",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: accessing/handling bluetooth wireless keboard input(key press) in my ipad application i have already done much googling on this neither i found a tutorial/way to accomplish this nor find that it could not be acheived(so that i can assist my client ,it's not possible)
we have requirement to integrate a bluetooth wireless keyboard in our existing ipad application.
some of the scenarios are....
suppose you are having a uibutton on the view.
then according to the requirement if user tap the key "entr/return" on the wireless keyboard
the result is same as tapping the button on view.if user tap the key "i" on the wireless keyboard the result is same as tapping the information button (UIButtonTypeInfoDark) on view.
Means we have to handl wireless keyboard key press events.
any idea/link/tutorial would very helpful for this situation.
thanks!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515375",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Sort a list of nontrivial elements in R In R, I have a list of nontrivial objects (they aren't simple objects like scalars that R can be expected to be able to define an order for). I want to sort the list. Most languages allow the programmer to provide a function or similar that compares a pair of list elements that is passed to a sort function. How can I sort my list?
A: The order function will allow you to determine the sort order for character or numeric aruments and break ties with subsequent arguments. You need to be more specific about what you want. Produce an example of a "non-trivial object" and specify the order you desire in some R object. Lists are probably the most non-vectorial objects:
> slist <- list(cc=list(rr=1), bb=list(ee=2, yy=7), zz="ww")
> slist[order(names(slist))] # alpha order on names()
$bb
$bb$ee
[1] 2
$bb$yy
[1] 7
$cc
$cc$rr
[1] 1
$zz
[1] "ww"
slist[c("zz", "bb", "cc")] # an arbitrary ordering
$zz
[1] "ww"
$bb
$bb$ee
[1] 2
$bb$yy
[1] 7
$cc
$cc$rr
[1] 1
A: To make this is as simple I can, say your objects are lists with two elements, a name and a value. The value is a numeric; that's what we want to sort by. You can imagine having more elements and needing to do something more complex to sort.
The sort help page tells us that sort uses xtfrm; xtfrm in turn tells us it will use == and > methods for the class of x[i].
First I'll define an object that I want to sort:
xx <- lapply(c(3,5,7,2,4), function(i) list(name=LETTERS[i], value=i))
class(xx) <- "myobj"
Now, since xtfrm works on the x[i]'s, I need to define a [ function that returns the desired elements but still with the right class
`[.myobj` <- function(x, i) {
class(x) <- "list"
structure(x[i], class="myobj")
}
Now we need == and > functions for the myobj class; this potentially could be smarter by vectorizing these properly; but for the sort function, we know that we're only going to be passing in myobj's of length 1, so I'll just use the first element to define the relations.
`>.myobj` <- function(e1, e2) {
e1[[1]]$value > e2[[1]]$value
}
`==.myobj` <- function(e1, e2) {
e1[[1]]$value == e2[[1]]$value
}
Now sort just works.
sort(xx)
It might be considered more proper to write a full Ops function for your object; however, to just sort, this seems to be all you need. See p.89-90 in Venables/Ripley for more details about doing this using the S3 style. Also, if you can easily write an xtfrm function for your objects, that would be simpler and most likely faster.
A: One option is to create a xtfrm method for your objects. Functions like order take multiple columns which works in some cases. There are also some specialized functions for specific cases like mixedsort in the gtools package.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515377",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: SharePoint 2010 custom breadcrumb, change only HTML I have a requirement for changing the way bread crumbs looks in sharepoint. Please note that the data source will still be sharepoint but i need to generate the html little differently than the one displayed by sharepoint.
for example, if you are in a custom list,sharepoint displays as site > custom list > all items.
I neeed to display site, custom list and all items (no change in the items that are got from sharepoint). The only change will be, the user interface will be generated with a combination of html ul tags with some custom css?
Can someone suggest me the best approach?
Thanks
A: The visual appearance of the SiteMapPath control that displays a breadcrumb can be modified by setting the attributes of the control or by configuring the templates that are available for the control. I think that the CssClass and NodeTemplate properties is what you need.
*
*How to: Customize the Appearance of SiteMapPath Web Server Controls
*SiteMapPath Properties
*Using a template with the SiteMapPath control
To modify the content of the breadcrumb you need to create a custom site map provider inheriting from SPContentMapProvider.
*
*SharePoint Branding Issues: Breadcrumb
*How to Create custom XMLSiteMapProvider and render it in SharePoint 2007 MOSS
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515381",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: GWT - Unable to find type 'com.myapp.launcher.client.LauncherInitializer' multi-module architecture I have a project with the following structure:
com.myapp.gwt:
Basic.gwt.xml
Launcher.gwt.xml - inherits Basic.gwt.xml
Module1.gwt.xml - inherits Basic.gwt.xml
com.myapp.gwt.ui.basic.client:
AppActivityMapper.java
AppHistoryManager.java
AppPlaceHistoryMapper.java
BasicInitializer.java - this is a daddy class for all entry points
MainClientFactory.java
MainClientFactoryImpl.java
com.myapp.gwt.ui.launcher.client: - all the stuff for the launcher module is here
LauncherInitializer.java (extends BasicInitializer, launcher module's EntryPoint)
com.myapp.gwt.ui.launcher.client.places:
Places and activities for the launcher module
com.myapp.gwt.ui.module1.client: - all the stuff for the module1 module is here
Module1Initializer.java (extends BasicInitializer, module1 module's EntryPoint)
com.myapp.gwt.ui.module1.client.places:
Places and activities for the module1 module
com.myapp.gwt.shared:
Stuff shared between the client and the server (interfaces, dtos)
com.myapp.gwt.server:
Code that works only on the server
what i have in my Basic.gwt.xml is this:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit 2.1.0//EN" "http://google-web-toolkit.googlecode.com/svn/tags/2.3.0/distro-source/core/src/gwt-module.dtd">
<module rename-to='myapp'>
<!-- Inherit the core Web Toolkit stuff. -->
<inherits name='com.google.gwt.user.User' />
<!-- Inherit the default GWT style sheet. You can change -->
<!-- the theme of your GWT application by uncommenting -->
<!-- any one of the following lines. -->
<inherits name='com.google.gwt.user.theme.clean.Clean' />
<inherits name="com.google.gwt.place.Place" />
<inherits name="com.google.gwt.activity.Activity" />
<inherits name="com.google.gwt.editor.Editor" />
<!-- Specify the paths for translatable code -->
<source path='ui.basic.client' />
<source path='shared' />
<replace-with class="com.myapp.gwt.ui.basic.client.ClientFactoryImpl">
<when-type-is class="com.myapp.gwt.ui.basic.client.ClientFactory" />
</replace-with>
<set-configuration-property name="UiBinder.useSafeHtmlTemplates" value="true" />
</module>
what i have in my Launcher.gwt.xml is this:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit 2.1.0//EN" "http://google-web-toolkit.googlecode.com/svn/tags/2.3.0/distro-source/core/src/gwt-module.dtd">
<module rename-to='launcher'>
<!-- Other module inherits -->
<inherits name="com.myapp.gwt.Basic" />
<!-- Specify the paths for translatable code -->
<source path="ui.launcher.client"></source>
<!-- Specify the app entry point class. -->
<entry-point class='com.myapp.gwt.ui.launcher.client.LauncherInitializer' />
</module>
None of my classes residing inside the com.myapp.gwt.ui.basic.client package have reference to any of the classes inside the other module packages. The other module packages on the other hand have lots of references to the basic module and some of the classes even extend the classes inside the basic package.
The problem is that i'm getting this error during compiling to javascript launcher module:
[TRACE] [launcher] - Finding entry point classes
[ERROR] [launcher] - Unable to find type 'com.myapp.gwt.ui.launcher.client.LauncherInitializer'
[ERROR] [launcher] - Hint: Previous compiler errors may have made this type unavailable
[ERROR] [launcher] - Hint: Check the inheritance chain from your module; it may not be inheriting a required module or a module may not be adding its source path entries properly
[ERROR] [launcher] - Failed to load module 'launcher' from user agent 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0' at localhost:61253
Also please tell me if you see something worth changing in the stuff i've done.
A: Just a quick guess: did you try : <source path='ui/basic/client' />
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515382",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Error when removing a TitleWindow via PopUpManager I am having issues to remove a PopUp form my application. In fact I have a title Window with a component in it. In the component I have a Button, which when clicked should remove the TitleWindow (the PopUp). I am getting the error :
TypeError: Error #1009: Cannot access a property or method of a null object reference.
My Title Window is as follows:
<?xml version="1.0" encoding="utf-8"?>
<s:TitleWindow xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" left="10"
width="1366" height="768">
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<fx:Script>
<![CDATA[
import mx.managers.PopUpManager;
public function removeTitleWindow():void {
PopUpManager.removePopUp(this);
}
]]>
</fx:Script>
<s:VGroup width="100%" height="100%" horizontalAlign="left">
<comps:SearchEngine />
<comps:SearchResults />
</s:VGroup>
</s:TitleWindow>
My Component is as follows:
<?xml version="1.0" encoding="utf-8"?>
<s:Group xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" width="400 " height="300">
<fx:Declarations>
</fx:Declarations>
<fx:Script>
<![CDATA[
]]>
</fx:Script>
<s:Button label="Cancel" click="parentApplication.parentApplication.removeTitleWindow()"/>
</s:VGroup>
</s:Group>
Can someone help me on this?
Thanks
A: Got it Mates :)
I tried using parentApplication or rather flexGlobals.top... It didnt work.
Hence I used parentDocument.methodName().
This solved the issue.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515385",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to render reports by code (C#) in CRM 2011 ADFS or Online-deployments? How can I render reports by code (C#) in CRM 2011 ADFS or Online-deployments?
A customer is moving their solution to a "private cloud", that is partner hosted using ADFS 2.0 and claims based authentication only. However, they have an application that each month generate reports for each account and sends this as Excel-attachment to several CRM contacts. The problem now is how to generate the reports automatically by code?
With AD deployment it is possible to contact the Reporting Services-service directly to render reports (to excel, pdf etc). But how can I do this with CRM 2011 and ADFS? It will be possible for me to get access to reporting services through the use of VPN but what about authentication? Also, how would customers that use Microsoft Online solve this?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515387",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Decrypt data only for authorized client I have an asp.net mvc web application with some customers.
A new customer tells me that its data should be crypted on its client and then sent to server (that will store the data into database).
When the client will request the data, they will be read from db and decrypted on client side.
As is, only he will be able to display the correct data.
I found another post, but i need some samples.
Can i make it with javascript?
How it works? javascript read the private key from a certificate on client machine?
How could you encrypt user data so only they can decrypt it?
tks
A: Public Key Encryption with Javascript:
http://shop-js.sourceforge.net/crypto2.htm
Keep in mind that you can't read local files with javascript alone. You might need to have a Silverlight app running on the client-side as silverlight can read local files. Maybe have your login screen done in Silverlight?
http://www.insidercoding.com/post/2008/08/17/Reading-Local-Files-in-Silverlight.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515392",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why is my Android background color not visible? I'm trying to figure out one simple thing: how to set a background color in Android view. Here is the code in an Activity:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View v = new View(this);
setContentView(v);
v.setBackgroundColor(23423425);
}
and all I get is black screen.
A: You are passing in the color incorrectly. DeeV got to it before me but you need to use a hex value.
Here is a link that lists all combinations for easy access.
Colors for Android
You can also set in the XML by using
android:background = "#FF00000000"
Which would be black.
A: The integer you set is easier represented as a hex value. The hex values are 0xAARRGGBB.
*
*A - represents the Alpha value which is how transparent the color is. A value of FF means it's not transparent at all. A value of 00 means the color won't be shown at all and everything behind it will be visible.
*R - Red value; self-explanatory
*G - Green value; self-explanatory
*B - Blue value; self-explanatory
What you entered in hex is 0x016569C1 which has an Alpha values of 1 (barely visible). Put, 0xFFFF0000 and you'll have a red background.
A: Common way to represent color in ARGB(sometimes RGBA but it is just a naming) model is hexadecimal. No one uses decimal numeral system to represent color digitally.
let's set yellow color to button's text: button.setTextColor(0xFFFFFF00);. Now We set yellow to out button's text.
ARGB consists of 4 cannel. each with 8-bit. first channel is alfa - 0xFFFFFFFF; alfa is opacity level(in this case we have max value of it). second is red - 0xFFFFFF00, and so on; green and blue respectively.
The easiest way to create color in ARGB color model with decimal numeral system is to use Color class.
Color class has all basic static functions and fields.
In your case you can use static function Color.rgb(int red, int, green, int blue) where red, green, blue must be in the range of 0 to 255. Alfa bits by default is set to max - 255 or in hex - 0xff.
Now you know how to represent color in hexadecimal numeric system it will be very easy to create color in xml resource file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515395",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Evaluating math expression on dictionary variables I'm doing some work evaluating log data that has been saved as JSON objects to a file.
To facilitate my work I have created 2 small python scripts that filter out logged entries according to regular expressions and print out multiple fields from an event.
Now I'd like to be able to evaluate simple mathematical operations when printing fields. This way I could just say something like
./print.py type download/upload
and it would print the type and the upload to download ratio. My problem is that I can't use eval() because the values are actually inside a dict.
Is there a simple solution?
A: eval optionally takes a globals and locals dictionaries. You can therefore do this:
namespace = dict(foo=5, bar=6)
print eval('foo*bar', namespace)
Keep in mind that eval is "evil" because it's not safe if the executed string cannot be trusted. It should be fine for your helper script though.
For completness, there's also ast.literal_eval() which is safer but it evaluates literals only which means there's no way to give it a dict.
A: You could pass the dict to eval() as the locals. That will allow it to resolve download and upload as names if they are keys in the dict.
>>> d = {'a': 1, 'b': 2}
>>> eval('a+b', globals(), d)
3
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515397",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: UTC time resets to 2000-01-01 (ruby). How do I prevent the time from resetting? I'm using a task and the spreadsheet gem to read in an excel spreadsheet into my database. One of the columns I'm reading in is "start_time." To do this, I'm forming an array of values, then passing in each of these array values, one by one.
cnum_array = [] # for start times
sheet1.each 3 do |row|
unless row[9].blank?
time = Time.parse(row[9])
cnum_array << time.utc
end
end
count = 0
for course in Course.all
course.update_attribute :start_time, cnum_array[count]
count += 1
end
This seems to work fine. If I insert a "puts course.start_time" statement within this last loop, it prints off the right time. Like so:
count = 0
for course in Course.all
course.update_attribute :start_time, cnum_array[count]
puts course.start_time
count += 1
end
This gives me the right time, e.g. "2012-01-23 15:30:00."
But when I look up the course time later (e.g. via my console's Course.find(1).start_time), it gives me "2000-01-01 15:20:00." So the time of day is right, but the day itself goes back to 2000-01-01.
Does anyone know why this is happening, and how I can fix it? Thanks!
A: You are using the Time class. This class deals with times, not dates. My guess is that your database column is of type time as well.
I recommend you use a datetime (or possibly timestamp) column type.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515398",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Returning a 401 Unauthorized from WCF Web API in an MVC 3 App I'm using the WCF Web API (the latest version, which I think is 0.5, obtained from the VS2010 Ultimate integrated package dependency GUI).
I've got a simple API class exposed and in each method I'm making a call that performs authorization against the user. When the user is unauthorized, I throw an HttpResponseException with the 401/unauthorized code.
This works, and you can see that at some point in the Http Handler chain, the 401 was trapped. The problem is that the site in which the API resides contains ASP.NET Forms authentication... and so when it sees the 401, it tries to forward my client request to the logon page.
How do I disable this behavior for a particular sub-directory within my site? I've tried setting a location of "api" always allowing users... but I still throw a 401 which still causes ASP.NET to try and redirect me to the logon page.
I'm sure I'm just missing a simple configuration setting that tells forms auth to ignore requests for the /api/* directories, but I can't find any information on it.
A: I have described the problem and it's solution here (with Preview4): Basic Authentication with WCF Web API hosted in IIS / Getting a 404 - Disable Forms Authentication Redirection
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515402",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: new problem in xcode 4 When we open a new project in xcode and then run that, this will run without any error.
but if we close the application in simulator ( by duble click on the home button and keeping MouseButton on the applicaton and hitting the red circle) and click on the desired application icon again, this makes an error in the following link
int retVal = UIApplicationMain(argc, argv, nil, nil);
what's problem ?
A: Your manually terminating the process in the simulator, so the debugging session ends when you terminate the App, probably by the simulated OS sending a SIG_KILL to the process, which gets cought and rethrown by another routine within the main run loop. Thats why it shows up in gdb.
Edit:
To attach to a process manually (for checking if everything in the applicationWillTerminate method executed properly, etc):
What you can do is run your App in the simulator, click 'Stop' in xCode or click 'X' on the App in the Simulator task list to close the App. Then run it in the Simulator manually by clicking the App icon in the simulator, and once it is open use Xcode to attach to the new process (by name or process ID) from the 'Product' -> 'Attach to Process' menu (Xcode 4.1).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515404",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: IE shows my website as an empty page on first visit I have a wordpress site, work great in all browsers except IE8.
It shows the site as an empty page on the first visit. However, if mouse over a link or image tooltips are shown. If I click refresh page the page starts to work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515410",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to implement a check for update on Mac OS X I'm trying to create an internal app for my company. I want to provide some kind of "automatic update" feature that give the user a message (with install option) once a new version is available. I know that for windows there is a technology named ClickOnce. Is there some kind of standard implementation for mac os x? Should I write it from scratch? If so, how can I start the install process directly from my application? Should I provide a mpkg?
A: Sparkle is probably what you want. It's used in many apps and is probably the "norm" of actual automatic update nowadays in mac apps other than the app store itself.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515416",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Export an EmailMessage from EWS that can be opened in MS Outlook I'm writing an application that monitors an Exchange mailbox using EWS. It saves the attachments of the incoming mails to a network folder.
These files are then used by a 3d party application.
Now I've been asked if it is possible to not only save the attachments but the entire e-mail with attachments still included so it can be opened in Outlook. (no other mailclients need to be supported).
The Exchange server is Exchange 2010 and the application is being written in C#
Can this be done using EWS? Or is my only solution to use Interop.Outlook to create a .msg file?
A: Which Outlook version are you using? Outlook 2010 can open .EML files, which is the "native" storage format for mails (RFC 2822). In this case, you can use the EWS Webservices (or EWS Managed API) to download the MIME content.
In any other cases, have a look at Outlook Redemption (http://www.dimastr.com/redemption/). It can save items as .msg file and can be used from C#.
A: ExchangeService exchangeService = ...
EmailMessage mailMessage = ...
var propertySet = new PropertySet(BasePropertySet.FirstClassProperties, ItemSchema.MimeContent, EmailMessageSchema.IsRead);
exchangeService.LoadPropertiesForItems(mailMessage, propertySet);
File.WriteBytes("filename.eml", mailMessage.MimeContent.Content);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515417",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: heatmap.2() overwrite colnames I am using the function heatmap.2 in R. I created an heatmap with the following conditions:
heatmap.2(tada1, Rowv=FALSE, Colv="FALSE", dendrogram='none', scale="row",trace='none',col=redgreen(3))
My problem is that the column of the heatmap contains 596 names. I cant see this names because they are overwriting each other. My Question is therefore: How can i display all the names without overwriting each other?
Thanks!
A: I was going to say "Use cex.axis to make the font size smaller", but I see that there is already provision in the code to make the row and column labels smaller in proportion to their numbers. See the argument list on the help page:
cexRow = 0.2 + 1/log10(nr),
cexCol = 0.2 + 1/log10(nc),
... so maybe you just need to purchase a magnifying glass. Or: print to a vector graphics device that is larger and scale it down. (Or provide an example so we can see what difficulty you are experiencing.
To implement my second to last suggestion you could look at this output with a pdfviewer. That should let you zoom in or out.
pdf(file="Hmap2.pdf", height=20, width=15)
# will go to the working directory unless you use path
heatmap.2(tada1, Rowv=FALSE, Colv="FALSE", dendrogram='none', scale="row",
trace='none', col=redgreen(3))
dev.off()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515419",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there a way to use one ANTLR grammar that targets multiple languages? I am developing a language service in Visual Studio using an ANTLR grammar for a custom language. However, the grammar is filled with C++ code to handle preprocessor directives and for efficiency reasons for the compiler.
Language services for Visual Studio are a pain to write in C++, so I need a C# parser for the same language. That means I have to set language=CSharp2 and strip all the C++ code from the grammar.
I am thinking of writing a little exporter that strips away all the C++ code from the grammar, and converts simple statements like { $channel = HIDDEN; } to { $channel = TokenChannels.Hidden; }.
Is there a more clever method to do this? Like through templates, or little tricks to embed both languages in the grammar?
A: I'd break the problem up into two phases using an AST. Have your parser in a target language neutral grammar (that produces an AST) and use the -target option to the Antlr Tool to generate the parser in the target language of your choice (C++, C#, Java, etc).
Then implement AST walkers in the target language with your actions. The benefit of this is that once you get one AST walker finished you can copy it and just change the actions for another target language.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: jqGrid extend configurations from other jqGrid I will have many jqGrid tables at my application. However it is not easy to write every configuration of it again and again
(i.e.
viewrecords: true,
sortorder: "desc",
multiselect: true,
multiboxonly: true,
)
How can I instruct a basic grid and extend and overwrite its configurations from other grids to have less code?
A: See the documentation at
http://www.trirand.com/jqgridwiki/doku.php?id=wiki:options
Create the options array once and pass it in when you create the other grids. To set the defaults for all grids, see the bottom of the docs called "Setting Options Globally" which may be what you want.
A: Just make a jqgrid adapter and use it instead of jqgrid.
jQuery.fn.jqGridAdapter = function(options) {
options = jQuery.extend(options, {viewrecords: true,
sortorder: "desc",
multiselect: true,
multiboxonly: true,
});
jQuery(this).jqGrid(options);
}
$('#table').jqGridAdapter();
With such adapter in case of new version of jqgrid that require changes in your code, you will have to change only this function.
A: You can use the following before creating any jqGrid.
$.extend($.jgrid.defaults, {
viewrecords: true,
sortorder: "desc",
multiselect: true,
multiboxonly: true
});
Moreover I recommend you to use column templates. See here and here for more information.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515427",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C++ newbie: writing a function for extracting i vectors from a file. How do I get i/unkown number of vectors out of the function? I am writing a function for getting datasets from a file and putting them into vectors. The datasets are then used in a calculation. In the file, a user writes each dataset on a line under a heading like 'Dataset1'. The result is i vectors by the time the function finishes executing. The function works just fine.
The problem is that I don't know how to get the vectors out of the function! (1) I think I can only return one entity from a function. So I can't return i vectors. Also, (2) I can't write the vectors/datasets as function parameters and return them by reference because the number of vectors/datasets is different for each calculation. If there are other possibilities, I am unaware of them.
I'm sure this is a silly question, but am I missing something here? I would be very grateful for any suggestions. Until now, I have not put the vector/dataset extraction code into a function; I have kept it in my main file, where it has worked fine. I would now like to clean up my code by putting all data extraction code into its own function.
For each calculation, I DO know the number of vectors/datasets that the function will find in the file because I have that information written in the file and can extract it. Is there some way I could use this information?
A: If each vector is of the same type you can return a
std::vector<std::vector<datatype> >
This would look like:
std::vector<std::vector<datatype> > function(arguments) {
std::vector<std::vector<datatype> > return_vector;
for(int i =0; i < rows; ++i) {
\\ do processing
return_vector.push_back(resulting_vector);
}
return return_vector;
}
A: As has been mentionned, you may simply use a vector of vectors.
In addition, you may want to add a smart pointer around it, just to make sure you're not copying the contents of your vectors (but that's already an improvement. First aim at something that works).
As for the information on the number of vectors, you may use it by resizing the global vector to the appropriate value.
A: You question is, at its essence "How do I return a pile of things from a function?" It happens that your things are vector<double>, but that's not really important. What is important is that you have a pile of them of unknown size.
You can refine your thinking by rephrasing your one question into two:
*
*How do I represent a pile of things?
*How do I return that representation from a function?
As to the first question, this is precisely what containers do. Containers, as you surely know because you are already using one, hold an arbitrary numbers of similar objects. Examples include std::vector<T> and std::list<T>, among others. Your choice of which container to use is dictated by circumstances you haven't mentioned -- for example, how expensive are the items to copy, do you need to delete an item from middle of the pile, etc.
In your specific case, knowing what little we know, it seems you should use std::vector<>. As you know, the template parameter is the type of the thing you want to store. In your case that happens to be (coincidentally), an std::vector<double>. (The fact that the container and its contained object happen to be similar types is of no consequence. If you need a pile of Blobs or Widgets, you say std::vector<Blob> or std::vector<Widget>. Since you need a pile of vector<double>s, you say vector<vector<double> >.) So you would declare it thus:
std::vector<std::vector<double > > myPile;
(Notice the space between > and >. That space is required in the previous C++ standard.)
You build up that vector just as you did your vector<double> -- either using generic algorithms, or invoking push_back, or some other way. So, your code would look like this:
void function( /* args */ ) {
std::vector<std::vector<double> > myPile;
while( /* some condition */ ) {
std::vector<double> oneLineOfData;
/* code to read in one vector */
myPile.push_back(oneLineOfData);
}
}
In this manner, you collect all of the incoming data into one structure, myPile.
As to the second question, how to return the data. Well, that's simple -- use a return statement.
std::vector<std::vector<double> > function( /* args */ ) {
std::vector<std::vector<double> > myPile;
/* All of the useful code goes here*/
return myPile;
}
Of course, you could also return the information via a passed-in reference to your vector:
void function( /* args */, std::vector<std::vector<double> >& myPile)
{
/* code goes here. including: */
myPile.push_back(oneLineOfData);
}
Or via a passed-in pointer to your vector:
void function( /* args */, std::vector<std::vector<double> >* myPile)
{
/* code goes here. */
myPile->push_back(oneLineOfData);
}
In both of those cases, the caller must create the vector-of-vector-of-double before invoking your function. Prefer the first (return) way, but if your program design dictates, you can use the other ways.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515429",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Integer Partition in Java Here is my code to do this. It works for the string representation, but not the ArrayList<ArrayList<Integer>> one.
public static void partition(int n) {
partition(n, n, "",
new ArrayList<ArrayList<Integer>>(),
new ArrayList<Integer>());
}
public static void partition(int n, int max, String temp,
ArrayList<ArrayList<Integer>> master,
ArrayList<Integer> holder) {
if (n == 0) {
ArrayList<Integer> temp1 = new ArrayList<Integer>();
for (int i = 0; i <= holder.size(); i++) {
temp1.add(holder.get(0));
holder.remove(0);
}
master.add(temp1);
System.out.println(temp);
}
for (int i = Math.min(max, n); i >= 1; i--) {
holder.add(i);
partition(n - i, i, temp + " " + i, master, holder);
}
}
The reason that I am doing the funny business with temp1 is that if I were to just add temp to master, the previous elements would change (all elements in master would be references pointing to the same place) so this is my attempt at a deep copy + clear.
The string works. Why doesn't the ArrayList<ArrayList<Integer>>? And how can I fix it?
Output of the ArrayList<ArrayList<Integer>> is:
[[5], [4, 1], [3, 2], [1, 1], [2, 2], [1, 1, 1], [1, 1, 1, 1]]
A: You are mixing up your holder array inside the if branch which you shouldn't do. Try the following:
public static void partition(int n, int max, String temp,
ArrayList<ArrayList<Integer>> master,
ArrayList<Integer> holder) {
if (n == 0) {
ArrayList<Integer> temp1 = new ArrayList<Integer>();
for (int i = 0; i < holder.size(); i++) {
temp1.add(holder.get(i));
}
master.add(temp1);
System.out.println(temp);
}
for (int i = Math.min(max, n); i >= 1; i--) {
holder.add(i);
partition(n - i, i, temp + " " + i, master, holder);
holder.remove(holder.size() - 1);
}
}
A: You have to pass a copy of holder to each subsequent branch of the recursion.
Java 7:
public static void main(String[] args) {
List<List<Integer>> list = partition(5);
for (List<Integer> comb : list)
System.out.println(comb);
}
public static List<List<Integer>> partition(int n) {
List<List<Integer>> list = new ArrayList<>();
partition(n, n, "", list, new ArrayList<Integer>());
return list;
}
public static void partition(int i, int max, String indent,
List<List<Integer>> master, List<Integer> holder) {
if (i == 0) {
master.add(holder);
System.out.println(
indent + "i=" + i + ",max=" + max + " comb=" + holder);
}
for (int j = Math.min(max, i); j >= 1; j--) {
ArrayList<Integer> temp = new ArrayList<>(holder);
temp.add(j);
System.out.println(
indent + "i=" + i + ",j=" + j + ",max=" + max + " temp=" + temp);
partition(i - j, j, indent + " ", master, temp);
}
}
Output of the recursive tree n=5:
i=5,j=5,max=5 temp=[5]
i=0,max=5 comb=[5]
i=5,j=4,max=5 temp=[4]
i=1,j=1,max=4 temp=[4, 1]
i=0,max=1 comb=[4, 1]
i=5,j=3,max=5 temp=[3]
i=2,j=2,max=3 temp=[3, 2]
i=0,max=2 comb=[3, 2]
i=2,j=1,max=3 temp=[3, 1]
i=1,j=1,max=1 temp=[3, 1, 1]
i=0,max=1 comb=[3, 1, 1]
i=5,j=2,max=5 temp=[2]
i=3,j=2,max=2 temp=[2, 2]
i=1,j=1,max=2 temp=[2, 2, 1]
i=0,max=1 comb=[2, 2, 1]
i=3,j=1,max=2 temp=[2, 1]
i=2,j=1,max=1 temp=[2, 1, 1]
i=1,j=1,max=1 temp=[2, 1, 1, 1]
i=0,max=1 comb=[2, 1, 1, 1]
i=5,j=1,max=5 temp=[1]
i=4,j=1,max=1 temp=[1, 1]
i=3,j=1,max=1 temp=[1, 1, 1]
i=2,j=1,max=1 temp=[1, 1, 1, 1]
i=1,j=1,max=1 temp=[1, 1, 1, 1, 1]
i=0,max=1 comb=[1, 1, 1, 1, 1]
Output of the list n=5:
[5]
[4, 1]
[3, 2]
[3, 1, 1]
[2, 2, 1]
[2, 1, 1, 1]
[1, 1, 1, 1, 1]
See also: Building permutation that sums to a number efficiently
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Profile Manager Lion Server error My Lion Server (10.7.1) worked perfectly until this tuesday. Yesterday when I went to profile manager's page, sometime it works and sometime not.
Also, if I do the enrollment of a device sometimes works and sometimes not (I received a timeout).
I discovered that port 5223 does not work, probably something happened to the Profile Manager? I have not done anything and the last time there were two updates info about 150 devices and sending two settings push about 150 users.
Help me guys, I'm really sad now :/.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515435",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: MVC3: Portions of Model Not Reconstituted on Postback Portions of my models are not being correctly reconstructed on postback.
Models
public class DemographicsModel
{
public List<QuestionModel> Questions { get; set; }
}
public abstract class QuestionModel
{
[HiddenInput(DisplayValue = false)]
public int ID { get; set; }
[HiddenInput(DisplayValue = false)]
public string Title { get; set; }
}
public abstract class ChooseQuestionModel : QuestionModel
{
public abstract List<SelectListItem> Items { get; set; }
}
public class ChooseManyQuestionModel : ChooseQuestionModel
{
[Required]
[DataType("CheckBoxList")]
public override List<SelectListItem> Items { get; set; }
}
Views
ChooseManyQuestionModel.cshtml
@model X.Y.Z.ChooseManyQuestionModel
<div class="Form Wide NoLabel">
<div class="Title">@this.Model.Title</div>
@Html.TypeStamp()
@Html.EditorFor(m => m.ID)
@Html.EditorFor(m => m.Title)
@Html.EditorFor(m => m.Items)
</div>
CheckBoxList.cshtml
@model IEnumerable<SelectListItem>
@if (!this.Model.IsNullOrEmpty())
{
foreach (var item in this.Model)
{
<div>
@Html.HiddenFor(m => item.Value)
@Html.HiddenFor(m => item.Text)
@Html.CheckBoxFor(m => item.Selected)
@Html.LabelFor(m => item.Selected, item.Text)
</div>
}
}
I believe the issue lies within CheckBoxList.cshtml since these items are not being re-constituted on postback.
HTML Output
<div class="Form Wide NoLabel">
<div class="Title">Question title displays here?</div>
<input id="Questions_1___xTypeStampx_" name="Questions[1]._xTypeStampx_" type="hidden" value="Hrxh2HjDRorBAZWo18hsC0OvbJwyswpDkfTBfNF2NC8=" />
<input data-val="true" data-val-number="The field ID must be a number." data-val-required="The ID field is required." id="Questions_1__ID" name="Questions[1].ID" type="hidden" value="76" />
<input id="Questions_1__Title" name="Questions[1].Title" type="hidden" value="Question title displays here?" />
<div>
<input id="Questions_1__Items_item_Value" name="Questions[1].Items.item.Value" type="hidden" value="148" />
<input id="Questions_1__Items_item_Text" name="Questions[1].Items.item.Text" type="hidden" value="Organization Type 1" />
<input data-val="true" data-val-required="The Selected field is required." id="Questions_1__Items_item_Selected" name="Questions[1].Items.item.Selected" type="checkbox" value="true" /><input name="Questions[1].Items.item.Selected" type="hidden" value="false" />
<label for="Questions_1__Items_item_Selected">Organization Type 1</label>
</div>
</div>
</div>
Controller
public class AccountController : BaseController
{
public ActionResult Demographics()
{
return this.View(new DemographicsModel());
}
[HttpPost]
public ActionResult Demographics(DemographicsModel model)
{
return this.View(model);
}
}
On postback, the DemographicsModel is populated with the correct types (I'm using MvcContrib to handle abstract type binding). The List<Question> is populated with all of the correct data including the ID and Title of each question from the hidden fields. However, List<SelectListItem> within each question is set to null.
Update 1
The issue is definitely occurring because the fields are not named correctly. For instance, the "item" field names are being generated like this:
Questions_1__Items_item_Value
When they should really look like this (addition of item index and removal of erroneous "item"):
Questions_1__Items_1__Value
Similarly, the field IDs are being generated like this (addition of item index and removal of erroneous "item"):
Questions[1].Items.item.Value
Instead of:
Questions[1].Items[0].Value
Using Fiddler with the correct IDs being posted back, the model is constructed correctly with all radio buttons and checkboxes in place.
A: Try the following.
In ChooseManyQuestionModel.cshtml, change @Html.EditorFor(m => m.Items) to:
@Html.EditorForModel(m => m.Items)
Then, in CheckBoxList.cshtml, change @model IEnumerable<SelectListItem> to:
@model SelectListItem
Finally, in each item, modify each lambda expression, and change item to m, then remove the foreeach loop. This will allow the Editor to iterate through the collection, and should give you correct id generation for each element.
A: When foreach loop is used the ids generated in HTML are all same.
When for look is used the ids generated with the for loops index so binding is happening correctly and all the data is available after post back.
A: In this scenario, it seems the Helper class is not doing what you want it to do. I would suggest writing your own helper class to name your inputs exactly as you require them to be.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515441",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to align text around a bottom right image using a spacer div (not working in Safari)? I have a fixed height div and want to align an image to the bottom right corner with the text (of an unknown/variable length) to wrap around it. I'd ideally like to avoid using Javascript and the best solution so far appears to be to use a vertical spacer div above the image (which is the container height - image height) to push it down. This works perfectly on IE / FF but the text overlaps the top of the image on safari (mobile and standard). I'm not sure why this is happening, I appreciate the fonts are displaying differently but surely the text should flow around the div/image either way? You can see an example of what i'm talking about at http://jsfiddle.net/deshg/XScmK/, i've just used a coloured div with some text instead of an image in this example.
Any thoughts would be massively appreciated as I'm not sure why this isn't working?
Thanks very much as ever,
Dave
A: in your 3rd div margin-top:20px; for a quick fix, but this will push up your 1px wide div.
also try changing these heights: 141px to 140px, and change 159px to 160px.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515445",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Eject sdcard when playing video on internal storage cause "media server died" I am developing android applications and firmware for a hardware device, the device have internal storage at /mnt/sdcard. When insert external sdcard, it is mounted at /mnt/sdcard/extsd, and /mnt/sdcard/udisk for external usb disk(thumb drive).
Now the problem is, when I am playing a video on internal storage using "VideoView" and I eject the external sdcard, then there is a popup saying that "Sorry, cannot play video".
I looked at the logcat and found something like this
WARN/AudioSystem(92): AudioFlinger server died!
WARN/AudioSystem(92): AudioPolicyService server died!
INFO/ServiceManager(53): service 'media.audio_flinger' died
INFO/ServiceManager(53): service 'media.player' died
INFO/ServiceManager(53): service 'media.camera' died
INFO/ServiceManager(53): service 'media.audio_policy' died
WARN/IMediaDeathNotifier(912): media server died
WARN/IMediaDeathNotifier(912): media server died
ERROR/MediaPlayer(912): error (100, 0)
I am playing a file on internal storage and why removing sdcard cause error to "media server"? or Will the so call "media server" died when ejecting sdcard and is not related to playing video? or the problem is actually not related to "media server"?
The android version I am working on is 2.3.3
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515446",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to make a favourite list iphone I am making an app that has two tabs, one of which is a "favourite" tab. In the other tab called "search", I have a list of results displayed in a table view, when you tap one, you get to see the detail of that particular result. What I'm trying to do here is, there is a button in the detail view, when it is pressed, the current result gets sent to the "favourite" tab. I tried to use delegate to pass the information, but it didn't work out. Here is my code:
DetailViewController.m
-(IBAction) addSomething {
[self.delegate detailViewController:self addToFavourite:self.something];
}
FavouriteViewController.m, implement the delegate method:
- (void) detailViewController:(DetailViewController *)detailViewController addToFavourite:(Something *)something{
detailViewController.delegate = self;
[thingsList addObject:something];
[theTableView reloadData];
}
Everything is built and fine, but when I click "add" button in the detail view, the data doesn't get sent to "favourite" tab's view. Can anyone help me with this one? Do I need to use core data in this case, I never used core data before. Thanks.
A: One way to do it that is drop dead easy is storing your information in NSUserDefaults.
NSUserDefaults *defaults = [NSUserDefaults standardDefaults];
[defaults setObject:thingsList forKey:@"myData"];
[defaults synchronize];
When you load your data up in your other tab, just fill it from user defaults.
NSUserDefaults *defaults = [NSUserDefaults standardDefaults];
otherData = [defaults objectForKey:@"myData"];
I probably abuse user defaults more than I should, but it makes for a very easy way to store your data locally and have it persist between runs. It will also backup with iTunes for added persistence. Hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515448",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Does the Google+ Hangouts API support filling app fields on the runtime? I am trying to build a app using the hangout API, starter app.
Does the Hangouts API have support for data fields to be added on runtime?
For example,
a. If we need to add team members to our app
b. Or when we do 'Create Application' (https://appengine.google.com/)
c. When we enter AppEngine app ID to Gadget URL (https://code.google.com/apis/console/?api=plusHangouts)
Can we do the above using Python code and using the API (if there are any)?
A: As documented in Google APIs Console Help we don't let people programmatically register data into the APIs console.
Don't forget that that the current restrictions are because we are in a developer preview.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515449",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: to search for consecutive list elements prefixed by number and dot in plain text The text looks like this:
"Beginning. 1. The container is 1.5 meters long 2. It can hold up to 2lt of fluid. 3. It 4 holes."
There may not be a dot at the end of each list element.
How can I split this text into a list as shown below?
"Beginning."
"The container is 1.5 meters long"
"It can hold up to 2lt of fluid."
"It has 4 holes."
In other words I need to match (\d+)\. such that all (\d+) are consecutive integers so that I can split and trim the text between them. Is it possible with regex? How far do I have to venture into the realm of computer science?
A: Use
\d+\.(?!\d)
as the splitting regex, i. e. in PHP
$result = preg_split('/\d+\.(?!\d)/', $subject);
The negative lookahead (?!\d) ensures that no digit follows after the dot has been matched.
Or make the spaces mandatory - if that's an option:
$result = preg_split('/\s+\d+\.\s+/', $subject);
A: This is working c# code:
string s = "Beginning. 1. The container is 1.5 meters long 2. It can hold up to 2lt of fluid. 3. It has 4 holes.";
string[] res = Regex.Split(s, @"\s*\d+\.\s+");
foreach (var r in res)
{
Console.WriteLine(r);
}
Console.ReadLine();
I split on \s*\d+\.\s+ that means optional white space, followed by at least one digit ,followed by a dot, then at least one whitespace.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515450",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I make two vertical DIVs be the same length? I have the following HTML:
<div id="body">
<div id="left">xx</div>
<div id="right">yy
aa
<br>
<br>
<br>
aa
</div>
</div>
and the following CSS:
#body { background-color: yellow; }
#left, #right { float: left; }
#left { background-color: blue; }
#right { background-color: red; }
What I need is for the DIV on the left to grow to be the same length as the one on the right? Is this possible? I tried a few things but it doesn't work.
fiddle
A: There are numerous way to try it. You didn't assign either of them a height so they won't be doing much at the moment. If you add equal heights, they can be the same. You can try style="height:100%;" for both of them
Or add that to those IDs in your CSS, or make a class with it and assign that to your divs.
A: something like this $("#right").css("height", $("#left").css("height"));
A: Here's a way about it, using display: table-cell
Won't work in older browsers.
http://jsfiddle.net/ZrGBB/
A: You could having the right inside the left as so
<div class="left">
aa
<div class="right">
bb
<br/>
<br/>
bb
</div>
<div style="clear:both"></div>
</div>
and floating the right div right and stoppnig the left colapsing using the clear:both
A: There's no real simple one line of code way to do this but there are many solutions out on the web like Faux Columns or Equal Height Columns.
Give it a Google and find a solution that works best for you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515456",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Convert MailMessage to Raw text Is there any easy way to convert a System.Net.Mail.MailMessage object to the raw mail message text, like when you open a eml file in notepad.
A: I've implemented logic in MimeKit to allow you to cast a System.Net.Mail.MailMessage into a MimeKit.MimeMessage. Once you do that, you can simply write the message to a stream:
var message = (MimeMessage) CreateSystemNetMailMessage ();
using (var stream = File.Create ("C:\\message.eml"))
message.WriteTo (stream);
This does not require reflecting into internal methods which means that it isn't dependent on the runtime, making it far more portable that the other answers given so far.
A: The code I've seen to do this relies on reflection. I adapted the samples found online to create this method:
private static MemoryStream ConvertMailMessageToMemoryStream(MailMessage message)
{
BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
Assembly assembly = typeof(SmtpClient).Assembly;
MemoryStream stream = new MemoryStream();
Type mailWriterType = assembly.GetType("System.Net.Mail.MailWriter");
ConstructorInfo mailWriterContructor = mailWriterType.GetConstructor(flags, null, new[] { typeof(Stream) }, null);
object mailWriter = mailWriterContructor.Invoke(new object[] { stream });
MethodInfo sendMethod = typeof(MailMessage).GetMethod("Send", flags);
sendMethod.Invoke(message, flags, null, new[] { mailWriter, true }, null);
MethodInfo closeMethod = mailWriter.GetType().GetMethod("Close", flags);
closeMethod.Invoke(mailWriter, flags, null, new object[] { }, null);
return stream;
}
You can then convert the MemoryStream to a string or whatever you need.
Update: A method signature has changed in .NET 4.5, which breaks the above:
Getting System.Net.Mail.MailMessage as a MemoryStream in .NET 4.5 beta
A: Here's the same solution, but as an extension method to MailMessage.
Some of the reflection overhead is minimized by grabbing the ConstructorInfo and MethodInfo members once in the static context.
/// <summary>
/// Uses reflection to get the raw content out of a MailMessage.
/// </summary>
public static class MailMessageExtensions
{
private static readonly BindingFlags Flags = BindingFlags.Instance | BindingFlags.NonPublic;
private static readonly Type MailWriter = typeof(SmtpClient).Assembly.GetType("System.Net.Mail.MailWriter");
private static readonly ConstructorInfo MailWriterConstructor = MailWriter.GetConstructor(Flags, null, new[] { typeof(Stream) }, null);
private static readonly MethodInfo CloseMethod = MailWriter.GetMethod("Close", Flags);
private static readonly MethodInfo SendMethod = typeof(MailMessage).GetMethod("Send", Flags);
/// <summary>
/// A little hack to determine the number of parameters that we
/// need to pass to the SaveMethod.
/// </summary>
private static readonly bool IsRunningInDotNetFourPointFive = SendMethod.GetParameters().Length == 3;
/// <summary>
/// The raw contents of this MailMessage as a MemoryStream.
/// </summary>
/// <param name="self">The caller.</param>
/// <returns>A MemoryStream with the raw contents of this MailMessage.</returns>
public static MemoryStream RawMessage(this MailMessage self)
{
var result = new MemoryStream();
var mailWriter = MailWriterConstructor.Invoke(new object[] { result });
SendMethod.Invoke(self, Flags, null, IsRunningInDotNetFourPointFive ? new[] { mailWriter, true, true } : new[] { mailWriter, true }, null);
result = new MemoryStream(result.ToArray());
CloseMethod.Invoke(mailWriter, Flags, null, new object[] { }, null);
return result;
}
}
To grab the underlying MemoryStream:
var email = new MailMessage();
using (var m = email.RawMessage()) {
// do something with the raw message
}
A: byte[] allBytes = new byte[attachment.ContentStream.Length];
int bytesRead = attachment.ContentStream.Read(allBytes, 0, (int)attachment.ContentStream.Length);
Encoding encoding = Encoding.UTF8;
String contenidoCorreo = encoding.GetString(allBytes);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515457",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: Jsoup vs groovy XmlSlurper? I am looking at parsing some xml content for my application (based on groovy) and I am stuck at this point where I have to choose between JSoup and groovy's native XMLSlurper.
RSS Feeds parsed are of medium size not exceeding more than 25 items. So the size of the content being parsed is neither too much nor too less.
Although the content is of medium size, parsing of content happens several times. So in terms of overhead and speed, which of the two is a better choice?
A: For parsing 25 items, I wouldn't worry about it too much.
I'd use XmlSlurper first, as it doesn't add a dependency to your project and is integrated tightly into Groovy, but then consider other options if for some reason it does not work as well as expected
A: XmlSlurper. TagSoup is really for the vagaries of HTML.
Pretty easy to do a speed comparison though, no?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515469",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Insert comma before last three digits of a mysql_fetch_array result? is it at all possible to do this?
for instance if i had
$row['price']
and the value of this was 15000
I would like it to show as 15,000 but I dont have a clue about how to go about this?
thanks for any help.
A: So, you want to FORMAT your data? How about using the FORMAT function?
FORMAT(X,D)
Formats the number X to a format like '#,###,###.##', rounded to D decimal places, and returns the result as a string. If D is 0, the result has no decimal point or fractional part. D should be a constant value.
mysql> SELECT FORMAT(12332.123456, 4);
-> '12,332.1235'
mysql> SELECT FORMAT(12332.1,4);
-> '12,332.1000'
mysql> SELECT FORMAT(12332.2,0);
-> '12,332'
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_format
EDIT: Sample query
As opposed to the SELECT * people use (too often), slightly modify your queries.
SELECT id, fullName, position, FORMAT(pay, 0) as pay
FROM Employees WHERE lastName = 'Rubble';
A: From PHP, you can use number_format:
$formatted = number_format($row['price']);
This will add a comma between every group of thousands. If you also want to format your price with a dot and two decimal places, use this:
$formatted = number_format($row['price'], 2);
A: If you'd like to do the formatting in MySQL then you can use the FORMAT() function: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_format
A: Try this:
$row['price'] = 15000;
echo substr($row['price'], 0, -3) . ',' . substr($row['price'], -3);
echo substr($row['price'], 0, -3); // == 15
echo substr($row['price'], -3); // == 000
The 0 is the start position of the string. The -15 is the negative end position of the string.
http://at2.php.net/manual/en/function.substr.php
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515479",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C# ShowDialog() throws error because of importing C++ DLL This C# program works fine without using showdialog() but it creates "system access violation" exception when i tried to use showdialog(). Weird!!
C# Code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace w_CSharp_GUI_1
{
public partial class Form1 : Form
{
private String W_Addr,C_Addr,Pic_Addr="lol";
[DllImport("face_proj_trial_dll.dll")]
public static extern string f_detect(string path);
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog2 = new OpenFileDialog();
openFileDialog2.ShowDialog(this);
Pic_Addr = (f_detect("C:\\pic.jpg"));
textBox1.Text = Convert.ToString(Pic_Addr);
}
}
}
C++ code:
#include "face_detect_DLL.h"
extern "C" __declspec(dllexport) char* _stdcall f_detect(char* path)
{
return path;
}
A: That's not at all surprising. You are returning a C string that was actually created by the C# marshaller. The marshaller then tries to free that memory twice. Once as the return value and once for the parameter passed to the DLL. The first free will fail because the memory was not allocated with the allocator that the C# marshaller assumes.
Anyway, you simply don't want to return a char* from your DLL. I'm not sure what you really want to do but the normal patterns with string P/invokes are:
*
*For marshalling strings from C# to C++ declare them as string in your C# and char* in C++.
*When going the other way use StringBuilder. Allocate a buffer before you call and use MarshalAs. There are a gazillion examples on the web of this pattern.
A: Functions that return a string are a memory management problem. The memory for the string has to be released. The pinvoke marshaller is going to call CoTaskMemFree() on the returned string. That's going to crash on Vista and up, silently leak memory on XP since the string wasn't allocated with CoTaskMemAlloc.
You'll need to declare the return type as IntPtr to prevent the marshaller from doing this. And marshal it yourself with Marshal.PtrToStringAnsi(). That solves the crash but not the memory leak. You'll need to declare the function as void f_detect(const char* path, char* somevalue, size_t somevaluebuffersize) so that the caller can pass his own buffer. StringBuilder on the managed side.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515481",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to select data from multiple tables with LINQ (entities) I have two tables and corresponding LINQ entities
*
*product
*order
order has a fk_product_id in the database which is linked to pk_product_id in table product
How can I write a method that returns data from both tables, so that I can hook it up to a repeater or gridview?
I found examples where people are writing joins, but I wonder if that's really necessary.
A: With LINQ you can do something like this:
var results = from o in Order
select new
{
order = o,
product = o.Product
};
Then feed that as a DataSource to your repeater, and then access it in an ItemTemplate or such like this:
<asp:Label Text='<%# Eval("product.Name") %>' />
A: You can flatten the fields you want from the 2 different objects into a new 'flat' anonymous type. See here.
A: Use db.orders.include("product").all();
While u had define product entity in order class ...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515487",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: excel vba macro - extract value from where clause In columnA of excel sheet 'Input' I have the following (with each line being on a new row in the sheet):
update my_table
set time = sysdate,
randfield1 = 'FAKE',
randfield5 = 'ME',
the_field8 = 'test'
where my_key = '84'
;
update my_table
set time4 = sysdate,
randfield7 = 'FAeKE',
randfield3 = 'MyE',
the_field9 = 'test'
where my_key = '37';
I'm trying to create a new sheet 'output' that only contains the following values in columnA but I don't know how to extract the bit in between the quotes after --> where my_key:
84
37
Some notes: it would be great to be able to specify the fieldname in cell B1 of sheet 'input', in this example it would be my_key.
Previously, I've been doing this manually using filter column where text contains 'where' then stripping out everything after the equals then doing a find/replace on single quotes and ;s. Has anyone been able to achieve this with a single button click macro?
A: While using Filtering or Find is very efficient I don't think you will see much difference in using a variant array to hold the all values for your Input Sheet, to be tested against a regex using a fieldname in InputB1, with any numeric portions of the match being dumped to Column A Output.
Sub VarExample()
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim X
Dim Y
Dim lngRow As Long
Dim objRegex
Dim objRegexMC
Set ws1 = ActiveWorkbook.Sheets("Input")
Set ws2 = ActiveWorkbook.Sheets("Output")
Set objRegex = CreateObject("vbscript.regexp")
objRegex.Pattern = ".+where.+" & ws1.[b1] & ".+\'(\d+)\'.*"
X = ws1.Range(ws1.[a1], ws1.Cells(Rows.Count, "A").End(xlUp)).Value2
ReDim Y(1 To UBound(X, 1), 1 To UBound(X, 2))
For lngRow = 1 To UBound(X, 1)
If objRegex.test(X(lngRow, 1)) Then
Set objRegexMC = objRegex.Execute(X(lngRow, 1))
lngCnt = lngCnt + 1
Y(lngCnt, 1) = objRegexMC(0).submatches(0)
End If
Next
ws2.Columns("A").ClearContents
ws2.[a1].Resize(UBound(Y, 1), 1).Value2 = Y
End Sub
A: A simple solution but definitely not a good one could be like this:
Sub getWhere()
Dim sRow as Integer
Dim oRow as Integer
Dim curSheet as Worksheet
Dim oSheet as Worksheet
dim words() as String
Set curSheet = ThisWorkbook.Sheets("Input")
Set oSheet = ThisWorkbook.Sheets("Output")
sRow = 1
oRow = 1
Do while curSheet.Range("A" & sRow).Value <> ""
If Instr(lcase(curSheet.Range("A" & sRow).Value), "where") > 0 Then
words = Split(curSheet.Range("A" & sRow).Value, " ")
oSheet.Range("B" & oRow).Value = words(1)
oSheet.Range("C" & oRow).Value = getNumeric(words(3))
oRow = oRow + 1
End If
sRow = sRow +1
Loop
End Sub
Function getNumeric(ByVal num As String) As Long
Dim i As Integer
Dim res As String
For i = 1 To Len(num)
If Asc(Mid(num, i, 1)) >= 48 And Asc(Mid(num, i, 1)) <= 57 Then res = res & Mid(num, i, 1)
Next
getNumeric = CLng(res)
End Function
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515490",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: reloadData - UITableView I have a problem in displaying the data in a table, call the method [tv reloadData] when Tebel is updated but when I select a row it will appear blurred, as if the previous data had not been removed. I think the problem is in the class that stores the data brought by my SQL query, but I have one [release] in all the fields and did not work.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
iMAPArrayProdutos *ArrayProdutos = (iMAPArrayProdutos *)[iMAP objectAtIndex:indexPath.row];
NSString *MyIdentifier = [NSString stringWithFormat:@"MyIdentifier %i", indexPath.row];
iMAPTabela *cell = (iMAPTabela *)[tableView dequeueReusableCellWithIdentifier:MyIdentifier];
tv.autoresizesSubviews = YES;
if (cell == nil) {
cell = [[[iMAPTabela alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
}
UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(0.0, 0, 50.0, tableView.rowHeight)] autorelease];
[cell addColumn:70];
label.tag = TAG_1;
label.font = [UIFont systemFontOfSize:12.0];
label.text = ArrayProdutos.Cod;
label.textAlignment = UITextAlignmentRight;
label.textColor = [UIColor blueColor];
label.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview:label];
label = [[[UILabel alloc] initWithFrame:CGRectMake(80.0, 0, 50.0, tableView.rowHeight)] autorelease];
[cell addColumn:140];
label.tag = TAG_2;
label.font = [UIFont systemFontOfSize:12.0];
label.text = ArrayProdutos.Artrf2;
label.textAlignment = UITextAlignmentRight;
label.textColor = [UIColor blueColor];
label.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview:label];
label = [[[UILabel alloc] initWithFrame:CGRectMake(145.0, 0, 100.0, tableView.rowHeight)] autorelease];
[cell addColumn:260];
label.tag = TAG_3;
label.font = [UIFont systemFontOfSize:12.0];
label.text = ArrayProdutos.Descri;
label.textAlignment = UITextAlignmentRight;
label.textColor = [UIColor blueColor];
label.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview:label];
return cell;
}
Perform the query directly from the Bank:
- (void)readiMAPFromDatabase {
// Setup the database object
sqlite3 *database;
// Init the Array
iMAP = [[NSMutableArray alloc] init];
// Open the database from the users filessytem
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
// Setup the SQL Statement and compile it for faster access
sqlite3_stmt *compiledStatement;
const char *sqlStatement;
if ([sb.text length] == 0) {
sqlStatement = "SELECT * FROM APSB1010";
}
else {
NSString *string1;
if ([OpcaoFiltro isEqualToString:@"1"]) {
string1 = @"SELECT * FROM APSB1010 WHERE TRIM(COD) LIKE '%";
}
else if ([OpcaoFiltro isEqualToString:@"2"]) {
string1 = @"SELECT * FROM APSB1010 WHERE TRIM(ARTRF2) LIKE '%";
}
else if ([OpcaoFiltro isEqualToString:@"3"]) {
string1 = @"SELECT * FROM APSB1010 WHERE TRIM(DESCRI) LIKE '%";
}
else if ([OpcaoFiltro isEqualToString:@"4"]) {
string1 = @"SELECT * FROM APSB1010 WHERE TRIM(APLICA) LIKE '%";
}
else {
string1 = @"SELECT * FROM APSB1010 WHERE TRIM(APLICA) LIKE '%";
}
NSString *string2 = @"%'";
NSString *result = [[NSString alloc] init];
result = [result stringByAppendingString:string1];
result = [result stringByAppendingString:sb.text];
result = [result stringByAppendingString:string2];
sqlStatement = [result UTF8String];
}
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
// Loop through the results and add them to the feeds array
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
// Read the data from the result row
NSString *ProdCod = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
NSString *ProdPrv1 = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
NSString *ProdGrupo = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
NSString *ProdPicment = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
NSString *ProdDescri = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 4)];
NSString *ProdArtrf2 = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 5)];
NSString *ProdUm = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 6)];
NSString *ProdEmbap = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 7)];
NSString *ProdDesmax = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 8)];
NSString *ProdImgap = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 9)];
NSString *ProdAplica = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 10)];
NSString *ProdQatu_01 = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 11)];
NSString *ProdQatu_11 = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 12)];
NSString *ProdQatu_12 = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 13)];
NSString *ProdQatu_13 = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 14)];
NSString *ProdQatu_14 = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 15)];
NSString *ProdPrprom = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 16)];
NSString *ProdR_E_C_N_O_ = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 17)];
// Create a new object with the data from the database
iMAPArrayProdutos *ArrayProdutos = [[iMAPArrayProdutos alloc] Cod:ProdCod Prv1:ProdPrv1 Grupo:ProdGrupo Picment:ProdPicment Descri:ProdDescri Artrf2:ProdArtrf2 Um:ProdUm Embap:ProdEmbap Desmax:ProdDesmax Imgap:ProdImgap Aplica:ProdAplica Qatu_01:ProdQatu_01 Qatu_11:ProdQatu_11 Qatu_12:ProdQatu_12 Qatu_13:ProdQatu_13 Qatu_14:ProdQatu_14 Prprom:ProdPrprom R_E_C_N_O_:ProdR_E_C_N_O_];
// Add the object to the Array
[iMAP addObject: ArrayProdutos];
[ArrayProdutos release];
}
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
[tv reloadData];
}
Class where I store the data brought by the query:
@implementation iMAPArrayProdutos
@synthesize Cod;
@synthesize Prv1;
@synthesize Grupo;
@synthesize Picment;
@synthesize Descri;
@synthesize Artrf2;
@synthesize Um;
@synthesize Embap;
@synthesize Desmax;
@synthesize Imgap;
@synthesize Aplica;
@synthesize Qatu_01;
@synthesize Qatu_11;
@synthesize Qatu_12;
@synthesize Qatu_13;
@synthesize Qatu_14;
@synthesize Prprom;
@synthesize R_E_C_N_O_;
-(id)Cod:(NSString *)ProdCod Prv1:(NSString *)ProdPrv1 Grupo:(NSString *)ProdGrupo Picment:(NSString *)ProdPicment Descri:(NSString *)ProdDescri Artrf2:(NSString *)ProdArtrf2 Um:(NSString *)ProdUm Embap: (NSString *)ProdEmbap Desmax:(NSString *)ProdDesmax Imgap:(NSString *)ProdImgap Aplica:(NSString *)ProdAplica Qatu_01:(NSString *)ProdQatu_01 Qatu_11:(NSString *)ProdQatu_11 Qatu_12:(NSString *)ProdQatu_12 Qatu_13:(NSString *)ProdQatu_13 Qatu_14:(NSString *)ProdQatu_14 Prprom:(NSString *)ProdPrprom R_E_C_N_O_:(NSString *)ProdR_E_C_N_O_ {
self.Cod = ProdCod;
self.Prv1 = ProdPrv1;
self.Grupo = ProdGrupo;
self.Picment = ProdPicment;
self.Descri = ProdDescri;
self.Artrf2 = ProdArtrf2;
self.Um = ProdUm;
self.Embap = ProdEmbap;
self.Desmax = ProdDesmax;
self.Imgap = ProdImgap;
self.Aplica = ProdAplica;
self.Qatu_01 = ProdQatu_01;
self.Qatu_11 = ProdQatu_11;
self.Qatu_12 = ProdQatu_12;
self.Qatu_13 = ProdQatu_13;
self.Qatu_14 = ProdQatu_14;
self.Prprom = ProdPrprom;
self.R_E_C_N_O_ = ProdR_E_C_N_O_;
return self;
}
A: The problem is probably here:
...
[cell.contentView addSubview:label];
...
you continuously add new labels to the cell, even if it is reused (returned by dequeueReusableCellWithIdentifier)
You should add your labels in the block where you create your cell. Later, if the cell is reused just get the labels from the cells using the assigned tags and change the text according to the new data.
if (cell == nil) {
// this is invoked when dequeueReusableCell returns nil - we actually create the label
cell = [[[iMAPTabela alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(0.0, 0, 50.0, tableView.rowHeight)] autorelease];
[cell addColumn:70];
label.tag = TAG_1;
label.font = [UIFont systemFontOfSize:12.0];
label.text = ArrayProdutos.Cod;
label.textAlignment = UITextAlignmentRight;
label.textColor = [UIColor blueColor];
label.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview:label];
}
//this is invoked every time UITableView asks for a cell
UILabel *labelToChange = [cell.contentView viewWithTag:TAG_1];
labelToChange.text = text = ArrayProdutos.Cod;
A: I got same problem long time ago. This is the solution of it.
You need to remove existing labels before u add new ones, as new labels are overlapping on existing labels.
NSArray *subviews = [[NSArray alloc] initWithArray:cell.contentView.subviews];
for (UILabel *subview in subviews) {
[subview removeFromSuperview];
}
[subviews release];
Happy coding...
Stay Hungry, Stay Foolish.
A: My problem was that I had 9 tableviews in one view controller (a carousel of tableviews) and was using one cell identifier for all of them. I resolved this issue by assigning separate identifiers(9,in my case, different identifiers for each of my tableviews) for each tableview cell.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"ProjectTableviewCell";
TimesheetTableviewCell *cell = [tableView dequeueReusableCellWithIdentifier:[NSString stringWithFormat:@"ProjectTableviewCell %li",tableView.tag]];
if (!cell) {
cell = [[TimesheetTableviewCell alloc] initWithReuseIdentifier:CellIdentifier];
}
TimesheetWeek *week = [LoginVC getTimesheetWeeks][tableView.tag];
Project *project = week.currentData[indexPath.row];
[cell setCellProject:project];
cell.delegate = self;
return cell;
}
Screenshots before & after:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515491",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: make the element in the div align vertically middle This is the live example:
http://jsfiddle.net/NjnAF/
The div#con is the search result panel,I want the search item displayed in the list manner with the icon and text.
Now I can not make the icon align middle vertically and make the text the "1" "2" just in the center of the image.
Any suggestion?
A: I used :
div.item div.img {
float: left;
width: 22px;
height: 25px;
background-image: url('http://i.stack.imgur.com/NpSHB.gif');
background-repeat: no-repeat;
background-position: center left;
text-align: center;
vertical-align: middle;
}
and I have updated the fiddle. Is that what you needed?
A: Use line-height - vertical alignment: block level elements, like a div do not have any effect with vertical alignment. You would need to use line-height or use absolute positioning with div as relative.
A: you need to modify the CSS
div.item div.img{ text-align:center;
margin-top:2px; /*can change this according to your need */
}
Add these two properties. Vertical align will not work. Fiddle http://jsfiddle.net/NjnAF/2/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515497",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Re-evaluating a var in python Consider the following pseudo-code:
class Atrribute(object):
def __init__(self):
self.value = 0
def get():
self.value = random(10)
def func(var):
lambda var: return var+1
1) myFunc = func(Attribute().get())
2) myFunc()
3) myFunc()
Now, when I call myFunc() in line 2 I get a random value from 0 to 10 (plus one) which was produced by the get() function in Attribute. The problem is that when I call myFunc() in line 3, I get the same random value from line 2. Is there anyway I can make python initiate the get() function again on line 3 to produce a new random value?
Meir
A: Yes, there is:
import random
class Attribute(object):
def __init__(self):
self.value = 0
def get(self):
self.value = random.random() * 10
return self.value
def func(fn):
return lambda: fn() + 1
att = Attribute()
myFunc = func(att.get)
print myFunc()
print myFunc()
In future, please make sure that any code that you post is free of syntax errors and actually does what you say it does.
A: How about:
def myFunc():
return random(10)
A: Your code (if written correctly and as I believe you intended it) would only call Attribute.get() once,, on lin 1. Then assigns the value returned to the variable 'myFunc'.
Try this instead:
class Atrribute(object):
def __init__(self):
self.value = 0
def get():
self.value = random(10)
def func(var):
return var+1
1) a = Attribute()
2) myFunc = a.get
3) func(myFunc)
4) func(myFunc)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515499",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How would I change the default loaded view controller in Xcode? How would I do this? Is it simple enough to explain clearly? If not, a tutorial would be nice. I checked the web and this site and still couldn't find exactly what I was looking for.
A: The default XIB file loaded when your application start is MainWindow.xib by default.
If you want you app to load another XIB instead, this can be changed in the Info.plist file of your project.
In this XIB loaded when the app is launched (MainWindow.XIB by default), you will find:
*
*a placeholder for the File's Owner (like in any XIB) which in the case of the XIB loaded by the application on startup is the UIApplication itself.
*a UIWindow (the main and unique window of your iPhone app),
*an object that acts as the delegate of your UIApplication (commonly called "the AppDelegate")
*And probably a UIViewController too.
When the XIB is loaded at startup, the AppDelegate objet is instanciated (like all objects in the XIB except the File's Owner) and as it is set as the delegate of the application, application:didFinishLaunhcingWithOptions: will be executed. This code then generally add the viewController's view as a subview of your app window using a line like [self.window addSubview:self.viewController.view]. (As your AppDelegate have an IBOutlet that points to the ViewController in the XIB)
If you need to change the class of the ViewController used in your MainWindow.xib, change the class of the UIViewController in Interface Builder, and also change the type of the associated IBOutlet in the AppDelegate header file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515501",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to organise classes, packages How do you decide what a package name should be and what class should go into what package ?
I'm working on a project where I am constantly adding/removing classes and not really sure if I need a new package, or should add it to an existing one that im not currently aware of.
Do you follow a set of rules when creating a new package ?
How do you know if you are not duplicating package functionality ? Is this just down to familiarity with the project.
Any pointers appreciated.
A: I don't believe there are any hard and fast rules on packaging convention (though I could be wrong). Normally I break it up into
com.mycompanyname and then:
*
*api
*controllers
*data (for models)
*jobs (for cron jobs)
*reporting
*servlet
*utils
If I find I have a class which does not fit into any of those, then I create a new package.
A: I strongly discourage from organizing packages from an implementational point of view, like controllers, data, etc. I prefer grouping them by functionality, that is, feature1, feature2, etc. If a feature is reasonably complex and requires a large number of classes, then (and only then) I create subpackages like above, that is, feature1.controllers, feature1.data, etc.
A: Classes should do one thing (Single Responsibility Principle).
Classes that do related things should go in the same package. If you find you can more closely relate some of the classes in a package, make them a subpackage!
For example, if I had a project with these classes:
*
*GreetingInputWindow
*GreetingDatabaseObject
*GreetingDatabaseConnector
I might just put them all in the greeting package. If I wanted to, I might put GreetingInputWindow in the greeting.ui package, and the other 2 into the greeting.db package.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515503",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Maven project with native dependency and copying files I have the following scenario:
mylib is a library (for which I have the sources, so I'd like to put them into a Maven project mylib:mylib for example). This library has a jar dependency for which I only have the jar, and it is not to be found in the Maven repository (and I do NOT want to install it there either). To make it compile, something like this would work: add the jar file to the mylib project in a "lib" folder, e.g. "lib/thirdpartylib.jar" and in mylib's pom.xml, add a dependency with self-chosen group/artifact/version and a "<scope>system</scope><systemPath>${project.basedir}/lib/thirdpartylib.jar</systemPath>" entry. The mylib project will compile fine.
Note that mylib also has a runtime dependency to a dll file, say thirdparty.dll. But for compilation this is not important.
However, now what I am wondering how to achieve the following:
Any other projects, e.g. project "X", that uses mylib, will need the
- mylib.jar
- thirdpartylib.jar
- thirdpartylib.dll
,
and it'll have to set the java.library.path to the directory (e.g. ".") such that the thirdparty jar and dll are found by the executing VM.
My concern is this: I would like the thirdparty jar/dll things to be the responsibility of the mylib project. I.e. I want to define the knowledge, that you need to copy the thirdparty jar and dll to the target folder and that java.library.path refers to them, to be part of the mylib project (the mylib pom knows how the thing is to be used in other projects). Yet, I want this knowledge (i.e. copy instructions, regardless how they are exactly done in Maven) to be transitively handed over to any other project using mylib, like X for example. Is that somehow possible?
[My hack solution for now would be that I have a copy of the thirdparty things in X, but even then I dunno how to copy/deal with the dll file, so I'd have to write a readme saying that the dll file has to be copied to the bin folder of the executing VM).
Any suggestions are appreciated!
A: The base idea is the following:
*
*Maven is good in handling with one result per Maven POM.
*It is possible to have libraries and dependencies to these libraries in your local repositories only.
So you have to do the following steps:
*
*Define for the additional library a separate project (or a module in your project) and define the library as the result.
*Change your POM so that this POM has now a dependency to the new project.
*Do the same steps for your DLL (see the post Managing DLL dependencies with Maven) how to do that).
*Deploy your additional library and your DLL to your local repository.
Now you should be able to use Maven for the build process again, and by using additional plugins like the maven-assembly-plugin, you are able to pack all together.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515504",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Request Processing Model of HTTP Intermediaries Does anyone know of an overview or comparision table of the common HTTP intermediaries (caches) such as Squid, Varnish, TrafficServer,...?
I am looking in particular for information about their request handling approach (sync vs async, multi-process, multi-threaded etc.)
(I am investigating options I have with regards to ESI. Where my ESI-approach might involve executing a substantial amount of logic during request handling)
Jan
A: One of the big complaints I've read so far is that Varnish processes (replaces) the ESI parts of a (cached) response sequentially. I'm not aware of a concurrent processing implementation, but it would be interesting to see a comparison of the solutions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515506",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: WCF POST method doesn't get called I've created a WCF REST service and initially used .Net Framework version 4. The service has two methods, one returns a plain string with the service status. The second allows a file to be uploaded. Both methods were working fine.
I was asked to see if the project could be moved back to only depend on .Net Framework 3.5 instead of version 4. I changed some references, and it built ok, and when I use the existing C++ client I can use the GetStatus method fine. However, now when a file gets uploaded, the client sees successful return codes to all methods, but, when I set a breakpoint at the start of WCF service's FileUpload method, it never gets executed. The file doesn't gets uploaded, it just disappears into the ether.
[ServiceContract]
internal interface IMyWebService
{
[OperationContract]
[WebGet(UriTemplate = "/Status", BodyStyle=WebMessageBodyStyle.Bare)]
Stream GetStatus();
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/FileUpload/{fileName}")]
Stream FileUpload(string fileName, Stream fileStream);
}
I've tried to use the WFetch tool as an alternative client. When I call the FileUpload method, I get this log:
started....WWWConnect::Close("localhost","80")\nclosed source port: 15800\r\n
WWWConnect::Connect("localhost","80")\nIP = "[::1]:80"\nsource port: 15866\r\n
REQUEST: **************\nPOST http://myMachine/MyService/FileUpload/hello.txt HTTP/1.1\r\n
Host: localhost\r\n
Accept: */*\r\n
Content-Length:11\r\n
\r\n
hello thereRESPONSE: **************\nHTTP/1.1 415 Missing Content Type\r\n
Content-Length: 0\r\n
Server: Microsoft-HTTPAPI/2.0\r\n
Date: Thu, 22 Sep 2011 13:26:09 GMT\r\n
\r\n
finished.
Could anybody give me any pointers for how I can diagnose this issue? I'm having trouble seeing where to start because no breakpoints get hit, and there are no error codes to investigate.
The WCF service must be doing something, because if I stop it, the client then fails to upload files, I just can't understand why execution never gets to the method that implements the POST operation.
Hmm, when using WFetch, even if I misspell the name of the method, it still seems to succeed with no error.
Thanks.
A: I'd start troubleshooting with the original 4.0 version of the service and a C# WCF-based test client to verify the service code will actually upload a file successfully. You could use the code in this Technet article for developing the test client.
Next, use your C++ client against the 4.0 service to verify your client will successfully send a file. Lastly, set the service back to 3.5 and see if it still works. To log messages the service is receiving for troubleshooting, look at this MSDN post to configure the built-WCF message logging capability.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Netsuite with Mule ESB How do I obtain the modified records of employees for a certain period of time?
How to get list of role?
how to delete record of role and department from employee?
I'm using the Mule Cloud connector to NetSuite.
Thx.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515511",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Rails 3 syntax error in development when line is split into multiple lines in controller When I was developing my project on my local file I had this line in code which worked correctly:
@json = Location.qty_of_deliv_from(params[:from_rc])
.qty_of_deliv_to(params[:to_rc])
When I deployd with passenger I get a syntax error on this line which goes avay if I have all the code in the same line:
@json = Location.qty_of_deliv_from(params[:from_rc]).qty_of_deliv_to(params[:to_rc])
Is this a known issue?
A: Perhaps your server's ruby version is different and parses differently?
In any case, in Ruby, when writing multiline code you typically want to make sure your lines to be wrapped are syntactically incomplete, so as not to confuse the parser, e.g. by using a hanging dot, instead.
Location.qty_of_deliv_from(params[:form_rc]).
qty_of_deliv_to(params[:to_rc])
Or you can use the backslash to escape the new line:
Location.qty_of_deliv_from(params[:form_rc]) \
.qty_of_deliv_to(params[:to_rc])
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515512",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: SQL Select statement Where time is *:00 I'm attempting to make a filtered table based off an existing table. The current table has rows for every minute of every hour of 24 days based off of locations (tmcs).
I want to filter this table into another table that has rows for just 1 an hour for each of the 24 days based off the locations (tmcs)
Here is the sql statement that i thought would have done it...
SELECT
Time_Format(t.time, '%H:00') as time, ROUND(AVG(t.avg), 0) as avg,
tmc, Date, Date_Time FROM traffic t
GROUP BY time, tmc, Date
The problem is i still get 247,000 rows effected...and according to simple math I should only have:
Locations (TMCS): 14
Hours in a day: 24
Days tracked: 24
Total = 14 * 24 * 24 = 12,096
My original table has 477,277 rows
When I make a new table off this query i get right around 247,000 which makes no sense, so my query must be wrong.
The reason I did this method instead of a where clause is because I wanted to find the average speed(avg)per hour. This is not mandatory so I'd be fine with using a Where clause for time, but I just don't know how to do this based off *:00
Any help would be much appreciated
A: Fix the GROUP BY so it's standard, rather then the random MySQL extension
SELECT
Time_Format(t.time, '%H:00') as time,
ROUND(AVG(t.avg), 0) as avg,
tmc, Date, Date_Time
FROM traffic t
GROUP BY
Time_Format(t.time, '%H:00'), tmc, Date, Date_Time
Run this with SET SESSION sql_mode = 'ONLY_FULL_GROUP_BY'; to see the errors that other RDBMS will give you and make MySQL work properly
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515514",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: svcutil.exe generates errors while wsdl.exe runs through without I'm looking into generating a web-service conforming to the WSDL found at:
http://assets.cdn.gamigo.com/xml/connection-service/1.0.10/account.wsdl
When I run with svcutil.exe like this:
svcutil.exe /language:C# /out:GamigoServices.cs http://assets.cdn.gamigo.com/xml/connection-service/1.0.10/account.wsdl
I get these errors:
Error: Cannot import wsdl:binding
Detail: The given key was not present in the dictionary.
XPath to Error Source: //wsdl:definitions[@targetNamespace='http://connection.ga
mes.gamigo.com/v_1_0']/wsdl:binding[@name='DefaultAccountServiceServiceSoapBindi
ng']
Error: Cannot import wsdl:port
Detail: There was an error importing a wsdl:binding that the wsdl:port is depend
ent on.
XPath to wsdl:binding: //wsdl:definitions[@targetNamespace='http://connection.ga
mes.gamigo.com/v_1_0']/wsdl:binding[@name='DefaultAccountServiceServiceSoapBindi
ng']
XPath to Error Source: //wsdl:definitions[@targetNamespace='http://connection.ga
mes.gamigo.com/v_1_0']/wsdl:service[@name='AccountService']/wsdl:port[@name='Acc
ountServicePort']
I also tried a tool, Wscf:Blue, which gives me the same errors (it's a WCF VS plugin which, supposably, would do yet a lot more for me once I get past this step).
On the other hand, if I use wsdl.exe (which I don't want because I want to use WCF, and, as far as I understand, I need to use svcutil.exe for WCF, but I just tried wsdl.exe in my attempts to narrow down the source of the problems) like this:
wsdl.exe http://assets.cdn.gamigo.com/xml/connection-service/1.0.10/account.wsdl /serverInterface
there are no errors.
I've been trying all kinds of things with local copies of the WSDL (and the types.xsd which it references), commenting out sections etc. to narrow down the problem. However, it really boils down to exactly what the error message is referring to, the definition of that binding. I've also googled, but the few references to this kind of error are not helpful at all.
Besides, I'm particularly puzzled by the fact that wsdl.exe seems perfectly fine with that WSDL. I also used
http://xmethods.net/ve2/WSDLAnalyzer.po# to validate the WSDL, no errors were shown.
So, now I'm at the point where I really got no idea how to proceed. As the whole issue is somewhat time-critical - by next week I should really start with implementation -, I might end up using the code generated by wsdl.exe and going for the older technology obsoleted by MS, but for several (obvious) reasons I'd rather not go that route. So if anyone has any idea what to do to make svcutil.exe work with that, I'd be grateful.
I might add that while I cannot modify the definition, I might be able to convince the publisher of that WSDL to perform certain edits or at least publish a second version for my purposes.
Many thanks,
Max
Vienna,
Austria
A: step1. Stare at your WSDL file
step2. ensure that the wsdl:portType "aligns with" wsdl:binding (i.e. all operations are defined in a corresponding way under portType and binding).
step3. Thank me for the best advice ever when dealing with svcUtil errors such as "the given key was not present in the dictionary" :-)
A: Svcutil.exe is used for the WCF service. If its a web service wsdl.exe will work fine. I think you are using the svcutil.exe for the web service so it is giving error.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515515",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: CSS/HTML scrolling text without scrollbars all!
I need to make effects with like on the picture. I can make text shading (transparent imgage on top and bottom of a text) but I have no idea how to make scrollable text without scrollbars and clipping (overflow: hidden). Have eny idea?
I have only one idea - add image over scrollbar to hide it from users
A: Try this out:
<div id="container" style="width: 183px; height: 183px; overflow:
hidden; border: solid black 1px">
<div id="floating-div" style="width: 200px; height:200px; overflow:
auto">
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</div>
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515518",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Is Android's Visualizer class's handling of media volume inconsistent across different devices? I have made a music visualizer app for Android. While developing on my HTC Legend (running Android 2.2), I noticed that setting the "media volume" of the phone had no effect on the output of the Visalizer class, i.e. I always got the full-volume amplitude data of the playing music, regardless of the volume setting, which was great because that's precisely what I want.
I have recently purchased an Asus EEE transformer tablet, running Android 3.2, and now the user-set volume DOES impact the volume of the data I get back from the Visualiser class.
Does anyone know what the official behaviour should be? I'd hope for volume independence, but the evidence I've seen points to inconsistent behaviour across different devices...
Is this a driver issue, or has the behaviour changed in 3.2?
Thanks!
Nils
A: Refere this link here. I think that you are not enable equalizer and visualizer for same seesion id.Accroding to me Audio effects need equalizer engine enable for audio modifications settings.Otherwise it gives higher values and it will be affected by media volume also.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515519",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to do a generic call to function based on a Type object? how do you execute Get, when all you have is: T expressed as a Type object i.e.
Type type=typeof(int);
and arguments param1 and param2?
public void DoCall(){
var type=typeof(int);
// object o=Get<type> ("p1","p2"); //<-- wont work (expected)
// *** what should go here? ***
}
public IEnumerable<T> Get<T>(string param1,string param2) {
throw new NotImplementedException();
}
A: You need to use reflection:
public IEnumerable GetBoxed(Type type, string param1, string param2)
{
return (IEnumerable)this
.GetType()
.GetMethod("Get")
.MakeGenericMethod(type)
.Invoke(this, new[] { param1, param2 });
}
A: MakeGenericMethod is the key:
var get = typeof(WhereverYourGetMethodIs).GetMethod("Get");
var genericGet = get.MakeGenericMethod(type);
A: What's wrong with just using the generic type parameter directly?
public void DoCall(){
IEnumerable<int> integers = Get<int> ("p1","p2");
// ...
}
A: In the example above the 'T' will be whatever you pass into the Get method and it will also return the same IEnumerable. So if you do the following:
IEnumerable<int> o = Get<int>("p1", "p2");
o will be IEnumerable
but if you want something else, then you just pass in a different Type, hence Generic types.
A: If possible, you should redefine your Get method to take the type of object as an argument:
public IEnumerable<object> Get(object type, string param1,string param2)
{
}
Then if you really need it, you can rewrite the original generic method as follows:
public IEnumerable<T> Get<T>(string param1,string param2)
{
var result = Get(typeof(T), param1, param2);
return result.Cast<T>();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515521",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Location of VB.NET Windows Service My.Settings - settings I have a VB.NET solution built in Visual Studio 2010. It consists of a class project, a service, and a setup project. I have successfully created a setup, and run the setup from the "Release" directory of the setup project (outside of Visual Studio). It installed the service (on the same machine as where the project is), and the service seems to be running fine. The service executable is installed in a directory under c:\program files (x86)\ along with some DLL's it is dependent of.
The service (actually the class project I mentioned above) uses some settings from My.Settings. As far as I know these settings are stored in a app.config file in the project directory, as well as in a settings.settings file in the My Project directory under the project directory.
Neither of these files are installed by the installer. But the service can only run if it can read the settings. So where does my service get these settings from? To check if it still reads the settings from the VS project directory, I have temporarily renamed that directory, but that didn't affect the correct operation of the service.
A: look on this path. Find your service name and navigate down until you find user.config
C:\Windows\System32\config\systemprofile\AppData\Local\
The user.config only has the settings that your service has updated the others will in the exe.config on the service install path.
Protected Overrides Sub OnStart(ByVal args() As String)
My.Settings.TimerMsInterval = thisTimer.Interval
My.Settings.MoreMsgs = My.Settings.MoreMsgs
My.Settings.LastTime = My.Settings.LastTime
My.Settings.Save()
EventLog.WriteEntry("Startup Parameters: TimerMsInterval: LastTime: MoreMsgs " & thisTimer.Interval.ToString & " : " & My.Settings.LastTime & " : " & My.Settings.MoreMsgs)
End Sub
A: Have a look in the Virtual Store C:\Users\User_name\AppData\Local\VirtualStore\
A: I found the answer myself: the settings of the class project are stored within the class projects DLL-file. So they cannot be edited after the service (that uses this DLL) has been installed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515525",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Constructor initialization order and reference passing Hi I have a question about the constructor initialization order. Given below
struct B {}
struct A
{
B& b;
A(B& b) : b(b) {}
}
struct C
{
B b;
A a;
C() : b(),a(b) {}
}
struct D
{
A a;
B b;
D() : a(b),b() {}
}
I know that C is valid as b gets initialized before a. But what about D? b wouldn't have been constructed yet, but the address should already be known, so it should be safe?
Thanks
A: They're both valid because A doesn't call into B at all. If A accessed a data member or member function of B, then that would be invalid. In the existing case of A, it's impossible to produce an invalid example.
A: just a sample to show you when stuff happens
struct B {
B() {
print("struct B / constructor B", 1);
}
};
struct A
{
B& b;
A(B& b) : b(b) {
print("struct A / constructor with B", 1);
};
};
struct C
{
B b;
A a;
C() : b(),a(b) {
print("struct C / constructor C", 1);
};
void dummy()
{
print("dummy",1);
}
};
struct D
{
A a;
B b;
D() : a(b),b() {
print("struct D / constructor D", 1);
};
void dummy()
{
print("dummy",1);
}
};
int main(int argc, char* argv[])
{
D dTest;
dTest.dummy();
C cTest;
cTest.dummy();
}
--- output
struct A / constructor with B
struct B / constructor B
struct D / constructor D
dummy
struct B / constructor B
struct A / constructor with B
struct C / constructor C
dummy
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515528",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Azure BLOB storage - Pricing and speed "Within the data center" I am quite sure I know the answer, just want to make sure I got this right.
From Azure In Action :
If I use the CloudBlobClient from a WCF service that sits in my WebRole, to access blobs (read/write/update) , so :
1) Does read/write/update charge as transaction or are they free ?
2) Does the speed of accessing those blobs is fast as mentioned in the note ?
A:
If I use the CloudBlobClient from a WCF service that sits in my
WebRole, to access blobs (read/write/update) , so :
1) Does read/write/update charge as transaction or are they free ?
Transaction metering is independent of where the requests are made from. Storage read/write/update is done via REST API calls (or through an SDK call that wraps the REST API calls). Each successful REST API call will effectively count as a transaction. Specific details of what constitutes a transaction (as well as what's NOT counted as a transaction) may be found here.
By accessing blob storage from your Worker / Web role, you'll avoid Internet-based speed issues, and you won't pay for any data egress. (Note: Data ingress to the data center is free).
2) Does the speed of accessing those blobs is fast as mentioned in the note ?
Speed between your role instance and storage is governed by two things:
*
*Network bandwidth. The DS and GS series have documented network bandwidth. The other sizes only advertise IOPS rates for attached disks.
*Transaction rate. On a given storage account, there are very specific documented performance targets. This article breaks down the numbers in detail for a storage account itself, as well as targets for blobs, tables and queues.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515529",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: whats faster, count(*) or count(table_field_name) in mysql?
Possible Duplicate:
COUNT(*) vs. COUNT(1) vs. COUNT(pk): which is better?
I want to retrieve the count from a select query.
What is faster: count(*) or count(table_field_name)?
I want to know which way is faster for performance.
A: The difference is Count(field) returns count of NOT NULL values in the field, whether COUNT(*) returns COUNT of rows.
COUNT(*) in MyIsam should be faster.
http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_count
A: at least on MyISAM tables count(*) should be faster than count(fliedname) as it allows mysql to use an index (the primary key most times) to do the counting. if the given fieldname is the primary key, it wont make any difference.
using *, mysql wont be so dump to "load the data of the entire row" as others said - count(*) is always the fastest or one of the fastest options while count(fieldname) could be slower, depending on what field is given.
EDIT:
the documantation says:
COUNT(*) is optimized to return very quickly [...]. This optimization applies only to MyISAM tables only
read on the documentation for more information about this topic.
Important note: count(*) returns to total count of rows while count(fieldname) returns the count of rows there that given field isn't NULL. this is logically consistent as with * mysql can't know wich NULL-values to leave out. always think of this when doing count() as it may have a bic impact on the result.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7515531",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.