text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Raw SQL with Doctrine I want to execute a query in raw SQL with Doctrine. I have an error but I don't know where.
$my_id = 12;
$pdo = Doctrine_Manager::getInstance()->getCurrentConnection()->getDbh();
$q = 'SELECT date FROM my_table WHERE my_text LIKE "%'.$my_id.'%" ORDER BY date DESC LIMIT 1';
$r = $pdo->query($q)->fetchOne();
$result['date'] = $r->date;
The error is $pdo->fetchOne(); : "Call to undefined method PDO::fetchOne()"
I have the same message with fetchAll().
How can it be fixed?
A: Answer as written in comments:
Here is the correct code :
$conn = Doctrine_Manager::getInstance()->getCurrentConnection();
$q = 'SELECT date FROM my_table WHERE ...';
$r = $conn->fetchAssoc($q);
echo $r[0]['date'];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612280",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can I wait for location.href to load a page? Is it possible to know when a page has loaded using location.href? My current code looks like this and I want to trigger some events to happen once my page has finished loading. I tried using $.get but it breaks my current implementation of jquery address so this won't work.
$('.search').click(function(){
location.href = "/search.php";
// trigger event here...
return false;
});
This will NOT work for my current setup:
$.get('search.php', function() {
alert('Page has finished loading');
});
Are there any other options?
A: Have you tried this:
$(document).ready(function () {
alert('Page has finished loading');
});
EDIT: Removed second portion of answer since the purposeful redirect negates it's usefullness
A: Once you change your location, your page unloads. You cannot run script after doing so. All you can do is detect when the new page has loaded within the new page as @DJ Quimby's answer describes.
An exception is if you change your hash location but stay within the same document. That can be bound to an event using jQuery.
A: That will simple redirect the browser...
You want to use...
$.ajax({ ... });
Call using jQuery to call search.php and you can then load the results into a div or something.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612285",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: I have a CSS overflow issue On this website http://rwl.rwlwater.com/ I have a small issue... I added overflow: hidden to the featured slider div, the pictures were showing up stacked if the javascript was enabled or the user had a slow internet connection..
But now I have another problem.. The description had a little thing positioned outside the slider and it's hidden now...If I add overflow-x: visible it adds the scroll bar and that's not what I want. I want the description to be fully visible, but the overflow-y to be hidden.
A: change it to
overflow-x: auto;
overflow-y: hidden;
Check out http://www.brunildo.org/test/Overflowxy2.html for examples of all combinations
A: In your #slides .description change
right: -11px;
to
right: 11px;
or something similar.
Works for me in Chrome inspect element.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612286",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How bad it is to keep calling malloc() and free()? I'm sending a text file - client-server
breakup the text into packets each of 512 bytes
but some packets contain text less than max size so on the servers side when receiving each packet I'm calling malloc() to build a string again , is this a bad practice ?
is it better to keep a working buffer that can fit for max length and keep iterating , copying and overwriting its values ?
okay @n.m. here is the code , this if is inside a for(;;) loop wakened by the select()
if(nbytes==2) {
packet_size=unpack_short(short_buf);
printf("packet size is %d\n",packet_size);
receive_packet(i,packet_size,&buffer);
printf("packet=%s\n",buffer);
free(buffer);
}
//and here is receive_packet() function
int receive_packet(int fd,int p_len,char **string) {
*string = (char *)malloc(p_len-2); // 2 bytes for saving the length
char *i=*string;
int temp;
int total=0;
int remaining=p_len-2;
while(remaining>0) {
//printf("remaining=%d\n",remaining);
temp = recv(fd,*string,remaining,0);
total+=temp;
remaining=(p_len-2)-total;
(*string) += temp;
}
*string=i;
return 0;
}
A: There is overhead associated with calling malloc and free. A block has to be allocated from the heap and marked as in use, when you free the revese happens. Not knowing what OS or complier you are using, this could be in the c library or at the OS memory managment level. Since you are doing a lot of mallocs and frees you could wind up severly fragmenting your heap where you may not have enough contiguous free memory to do a malloc elsewhere. If you can allocate just one buffer and keep reusing it, that is generally going to be faster and have less danger of heap fragmentation.
A: I have found that malloc, realloc and free are pretty expensive. If you can avoid malloc it is better to reuse the memory that you've already got.
Edit:
It looks like I am wrong about how expensive malloc is. Some timing tests with the GNU C Library version 2.14 on Linux show that for a test that loops 100,000 times and allocates and frees 512 slots with random sizes from 1 to 163840 bytes:
tsc average loop = 408
tsc of longest loop = 294350
So wasting 408 cycles doing malloc or new in a tight inner loop would be a silly thing to do. Other than that don't bother worrying about it.
A: Malloc is generally fairly inexpensive. It is only expensive if it generates a syscall to get more heap space. For instance, in UNIX-Like systems it will eventually generate an sbrk call which will be expensive. If you repeatedly malloc and free the same size of memory, it will do it crazy fast. For instance, consider the following little test program:
#include <stdlib.h>
int main()
{
int i=0;
int *ptr;
for(int i=0; i<1e6; i++) {
ptr = malloc(1024*sizeof(int));
free(ptr);
}
}
It allocates 1024 integers and frees them and does this one million times. Running this on my rather modest little chromebook turned linux machine, I get timings that look like this:
time ./test
real 0m0.125s
user 0m0.122s
sys 0m0.003s
Now, if I comment out the malloc and free part of the loop, I get these timings:
time ./test
real 0m0.009s
user 0m0.005s
sys 0m0.005s
So you see that malloc and free does have overhead, though I think that being just over ten times the overhead of doing nothing is terribly much overhead.
It is especially fast if it can just keep reusing the same chunk of heap over and over again (as is the case here). Of course, if I kept repeatedly allocating and growing the program, it would take more time because that would result in a few syscalls.
Of course, your mileage may vary depending on OS, compiler, and stdlib implementation.
A: In your example, your function already contains a syscall, so the relative cost of malloc/free will be virtually unmeasurable. On my system, a malloc/free "round trip" averages about 300 cycles, and the cheapest syscalls (getting the current time, pid, etc.) cost at least 2500 cycles. Expect recv to easily cost 10 times that much, in which case the cost of allocating/freeing memory will be at most about 1% of the total cost of this operation.
Of course exact timings will vary, but the rough orders of magnitude should be fairly invariant across systems. I would not even begin to consider removing malloc/free as an optimization except in functions that are purely user-space. Where it's probably actually more valuable to go without dynamic allocation is in operations that should not have failure cases - here the value is that you simplify and harden you code by not having to worry about what to do when malloc fails.
A: Calling multiple malloc/free can actually increase the memory used by your process (without any leaks involved), if the size passed to malloc is variable, as proven by this question:
C program memory usage - more memory reported than allocated
So the single buffer approach is probably best.
A: Only testing can tell. When programming in C I do err on the side of avoiding malloc though, since memory leaks can be quite hard to fix if you create one by accident.
A: Measure the performance of the two solutions. Either by profiling or measuring throughput. It's impossible to say anything for certain.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612292",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
}
|
Q: Session State Issue When visiting a page, I am storing a value in session state. When I click back on the browser, the value in session reverts to its original value. Why does this happen? I am not resetting the value when i go back.
This happens on iPhone and iPad - all other browsers do NOT roll back the session state value.
Thanks in advance.
I am using this javascript code (code in both pages is identical):
function pageLoad() {
// Get the current url path
var url = document.URL;
PageMethods.IsNavigatingBackward(url, handleCallback);
}
function handleCallback(isBackward) {
if (isBackward) {
// Go back to previous page
history.back();
}
else {
// Set the current url in the session
var url = document.URL;
PageMethods.SetCurrentPage(url, getLocation);
}
}
And the code behind:
[WebMethod]
public static bool IsNavigatingBackward(Uri url)
{
string currentPath = url.LocalPath;
string lastPath = (string)HttpContext.Current.Session["LastPage"];
bool isBackward = false;
NavigationList table = NavigationList.GetInstance();
if (table.IsBackwardNavigation(currentPath, lastPath))
{
isBackward = true;
}
return isBackward;
}
[WebMethod]
public static void SetCurrentPage(Uri url)
{
HttpContext.Current.Session["LastPage"] = url.LocalPath;
}
A: You will only see the new session state value if the browser is:
*
*Accepting cookies
*Not showing you the cached original page
If both are these are true and assuming you're not reverting the value somewhere on the second page load, you will see the session state.
It would appear iPhone and iPad are not doing this.
A: I think you are misunderstanding what's going on. More than likely, the page is not being re-downloaded (and thus the session is not actually being set to anything). it's just using the previously cached downloaded page.
A: Can you try using the following instead:
[WebMethod(EnableSession = true)]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612295",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can I reuse a TCP connection? I'm connecting to a website and retrieving HTTP data by sending it a GET request. And I have to connect to the same site twice to retrieve two different pages. I'm new to network programming but I believe the connect function connects to the server, and creates a tcp connection.
Now each time I connect to the server to retrieve the HTTP data, it has to create a new tcp connection, is there any way I can reuse the old one? It's retrieving the http data immediately after the other.
It's not that big of a deal but I'm curious.
A: You could use HTTP 1.1 where connection are persistent or use HTTP 1.0 and send the header "Connection: Keep-Alive".
That way you can fetch a second page without connecting again (just GET again on the same socket).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612297",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: sort NSDictionary values by key alphabetical order I can get an array of dictionary keys sorted by values, but how to I get an array of values sorted by dictionary keys? I've been looking everywhere with no luck. Any help appreciated.
A: This might work:
NSArray * sortedKeys = [[dict allKeys] sortedArrayUsingSelector: @selector(caseInsensitiveCompare:)];
NSArray * objects = [dict objectsForKeys: sortedKeys notFoundMarker: [NSNull null]];
or in Swift
let objects = dict.keys.sorted().flatMap{ dict[$0] }
or
let objects = dict.sorted{ $0.0 < $1.0 }.map{ $1 }
…and that is why you should start developing in Swift
A: One way is to construct the array of sorted dictionary keys, then create another array of the values based on the array of keys:
//Construct array of sorted keys
NSArray keyarray = ... //etc
NSMutableArray valuearray = [[NSMutableArray alloc] init];
for (id key in keyarray) {
[valuearray addObject:[dict objectForKey:key]];
}
A: My experience shows that sorting NSDictionary by keys is not much useful. Although after logging the NSDictionary they seem to be sorted, when needed to put them in a tableview they are not in order any more.
I suggest storing the keys in an NSArray property and then query the NSDictionary objects according to the order of the keys in the NSArray.
A: I created a category on NSDictionary to get this accomplished:
@implementation NSDictionary (Extra)
-(NSArray *) sortedKeys {
return [[self allKeys] sortedArrayUsingSelector:@selector(compare:)];
}
-(NSArray *) allValuesSortedByKey {
return [self objectsForKeys:self.sortedKeys notFoundMarker:[NSNull null]];
}
-(id) firstKey {
return [self.sortedKeys firstObject];
}
-(id) firstValue {
return [self valueForKey: [self firstKey]];
}
@end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612299",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "25"
}
|
Q: What is the proper way of using RMI remote objects on the client side? In a dialog (window) let suppose we have some buttons and when a button is pressed a remote method invocation take place.
How it is better:
*
*create the remote object (registry.lookup()) one time and use this object every time we need a remote method invocation?
*each time we need a remote method invocation we execute registry.lookup() and after this we call the remote method?
A: Just do your lookup once, and cache the reference to the remote object somewhere. The rmiregistry is just used for bootstrapping. Doing a lookup every time will cause lots of unnecessary network calls.
The ServiceLocator pattern talks about it:
The Service Locator pattern centralizes distributed service object
lookups, provides a centralized point of control, and may act as a
cache that eliminates redundant lookups.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612301",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Android Sqlite sqlite3_bind_parameter_count Hi we want to execute statements that contain the standard sqlite named placeholderpatter like "select * from contatct where contactid=@contactid"
Such statements are defined on our server for other applications (iOS, WIndowsPhone etc.)
I found nothing ind the android.database.sqlite namespace that allows such a handling, it is only the placeholder "?" provided- That really sucks, anyone experience with something like that?
We need something like this raw methods in android
sqlite3_bind_parameter_count
sqlite3_bind_parameter_index
sqlite3_bind_parameter_name
Thank you very much.
A: I don't now whether there is a chance of using names but you could use compileStatement() and bind your parameters by its position in the query (e.g. by using named constants).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612303",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can i get a website to open up a page server side? I want to create a callback feature. E.g. The client does something but then we need to open up a page with a few GET variables to one of our partners. Therefore id like to make a PHP script which opens a website with all the data in the URL (The user shouldnt see this, it should be done server sided). How could I do this thanks. A bit like some IPN systems. Sorry that the question is not very well constructed if you need more detail ill provide more.
A: See fopen. If you are expecting to get a response from the other server, you can use file_get_contents to read the response.
A: Take a look at CURL. It's a really powerful API.
A: I like fopen okay, though fsockopen is more appropriate for a remote URL, but I find CURL to be much more powerful. You'll need to have compiled PHP with support for CURL, but it's a default package on many systems. You can check if your current system supports it by pulling up a phpinfo() page and looking for CURL.
The benefit of using CURL is you get really fine grained control over the request and how to handle the response. The php docs have a fairly concise example of how to use CURL; due to the number of options available it can get verbose quickly. The functions you'll use most are curl_init, curl_setopt and curl_exec
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612307",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Maven: Non-resolvable parent POM I have my maven project setup as 1 shell projects and 4 children modules. When I try to build the shell. I get:
[INFO] Scanning for projects...
[ERROR] The build could not read 1 project -> [Help 1]
[ERROR]
[ERROR] The project module1:1.0_A0 (C:\module1\pom.xml) has 1 error
[ERROR] Non-resolvable parent POM: Failure to find shell:pom:1.0_A0 in http://nyhub1.ny.ssmb.com:8081/nexus/content/repositories/JBoss/ was cached in the local repository, resolution will not be reattempted until the update interval of jboss has elapsed or updates are forced and 'parent.relativePath' points at wrong local POM @ line 5, column 11 -> [Help 2]
If I try to build a lone module I get the same error only replace module1, with whatever module it was.
Have them all referencing the parent in their poms.
<parent>
<artifactId>shell</artifactId>
<groupId>converter</groupId>
<version>1.0_A0</version>
</parent>
Here is the relevant parts of the shell pom:
<groupId>converter</groupId>
<artifactId>shell</artifactId>
<version>1.0_A0</version>
<packaging>pom</packaging>
<name>shell</name>
<modules>
<module>module1</module>
<module>module2</module>
<module>module3</module>
<module>module4</module>
</modules>
A: Just add <relativePath /> so the parent in pom should look like:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath />
</parent>
A: Non-resolvable parent POM:
This means you cannot resolve the parent repo.
Trun on debug mode:
[DEBUG] Reading global settings from **/usr/local/Cellar/maven/3.5.4/libexec/conf/settings.xml**
[DEBUG] **Reading user settings from /Users/username/.m2/settings.xml**
[DEBUG] Reading global toolchains from /usr/local/Cellar/maven/3.5.4/libexec/conf/toolchains.xml
[DEBUG] Reading user toolchains from /Users/username/.m2/toolchains.xml
[DEBUG] Using local repository at /Users/username/.m2/repository
[DEBUG] Using manager EnhancedLocalRepositoryManager with priority 10.0 for /Users/username/.m2/repository
[INFO] Scanning for projects...
[ERROR] [ERROR] Some problems were encountered while processing the POMs:
Because the parent repo is not part of the maven central.
The solution is specify a setting.xml in ~m2/ to help result the parent POM. /Users/username/.m2/settings.xml
In that XML, you might need to specify the repository information.
A: It can also be fixed by putting the correct settings.xml file into the ~/.m2/ directory.
A: <relativePath>
If you build under a child project, then <relativePath> can help you resolve the parent pom.
install parent pom
But if you build the child project out of its folder, <relativePath> doesn't work. You can install the parent pom into your local repository first, then build the child project.
A: In addition to the answer by Luke Willis, looks like this:
<parent>
<groupId>com.example</groupId>
<artifactId>some-module</artifactId>
<version>1.0</version>
<relativePath>../pom.xml</relativePath>
</parent>
A: Alternative reason also might be the parent artifact comes from repository which is not accessible from pom.xml, typically private repository. The solution was to provide that repository in pom.xml:
<repositories>
<repository>
<id>internal-repo</id>
<name>internal repository</name>
<url>https://my/private/repo</url>
<layout>default</layout>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
In my case the problem was even more complicated due to Eclipse: the repository was active only in special profile (<profiles><profile><id>activate-private-repo</id><repositories>...) and Maven GUI in Eclipse didn't allow to set this profile through Ctrl+Alt+P shortcut.
The solution was to temporarily declare repository outside profile (unconditionally), launch Alt+F5 Maven Update Project, activate profile and put repository declaration back into profile. This is rather Eclipse bug, not Maven bug.
A: verify if You have correct values in child POMs
GroupId
ArtefactId
Version
In Eclipse, for example, You can search for it:
A: Replace <version>1.0_A0</version> with <version>${project.version}</version>
Run mvn once. This will download all the required repositories. You may switch back to 1.0_A0 after this step.
A: It was fixed when I removed settings.xml from .m2 folder.
A: In this case the parent artifact is not found. As others pointed out, adding <relativePath/> to the pom where you reference a parent that cannot be found locally may work. But why does it work?
If the parent POM is not located in the parent folder, we need to use
the relativePath tag to refer to the location.
...
To skip the local file search and directly search the parent POM
in Maven repositories, we need to explicitly set the relativePath to
an empty value
as they explained here.
In other cases it will not work because the real reason is that Maven is unable to find the settings.xml which specifies the repositories to check for the parent artifact. E.g. when you try to build your Maven project from WSL2 (Linux shell on Windows) where you have not set up your Maven configuration.
In that case you need to create the settings.xml in the .m2 directory of WSL2 or create a reference to it, e.g. via a symbolic link.
(That is a different issue but could be solved like this.)
A: Just for reference.
The joys of Maven.
Putting the relative path of the modules to ../pom.xml solved it.
The parent element has a relativePath element that you need to point to the directory of the parent. It defaults to ..
A: I had similar problem at my work.
Building the parent project without dependency created parent_project.pom file in the .m2 folder.
Then add the child module in the parent POM and run Maven build.
<modules>
<module>module1</module>
<module>module2</module>
<module>module3</module>
<module>module4</module>
</modules>
A: I had the following config in the parent pom:
<properties>
<revision>1.0-SNAPSHOT</revision>
</properties>
<groupId>com.company.org</groupId>
<artifactId>api-reactor-pom</artifactId>
<version>$revision</version>
<packaging>pom</packaging>
And I was getting 'Non-resolvable parent POM' error. I changed version to <version>1.0-SNAPSHOT</version>, and it's gone.
Apache Maven 3.6.3.
A: I solved that problem on me after a very long try, I created another file named "parent_pom.xml" in child module file directory at local and pasted contents of parent_pom.xml,which is located at remote, to newly created "parent_pom.xml".
It worked for me and error message has gone.
A: Inside relative path tag do as follows
<relative>{project_name}/pom.xml</relative>
and then RunAs-> Maven build
It worked for me.
A: I had the issue that two reactor build pom.xml files had the same artefactId.
A: Add a Dependency in
pom.xml:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.8.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.4.3</version>
</dependency>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612309",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "143"
}
|
Q: Get request_token and request_secret from Foursquare I want to get my access_token and access_token_secret from developer.foursquare.com. I read and used
oauth_key = 'my_key'
oauth_secret = 'my_secret'
oauth = Foursquare::OAuth.new(oauth_key, oauth_secret)
request_token = oauth.request_token.token
request_secret = oauth.request_token.secret
also I have tried;
oauth_key = 'my_key'
oauth_secret = 'my_secret'
oauth = Foursquare::OAuth.new(oauth_key, oauth_secret)
oauth.request_token(:oauth_callback => "https://foursquare.com/oauth2/access_token")
request_token = oauth.request_token.token
request_secret = oauth.request_token.secret
but when I run my project I get "OAuth::Unauthorized (404 Not Found):" error. How can I solve it? Does anyone have any idea?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612311",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to show Text in the text file separated by commas in a DataRow or a GridView in c# I have created an application in C#. I want to display the text in the text file separated by commas in a DataRow or a GridView.
I am using this code to display the text in a listbox
private void button1_Click(object sender, EventArgs e)
{
var file = File.OpenText("C:\\File.txt");
string line;
bool flag = true;
while ((line = file.ReadLine()) != null)
{
listBox1.Items.Add(new { srno= line, Date= "descr", Time= DateTime.Now ,symbol = Symbol });
}
}
But its not well for others to understand what its displaying.i want to display something like this
check this link http://i.stack.imgur.com/LEmdz.jpg
There would be great appreciation if someone could help me.
Thanks In Advance.
A: Silly me looks like this is WinForms not asp.net. Got retagged. I'll leave this here for someone else then.
You'll want to turn the file in to a DataTable. There is a decent example of this at http://www.akamarketing.com/blog/256-csv-datatable.html
It's more of a generic approach than anything.
Here is an untested example you could try to work through.
DataTable dataTable = new DataTable();
dataTable.Columns.Add("Srno");
dataTable.Columns.Add("Date");
dataTable.Columns.Add("Time");
dataTable.Columns.Add("Symbol");
while ((line = file.ReadLine()) != null)
{
DataRow row = dataTable.NewRow();
string[] s = line.Split(',');
row["Srno"] = s[0];
row["Date"] = s[1];
row["Time"] = s[2];
row["Symbol"] = s[3];
}
//Add to your GridView that is in your aspx file
gridView.DataSource = dataTable;
gridView.DataBind();
A: Define a class (say Foo) having four public properties - srno, Date,Time, and symbol. Use String.Split method to parse the comma separated string, constructs an object of Foo class and append it to List<Foo>. Finally bind the List<Foo> object to the GridView control.
Demo:
public class Foo
{
public string SrNo {get;set;}
public string Date {get;set;}
public string Time {get;set;}
public string Symbol {get;set;}
}
List<Foo> list=new List<Foo>();
while ((line = file.ReadLine()) != null)
{
string []ar = line.Split(',');
list.Add(new Foo()
{
SrNo=ar[0],
Date=ar[1],
Time=ar[2],
Symbol=ar[3]
});
}
//Bind the list
dataGridView1.DataSource=list;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612313",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Offset UITableView Index - Overlap with iAd I have a table based app with an iAd at the top. I have added a A-Z index to the Table View. The index is now obscured by the iAd at the top.
Can anyone suggest a good way to fix this ?
Thank you.
A: You can drag a UIView on top of a UITableView in Interface Builder to give the UITableView a header or footer view, which you can place the iAd in and have it not interfere with the tableView's contents.
A: If you have an Apple Developer account there is a video from WWDC 2010 that demonstrates how to use iAd. This can be found if you go to: http://developer.apple.com/videos/ which will open iTunes. Then go to WWDC 2010 Sessions -> Application Frameworks -> Session 112 - Integrating Ads with iAds.
This will show you how to move the banner in and out of a view depending on if an ad is loaded correctly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612314",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Play a System Sound using HTML I would like to know if is possible to play a SYSTEM sound using HTML 5 (even with js).
I recently found out this article that show how to do it, but for my understanding is only with attached external sound (like mp3 or other). I would need instead use some OS SYSTEM sound.
Thanks guys for helping to understand css better :)
A: I don't believe this to be possible without something like maybe an ActiveX control, and even then, support would be extremely spotty. If this were possible, it could cause a huge security vulnerability. Why don't you just get a .mp3 of the OS SYSTEM sound that you want to play and use the same trick that you linked to?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612318",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Bash, weird variable scope when populating array with results I am parsing command output and putting results into array.
Works fine until exiting the inner loop - output array is empty.
declare -a KEYS
#-----------------------------------------------------------------------------#
get_keys()
{
# this extracts key NAMES from log in format "timestamp keycode"
$glue_dir/get_keys $ip | while read line; do
echo line: $line
set -- $line # $1 timestamp $2 keycode
echo 1: $1 2: $2
key=(`egrep "\\s$2$" "$glue_dir/keycodes"`) # tested for matching '40' against 401, 402 etc
set -- $key # $1 key name $2 keycode
KEYS+=("$1")
echo key $1
echo KEYS inside loop: "${KEYS[@]}"
done
echo KEYS outside loop: "${KEYS[@]}"
}
The output when run agains two output lines:
line: 1270899320451 38
1: 1270899320451 2: 38
key UP
KEYS inside loop: UP
line: 1270899320956 40
1: 1270899320956 2: 40
key DOWN
KEYS inside loop: UP DOWN
KEYS outside loop:
I spent an hour trying to figure this out. Please help. ;-)
A: When you use a pipe (|) to pass your command output to while, your while loop runs in a subshell. When the loop ends, your subshell terminates and your variables will not be available outside your loop.
Use process substitution instead:
while read line; do
# ...
done < <($glue_dir/get_keys $ip)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612320",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
}
|
Q: Cannot alter table (add unique constraint) in a SQL PL store procedure for db2 I am trying to create a store procedure in SQL PL for db2. A new field needs to be added as part of the unique key, so I need to drop the previous uk first, and then add the new unique key. That worked fine for MS SQLServer and Oracle, but I cannot make it for db2.
CREATE PROCEDURE update_unique_key ()
LANGUAGE SQL
BEGIN
DECLARE uk_constraint_name VARCHAR(50);
DECLARE sql_stmt VARCHAR(100);
SELECT constname INTO uk_constraint_name FROM SYSCAT.TABCONST WHERE tabname = 'TABLE_NAME' AND type = 'U';
SET sql_stmt = 'alter table TABLE_NAME drop constraint ' || char(uk_constraint_name);
SET sql_stmt_2 = 'alter table TABLE_NAME add unique (F1, F2)';
prepare s1 from sql_stmt;
prepare s2 from sql_stmt_2;
EXECUTE IMMEDIATE s1;
EXECUTE IMMEDIATE s2;
END
Getting this error when trying to deploy the routine with IBM Data Studio as client (the database is db2 9.5)
DEV.UPDATE_UNIQUE_KEY - Deploy started.
Create stored procedure returns SQLCODE: -206, SQLSTATE: 42703.
DEV.UPDATE_UNIQUE_KEY: 8: "SQL_STMT_2" is not valid in the context where it is used.. SQLCODE=-206, SQLSTATE=42703, DRIVER=4.12.55
"SQL_STMT_2" is not valid in the context where it is used.. SQLCODE=-206, SQLSTATE=42703, DRIVER=4.12.55
The thing I don't understand is:
- If in the routine I just drop the constraint it works.
- I can add the constraint just doing an alter table from a sql client (Squirrel)
- If I have just a routine trying to add the constraint I get the same error.
I appreciate any help. Thanks
A: I just forgot to declare the variable... DECLARE sql_stmt_2 VARCHAR(100);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612323",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Need input with adding second MySql Update in conditional IF just trying to add a second Update inside the second if (if $amount == "0.00"
It all works perfectly, until I try to add this bit in below:
Bit to add:
$updateSQL = "UPDATE brick_codes
SET number_of_uses= '$number_of_uses'
WHERE code= 'bricks_type_0005'";
My code:
if ($amount != "0.00") :
$updateSQL = "UPDATE bricks
SET payment_page_completed = '$payment_page_completed'
, discount = '$discount'
, discount_code_used = '$discount_code_used'
, access_period = '$access_period'
, gift_certificate = '$gift_certificate'
, bricks_price = '$bricks_price'
WHERE brick_id = '$brick_id'";
elseif( $amount == "0.00" ) :
$updateSQL = "UPDATE bricks
SET payment_page_completed = '$payment_page_completed'
, discount='$discount'
, discount_code_used='$discount_code_used'
, access_period='$access_period'
, gift_certificate='$gift_certificate'
, bricks_price='$bricks_price'
, payment_date='$payment_date'
, bricks_paid='$bricks_paid'";
// THIS BIT TRYING TO ADD BUT NOW WORKING
$updateSQL = "UPDATE brick_codes
SET number_of_uses = '$number_of_uses'
WHERE code = 'bricks_type_0005'";
// END NEW BIT
WHERE bricks_id = '$bricks_id'";
endif;
Ideas? Been looking at it toooo long..
A: If you use this syntax:
if ($var = something) :
You can also execute one statement after the if. I would advice you to never use this syntax and use brackets { ... } instead, whatever you place inside the brackets is executed, be it 1 or 100 statements.
You code will look something like this:
if ($amount != "0.00") {
$updateSQL1 = "UPDATE bricks
SET payment_page_completed = '$payment_page_completed'
, discount = '$discount'
, discount_code_used = '$discount_code_used'
, access_period = '$access_period'
, gift_certificate = '$gift_certificate'
, bricks_price = '$bricks_price'
WHERE brick_id = '$brick_id'";
$updateSQL2 = //insert second UPDATE statement here.
} else { //no need for an explicit test, just use an else.
$updateSQL1 = //insert update statement here.
$updateSQL2 = "SELECT 1"; //empty statement, or another UPDATE, whatever you want.
}
The indentation makes the structure of the program clear, every time you have an opening { you indent with 2 spaces, every time you have a closing } you unindent two spaces.
Always use the brackets, even if you have only a single statement inside them, because that way you cannot get errors if you want to add another statement later.
A: you need to format your if statements better!
if ($amount != "0.00")
{
$updateSQL = "UPDATE bricks SET payment_page_completed='$payment_page_completed',discount='$discount',discount_code_used='$discount_code_used', access_period='$access_period', gift_certificate='$gift_certificate',bricks_price='$bricks_price' WHERE brick_id='$brick_id'";
}
elseif( $amount == "0.00" )
{
$updateSQL = "UPDATE bricks SET payment_page_completed='$payment_page_completed',discount='$discount', discount_code_used='$discount_code_used',access_period='$access_period', gift_certificate='$gift_certificate',bricks_price='$bricks_price', payment_date='$payment_date', bricks_paid='$bricks_paid'";
// Execute this one...
$updateSQL = "UPDATE brick_codes SET number_of_uses='$number_of_uses' WHERE code='bricks_type_0005'";
// Then execute this one...
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612326",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PhoneGap and Retina display I'm creating an app for iPhone using phoneGap, but I'm sure it is not working using retina display, instead of that, it is using the old iPhone3 resolution.
Is there any way to have 2 versions for iPhone when developing using phoneGap? this is, one version using retina and another version with worst resolution for the older devices.
Thanks
A: Retina.js with less CSS it will solve your problem.
On the other hand, for problems with Phonegap (e.g.: you don’t see the page like it should, instead you see everything zoomed in) after using the following code in your app:
<meta name="viewport" content="width=device-width, user-scalable=no, initial-
scale=0.5, maximum-scale=0.5" />
Add this into your Cordova.plist:
EnableViewportScale : YES
A: Yes, but you'll need to use either CSS media queries or JavaScript.
http://troymcilvena.com/post/998277515/jquery-retina is a jQuery plugin that'll automatically handle @2x images.
In CSS, you'd need to use a media query targeting -webkit-min-device-pixel-ratio: 2 that replaces background images with their higher-resolution versions (and sets background-size).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612330",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: Rails error "wrong number of arguments (1 for 0)" I am using a scope to filter my results :
@hotels = @hotels.type(params[:hotel_type]) unless params[:hotel_type].blank?
with
scope :type, lambda { |type|
self.scoped.where('hotel_type_id IN ( ? )', type.join(', ')) unless type.blank?
}
And params[:hotel_type] = ["2","3"]
Anyone can help me? I think it's because it's an array but i don't know how to fix this.
Thank you
A: i think you cant name your scope type, i'd name it by_type
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612333",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: creating a jQuery plugin having issues with when implemented multiple times on the same page I have created a jQuery plugin that changes the generic select box into something pretty, however I am having a problem, when the plugin is used more than once on the page I run into problems, for example when I trigger the click event that slides the options of the dropdown down, all the selects on the page slidedown, how can I stop this?
MY CODE
/***********
* Select-Me create pretty select lists using a <ul> inplace of the <select>
* Author: Simon Ainley
* Version: 0.0.1
***********/
(function($){
$.fn.selectMe = function(options) {
var defaults = {
select_text : null,
remove_first_value : false,
speed : 1000
}
var options = $.extend(defaults, options);
return this.each(function() {
//get an instance of the object we are working with
var obj = $(this);
var obj_name = obj.attr('name');
obj.closest('form').append('<input type="hidden" id="dropdown_value" value="" name="'+obj_name+'"/>');
var options = $("option", obj);
var replacement_list_heading = "<dl id='dropdown'><dt><span>"+defaults.select_text+"</span><a href=''>Go</a></dt></dl>";
obj.closest('form').prepend(replacement_list_heading);
var values_start = "<dd class='shadow_50'><ul></ul></dd>";
$("#dropdown").append(values_start);
if(defaults.remove_first_value == true) {
options.splice(0, 1);
}
options.each(function(){
$("#dropdown dd ul").append(
'<li><a href="#"><span class="option">' +
$(this).text() + '</span><span class="value">' +
$(this).val() + '</span></a></li>'
);
});
obj.remove();
$('#dropdown li a').hover(function() {
$(this).parent('li').addClass('hover');
}, function() {
$(this).parent('li').removeClass('hover');
});
$("#dropdown dt a").click(function() {
$("#dropdown dd").slideToggle(defaults.speed);
return false;
});
$("#dropdown ul a").click(function(e) {
var value = $(this).find('span').text();
$(this).addClass('selected');
$("#dropdown_value").val(value);
$("#dropdown dt span").text($('.selected .option').text());
$("#dropdown dd").slideUp(defaults.speed);
$(this).removeClass('selected');
e.preventDefault();
});
});
};
})(jQuery);
A: When attaching the event handlers like click, what you want to do is find the elements in context to your current obj, right now you have a very general selector i.e
$("#dropdown dt a").click(function() {
This will select all the dropdowns( btw you can't have two elements with the same id, looks like your plugin is creating a dl with id = "dropdown" for each select). What you want to do is select the dropdown in context to your current obj, so roughly maybe something like this
obj.closest('.dropdown dt a').click(function() {...
Do the same for the other events as well, use the selectors in context to the current element.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612336",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: DbContext mapping tables dynamically If i have a dbContext who's connection string is created during a context creation and then I want to map the table names based on some of that information....how would I pass in that data to the table mappings? For instance:
private object createContext(string name, string country)
{
DbConnectionstringbuilder conn = new DbConnectionstringbuilder();
conn.Add("Provider", "System.Data.SqlClient");
conn.ConnectionString = string.Format(name, "dbName_" + country + "_moreName");
//maybe an if/else since we will say there are more names and countries
return new object(conn.ToString());
}
Now when you initialize the dbcontext it is something like:
public class object : DbContext
{
public object(string conn):base(conn)
{
DbDatabase.SetInitializer<object>(null);
}
//insert dbset and mapping config calls here
}
Now I want my tables to map to like "table_" + country + "_endtablename"; I guess how do I get that data passed to the mapping call?
These tables are mapped to an existing database that used this format. The country is actually coming from the credentials of the logged in user and thus based on location etc. I just need to find a way to access that country code that is an internal constructor to the base class in the latter created dbcontext.
A: Well ... I would make a factory method on your DbContext class then implement derived DbContext classes for each country you wish to support. This will give you the ability to customize the database initializer for each country. Since all the derived, concrete DbContexts use the same abstract parent, you can just cast them as the parent and use them. In the initializer you can use the fluent mappings to set the database name and map the table names you require. The beauty of EF Code First is that it allows you to use standard OO patterns (like Factory Method) to solve problems like the one you describe.
However, I have to say, you may want to re-think your table naming scheme. The reason you are finding this hard is because it is a somewhat unusual setup. End users don't generally go mucking around making queries directly against the tables in your database because it is too hard to enforce business rules. Unless there is a technology reason you require the tables in each database to have country-coded names, I would let the technology drive your table naming schemes and let your customer drive the end user experience. I would think that country coded database names are adequate. That achieves data separation but makes the coding much simpler and it makes queries written for one database work on the others.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612340",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Running java hadoop job on local/remote cluster I'm trying to run hadoop job on local/remote cluster. This job in future will be executed from web application. I'm trying to execute this piece of code from eclipse:
public class TestHadoop {
private final static String host = "localhost";
public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
run();
}
static void run() throws IOException, InterruptedException, ClassNotFoundException {
Configuration conf = new Configuration();
// run on other machine/cluster
conf.set("fs.default.name", "hdfs://" + host + ":8020");
conf.set("mapred.job.tracker", "hdfs://" + host + ":8021");
Job job = new Job(conf, "Wordcount");
job.setJarByClass(TestHadoop.class);
FileInputFormat.addInputPath(job, new Path("/user/hue/jobsub/sample_data/midsummer.txt"));
FileOutputFormat.setOutputPath(job, new Path("/tmp/hadoop-out2"));
job.setMapperClass(Map.class);
job.setReducerClass(Reduce.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
job.setInputFormatClass(TextInputFormat.class);
job.setOutputFormatClass(TextOutputFormat.class);
job.waitForCompletion(true);
}
static class Map extends Mapper<LongWritable, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
@Override
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String line = value.toString();
StringTokenizer tokenizer = new StringTokenizer(line);
while (tokenizer.hasMoreTokens()) {
word.set(tokenizer.nextToken());
context.write(word, one);
}
}
}
static class Reduce extends Reducer<Text, IntWritable, Text, IntWritable> {
@Override
public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException,
InterruptedException {
int sum = 0;
for (IntWritable val : values) {
sum += val.get();
}
context.write(key, new IntWritable(sum));
}
}
}
However I get the following errors:
2011-09-30 16:32:39,000 WARN org.apache.hadoop.mapred.Child: Error running child
java.lang.RuntimeException: java.lang.ClassNotFoundException: org.mmm.hadoop.TestHadoop$Map
at org.apache.hadoop.conf.Configuration.getClass(Configuration.java:996)
at org.apache.hadoop.mapreduce.JobContext.getMapperClass(JobContext.java:212)
at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:602)
at org.apache.hadoop.mapred.MapTask.run(MapTask.java:323)
at org.apache.hadoop.mapred.Child$4.run(Child.java:270)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:396)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1127)
at org.apache.hadoop.mapred.Child.main(Child.java:264)
Caused by: java.lang.ClassNotFoundException: org.mmm.hadoop.TestHadoop$Map
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:247)
at org.apache.hadoop.conf.Configuration.getClassByName(Configuration.java:943)
at org.apache.hadoop.conf.Configuration.getClass(Configuration.java:994)
... 8 more
16:33:01.209 [LeaseChecker] DEBUG org.apache.hadoop.hdfs.DFSClient - LeaseChecker is interrupted.
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method) [na:1.7.0]
at org.apache.hadoop.hdfs.DFSClient$LeaseChecker.run(DFSClient.java:1167) ~[hadoop-core-0.20.2-cdh3u1.jar:na]
at java.lang.Thread.run(Thread.java:722) [na:1.7.0]
I'm using CDH3 with Hue. Jobs appears on job list with above running child error.
A: You have to bundle your custom mapper/reducer implementations in an jar.
job.setJarByClass(TestHadoop.class);
will then lookup that jar and transfer it to the cluster.
A: I know I'm probably way too late, but try declaring Map and Reduce as public, too.
A: mapred.job.tracker url should be http not hdfs...
and make Mapper and Reducer public..
//error
conf.set("mapred.job.tracker", "hdfs://" + host + ":8021");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612347",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Does adoCon.open in asp returns any value I am establishing a connection to a mssql server database in asp using the command
adoCon.Open "Driver={SQL Server}; Server=" & host_name & "; Database="
& db_name & "; Uid=" & user_name & "; Pwd=" & password
Now my question is how to know if this connection establishment was successful. Does adoCon.open returns any value which I can use in my if statement?
A: I guess you are useing ADODB-ActiveX object... so that would be the property adoCon.State.
*
*adStateClosed 0 -> The object is closed
*adStateOpen 1 -> The object is open
*adStateConnecting 2 -> The object is connecting
*adStateExecuting 4 -> The object is executing a command
*adStateFetching 8 -> The rows of the object are being retrieved
find more information here enter link description here
A:
After this method successfully completes, the connection is live and
you can issue commands against it and process the results.
So it returns when the connection is established; if for any reason it could not be created - invalid credentials, networking issue etc - it will raise an error which you should trap & deal with inline or in a helper routine.
function open(cn as adodb.connection) as boolean
on error goto handler
cn.Open "Driver={SQL Server}; Server=" & host_name & "; Database=" & db_name & "; Uid=" & user_name & "; Pwd=" & password
open=true
exit function
handler:
response.write "fail " & err.description
end function
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612348",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Using Delphi Subversion integration to check files in from another folder So we're converting from VSS to delphi and we use a lot of include paths.
We'd like to at least attempt to conform to whatever the Delphi IDE decides is the right way to do this, but it's non-obvious.
Apparently, you can't include files in SVN that are used in a different folder, even if they are mentioned in the project group.
So... what is the expectation? Do we have to convert all our files to use namespaces and put them in the same folder just to use Delphi's subversion integration completely?
Should we create BPL's for all of our 'unprojected' common files that are shared between multiple DLLs?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612352",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can I programmatically get access to GMAIL attachments? Currently I've signed up for a subscription service that sends me data as an email attachment...it's a zip file. I get a file everyday.
What I want is a program that runs every day that downloads the attachment from Gmail and then opens the zip file and processes it's contents.
The server I would be running this app on is running Ubuntu
I'm looking for either existing tools that will do this or a strategy that I can implement myself.
A: You can use JavaMail to connect to GMail's imap or pop3 interface, then fetch emails and retrieve attachments.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612355",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: web service calling I'm novice at webservices. So, I have web service:
public interface IReportingService
{
[OperationContract]
void SendStatistics(StatisticsInfo info);
[OperationContract]
void CloseTranslationSession(StatisticsInfo info);
}
if I go to http://localhost/ReportingService.svc?wsdl, then I can see there some xml. Looks like it works. Now i want to invoke one of this methods from js.
How can I do this?
A: It seems that you are trying to invoke a SOAP service from JavaScript. The answer in this StackOverflow question might help.
Additional info:
Just by doing a quick search on google on the following string "invoke soap from JS" it seems that there are quite a few libraries for doing that, besides the one in the link mentioned above.
While I have quite a lot of experience with web services, I am not able to make a recommendation on a particular library since I have never invoked SOAP from JavaScript.
SOAP services are primarily used by business applications. The message size is quite big and the protocol itself is quite complicated in places. In the world of the web REST web services are used instead.
If you are the owner of the service and JS is the main place from where it is going to be consumed, you should consider exposing it as REST rather than SOAP and return the data as JSON which is really easy to consume in JS.
Here you can find a short tutorial on setting up WCF REST services.
A: You can use Ajax (I suggest with JQuery).
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ReportingService.svc/SendStatistics",
data: "{YouDataHere}",
dataType: "json"
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612356",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Mainframe access to Facebook data I am working on a request to allow our Unisys mainframe users to access their Facebook data from non-GUI terminals. Based on the "no scraping, no automation" Facebook terms-of-service, and the way Facebook's oAuth authentication works, I don't see how the mainframe software can log on to the user's account to access/update their data.
Does Facebook support any kind of authentication that does not require a person sitting at a GUI screen?
A: Rod,
The thing that stopped me was the OAUTH code. Twitter (and I believe Facebook) allow an API connection via OAuth. You have to create the callback and use the Unisys CryptoAPI to handle some digest creation. Another way I did it was to use the MCP JProcessor and implement it on that front, but I am sure you are looking for an ALGOL way to do it. If you have a need to add the OAUTH code and can handle the special SHA2-256 it would work from ALGOL.
A: Sorry. No. They don't offer this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612361",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: GPU usage via scripts or API is there any way to find the GPU usage in windows?
Either via scripts (vb, tcl,...)
or any API or library in high level languages.
A: Riva Tuner has an SDK to allow plugins / other applications to access GPU statistics, such as current clock speed, current fan speed, current temperature, GPU load, etc.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612364",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: getting timeout error when select the 50th page in telerik RadGrid I am loading 100000 records in the Radgrid, if I am doing anything (select 50th page in RadGrid Pager Control or Filter something in the RadGrid) in the radgrid it's taking too much of time to load, sometimes I got the error like "Not enough storage is available to complete this operation.",
This is the code:
<telerik:RadGrid ID="RadGridRollup" Skin="Vista" runat="server" AutoGenerateColumns="true"
ShowHeader="true" AllowFilteringByColumn="true" AllowSorting="true" ShowFooter="false"
PageSize="50" OnNeedDataSource="RadGridRollup_NeedDataSource" AllowPaging="true"
EnableLinqExpressions="false" PagerStyle-AlwaysVisible="true" PagerStyle-Position="Bottom"
GridLines="None" Height="300px" Width="1000px" >
<ClientSettings AllowKeyboardNavigation="true" EnableRowHoverStyle="true">
<Scrolling AllowScroll="True" EnableVirtualScrollPaging="True" UseStaticHeaders="True"
SaveScrollPosition="True" />
</ClientSettings>
<GroupingSettings CaseSensitive="false" />
<MasterTableView PagerStyle-AlwaysVisible="true" PagerStyle-Position="Bottom" PagerStyle-Mode="NextPrevAndNumeric">
<ItemStyle Wrap="true" />
<Columns>
</Columns>
</MasterTableView>
</telerik:RadGrid>
After that I include the properties (ViewStateMode="Disabled" EnableViewState="false" for RadGrid) at that time also I am having same error.
Can anyone suggest what I need to do further to improve the performance?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612367",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Bison/Flex declaration mess... how what should I include/declare where? I'm using Bison and Flex to make a reentrant scanner/parser pair but can't wrap my head around where everything is to be included and declared.
First of all, I'm using reentrant Flex so I need to pass the yyscan_t scanner type first to Bison by declaring %parse-param {yyscan_t scanner} and then make Bison pass this to Flex by declaring %lex-param {yyscan_t scanner}. But yyscan_t is not declared by Bison so I must include the Flex generated scanner header file (which I named scanner.flex.h) in my Bison file. But since my Flex file includes my Bison header, and my Bison header now includes the Flex header, I get circular includes which messes up stuff in unpredictable ways!
And let's say I want to add in location tracking with %locations in my Bison file and %bison-locationsin my Flex file. Now I need to change the declaration of my yyerror and my yylex (it seems I have to define yylex AGAIN even though it's defined in the Flex generated header but I cannot include that, remember?) functions in my Bison file to include the YYLTYPE pointer. But what now? It seems that the default YYLTYPE declaration is placed AFTER the prologue is inserted and thus I cannot use this default YYLTYPE in the declaration of my yyerror and my yylex.
I realize that there are a lot of workarounds to these problems... but how are you supposed to do it properly? It totally escapes me and this just leaves my head a mess...
A: In the top of your bison file you need to forward declare these values. You can do this in a common header or in the code file before you include the flex and bison files. yyscan_t is just a typedef of a void * so I declared the parameters as void pointers to get it to work.
CommonHeader.h
int yylex (union YYSTYPE * yyval_param, struct YYLTYPE * yylloc_param, void * yyscanner);
int yyerror(struct YYLTYPE * yylloc_param, void *scanner, const char *s);
Example of yyerror
int yyerror(struct YYLTYPE * yylloc_param, void *scanner, const char *s)
{
printf("*** Lexical Error %s %d.%d-%d.%d\n", s,
yylloc_param->first_line, yylloc_param->first_column,
yylloc_param->last_line, yylloc_param->last_column);
}
A: Came across this while looking for something else.
The answer is that Bison emits the internal declaration for YYLTYPE after the %union spec. Hence, putting function prototypes and other stuff in a prologue section after the %union avoids the problem of declaring YYLTYPE yourself; this is quite OK, Bison allows more than one prologue section:
%{
/* Prologue 1 */
%}
%this
%that
%union {}
%{
/* Prologue 2, YYLTYPE declared */
%}
%%
blah: talk | blah talk
%%
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612371",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: How to convert AsciiDoc to Perl POD? How to convert manpage written in AsciiDoc lightweight markup language automatically into Perl's POD (Plain Old Documentation)?
Perhaps something that converts from DocBook to POD (the conversion from AsciiDoc sources to manpage format i.e. troff goes via DocBook (via XML)).
A: You should be able to accomplish this using a2x and rman, to first convert asciidoc to man page format, then to convert that to POD:
a2x -f manpage foo.1.txt
groff -e -mandoc -Tascii foo.1 | rman -f POD > foo.pod
The groff command is there to fix some formatting issues -- apparently rman does not understand specific macros produced by a2x (I found this piece of advice on this page: http://www.datastat.com/sysadminjournal/misctips.html).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612374",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Insert text in textarea at caret position
Possible Duplicate:
How to insert text at the current caret position in a textarea
I want to insert text in a textarea using javascript at the caret position, i already have the code to find the position, whats the code to put text at that particular position?
Thanks,
Jake
A: var myTextarea = ... // select the text area
$(myTextarea).html('The text I want to insert'); // this will replace the existing contents
To append text to the textarea, use this:
$(myTextarea).html($(myTextarea.html() + 'The text I want to insert');
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612375",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: EXC_BAD_ACCESS when using VBO I've made some rendering with out using VBO. Now i want to add VBO for more complex rendering. I'm just creating a VBO now, keeping the old rendering as it was and i render nothing with VBO now. Here is the code:
GLuint bufId;
glGenBuffers(1, &bufId);
glBindBuffer(type, bufId);
glBufferData(type, size, 0, GL_STATIC_DRAW);
//size = 100000;
That's the only code about VBO. But if the last stroke is not commented then i get EXC_BAD_ACCESS in old rendering when drawing GL_TRIANGLE_STRIP. I've put glGetError() before this bad access and it returns 0. What is the problem? thanks
A: EXC_BAD_ACCESS means that you have tried to read or write to memory that hasn't been mapped to your process.
There are lots of ways this can happen, and there's no way that glGetError() will know about it.
I wrote this blog that tries to help you debug it. It was for iPhone, but everything in it applies to Mac apps as well.
http://loufranco.com/blog/files/Understanding-EXC_BAD_ACCESS.html
A key point is that EXC_BAD_ACCESS doesn't have to happen at the point of the bug -- the bug that caused it could have already run, and the bad access is happening in response -- the crash point may not be related at all. My blog goes through some debugging techniques to figure out where the problem really is. For example, it might have nothing to do with GL.
In your code, what is the value of size and type? It might have nothing to do with this.
Some things to check for in all code that has run up to this point.
*
*A double-free
*Out-of-bounds reading/writing on arrays
*Bad casts
A: I've found the problem. You have to unbind VBO if you want to draw with out it:
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
after that everything worked
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612376",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: CSS error with position and overflow on all browsers I have set up a scrollable div that until recently was scrolling and now appears to be jammed at the top. The only difference is the addition of position: relative;.
Here is a FIDDLE
http://jsfiddle.net/PMzcB/
Any ideas why?
A: Change z-index to a positive value.
A: The z-index:-1; was the problem.
http://jsfiddle.net/PMzcB/13/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612379",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Use bash to concatenate a list of items I have a list of items like:
ERR001268_chr6
ERR001312_chr6
ERR001332_chr6
ERR001361_chr6
ERR001369_chr6
ERR001413_chr6
ERR001433_chr6
ERR001462_chr6
ERR001698_chr6
ERR001734_chr6
ERR001763_chr6
ERR001774_chr6
ERR001799_chr6
say now I want to concatenate ERR001268_chr6 until ERR001763_chr6.
I can do cat ERR001268_chr6 ERR001269_chr6....ERR001763_chr6 > xxx
But obviously I don't want to type in these items one by one...So any simple bash commands to do this?
thx
A: Assuming that the item list is the full list of 'files' under current directory:
cat `ls -1 ERR*_chr6 | head -n11` > xxx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612380",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Exact c# result of sql datediff I'm trying to get the number of days (calculated byu datediff) in sql and the number of days in c# (calculated by DateTime.now.Substract) to be the same, but they return different results....
//returns 0
int reso = DateTime.Now.Subtract(expirationDate).Days;
vs
//returns 1
dateDiff(dd,getDate(),ExpirationDate)
In both cases, ExpirationDate is '10/1/2011 00:00:00', and the code and the DB are sitting on the same server. I want the return int to be the same. I suspect I'm missing something stupid... ideas??
A: dateDiff(dd,getDate(),ExpirationDate) Is doing a days comparison. DateTime.Now.Subtract(expirationDate).Days is doing a date and time
For example
SELECT dateDiff(dd,'10/1/2011 23:59:00' , '10/2/2011') returns one day even when only one minute apart.
If you want the same in C# you need to remove the time component
e.g.
DateTime dt1 = new DateTime(2011,10,1, 23,59,0);
DateTime dt2 = new DateTime(2011,10,2, 0,0,0);
Console.WriteLine((int) dt2.Subtract(dt1.Subtract(dt1.TimeOfDay)));
So in your case it would be something like
DateTime CurrentDate = DateTime.Now;
int reso = CurrentDate.Subtract(CurrentDate.TimeOfDay).Subtract(DateTime.expirationDate).Days;
I haven't tested it but I would not do
DateTime.Now.Subtract(DateTime.Now.Subtract.TimeOfDay)
Because the second call to Now wouldn't be guaranteeing to be the same as first call to Now
In any case Stealth Rabbi's answer seems more elegant anyway since you're looking for a TimeSpan not a DateTime
A: 10/1/2011 is less than 1 day away from DateTime.Now. Since you're getting back a TimeSpan and then applying Days to it, you're getting back a TimeSpan that is < 1 day. So it'll return 0 Days.
Instead, just use the Date component of those DateTimes and it'll correctly report the number of days apart - like this:
DateTime now = DateTime.Now;
DateTime tomorrow = new DateTime(2011, 10, 1);
var val = (tomorrow.Date - now.Date).Days;
This will yield you 1 day.
A: I'm assuming you want the number of Total days, not the number of days from the largest previous unit. You'd want to use the TotalDays property. Also, you may find it easier to use the minus operator to do a subtraction
DateTime d1 = DateTime.Now;
DateTime d2 = new DateTime(2009, 1, 2);
TimeSpan difference = d1 - d2;
Console.WriteLine(difference.TotalDays); // Outputs (today):1001.46817997424
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612383",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Replace text at top-level of node without breaking formatting of children If I have the following html code:
<div id="element">
Qwerty Foo Bar
<span style="color: red;">This text should/will never be changed by the script.</span>
</div>
And I want to change "Foo" to "baz", I can do the following:
var element = document.getElementById('element');
element.innerText = element.innerText.replace('Foo', 'baz');
However this will destroy the formatting of the red text.
How can you do this?
I don't need cross-browser support, only support for chrome and I don't want to use a js framework. jsFiddle: http://jsfiddle.net/cLzJD/3/
A: You can iterate over the children and only modify text nodes:
var children = element.childNodes,
child;
for(var i = children.length; i--; ) {
child = children[i];
if(child.nodeType === 3) {
child.nodeValue = child.nodeValue.replace('Foo', 'baz');
}
}
DEMO
Notes:
*
*If you want to replace all occurrences of Foo, you have to use a regular expression: replace(/Foo/g, 'baz').
*The advantage of this approach is that event handlers bound through JavaScript will stay intact. If you don't need this, innerHTML will work as well.
A: Although @Felix Kling's solution is the best approach, in your special case you could use .innerHTML instead of .innerText.
element.innerHtml = element.innerHtml.replace('Foo', 'baz');
.replace() will only replace the first occurrence, so if you're sure there is no HTML content before your text, you can use it. Otherwise it could break your HTML.
A: You are losing the formatting because you're using innerText (which will return the contents with all the HTML stripped out). Just use innerHTML instead: http://jsfiddle.net/cLzJD/4/ (I've also changed the ids to be unique).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612391",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to draw Ropes using cocos2d texture programming I am new to cocos2d framework but I have good experience in iPhone application programming. We can draw lines between 2 points using ccDrawLine command. What I need to do is draw a Rope which connects the two points similar to ccDrawLine
The rope is straight.
I have a png of the rope image which is horizontal.
What I thought was using Open GL Texture to create a Texture which has the above mentioned image and then drawing line with the same. But I donno where to start and how to proceed. Please Help
A: Check out this tutorial in Cocos2d site: http://www.cocos2d-iphone.org/archives/1112, which shows you how to setup ropes between two points using a custom class called VRope. You should be able to download the code, and replace the rope.png with your texture.
Cheers,
Pras.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612392",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Cassandra Insertion Error I have a 4 Node Cassandra cluster with 2 Cassandra nodes and 2 brisk nodes[cassandra+TT]. Brisk beta 2
I used cassandra-cli to insert create and update column families
My insertions and projections are are always getting failed. For example
Counter Column family
[default@StatsKeySpace] create column family Impressions with comparator=UTF8Type and default_validation_class=CounterColumnType and key_validation_class=UTF8Type;
175d69d0-eb6f-11e0-0000-93bbb4d362fc
Waiting for schema agreement...
... schemas agree across the cluster
[default@StatsKeySpace] incr Impressions['Test']['impressions'] by 10;
null
[default@StatsKeySpace] incr Impressions['Test']['impressions'] by 1;
null
[default@StatsKeySpace] get Impressions['Test']['impressions'];
null
[default@StatsKeySpace] list Impressions;
Using default limit of 100
null
Standard Column family
[default@StatsKeySpace] set TestColumnFamily['Test']['tamil']='hai';
null
All the nodes are alive in the cluster
This is my keyspace defn
Keyspace: StatsKeySpace:
Replication Strategy: org.apache.cassandra.locator.NetworkTopologyStrategy
Durable Writes: true
Options: [replication_factor:1]
I tried cassandra-cli with debug mode I found this error
[default@unknown] use StatsKeySpace;
Authenticated to keyspace: StatsKeySpace
[default@StatsKeySpace] incr Impressions['tamil']['count'] by 1;
null
java.lang.RuntimeException
at org.apache.cassandra.cli.CliClient.executeCLIStatement(CliClient.java:297)
at org.apache.cassandra.cli.CliMain.processStatement(CliMain.java:217)
at org.apache.cassandra.cli.CliMain.main(CliMain.java:345)
Both the column families has replicate_on_write false
Thanks for help in advance
Regards,
Tamil
A: Thanks to jbellis,
I upgraded the cassandra version being shipped with brisk and ran cassandra-cli with debug mode set. As jbellis mentioned I got a meaningful exception.
UnavailableException - Not enough nodes alive for replication factor to be satisfied.
Since brisk uses brisksnitch which deploys brisk nodes and cassandra nodes across different DCs. One of my 4 nodes cluster which is the seed for Brisk DC was down. I hope that is why I was getting that exception.
So, I restarted my entire cluster with all nodes upgraded with 0.8.6 and keyspace with simplestrategy since, my deployment need to have only one datacenter.
Now all my insertions and projections are doing fine :) Hope brisk b2 is compatible with 0.8.6 in all aspects
Regards,
Tamil.s
A: You are trying to increment non-counter columns. See http://www.datastax.com/dev/blog/whats-new-in-cassandra-0-8-part-2-counters for an example of creating a CF for use with counters.
(Brisk b2 ships with what is at this point a fairly old version of Cassandra. I believe newer versions will give back a more helpful error message.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612394",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Which `boost::system::error_code` value should be provided when `boost::asio::ip::tcp::resolver::resolve()` fails? I want to return a boost::system::error_code indicationg whether a host/service could be resolved or not. There might be multiple reasons why a host/service look-up failed (e.g. network connection problems or an invalid argument).
What should be returned?
A: You have to come up with error code and category in order to create error_code object. Here is an example, assuming that error is due to another host refusing connection:
error_code ec (errc::connection_refused, system_category());
return ec;
You can also pass errno value as error code when using system category. For example:
#include <fstream>
#include <cerrno>
#include <boost/system/system_error.hpp>
void foo ()
{
ifstream file ("test.txt");
if (!file.is_open ())
{
int err_code = errno;
boost::system::error_code ec (err_code
, boost::system::system_category ());
throw boost::system::system_error (ec, "cannot open file");
}
}
Unfortunately, this library is poorly documented, so I can recommend you to look into header files to figure things out. The code is fairly simple and straight forward there.
Just in case your compiler supports C++11 and you are willing to use it, this functionality made it into standard. As far as I know gcc 4.6.1 has it already. Here is a simple example:
#include <cerrno>
#include <system_error>
std::error_code
SystemError::getLastError ()
{
int err_code = errno;
return std::error_code (err_code, std::system_category ());
}
void foo ()
{
throw std::system_error (getLastError (), "something went wrong");
}
Generally, libraries pass error_code object around if there is no need to throw and use system_error to throw an exception describing system failures. Another reason to use error_code without exceptions is when you need to signal the error across different threads. But C++11 has a solution for propagating exceptions across threads.
Hope it helps!
A: It's impossible to get this right from outside resolve(). But you can get it to do it for you, by using one of the overloads that takes an error_code& as an out-parameter:
*
*iterator resolve(const query & q, boost::system::error_code & ec)
*iterator resolve(const endpoint_type & e, boost::system::error_code & ec)
and then return the error_code it sets. I trust that this will wrap up errno or h_errno as appropriate.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612395",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Reverse String in Java without using any Temporary String,Char or String Builder Is it possible to reverse String in Java without using any of the temporary variables like String, Char[] or StringBuilder?
Only can use int, or int[].
A: String s = "Hello World!";
for(int i = 0; i < s.length(); i++)
{
s = s.substring(1, s.length() - i) + s.charAt(0) + s.substring(s.length() - i);
}
System.out.println(s); // !dlroW olleH
No temporary variables! :)
A: One of many ways:
String str = "The quick brown fox jumps over the lazy dog";
int len = str.length();
for (int i = (len-1); i >= 0; --i)
str += str.charAt(i);
str = str.substring(len);
System.out.println(str);
A: public String reverseStr(String str) {
if (str.length() <= 1) {
return str;
}
return reverseStr(str.substring(1)) + str.charAt(0);
}
A: String reverseMe = "reverse me!";
for (int i = 0; i < reverseMe.length(); i++) {
reverseMe = reverseMe.substring(1, reverseMe.length() - i)
+ reverseMe.substring(0, 1)
+ reverseMe.substring(reverseMe.length() - i, reverseMe.length());
}
System.out.println(reverseMe);
Output:
!em esrever
Just for the fun of it, of course using StringBuffer would be better, here I'm creating new Strings for each Iteration, the only difference is that I'm not introducing a new reference, and I've only an int counter.
A: The objects of the Java String class are immutable - their contents cannot be altered after being created.
You will need at least two temporary objects - one for the final result and one for the intermediate values - even if you do find a way to avoid using a local variable.
EDIT:
That said, since you can use int[] you may be able to cheat.
Since char can be assigned to int, you can use String.charAt() to create an int array with the character values in reverse order. Or you may be allowed to use String.toCharArray() to get a char array that will be copied over to your int[] temporary.
Then you use the variable that holds the reference to your original string (or the result variable, if you are allowed one) to start from an empty string (easily obtainable with a direct assignment or String.substring()) and use String.concat() to create the final result.
In no case, however, will you be able to swap the characters in-place as you would do in C/C++.
EDIT 2:
Here's my version which does not use StringBuffer/Builders internally:
int r[] = new int[s.length()];
int idx = r.length - 1;
for (int i : s.toCharArray()) {
r[idx--] = i;
}
s = s.substring(0, 0);
for (int i : r) {
s = s.concat(String.valueOf((char)i));
}
A: Because you can use an int, you can assign an int a char value:
String aString = "abc";
int intChar = aString.charAt(0);
You will have to convert from the int back to the char to assign it to aString.charAt(2).
I'm sure you can figure it out from there.
A: First append the string to itself in reverse manner. Then take the second half out of it.
public class RevString {
public static void main(String[] args) {
String s="string";
for(int i=s.length()-1;i>=0;i--){
s+=s.charAt(i);
}
s=s.substring(s.length()/2, s.length());
System.out.println(s);
}
}
A: Without using any collection,StringBulider, StringBuffer or temp array reverse the string. Simple and crisp:
public static void main(String[] args) {
String test = "Hello World";
String rev = "";
Pattern p = Pattern.compile("[\\w|\\W]");
Matcher m = p.matcher(test);
while (m.find()) {
rev = m.group()+rev;
}
System.out.println("Reverse==" + rev);
}
Output
Reverse==dlroW olleH
Hope it helps :)
A: public class Test {
static St`enter code here`ring reverseString(String str) {
for (int i = 0; i < str.length() / 2; i++) {
if (i == 0) {
str = str.charAt(str.length() - 1 - i) + str.substring(i + 1, str.length() - 1 - i) + str.charAt(i);
} else {
str = str.substring(0, i) + str.charAt(str.length() - 1 - i)
+ str.substring(i + 1, str.length() - 1 - i) + str.charAt(i)
+ str.substring(str.length() - i, str.length());
}
}
return str;
}
public static void main(String args[]) {
String s = "ABCDE";
System.out.println(Test.reverseString(s));
}
}
A: String str = "Welcome";
for(int i=0;i<str.length();){
System.out.print(str.charAt(str.length()-1));
str = str.substring(0,str.length()-1);
}
Except for loop variables.
A: You can use class java.lang.StringBuilder:
String reservedString = new StringBuilder(str).reserve().toString();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612396",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Strange behaviour when returning an array from class_eval'ed method With Ruby 1.9.2, I'm using class_eval to extend a class.
def slugged(fields)
# assign string to variable only for easier debugging
method = <<-EOS
def slug_fields
#{ fields.is_a?(Array) ? fields.inspect : ":#{ fields }" }
end
EOS
class_eval method
end
This works fine as long as fields is a symbol (e.g. after slugged :name, slug_fields returns :name).
However, calling slugged with an array makes slug_fields returns nil (e.g. after slugged [:kicker, :headline], slug_fields returns nil).
Strangely, when debugging slugged, the string containing the to-be-created method looks exactly the way you would expect them to:
" def slug_fields\n [:kicker, :headline]\n end\n"
" def slug_fields\n :name\n end\n"
edit: as requested, a more complete version of what breaks for me:
module Extensions
module Slugged
extend ActiveSupport::Concern
included do
before_validation { |record| record.slug ||= record.sluggerize }
end
module ClassMethods
def slugged(fields)
# assign string to variable only for easier debugging
method = <<-EOS
def slug_fields
#{ fields.is_a?(Array) ? fields.inspect : ":#{ fields }" }
end
EOS
class_eval method
end
end
module InstanceMethods
def sluggerize
fields = slug_fields
slug_string = case
when fields.is_a?(Array)
fields.map { |f| self.send(f) }.join('-')
else
self.send fields
end
slug_string.parameterize
end
end
end
end
class Article < ActiveRecord::Base
include Extensions::Slugged
slugged [:kicker, :headline]
end
class Station < ActiveRecord::Base
include Extensions::Slugged
slugged :name
end
a = Article.new :headline => "this is a great headline!", :kicker => "attention-drawing kicker"
a.save # works, slug is set
s = Station.new :name => "Great Music"
s.save # TypeError: nil is not a symbol (in sluggerize where "self.send fields" is called)
A: Your code works fine for me under 1.9.2:
class Foo
class << self
def slugged(fields)
method = <<-EOS
def slug_fields
#{ fields.is_a?(Array) ? fields.inspect : ":#{ fields }" }
end
EOS
class_eval method
end
end
end
Foo.slugged :a
p Foo.new.slug_fields
#=> :a
Foo.slugged [:a,:b]
p Foo.new.slug_fields
#=> [:a, :b]
p RUBY_DESCRIPTION
#=> "ruby 1.9.2p180 (2011-02-18) [i386-mingw32]"
Can you please provide a complete, runnable, standalone test case that breaks for you?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612397",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android - retrieving text input from an alertbuilder dialog I've got a View defined in an xml file. It contains two Edittext fields (amongt other things like text)
I use an AlertBuilder to trigger a dialog where a user enters text(such as username and pass) into both edittext fields. When I try to retrieve the strings and send them to Login(), both strings are just null. What is going on?
It seems like somehow the string data isn't saved?
Here's when I show the Dialog in my app:
SignInDialog.show(ScreenMain.this,
"Login",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
LayoutInflater inflater = (LayoutInflater) ScreenMain.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.screen_dialog_login, null);
LogIn(((EditText) layout.findViewById(R.id.screen_dialog_login_username_edit)).getText().toString(),
((EditText) layout.findViewById(R.id.screen_dialog_login_password_edit)).getText().toString());
}
},
"Cancel",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
Here's a class I use to instantiate a Dialog:
/* login dialog*/
static class SignInDialog {
public static void show(Context context, String positiveText, DialogInterface.OnClickListener positive, String negativeText, DialogInterface.OnClickListener negative){
AlertDialog.Builder builder;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.screen_dialog_login, null);
builder = new AlertDialog.Builder(context);
builder.setView(layout);
if(positive != null && positiveText != null){
builder.setPositiveButton(positiveText, positive);
}
if(negative != null && negativeText != null){
builder.setNegativeButton(negativeText, negative);
}
builder.create().show();
}
}
A: Why not just completely subclass AlertDialog.Builder and add a method to retrieve the EditText values?
A: To inflate a layout is to create a new instance of it. (You're not receiving a reference to an existing instance.) So, in your onClick you are creating a new copy of the layout and your fields don't contain any text because they are not the same ones your user just entered text in.
A: Do something like:
View layout = inflater.inflate(R.layout.screen_dialog_login, null);
layout.findViewById(R.id.*yourwidget*);
i tried it and it helped
A: Here is the method I am using:
private void showPopUp3() {
AlertDialog.Builder helpBuilder = new AlertDialog.Builder(AlarmReceiverActivity.this);
helpBuilder.setTitle("hi");
// helpBuilder.setMessage("This is a Simple Pop Up");
final EditText input = new EditText(this);
input.setHeight(20);
input.setText("");
LayoutInflater inflater = getLayoutInflater();
final View checkboxLayout = inflater.inflate(R.layout.alarm, null);
checkboxLayout.findViewById(R.id.Yes).setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
// setTitle("button2");
checkboxLayout.findViewById(R.id.note).setVisibility(View.VISIBLE);
}
});
checkboxLayout.findViewById(R.id.No).setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
// setTitle("button2");
checkboxLayout.findViewById(R.id.note).setVisibility(View.INVISIBLE);
}
});
helpBuilder.setView(checkboxLayout);
helpBuilder.setPositiveButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Do nothing but close the dialog
mMediaPlayer.stop();
finish();
}
});
helpBuilder.setNegativeButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Do nothing but close the dialog
mMediaPlayer.stop();
//showSimplePopUp();
}
});
// Remember, create doesn't show the dialog
AlertDialog helpDialog = helpBuilder.create();
helpDialog.show();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612399",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to select Y values at X position in Groovy? this is sort of a mathy question...
I had a question prior to this about normalizing monthly data here :
How to produce X values of a stretched graph?
I got a good answer and it works well, the only issue is that now I need to check X values of one month with 31 days against X values of a month with 28.
So my question would be: If I have two sets of parameters like so:
x | y x2 | y2
1 | 10 1.0 | 10
2 | 9 1.81 | 9.2
3 | 8 2.63 | 8.6
4 | 7 3.45 | 7.8
5 | 6 4.27 | 7
6 | 5 5.09 | 6.2
7 | 4 5.91 | 5.4
8 | 3 6.73 | 4.2
9 | 2 7.55 | 3.4
10 | 1 8.36 | 2.6
9.18 | 1.8
10.0 | 1.0
As you can see, the general trend is the same for these two data sets.
However, if I run these values through a cross-correlation function (the general goal), I will get something back that does not reflect this, since the data sets are of two different sizes.
The real world example of this would be, say, if you are tracking how many miles you run per day:
In February (with 28 days), during the first week, you run one mile each day. During the second week, you run two miles each day, etc.
In March (with 31 days), you do the same thing, but run for one mile for eight days, two miles for eight days, three miles for eight days, and four miles for seven days.
The correlation coefficient according to the following function should be almost exactly 1:
class CrossCorrelator {
def variance = { x->
def v = 0
x.each{ v += it**2}
v/(x.size()) - (mean(x)**2)
}
def covariance = {x, y->
def z = 0
[x, y].transpose().each{ z += it[0] * it[1] }
(z / (x.size())) - (mean(x) * mean(y))
}
def coefficient = {x, y->
covariance(x,y) / (Math.sqrt(variance(x) * variance(y)))
}
}
def i = new CrossCorrelator()
i.coefficient(y values, y2 values)
Just looking at the data sets, it seems like the graphs would be exactly the same if I were to grab the values at 1, 2, 3, 4, 5, 6, 7, 8, 9, and 10, and the function would produce a more accurate result.
However, it's skewed since the lengths are not the same.
Is there some way to locate what the values at the integers in the twelve-value data set would be? I haven't found a simple way to do it, but this would be incredibly helpful.
Thanks in advance,
5
Edit: As per request, here is the code that generates the X values of the graphs:
def x = (1..12)
def y = 10
change = {l, size ->
v = [1]
l.each{
v << ((((size-1)/(x.size() - 1)) * it) + 1)
}
v -= v.last()
return v
}
change(x, y)
Edit: Not working code as per another request:
def normalize( xylist, days ) {
xylist.collect { x, y -> [ x * ( days / xylist.size() ), y ] }
}
def change = {l, size ->
def v = [1]
l.each{
v << ((((size-1)/(l.size() - 1)) * it) + 1)
}
v -= v.last()
return v
}
def resample( list, min, max ) {
// We want a graph with integer points from min to max on the x axis
(min..max).collect { i ->
// find the values above and below this point
bounds = list.inject( [ a:null, b:null ] ) { r, p ->
// if the value is less than i, set it in r.a
if( p[ 0 ] < i )
r.a = p
// if it's bigger (and we don't already have a bigger point)
// then set it into r.b
if( !r.b && p[ 0 ] >= i )
r.b = p
r
}
// so now, bounds.a is the point below our required point, and bounds.b
// Deal with the first case (where a is null, because we are at the start)
if( !bounds.a )
[ i, list[ 0 ][ 1 ] ]
else {
// so work out the distance from bounds.a to bounds.b
dist = ( bounds.b[0] - bounds.a[0] )
// And how far the point i is along this line
r = ( i - bounds.a[0] ) / dist
// and recalculate the y figure for this point
y = ( ( bounds.b[1] - bounds.a[1] ) * r ) + bounds.a[1]
[ i, y ]
}
}
}
def feb = [9, 3, 7, 23, 15, 16, 17, 18, 19, 13, 14, 8, 13, 12, 15, 6, 7, 13, 19, 12, 7, 3, 4, 15, 6, 17, 8, 19]
def march = [8, 12, 4, 17, 11, 15, 12, 8, 9, 13, 12, 7, 3, 4, 8, 2, 17, 19, 21, 12, 12, 13, 14, 15, 16, 7, 8, 19, 21, 14, 16]
//X and Y Values for February
z = [(1..28), change(feb, 28)].transpose()
//X and Y Values for March stretched to 28 entries
o = [(1..31), change(march, 28)].transpose()
o1 = normalize(o, 28)
resample(o1, 1, 28)
If I switch "march" in the o variable declaration to (1..31), the script runs successfully. When I try to use "march," I get "
java.lang.NullPointerException: Cannot invoke method getAt() on null object"
Also: I try not to directly copy code just because it's bad practice, so one of the functions I changed basically does the same thing, it's just my version. I'll get around to refactoring the rest of it eventually, too. But that's why it's slightly different.
A: Ok...here we go...this may not be the cleanest bit of code ever...
Let's first generate two distributions, both from 1 to 10 (in the y axis)
def generate( range, max ) {
range.collect { i ->
[ i, max * ( i / ( range.to - range.from + 1 ) ) ]
}
}
// A distribution 10 elements long from 1 to 10
def e1 = generate( 1..10, 10 )
// A distribution 14 elements long from 1 to 10
def e2 = generate( 1..14, 10 )
So now, e1 and e2 are:
[1.00,1.00], [2.00,2.00], [3.00,3.00], [4.00,4.00], [5.00,5.00], [6.00,6.00], [7.00,7.00], [8.00,8.00], [9.00,9.00], [10.00,10.00]
[1.00,0.71], [2.00,1.43], [3.00,2.14], [4.00,2.86], [5.00,3.57], [6.00,4.29], [7.00,5.00], [8.00,5.71], [9.00,6.43], [10.00,7.14], [11.00,7.86], [12.00,8.57], [13.00,9.29], [14.00,10.00]
respectively (to 2dp). Now, using the code from the previous question, we can normalize these to the same x range:
def normalize( xylist, days ) {
xylist.collect { x, y -> [ x * ( days / xylist.size() ), y ] }
}
n1 = normalize( e1, 10 )
n2 = normalize( e2, 10 )
This means n1 and n2 are:
[1.00,1.00], [2.00,2.00], [3.00,3.00], [4.00,4.00], [5.00,5.00], [6.00,6.00], [7.00,7.00], [8.00,8.00], [9.00,9.00], [10.00,10.00]
[0.71,0.71], [1.43,1.43], [2.14,2.14], [2.86,2.86], [3.57,3.57], [4.29,4.29], [5.00,5.00], [5.71,5.71], [6.43,6.43], [7.14,7.14], [7.86,7.86], [8.57,8.57], [9.29,9.29], [10.00,10.00]
But, as you correctly state they have different numbers of sample points, so cannot be compared easily.
But we can write a method to step through each point we want in our graph, fond the two closest points, and interpolate a y value from the values of these two points like so:
def resample( list, min, max ) {
// We want a graph with integer points from min to max on the x axis
(min..max).collect { i ->
// find the values above and below this point
bounds = list.inject( [ a:null, b:null ] ) { r, p ->
// if the value is less than i, set it in r.a
if( p[ 0 ] < i )
r.a = p
// if it's bigger (and we don't already have a bigger point)
// then set it into r.b
if( !r.b && p[ 0 ] >= i )
r.b = p
r
}
// so now, bounds.a is the point below our required point, and bounds.b
if( !bounds.a ) // no lower bound...take the first element
[ i, list[ 0 ][ 1 ] ]
else if( !bounds.b ) // no upper bound... take the last element
[ i, list[ -1 ][ 1 ] ]
else {
// so work out the distance from bounds.a to bounds.b
dist = ( bounds.b[0] - bounds.a[0] )
// And how far the point i is along this line
r = ( i - bounds.a[0] ) / dist
// and recalculate the y figure for this point
y = ( ( bounds.b[1] - bounds.a[1] ) * r ) + bounds.a[1]
[ i, y ]
}
}
}
final1 = resample( n1, 1, 10 )
final2 = resample( n2, 1, 10 )
now, the values final1 and final2 are:
[1.00,1.00], [2.00,2.00], [3.00,3.00], [4.00,4.00], [5.00,5.00], [6.00,6.00], [7.00,7.00], [8.00,8.00], [9.00,9.00], [10.00,10.00]
[1.00,1.00], [2.00,2.00], [3.00,3.00], [4.00,4.00], [5.00,5.00], [6.00,6.00], [7.00,7.00], [8.00,8.00], [9.00,9.00], [10.00,10.00]
(obviously, there is some rounding here, so 2d.p. is hiding the fact that they are not exactly the same)
Phew... Must be home-time after that ;-)
EDIT
As pointed out in the edit to the question, there was a bug in my resample method that caused it to fail in certain conditions...
I believe this has now been fixed in the code above, and from the given example:
def march = [8, 12, 4, 17, 11, 15, 12, 8, 9, 13, 12, 7, 3, 4, 8, 2, 17, 19, 21, 12, 12, 13, 14, 15, 16, 7, 8, 19, 21, 14, 16]
o = [ (1..31), march ].transpose()
// X values squeezed to be between 1 and 28 (instead of 1 to 31)
o1 = normalize(o, 28)
// Then, resample this graph so there are only 28 points
v = resample(o1, 1, 28)
If you plot the original 31 points (in o) and the new graph of 28 points (in v), you get:
Which doesn't look too bad.
I have no idea what the change method was supposed to do, so I have omitted it from this code
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612401",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Git Rebase or SVN Reintegrate for Feature Branches? We are currently using SVN, but considering moving to Git to support our new workflow, which relies heavily on rebase.
We're considering a development workflow where each individual feature is developed on a separate branch, then merged into trunk/master when it's ready for release. The branch will always be deleted after it is merged back into trunk/master.
One proposal is to use git rebase to keep the feature branch up-to date with changes in master (so we can test in the branch exactly what will be released), and to simplify the merge from branch -> master.
The alternative we're considering is to use svn merge to keep the feature branch up-to-date with changes in trunk, then using svn merge --reintegrate to merge the feature branch back into trunk for release.
What are the differences and potential pitfalls of each of these approaches? And which is more appropriate for our workflow?
A: This is a really straightforward workflow in git. Several developers use one or both of the methods you described.
Personally, I'm a fan of scott Chacon's strategy and have found it really useful.
You can rebase to keep the master branch in a linear history, and that's normal, but it does have a slight possibility of throwing some major loops to guys just starting out in git. Rebasing changes history and can really cause problems if you're not careful.
Git-merge (not the svn-merge --reintegrate you noted) is a little more straightforward in git if you're just starting out. Git's merging strategies are really well thought out and automatically keep you out of trouble.
If I'm developing on feature branch and then merging it into master, I like to run git merge --no-ff feature while on master to create the merge commit just to be explicit.
As you're just starting out with git, I'd go for the merge workflow. IMHO, it's more intuitive if you're coming from a svn background.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612402",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Convert Word Mail Merge documents from 2003 to 2010 format I need to convert about 100 mail merge documents from 2003 to 2010 format(.doc to .docx).
The trouble I am having is that in order to convert the documents I need to open them. But some of them won't open because I don't have the correct header files/ any data in the files.
Is there a way I can convert these documents to the new format without opening them?
Note: The converter provided by microsoft fails. Also it doesn't matter how. If there's a program or code that can accomplish this then it is helpful.
A: You can try npoi project.
Hope this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612404",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: MPI distribution layer I used MPI to write a distribution layer. Let say we have n of data sources and k of data consumers. In my approach each of n MPI processes reads data, then distributes it to one (or many) of k data consumers (other MPI processes) in given manner (logic).
So it seems to be very generic and my question is there something like that already done?
It seems simple, but it might be very complicated. Let say that distribution checks which of data consumers is ready to work (dynamic work distribution). It may distribute data according to given algorithm based on data. There are plenty of possibilities and I as every of us do not want to reinvent the wheel.
A: As far as I know, there is no generic implementation for it, other than the MPI API itself. You should use the correct functions according to the problem's constraints.
If what you're trying to build a simple n-producers-and-k-consumers synchronized job/data queue, then of course there are already many implementations out there (just google it and you should get a few).
However, the way you present it seems very general - sometimes you want the data to only be sent to one consumer, sometimes to all of them, etc. In that case, you should figure out what you want and when, and use either point-to-point communication functions, or collective communication functions, accordingly (and of course everyone has to know what to expect - you can't have a consumer waiting for data from a single source, while the producer wishes to broadcast the data...).
All that aside, here is one implementation that comes to mind that seems to answer all of your requirements:
Make a synchronized queue, producers pushing data in one end, consumers taking it from the other (decide on all kinds of behaviors for the queue as you need - is the queue size limited, does adding an element to a full queue block or fail, does removing an element from an empty queue block or fail, etc.).
Assuming the data contains some flag that tells the consumers if this data is for everyone or just for one of them, the consumers peek and either remove the element, or leave it there and just note that they already did it (either by keeping its id locally, or by changing a flag in the data itself).
If you don't want a single piece of collective data to block until everyone dealt with it, you can use 2 queues, one for each type of data, and the consumers would take data from one of the queues at a time (either by choosing a different queue each time, randomly choosing a queue, prioritizing one of the queues, or by some accepted order that is deductible from the data (e.g. lowest id first)).
Sorry for the long answer, and I hope this helps :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612406",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Workflow services correlation I would like to implement next workflow scenario:
I have workflow service with two branches. Operation2 (Receive activity) is correlated with CorrelationHandle “handle2” which is initialized from message header.
The flow is next:
1) Someone calls Operation1 and it initializes correlation handler for Operation2. So the case is that correlation value for Operation2 is not the same as for Operation1 and should be obtained in runtime when execution Operation1.
2) Using correlation value client may call Operation2.
3) If correlation is not correct Operation2 should still be executed but with custom logic.
The problem is when I call the first service I get an exception:
The CorrelationHandle is already in use with BookmarkScope '{bookmark
scope id x} ', so it cannot be used with BookmarkScope '{bookmark
scope id y}'
Debugging shows that even if I call Operation1 only “handle2” from Operation2 is also initialized with some value in Receive2 activity!!! so I it seems I cannot re-initialize it.
Any ideas how it can be fixed?
UPDATE:
I have attached file with source code so you may reproduce the issue. Just launch Operation1.
http://dl.dropbox.com/u/27847776/WorkflowCorrelation.zip
Thanks beforehand,
-Petro
A: In my experience you cannot re-initialize a correlation handle. You would need to create a separate correlation handle for each key you want to correlate on.
A: Do't use Pick. Use Parallel and set the parallel to terminate only when you are sure the conversation has ended. The Parallel has a property where you can set the terminate condition.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612407",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: INotifyPropertyChanged, no UI updates I looked around the web for an answer, but can't seem to get this to work. Here is what I have:
public class UIValues : INotifyPropertyChanged
{
private double zoomValue = 1;
private static readonly UIValues instance = new UIValues();
public event PropertyChangedEventHandler PropertyChanged;
internal static UIValues Instance { get { return instance; } }
internal double ZoomValue
{
get { return zoomValue; }
set
{
if (this.zoomValue == value)
return;
this.zoomValue = value;
this.OnPropertyChanged(new PropertyChangedEventArgs("ZoomValue"));
}
}
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, e);
}
}
and then I have this:
<UserControl>
<UserControl.DataContext>
<local:UIValues x:Name="uiValues"/>
</UserControl.DataContext>
.
.
.
<Viewbox x:Name="vbViewBox" RenderTransformOrigin="0.5,0.5">
<local:ImageControl x:Name="imgControl" VerticalAlignment="Center" HorizontalAlignment="Center"/>
<Viewbox.RenderTransform>
<TransformGroup>
<CompositeTransform x:Name="trCompositeTransform" ScaleX="{Binding ZoomValue}" ScaleY="{Binding ZoomValue}" Rotation="0" SkewX="0" SkewY="0"/>
</TransformGroup>
</Viewbox.RenderTransform>
</Viewbox>
</UserControl>
So basically, whenever I make a change to the ZoomValue from the UIValues class from code-behind, the UI is not updated.
Anyone know why?
Thanks!
A: Looking at the posted code I'll have a guess that you have something like this to change the Zoom Value.
UIValues.Instance.ZoomValue = x;
The problem is this xaml:-
<local:UIValues x:Name="uiValues"/>
constructs an independent instance of UIValues that is not the same instance returned by your static Instance property. Hence you will be changing a value on a object that nothing is listening to.
Edit
Also ZoomLevel is internal, for it work with binding is must be public.
The solution is to use IApplicationService and do things through App.xaml.
Change you class to:
public class UIValues : INotifyPropertyChanged, IApplicationService
{
private double zoomValue = 1;
public event PropertyChangedEventHandler PropertyChanged;
internal static UIValues Instance { get; private set; }
public double ZoomValue
{
get { return zoomValue; }
set
{
if (zoomValue == value)
return;
zoomValue = value;
this.OnPropertyChanged(new PropertyChangedEventArgs("ZoomValue"));
}
}
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, e);
}
void IApplicationService.StartService(ApplicationServiceContext context)
{
Instance = this;
Application.Current.Resources.Add("UIValues", Instance);
}
void IApplicationService.StopService() { }
}
Add the instance of UIValues to App.Xaml:-
<Application.ApplicationLifetimeObjects>
<local:UIValues />
</Application.ApplicationLifetimeObjects>
Then set the user control DataContext like this:-
<UserControl ... DataContext="{StaticResource UIValues}">
That said this is waste of the DataContext which you may need to bind to real data. You can specify the Source directly on the bindings instead:-
<CompositeTransform ScaleX="{Binding ZoomValue, Source={StaticResource UIValues}}" ScaleY="{Binding ZoomValue, Source={StaticResource UIValues}}" Rotation="0" SkewX="0" SkewY="0"/>
A: Change access modifier for ZoomValue property to public and everything will work fine.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612409",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Map Isn't Returning Correct Numbers I have a map that is acting up and not returning the correct number. It did then it didn't, now it's just not returning. Any help is appreciated. Thank you.
struct file_data
{
std::wstring sLastAccessTime;
__int64 nFileSize ;
};
int GetFileList(const wchar_t *searchkey, std::map<std::wstring, file_data> &map)
{
WIN32_FIND_DATA fd;
HANDLE h = FindFirstFile(searchkey,&fd);
if(h == INVALID_HANDLE_VALUE)
{
return 0; // no files found
}
while(1)
{
wchar_t buf[128];
FILETIME ft = fd.ftLastWriteTime;
SYSTEMTIME sysTime;
FileTimeToSystemTime(&ft, &sysTime);
wsprintf(buf, L"%d-%02d-%02d",sysTime.wYear, sysTime.wMonth, sysTime.wDay);
file_data filedata;
filedata.sLastAccessTime= buf;
filedata.nFileSize = (((__int64)fd.nFileSizeHigh) << 32) + fd.nFileSizeLow;
map[fd.cFileName]= filedata;
if (FindNextFile(h, &fd) == FALSE)
break;
}
return map.size();
}
int main()
{
std::map<std::wstring, file_data> map;
int count = GetFileList(L"C:\\Users\\DS\\Downloads\\*.pdf", map);
int count1 = GetFileList(L"C:\\Users\\DS\\Downloads\\*.txt", map);
int count2 = GetFileList(L"C:\\Users\\DS\\Downloads\\*.jpg", map);
for(std::map<std::wstring, file_data>::const_iterator it = map.begin(); it != map.end(); ++it)
{
if (count2 != 0)
{
printf("\n How Many: %i \n", count2);
}
else
{
printf ("%s \n", "Nothing");
}
return 0;
}
}
A: Note that GetFileList() returns the number of items in the map.
In your implementation it is cumulative. Maybe you want to clear the map between consecutive calls to GetFileList().
A: OK found the solution. This is it.
GetFileList(L"C:\\Users\\DS\\Downloads\\*.pdf", map);
GetFileList(L"C:\\Users\\DS\\Downloads\\*.txt", map);
GetFileList(L"C:\\Users\\DS\\Downloads\\*.jpg", map);
if( map.size() > 0
then...........
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612410",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What are some approaches for gathering and conveying compiler errors The simplest approach is just to throw an exception with error information at the first occurrence of an error. Perhaps another approach is to pass a mutable list argument through analysis functions. But I've noticed the F# compiler for example will accumulate errors incrementally in the Visual Studio error pane throughout compilation. Would using a TraceListener be an option? What are some pros and cons of different approaches.
I'm particularly interested in approaches for compilers targeting .NET using a functional language like F#, but would appreciate approaches (which may or may not be different) in other contexts as well.
A: You can always look at the F# compiler code as one example (though real-world code is always a bit of a mess :) ):
https://github.com/fsharp/fsharp/blob/master/src/fsharp/ErrorLogger.fs
We have an ErrorLogger interface with warning and error 'sinks', and various parts of the compiler 'sink' errors and warnings to the active logger via the interface.
It can be tough when encountering an error to decide whether you should throw (and abandon local control flow) or log-and-continue (to get more info but risk more cascade errors). There are lots of strategies to deal with this, but all end up being tricky, as your typical industrial-strength compiler has thousands of diagnostics and people can write incorrect code a seemingly infinite number of ways, and a one-size-fits-all solution is unlikely to provide the best experience for every error, or even every common error.
As someone said, compilers universally write output to stdout/stderr in a canonical format. MSBuild and Visual Studio parse the build output to light up the error list and squiggles in the IDE UI. For incremental feedback while typing (and not building), VS does also 'host' the front-end of the compiler in-process and read the error messages directly out of the 'sinks'.
So long as you at least have one abstraction boundary (e.g. a LogWarning and LogError function, which might even be global, just ensure all warnings/errors use it), then you're always in a position to refactor to meet changing needs/designs.
A: Any compiler I've used, including .NET ones, immediately types the error message to the console. Pretty important consideration is that this allows the programmer to type Ctrl+C to put a quick end to the slew of errors that are generated because of a mistake in a declaration. Not terribly relevant anymore these days but neither is doing it differently.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612413",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Delphi (XE2): Trial - what can I do? What about my old Delphi? I have been at RAD Studio XE2 World Tour here in Poland in Cracov and I really love new features, so Im almost sure, Ill buy it. But now I downloaded trial version and I want to ask about two things:
Firstly: What can I do with it? I mean - can I build for example one free application and distribute it over Internet? It would be freeware application written within these 30 days. License is quite long and I cant find restrictions like that.
Secondly: If I install this trial anything bad can happen to my Delphi 2009 (Professional)? I have a lot of IDE experts, additional components, important projects etc etc - I dont want to lose anything. In short - is it better to install it on VM?
A: You are not allowed to distribute applications or components written with the trial edition of Delphi.
A: I've installed 'full' XE2 onto a VM which already had Delphi 7 and Delphi 2010 on, and haven't seen any adverse effects over the last couple of days. All 3 environments appear to get along fine, as has long been the Delphi tradition.
Once I get a chance I'll stick it on my 'main' development VM, which is currently Delphi 2007.
However, I don't know about the trial version aspect of it. I wouldn't expect it to behave any differently but if you're concerned about your production/work environment, I would strongly suggest that you isolate your trial explorations to a VM... - just to be safe. :-)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612418",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: php.ini display_errors not respected OS X Server I am running an 10.6.8 OS X Server. It acts as a web server using the built in PHP and Apache.
PHP is at 5.3.4
Apache is at 2.2.17
I am trying to disable the reporting or errors to end users with a server wide setting.
I have tried the following:
in PHP.ini
error_reporting = E_ALL & ~E_DEPRECATED
display_errors = Off
display_startup_errors = Off
log_errors = On
log_errors_max_len = 1024
ignore_repeated_errors = Off
ignore_repeated_source = Off
report_memleaks = On
track_errors = Off
html_errors = Off
error_log = /dir/php_errors.log
The display_errors = Off is not being respected. When calling a php file that requires a string to be passed with it I will get error such as:
Notice: Undefined index: username in ......
I am able to suppress the error by adding the following code to the top of the php file being called:
ini_set("display_errors" , "0")
I have also tried adding variables to various apache .conf and .htaccess .files with the following code:
php_value display_errors 0
Errors are being written to my specified log correctly. Using phpinfo() I see that I am using the correct php.ini file, and display_errors is showing off.
Any ideas?
A: First off using a phpinfo()... check the location of the php.ini file. It may be referencing a different one from the one you think it should be.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612424",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Regular Expression change text between tags I have some code in the following layout,i m using textcrawler to do a find and replace
<a>
Name=LineA
epsium
ask
answer
line=10
color=red
</a>
<a>
Name=LineB
Color=Blue
</a>
...
Now the question is what regular expression i need to use so as to remove the second block of code between <a> and </a>
A: <a>(\s*?Name\=LineB[\S\s]*?)</a>
It captures all text between and including the <a></a> tags that starts with the text Name=LineB.
A: In Perl, I'll do :
$str =~ s~^(.*?<a>.*?</a>.*?)<a>.*?</a>(.*)$~${1}New text$2~s;
the first group contains everything before the second block <a></a> and the second group everything after.
In php:
$str = preg_replace('~^(.*?<a>.*?</a>.*?)<a>.*?</a>(.*)$~', "${1}New text$2", $str);
A: preg_replace("/<body>([\s\S]*.*)<\/body>/",$replace,$origional);
this will replace whole content between body tags.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612426",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Difference between uint8_t and unspecified int for large matrices I have a matrix that is over 17,000 x 14,000 that I'm storing in memory in C++. The values will never get over 255 so I'm thinking I should store this matrix as a uint8_t type instead of a regular int type. Will the regular int type will assume the native word size (64 bit so 8 bytes per cell) even with an optimizing compiler? I'm assuming I'll use 8x less memory if I store the array as uint8_t?
A: If you doubt this, you could have just tried it.
Of course it will be smaller.
However, it wholly depends on your usage patterns which will be faster. Profile! Profile! Profile!
Reasons for unexpected performance considerations:
*
*alignment issues
*elements sharing cache lines (could be positive on sequential access; negative in multicore scenarios)
*increased need for locking on atomic reads/writes (in case of threading)
*reduced applicability of certain optimized MIPS instructions (? - I'm not up-to-date with details here; also a very good optimizing compiler might simply register-allocate temporaries of the right size)
*other, unrelated border conditions, originating from the surrounding code
A: The standard doesn't specify the exact size of int other than it's at least the size of short. On some 64-bit architectures (for example many Linux and Solaris x86 systems I work with) int is 32 bits and long is 64 bits. The exact size of each type will of course vary by compiler/hardware.
The best way to find out is to use sizeof(int) on your system and see how big it is. If you have enough RAM using the native type may in fact be significantly faster than the uint8_t.
A: Even the best optimizing compiler is not going to do an analysis of the values of the data that you put into your matrix and assume (anthropomorphizing here) "Hmmm. He said int but everything is between 0 and 255. I'm going to make that an array of uint8_t."
The compiler can interpret some keywords such as register and inline as suggestions rather than mandates. Types on the other hand are mandates. You told the compiler to use int so the compiler must use int. So switching to a uint8_t matrix will save you a considerable amount of memory here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612428",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why are some functions located densely and others are aligned and padded with int 3 instructions? I compile the following program with Visual C++ 10:
include <Windows.h>
int _tmain(int /*argc*/, _TCHAR* /*argv*/[])
{
Sleep( 0 );
return 0;
}
and look into disassembly. There're lots of C++ runtime functions in the program image. Some functions are located densely - ret of some function is followed by the first instruction of the next function. For example,
` __declspec(noreturn) void __cdecl __report_gsfailure(ULONGLONG StackCookie)`
ends at address 004013B7 (there's a ret instruction) and address 004013B8 contains some other function for which the debugger can't find the source. Meanwhile
BOOL __cdecl _ValidateImageBase(PBYTE pImageBase)
ends at address 00401554 but the next function
PIMAGE_SECTION_HEADER __cdecl _FindPESection( PBYTE pImageBase, DWORD_PTR rva )
starts at address 00401560 and there're multiple int 3 instructions between the latter two addresses.
Why the difference? Why some functions are put densely and others are separated with unreachable code?
A: I reproduced this behavior. You can notice as well that these functions start with a mov edi,edi intruction.
The int 3 instructions, along with the mov edi,edi instruction at the beginning of the function allows hotpatching.
When a function needs to be hotpatched, the mov edi,edi is replaced by a short jump instruction that jumps before the entry point of the function and the int 3 instructions are replaced by a long jump to the patched function.
Refer to Anyone knows what "mov edi,edi " does?
Don't know why __report_gsfailure is only preceeded by 2 int 3 even if it starts with a mov edi,edi instruction...
A: Raymond Chen tells all you need to know about this: Why do Windows functions all begin with a pointless MOV EDI, EDI instruction?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Outlook Signature folder in Windows OS I have been working on an application which integrate with VSTO components in order to leverage MS Office including Outlook. In this, I have a method which read the all defined outlook signature and import it into our application. All works well and I am accessing the signature location using the following logic.
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),@"Microsoft\Signatures");
The above code works fine with English version of Windows (en-us,en-gb etc).
Does someone have exposure towards Microsoft OS installed using German language or any other? If so, how do I generalize or customize logic which does the aforementioned?
A: There is no "special folder" api for outlook folders. Your only choice is to translate it to each language you want to support.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612433",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Using js to determine if an element's width is determined by its content? I want to know if there's a way I can use jQuery or javascript to determine, given an element, if its width is set by a css style (either inline, inherited or directly) or if its being determined by the size/length of its content.
A: One idea comes to mind:
*
*Store the element's .width()
*Remove all children of the element, move them elsewhere, or make them display: none
*Check out the element's .width(). If it has changed, it depended on the content. If it has not changed, it was set using CSS.
*Restore the children's display property or move them back if necessary.
Here is a very primitive prototype that simply removes all the element's content:
function determineWidth(jQueryElement)
{
var widthBefore = jQueryElement.width();
jQueryElement.html(""); // Empty the element
var widthAfter = jQueryElement.width();
if (widthAfter != widthBefore)
var result = "The width depended on the content.";
else
var result = "The width did NOT depend on the content.";
alert("Before: "+widthBefore+" After: "+widthAfter+" - "+result);
}
There's one side-effect for block level elements: Since their width doesn't depend on the content, the script will return "...did not depend...." even though the element may not have had an explicit width set in CSS as you require.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612441",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Django validating ImageField dimensions etc I have a custom clean method below:
def clean_image(self):
image = self.cleaned_data['image']
if image:
from django.core.files.images import get_image_dimensions
w, h = get_image_dimensions(image)
if not image.content_type in settings.VALID_IMAGE_FORMATS:
raise forms.ValidationError(u'Only *.gif, *.jpg and *.png images are allowed.')
if w > settings.VALID_IMAGE_WIDTH or h > settings.VALID_IMAGE_HEIGHT:
raise forms.ValidationError(u'That image is too big. The image needs to be ' + str(settings.VALID_IMAGE_WIDTH) + 'px * ' + str(settings.VALID_IMAGE_HEIGHT) + 'px (or less).')
return image
The problem scenario is this:
An image has been uploaded. I now want to clear it using the checkbox that appears using the ImageField widget. When submitting the form to make this clear take place the clear does not.
If I remove my custom clean method the clear does work. Therefore I guess my method is doing something wrong.
A: There are 3 problems when django realize this validations:
*
*Django need obtain the value of these field, always need return a value
*Need put class Meta with the name of the model you used.
*In this sentences need put .get this way
self.cleaned_data.get['image']
*The code looks like this:
class Meta:
model = NameModel
def clean_image(self):
image = self.cleaned_data.get['image']
if image:
from django.core.files.images import get_image_dimensions
w, h = get_image_dimensions(image)
if not image.content_type in settings.VALID_IMAGE_FORMATS:
raise forms.ValidationError(u'Only *.gif, *.jpg and *.png images are allowed.')
if w > settings.VALID_IMAGE_WIDTH or h > settings.VALID_IMAGE_HEIGHT:
raise forms.ValidationError(u'That image is too big. The image needs to be ' + str(settings.VALID_IMAGE_WIDTH) + 'px * ' + str(settings.VALID_IMAGE_HEIGHT) + 'px (or less).')
return image
A: I think it isn't returning image from cleaned_data. You shoudl check that, because your coding looks fine.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612445",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Should I prefer NSNotificactionCenter or .NET events when using Monotouch? When developing in Monotouch, is it "better" to us real .NET events or NSNotificationCenter?
Simple example: I have a UIViewController. It offers an event "CallbackWhenDisappeared". This event is triggred in ViewDidDisappear. Who ever is interested can register to the event.
I could as well post a "MyFancyControllerHasDisappeared" on the NSNotificationCenter and let interested objects subscribe there.
Which version is to be preferred?
The disadvantage with the .NET events I see: the disappearing controller might hold a reference to the subscribing controller (or the other way round?) and might not be garbage collected.
I also like the loose coupling when using NSNotificationCenter compared to the events where the classes really have to know each other.
Is there a wrong or a right way of doing it?
A: I actually prefer to use TinyMessenger. Unlike NSNotifications it handles the asynchronicity of the calls for you as part of the framework.
Managed objects also allow for better debuggability especially considering that these are usually cross container calls I find this to be very very useful.
var messageHub = new TinyMessengerHub();
// Publishing a message is as simple as calling the "Publish" method.
messageHub.Publish(new MyMessage());
// We can also publish asyncronously if necessary
messageHub.PublishAsync(new MyMessage());
// And we can get a callback when publishing is completed
messageHub.PublishAsync(new MyMessage(), MyCallback);
// MyCallback is executed on completion
https://github.com/grumpydev/TinyMessenger
A: There is no really right or wrong, but in my opinion it looks so:
NotificationCenter - You don't know which Objects are interested on the "Events", you send it out and any object can receive it
.Net Events - If there is a direct connection between two objects use this, for example like an UIViewController shows an other UIViewcontroller as Modal. The ModalUIViewcontroller fires an event, if it will hide and the UIViewController is Suscribed to it
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612448",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: C++ conversion const pass-by-reference Given a template pass-by-reference conversion/type-cast operator (without const) is possible:
class TestA
{
public:
//Needs to be a const return
template<typename TemplateItem>
operator TemplateItem&() const {TemplateItem A; A = 10; return A;}
};
int main()
{
TestA A;
{
int N;
N = A;
printf("%d!\n",N);
}
{
float N;
N = A;
printf("%f!\n",N);
}
return 0;
}
And given the following code (with const):
class TestA
{
public:
//Produces error
template<typename TemplateItem>
operator const TemplateItem&() const {TemplateItem A; A = 10; return A;}
};
Produces these errors:
error: cannot convert 'TestA' to 'int' in assignment
error: cannot convert 'TestA' to 'float' in assignment
Question
How do I make it so the conversion/type-cast operator return a const pass-by-reference of the template type?
Context
Before most people come in and freak about how 'you can't convert it to just anything', you'll need context. The above code is pseudo code - I'm only interested on const reference returns being possible, not the pitfalls of a templated conversion function. But if you're wondering what it's for, it's relatively simple:
TemplateClass -> Conversion (turned into byte data) -> File
TemplateClass <- Conversion (changed back from byte data) <- File
The user is expected to know what they are getting out, or it's expected to be automated (I.E. saving/loading states). And yes, there is a universal method for templates using pointers to convert any type into byte data.
And don't give me claptrap about std doing this sort of thing already. The conversion process is part of a more complicated class library setup.
I'm a programmer. Trust me. C++ trusts me and lets me make mistakes. Only way I'll learn.
A: Firstly, your conversion operator is already undefined behavior because you return a reference (const or not) to a local variable that has gone out of scope. It should work fine if you change your conversion operator to return by value which won't induce UB.
EDIT: (removed incorrect information about conversion operators).
But are you really sure that you really want your class type to be convertible to anything? That seems like it's just going to cause many headaches in the future when you're maintaining the code and it converts to an unexpected type automatically.
Another possible implementation is to create an as template method that basically does what your conversion operator wants to do and call it like obj.as<int>().
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612455",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: EntityFramework Repositories drives from an Interface and abstract class : how to use dependency inject on ASP.NET MVC Ok, let me break down what I have been trying to do :
First of all here is the abstract generic repository of mine :
public abstract class Repository<T, C> where T : class where C : DbContext, new() {
private C _entities = new C();
public IQueryable<T> FindBy(Expression<Func<T, bool>> predicate) {
IQueryable<T> query = _entities.Set<T>().Where(predicate);
return query;
}
public void Add(T entity) {
_entities.Set<T>().Add(entity);
}
public void Delete(T entity) {
_entities.Set<T>().Remove(entity);
}
public void Edit(T entity) {
_entities.Entry(entity).State = System.Data.EntityState.Modified;
}
public void Save() {
_entities.SaveChanges();
}
}
Also, here is an interface which I will use for my AccommPropertyWebDetailRepository repository class :
public interface IAccommPropertyWebDetailRepository {
IQueryable<AccommPropertyWebDetail> GetAll(ApprovalStatus approvalstatus = ApprovalStatus.All);
AccommPropertyWebDetail GetSingle(int accommPropertyWebDetailId, ApprovalStatus approvalstatus = ApprovalStatus.All);
AccommPropertyWebDetail GetSingleByAccommPropertyId(int accommPropertyId, ApprovalStatus approvalstatus = ApprovalStatus.All);
}
And the below one is my AccommPropertyWebDetailRepository class :
public class AccommPropertyWebDetailRepository : Repository<AccommPropertyWebDetail, ReservationHubEntities>, IAccommPropertyWebDetailRepository {
ReservationHubEntities _entities = new ReservationHubEntities();
public IQueryable<AccommPropertyWebDetail> GetAll(ApprovalStatus approvalstatus = ApprovalStatus.All) {
IQueryable<AccommPropertyWebDetail> query = _entities.AccommPropertyWebDetails;
switch (approvalstatus) {
case ApprovalStatus.Approved:
query = query.Where(x => (x.AccommProperty.IsApproved == true) && (x.AccommProperty.IsLockedForView == false));
break;
case ApprovalStatus.NotApproved:
query = query.Where(x => (x.AccommProperty.IsApproved == false) || (x.AccommProperty.IsLockedForView == true));
break;
}
return query;
}
public AccommPropertyWebDetail GetSingle(int accommPropertyWebDetailId, ApprovalStatus approvalstatus = ApprovalStatus.All) {
var query = GetAll(approvalstatus).First(x => x.AccommPropertyWebDetailID == accommPropertyWebDetailId);
return query;
}
public AccommPropertyWebDetail GetSingleByAccommPropertyId(int accommPropertyId, ApprovalStatus approvalstatus = ApprovalStatus.All) {
var query = GetAll(approvalstatus).Single(x => x.AccommPropertyID == accommPropertyId);
return query;
}
}
So everything has been fine so far (according to me but I am not sure what I am missing).
The real problem I have is on the ASP.NET MVC Web application side.
Let's assume that my controller class starts as follows :
public AccommPropertyController(
IAccommPropertyPictureRepository accommpropertypicturerepo) {
_accommpropertypicturerepo = accommpropertypicturerepo;
}
private readonly IAccommPropertyPictureRepository _accommpropertypicturerepo;
And for dependency injection, I have the following code (I am using Ninject for Dependency Injection) :
/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel) {
kernel.Bind<IAccommPropertyPictureRepository>().
To<AccommPropertyPictureRepository>();
}
So, where is Repository<T, C> abstract class supposed to fit in here?
Because, I didn't directly use AccommPropertyPictureRepository inside my controller and only used IAccommPropertyPictureRepository interface, my controller doesn't know anything about Repository<T, C> abstract class.
Any known ways of dealing with this annoying issue?
UPDATE 1
So, now after @Darin's suggestion, I have following interface
public interface IRepository<T, C> where T : class where C : DbContext {
IQueryable<T> FindBy(Expression<Func<T, bool>> predicate);
void Add(T entity);
void Delete(T entity);
void Edit(T entity);
void Save();
}
And my abstract class is as follows :
public abstract class Repository<T, C> : IRepository<T, C> where T : class where C : DbContext, new() {
private C _entities = new C();
public IQueryable<T> FindBy(Expression<Func<T, bool>> predicate) {
IQueryable<T> query = _entities.Set<T>().Where(predicate);
return query;
}
public void Add(T entity) {
_entities.Set<T>().Add(entity);
}
public void Delete(T entity) {
_entities.Set<T>().Remove(entity);
}
public void Edit(T entity) {
_entities.Entry(entity).State = System.Data.EntityState.Modified;
}
public void Save() {
_entities.SaveChanges();
}
}
Can't figure the rest of it out.
UPDATE 2
Now I have figured something out as well. Here is IAccommPropertyPictureRepository interface :
public interface IAccommPropertyPictureRepository<T, C> : IRepository<T, C> where T : class where C : DbContext {
IQueryable<AccommPropertyPicture> GetAll(ApprovalStatus approvalstatus = ApprovalStatus.All);
IQueryable<AccommPropertyPicture> GetAll(int accommPropertyId, ApprovalStatus approvalstatus = ApprovalStatus.All);
AccommPropertyPicture GetSingle(int accommPropertyPictureId, ApprovalStatus approvalstatus = ApprovalStatus.All);
AccommPropertyPicture GetSingle(Guid accommPropertyPictureGUID, ApprovalStatus approvalstatus = ApprovalStatus.All);
}
and here is the AccommPropertyPictureRepository class :
public class AccommPropertyPictureRepository : Repository<AccommPropertyPicture, ReservationHubEntities>, IAccommPropertyPictureRepository<AccommPropertyPicture, ReservationHubEntities> {
ReservationHubEntities _entities = new ReservationHubEntities();
public IQueryable<AccommPropertyPicture> GetAll(ApprovalStatus approvalstatus = ApprovalStatus.All) {
IQueryable<AccommPropertyPicture> query = _entities.AccommPropertyPictures;
switch (approvalstatus) {
case ApprovalStatus.Approved:
query = query.Where(x => (x.AccommProperty.IsApproved == true) && (x.AccommProperty.IsLockedForView == false));
break;
case ApprovalStatus.NotApproved:
query = query.Where(x => (x.AccommProperty.IsApproved == false) || (x.AccommProperty.IsLockedForView == true));
break;
}
return query;
}
public IQueryable<AccommPropertyPicture> GetAll(int accommPropertyId, ApprovalStatus approvalstatus = ApprovalStatus.All) {
var query = GetAll(approvalstatus).Where(x => x.AccommPropertyID == accommPropertyId);
return query;
}
public AccommPropertyPicture GetSingle(int accommPropertyPictureId, ApprovalStatus approvalstatus = ApprovalStatus.All) {
var query = GetAll(approvalstatus).First(x => x.AccommPropertyPictureID == accommPropertyPictureId);
return query;
}
public AccommPropertyPicture GetSingle(Guid accommPropertyPictureGUID, ApprovalStatus approvalstatus = ApprovalStatus.All) {
var query = GetAll(approvalstatus).First(x => x.AccommPropertyPictureGUID == accommPropertyPictureGUID);
return query;
}
}
I have a successful build now. Should Ninject stuff stay unchanged? I think I only need to change some of the code from my controller constructor, right?
A: One possibility would be to have a base IRepository<T, C> interface containing all the necessary operations and which will be implemented by the Repository<T, C> abstract class as well as by the IAccommPropertyWebDetailRepository interface.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612459",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Reading an IEnumerable multiple times Let's say I have some code:
var items = ItemsGetter.GetAllItems().Where(x => x.SomeProperty > 20);
int sum1 = items.Sum(x => x.SomeFlag == true);
And for example I need some other sum from the items collection later in the code.
int sum2 = items.Sum(x => x.OtherFlag == false);
So my question: Is it OK to call Linq methods on IEnumerable more than once? Maybe I should call Reset() method on enumerator or make list from items using ToList method?
A: I'm occasionally in the situation that I have to process an enumerable multiple times. If enumerating is expensive, non-repeatable and yields a lot of data (like a IQueryable that reads from a database), enumerating multiple times is not an option, neither is buffering the result in memory.
Until today I often ended up writing aggregator classes into which I could push items in a foreach loop and eventually read the results out - much less elegant than LINQ is.
But wait, did I just say "push"? Doesn't that sound like... reactive? So I was thinking during tonight's walk. Back home I tried it - and it works!
The example snippet shows how to get both the minimum and maximum items from a sequence of integers in a single pass, using standard LINQ operators (those of Rx, that is):
public static MinMax GetMinMax(IEnumerable<int> source)
{
// convert source to an observable that does not enumerate (yet) when subscribed to
var connectable = source.ToObservable(Scheduler.Immediate).Publish();
// set up multiple consumers
var minimum = connectable.Min();
var maximum = connectable.Max();
// combine into final result
var final = minimum.CombineLatest(maximum, (min, max) => new MinMax { Min = min, Max = max });
// make final subscribe to consumers, which in turn subscribe to the connectable observable
var resultAsync = final.GetAwaiter();
// now that everybody is listening, enumerate!
connectable.Connect();
// result available now
return resultAsync.GetResult();
}
A: Well, it really depends what you want to do. You could take the hit of executing the query twice (and the exact meaning of that will depend on what GetAllItems() does), or you could take the hit of copying the results to a list:
var items = ItemsGetter.GetAllItems().Where(x => x.SomeProperty > 20).ToList();
Once it's in a list, obviously it's not a problem to iterate over that list multiple times.
Note that you can't call Reset because you don't have the iterator - you have the IEnumerable<T>. I wouldn't recommend calling IEnumerator<T> in general anyway - many implementations (including any generated by the C# compiler from iterator blocks) don't actually implement Reset anyway (i.e. they throw an exception).
A: LINQ uses deferred execution, so 'items' will only enumerate when you request it to via another method. Each of your Sum methods will take O(n) to iterate through. Depending on how large your items list is, you may not want to iterate over it multiple times.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612462",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "25"
}
|
Q: JasperReports - Conditional style per locale? Is there a way to use a different styles, or redefine a style, based on a report parameter locale? I need to modify font sizes for certain languages.
A: I have implemented this in the past using external style templates. There is a sample on jasperforge that illustrates how to do this.
Once you've moved your styles to external templates, you can create locale specific templates. The templating mechanism allows you to inherit from and override specific styles, so the locale specific versions don't get overly bloated. The example I linked above includes inheriting from and overriding base styles.
In your reports, you can then load the appropriate template at render time.
One easy way to do this is:
*
*provide the path to the template that you want to use as a parameter
to the report
*include a template tag in the jrxml file that references the
parameter:
<template><![CDATA[$P{TEMPLATE_PATH}]]></template>
Then, in the code that renders the report, just set the TEMPLATE_PATH parameter appropriately for the report locale.
Again, the linked documentation mentions how to do this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612473",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How can I reliably use code from github in vendor/gems? I like to vendor as many gems as possible, except those that must be built on each platform (libxml, etc.) but sometimes I like to use some bleeding-edge code rather than the gems that are out there on the gem servers.
Can I clone a github gem directly into vendor/gems. I guess I could, but will it affect my app code since it is already a git repository? I would like to just do periodic git pulls for these couple of gems so that I don't have to update every gem and maybe break something.
A: Use of vendor/gems has been deprecated in favor of using Bundler and Gemfile instead. The vendor system had a number of flaws including a lack of support for compiled extensions, so it was never a complete solution.
You're better off locking your versions in the Gemfile as required. If you want to use bleeding edge versions, comment out the version declaration, remove Gemfile.lock and do a bundle install again.
It's often the case that the published version of the gem has a flaw you need to repair by forking and fixing, so it's easy to track this:
gem 'broken-gem', :git => 'git://github.com/myname/broken-gem.git'
The advantage here is that the Gemfile serves as documentation of what versions of the gems you require, and where to get them. vendor/gems leaves people in the dark as to where that version came from.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612477",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Error while adding WebSphere in Eclipse I am trying to use WebSphere v6.0 with Eclipse. When I try to add the runtime server for a Dynamic Web Project, I get the following error:
Missing classpath entry \your_server_root\was-6.0\properties
Why?
A: My thought? Add that entry to the CLASSPATH.
Another thought would be to ditch WebSphere and use Tomcat, JBOSS, or Glassfish.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612478",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Access to jquery selection while in context of a Google Maps Info Window I have a web page that uses JQuery extensively, with no issues. It's basically a Google Map, with extra buttons, implemented as custom controls.
However, when I popup an Info Window, I want to put up some text in that window, but also a button. When the user clicks that button, I want something to happen (popup another small window).
My problem is, JQuery selectors don't seem to know about the markup in my Info Window.
Here's a piece of JavaScript that shows how I open the Google Maps InfoWindow:
contentString = contentString + '<input class=\"key\" id=\"dtmf55\" value=\"More\" type = \"button\" title=\"Click me for information !\">';
current_infowindow.setContent(contentString);
current_infowindow.open();
Elsewhere on the page, I have JQuery:
$("#dtmf55").click(function() {
alert ("Ya got me.");
});
I know the JQuery works, because I can put the same button elsewhere on the page, (not in an Info Window), and pressing the button fires the click function.
So how can I get my Info Window to have access to the same context? Or am I just profoundly on the wrong track?
Thanks,
A: you probably need to use a LIVE function
$("#dtmf55").live('click',function() {
alert ("Ya got me.");
});
That will bind click to a javascript generated element.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I display post without comments using the Comments plug-in Below is the code generated from facebook plugins page:
<div id="fb-root"></div>
<script> (function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) { return; }
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
} (document, 'script', 'facebook-jssdk'));</script>
<div class="fb-comments" data-href="example.com" data-num-posts="1" data-width="200"></div>
How can I display only 1 post on my website but hide all the comments for that post?
A: There is not an option for this with the Facebook comments plugin. You could pull down all comments and render the post you wanted yourself via the graph api with this style url:
https://graph.facebook.com/comments/?ids=http://developers.facebook.com/docs/reference/plugins/comments
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612483",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Initializing a new class in its own constructor I have a User class. One of the properties needs to be an "associated" user, so it's type needs to be User. Right now when I initialize the class, I get a stack overflow when it tries to initialize the Associated property. Current code:
public class User {
public User() {
this.Associated = new User();
}
public User Associated { get; set; }
}
Is this doable or am I barking up the wrong tree?
A: Does User.Associated have to be populated on construction? If you remove the assignment from the constructor you shouldn't get SO.
The reason you are getting an SO is because when you construct a User() it constructs a User() which in turn constructs a User() and it is turtles all the way down.
A: You could use a lazy loaded method for your aggregated User class and not initialize it in the constructor:
public class User {
private User _user;
public User Associated
{
get
{
if (_user == null)
_user = new User();
return _user;
}
}
}
A: You are calling the User constructor recursively. Every time you new a User, it news another User ad infinitum (or rather, ad StackOverflowException).
A: Do not initialize the Associated member in the constructor. If you only initialize it when you need it, I think the stack overflow should go away.
A: The problem is that you've developed an endless loop of new users. Each new user gets a new user as an associate.
I would remove the assignement from the default constructor, then add it as a public property. Doing this will allow you to control when associates are assigned, and will prevent the endless loop.
A: Calling the constructor inside the constructor leads you to an infinite loop:
Create a new User instance -> Create a new User instance -> Create a new User instance -> Create a new User instance -> Create a new User instance -> Create a new User instance...
You could do something like that:
public class User {
public User() {
}
public AddAssociatedUser() {
this.Associated = new User();
}
public User Associated { get; set; }
}
And call the AddAssociatedUser when you need it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612488",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: workaround to read proper dimension when display : 'none' Are there any workarounds to read proper element dimensions when it's display value is set to none?
Well, one would be to hide it without changing the display, but visibility property instead. While it gives proper dimensions, the element affects document flow.
One more way I can think of is opacity, but then the browser support kicks in.
The element I'm working with is appended to body.
Oh yes, I'm looking for computed style. There are no static CSS properties set for dimensions etc.
Any other solutions?
A: When display is none, by definition elements non-block elements have no dimensions. (Thanks, @Pekka) One potential way around this is to position the element far off-screen by setting position: absolute and left: -999em. The element will still exist so you can get its dimensions, but it won't appear in the document and should not affect flow.
A: There is a way to do it with offsetHeight and javascript
<script type="text/javascript">
<!--
onload=function() {
var divh = document.getElementById('top').offsetHeight;
alert(divh +"px");
}
//-->
</script>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612489",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: HTML to PDF Solution (Handling Content, Headers and Footers) I'm trying to create a "report" by generating a PDF based on HTML.
At first, I simply attempted to write raw encoded HTML to a document and then print that document using Javascript. However, this gave me little to no control involving headers and footers.
I attempted using thead and tfoot elements, which worked reasonably well in most browsers, however I wasn't able to get the formatting that I was looking for.
Currently - I am trying to work on a server-side solution using iTextSharp in MVC3, however I am a bit lost as to how to proceed, having not worked with iTextSharp much.
Input and Description of Output:
There will be 4 items used in creating the Report:
*
*Report Content (which is currently encoded HTML, as I am unsure if decoding will change any formatting)
*Report Title (will simply be the name of the PDF generated)
*Report Header (will be displayed at the upper-left of each page)
*Report Footer (will be displayed at the lower-left of each page)
Controller Action:
//This will be accessed by a jQuery Post
[HttpPost]
public FileStreamResult GeneratePDF(string id)
{
//Grab Report Item
ReportClass report = reportingAgent.GetReportById(id);
Document doc = new Document();
//Do I need to decode the HTML or is it possible to use the encoded HTML?
//Adding Headers / Footers
//Best method of returning the PDF?
}
A: iTextSharp cannot convert HTML to PDF. It's not what it was designed to do. It was designed to create PDF files from scratch, not converting between various formats into PDF. If you want to convert HTML into PDF you could for example use the the flying-saucer library which is based on iText. I have blogged about how this could be done in .NET using IKVM.NET Bytecode Compiler (ikvmc.exe).
So your controller action might look something along the lines of:
[HttpPost]
public FileStreamResult GeneratePDF(string id)
{
ReportClass report = reportingAgent.GetReportById(id);
return PdfResult(report.Html);
}
where PdfResult could be a custom action result taking the raw HTML and outputting the PDF into the response stream:
public class PdfResult : ActionResult
{
private readonly string _html;
public PdfResult(string html)
{
_html = html;
}
public override void ExecuteResult(ControllerContext context)
{
var response = context.HttpContext.Response;
response.ContentType = "application/pdf";
var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
using (var bais = new ByteArrayInputStream(Encoding.UTF8.GetBytes(_html)))
using (var bao = new ByteArrayOutputStream())
{
var doc = builder.parse(bais);
var renderer = new ITextRenderer();
renderer.setDocument(doc, null);
renderer.layout();
renderer.createPDF(bao);
var buffer = bao.toByteArray();
response.OutputStream.Write(buffer, 0, buffer.Length);
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612496",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: xcode4 svn commit failed: File .xcodeproj/project.pbxproj is out of date Just getting started in xcode 4 and svn, opened my project (had been using xcode3 and svn) but now when I commit I have no trouble except when I try to commigt the file project.pbxproj and I get the message about being out of date. Probably an easy problem but I'm such a newb with macs, xcode and svn I'm stuck.
Also is there a really good tutorial on using svn with xcode, I've been trying to use the one at apple but it was pretty useless, when I do a checkout i get not just a working copy but it seems to copy over the whole svn repository beside my working copy. I know there are a bunch of tuts found via google but I'm asking if you can recommend a really good one. I might need to even redesign my repository since some of my previous commits(before i upgraded to xcode4) seem to have been ignored.
Thanks in advance
A: The file you are trying to commit is out of date, meaning it has been changed in the repository since you last updated.
Execute this and resolve any conflicts (if any):
svn up project.pbxproj
Then you can commit again.
A: When you see this message, run SVN's Update command. I don't know about XCode 4, but in XCode 3 there are "Update Entire Project" and "Update To" SCM menu commands.
If update ends in conflicts, read generic SVN tutorial about what they are and what to do.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612498",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Implementing pthread pool I need to implement a thread pool using pthreads. I could not move forward. I found similar question here
But that still does not clarify my question. My question is once a thread runs to its termination can I use it again? Another way of putting this question is, How does a thread return to its thread pool after running a task to its completion. Could anyone point me to some simple pthread pool article? My confusion arises mainly because I have little bit of java background. I read somewhere we cannot call start() on thread second time once it terminates.
A:
My question is once a thread runs to its termination can I use it
again?
Yes, that's the purpose of the pool, to reuse threads instead of destroying them.
How does a thread return to its thread pool.
By trying to get another element from the queue. Doing it in a loop is one way.
Here is what every thread does in my implementation (this is the actual function used with pthread_create):
static void *
_tp_worker(void *arg)
{
/* ... */
/* Wait until tasks is available. */
while (!queue_get(pool->pend_q, &t_ptr)) {
/* And then execute it. */
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612501",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Change Text Color of Menu Item in ASP.Net Navigation Menu From Javascript I have an ASP.Net Navigation Menu control with 1 item that I need to dynamically change the color of the text if certain conditions exist. I have a function set to run every 1 second to check for those conditions and needs to set the text of the menu item to Red if true. I've tried:
var item = $("ul").children().eq(6);
item.style.color = "red";
But get "cannot set property color of undefined" error. I've tried:
$("ul").children().eq(6).css("color", "red");
And it finds the menu item, changes the color property to red, but still displays the previous color. Never actually turns red. Below is the html from the page when this happens:
<li role="menuitem" class="static" style="position: relative; float: left; color: red; ">
<a class="level1 static" href="Sync.aspx" tabindex="-1">Sync</a>
</li>
Any ideas?
A: If you are trying to access any elements with the attribute runat="server" from javascript, try giving the element the ClientIDMode="Static" attribute. Otherwise, asp.net is prone to renaming the IDs of your elements.
A: It's because you've got an anchor tag <a> within the <li>. What you need to do is to set the color of the <a> not the color of the <li>:
$("ul").children().eq(6).children().css("color", "red");
Example: http://jsfiddle.net/Jscng/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612502",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can you loop through an enum in C#? for (int i = (int)MY_ENUM.First; i <= (int)MY_ENUM.Last; i++)
{
//do work
}
Is there a more elegant way to do this?
A: Enums are kind of like integers, but you can't rely on their values to always be sequential or ascending. You can assign integer values to enum values that would break your simple for loop:
public class Program
{
enum MyEnum
{
First = 10,
Middle,
Last = 1
}
public static void Main(string[] args)
{
for (int i = (int)MyEnum.First; i <= (int)MyEnum.Last; i++)
{
Console.WriteLine(i); // will never happen
}
Console.ReadLine();
}
}
As others have said, Enum.GetValues is the way to go instead.
A: Take a look at Enum.GetValues:
foreach (var value in Enum.GetValues(typeof(MY_ENUM))) { ... }
A: You should be able to utilize the following:
foreach (MY_ENUM enumValue in Enum.GetValues(typeof(MY_ENUM)))
{
// Do work.
}
A: The public static Array GetValues(Type enumType) method returns an array with the values of the anEnum enumeration. Since arrays implements the IEnumerable interface, it is possible to enumerate them.
For example :
EnumName[] values = (EnumName[])Enum.GetValues(typeof(EnumName));
foreach (EnumName n in values)
Console.WriteLine(n);
You can see more detailed explaination at MSDN.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612507",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "32"
}
|
Q: How to mock wcf service(transformed from asmx) by Moq I have Silverligth Unit test Application (.net 4.0) and I've added reference to my WCF service(3.5)
And here are my codes
MyService.svc
<%@ServiceHost Language="VB" Service="MyServiceWS.Service1" %>
MyService.asmx
<System.Web.Services.WebService(Namespace:="http://schemas.mypage.co.uk/MyService")> _
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ServiceContract(Namespace:="http://schemas.mypage.co.uk/MyService")> _
<ServiceKnownType(GetType(Member))> _
<ToolboxItem(False)> _
Public Class Service1
Inherits System.Web.Services.WebService
From reference.cs
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public partial class Service1Client : System.ServiceModel.ClientBase<MyServiceApp.MyServiceService.Service1>, MyServiceApp.MyServiceService.Service1 {
my testclass:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
namespace MyServiceApp.UnitTests
{
[TestClass]
public class ShowroomLogViewModelTests
{
[TestMethod]
public void ReloadShowroomLogs_IsBusyShouldBeFalse()
{
var mockedWebService = Mock<IService1>;
Problem is that:
IService1 cannot be resolved
How can I mock my wcf service?
EDIT: One Step Closer
var mockedWebService =new Mock<MyService.Service1>;
I've changed to this and now is compiling, but...
I haven' access to method, e.g.
mockedWebService.GetShowroomLogs();
It is a big problem, because, I need change a property ServiceClient at ShowroomLogViewModel to interface, and I can't because then my viewmodel can't use wcf service methods.
A: You should do this: mockedWebService.Object.GetShowroomLogs();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Matlab shrink image array based on another array I have an array that is holding an image of size (560 x 296) which is the original image that I input into my program. Now I have another array of the same size (560 x 296) that is filled with 0s and 1s. The 1s mark the position of pixels I want to keep in the original image, and the 0s mark the pixels I want to remove from the original image.
Is there some sort of fancy matlab function that shrinks an array based on another array?
Any help/links would be awesome as I am new to Matlab.
Thanks
A: Assuming B is a logical array, you want either
A(~B) = 0;
or
A(~B) = [];
Only the first is guaranteed to preserve the shape of A, but it doesn't really remove them: it only blanks them.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612511",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: JasperReport 4.1.2 - Using complex Java Bean and subreports I'm facing a problem when trying to generate a report based on some java bean's.
Suppose I have this configuration: a master bean, say
Bean1
*
*String name
*String age
*ArrayList bean2
Bean2
*
*String text
*ArrayList
Bean3 is the last child of the tree and it is composed by:
*
*String text
(I have more levels but this is enough for you to understand)
I'm using SubReport component to access data inside every ArrayList of a bean and it works well (using JRBeanCollectionDataSource()).
The problem is that, at Bean3, I have acess to all text fields of every Bean2. For example: I have an ArrayList<Bean2> of size 2: bean2_1 and bean2_2.
bean2_1 has an ArrayList<Bean3> of size 2 and bean2_2 has an ArrayList of size 3.
When I print the content of Bean3 (field text) for bean2_1 and bean2_2, it shows all 5 text values for all my beans: bean2_1 and bean2_2.
Anyone had already faced this problem? How can i bind the differente levels to show only the correct data??
Can anyone help ?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612513",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: declarative authorization in Java EE is there any declarative way in Java EE to restrict method calls based on both the caller and the target entity?
Let's say I have a Forum object and a user set with the Moderator role, but this is on a per-forum basis. The moderator is the only one that can call the deletePost() method on the Forum entity, the others can only post their own.
Please ignore Spring now; let's stick to Java EE 6 preferably with Glassfish, but I'm open to WAS too.
A: I can't see how this could be done. Maybe a combination of interceptors and instead of using the entities directly, use a SLSB. I don't like this, tho.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612516",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ASP.NET MVC rendering model not the way I expect Today I faced a problem and I'm not able to get weather I understand something wrong about ASP.NET MVC (and possibly MVC in general) or I miss something about it's implementation.
So, I have a simple model hierarchy:
public class Child
{
public Child(int notId, bool isSelected, string text)
{
NotId = notId;
IsSelected = isSelected;
Text = text;
}
public Child(){}
// naming: just to make sure I do not mess with some
// conventional infrastructure
public int NotId { get; set; }
public bool IsSelected { get; set; }
public string Text { get; set; }
}
public class Parent
{
public List<Child> Children { get; set; }
}
Here is my HomeController's Edit actions:
[HttpGet]
public ActionResult Edit()
{
var parent = new Parent
{
Children = new List<Child>
{
new Child(1, true, "a"),
new Child(2, false, "b")
}
};
return View(parent);
}
[HttpPost]
public ActionResult Edit(Parent parent)
{
parent.Children = new List<Child>
{
new Child(4, false, "c"),
new Child(5, true, "d")
};
return View(parent);
}
Hese is my Edit.aspx view:
<!-- Standart HTML elements ommited -->
<% Html.BeginForm(); %>
<% for (var i = 0; i < Model.Children.Count; i++){%>
<div>
<%=Html.LabelFor(m => m.Children[i].IsSelected)%>
<%=Html.EditorFor(m => m.Children[i].IsSelected)%> <!-- lamda -->
<%=Html.CheckBoxFor(m => m.Children[i].IsSelected)%> <!-- lamda -->
<%=Html.CheckBox("A", Model.Children[i].IsSelected)%> <!-- simple -->
</div>
<% } %>
<input type="submit" value="Submit" />
<% Html.EndForm();%>
The point is that in Edit (HttpGet) method I create Parent instance with two child Child elements having their IsSelected properties set to true and false respectively. After form is submitted in Edit (HttpPost) method I give my Parent object a new children collection of two Child elements with their IsSelected properties set to false and true respectively (that is opposite from HttpGet method) and call View() method to render my model.
But what I get after submit is checkboxes, rendered with Html.EditorFor() and Html.CheckBoxFor() do not changes their state. It looks like Html.EditorFor() and Html.CheckBoxFor() methods take data NOT from my model but from a posted form data.
Could someone please explain me what is going on here and why ASP.NET MVC refuses to render my model? Workarounds? Fixes to my code?
Thanks in advance.
P.S. I noticed this behavior in MVC2 and thought this was some kind of a bug, but when I tested this with MVC3 it did the same thing.
A:
But what I get after submit is checkboxes, rendered with
Html.EditorFor() and Html.CheckBoxFor() do not changes their state. It
looks like Html.EditorFor() and Html.CheckBoxFor() methods take data
NOT from my model but from a posted form data.
That's exactly what they do and that's by design. Html helpers first look at modelstate when binding values and then the model. If you want to change this behavior you could remove all the items from model state that you intend to modify in your controller action:
[HttpPost]
public ActionResult Edit(Parent parent)
{
ModelState.Remove("Children");
parent.Children = new List<Child>
{
new Child(4, false, "c"),
new Child(5, true, "d")
};
return View(parent);
}
A:
Html.CheckBoxFor() methods take data NOT from my model but from a
posted form data.
That is correct.
You'll have to clear ModelState with ModelState.Clear() to get these checkboxes to use the actual Model value and not the form data.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612518",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: groovy singleton pattern Q1. What is the best way to implement the singleton pattern using groovy? What are the other options available in groovy to support the singleton mechanism?
Any example that would be useful.
Q2. Does groovy support something like File changed listener?
A: Regarding Q2: while groovy itself doesn't provide any way to be notified on file changes, Java 7, which can be used with groovy, does.
In particular, if you want to watch for file changes on a file foo in the current directory, you can do something like this:
import java.nio.file.*
FileSystems.default.getPath(".") // dot for current directory
def watchKey = p.register(FileSystems.default.newWatchService(),
StandardWatchEventKinds.ENTRY_MODIFY)
def events = watchKey.pollEvents()
events.findAll{it.context().fileName == 'foo'}.each { event ->
println "foo was changed"
}
A: Q1
You can make any class a singleton simply by adding a @Singleton annotation (since groovy v1.7.0 at least):
@Singleton
class MyClass {
}
You can then access the singleton instance with
MyClass singleton = MyClass.instance
Q2
I think you're asking if Groovy provides a listener which is called every time a file is changed? I am not aware of any such facility in Groovy. If such a class exists you're more likely to find a Java implementation (which you could use in your Groovy program).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612520",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: How to tell if an object is a RegExp object?
Possible Duplicate:
typeof for RegExp
I have a routine that is testing to see if an object matches given criteria.
testForMatch(objectToTest, matchCriteria) {
// all my testing logic here.
}
The parameter matchCriteria is an object that could look like this, for example:
{
'size' : "large",
'color' : /(blue|red)/
}
This matchCriteria in the above example will be used to test if objectToTest has an attribute size with value "large", and an attribute color with value of either "blue" or "red".
So matchCriteria has property/attribute names that will be sought in objectToTest with the goal of matching the values of the properties. Or, if a regex is given as the value (as in the case of color above) the property in objectToTest will be RegExp.test()'ed against the given regex.
But in order to treat the matchCriteria properly in testForMatch(), I need to be able to tell if the value of an attribute in matchCriteria is a string or a RegExp object.
My question is, how can I detect if the value of an attribute is a RegExp object?
A: how about
var o = {
'size' : "large",
'color': /(blue|red)/
}
console.log( o['color'] instanceof RegExp )
>>true
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612523",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Parse output from a process that updates a single console line Greetings stackoverflow members,
in a BackgroundWorker of a WPF Frontend i run sox (open source console sound processing tool) in a System.Diagnostics.Process. In that same way i use several other command line tools and parse their output to poulate progress bars in my frontend.
This works fine for the other tools but not for Sox since instead of spamming new lines for each progress step, it updates a single line on the console by only using carriage returns (\r) and no line feeds (\n). I tried both asynchronous and synchronous reads on process.StandardError.
Using async process.ErrorDataReceived += (sender, args) => FadeAudioOutputHandler(clip, args); in combination with process.BeginErrorReadLine(); doesn't produce any individual status updates because for some reason the carriage returns do not trigger ReadLine, even though the MSDN docs suggest that it should. The output is spit out in one chunk when the process finishes.
I then tried the following code for synchronous char by char reads on the stream:
char[] c;
var line = new StringBuilder();
while (process.StandardError.Peek() > -1)
{
c = new char[1];
process.StandardError.Read(c, 0, c.Length);
if (c[0] == '\r')
{
var percentage = 0;
var regex = new Regex(@"%\s([^\s]+)");
var match = regex.Match(line.ToString());
if (match.Success)
{
myProgressObject.ProgressType = ProgressType.FadingAudio
//... some calculations omitted for brevity
percentage = (int) Math.Round(result);
}
else
{
myProgressObject.ProgressType = ProgressType.UndefinedStep;
}
_backGroundWorker.ReportProgress(percentage, myProgressObject);
line.Clear();
}
else
{
line.Append(c[0]);
}
}
The above code does not seem to read the stream in realtime but will stall output for a while. Then it spams a small chunk and finally deadlocks half-way through the process.
Any hints towards the right direction would be greatly appreciated!
UPDATE with (sloppy?) solution:
This drove me crazy because nothing i tried on the C# side of things seemed to have any effect on the results. My original implementation, before changing it 15 times and introducing new dependencies, was fine.
The problem is with sox and RedirectStandardError alone. I discovered that after grabbing the sox source code and building my own version. First i removed all output of sox entirely except for the stuff i was really interested in and then changing the output to full lines followed by a newline \n . I assumed that this would fix my issues. Well, it didn't. I do not know enough c++ to actually find out why, but they seem to have tempered with how stdio writes to that stream, how it's buffered or do it in such a special way that the streamreader on the c# side is not flushed until the default 4096 byte buffer is full. I confirmed that by padding each line to at least 4096 byte. So in conclusion all i had to do was to manually flush stderr in sox.c after each fprintf(stderr, ...) call in display_status(...):
fflush(stderr);
Though, I'm not sure this is anywhere close to an elegant solution.
Thanks to Erik Dietrich for his answer which made me look at this from a different angle.
A: The situation you describe is a known problem - for a solution including source code see http://www.codeproject.com/KB/threads/ReadProcessStdoutStderr.aspx
It solves both problems (deadlock and the problem with \n)...
A: I've had to deal with a similar issue with a bespoke build tool in visual studio. I found that using a regex and doing the parsing in the same thread as the reading is a problem and the output processing grinds to a halt. I ended up with a standard consumer producer solution where you read lines from the output and stick them onto a Queue. Then have the queue be dequeued and processed on some other thread. I can't offer source code but this site has some fantastic resources: http://www.albahari.com/threading/part2.aspx
A: It's a little kludgy, but perhaps you could pipe the output of the uncooperative process to a process that does nothing but process input by characters, insert line feeds, and write to to standard out... So, in terms of (very) pseudo-code:
StartProcess("sox | littleguythatIwrote")
ReadStandardOutTheWayYouAleadyAre()
Could be that just moves the goalposts (I'm a lot more familiar with std in/out/err in the NIX world), but it's a different way to look at the problem, anyway.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612524",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Creating search box using links in html file? I will preface this question with the fact that I am extremely new to HTML and CSS.
I currently have an engineering page at my company I have inherited that has a ton of links. I have organized into some general categories. However, it has been expressed that they would love a searchbox to search links.
I do not have PHP available to me due to circumstances out of my control. What I do have is all the links in my index.html file with the text they display associated with them.
My thought it that I can create the engine such that it recognizes the tag, and then searches the "name" associated with the link in the tag. However, I really have no idea where to start in terms of implementing such a script.
Of course, there may be a much easier way. I am open to any new approaches. I am not biased toward any programming method or language. Thank you so much for the help everyone, and I can provide any other non-NDA information I can.
A: You'll need to include jQuery in your index.html.
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js' />
Give each link a common class. You can then use jQuery to find the link the user is searching for:
var search = $("#searchBox").val();
$("a.myLinks[href*="+search+"]"); // uses jQuery to select the link, see jQuery selectors
Now you can do things with that link, like show it or navigate to it.
A: I would look at the jQuery UI Automcomplete library http://jqueryui.com/demos/autocomplete/, specifically the custom data demo.
I imagine the code something like this (note this is untested and definitely not complete for your purposes):
<head>
<script type='text/javascript'>
var urls = [
{
value: "url-text",
label: "URL Text",
desc: "URL"
},
{
value: "url2-text",
label: "URL2 Text",
desc: "URL2"
}
];
$('#search').autocomplete({
minLength: 0,
source: urls,
focus: function (event, ui) {
$('#search').val(ui.item.label);
return false;
},
select: function (event, ui) {
$('#search').val(ui.item.label);
$('#url').val(ui.item.desc);
return false;
}
})
.data ("autocomplete")._renderItem= function(ul,item) {
return $('<li></li>")
.data( 'item.autocomplete', item )
.append( '<a>' + item.label + '<br />' + item.desc + '</a>' )
.appendTo( ul );
};
</script>
</head>
<body>
<input id="search" />
<p id='url'></p>
</body>
Doing it this way does mean you have to keep a separate list of URLs and text in a javascript variable.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612527",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: setting submit name outside the form I have a zend_form for updating and inserting data.
I want it to have diffrent sumbit labels but it doesn't seem to work.
My form:
class Staff_Form extends Zend_Form
{
public function init()
{
$this->setAction('')
->setMethod('post');
$firstname = new Zend_Form_Element_Text('firstname');
$firstname->setLabel('firstname')->setRequired(true);
$submit = new Zend_Form_Element_Submit('submit');
$submit->setName('insert');
$this->addElements(array(
$firstname,
$submit
));
}
}
Now I would expect this to work:
//in controller
$form = new My_Form();
$form->getElement('submit')->setName('update');
But it gives a fatal error:
Fatal error: Call to a member function setName() on a non-object in.....
So I tried:
$first = $form->getElement('firstname');
var_dump($first);
echo 'html break';
$submit = $form->getElement('submit');
var_dump($submit);
die();
It appears $submit is NULL
What Am I doing wrong?
A: Should really be an typing error somewhere in your code, i just tested the following which works:
class Application_Form_Test extends Zend_Form
{
public function init()
{
$sub = new Zend_Form_Element_Submit('submit');
$sub->setLabel('Submit Me');
$this->addElement($sub);
}
}
//controller - It works
$form = new Application_Form_Test();
$sub = $form->getElement('submit');
$sub->setName('wahahahar');
A: You could pass in the submit value when instatiating the form.
// form
class App_Form_Something extends Zend_From {
protected $submitName
public function init() {
$this->addElement('submit',$this->submitName, array(
'label' => $this->submitName
));
public function setSubmitName($submitName) {
$this->submitName = $submitName;
}
}
Then in your controller
$form = new App_Form_Something(array('submitName' => 'Update or something'));
I use this techique quite often to pass in Id's of certain database objects so they can be auto populated etc.
Good luck
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612528",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: HTTPS on app store - what is the process? (I think this question has been asked before, but the answers have been contradictory and may be out-of-date by now)
I'm creating an app which uses HTTPS, using the ASIHTTPRequest library.
My company is based in the UK, and the app will only be released in the UK.
Do I need to say my app contains encryption, and if so what are the steps required for compliance? Specifically for a non-US company?
A: Here is a fantastic blog post which really helped me with situations like this when using HTTPS API's
Depending on where you go, and what you read you might think you don't need to do anything. That's wrong. If you application uses encryption (including SSL and HTTPS, possible other public domain encryption) then you need to get at least get an ERN before submitting your app to Apple for approval.
Some do get away with saying that no encryption is included even with a toggle to enable SSL on some applications but if you really want to be on the safe side then it's best if you get the certificate.
Another Article I found: http://blog.theanimail.com/iphone-encryption-export-compliance-for-apps
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612541",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Windows Phone 7: All I get is System.MethodAccessException This is my first time to develop apps in Windows Phone 7 and I was not that welcome. LOL.
Anyways, my problem is this MethodAccessException and am not sure why it keeps throwing me that exception.
Here's what I was trying to do.
*
*Getting Application StartUp Path by:
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase
System.Reflection.Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName
API:
[DllImport("coredll.dll", SetLastError = true)]
public static extern int GetModuleFileName(IntPtr hModule, StringBuilder lpFilename, int nSize);
*Try to just enumerate some files
int c = Directory.GetFiles(@"\").Length;
System.Diagnostics.Debug.WriteLine("total files: " + c);
and am not sure what else since I just started coding. I have a big app in mind, and it will cover Registry IO, File IOs, and Database. But if this MethodAccessException keeps blocking my way, I'd rather be dead.
Am using Windows Phone 7.0
6176.WM7 RC1Escrow(buildlab).20100406 1457
A: You cannot use Reflection or P/Invokes in Phone 7.
For File I/O you should be using IsolatedStorageFile for dealing with files. See this example (among many on the web).
There is no Registry access (maybe explaining why you think you need it can lead us to providing alternatives).
For Database access, there are lots of options. Depends on where you want the database (local/remote/cloud), what engine you want, ORM preferences, etc.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612550",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to call methods in objective-c? I am actually following a tutorial to create a custom view.But when i try to call methods it doesnot work
Here is the tutorial
http://dialogtree.com/2011/02/ios-development-a-shape-class/
So
1)I have created a new iPhone project Test.xcodeproj
2)Include both the classes form tutorial Shape.h and Shape.m
3)Now i heve imported Shape.h to my TestViewController.m where i am going to display this.
i am trying to call methods in my TestViewController
- (void)viewDidLoad {
[super viewDidLoad];
Shape * shape;
shape = [Shape alloc];
shape = [shape setLocationWithX:10 andY:20];
[shape addPointWithX:10 andY:10];
[shape setColorWithR:20 andG:30 andB:40];
[shape setAlpha:0.5];
}
But it does not showing anythig, why?
What i am going wrong?
A: For starters the correct instantiation for an object is:
shape = [[Shape alloc] init];
Then the line
shape = [rectangle setLocationWithX:10 andY:20];
overwrites the shape object just created.
A: After reading the definition and implementation of the Shape class I see there is a draw method. But this -draw method of your Shape class won't call itself!
You need to call [shape draw:UIGraphicsGetCurrentContext()] in the implementation of the -(void)drawRect:(CGRect)rect method of your custom view to actually ask the shape to draw itself!
[EDIT]
The answer of CocoaFu is also true and is another point you need to fix in your code
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612553",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: File handling : Extra characters in output #include <stdio.h>
int main () {
FILE *fp;
char ch;
char data[100];
int i;
fp = fopen("file.txt","r");
i=0;
while( (ch=fgetc(fp)) != EOF) {
data[i]=ch;
i++;
}
i=0;
while(data[i]) {
printf("%c",data[i]);
i++;
}
return 0;
}
Content of file.txt :
udit@udit-Dabba /opt/lampp/htdocs $ cat file.txt
aGVsbG9teW5hbWVpc2toYW4K
Output of Program :
udit@udit-Dabba /opt/lampp/htdocs $ sudo vim test.c
udit@udit-Dabba /opt/lampp/htdocs $ sudo gcc test.c
udit@udit-Dabba /opt/lampp/htdocs $ ./a.out
aGVsbG9teW5hbWVpc2toYW4K
P�udit@udit-Dabba /opt/lampp/htdocs $
Why these two extra characters appearing in the output of array...???
The input file is actually outcome of base-64 encoding.
A: You aren't terminating the data[] array - there is nothing to put a zero at the end of the inpout, so when you write it out you keep printing the extra (random) values at the end of the data until you happen to hit a zero,
Remember data isn't initialized to anything in c
A: It looks like its because you didn't set data to zeros before you started. Try adding
memset(data,0,sizeof(data));
before you read. The extra output is what happened to be in memory at that location before you started using it.
A: The first loop terminates with EOF, which you don't write to the data array (because you can't).
The second loop terminates with a '\0' which is nowhere in the data array.
I suggest you add the terminating '\0' once you read the EOF.
A: fgetc returns an int not a char.
See if this works out for you:
#include <stdio.h>
int main (void) {
FILE *fp;
int ch;
int data[100] = { 0 }; // Easiest way of initializing the entire array to 0
int i;
fp = fopen("file.txt","r");
i=0;
while( (ch=fgetc(fp)) != EOF) {
data[i]=ch;
i++;
}
// data[i]=0; -->You did not provide a terminating point -
// Not needed if the array is initialized the way i did.
i=0;
while(data[i]) {
printf("%c",data[i]);
i++; }
return 0;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612555",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: DotNetNuke Upgrade Telerik Error I'm trying to upgrade from 05.05.00 to 05.06.03 and getting Telerik-Install-Errors which I can't solve..
Anyone can help?
00:00:00.015 - Installing Package File Telerik_05.04.00_Install: Error!
00:00:01.466 - Installing Package File Telerik_05.05.00_Install: Error!
00:00:02.059 - Installing Package File Telerik_05.06.02_Install: Error!
00:00:02.683 - Installing Package File Telerik_05.06.03_Install: Error!
A: This is a fairly common upgrade error, but it is easy to fix.
First, install Telerik_05.06.03 manually to get the correct version of Telerik.Web.UI.dll , and then reinstall it with the extension installer in order to avoid the same upgrade errors in the future.
Manual install instructions:
*
*Extract the Telerik install package to a convenient location. The package can be found in:
DotNetNuke_Community_05.06.03_Upgrade\Install\Module\Telerik_05.06.03_Install.zip
*Copy the Telerik.Web.UI.dll to the DNN /bin folder, replacing the existing version
*Modify the bindingRedirect in the web.config to point to the correct version (below)
*Once you get the site up and running, use Host Settings - Extensions to reinstall the module.
I have avoided this error by taking the site down from the public internet during upgrades, and by being careful with the file permissions. You can allow only localhost access by removing other IP bindings from IIS. Make sure that 127.0.0.1 or localhost is in the DNN's PortalAlias table. Prior to an upgrade I usually reapply the required permissions to the DNN folders, just in case they have changed since the last upgrade. Depending on the IIS version and configuration you are running, either Network Service or IIS AppPool\DefaultAppPool needs read, write and modify privileges.
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<probing privatePath="bin;bin\HttpModules;bin\Providers;bin\Modules;bin\Support;" />
<dependentAssembly xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity name="Telerik.Web.UI"
publicKeyToken="121fae78165ba3d4" />
<bindingRedirect oldVersion="2008.0.0.0-2020.0.0.0"
newVersion="2011.1.519.35" />
</dependentAssembly>
</assemblyBinding>
</runtime>
See also:
*
*DotNetNuke Installation Guide
*Windows 7 /Windows 2008 R2 cross
application pool isolation
A: @Mika hits the key points on this issue. Here is another description of a similar solution. http://www.dotnetnuke.com/Resources/Forums/forumid/200/postid/413148/scope/posts.aspx#413148
On a positive note, during the development of 6.0 I think we finally identified the cause of this issue and created a fix for it. We should never see this problem in 6.x. I would be very interested to know if you do see it in a 6.x release.
A: Just did another DNN upgrade and found ALL of the above to NOT help prevent the issue. Here is a last ditch option for those who find the above answers did not help:
*
*Backup everything first, duh.
*Keep a copy of your web.config file handy, but rename it to something like original_web.config.
*Make a copy of the release.config from your OLD site copy. (Do NOT take one from the upgrade copy of DNN.)
*Edit the release.config and replace your database connection, including the legacy 'app settings' version, and make them point to your database. (Which you backed up, I can't stress this enough.)
*Change the value in this setting '' to false, not true.
*Copy the upgrade package you are targeting over top.
*Do all the precautions suggested by Mika's post above.
* Bonus: Enable 32-bit support and ensure you are in 'Classic' mode IF you are running a version of DotNetNuke that required it. Don't change if you are unsure!
*Browse to the site, upgrade (successfully!).
NOW, a VERY important step. You'll need to walk through your site testing things. If you find errors you probably had some critical thing in your original_web.config that is NOW MISSING from the fresh web.config I helped you to create (from release.config) above.
So you'll need to do a line-by-line comparison (this takes a seasoned eye) and find things like missing assembly references, binding redirections, handlers, modules, application settings/keys and the like. The more you do this, the faster it gets. (If you suck at understanding web.config stuff, and don't have a strong IIS background, this step has the potential to be horrible - I won't lie.)
That said, a good percentage of the time hardly anything is required from the web.config. When something is missing, it's often just an obvious DLL reference or handler.
Best of luck!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612556",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: From where may I download the Flash Builder SDK equivalent to Flash Player 11? I wish to use Stage3D and Context3D in ActionScript. For that I need to download the beta version of Flash Player 11. However, I can't find the equivalent Flash Builder SDK with the mxmlc executable that can compile ActionScript into Flash 11 capable Shockwave Flash files. Any clue as to where I may download it from?
A: You do not need another SDK you need to modify the flex-config.xml file and add additional parameter to your mxmlc command. Look in sdks\4.5.1\frameworks\flex-config.xml and change the target-player node the swf-version to 13 and the node path-element to the correct playerglobal.swc (available on labs.adobe.com).
The compiler parameter is "-target-player=11.0.0" (if your flex-config.xml reflect that version).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612557",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Available implementations of a distributed REST queue I have the following (common, I guess) scenario: a master node holding a list of items (urls, jobs, whatever) to be processed, and a set of N worker nodes.
Each worker pops an item from the queue, does something, then notifies the master node that the job has successfully finished.
A worker may push new items to the master node, for these to be queued for processing.
Requirements are quite simple:
*
*no job gets executed twice
*no job gets picked by two nodes (ie. "pop" is atomic)
*if a job fails, after a fixed timeout, the job is again available for processing
*the number of concurrent workers is potentially big
*several workers may live on a single node
*master and workers are not assumed to be in the same network
*pop and push must be exposed as a REST API (ie. the queue is language-agnostic)
*items must be stored persistently on the master node (ie. no in-memory solutions)
I am not able to find simple and lightweight REST implementations: I have looked at RabbitMQ, Celery, Google App Engine and a bunch of other less mature projects, but all of them seem quite complex to manage, and a bit like overkill for what I need.
Any solution that I might be overlooking?
A: Amazon SQS might be what you want: http://aws.amazon.com/sqs/
Jan
A: I went through the same search. I found celery was close (also looked at others like octobot) - none seemed as simple as I desired, and were missing a few things. I found celery was fairly simple, however introduces a reasonable amount of dependencies which I didn't already have in the mix, so I went with something bespoke instead (erlang based)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612558",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Guidance with header and main template - seek best practice please I'm new to C++ and was needing some help in terms of using the best coding practices. Basically I have created my header file (character.h) with the following data:
using namespace std;
class character
{
//available to all
public:
character();
~character(){};
int getHP(){return hp;};
int damage(int _damage);
int levelUp(int _xp);
void setHP(int _hp){hp = _hp;};
string getName(){return name;};
protected:
int hp;
string name;
};
class player:public character
{
public:
player();
~player(){};
protected:
string name;
int lvl;
int xp;
};
class enemy:public character
{
public:
enemy(string _name, int _hp);
~enemy(){};
protected:
string name;
int lvl;
int xp;
};
I was trying to generate the main file (main.cpp) from this data
#include "character.h"
player::player()
{
cout << "\t\t\nPlease enter your name: \n\t\t";
cin >> name;
};
int main()
{
//some code
return 0;
}
But I keep getting errors
"undefined reference to `character::character()"
Can someone please help me, why am I getting this error and also is this approach the best practice for the layout of this design?
A: You need to define the constructor(s) for character in your code file:
character::character():
hp(10),
name("default")
{
}
character::character (std::string name): hp(10) [...]
character::character (int hp): name("Default") [...]
character::character (std::string name, int hp) [...]
This makes sure that all your instance variables are defined.
Since you define a destructor, you must obey the rule of three and define a copy constructor and assignment operator as well.
On a side note, you should use a convention to name your class/instance variables: myName, _name, or name_ are quiet common. Using cppcheck may save you some time/hassle as well.
A: What you need to do is create the definition for your default constructors character::character() and player::player(). While default constructors take no arguments, you still need need to provide a definition for them. If they do absolutely nothing, not even member initialization, then you could simply do what you did for your destructors: character() { } and player() { }.
However, you could (and you probably should), initialize the data members in the constructors, using initializer list syntax. For example, for the character class, it would be:
character() : hp(100), name("Mario") { }
Note that you don't need the semicolon after }. Or you could NOT use initializer lists and have:
character() {
hp = 100;
name = "Mario";
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612561",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Write conflict in very simple Access form with subform This one is stumping me because what I'm doing seems so straightforward.
I have an unbound form (frmAdmin) with a listbox (lstUsers) and a subform that also contains a listbox (lstUsergroups).
lstUsers is unbound and shows a list of usernames (row source is the users table left joined with the contacts table on users.fk__ContactID = contacts.pk__ContactID so I can get the names to display)
The subform is bound to the users table and has the filter pk__UserID = Forms!frmAdmin!lstUsers
lstUsergroups shows a list of usergroups as is bound to the fk__Usergroup field in the users table.
The only VBA involved is a click event on lstUsers that requerys the subform.
When I select a user from lstUsers the subform listbox shows the user's usergroup selected, but if I select a different usergroup and then select a different user or close the form I get the write conflict "This record has been changed by another user" etc.
This seems so simple! What could cause a write conflict? There are no other forms open, the users table is a linked SQL Server table but there are no triggers anything that should be writing to it. It's just a form, a subform, and a click event.
A: Make sure the SQL table has a primary key, then update your linked table. If that doesn't seem to resolve it, try adding a timestamp field to the SQL table that's getting the write conflict, then update the linked table again. This happens to me all the time. Access seems finicky about what it actually uses as unique identifiers sometimes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612562",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: C# Select list items at the same index as another list A little stuck once again.
I have been trying to find a way to code the following (all of my attempts failed unfortunately...)
I have two arrays/lists whatever you want to call them.
Both have different items in them, although they will always have the same number of items.
For the sake of my question, these lists have 3 items each.
How would one go about coding it so that if I take item 2 from list 1, item 2 from list 2 would also be transported.
So.. effectively.. If I was to move item 2 from list 1 to list 3, I would like item 2 from list 2 to go to list 4.
If that makes sense...
Do not have any code to show off as I have not found a way to code this yet..
Any kind souls that would be able to educate me in this matter?
Thank you.
EDIT
The actual thing I am trying to do is this:
I have a list of real-time generated hashes, a list of locations for files those hashes came from, and a list of healthy hashes. I am comparing both hash lists to find differences, then I am listing the differences. (all of which I have already coded)
THe last thing i want to do is by using the listed hashes that do not match the healthy ones, return their directory (which is already in the list mentioned above)
string path = Application.ExecutablePath; // <------- Get full file path from this EXE
string root = Path.GetDirectoryName(path); // <------- Get just the directory from above file path
IEnumerable<string> list0 = File.ReadLines(root + "/healthy.txt");
List<string> list1 = new List<string>();
IEnumerable<string> list2 = Directory.EnumerateFiles(root, "*.lol", SearchOption.AllDirectories);
List<string> list3 = new List<string>();
foreach (string forone in list0)
{
list1.Add(forone.ToString());
}
foreach (string obj in list2)
{
listBox4.Items.Add(obj.ToString());
list3.Add(GetMD5HashFromFile(obj.ToString()));
}
foreach (string obj2 in list3)
{
listBox2.Items.Add(obj2.ToString());
}
foreach (string hea in list1)
{
listBox1.Items.Add(hea.ToString());
}
IList<string> difference = list3.Except(list1).ToList();
foreach (string something in difference)
{
listBox3.Items.Add(something.ToString());
}
Please note that listboxes are only used for troubleshooting and so I can see what is in the arrays.
A: Create a wrapper class that holds both items and make a single list of that. You can easily convert your combined list into a list of the objects you are interested in if you need to:
List<Item1> item1s = combinedList.ConvertAll(pair => pair.Item1);
A: Generic:
public class SynchronizedListsWrapper<T>
{
private readonly List<T> _first;
private readonly List<T> _second;
public SynchronizedListsWrapper(List<T> first, List<T> second)
{
_first = first;
_second = second;
}
public void Add(T item)
{
first.Add(item);
second.Add(item);
}
public void Remove(T item)
{
first.Remove(item);
second.Remove(item);
}
}
Or without generics:
public class SynchronizedListsWrapper
{
private readonly ArrayList _first;
private readonly ArrayList _second;
public SynchronizedListsWrapper(ArrayList first, ArrayList second)
{
_first = first;
_second = second;
}
public void Add(object item)
{
first.Add(item);
second.Add(item);
}
public void Remove(object item)
{
first.Remove(item);
second.Remove(item);
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612565",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to make Visual Studio close running process before performing build? I'm building WinForms application using Visual Studio 2010. Every time I make a change in the code I have to run the application and check how it works. The problem is that I do this frequently and once I forget to close the previous instance of the application the compiler generates error "The process cannot access the file bin\Debug....". Is it possible to make Visual Studio close the running instance before performing build?
A: In addition to Morten's answer:
Use taskkill and then ignore errors.
taskkill /F /IM "$(TargetFileName)"
exit 0
A: An idea: Make a pre-build step for the executable project that uses Taskkill to kill the process. Read more about Taskkill here: http://technet.microsoft.com/en-us/library/bb491009.aspx
A: Following code from another stackexchange answer worked for me.
wmic process where name='chromedriver.exe' delete
A: Add the following to the projects Pre-build event (based on the accepted answer):
taskkill /f /fi "imagename eq $(TargetFileName)"
The command as used in the other answer may result in an error in cases where the process is not running.
This variation uses a filter (/fi) which does not 'fail' even if there is 0 matches.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612566",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: Error JSF 2.1: java.io.FileNotFoundException:*/*.xhtml Not Found in ExternalContext I have an a error in Jboss 7.0.2 "Arc", spring webflow 2.3.0.RELEASE with richfaces 4.0.0.Final(Myfaces 2.1.1):
12:34:19,729 SEVERE [org.apache.myfaces.renderkit.ErrorPageWriter] (http--127.0.0.1-8080-2) An exception occurred: javax.faces.FacesException: java.io.FileNotFoundException: /sections/login/header.xhtml Not Found in ExternalContext as a Resource.
when i run my login.xhtml page:
<ui:composition template="/WEB-INF/flows/template/default.xhtml"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:rich="http://richfaces.org/rich">
<ui:define name="windowTitle">
#{msgs.loginTitle}
</ui:define>
<ui:define name="heading">
<ui:include src="/sections/login/header.xhtml"/>
</ui:define>
<ui:define name="sidebarLeft">
<ui:include src="/sections/login/sidebarLeft.xhtml"/>
</ui:define>
<ui:define name="content">
<h:form>
<h:panelGrid columns="2">
#{msgs.namePrompt}
<h:inputText id="name" value="#{user.name}"/>
#{msgs.passwordPrompt}
<h:inputSecret id="password" value="#{user.password}"/>
</h:panelGrid>
<p>
<h:commandButton value="#{msgs.loginButtonText}"
action="planetarium"/>
</p>
</h:form>
</ui:define>
The code of header.xhtml is:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
<!-- <head><title>IGNORED</title></head> -->
<body>
<ui:composition>
<div class="header">
#{msgs.loginHeading}
</div>
</ui:composition>
</body>
</html>
the structure file is like this:
WEB-INF/flows/inscripcion
inscripcion-flow.xhtml
inscripcion.xhtml
login.xhtml
WEB-INF/flows/sections/login
header.xhtml
sidebarLeft.xhtml
WEB-INF/flows/template
template.xhtml
Why is this error?, I attached my Jboss Prompt
https://rapidshare.com/files/817066879/log12.zip
Thnks.
A: You seem to have placed it in WEB-INF/flows/sections/login/header.xhtml. Fix the src accordingly to match this.
<ui:include src="/WEB-INF/flows/sections/login/header.xhtml"/>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612567",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to add mouse listener to a component in a custom JTable header cell renderer I implemented a custom header cell renderer which is used by a JTable instance.
private final class TableHeaderCellRenderer extends DefaultTableCellRenderer {
private static final long serialVersionUID = 6288512805541476242L;
public TableHeaderCellRenderer() {
setHorizontalAlignment(CENTER);
setHorizontalTextPosition(LEFT);
setVerticalAlignment(BOTTOM);
setOpaque(false);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
setIcon(getIcon(table, column));
JPanel headerContainer = new JPanel();
headerContainer.setLayout(new BorderLayout());
headerContainer.setBorder(UIManager.getBorder("TableHeader.cellBorder"));
Box buttonBox = Box.createHorizontalBox();
JButton pinButton = new JButton();
pinButton.setOpaque(false);
pinButton.setMaximumSize(new Dimension(16, 16));
pinButton.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
JOptionPane.showMessageDialog(null, "ASD");
}
});
buttonBox.add(pinButton);
headerContainer.add(this, BorderLayout.CENTER);
headerContainer.add(buttonBox, BorderLayout.EAST);
return headerContainer;
}
}
When I click "Pin Button" the message dialog doesn't appear instead only sorting occurs. Note that the respective JTable instance uses setAutoCreateRowSorter(true);. Can this be the cause why the button doesn't receive any mousePressed events?
A:
Note that the respective JTable instance uses setAutoCreateRowSorter(true). Can this be the cause why the button doesn't receive any mousePressed events?
That is not the problem.
A renderer is NOT a real component. It is only a painting of a component so it can not receive events.
If you want to handle mouseEvents then you need to add the MouseListener to the table header. You then need to convert the mouse point to the appropriate table header column and then do your processing.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612569",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: UILabel to display Emoji emotions rather than their unicode values \ueXXXX I'm retrieving values from a server in XML format, the server sends the following string:
"This is a nice string with Emoji \ue056\ue056\ue056\ue057\ue057\ue056\ue056"
I have been struggling to make my UILabel display the emoji icons rather the following
\ue056\ue056\ue056\ue057\ue057\ue056\ue056
I have tried
[chatText setText:[chatString stringByReplacingOccurrencesOfString:@"\\\\u" withString:@"\\u"]];
Not much luck. Being desperate I have done the following:
[chatText setText:[[chatString cStringUsingEncoding:NSNonLossyASCIIStringEncoding] stringByReplacingOccurrencesOfString:@"\\\\u" withString:@"\\u"]];
Note: Assigning the following string does the trick:
[chatText setText:@"\ue056\ue056\ue056\ue057\ue057\ue056\ue056"];
A: It looks like you would need to go through each of the characters, and use stringWithFormat:@"%C" for each of the emoji characters:
// Loop through string by characters, and then do something like:
// NSString *emoji = [NSString stringWithFormat:@"%C", 16-bit Unicode character (unichar) here];
NSString *emoji = [NSString stringWithFormat:@"%C", 0xe415];
chatText.text = [chatText.text stringByAppendingString:emoji];
Check out the String Format Specifiers
A: I have built a stringHandler class that contains the following function to overcome this issue, which pretty much solved my problem:
+ (NSString *) mapEmojiFromServer:(NSString *) inString
{
inString = [inString stringByReplacingOccurrencesOfString:@"\\" withString:@""];
inString = [inString stringByReplacingOccurrencesOfString:[@"ue001" lowercaseString] withString:@"\ue001"];
.
.
.
return inString;
}
I haven't noticed a performance issue other than the IDE getting crazy when navigating and scrolling through the page that contains this 2000 lines function
Thanks a lot for your help.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7612570",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.