text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Strings java null character with nextLine() System.out.println("-----------------------------------------------------------");
System.out.println("Please select a task");
System.out.println("1: List employees with details");
System.out.println("2: List of clients in state");
System.out.println("3: List portfolio of client");
System.out.println("4: Release an employee");
System.out.println("5 Display stocks available for purchase/selling");
System.out.println("6: Display client details");
System.out.println("7: Buy Stock for client ");
System.out.println("0: Exit program");
System.out.println("-----------------------------------------------------------" + "\n" + "\n");
System.out.print("Input:");
Scanner scan = new Scanner(System.in);
input = scan.nextInt();
if (input == 1)
{
System.out.println("length of array list: " + employeeList.size());
int index = 0;
while ( index < employeeList.size() )
{
System.out.println(employeeList.get(index));
index++;
}
}
else if (input == 2)
{
String state_choice;
System.out.println("Please enter the abbrivation for the state:");
state_choice = scan.nextLine();
This is a portion from my current code I'm having issues at [else if (input == 2)] when I try to run it doesn't let me input and just ignores it actually. I think its because of the "\n" from the previous entry. Is there a way to remove that "\n" or extra character without putting another scan.nextLine() before my entry? Didn't really see anything in java docs..
A: Just add scan.nextLine(); after input = scan.nextInt();. The problem is within input = scan.nextInt();, it only reads integer number, so you need scan.nextLine(); to discard the new line \n generated by pressing Enter.
A: What Eng.Fouad said, only scanner.nextLine() not input.nextLine() ;)
Here's what I got running just fine:
import java.util.ArrayList;
import java.util.Scanner;
public class Testing {
private static final ArrayList<String> employeeList = new ArrayList<String>();
public static void main(String[] args) {
System.out.println("---------------------------------------------------------");
System.out.println("Please select a task");
System.out.println("1: List employees with details");
System.out.println("2: List of clients in state");
System.out.println("3: List portfolio of client");
System.out.println("4: Release an employee");
System.out.println("5: Display stocks available for purchase/selling");
System.out.println("6: Display client details");
System.out.println("7: Buy Stock for client ");
System.out.println("0: Exit program");
System.out.println("---------------------------------------------------------");
System.out.println("\n\n");
System.out.print("Input: ");
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
scan.nextLine();
if (input == 1) {
System.out.println("length of array list: " + employeeList.size());
int index = 0;
while (index < employeeList.size()) {
System.out.println(employeeList.get(index));
index++;
}
} else if (input == 2) {
System.out.print("Please enter the abbrivation for the state: ");
String state_choice = scan.nextLine();
System.out.println("State: " + state_choice);
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572367",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to create a jumplist clone to use it as ListView? Is there an easy possibility to create a Windows 7 Jumplist clone to use it as a ListView-Control? Especially the design should be 1:1 to the original.
important: I'm working with WPF if that helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572371",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Javascript, looping a set of instructions (set timeouts) I want to loop an animation which is essentially changing the background-position ever 150 milliseconds. It does not fade or anything, it just has to happen over and over again. But I can not seem to find a solution that loops these set of instructions.
setTimeout( function() {
$('div.arrow').css('backgroundPosition', '0 -47px');
}, 150 );
setTimeout( function() {
$('div.arrow').css('backgroundPosition', '0 -94px');
}, 250 );
setTimeout( function() {
$('div.arrow').css('backgroundPosition', '0 -141px');
}, 350 );
setTimeout( function() {
$('div.arrow').css('backgroundPosition', '0 -188px');
}, 450 );
setTimeout( function() {
$('div.arrow').css('backgroundPosition', '0 -235px');
}, 550 );
A: Use setInterval instead of setTimeout.
Also use a global variable to see where the background image is, rather than setting lots of timeouts...
So you'll end up with something like this:
var currPos = 0;
setInterval(function(){
currPos = currPos-47;
if(currPos < -235){
currPos = 0;
}
$('div.arrow').css('backgroundPosition','0 '+currPos+'px');
}, 150);
See example here: http://jsfiddle.net/aUBNw/
A: var div = $('div.arrow');
function tim(){
setTimeout( function() {
div.css('backgroundPosition', '0 -47px');
}, 150 );
setTimeout( function() {
div.css('backgroundPosition', '0 -94px');
}, 250 );
setTimeout( function() {
div.css('backgroundPosition', '0 -141px');
}, 350 );
setTimeout( function() {
div.css('backgroundPosition', '0 -188px');
}, 450 );
setTimeout( function() {
div.css('backgroundPosition', '0 -235px');
}, 550 );
setTimeout( function() {
tim();
}, 550 );
}
tim();
will simply call itself after it's completed
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572377",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Eclipse projects in VCS What Eclipse specific files should I add to the VCS (Subversion, GIT, etc...) when sharing an Eclipse project?
What I have here:
.autotools
.cproject
.project
.settings/
A: Just stumbled upon this and had the same problem some time ago, so I will try to share my experience.
First it depends on who are the other users of the VCS or better what programs they will use. If they do not use Eclipse these files will only pollute their projects.
If they do use Eclipse the files might be of use to them, but in my latest project I did not include them for the following reasons:
Everyone had another system which meant other paths for the includes and so on. Concluding from this I surveyed the contents of these files to see if they should be used:
*
*.cproject: The includes are listed here, so you will have different files in the list on each platform. -> leave out
*.project: Found some environment dependent paths here too. Maybe it also has a problem when there are different plugins installed. -> leave out
*.settings: It might make sense sometimes to share the settings but usually it is each developers own decision. -> leave out
*.autotools: I did not use this, so I cannot say anything about it.
Summary
It seems best to leave those files out of the repository.
For Eclipse this introduces the problem of creating a new project when importing from the VCS. In this case you should give advice on how to configure the project to set it up correctly.
When you put the project files into the VCS those who do not use Eclipse will probably have less problems than those who do, because the files are simply ignored at their site while the Eclipse users will have to reconfigure them for their system.
Maybe there is some better way to share those projects but I did not find one yet.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572378",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Why are appengine database keys sorted differently than strings I found this interesting, and am curious to know why db keys are ordered differently than strings ..
If you test the following example in the Python development environment (true for server as well), you will see the following (somewhat unexpected) behaviour
str1 = 'agpyb21hbmNlYXBwchILEglVc2VyTW9kZWwY4-agBgw'
str2 = 'agpyb21hbmNlYXBwchILEglVc2VyTW9kZWwYkoWBBQw'
Result: str < str2 is TRUE
However, if we do the following
key1 = db.Key(str1)
key2 = db.Key(str2)
Result: key1 < key2 is FALSE
A: They use a different collation in extraction operator. I guess the db.Key() has strong probabilities to bind to DB properties.
So the < operator 'sees' different data, the first being (say) Ut8 source based, the second some weird db collation based, where the dash has specific meaning (unknown until we can get the specification). I've experienced some pain in the past feeding massive data across DB interfaces. But internationalization it's inherently complex.
A: What you're comparing are string encoded keys, which have been passed through base64 in order to be safe for output as text. Base64 does not preserve string ordering. If you decode them using base64.urlsafe_b64decode, they will compare in the order you expect.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572386",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Javascript Captcha I found this great little code online but it doesn't seem to be comparing the two strings after removing the spaces correctly? I know some js but whatever wrong here is beyond my understanding. Hopefully someone will know the answer to this.
Note: it seems to also validate based on the number of chs and not what those chs are, the numbers dont seem to need to match up, just so long as there's enough of them.
Org code was done by "mama21mama" from "http://osticket.com/forums/showthread.php?t=6489&highlight=captcha"
I have made some small personal modifications to try to fix it, below is my vr.
<script type="text/javascript">
function DrawCaptcha() {
var a = Math.ceil(Math.random() * 9)+ '';
var b = Math.ceil(Math.random() * 9)+ '';
var c = Math.ceil(Math.random() * 9)+ '';
var d = Math.ceil(Math.random() * 9)+ '';
var e = Math.ceil(Math.random() * 9)+ '';
var f = Math.ceil(Math.random() * 9)+ '';
var g = '10';
var code = a + ' ' + b + ' ' + ' ' + c + ' ' + d + ' ' + e + ' '+ f + ' ' + g;
document.getElementById("txtCaptcha").value = code
}
function ValidCaptcha() { // valida los numeros ingresados
var str1 = removeSpaces(document.getElementById('txtCaptcha').value);
var str2 = removeSpaces(document.getElementById('txtInput').value);
if (str1 == str2){
return true; }
else {
return false; }
}
function removeSpaces(string) {
return string.split(' ').join('');
}
</script>
A: Do not use this code. It does nothing to increase security.
In order for a captcha to be effective, the answer to the captcha must be a secret known only by the server. A client-side script cannot implement a captcha because the client code would necessarily know the answer.
This script does nothing to secure your sever against a malicious attack. All the JavaScript in the world doesn't prevent an attacker from writing a script that POSTs a fake form to your server. Since the captcha validation happens on the client, your sever is clueless as to whether the request is legitimately generated by a human.
This captcha also misses the point by rendering the challenge as plain text. Any script could read the challenge from the DOM and provide the correct answer.
This script is useless if a browser has JavaScript disabled. This script is useless if I type ValidCaptcha = function() { return true; } in the console.
Instead of trying to roll your own, use reCAPTCHA. It is free, has an easy API, and has built-in accomodations for blind users.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572395",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Silverlight not initializing controls I'm trying to add some values in several controls in my silverlight page (textboxes, datepickers...) but it seems like some of them are never initialize (until user sets any value manually).
I've tried it by been suscribed to the "Loaded" event in the page's code behind but it doesn't work... (I thought it was because of the order it was being initialized).
I've read that this is one of silverlight limitations but maybe there is any workaround...
Any idea?? Thanks in advance.
Some code to illustrate it, first the xaml controls:
<sdk:Label Target="{Binding ElementName=txtNumeroColegiado}" Content="Nº Colegiado" HorizontalAlignment="Right" Margin="5,0" Name="label2" VerticalAlignment="Center" />
<TextBox Margin="5,0" Name="txtNumeroColegiado" TabIndex="27" Text="{Binding Medico.colegiado, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True, ValidatesOnDataErrors=True}" VerticalAlignment="Center" Grid.Column="1" />
<sdk:Label Target="{Binding ElementName=txtNombreComercial}" Content="Nombre Comercial" HorizontalAlignment="Left" Margin="5,0" Name="label4" VerticalAlignment="Center" Grid.Column="2" />
<TextBox Margin="5,0" Name="txtNombreComercial" TabIndex="27" Text="{Binding Medico.nombrecomercial, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True, ValidatesOnDataErrors=True}" VerticalAlignment="Center" Grid.Column="3" />
And this is my conde behind:
public DatosMedico()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(DatosMedico_Loaded);
}
void DatosMedico_Loaded(object sender, RoutedEventArgs e)
{
this.txtNombreComercial.GetBindingExpression(TextBox.TextProperty).UpdateSource();
this.txtNumeroColegiado.GetBindingExpression(TextBox.TextProperty).UpdateSource();
}
When it tries to run "updateSource", these textboxes are null (but they are working perfectly in the page...). Apparently they are initialized when user inputs some text...
A: At guess, the DataContext is either not being set or not set to the object you are expecting it to be set to. Check the output window in VS when debugging, do you see any complaints about binding?
A: It was solutioned by deleting a "ContentPresenter" that had many controls inside.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572399",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Subsetting data frame using variable with same name as column I have a data frame and I'm trying to run a subset on it. In my data frame, I have a column called "start" and I'm trying to do this:
sub <- subset(data,data$start==14)
and I correctly get a subset of all the rows where start=14.
But, when I do this:
for(start in seq(1,20,by=1)) {
sub <- subset(data,data$start==start)
print(sub)
}
it does not correctly find the subsets. It just prints the entire data frame.
Why is this and how do I fix it?
A: Fixing it is easy. Just rename either your for loop counter or your data frame column to something other than start.
The reason it happens is because subset is trying to evaluate the expression data$start == start inside the data frame data. So it sees the column start and stops there, never seeing the other variable start you defined in the for loop.
Perhaps a better insight into why R gets confused here is to note that when using subset you don't in general need to refer to variables using data$. So imagine telling R:
subset(data,start == start)
R is just going to evaluate both of those start's inside data and get a vector of all TRUE's back.
A: You can also specify the environment you're working with:
x<-data.frame(
start=sample(3,20,replace=TRUE),
someValue=runif(20))
env<-environment()
start<-3
cat("\nDefaut scope:")
print(subset(x,start==start)) # all entries, as start==start is evaluated to TRUE
cat("\nSpecific environment:")
print(subset(x,start==get('start',env))) # second start is replaced by its value in former environment. Equivalent to subset(x,start==3)
A: Another approach is to use bracket subsetting rather than the subset function.
for(start in seq(1,20,by=1)) {
sub <- data[data$start==start,]
print(sub)
}
subset has non-standard evaluation rules, which is leading to the scoping problem you are seeing (to which start are you referring?). If there are (or may be) NA's in data$start, you probably need
sub <- data[!is.na(data$start) & data$start==start,]
Note this warning from the subset help page:
This is a convenience function intended for use interactively. For programming it is better to use the standard subsetting functions like [, and in particular the non-standard evaluation of argument subset can have unanticipated consequences.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572400",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: jquery ui slider with rounded corners - older borwser issues (.corner) I'm using this library to apply corners to a jquery ui slider element - https://github.com/malsup/corner
You can see a working example here - http://jsfiddle.net/FtkRQ/3/
I've applied the corners using css3 for modern browsers and am using the aforementioned jquery plugin for older browsers.
If you look at the slider's handles in ie7 you'll see I'm having an issue with the background colour.
Any idea why?
A: The plugin sets the border to the color of the first parent element that has it set, here is the plugin code,
function gpc(node) {
while(node) {
var v = $.css(node,'backgroundColor'), rgb;
if (v && v != 'transparent' && v != 'rgba(0, 0, 0, 0)') {
if (v.indexOf('rgb') >= 0) {
rgb = v.match(/\d+/g);
return '#'+ hex2(rgb[0]) + hex2(rgb[1]) + hex2(rgb[2]);
}
return v;
}
if (node.nodeName.toLowerCase() == 'html')
break;
node = node.parentNode; // keep walking if transparent
}
return '#ffffff';
};
The plugin just creates a bunch of 1px high spans and varies the border width and sets a color. There doesn't seem to be a way to use transparent borders.
So it is not possible to use a transparent background for the cornering, sorry.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572405",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Receiving function name in C I have a program like this,
void test(char* a)
{
printf("%s",a); // Trying to print the function name "add" here
return;
}
int add(int,int)
{
test(__FUNCTION__); // I need the function name add to be passed to the test function
...................
....................
}
But while building I am getting the error in a C compiler(gcc flavour) like this,
passing argument 1 of 'test' discards qualifiers from pointer target type
Please have a look at this,
/R
A: From here:
The identifier __func__ is implicitly declared by the translator as if, immediately following the opening brace of each function definition, the declaration
static const char __func__[] = "function-name";
appeared, where function-name is the name of the lexically-enclosing function. This name is the unadorned name of the function.
__FUNCTION__ is another name for __func__.
So, you're trying to pass a const char * to a char *, discarding the const qualifier. Since in your test function you aren't modifying the passed string, change its parameter type to const char *, promising to the caller that you aren't modifying its string.
By the way, to get const correctness right you should always remember to declare pointers as const if they are "input-only" parameters.
A: Change the signature of test to
void test(const char* a)
GCC is complaining that you're converting a pointer to a constant string literal to a mutable pointer by calling test.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572407",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Does Python have C#/Java-style interfaces? I worked for a few months as a C# programmer, and got used to the idea of generics/templates interfaces, which I could pass to a library without caring how the object was created.
I'm about to start on a relatively large project, probably in python (I've written a lot of python before, but mostly my own code for data analysis etc), and was wondering if there exists a similar concept in this language? I've tried googling for it and not come up with much.
If the answer's no, that's fine, but in that case what do people generally do instead?
A: python is dynamically typed so (in most cases) there is no need for generics/templates.
A: My understanding of interfaces is from Java, so hopefully that's close enough to what you mean...
There is no syntactic way to assert that a particular object has a set of methods and fields because Python uses dynamic typing/duck typing. If you want to check whether an object has a certain method or field, you can:
*
*Dig into it with reflection (this is the most work)
*Check for what you want in its __dict__ (a dictionary of all of an
object's members). MyObj.__dict__.hasKey(o) is what you want, I think. (pretty easy)
*Just use the object and trust that you, your fellow developers, or your users have given you a proper object. (Maximum easy, but dangerous)
*Or, do the above and wrap it in a try/except block. (This will be familiar to Java programmers)
Designing a complex set of classes in Python is a very different experience from doing the same in C-like languages, so be prepared to do things you may be uncomfortable with (like option 3, above). Good luck!
A: If you are talking strictly about C#/Java-like interface, then the answer is simple. They are concepts that belong to statically typed languages and do not really apply to dynamic language such as Python.
The usual pythonic approach is to trust the objects you get and assume they have the necessary traits you need. Should they do not, you might expect runtime errors that can be handled or left for the caller. This matches the general dynamic nature of the language: if something goes wrong, you can expect it to surface at runtime.
Interfaces from Java or C#, on the other hand, are means for checking necessary preconditions (i.e. objects having certain methods) during compilation. This (arguably) trades off some of the runtime flexibility for increased safety of compile-time checks.
Note that it doesn't mean that any concept of interface has no place in dynamically typed language. In fact, Python has a slightly blurred notion of "meta-types" - such as iterables - that are often checked against, e.g. by verifying the presence of particular method(s):
def process_sequence(seq):
if not hasattr(seq, '__iter__'):
seq = [seq] # turn single element into iterable
for elem in seq:
process_element(elem)
This is conceptually similar to non-manifest interfaces from Go language. If you want to have your own iterable, you just implement the __iter__ method - without explicitly stating that you will implement it (as in Java, where you would inherit from List class). Should anyone wants to check whether your object is indeed an iterable, they can verify whether the "contract" - i.e. having __iter__ method - is indeed fulfilled. This is what andronikus described in their answer.
As a shameless plug, I can point out to the pyduck library that I'm implementing. It aims to simplify (and maybe even standarize) verification of such "contracts" (via reflection) and make it slightly more reliable.
A: zope.interface
But most people don't use it.
A:
If the answer's no, that's fine, but in that case what do people generally do instead?
Duck Typing.
What's important is to approach Python by dropping the technical baggage of C#.
Learn Python as a new language. Don't try to map concepts between Python and C#. That way lies madness.
"INTERFACES, not generics, or templates"
Doesn't matter. All that static type declaration technology isn't necessary. For that matter type casting in order to break the rules isn't necessary either.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572410",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Beginning and end of the string in Emacs regexps What is the characters that indicate the beginning and the end of the string with newlines in it? I'm writing a trim function:
(defun trim (str)
(if (string-match "^[[:space:]]*\\(.+?\\)[[:space:]]*$" str)
(match-string 1 str)
str))
But with a string like "first/nnext" (got from shell-command-to-string) it returns only the "first". Reference manual says:
When matching a string instead of a buffer, ‘^’ matches at the beginning of the
string or after a newline character.
\\' and the left one are for beginning/end of a buffer, so it simply returns nothing from a string. Therefore, how to indicate the 'absolute' beginning of a string, if possible?
A: It's \\` for beginning of buffer or string. And \\' for end. See manual
However, I think the root of your confustion isn't the anchor. The [:space:] char class matches different characters based on the current syntax table. To reliably match a non-printing or printing character use [:graph:]. See char class
Also . won't match newlines.
E.g.
(let ((str " \n a\nbc \n "))
(string-match "\\`[^[:graph:]]*\\(\\(?:.\\|\n\\)+?\\)[^[:graph:]]*\\'" str)
(match-string 1 str))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572411",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Sitecore SIP active directory issues after authentication I've setup the active directory LDAP module in Sitecore's Intranet Portal 3.2 product and have had limited success. I receive the error "Unable to cast object of type 'System.Configuration.SettingsPropertyValue' to type 'LightLDAP.ADSettingsPropertyValue'." when I click the "Ok" button on user properties, applying a user template with custom properties, when I try to view the workbox from the front end editor, and when I try to access any item in the content editor.
I am able to successfully sign-on through the LDAP module, manage CMS role access, security, etc. I am automatically logged in on the front-end, and can type in my domain\username\pwd and successfully authenticate though AD.
Any help would be much appreciated
Stack Trace
[InvalidCastException: Unable to cast object of type 'System.Configuration.SettingsPropertyValue' to type 'LightLDAP.ADSettingsPropertyValue'.]
LightLDAP.SitecoreADProfileProvider.SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection collection) +388
Sitecore.Security.SwitchingProfileProvider.SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection collection) +294
System.Configuration.SettingsBase.SaveCore() +484
System.Configuration.SettingsBase.Save() +72
System.Web.Profile.ProfileBase.SaveWithAssert() +43
System.Web.Profile.ProfileBase.Save() +159
Sitecore.Security.UserProfile.Save() +32
Sitecore.Web.UI.HtmlControls.Registry.SetValue(String key, String value) +202
Sitecore.Web.UI.HtmlControls.Listview.DoSetView(String name) +163
Sitecore.Shell.Applications.ContentEditor.FileDropArea.OnLoad(EventArgs e) +693
System.Web.UI.Control.LoadRecursive() +66
System.Web.UI.Control.LoadRecursive() +191
System.Web.UI.Control.AddedControl(Control control, Int32 index) +350
Sitecore.Web.UI.Sheer.ClientPage.AddControl(Control parent, Control control, String placeholder) +240
Sitecore.Shell.Applications.ContentEditor.EditorFormatter.AddEditorControl(Control parent, Control editor, Field field, Boolean hasRibbon, Boolean readOnly, String value) +249
Sitecore.Shell.Applications.ContentEditor.EditorFormatter.RenderField(Control parent, Field field, Item fieldType, Boolean readOnly, String value) +1097
Sitecore.Shell.Applications.ContentEditor.EditorFormatter.RenderField(Control parent, Field field, Item fieldType, Boolean readOnly) +204
Sitecore.Shell.Applications.ContentEditor.Pipelines.RenderContentEditor.RenderSkinedContentEditor.RenderInput(Field field) +131
Sitecore.Shell.Applications.ContentEditor.Pipelines.RenderContentEditor.RenderSkinedContentEditor.RenderElement(XmlNode element) +603
Sitecore.Shell.Applications.ContentEditor.Pipelines.RenderContentEditor.RenderSkinedContentEditor.RenderChildElements(XmlNode element) +141
Sitecore.Shell.Applications.ContentEditor.Pipelines.RenderContentEditor.RenderSkinedContentEditor.RenderMarker(XmlNode element) +175
Sitecore.Shell.Applications.ContentEditor.Pipelines.RenderContentEditor.RenderSkinedContentEditor.RenderElement(XmlNode element) +674
Sitecore.Shell.Applications.ContentEditor.Pipelines.RenderContentEditor.RenderSkinedContentEditor.RenderChildElements(XmlNode element) +141
Sitecore.Shell.Applications.ContentEditor.Pipelines.RenderContentEditor.RenderSkinedContentEditor.RenderSectionPanel(XmlNode element) +270
Sitecore.Shell.Applications.ContentEditor.Pipelines.RenderContentEditor.RenderSkinedContentEditor.RenderElement(XmlNode element) +635
Sitecore.Shell.Applications.ContentEditor.Pipelines.RenderContentEditor.RenderSkinedContentEditor.AddText(XmlNode element) +494
Sitecore.Shell.Applications.ContentEditor.Pipelines.RenderContentEditor.RenderSkinedContentEditor.RenderElement(XmlNode element) +717
Sitecore.Shell.Applications.ContentEditor.Pipelines.RenderContentEditor.RenderSkinedContentEditor.AddText(XmlNode element) +494
Sitecore.Shell.Applications.ContentEditor.Pipelines.RenderContentEditor.RenderSkinedContentEditor.RenderElement(XmlNode element) +717
Sitecore.Shell.Applications.ContentEditor.Pipelines.RenderContentEditor.RenderSkinedContentEditor.Render(XmlDocument skin) +125
Sitecore.Shell.Applications.ContentEditor.Pipelines.RenderContentEditor.RenderSkinedContentEditor.Process(RenderContentEditorArgs args) +353
(Object , Object[] ) +79
Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args) +240
Sitecore.Shell.Applications.ContentManager.Editor.Render(RenderContentEditorArgs args, Control parent) +538
Sitecore.Shell.Applications.ContentManager.ContentEditorForm.RenderEditor(Item item, Item root, Control parent, Boolean showEditor) +232
Sitecore.Shell.Applications.ContentManager.ContentEditorForm.UpdateEditor(Item folder, Item root, Boolean showEditor) +345
Sitecore.Shell.Applications.ContentManager.ContentEditorForm.Update() +344
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) +0
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks) +1255
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +38
Sitecore.Reflection.ReflectionUtil.InvokeMethod(MethodInfo method, Object[] parameters, Object obj) +91
Sitecore.Reflection.ReflectionUtil.CallMethod(Object obj, String methodName, Boolean includeNonPublic, Boolean includeInherited, Object[] parameters) +75
Sitecore.Shell.Applications.ContentManager.ContentEditorPage.OnPreRender(EventArgs e) +120
System.Web.UI.Control.PreRenderRecursiveInternal() +108
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3410
A: I did not solve the actual problem, but did come up with a work around. It appears the AD sitecore module in some sense requires write access to AD even though I had disabled almost all parts of the module. I'm not sure why there is no configuration option for a read-only mode.
Regardless, I created some code that finds the user in AD; if found it creates a virtual user, creates a user profile if needed, and updates that profile with the most current info from AD each time the user authenticates with the page.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572414",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to verify Restful Client certificate authentication working with WCF? I have set up Restful webservice in WCF with client authentication using certificate authentication. I am also using SSL (on IIS) for Rest services. When I use fiddler to check whether SSL and certificate authentication are working then I can find only one request of http which is returning SSL encrypted data. But what I am looking for is verifying my certificate authentication is actually working or not.
For testing purpose what I have done so far is
1) removing certificate from client request and getting Forbidden error message from WCF service
2) also sending invalid certificate name and getting again Forbidden error message from WCF service.
Kindly tell me how can I check certificate handshake for authentication using Fiddler or any other tool .
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572418",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to vertical and horizontal align a div inside another div? How do I vertical and horizontal align a div inside another div?
Basically, I'm trying to align <div id="middle2"> inside <div id="middle">.
<div id="middle">
<div id="middle2">
<span id="sp1"class="ui-icon ui-icon-circle-triangle-w" style="float:left;"></span>
<div class="middleContent"></div>
<span id="sp2" class="ui-icon ui-icon-circle-triangle-e" style="float:left;"></span>
</div>
This is the CSS I've tried:
.middleContent
{
background-color: white;
height: 22px;
width: 90%;
border: 1px solid #252C3E;
float: left;
}
#middle2
{
margin: auto;
}
A: http://phrogz.net/css/vertical-align/index.html the article of all articles on this topic.
A: Are you trying to horizontally align the middle2 div inside the middle div? You haven't specified a width for either, so both divs will have the same width and horizontal align effectively won't do anything here.
I think what you want is to horizontally align the middleContent div inside the middle2 div. Since middleContent is set at 90% width, the effect of the horizontal align should be noticeable. To do this, add the following to your CSS code:
#middle2 {
text-align: center;
}
#middleContent {
margin: auto;
}
That should do it. If it's still not working, please update your question with your latest code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572420",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is there any thing you can do if you can't pay for a SSL certificate Hello I am a hobbies developer and I don't make money of my app/website, I only have it to give out my work to FB users for free My APP
I can't afford to pay the £30-40-50 for a SSL certificate and I think it is a little unfair that FB will be forcing you to use SSL.
My question is there any way I can get a free certificate or can FB provide me with one?
Hope there is some way around this as I don't want my app going down.
Kind Regards
Sifonick
A: you can try http://www.startssl.com/. you can get a free certificate for your domain and subdomain for free, and it is accepted by browsers automatically
A: If you search around you will find a few sites that provide free SSL certificates. While these are generally not as widely accepted, it's certainly an alternative option and a step up from generating your own completely unaccepted certificate [which you can also do].
A: I also had the same problem:
Not sure if free cloud service is a solution (a link offering info on this is displayed when you edit your FB app settings. hxxps://developers.facebook.com/blog/post/558/ )
Another CA hxxp://www.affirmtrust.com/free-ssl-certificate-products.html has announced they will be offering free certs for 3 years. Not up and running yet but I believe iminent and you you can pre-register.
No one else has mentioned it so I could be wrong, but I think you will also need an additional IP addres for https. ($30/£20 p.a. ?)
My web host provides a shared server for ssl/https - its free as part of my package - your package may include similar. As you are sharing it you may have to refer to it by a different domain e.g. hxxps://servername.sec.example.com/~accntid/index.html. This means both abs & rel links in your pages will require modification. As the server is shared "document root" is above "~accntid" in the example so server script references to the "doc root" will have to be altered.
HTH
A: I had the same question and came across this site. Seems to get the job done.
Edit: Oh, did I mention it's free and instant?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: JSON returned from remote CFC function is out of order I have a remote CFC that returns a structure. It is called using cfajaxproxy. I want the JSON returned to be in order i.e. first into the structure first into the JSON object. However, the JSON that is returned is in a mixed up order.
Here's the remote function.
<cfcomponent displayname="validation" hint="">
<cffunction name="validateForm" displayname="validateForm" hint="" access="remote" verifyClient="yes" returntype="struct">
<cfargument name="formVals" type="struct" required="yes">
<cfset errors = StructNew()>
<cfif formVals.project neq "project">
<cfset errors["project"] = "Invalid project name." />
</cfif>
<cfif Len(formVals.description) eq 0>
<cfset errors["description"] = "Please enter a description." />
</cfif>
<cfif StructIsEmpty(errors)>
<cfset errors["message"]["type"] = "success">
<cfset errors["message"]["text"] = "Client and server-side validation passed successfully.">
<cfset errors["areErrors"] = false>
<cfelse>
<cfset errors["message"]["type"] = "validation">
<cfset errors["message"]["text"] = "Please fix the errors, and resubmit.">
<cfset errors["areErrors"] = true>
</cfif>
<cfreturn errors />
</cffunction>
</cfcomponent>
This is the cfajaxproxy that I have set at the top of my form page.
<cfajaxproxy cfc="validation" jsclassname="validation">
Here's the call made to the remote function in the onSubmit handler of my form.
var v = new validation();
v.setHTTPMethod("POST");
var errors = v.validateForm(o);
Here's the data (o variable above) that is sent to the function in the post request.
{"formVals":{"project":"","description":""}}
Here's the JSON response returned from the function.
{"message":{"text":"Please fix the errors, and resubmit.","type":"validation"},"description":"Please enter a description.","project":"Invalid project name.","areErrors":true}
I want the response to be in the same order as the structure was created which would look like this.
{"project":"Invalid project name.","description":"Please enter a description.","message":{"text":"Please fix the errors, and resubmit.","type":"validation"},"areErrors":true}
That way when I iterate over the response I can set the focus to the first form field with an error in it.
var focusSet = false;
$.each(errors, function(key, val){
//alert(key + ': ' + val);
if(key != 'message' && key != 'areErrors') {
var fi = $('#' + key).parents('.formItem').filter(':first');
fi.addClass("inError");
fi.find('.err').filter(':first').html(val);
if(!focusSet) {
$('#' + key).focus();
focusSet = true;
}
}
});
Right now this places focus in the second field of the form, description, instead of in the project field.
A: The keys of a ColdFusion struct are never stored in any particular order. However, I found one post that shows how you can create a java LinkedHashMap (which is the java underneath a CF Struct) to store and retrieve keys in a specific order.
<cfset pets = CreateObject("java", "java.util.LinkedHashMap").init()>
<cfscript>
pets["Cat Name"] = "Leo";
pets["Dog Name"] = "Meatball";
pets["Fish Name"] = "Lil Fish";
pets["Bird Name"] = "PePe";
pets["Snake Name"] = "Sizzle";
</cfscript>
<cfloop collection="#pets#" item="key" >
<cfoutput>
#key#: #pets[key]#<br/>
</cfoutput>
</cfloop>
EDIT: Dan's solution (array instead of struct) would probably be much easier.
A: You can't (easily) control the order of the returned JSON structure data unless you manually build the string to return that data. If you must be reliant on an order, then you need to return your errors in an array instead of a structure. You can even return an array of error structures, and CF will maintain the correct array order.
I would return your data like so:
<cfcomponent displayname="validation" hint="">
<cffunction name="validateForm" displayname="validateForm" hint="" access="remote" verifyClient="yes" returntype="struct">
<cfargument name="formVals" type="struct" required="yes">
<cfset var retVal = StructNew() />
<cfset var tempError = StructNew() />
<cfset retVal.errors = ArrayNew(1) />
<cfif formVals.project neq "project">
<cfset tempError["key"] = "project" />
<cfset tempError["message"] = "Invalid project name." />
<cfset ArrayAppend(retVal.errors, Duplicate(tempError)) />
</cfif>
<cfif Len(formVals.description) eq 0>
<cfset tempError["key"] = "description" />
<cfset tempError["message"] = "Please enter a description." />
<cfset ArrayAppend(retVal.errors, Duplicate(tempError)) />
</cfif>
<cfif ArrayIsEmpty(retVal.Errors)>
<cfset retVal["message"]["type"] = "success" />
<cfset retVal["message"]["text"] = "Client and server-side validation passed successfully.">
<cfset retVal["areErrors"] = false>
<cfelse>
<cfset retVal["message"]["type"] = "validation">
<cfset retVal["message"]["text"] = "Please fix the errors, and resubmit.">
<cfset retVal["areErrors"] = true>
</cfif>
<cfreturn retVal />
</cffunction>
</cfcomponent>
This would give you a separate array of errors to loop over, instead of dealing with your base message and areErrors keys at the same time as your errors. Break them out into a separate entity altogether, and you'll have an easier time of looping through them on the client side.
A: struct is not ordered in CFML (it's just a Hashmap-like collection).
If you want ordered struct, use
struct function orderedStructNew()
{
return createObject("java","java.util.LinkedHashMap").init();
}
A: The easiest way if you want something to stay in order use an Array instead of a structure.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572422",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Web design agency using Git for development Background
Up until now we've been using Plastic SCM for version control. Recently we've been looking into Git and I've come up with a basic plan - Available here on Google Docs
My plan is to not allow developers to commit or FTP directly to the server, instead we would push our work to either the live or proof hub which would then in turn cause the live / proof workspaces to pull the changes from their respective hub.
One of the main benefits of this methodology in my eyes is that we can keep up to date with user-uploaded content. For example, when a user uploads an image via our CMS the server will automatically add, commit and push it to the hub the next time a developer pushes some work to the hub. Therefore at any time we can clone either the live or proof repository to a brand new server.
Up until now we've had problems sending work to a client to proof whilst simultaneously uploading new functionality to the live server - the proof work ends up on the live site and all hell breaks lose.
Questions
*
*Do you see any holes in this plan?
*Is Git the right thing to use for this kind of structure?
*Is there a pre-existing plan that we could use instead?
Thanks in advance.
A: Take a look at how Heroku and AppHarbour work. You are definitely on the right track.
A: You should consider using Gerrit - code review engine that also happens to be fully git-compliant git server. Gerrit is written in Java by Google for Android project needs.
You can use review functionality to let content "bake in" in approval queue until it finally gets approved and becomes official (or rejected/reviewed again). At the same time, you can set flexible access permission rules for different people - like somebody can push directly bypassing code review (in which case it becomes just standard git server), or can only submit for review, or approve, or only vote up or down - you set the rules. In case you have multiple git repositories, you can also restrict access to some highly secret repositories from users you do not trust or from 3rd parties.
It is easy to set up, and makes life much easier for admins and for end users as well - ssh key management is automatically provided on Gerrit web interface.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572424",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Mac OSX : python packages failed to build because of gcc issues I am trying to install MySQL-python package with the following error:
cc1: error: unrecognized command line option "-arch"
cc1: error: unrecognized command line option "-Wno-long-double"
error: Setup script exited with error: command 'gcc' failed with exit status 1
I am using Mac OSX version 10.6.8 with gcc
bash-3.2$ gcc --version
gcc (GCC) 4.2.1 (Apple Inc. build 5666) (dot 3)
How can I resolve the this issue?
thanks
A: I restored the gcc that comes with Mac and that removed the first error which is
cc1: error: unrecognized command line option "-arch"
for the second one, I removed the option from /Library/Frameworks/Python.framework/Versions/Current/lib/python2.5/config/Makefile
from BASECFLAGS and added the following to my ~/.bashrc
export C_INCLUDE_PATH=/Developer/SDKs/MacOSX10.5.sdk/usr/include
export LIBRARY_PATH=/Developer/SDKs/MacOSX10.5.sdk/usr/lib
and that removed the error
cc1: error: unrecognized command line option "-Wno-long-double"
A: You need to use the Apple-supplied gcc that comes with the Xcode Developer Tools. There should be a Snow Leopard version of Xcode that either came with your Mac or is on a system restore DVD or a retail copy of Snow Leopard or can be downloaded (after free registration) from the Apple Developer Connection.
A: Solution 1:
May be missing installation package of pyton-dev:
$ yum list | grep python-dev
$ yum -y install python-dev* //need root privileges
After the execution, re-installation.
Solution 2:
If solution 1 does not resolve the problem, might be "gcc" is not installed or are no longer in the PATH
$ whereis gcc //check gcc
$ echo $PATH //Check the gcc whether in the PATH
If you do not install the "gcc", execute the following command
$ yum list | grep gcc
$ sudo yum install -y gcc.x86_64
After the execution, re-install.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572429",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: CSS Background Sizing Polyfill? Is there a polyfill to handle CSS Background Sizing in Safari 4 (iOS) and IE
A: could try this.
http://nooshu.com/jquery-plug-in-scalable-background-image
I'm in the process of looking as well.
A: Allegedly this is a polyfill on GitHUb that enables CSS3 Background Size to work, but I'm still having issues figuring it out myself.
https://github.com/louisremi/background-size-polyfill
Let me know if you get it to work. I'm looking for something similar.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572432",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
}
|
Q: How to implement a concurrent circular ticker (counter) in Java? I want to implement a circular counter in Java.
The counter on each request should increment (atomically) and on reaching an upper limit should roll over to 0.
What would be the best way to implement this and are there any existing implementations?
A: If you're that worried about contention using either CAS or synchronized then you could consider something more sophisticated like the proposed JSR 166e LongAdder (source, javadoc).
That's a straightforward counter with low contention on multithreaded access. You could wrap that to expose (current value mod max value). That is, don't store the wrapped value at all.
A: If you use the modulus operator, you could just increment and return the modulus. Unfortunately the modulus operator is expensive, so I encourage other solutions where performance is important.
public class Count {
private final AtomicLong counter = new AtomicLong();
private static final long MAX_VALUE = 500;
public long getCount() {
return counter.get() % MAX_VALUE;
}
public long incrementAndGet(){
return counter.incrementAndGet() % MAX_VALUE;
}
}
You would have to solve the Long.MAX_VALUE case as well.
A: It is easy to implement such a counter atop AtomicInteger:
public class CyclicCounter {
private final int maxVal;
private final AtomicInteger ai = new AtomicInteger(0);
public CyclicCounter(int maxVal) {
this.maxVal = maxVal;
}
public int cyclicallyIncrementAndGet() {
int curVal, newVal;
do {
curVal = this.ai.get();
newVal = (curVal + 1) % this.maxVal;
} while (!this.ai.compareAndSet(curVal, newVal));
return newVal;
}
}
A: I personally think the AtomicInteger solution is a little ugly as it introduces a race-condition which means your update attempt could "fail" and have to be repeated (by iterating within the while loop) making the update time less deterministic than performing the entire operation within a critical section.
Writing your own counter is so trivial I'd recommend that approach. It's nicer from an OO-perspective too as it only exposes the operations you're allowed to perform.
public class Counter {
private final int max;
private int count;
public Counter(int max) {
if (max < 1) { throw new IllegalArgumentException(); }
this.max = max;
}
public synchronized int getCount() {
return count;
}
public synchronized int increment() {
count = (count + 1) % max;
return count;
}
}
EDIT
The other problem I perceive with the while loop solution is that given a large number of threads attempting to update the counter you could end up with a situation where you have several live threads spinning and attempting to update the counter. Given that only 1 thread would succeed, all other threads would fail causing them to iterate and waste CPU cycles.
A: With Java 8
public class CyclicCounter {
private final int maxVal;
private final AtomicInteger counter = new AtomicInteger(0);
public CyclicCounter(int maxVal) {
this.maxVal = maxVal;
}
public long incrementAndGet() {
return counter.accumulateAndGet(1, (index, inc) -> (++index >= maxVal ? 0 : index));
}
}
A: You can use the java.util.concurrent.atomic.AtomicInteger class to increment atomically. As for setting an upper bound and rolling back to 0, you'll need to do that externally...perhaps encapsulating all this within your own wrapper class.
Actually, it appears that you can use compareAndSet to check the upper bound, and then roll over to 0.
A: I have to create a similar circular ticker for a custom Akka Routing logic which had to be different than the default ones to avoid network overhead, since my logic is just to pick the next routee.
Note: Copied from the suggested Java 8 implementation:
import akka.routing.Routee;
import akka.routing.RoutingLogic;
import scala.collection.immutable.IndexedSeq;
import java.util.concurrent.atomic.AtomicInteger;
public class CircularRoutingLogic implements RoutingLogic {
final AtomicInteger cycler = new AtomicInteger();
@Override
public Routee select(Object message, IndexedSeq<Routee> routees) {
final int size = routees.size();
return size == 0 ? null : routees.apply(cycler.getAndUpdate(index -> ++index < size ? index : 0));
}
}
A: For highly-intensive circular counter incremented by multiple threads in parallel, I would recommend using LongAdder (since java 8, see the core idea inside Striped64.java), because it is more scalable compared to AtomicLong. It is easy to adapt it to the above solutions.
It is assumed that get operation is not so frequent in LongAdder. When calling counter.get, apply to it 'counter.get % max_number'. Yes, modulo-operation is expensive, but it is infrequent for this use-case, which should amortize the total performance cost.
Remember though, that get operation is non-blocking, nor atomic.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572434",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: Facebook like - showing cached version og:image, way to refresh or reindex it? Having an issue with Facebook like and a cached og:image.
Long story short:
Facebook has cached an older version of our like image. The meta content URL can't be changed. Is there anything I can do to refresh it?
Long story:
The site I'm working on has a meta tag for an og:image that Facebook uses when a page is liked. This meta tag uses the same image URL on all pages across the site. The image is simply a branding image for the site.
The issue is the site recently updated their branding, and we can't get the Facebook like image to update. When a user clicks the like link, the resulting post to Facebook still shows the old branding image.
The meta tag is similar to:
<meta property="og:image" content="http://[domain].com/images/bookmark/apple-touch-icon.png"/>
Whenever a like makes its way to Facebook, the URL to the image is changed to the cached Facebook URL, similar to this:
http://external.ak.fbcdn.net/safe_image.php?d=AQDajxm-qgVNdfEL&w=90&h=90&url=http%3A%2F%2F[domain].com%2Fimages%2Fbookmark%2Fapple-touch-icon.png
This URL displays the older version of the site's branding. It has been over a week, and it has not updated yet.
Is there any way to force Facebook to reindex the image/clear it's cache? Or, does Facebook periodically do this automatically? I couldn't find any relevant information on this.
I know that changing the URL in the meta tag could fix the issue, but the meta tag is generated by code used across multiple sites and it can not be changed. I also tried the delinter tool as was suggested to me by others. No luck.
A: Insert your URL into their linter and it should reload its cache
A: 7 years later after this post was made and this is still a problem, but its not facebook's cache: It is human error (allow me to elaborate)
OG:TYPE effects your image scrape:
*
*https://ogp.me/#type_article not the same as https://ogp.me/#type_website
Be aware that og:type=website will cause any /sub-pages/ of that url to become "canonical". This means you will have trouble getting your images to update using the scraper no matter what you do.
Consider this "assumption and common mistake"
-<meta property="og:type" content="website" /> => https://www.example.org (parent)
-<meta property="og:type" content="website" /> => https://www.example.org/sub-page/
-<meta property="og:type" content="website" /> => https://www.example.org/sub-page/child-2/
- Ergo: /sub-page/ and /child-2/ will inherit the og:image of the parent
Those are not "all websites", 1 is a website, the others are articles.
If you do that Facebook will think all of those are canonical and it will put the FIRST og:image into all of them. (try it, you'll see) - if you set the og:url to be your root or parent domain you've told facebook they are all canonical. (there is good reason for that, but its off topic)
Consider this solution (which is what most people "really want")
-<meta property="og:type" content="article" /> => https://www.example.org/sub-page/
-<meta property="og:type" content="article" /> => https://www.example.org/sub-page/child-2/
If you do that now Facebook will give you far far less problems with scraping your NEW images.
In closing, YES the cache busters, random vars, changing urls and suggestions here can work, but they will seem like "intermittent voodoo" if the og:type is not specified correctly.
PS: remember that a CDN or serverside cache will serve to Facebook's scraper even if you "think" you can see the most recent version. (I wont spend any time on this other than to point out it will waste colossal amounts of your time if not double checked.)
A: You can use Facebook's object debugger which will allow you to enter the page URL and then on the next page you can re-submit it in a request to 'Fetch new scrape information'. This will clear Facebook's cache for the given URL - Not that it may take some time to propagate around all their cache nodes.
Facebook's Object Debugger can be found here:
https://developers.facebook.com/tools/debug/
We recently found that Facebook was caching URLs using a query string against the relative URL and that the query string was being ignored which messed up a few dynamic images we were serving purely based on the query string.
It turns out that you can specify a last modified timestamp (in Unix timestamp format) to help ensure when FB crawls your site, it always gets the correct image.
This can be done by including the following OG meta tag:
<meta property="og:updated_time" content="123465789" />
For dynamic sites you'll want to generate the content value - using PHP the current Unix timestamp can be inserted as follows:
<meta property="og:updated_time" content="<?=time()?>" />
A: *
*Change the URL of the og:image when you update the Image
example
<meta property="og:image" content="https://abc.lk/img/share-english.jpg" />
to
<meta property="og:image" content="https://abc.lk/img/share-english-1.jpg" />
*go to https://developers.facebook.com/tools/debug/sharing
*Add url - click debug
*Check Time Scraped and Click Scrape again
A: I have think a possible solution... what if you add at the end of the URL a random string?
like www.server.com/something.php?v=<?php echo rand() ?>
or
www.server.com/something.jpg?v=<?php echo rand() ?>
i guess facebook cahce object depending on the url... change it randomly... could help.
A: <meta property="og:image" content="https://example.com/image.jpg?v=<?= time() ?>" />
This was my solution, using ?v=UNIX_TIMESTAMP
but still you have to fetch page again.
https://developers.facebook.com/tools/debug/sharing
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572441",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "60"
}
|
Q: Pass array elements to settimeout function I don't understand why the fadeOut works but the remove doesn't. I found out it's a problem with the array. I tried some combinations, but I can't make it work.
for (var i=0;i<fieldsblock.length;i++){
$("#"+fieldsblock[i]+"_tr"+nid).fadeOut();
t=setTimeout(function(){$("#"+fieldsblock[i]+"_tr"+nid).remove();},400);
}
Thanks.
A: It looks like you just need the remove to run once the fadeOut has completed. If that's the case, you don't need to use setTimeout. You can use a callback instead:
for (var i=0;i<fieldsblock.length;i++){
$("#"+fieldsblock[i]+"_tr"+nid).fadeOut(function() {
$(this).remove();
});
}
The callback is executed whenever the animation is complete, so doing it this way means you won't have to change the setTimeout duration if you wanted to change the duration of the fade as well.
A: While I believe using the callback for jquery's fadeOut() method is correct in this case, you could still remove the element without it.
var block;
for (var i = 0; i < fieldsblock.length; i++) {
// Get the element
block = $("#" + fieldsblock[i] + "_tr" + nid);
// Fade it out without using the callback for whatever reason
block.fadeOut();
// Wait 400ms to remove it
setTimeout((function (blockToRemove) {
return function () { blockToRemove.remove(); };
})(block), 400);
}
Basically, (function (args...) { ... })(args...) lets you pass arguments to a function's local scope, which will "save the state" of the arguments you're working with. In the example above, we're passing block to the function's blockToRemove parameter, which then returns's another function that actually removes the element.
In this case it's definitely better to use the callback, but there are other times when someone could be looping through something where this would be very useful.
A: You've created a closure around the i variable. Closures capture the variable itself, not the value of the variable. So once these timeouts trigger, i will be equal to fieldsblock.length for all of them, which is not quite what you want.
In this particular case, James Allardice's answer is a good one, you might also need to add a delay() call if you want the remove to not happen right after fade out.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572442",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: AddThis and ShareThis conflict with Facebook Connect SDK My iOS app uses the latest version of Facebook Connect as one method of allowing users to login.
I recently experienced a problem while adding an SDK that allows me to share posts via social networks, as well as obtain data for analytics on users' sharing activity within the app.
When I added the SDK for ShareThis, I received a compiler error that indicated a conflict between the ShareThis Facebook library and my official Facebook Connect SDK. So, I uninstalled ShareThis and added the SDK for AddThis. This also created a similar conflict.
Is there an easy way to segregate these libraries so the AddThis or ShareThis SDK don't conflict with Facebook Connect? Or, an easy way to point the Facebook authentication in AddThis or ShareThis to the Facebook Connect library that I've installed?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572443",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to download a new version of Flash Player executable for opening SWF files and Flash IDE I would like to update the swf player that I specify into FDT and what Flash IDE uses to play files, namely from Flash 10 to Flash 11 for Stage3d preview. How does one do this?
A: One goes to the Adobe Flash Player Support Center, and download there latest versions of the debug flash players, according to the system, and browser one needs.
A: Check out this tutorial I wrote here:
http://fdt.powerflasher.com/blog/2011/08/setting-up-away-3d-4-0-loading-a-3d-model/
For the newer '3D' stuff you'll need to test it in a browser environment, see the 'Analyzing The Setup'.
In general, to change which stand alone player you're using - you need to change this in the Preferences > FDT > Tools > Flash section.
See more here:
http://fdt.powerflasher.com/docs/Launch_Configuration_Tutorial
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572444",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Filtering Guava HashMultimap keys by count I have created a hash multi map of following type: key as a pair of string, string and value as long.
HashMultimap<Pair<String, String>, Long> hm = HashMultimap.create();
I have inserted some values in the table using put function.
Now I want to find all those keys which have multiple values. I want to use for loop to iterate over all keys and find those keys which have multiple values. Please help me how can i do that?
A: Matt has the procedural way covered. The more functional approach (still verbose since Java doesn't have closures yet) would be something like this:
public class MoreThanOnePredicate<T extends Map.Entry<?, ? extends Collection<?>>> implements Predicate<T> {
public boolean apply(T entry) {
return entry.getValue().size() > 1;
}
}
//...
return Maps.filterEntries(hm.asMap(), new MoreThanOnePredicate<Pair<String, String>, Collection<Long>>()).keySet();
I don't have the library and a compiler in front of me so there are probably some unresolved generics problems with that.
A: Set<Pair<String, String>> keysWithMultipleValues = Sets.newHashSet();
for (Pair<String, String> key : hm.keySet())
{
if (hm.get(key).size() > 1)
{
keysWithMultipleValues.add(key);
}
}
A: This should be a bit more efficient than Matt's version as no lookup by keys is used:
Set<Pair<String, String>> r = Sets.newHashSet();
for(Entry<Pair<String, String>> e : create.keys().entrySet()) {
if(e.getCount() > 1) r.add(e.getElement());
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572446",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Need PC Text editor/ IDE with the following features: I'm needing what seems like common sense tools for one source:
1) Sytax highlighting. (Specifically for PHP)
2) Integrated Terminal (Don't need to open Putty for ssh, it's integrated into IDE)
3) Search function that can search local directories. (Can select any directory on local machine and do searches on text content)
This is all available in Coda but I haven't found a single PC tool that does this well.
Aptana comes close, but has no search function for local directories. (Seriously? How do I find functions that aren't part of a project then?)
Any help in finding this elusive wonder would be great.
A: Notepad++ should do for 1) and 3)
2) possuldibly could be achieved with plugin NppFTP
http://notepad-plus-plus.org/
http://sourceforge.net/projects/nppftp/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572452",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: iPhone equivalent of Timer and TimerTask for periodic tasks I'm trying to port an Android app to an iPhone. On Android I could easily process data every 60 seconds by using a Timer class with TimerTasks using scheduleAtFixedRate:
timer.scheduleAtFixedRate(task,15000, epochLengthMs);
Thank you!
Is there something similar I can use on iPhone?
protected void startTimer(){
if(timerStarted){
//avoid duplicate timers!
}else{
running = true;
timerStarted = true;
if(D)Log.w(TAG,"*Timer Started*");
timer = new Timer();
readyToProcess = true;
EpochCounterTask task = new EpochCounterTask();
AutoSaveTask saveTask = new AutoSaveTask();
//give statMagnitude enough time to get values
//after 15 sec, every 60 sec
timer.scheduleAtFixedRate(task,15000, epochLengthMs);
timer.scheduleAtFixedRate(saveTask,645000, 600000);
}
}
A: You will need to create two NSTimers - one for the epoch counter and one for the autosave task. Something like this:
- (void)startTimer {
if(timerStarted){
//avoid duplicate timers!
}else{
running = true;
timerStarted = true;
readyToProcess = true;
epochTimer = [[NSTimer scheduledTimerWithTimeInterval:epochSeconds
target:self
selector:@selector(processEpochTimer:)
userInfo:nil
repeats:YES] retain];
autosaveTimer = [[NSTimer scheduledTimerWithTimeInterval:autosaveSeconds
target:self
selector:@selector(processAutosaveTimer:)
userInfo:nil
repeats:YES] retain];
}
}
You also need to define the following handler methods, which are called when the timers fire:
- (void)processEpochTimer:(NSTimer*)theTimer;
- (void)processAutosaveTimer:(NSTimer*)theTimer;
A: Take a look at NSTimer
A: take a look at http://www.iphoneexamples.com/ Timer
Timers
This timer will call myMethod every 1 second.
[NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:@selector(myMethod:)
userInfo:nil
repeats:YES];
What if you need to pass an object to myMethod? Use the "userInfo" property.
1. First create the Timer
[NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:@selector(myMethod:) //don't forget the ":"
userInfo:myObject
repeats:YES];
*
*Then pass the NSTimer object to your method:
-(void) myMethod:(NSTimer*)timer
// Now I can access all the properties and methods of myObject
[[timer userInfo] myObjectMethod];
To stop a timer, use "invalidate":
[myTimer invalidate];
myTimer = nil; // ensures we never invalidate an already invalid Timer
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572454",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: What's wrong with Jsch and Maven? I try to use Jsch 0.1.44 together with Maven.
I have the following dependency in my pom.xml.
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.44</version>
<scope>compile</scope>
</dependency>
If I run mvn compile maven looks normal and tells me that Jsch has been successful downloaded.
But when it comes to compile, the Jsch classes could not be found. If I look into my local repository I can see that the Jsch-jar has only a size of 3kb. If I open the jar file I can also see that there is only the META-INF folder.
So what is wrong here, how can I fix this?
A: There are different possibilities:
*
*You have used the correct Maven repository for jsch (seems to be this one: http://mvnrepository.com/artifact/com.jcraft/jsch/0.1.44-1), but the download stopped for whatever reason. This happens, and you have just to clear your local repository by deleting the directory for jsch or the the version only. It will be reloaded again.
*Perhaps you has misconfigured your remote repository for jsch, and jsch is hold somewhere, but not the library, only the meta data. I do not know if it is possible to see from which location you got the wrong library.
You should look at your settings.xml (for Maven or your user) and see if the repository is specified correctly.
You should check if the command
mvn dependency:get -DrepositoryUrl=http://mvnrepository.com/artifact/ \
-DgroupId=com.jcraft -DartifactId=jsch -Dversion=0.1.44 \
-Dtransitive=false
works properly.
A: For some reason the jar file in the central repository seems to be broken.
The solution is to add another repository for Jsch to the pom.xml.
<repository>
<id>Jsch</id>
<url>http://jsch.sf.net/maven2/</url>
</repository>
A: 0.1.44 version is broken (it's only 3KB)
http://mvnrepository.com/artifact/com.jcraft/jsch/0.1.44
use http://mvnrepository.com/artifact/com.jcraft/jsch/0.1.44-1 Instead
update your POM to this:
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.44-1</version>
</dependency>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572457",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Downloading PDF File with AJAX/MVC 3 Basically the issue is this:
I have a pdf file that I am requesting from a server based on the currently logged in user's ID and the OID. In order to get the OID, I have to parse a value from a HTML table based on the button the user clicks on and then send it to the home controller. Then an API call is run to grab the OID. Another API call is then made with the OID to pull the PDF file. AJAX is used to send the the parsed HTML value to the home controller using this code here:
$('.pdfPrint').live('click', function () {
$(this).addClass('selectedDetails');
var parent = $('.selectedDetails').parents('tr');
var tr = $(this).parents('tr');
var td = tr.children();
var i = 0;
td.each(function () {
$(this).addClass('tdGrid' + i);
i++;
});
var primaryReference = "";
primaryReference = $('.tdGrid1').text();
gridClassRemover();
$.ajax({ // create an AJAX call...
data: { pReference: primaryReference }, // get the form data
type: "POST", // GET or POST
url: "/Home/PrintFromGrid", // the file to call
success: function (response) { // on success..
callTrackDialog();
// update the DIV
}, // end of success
error: function () {
alert('An error has occurred. If this problem persists please contact support.');
}
}); // end of .ajax
});
A: Yes, don't use AJAX to download files. Simply redirect in javascript by passing the pReference as query string parameter:
window.location.href = '@Url.Action("PrintFromGrid", "Home")?pReference=' + encodeURIComponent(primaryReference);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572459",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Storing a password in SQL Server database. Do .Net functions suffice? My initial plan was to use the .NET built in hashing library (SHA512) and store the password along with a salt. I'm familiar with how this can be done.
It has been requested that we should be able to add users along with their passwords manually in a SQL script. I'm familiar with using the HASHBYTES SQL Server to accomplish password hashing and I'm aware with its drawbacks (SHA1 and no salt).
Is there a way I can make the .NET code and the SQL Server HASHBYTES work together? I figure it isn't possible unless I want to drop the salt and use SHA1 as the hashing algorithm in the .NET code.
A: You could write a CLR stored procedure/function which will use the .NET features and deploy it to the SQL server do do the task. So instead the HASHBYTES you will call directly your .NET code from the SQL server.
Here is a link to quick sample of such function
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572461",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Is there any class like VBox, HBox etc. in Flash Pro CS5? Flex has great classes for manipulating with controls in multiscreen apps like VBox, HBox, VGroup etc. But my project is in Flash Proffesional CS5. Are there any way to use these features?
A: Out-of-the-box, no. You can't use the Flex framework without building as a Flex project; there's a lot of code in those classes that depends on running within other Flex containers.
If you just need code to stack children vertically or horizontally (without any measure/layout passes), then the code is pretty trivial. Here's some very preliminary code for a container that will stack children vertically with no layout passes.
public class VerticalContainer extends Sprite
{
public function VerticalContainer()
{ super(); }
override public function addChild(child:DisplayObject):DisplayObject
{
child.y = height;
return super.addChild(child);
}
}
There's no protection of the child's location, so anything that has a reference on it could move it around without the VerticalContainer knowing about it. There are lots of holes to fill here, but it's a primitive example of what you could do to write these components.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572464",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: prevent html elements from squishing when resolution too small I see websites like Amazon and Google when you shrink the width of the web browser the elements only squish to a certain point and then it stops squishing even if you shrink the width even more.
What kind of techniques would allow this? Is there a specific CSS attribute that can enable this?
A: The CSS min_width property.
A: #header {
background: url(../images/image.jpg) repeat-x;
min-width: 960px;
}
Hope this helps
A: They use the min-width and min-height css properties.
For example, to make a content div (or with HTML 5 a content tag) stop shrinking when its 300px wide, use the following css code:
div#content {
min-width: 300px;
}
You can still use this method with a percentage or em based layout- just use it to prevent the page from becoming to small:
div#content {
width: 70%;
min-width: 300px;
}
Note: The min-width property does not include padding, borders, or margins when it calculates when to kick in (it only considers the container's width).
A: You're probably seeing the min-width and min-height styles in action.
eg:
.myclass {
width: 50%;
min-width:100px;
}
...will take up 50% of the container object, so can be resized, but will never get smaller than 100px wide.
min-height works in much the same way.
Note that if you need to support IE6, this browser doesn't support min-height or min-width. (there are work-arounds for this, but the best solution is not to support IE6)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572465",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Communication between excel and silverlight I am developing an application where i need to get data from excel to my silverlight oob application and after manuplation send it back to excel.
I am able to do this using with com automation factory classes. But the problem is we have already developed some logics for grabing data from wcf and odbc so we want to track changes by WCF service.
The requirement is: if i changes data into excel that will be reflected into silverlight and if I change data into silverlight that need to be reflected into excel, using an WCF Service.
Is it possible to communicate Excel to Silverlight or vice versa with WCF service ?
A: I'm having a hard time understanding what you want to accompish, but I'll try to answer the question as is.
It's possible to call a WCF service from both SL and an Excel .NET application (COM Add-in or VSTO). It's also possible to host a WCF service right in Excel .NET app (at least, should be: you can do it in a console app, so why not?). So basically you can use WCF to communicate between SL OOB and Excel .NET app. But the question is: why do it that way? I have a feeling that it's much faster and safer to just rewrite your logic so you won't need WCF at all...
A: upload the excel file though silverlight to WCF and then use OpenXml to do what you want with it. Then redownload it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572466",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: git add remote tracking branch to bare repo
*
*I have a bare repo that was cloned from git.drupal.org.
*I have cloned from this bare repo to various different websites.
*From each of these, I push a site-specific branch onto the bare repo.
E.g. if I have foo.org and bar.org, then my bare repo has drupal's branches + one called foo and one called bar.
The idea was that I could make the most of git's hard links to save disk space with local clones. I thought I would keep the bare repo fetching from git.drupal.org, and pull changes down to my local copies, foo & bar. Then when an update came along it would be easy.
bare-repo$ git fetch >/dev/null ; git branch -a
* 7.x
foo
bar
remotes/origin/7.x
remotes/origin/8.x
foo and bar started out on branch 7.x but I'd like to update them to 7.8, e.g. by git rebase 7.8 but this fails:
fatal: Needed a single revision
invalid upstream 7.8
foo and bar cannot 'see' the bare repo's remotes. What can I do?
A: you need a working folder for rebase. So you need to clone this repo and then do what you need. After that, push the modified branches back to the bare repo.
Alternatively, you can specify a working directory git --work-tree=../somedir rebase 7.8. Unfortunately the worktree and git dir options for the git command are not fully implemented for all commands. The first option is the best.
Rebase needs a working dir because it needs to give you control when it encounters a conflict. You can then fix the conflict and issue a git rebase --continue command to let it apply the rest of the commits on the new base.
Hope this helps.
A: 2 points, as explained in "git rebase fatal: Needed a single revision":
*
*you need to specify the name of a branch, which in your case would be origin/7.8, not 7.8:
git rebase origin/7.8
should work.
*
*You can't rebase to a branch that does not contain the commit your current branch was originally created on. (so make sure that it is the case for your repo)
The OP artfulrobot reports:
git rebase origin/7.8
fatal: Needed a single revision invalid upstream origin/7.8
To which I replied:
if 7.8 isn't present in origin as a branch, this error message is expected.
Maybe 7.8 is a tag in the 'origin' repo.
In this case, you need to explicitly fetch said tags first:
git fetch --tags origin
Then the rebase should work
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572469",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Azure Storage & Snapshots I have a VHD in a container which was mounted by an instance (a DotNetNuke accelerator). But now the instance is stopped so the VHD is not mounted anymore.
The problem is I can't rename this VHD with any UI client. "CloudBerry Explorer for Azure Blob Storage" shows an error when I try to rename it of
This operation is not permitted because the blob has snapshots.
I tried to list snapshots in VisualStudio but it only returns the blob's name...
I tried to mount the VHD in an instance and create a file and it works!?
I'm going crazy. :)
A: I've managed to remove blob which has snapshots by using Microsoft Azure Storage Explorer. Steps are:
*
*You navigate to the blob in question
*Right click -> Manage Snapshots
*Delete all the snapshots and the blob will disappear also
A: The error is accurate. If you get that, it means the blob actually has snapshots. When you mount a blob you are most likely mounting the current version and not a past snapshot. You can enumerate the snapshots using the REST API (use the 'include=snapshots option) to prove this to yourself.
If you really want to delete the blob with minimal hassle, I would suggest using https://www.myazurestorage.com (safe site from Microsoft DPE). It will enumerate your snapshots automatically and allow you to delete them. Once they are all deleted, you can also delete the blob.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572471",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Google maps and raising marker I'm writing web app that uses google maps. I've got some points placed to the map as markers. When I drag the marker - it raises - and when I drop it - it falls back down. I want to avoid raising marker. Is there any way to drag it without raising?
A: This feature has probably been added since the question was asked but stopping the marker from raising is quite straight forward now.
When creating Marker set its 'raiseOnDrag' property to false. Like so...
marker = new google.maps.Marker ({draggable : true, raiseOnDrag : false});
A: Since there is no option while creating the marker I guess there is no way.
The only thing, I could imagine would be using the icons (in the reference there is an example).
But you have to try, I don't know if selfmade icons are raised or not.
A: You can use marker.setAnimation() method:
var marker = new google.maps.Marker({...});
google.maps.event.trigger(marker, 'dragstart'); // trigger dragstart to keep marker in the "raised" state"
marker.setAnimation(3); // raise
// later
marker.setAnimation(4); // fall
In Google Maps API there are only two types of animations documented (BOUNCE and DROP), but I have discovered two more:
1: BOUNCE,
2: DROP,
3: raise,
4: fall
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572472",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How do I mitigate duplicate row inserts based on a non-key column? I need to import data from one MySQL table into another. The old table has a different outdated structure (which isn't terribly relevant). That said, I'm appending a field to the new table called "imported_id" which saves the original id from the old table in order to prevent duplicate imports of the old records.
My question now is, how do I actually prevent duplicates? Due to the parallel rollout of the new system with the old, the import will unfortunately need to be run more than once. I can't make the "import_id" field PK/UNIQUE because it will have null values for fields that do not come from the old table, thereby throwing an error when adding new fields. Is there a way to use some type of INSERT IGNORE on the fly for an arbitrary column that doesn't natively have constraints?
The more I think about this problem, the more I think I should handle it in the initial SELECT. However, I'd be interested in quality mechanisms by which to handle this in general.
Best.
A: You should be able to create a unique key on the import_id column and still specify that column as nullable. It is only primary key columns that must be specified as NOT NULL.
That said, on the new table you could specify a unique key on the nullable import_id column and then handle any duplicate key errors when inserting from the old table into the new table using ON DUPLICATE KEY
Here's a basic worked example of what I'm driving at:
create table your_table
(id int unsigned primary key auto_increment,
someColumn varchar(50) not null,
import_id int null,
UNIQUE KEY `importIdUidx1` (import_id)
);
insert into your_table (someColumn,import_id) values ('someValue1',1) on duplicate key update someColumn = 'someValue1';
insert into your_table (someColumn) values ('someValue2');
insert into your_table (someColumn) values ('someValue3');;
insert into your_table (someColumn,import_id) values ('someValue4',1) on duplicate key update someColumn = 'someValue4';
where the first and last inserts represent inserts from the old table and the 2nd and 3rd represent inserts from elsewhere.
Hope this helps and good luck!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572475",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Translating a QueryExpression into SQL: what's a Natural join? I am trying to translate a QueryExpression that is in some existing code into a T-SQL select statement.
I've run across the following statement and I'm having trouble understanding what they mean by a Natural Join:
linkEntity1.JoinOperator = JoinOperator.Natural;
Would this be equivalent to an Inner Join in T-SQL? Googling has not been much help.
Here's the rest of the QueryExpression Code:
QueryExpression query = new QueryExpression();
query.EntityName = "showinfo";
ColumnSet columns = new ColumnSet();
columns.Attributes = new String[] { "company" };
query.ColumnSet = columns;
query.Criteria = new FilterExpression();
query.Criteria.FilterOperator = LogicalOperator.And;
ConditionExpression condition1 = new ConditionExpression();
condition1.AttributeName = "company";
condition1.Operator = ConditionOperator.NotNull;
query.Criteria.Conditions = new ConditionExpression[] { condition1 };
LinkEntity linkEntity1 = new LinkEntity();
linkEntity1.JoinOperator = JoinOperator.Natural;
linkEntity1.LinkFromEntityName = "show";
linkEntity1.LinkFromAttributeName = "showid";
linkEntity1.LinkToEntityName = "showintegration";
linkEntity1.LinkToAttributeName = "showcode";
linkEntity1.LinkCriteria = new FilterExpression();
linkEntity1.LinkCriteria.FilterOperator = LogicalOperator.And;
ConditionExpression condition2 = new ConditionExpression();
condition2.AttributeName = "showend";
condition2.Operator = ConditionOperator.Null;
linkEntity1.LinkCriteria.Conditions = new ConditionExpression[] { condition2 };
query.LinkEntities = new LinkEntity[] { linkEntity1 };
A: There is no equivalent in SQL Server of a natural join where table intersect is based on column names by the RDBMS.
I'm glad of that because it is at best ambiguous and at worst dangerous. JOINs should be explicit. Examples why:
*
*having a InsertedBy column in both tables (quite common): should we have to prefix with the table name to remove ambiguity?
*future DDL that add columns that change JOIN semantics
See
*
*Natural join in SQL Server
*SQL Server - lack of NATURAL JOIN / x JOIN y USING(field)
Edit:
It looks like natural join means "don't repeat the column in the output" (like USING in MySQL would do) according to the JoinOperator Enumeration.
If I understand this (debatable!) it's misleading. Especially when I read the "LeftOuter" narrative..
A: A natural join compares all columns in the two tables that have the same column names. It's equivalent to an inner join with the matching columns explicitly listed.
A: Yes - the natural join is inner join - so you can write:
select * from tab1, tab2 where tab1.col1 = tab2.col1
as
select * from tab1 inner join tab2 on tab1.col1 = tab2.col1
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572479",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Spring Security 3 RestTemplate POST to j_spring_security_check I am using Spring Security 3 with REST endpoints. I managed to get a basic Spring Security working.
Part of the security-context.xml
<security:http auto-config="true" use-expressions="true" access-denied-page="/rest/denied" >
<security:intercept-url pattern="/rest/*" access="ROLE_USER"/>
and basic config as found on the web
<security:authentication-manager>
<security:authentication-provider user-service-ref="userDetailsService">
<security:password-encoder ref="passwordEncoder"/>
</security:authentication-provider>
<!-- Use a Md5 encoder since the user's passwords are stored as Md5 in the database -->
<bean class="org.springframework.security.authentication.encoding.Md5PasswordEncoder" id="passwordEncoder"/>
<!-- An in-memory list of users. No need to access an external database layer.
See Spring Security 3.1 Reference 5.2.1 In-Memory Authentication -->
<!-- john's password is admin, while jane;s password is user -->
<security:user-service id="userDetailsService">
<security:user name="john" password="21232f297a57a5a743894a0e4a801fc3" authorities="ROLE_USER, ROLE_ADMIN" />
<security:user name="jane" password="ee11cbb19052e40b07aac0ca060c23ee" authorities="ROLE_USER" />
</security:user-service>
I want to login to j_spring_security_check using a RestTemplate POST.
HttpEntity<String> entity = new HttpEntity<String>(request, headers);
HashMap<String, String> map = new HashMap<String, String>();
map.put("j_username", "john");
map.put("j_password","21232f297a57a5a743894a0e4a801fc3");
String response = restTemplate.postForObject("http://localhost:8080/rest/j_spring_security_check", map, String.class);
but in the log, it seems the username parameter is not being read
DEBUG o.s.s.authentication.ProviderManager - Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider
DEBUG o.s.s.a.d.DaoAuthenticationProvider - User '' not found
DEBUG o.s.s.w.a.UsernamePasswordAuthenticationFilter - Authentication request failed: org.springframework.security.authentication.BadCredentialsException: Bad credentials
What is the correct way to get the REST Template to post auth credentials? Is there a better way to login in/ get authorized other than j_spring_security_check? Does the information go in the header?
Thanks in advance.
A: This seems like a duplicate of another SO question. You are probably approaching this the wrong way, though. Typically if you are issuing a REST request you wouldn't be authenticating at the same time - this doesn't make any sense - certainly not using form POST style logic.
For authentication of REST requests you should be using another form of authentication (assuming these requests are generated programmatically):
* HTTP Basic auth
* X.509 certificates
OR if this is happening through an XHR / Javascript origin, you should be prepared to have the request fail and redirect the user to the login mechanism. Typically handling REST style requests with Spring Security is not at all the same as handling regular secured pages. You should be prepared for some amount of complexity.
Good luck!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572482",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Execute public String I have a public class EmailHelp.
In this class there is a public String called doIt.
How do i execute this public String DoIt from within let´s say a onClick event?
public class EmailHelp{
-----
public String DoIt {
------
public void crxExecute () {
execute DoIt
finish();
Thank you in advance.
A: Assuming that "DoIt" is not a static method, you'd need to create an instance of the EmailHelp class, and call that method:
public void Button_OnClick(object sender, EventArgs e)
{
var emailHelper = new EmailHelp();
emailHelper.DoIt();
}
The fact that it's not obvious that you need to instantiate EmailHelper may indicate that the method should in fact be a static one. If it were a static method, calling it would look like this:
public void Button_OnClick(object sender, EventArgs e)
{
EmailHelp.DoIt();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572491",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Print out ranks virtually I have done something similar to this in php and cannot figure it out in mvc3. I want to pull the top 100 results from a table and append a number to each result to print it out like a Top Charts type of deal. I want to just add the rank number on the fly.
My Code:
var tracks = db.Query(@"SELECT * FROM tracks ORDER BY plays DESC LIMIT 100").ToList();
@foreach (var track in tracks) {
var a = 0;
var x = a+1;
<tr>
<td>@x</td>
<td>@track.Title</td>
</tr>
}
What I want it to do (Append the next number in the next one):
<tr><td>1</td><td>Track Name</td></tr>
<tr><td>2</td><td>Track Name2</td></tr>
Nevermind project aborted, since people gotta criticize so hard on people trying to start a new flavor to write. Its all good.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572493",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: I can't fix this seemingly, simple, cast related, postgresql error So, I have this query:
SELECT count(*) AS count FROM table1 INNER JOIN "some query"
WHERE "some more query"
OR (table.smowid NOT LIKE (58)) OR "rest of query"
Sorry for the unclear code, the full query is quite big, but the problem is in the table.smowid NOT LIKE (58) part.
This is the error I get:
ERROR: operator does not exist: integer !~~ integer
LINE 11: or ( (table.smowid) NOT LIKE (58))
^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
I unfortunately, don't know much about casts and types, but why is the DB complaining when it's going from integer to integer?
I tried CASTING by saying (CAST (table.smowid) AS INTEGER) NOT LIKE (58) but that didn't work, I also tried (table.smowid :: integer) NOT LIKE (58) but that also didn't work for some reason.
So, what should I do? Thanks for all the help.
A: NOT LIKE and its equivalent !~~ are definitely not integer operators. What are you trying to do with a pattern matching operators on integers?
There's a way to use it but you first have to cast (or format) the integers to text.
A: you should cast them both to text or, better yet, have a smowis column with all the smowi values as text to save the overhead of casting each time.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572495",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Does managed code mean JIT or GC? I've seen several explanations on what "managed" code means, and some target the idea of managed code being compiled to an intermediate language and JITed and others talk about GC and memory management. Which actually makes a language managed, or is it both or neither?
The answer of GC makes a lot of sense since the memory is managed (henced "managed code"), but couldn't there hypothetically be a language that has GC but is native (not compiled to IL). Are GC and IL code somehow tightly coupled?
A: No, I would not say the the GC and IL are tightly coupled. In fact, one can exist without the other - and sometimes that is the case.
IL's major purpose is to make it platform agnostic, and to allow the JIT to make very specific optimizations that depend on the platform. For example, x86, x64, ARM, etc. The JIT's purpose is to turn that IL into native machine code for the architecture, and optimize it correctly.
You couldn't optimize for x86 and ARM because the platforms are too different. That's why there is a JIT for each specific platform. The JIT has the luxury of knowing what platform it's going to run against. As a code author, you may not know.
GC on the otherhand is about memory management. There are plenty of Garbage Collector libraries for software that does not compile to an intermediate language. Take for example this one, which is small but gets the job done. There have been plenty of papers on the subject as well.
It is possible for one to exist without the other, that's just not how we see it very often.
So what makes a "managed" language? To me, it means there is a virtual machine of some type involved. In .NET's case, the CLR. It provides various services, such as GC, Jit, Code Access Security (CAS), etc.
A: http://en.wikipedia.org/wiki/Managed_code
This makes it pretty clear that its the code that is managed (by running under a virtual machine), and not the memory.
A: Managed code means it is run by a virtual runtime machine and typically implies memory management. This is what people mean when they say "managed code". System resources (such as memory allocation) are managed for you among a few other things.
JIT has nothing to do with it. JIT is a feature of some virtual runtime machines but not a requirement. Visual Basic 6 uses a runtime but not JIT - it is interpreted line by line. JIT compiles a unit of code at the time of invocation. A .NET language, however, will use the .NET runtime which implements JIT compilation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572499",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: IntelliJ2-IDEA get Maven-2 to download source and documentation I have a spring mvc project setup using maven in IntelliJ.
While I was setting the project up, IntelliJ asked me if I wanted to download the source and documentation. In order to save time at that point I did not select this option. However now I would like to download some of the source if not all. Does any one know where how to accomplish this in IntelliJ for a project that has already been setup?
The question is specific to how to do this with intelliJ since I would like all the mouse over and documentation features in IntelliJ to show me the source / documentation when needed.
Thanks,
A: For automatic downloading: Go to File --> Settings --> Maven --> Importing. Then check the automatic download options.
To do so once only, open the Maven tab and click on the download icon and select "Download Sources and Documentation"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572500",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Does Apple Store, Android Market accept Mobile Apps made using jQuery , jQueryMobile and Phone-Gap I am making an application for online blog I am using JqueryMobile features to design the application and Phone Gap to add features to it like GPS to check location and other features from Mobile.
<div id="index" data-role="page">
<div data-role="header" data-position="fixed" id="nav_header">
<h1>Deals</h1>
<nav data-role="navbar">
<ul>
<li><a href="#index">home page</a></li>
<li><a href="#info">settings</a></li>
</ul>
</nav>
</div>
<div data-role="content">
<a href="#search" data-role="button">Search Blog</a>
<a href="#search" data-role="button">New Blog </a>
</div>
</div>
Would it be acceptable if writen in this format ? I am totally newbie in this. What else should I do or improve if I am missing somewhere in making this? Thanks
A: I'm fairly sure that you'd be fine on the Android marketplace, there are very few rules other than no malware. I can't help you regarding iOS though.
A: phonegap works for the apple store but occaisonally the acceptance time is higher then a normal iphone app http://www.macstories.net/news/apple-phonegap-framework-is-ok-for-the-app-store/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572503",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: disable automatic locking on iphone with iOS 4.3.3 I want to disable the auto lock on my iOS4.3.3 program. I found on the web the same answer several times for this and working for xcode3 but I cant find it to work with mine.. help pls? thks
A: This should work on iOS 4.3.3. If not then you're doing something wrong:
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];
A: I did it in a ViewController like this.
-(void) viewDidAppear:(BOOL)animated
{
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];
}
-(void) viewDidDisappear:(BOOL)animated
{
[[UIApplication sharedApplication] setIdleTimerDisabled:NO];
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572510",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How can I use assets within Mailer? I have trouble using any form of the asset pipeline within mailer, wether the Mailer itself or the view.
The following produces and empty src image tag.
<%= image_tag "emails/header-general.png" %>
The empty image tag looks like this:
img alt="Header-general"
The following form of attaching a file through the model and using it in the view attaches an empty image.
attachments.inline['header.jpg'] = 'emails/header-general.png'
...
<%= image_tag attachments['header.png'] %>
I did check the path and even tried with multiple paths and so on but with no luck.
Please help. Any form of including an image within the email would be helpful.
Here is the production env.
Xenium::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.compress = true
# Choose the compressors to use
config.assets.js_compressor = :yui
config.assets.css_compressor = :yui
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = true
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to Rails.root.join("public/assets")
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
config.log_level = :fatal
# Use a different logger for distributed setups
# config.logger = SyslogLogger.new
# Use a different cache store in production
config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
#config.action_controller.asset_host = "http://asset.xenium.bg"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
config.action_mailer.raise_delivery_errors = true
#config.action_mailer.perform_deliveries = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:address => "localhost",
:port => 25,
:domain => 'xenium.bg',
#:user_name => '<username>',
#:password => '<password>',
#:authentication => 'plain',
:enable_starttls_auto => false
}
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
end
Thanks!
A: set config.action_controller.asset_host and config.action_mailer.asset_host and this works well.
config.action_mailer.asset_host = URL from where pick image
<%= image_tag image_path('logo.png') %>
A: According to the 2.3.3 Making Inline Attachments section, to create an inline attachment you will do as follows
attachments.inline['image.jpg'] = File.read('/path/to/image.jpg')
So in your case, it should be
attachments.inline['header.jpg'] = File.read("#{Rails.root}/app/assets/images/emails/header-general.png"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572521",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Is it possible to have case insensitive targets with GNU make? Is it possible to design a makefile so that
make program_name
produces the same result as
make PROGRAM_NAME
?
I know I can do the following in the makefile
program_name : PROGRAM_NAME
but I don't know if there is a way to streamline this for multiple targets. We have about 50 or so targets.
A: Crude but effective:
PROGRAM_NAME:
@echo do something for $@
ANOTHER_TARGET:
@echo do something else for $@
YET_ANOTHER:
@echo and something else for $@
% :
@$(MAKE) `echo $@ | tr [:lower:] [:upper:]`
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572522",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Why would anyone ever use the Java Thread no argument constructor? In what situation would anyone ever use the no-argument constructor of the Java Thread class?
The API says:
This constructor has the same effect as Thread(null, null, gname),
where gname is a newly generated name.
Correct me if I am wrong, but I think the target of the thread can not be modified after the new Thread object is instantiated. If the target equals null then the start method will do nothing right?
Why would you use this constructor?
A: For one thing, it allows you to create subclasses without the PITA of explicitly calling the superclass constructor, e.g.
new Thread(){
public void run() { ... }
}.start();
A: If you make a (perhaps anonymou) class that inherits Thread and overrides run, your class needs to call this base constructor.
A: If you inherit from Thread you certainly can use the no-arg constructor of Thread.
A: Just to add to the other answers, this is the implementation of Java's Thread#run():
public void run() {
if (target != null) {
target.run();
}
}
So you can see the effect is achieved one of two ways, either by providing a Runnable to a Thread constructor, so it is assigned to target, or by overriding this method in a subclass. If one does neither, a call to run() has no effect.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572527",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Complexity of stl deque::insert() I learned the complexity of deque::insert() from the C++ standard 2003 (chapter 23.2.1.3) as follows:
In the worst case, inserting a single element into a deque takes time linear in the minimum of the distance from the insertion point to the beginning of the deque and the distance from the insertion point to the end of the deque.
I always understand the implementation of stl deque as a collection of memory chunks. Hence an insertion will only affect the elements in the same memory chunk as the insertion position. My question is, what does the standard mean by "linear in the minimum of the distance from the insertion point to the beginning of the deque and the distance from the insertion point to the end of the deque"?
My understanding is because C++ standard does not enforce a certain implementation of deque. The complexity is just in general for the worst case. However, in the actual implementation in compilers, it is linear to the number of elements in a memory chunk, which may vary for different element sizes.
Another guess might be that, since insert() will invalidate all iterators, deque needs to update all iterators. Therefore it's linear.
A: std::deque is normally (always?) implemented as a collection of chunks of memory, but it won't normally insert a whole new chunk just for you to insert one new element in the middle of the collection. As such, it'll find whether the insertion point is closer to the beginning or end, and shuffle the existing elements to make room for the new element in an existing chunk. It'll only add a new chunk of memory at the beginning or end of the collection.
A: I think you'd be better served by a diagram... let's play with ASCII art!
A deque is usually an array of memory chunks, but all apart the front and back memory chunks are full. This is necessary because a deque is a RandomAccessContainer, and to get O(1) access to any container, you cannot have an unbounded number of containers from which to read the size:
bool size() const { return first.size + (buckets.size()- 2) * SIZE + last.size; }
T& operator[](size_t i) {
if (i < first.size) { return first[SIZE - i]; }
size_t const correctedIndex = i - first.size;
return buckets[correctedIndex / SIZE][correctedIndex % SIZE];
}
Those operations are O(1) because of the multiplication/division!
In my example, I'll suppose that a memory chunk is full when it contains 8 elements. In practice, nobody said the size should be fixed, just that all inner buckets shall have the same size.
// Deque
0: ++
1: ++++++++
2: ++++++++
3: ++++++++
4: +++++
Now say that we want to insert at index 13. It falls somewhere in the bucket labelled 2. There are several strategies we can think about:
*
*extend bucket 2 (only)
*introduce a new bucket either before or after 2 and shuffle only a few elements
But those two strategies would violate the invariant that all "inner" buckets have the same number of elements.
Therefore we are left with shuffling the elements around, either toward the beginning or the end (whichever is cheaper), in our case:
// Deque
0: +++
1: ++++++++
2: +O++++++
3: ++++++++
4: +++++
Note how bucket 0 grew.
This shuffle implies that, in the worst case, you'll move half the elements: O(N/2).
deque has O(1) insert at either the beginning or the end though, because there it's just a matter of adding the element in the right place or (if the bucket is full) creating a new bucket.
There are other containers that have better insert/erase behavior at random indices, based on B+ Trees. In an indexed B+ Tree you can, instead of a "key" (or in parallel) maintain internally a count of the elements prior to a certain position. There are various technics to do this efficiently. At the end you get a container with:
*
*O(1): empty, size
*O(log N): at, insert, erase
You can check the blist module in Python which implements a Python list-like element backed by such a structure.
A: Your conjecture are ... 99.9% true.
All depends on what the actual implementation is. What the standard specifies are the minimum requirement for both the implementors (that cannot claim to be standard if they don fit the specs) and users (that must not expect "better performances" if writing implementation independent code).
The idea behind the spec., is a chunk (a == one) of uninitialized memory where elements are allocated around the center... until there is space for them.
Inserting in the middle means shift. Inserting at front or end means just construct in place. (when no space exist, a reallocation is done)
Indexes and iterators cannot be trusted after a modification, since we cannot assume what has been shifted and in which direction.
More efficient implementation don't use a single chunk, but multiple chunk to redistribute the "shifting" problem and to allocate memory in constant size from the underlying system (thus limiting reallocation and fragmentation).
If you're targeting one of them you can expect better performances, otherwise yo had better not to assume any structure optimization.
A: Linear on the number of elements inserted (copy construction). Plus, depending on the particular library implemention, additional linear time in up to the number of elements between position and one of the ends of the deque.
Reference...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572529",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Is it possible to remove voice search for edits in Android I have a requirement to suppress voice recognition button in Android SoftKeyboard.
During my research I found the setInputMethodAndSubType which has mode parameter. But I cannot locate how it can be used.
Any inputs.
A: My previous answer was incorrect. The correct flag was android:inputType. If you set this flag to textUri on your EditText it will make the voice recognition button not appear.
android:inputType="textUri"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572531",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: modifying django model forms after post I would like to modify a user submitted form to automatically insert the project_id, but I keep getting the error that project_id in the Employee model cannot be null;
My model:
class Project(models.Model):
name = models.CharField(max_length=100)
date_started = models.DateTimeField()
class Employee(models.Model):
name = models.CharField(max_length=200)
project = models.ForeignKey(Project)
class AddEmployeeForm(ModelForm):
class Meta:
model = Employee
exclude = ('project',)
My view:
def emp_add(request, project_id):
if request.method == 'POST':
post = request.POST.copy() # make the POST QueryDict mutable
post('project', project_id)
form = AddEmployeeForm(post)
if form.is_valid():
saved = form.save()
A: Like this?
if form.is_valid():
employee = form.save(commit=False)
employee.project = Project.objects.get(pk=project_id)
employee.save()
A: @maciag.artur's answer, to save with commit=False will work. Another way is to instantiate an Employee with the required project_id, and use it to construct the form.
This is useful if your model form's custom clean method relies on the Employee.project field.
def emp_add(request, project_id)
if request.method == 'POST':
# create a new employee with the given project id
employee = Employee(project_id) = project_id
form = AddEmployeeForm(request.POST, instance=employee)
if form.is_valid():
saved = form.save()
<snip>
For reference, see the note box below Using a subset of fields on the form in the Django docs.
A: Add the project ID to the form as a hidden input. When the request comes back as a POST, it will exist in the POST object, from the form.
def emp_add(request, project_id):
if request.method == 'POST':
post = request.POST.copy() # make the POST QueryDict mutable
post('project', project_id)
form = AddEmployeeForm(post)
if form.is_valid():
saved = form.save()
else:
form = AddEmployeeForm(initial={'project_id':'my_id_value'})
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572537",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why does getWritableDatabase crashes on some devices? (sqlite3_open_v2 ... Failed) My application uses a database and works pretty well on all Android devices.
Recently some users pointed that it crashes on HTC Tattoo. I decided to give a try and got one in loan.
So, the error come when I call: this.getWritableDatabase();
09-27 18:26:22.292: ERROR/Database(1537): sqlite3_open_v2("/data/data/com.xxx.xxx/databases/radars.db", &handle, 6, NULL) failed
09-27 18:26:22.292: WARN/System.err(1537): android.database.sqlite.SQLiteException: unable to open database file
And I have checked, the Database is in the device:
I really cannot understand what happens....
Thank a lot for your help!
EDIT:
As noticed by LAS_VEGAS
# sqlite3 /data/data/com.xxx.xxx/databases/radars.db
Gives this result:
sqlite3: not found
Seem that the HTC Tattoo has serious SQL issues:
adb shell
# cd /system/xbin
# ls | grep sqlite3
//Nothing//
A: This is weird. I think this could happen when you try to access database file from multiple threads simultaneously. Could it be the case?
Also for testing purposes did you try getReadableDatabase(), maybe it gives a clue...
EDIT:
Can you access from remote shell?:
http://developer.android.com/guide/developing/tools/adb.html#sqlite
EDIT2:
So it seems that HTC tattoo has no sqlite3.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572539",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: htaccess - do not rewrite in this case My access file looks like this:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
But I have a directory called facebook that I want to access as usuall through the URL http://mysite.com/facebook. What do I need to add to the above so that it ignores (does not rewrite) this directory?
A: add:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteCond %{REQUEST_URI} !^/facebook
RewriteRule ^.*$ index.php [NC,L]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572540",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Can't understand ps | wc output differences I was trying to write a set of functions that could check to see if a process name was running when I encountered some unexpected output. I've condensed the issue in the following script names isRunning.sh which depends on a system ps command that can take the '-fC' arguments...
#!/bin/bash
progname=isRunning.sh
ps -fC isRunning.sh
pRet=`ps -fC ${progname} | wc -l`
echo pRet $pRet
psOut=`ps -fC ${progname}`
wcOut=`echo "${psOut}" | wc -l`
echo
echo ps output
echo "${psOut}"
echo
echo wcOut $wcOut
The first attempt at piping the ps output to wc gets a return of 3. The second attempt gets the expected return value of 2. Can anyone explain this behavior? I figure it's got to be something stupid I am overlooking.
Thanks,
bbb
edit: my output
UID PID PPID C STIME TTY TIME CMD
root 6717 5940 0 13:10 pts/0 00:00:00 /bin/bash ./isRunning.sh
pRet 3
ps output
UID PID PPID C STIME TTY TIME CMD
root 6717 5940 0 13:10 pts/0 00:00:00 /bin/bash ./isRunning.sh
wcOut 2
A: I get 2 both attempts. Your ps might be outputting an extra blank line, or somesuch, and then your shell's backtick expansion stripping it. Or maybe you actually had two processes matching the first time you ran it.
If you just want to see if its running, check the exit code from your ps:
if ps -C "${progname}" > /dev/null; then
echo its running
else
echo not running
fi
Even better, you should take a look at pidof and pgrep if you can rely on them being present on whichever systems you're targeting. Or use the LSB functions, if you're on Linux.
edit: Actually, since you're looking for copies of yourself running, you might be picking up the shell doing a fork to implement the pipe.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572544",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: after user clicks allow, the browser is redirected to my server, without facebook iframe im implementing my own php facebook sdk. it works fine, but i'm still fighting with the oauth flow.
what i have now:
check if user has allowed my application and permissions
if not - show the dialog to login and accept permissions. this is all ok, but after clicking allow the browser is redirected to https://mydomain.com/?code=CODe...
i can then get the access token and everything but i would like that the facebook iframe stays there.
A: You're specifying the URL yourself as part of the auth process - if you want to send them to your app's canvas, use that as the URL.
If you're using the PHP SDK you're probably using the result of 'getLoginUrl()' - check how that works and choose another URL instead, bearing in mind the URL must be 'owned' by your app or it can't be used
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572551",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: compute rounded in cobol I am confused with the rounded in the compute function in cobol.
Declaration:
VAR-A PIC S9(9)V99 COMP-3.
VAR-B PIC S9(9)V9(6) COMP-3.
Procedure.
MOVE +12.08 TO VAR-A.
MOVE +6.181657 TO VAR-B.
COMPUTE VAR-A ROUNDED = VAR-A + VAR-B.
Will the result of VAR-A be 18.27 or 18.26? What would cobol do upon computing?
Would it round VAR-B first to the decimal places specified in VAR-A or will cobol add the 2 variables then round them up to the decimal places specified in VAR-A?
Any help will be appreciated.
@NealB,
How about this example:
DECLARATION:
01 VAR-ARRAY OCCURS 22 TIMES.
03 VAR-A PIC S9(9)V9(6) COMP-3.
01 VAR-B PIC S9(9)V99 COMP-3.
Supposing VAR-A is an array, and the following are its values:
VAR-A(01) = 123.164612
VAR-A(02) = 12.07865
VAR-A(03) = 6.181657
VAR-A(04) = 1.744353
VAR-A(05) = 6.118182
VAR-A(06) = 1.744353
VAR-A(07) = 6.158715
VAR-A(08) = 1.744353
VAR-A(09) = 6.194759
VAR-A(10) = 1.744353
VAR-A(11) = 3.037896
VAR-A(12) = 1.743852
VAR-A(13) = 6.14653
VAR-A(14) = 1.744353
VAR-A(15) = 0.000377
VAR-A(16) = 1.743852
VAR-A(17) = 6.144363
VAR-A(18) = 1.743852
VAR-A(19) = 0.007649
VAR-A(20) = 1.744353
VAR-A(21) = 0.000377
VAR-A(22) = 1.744353
VAR-B's value is:
VAR-B = 405.25
PROCEDURE:
PERFORM VAR-IDX FROM 1 BY 1 UNTIL VAR-IDX > 22
COMPUTE VAR-B ROUNDED = VAR-B + VAR-A(VAR-IDX)
END-PERFORM.
Why do I get 597.87 for VAR-B as a result after the computation?
A: I believe the default COBOL rounding behaviour is: Nearest away from zero.
COMPUTE VAR-A ROUNDED = VAR-A + VAR-B
should result in VAR-A containing 18.26
Rounding occurs after the expression has been evaluated. A more interesting example might be:
01 VAR-A PIC S9(9)V99 COMP-3.
01 VAR-B PIC S9(9)V9(6) COMP-3.
01 VAR-C PIC S9(9)V9(6) COMP-3.
MOVE +12.08 TO VAR-A.
MOVE +06.182000 TO VAR-B.
MOVE +00.004000 TO VAR-C.
COMPUTE VAR-A ROUNDED = VAR-A + VAR-B + VAR-C.
The result is 18.27. Rounding VAR-B and VAR-C to 2 decimal places before doing the addition would have yielded 18.26 because VAR-B rounds to 6.18 and VAR-C rounds to 0.00. The result is actually 18.27 so the rounding occurs after evaluation of the expression.
Reply to edited question
Not pretty output, but this is how my calculation goes using IBM Enterprise COBOL for z/OS
VAR-IDX = 01 VAR-B = +405.25 VAR-A = +123.164612 VAR-B + VAR-A = +528.41
VAR-IDX = 02 VAR-B = +528.41 VAR-A = +012.078650 VAR-B + VAR-A = +540.49
VAR-IDX = 03 VAR-B = +540.49 VAR-A = +006.181657 VAR-B + VAR-A = +546.67
VAR-IDX = 04 VAR-B = +546.67 VAR-A = +001.744353 VAR-B + VAR-A = +548.41
VAR-IDX = 05 VAR-B = +548.41 VAR-A = +006.118182 VAR-B + VAR-A = +554.53
VAR-IDX = 06 VAR-B = +554.53 VAR-A = +001.744353 VAR-B + VAR-A = +556.27
VAR-IDX = 07 VAR-B = +556.27 VAR-A = +006.158715 VAR-B + VAR-A = +562.43
VAR-IDX = 08 VAR-B = +562.43 VAR-A = +001.744353 VAR-B + VAR-A = +564.17
VAR-IDX = 09 VAR-B = +564.17 VAR-A = +006.194759 VAR-B + VAR-A = +570.36
VAR-IDX = 10 VAR-B = +570.36 VAR-A = +001.744353 VAR-B + VAR-A = +572.10
VAR-IDX = 11 VAR-B = +572.10 VAR-A = +003.037896 VAR-B + VAR-A = +575.14
VAR-IDX = 12 VAR-B = +575.14 VAR-A = +001.743852 VAR-B + VAR-A = +576.88
VAR-IDX = 13 VAR-B = +576.88 VAR-A = +006.146530 VAR-B + VAR-A = +583.03
VAR-IDX = 14 VAR-B = +583.03 VAR-A = +001.744353 VAR-B + VAR-A = +584.77
VAR-IDX = 15 VAR-B = +584.77 VAR-A = +000.000377 VAR-B + VAR-A = +584.77
VAR-IDX = 16 VAR-B = +584.77 VAR-A = +001.743852 VAR-B + VAR-A = +586.51
VAR-IDX = 17 VAR-B = +586.51 VAR-A = +006.144363 VAR-B + VAR-A = +592.65
VAR-IDX = 18 VAR-B = +592.65 VAR-A = +001.743852 VAR-B + VAR-A = +594.39
VAR-IDX = 19 VAR-B = +594.39 VAR-A = +000.007649 VAR-B + VAR-A = +594.40
VAR-IDX = 20 VAR-B = +594.40 VAR-A = +001.744353 VAR-B + VAR-A = +596.14
VAR-IDX = 21 VAR-B = +596.14 VAR-A = +000.000377 VAR-B + VAR-A = +596.14
VAR-IDX = 22 VAR-B = +596.14 VAR-A = +001.744353 VAR-B + VAR-A = +597.88
FINAL RESULT = +597.88
A: It depends on the intermediate rounding and the final rounding set.
see this for more info :
D.13a Rounding
COBOL provides the capability of specifying rounding in arithmetic statements and expressions at various points in the evaluation process and as values are prepared for storing in receiving data items.
There are eight different forms of rounding supported by this standard:
• AWAY-FROM-ZERO: Rounding is to the nearest value of larger magnitude.
• NEAREST-AWAY-FROM-ZERO: Rounding is to the nearest value. If two values are equally near, the value with the larger magnitude is selected. This mode has historically been associated with the ROUNDED clause in previous versions of standard COBOL.
• NEAREST-EVEN: Rounding is to the nearest value. If two values are equally near, the value whose rightmost digit is even is selected. This mode is sometimes called “Banker’s rounding”.
• NEAREST-TOWARD-ZERO: Rounding is to the nearest value. If two values are equally near, the value with the smaller magnitude is selected.
• PROHIBITED: Since the value cannot be represented exactly in the desired format, the EC-SIZE-TRUNCATION condition is set to exist and the results of the operation are undefined.
• TOWARD-GREATER: Rounding is toward the nearest value whose algebraic value is larger.
• TOWARD-LESSER: Rounding is toward the nearest value whose algebraic value is smaller.
• TRUNCATION: Rounding is to the nearest value whose magnitude is smaller. This mode has historically been associated with the absence of the ROUNDED clause as well as for the formation of intermediate results in the prior COBOL standard.
The programmer may specify how individual intermediate values are rounded when they are stored into receiving data items through the ROUNDED clause; may select a default mode of rounding to be used when the ROUNDED clause appears with no further qualification on a receiving data item through the DEFAULT ROUNDED MODE clause of the OPTIONS paragraph of the IDENTIFICATION DIVISION; and may specify how arithmetic operations and conversions to and from intermediate forms are rounded through the INTERMEDIATE ROUNDING clause.
D.13a.1 Intermediate rounding
Intermediate rounding applies when data items are retrieved for inclusion in an arithmetic operation or arithmetic expression, and during the execution of arithmetic operators to produce an intermediate result.
In the previous standard, for multiplication and division in Standard Arithmetic, the default mode of rounding for inexact results was truncation to 32 significant digits. This default is unchanged in this standard, and is also the default for Standard-Binary and Standard-Decimal arithmetic.
When the intermediate value can be represented exactly in the appropriate intermediate format, the exact value is used.
In the event the value cannot be exactly represented, the user may also now specify other modes of rounding for arithmetic operations and for the conversions to and from intermediate forms used in the arithmetic operations through the optional INTERMEDIATE ROUNDING clause of the OPTIONS paragraph of the IDENTIFICATION DIVISION.
Specifically, the following options are available:
• INTERMEDIATE ROUNDING IS NEAREST-AWAY-FROM-ZERO
• INTERMEDIATE ROUNDING IS NEAREST-EVEN
• INTERMEDIATE ROUNDING IS PROHIBITED
• INTERMEDIATE ROUNDING IS TRUNCATION
for which the subclause descriptions are found in D.13a, Rounding.
If the INTERMEDIATE ROUNDING clause is not specified, INTERMEDIATE ROUNDING IS TRUNCATION is presumed. This is unchanged from previous standards.
D.13a.2 Final rounding (the ROUNDED clause)
Final rounding applies to the formation of the final result of the expression or statement, at the completion of evaluation of the statement or expression, immediately before the result is placed in the destination. This form of rounding is that which is associated with the ROUNDED clause.
In previous COBOL standards, only two methods of “final” rounding were provided: rounding toward the smaller magnitude (truncation, signaled by the absence of the ROUNDED clause); and rounding to the nearest values, and if two values were equally near, choose the value with the larger magnitude (signaled by the presence of the ROUNDED clause).
The ROUNDED clause has been enhanced to allow explicit selection of any of eight modes of rounding (including the two previously available):
• ROUNDED MODE IS AWAY-FROM-ZERO
• ROUNDED MODE IS NEAREST-AWAY-FROM-ZERO
• ROUNDED MODE IS NEAREST-EVEN
• ROUNDED MODE IS NEAREST-TOWARD-ZERO
• ROUNDED MODE IS PROHIBITED
• ROUNDED-MODE IS TOWARD-GREATER
• ROUNDED MODE IS TOWARD-LESSER
• ROUNDED MODE IS TRUNCATION
If the ROUNDED clause is not present for a given result, the rules for ROUNDED MODE IS TRUNCATION apply.
The optional DEFAULT ROUNDED MODE clause in the OPTIONS paragraph of the IDENTIFICATION DIVISION is provided to allow the user to specify the mode of rounding to any operation for which the ROUNDED clause appears without the MODE IS subclause.
The DEFAULT ROUNDED MODE clause may take any of these forms:
• DEFAULT ROUNDED MODE IS AWAY-FROM-ZERO
• DEFAULT ROUNDED MODE IS NEAREST-AWAY-FROM-ZERO
• DEFAULT ROUNDED MODE IS NEAREST-EVEN
• DEFAULT ROUNDED MODE IS NEAREST-TOWARD-ZERO
• DEFAULT ROUNDED MODE IS PROHIBITED
• DEFAULT ROUNDED MODE IS TOWARD-GREATER
• DEFAULT ROUNDED MODE IS TOWARD-LESSER
• DEFAULT ROUNDED MODE IS TRUNCATION
for which the subclauses of the DEFAULT ROUNDED MODE is clause are described in D.13a, Rounding.
If the DEFAULT ROUNDED MODE clause does not appear in the program, the effect of the ROUNDED clause without the MODE IS subclause is as if ROUNDED MODE IS NEAREST AWAY FROM ZERO had been specified. This provides the same functionality available in prior COBOL standards.
If the DEFAULT ROUNDED MODE clause appears, ROUNDED clauses without the MODE IS subclause are treated as if they had been specified with the rounding mode specified in the DEFAULT ROUNDED MODE clause.
A: IDENTIFICATION DIVISION.
PROGRAM-ID. HELLO.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 VAR_NUM PIC 9(3)V9(02).
01 VAR_RESULT PIC 9(3).
PROCEDURE DIVISION.
MOVE 256.50 TO VAR_NUM.
COMPUTE VAR_NUM ROUNDED = VAR_NUM / 100.
MULTIPLY 100 BY VAR_NUM
MOVE VAR_NUM TO VAR_RESULT.
DISPLAY "Result : " VAR_RESULT.
STOP RUN.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572553",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Add count constraint to @XmlElement? So, I am back with another question for you fellas. I have a JAXB object which I am marshalling/de-marshalling from an XML file.
The code is something like:
@XmlAccessorType(XmlAccessType.FIELD)
public class Line {
@XmlElement(required = true)
@Min(1)
private int quantity;
...
}
My XML structure is:
<line>
<quantity>2</quantity>
</line>
Now the Java code accepts this too:
<line>
<quantity>2</quantity>
<quantity>2</quantity>
</line>
So, how should I program my constraints in a way that I accept only first xml and not the second.
Thanks again!
A: You should use an XSD and validate your xml against it.
We had to validate our xml files with an xsd corresponding to its version :
ValidationEventCollector vec = new ValidationEventCollector();
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
URL xsdURL = getClass().getResource("/xsd/" + xsd);
Schema schema = sf.newSchema(xsdURL);
//You should change your jaxbContext here for your stuff....
Unmarshaller um = (getJAXBContext(NotificationReponseEnum.NOTIFICATION, notificationWrapper.getEnteteNotification().getTypeNotification()))
.createUnmarshaller();
um.setSchema(schema);
try {
StringReader reader = new StringReader(xml);
um.setEventHandler(vec);
um.unmarshal(reader);
} catch (javax.xml.bind.UnmarshalException ex) {
if (vec != null && vec.hasEvents()) {
erreurs = new ArrayList<MessageErreur>();
for (ValidationEvent ve : vec.getEvents()) {
MessageErreur erreur = new MessageErreur();
String msg = ve.getMessage();
ValidationEventLocator vel = ve.getLocator();
int numLigne = vel.getLineNumber();
int numColonne = vel.getColumnNumber();
erreur.setMessage(msg);
msgErreur.setCode(ve.getSeverity())
erreur.setException(ve.getLinkedException());
erreur.setPosition(numLigne, numColonne);
erreurs.add(erreur);
logger.debug("Erreur de validation xml" + "erreur : " + numLigne + "." + numColonne + ": " + msg);
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572563",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Solution/Project name variable in TFS Build 2010 When creating a new build definition in TFS 2010 we specifiy a project or solution to build (Under the 'Required -> Items to Build' section in the 'Process' section of the definition.
Is there any way to get hold of the name of the solution being built in the Workflow scope? I.e. is the there a variable available with this information inside that I can pass into a custom code activity elsewhere within the work flow?
A: If you open the build workflow and tunnel down into Compile and Test, you'll see a For Each Project loop scope that shows the workflow variable assignment of BuildSettings.ProjectsToBuild as serverBuildProjectItem in an out of the box workflow. There's a task within the sub-sequence that translates that serverItem to a local path containing the proj file.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572567",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Knowing if a page is already liked on facebook
Possible Duplicate:
How to know if the user already like the page in Facebook Likebox?
Is there a way to know if a user likes the current page WITHOUT using asking the user for permissions?
The page has a like button and I am using the javascript to figure out when this button is clicked to show hidden content. However when the page is refreshed the button is shown as "liked" but the hidden content is still hidden.
Is there a javascript to know if the state of the facebook button is "Liked"?
A:
Is there a javascript to know if the state of the Facebook button is
"Liked" without app authorization/authentication on my web page (not FB page tab)?
NO, this is not possible.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572569",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: multiline string literals and tests var multiply = function (a, b) {
//An internal comment
return a * b;
};
var stupid = "function (a, b) {
return a * b;
}"
expect(multiply.toString()).toBe(stupid);
The test passes, but firefox gives me this:
unterminated string literal
[Break On This Error] var stupid = "function (a, b) {
Changing the code to use the \ line terminator stops the test from passing.
Expected 'function (a, b) {
return a * b;
}' to be 'function (a, b) {return a * b;}'.
The test fails if you escape the multiline string literal.
With newlines, the test still does not pass:
var stupid = "function (a, b) {\n
return a * b;\n
}"
expect(multiply.toString()).toBe(stupid);
A: Without the backslashes, it's a syntax error. More about string literals in this HTML transcription of the spec.
With them, remember that all leading space on subsequent lines is included in the string.
Separately: Your expect call will not be reliable. First off, Function#toString has never been standardized anywhere (certainly not by the ECMAScript standard). Secondly, it works differently on different engines (some will include comments, others won't; some will reformat the code [so for instance, there may not be a space after function], others won't; etc.).
A: Your test is not passing; it's giving that syntax error.
Javascript does not support (unescaped) multi-line string literals.
With the \ escapes, it's not passing because your string has no newlines.
The Javsacript source
"1\
2"
Is evaluated to "12". Escaped newlines are ignored; they don't become newlines.
You need to add \n characters.
A: you have to use
var stupid = "function (a, b) {" +
+ "return a * b;" +
+ "}";
because javascript does not support multiline string literals, as SLaks pointed out
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572572",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Java JNDI lookup to Microsoft Active Directory (using Tomcat 6), authentication failing The idea is to perform an authentication (basic form with username + password) by configuring my Tomcat 6 container so that it connects (using JNDI Realm) to Microsoft Active Directory to check whether or not credentials are correct.
I have found quite a few documentation on the subject but I fail to configure the Realm properly I believe.
This is the documentation I found on Oracle's website (which happens to be the same since Tomcat 4) http://tomcat.apache.org/tomcat-6.0-doc/realm-howto.html#JNDIRealm
Found this Oracle doc pretty poor but came across other websites such as this one http://www.jspwiki.org/wiki/ActiveDirectoryIntegration which elaborate on the subject.
However after many attempts I still cannot authenticate successfully:
*
*When I start Tomcat, everything seems fine, no WARNING or any other error message appears.
*When I try to authenticate, I am consistently redirected to my error page. And no WARNING or any other message appears.
These are 2 of the Realm configs I tried
<Realm className="org.apache.catalina.realm.JNDIRealm" debug="99"
connectionName="test"
connectionPassword="test"
connectionURL="LDAP://subDomain.myDomain.co.uk:389"
userPattern="uid={0},ou=London,dc=subDomain,dc=myDomain,dc=co,dc=uk"
roleBase="ou=London,dc=subDomain,dc=myDomain,dc=co,dc=uk"
roleName="cn"
roleSearch="memberUid={1}"
/>
<Realm className="org.apache.catalina.realm.JNDIRealm" debug="99"
connectionName="test"
connectionPassword="test"
connectionURL="LDAP://subDomain.myDomain.co.uk:389"
userBase="ou=London,dc=subDomain,dc=myDomain,dc=co,dc=uk"
userSearch="(sAMAccountName={0})"
roleBase="ou=Groups,dc=subDomain,dc=myDomain,dc=co,dc=uk"
roleName="cn"
roleSubtree="true"
roleSearch="(member={0})"
/>
I have tested the connection credential using an LDAP browser and they are fine.
This is my web.xml
<web-app>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<security-constraint>
<display-name>Example Security Constraint</display-name>
<web-resource-collection>
<web-resource-name>Protected Pages</web-resource-name>
<url-pattern>/protected/*</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>London</role-name>
</auth-constraint>
</security-constraint>
<!-- Default a login configuration that uses form-based authentication -->
<login-config>
<auth-method>FORM</auth-method>
<realm-name>DBRealm</realm-name>
<form-login-config>
<form-login-page>/WEB-INF/login.jsp</form-login-page>
<form-error-page>/WEB-INF/error.jsp</form-error-page>
</form-login-config>
</login-config>
<!-- Define a logical role for this application, needs to be mapped to an actual role at deployment time -->
<security-role>
<description>All Users</description>
<role-name>London</role-name>
</security-role>
</web-app>
Thanks in advance,
A.
A: Are you using the uid or memberUid attributes in AD? Those are atypical.
You probably want to replace the uid= in your userPattern with cn=.
For roleSearch, that's probably actually supposed to be member=.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572574",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to Call a View Helper Method in JavaScript using Rails 3.1 I'm working on a simple app that needs to render a time. But the time must be formatted the way time_ago_in_words helper does. I'm getting the time data from a JSON object. Is it possible to trigger a view helper (time_ago_in_words) inside a JavaScript file? I'm using Rails 3.1
Thanks.
A: You can't do it from inside a javascript function.
Ideally you would want a JSON equivalent to XML Builder where you could call the view helper methods from inside a .builder partial.
This gem provides similar functionality https://github.com/lassebunk/api_builder.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572576",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to convert list of objects to list of interfaces? I have some class that works with interfaces:
Here is the interface:
public interface Orderable
{
int getOrder()
void setOrder()
}
Here is the worker class:
public class Worker
{
private List<Orderable> workingList;
public void setList(List<Orderable> value) {this.workingList=value;}
public void changePlaces(Orderable o1,Orderable o2)
{
// implementation that make o1.order=o2.order and vice versa
}
}
Here is an object that implements the interface:
public class Cat implements Orderable
{
private int order;
public int getOrder()
{
return this.order;
}
public void setOrder(int value)
{
this.order=value;
}
public Cat(String name,int order)
{
this.name=name;
this.order=order;
}
}
In the main procedure I create a list of cats. I use glazed lists to dynamically update controls when the list is changed and when a control model is created with this list.
The goal is to transfer this list to a worker object, so I can add some new cat to the list in the main procedure, and the worker will know about it without setting its list property again (list is same object in main proc and in worker). But when I call worker.setList(cats) it alerts about expecting an Orderable, but getting a Cat... but Cat implements Orderable. How do I solve this?
Here is the main code:
void main()
{
EventList<Cat> cats=new BasicEventList<Cat>();
for (int i=0;i<10;i++)
{
Cat cat=new Cat("Maroo"+i,i);
cats.add(cat);
}
Worker worker=new Worker();
worker.setList(cats); // wrong!
// and other very useful code
}
A: It should work if you just change the declaration of cats:
List<? extends Orderable> cats = new BasicEventList<? extends Orderable>();
for (int i=0; i<10; i++)
{
cats.add(new Cat("Maroo"+i, i));
}
Worker worker = new Worker();
worker.setList(cats);
See:
*
*Why can't a method take a Collection<subClass> when the method's signature is defined as Collection<class>
*Can I add to a generic collection of type A values of type B ,which extends A, without any special syntax?
*Java Collections: Pass collection of children as collection of parents
*How to cast a list of inheriting objects to a collection of objects in Java?
*and many others...
A: You need to change the Worker class so that it accepts List<? extends Orderable>
public class Worker
{
private List<? extends Orderable> workingList;
public void setList(List<? extends Orderable> value) {this.workingList=value;}
public void changePlaces(Orderable o1,Orderable o2)
{
// implementation that make o1.order=o2.order and vice verca
}
}
A: If you really would like a new collection of the interface type. When for instance you don't own the methods you are calling.
//worker.setList(cats);
worker.setList( new ArrayList<Orderable>(cats)); //create new collection of interface type based on the elements of the old one
A: void main()
{
EventList<Orderable> cats = new BasicEventList<Orderable>();
for (int i=0;i<10;i++)
{
Cat cat=new Cat("Maroo"+i,i);
cats.add(cat);
}
Worker worker=new Worker();
worker.setList(cats); // should be fine now!
// and other very usefull code
}
Mostly, just construct a list of Orderables right away, since cat implements Orderable, you should be able to add a cat to the list.
note: this is me quickly guessing
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572581",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "42"
}
|
Q: Integrating CakePHP and Sage Pay (Protx) I am needing to integrate Sage Pay on our website to accept online payments.
I have downloaded and tested the PHP kit provided by Sage and have run a few successful tests, however, I don't know where to start when it comes to integrating this with Cake PHP.
If anybody has some initial pointers or ideas, or even links (multiple, varied Google searches yielded nothing) that would be great ...
Many thanks,
Dave
Hi there,thanks for the reply, and apologies for the delayed replying myself. I have it all working now, except my final issue as that I need to parse the final response returned from SagePay. The demo has the following code in the final step that gets posted to my site (to an action), The code they have is as follows:
...
$strVPSSignature=$_REQUEST["VPSSignature"];
$strStatusDetail=$_REQUEST["StatusDetail"];
...
Obviously this won't work due to Cake's routing. How do you suggest I parse these value>
Thanks again.
Dave
A: Haven't used Sagepay but a few pointers anyway:
*
*Third party PHP classes should be loaded as vendors, so that is what I would do with their PHP kit.
*This guy thinks SagePay's kit is a mess so you might find using his classes is easier to grok.
Although some might say payments belong in the business layer (your model), you might find it easier to initially perform payments from the controller layer. As such, I would start by creating a simple component with the inputs and outputs you need (methods/parameters/return values) and use it as a wrapper for the SagePay vendor of your choice. This will help keep your controller actions skinny. You can refactor later to your taste once you get things working.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572582",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Conditional SQL SELECT - when return set is empty, execute another SELECT? I have webpage that has its "pages/articles" stored in a MySQL database. It also has a feature to show a different side menu for different pages. All that (menus, menu's items) is stored in DB.
Here's my SQL for getting all menu items for current page:
SELECT *
FROM menu_items
JOIN pages
ON menu_items.menu_id=pages.right_menu_id
WHERE pages.link = "some_link"
and it works.
What I want is, when this query returns an empty set, to execute another query and get its result instead. Is it possible ?? If query mentioned above is empty, I would like to get result of this query:
SELECT *
FROM menu_items
WHERE menu_id=2;
Is it possible, or should I just do it in PHP ?
A: You could use the EXIST function to test whether the current page has any links:
IF EXISTS(SELECT menu_id FROM menu_items JOIN pages ON menu_items.menu_id = pages.right_menu_id WHERE pages.link = "some_link") THEN
SELECT *
FROM menu_items
JOIN pages
ON menu_items.menu_id=pages.right_menu_id
WHERE pages.link = "some_link"
ELSE
SELECT *
FROM menu_items
JOIN pages
ON menu_items.menu_id=pages.right_menu_id
WHERE menu_id = 2
END IF
You could also try something like this:
DECLARE @LinkCount INT
SELECT @LinkCount = COUNT(*) FROM menu_items JOIN pages ON menu_items.menu_id = pages.right_menu_id WHERE pages.link = "some_link"
SELECT *
FROM menu_items
JOIN pages
ON menu_items.menu_id=pages.right_menu_id
WHERE (@LinkCount > 0 AND pages.link = "some_link") OR (@LinkCount = 0 AND menu_id = 2)
There might be more elegant ways of doing this, but hope this helps.
A: Perhaps this is not the most elegant way:
SELECT *
FROM
menu_items
JOIN pages ON menu_items.menu_id = pages.right_menu_id
WHERE pages.link = "some_link"
UNION ALL
SELECT *, NULL, NULL, NULL
FROM menu_items
WHERE
menu_id = 2 AND
NOT EXISTS (
SELECT *
FROM
menu_items
JOIN pages ON menu_items.menu_id = pages.right_menu_id
WHERE pages.link = "some_link"
)
Note: Number of NULLs should be the same as number of columns in table pages.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572584",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to get the Image Width and Height? i have one image url(Online url), now i want this image height and width, how can i get this, it's greatly appreciate if anyone answer this
*
*i want to preview the image with 150px height and 150px width, so i set it up in aspx page height-150 and width-150 for img tag
*if i assign the above url to img src, it will throw the 150px width and 150px height, but i need the original height and width of the above url image
*if i didn't set it up anything for the img tag i will get 0px of height and 0px of width
Can anyone suggest this please?
A: if you have the url,you can set up the url as a DIV element's background-image.
and you can display the background whatever you want.
A: You can use the naturalWidth and naturalHeight properties of the img object.
See here: Determine original size of image cross browser?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572590",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Error in in visual studio 2010 professional installation i try to install visual studio 2010 professional but i am getting error and it is log file.
>
[09/27/11,21:21:50] Microsoft Application Error Reporting: [2] Error: Installation failed for component Microsoft Application Error Reporting. MSI returned error code 2
[09/27/11,21:21:51] VS70pgui: [2] DepCheck indicates Microsoft Application Error Reporting is not installed.
[09/27/11,21:21:52] VS70pgui: [2] DepCheck indicates VC 9.0 Runtime (x86) was not attempted to be installed.
[09/27/11,21:21:52] VS70pgui: [2] DepCheck indicates VC 10.0 Runtime (x86) was not attempted to be installed.
[09/27/11,21:21:52] VS70pgui: [2] DepCheck indicates VC 10.0 Runtime (x64) was not attempted to be installed.
[09/27/11,21:21:52] VS70pgui: [2] DepCheck indicates Microsoft .NET Framework 4 was not attempted to be installed.
[09/27/11,21:21:52] VS70pgui: [2] DepCheck indicates Microsoft Visual Studio 2010 64bit Prerequisites (x64) was not attempted to be installed.
[09/27/11,21:21:52] VS70pgui: [2] DepCheck indicates Microsoft Visual F# 2.0 Runtime was not attempted to be installed.
[09/27/11,21:21:53] VS70pgui: [2] DepCheck indicates Microsoft Visual Studio Macro Tools was not attempted to be installed.
[09/27/11,21:21:53] VS70pgui: [2] DepCheck indicates TFS Object Model (x64) was not attempted to be installed.
[09/27/11,21:21:53] VS70pgui: [2] DepCheck indicates .NET Framework 4 Multi-Targeting Pack was not attempted to be installed.
[09/27/11,21:21:53] VS70pgui: [2] DepCheck indicates Microsoft Visual Studio 2010 Professional - ENU was not attempted to be installed.
[09/27/11,21:21:53] VS70pgui: [2] DepCheck indicates Microsoft Web Deployment Tool (x64) was not attempted to be installed.
[09/27/11,21:21:53] VS70pgui: [2] DepCheck indicates Microsoft ASP.NET MVC 2 - Visual Studio 2010 Tools was not attempted to be installed.
[09/27/11,21:21:53] VS70pgui: [2] DepCheck indicates Microsoft ASP.NET MVC 2 was not attempted to be installed.
[09/27/11,21:21:53] VS70pgui: [2] DepCheck indicates Microsoft Silverlight was not attempted to be installed.
[09/27/11,21:21:53] VS70pgui: [2] DepCheck indicates Microsoft Silverlight 3 SDK was not attempted to be installed.
[09/27/11,21:21:54] VS70pgui: [2] DepCheck indicates Microsoft Visual Studio 2010 Tools for Office Runtime (x64) was not attempted to be installed.
[09/27/11,21:21:54] VS70pgui: [2] DepCheck indicates Microsoft Office Developer Tools (x64) was not attempted to be installed.
[09/27/11,21:21:54] VS70pgui: [2] DepCheck indicates Dotfuscator Software Services - Community Edition was not attempted to be installed.
[09/27/11,21:21:54] VS70pgui: [2] DepCheck indicates Crystal Reports templates for Visual Studio 2010 was not attempted to be installed.
[09/27/11,21:21:54] VS70pgui: [2] DepCheck indicates Microsoft SQL Server Compact 3.5 SP2 (x86) ENU was not attempted to be installed.
[09/27/11,21:21:54] VS70pgui: [2] DepCheck indicates Microsoft SQL Server Compact 3.5 SP2 (x64) ENU was not attempted to be installed.
[09/27/11,21:21:54] VS70pgui: [2] DepCheck indicates Visual Studio 2010 Tools for SQL Server Compact 3.5 SP2 ENU was not attempted to be installed.
[09/27/11,21:21:54] VS70pgui: [2] DepCheck indicates Microsoft Sync Framework Runtime v1.0 (x64) ENU was not attempted to be installed.
[09/27/11,21:21:54] VS70pgui: [2] DepCheck indicates Microsoft Sync Services for ADO.NET v2.0 (x64) ENU was not attempted to be installed.
[09/27/11,21:21:55] VS70pgui: [2] DepCheck indicates Microsoft Sync Framework Services v1.0 (x64) ENU was not attempted to be installed.
[09/27/11,21:21:55] VS70pgui: [2] DepCheck indicates Microsoft Sync Framework SDK v1.0 (x64) ENU was not attempted to be installed.
[09/27/11,21:21:55] VS70pgui: [2] DepCheck indicates VC 10.0 Designtime (x64) was not attempted to be installed.
[09/27/11,21:21:55] VS70pgui: [2] DepCheck indicates Microsoft SQL Publishing Wizard 1.4 was not attempted to be installed.
[09/27/11,21:21:55] VS70pgui: [2] DepCheck indicates Microsoft SQL Server System CLR Types was not attempted to be installed.
[09/27/11,21:21:55] VS70pgui: [2] DepCheck indicates Microsoft SQL Server System CLR Types (x64) was not attempted to be installed.
[09/27/11,21:21:55] VS70pgui: [2] DepCheck indicates Microsoft SQL Server 2008 R2 Management Objects was not attempted to be installed.
[09/27/11,21:21:55] VS70pgui: [2] DepCheck indicates Microsoft SQL Server 2008 R2 Management Objects (x64) was not attempted to be installed.
[09/27/11,21:21:55] VS70pgui: [2] DepCheck indicates Microsoft SQL Server 2008 Express Service Pack 1 (x64) was not attempted to be installed.
[09/27/11,21:21:55] VS70pgui: [2] DepCheck indicates Microsoft SQL Server 2008 R2 Data-Tier Application Framework was not attempted to be installed.
[09/27/11,21:21:56] VS70pgui: [2] DepCheck indicates Microsoft SQL Server 2008 R2 Data-Tier Application Project was not attempted to be installed.
[09/27/11,21:21:56] VS70pgui: [2] DepCheck indicates Microsoft SQL Server 2008 R2 Transact-SQL Language Service was not attempted to be installed.
[09/27/11,21:21:56] VS70pgui: [2] DepCheck indicates Microsoft SharePoint Developer Tools was not attempted to be installed.
[09/27/11,21:21:56] VS70pgui: [2] DepCheck indicates Microsoft Visual Studio 2010 ADO.NET Entity Framework Tools was not attempted to be installed.
[09/27/11,21:21:56] VS70pgui: [2] DepCheck indicates Microsoft Help Viewer 1.0 x64 was not attempted to be installed.
[09/27/11,21:23:51] Microsoft Application Error Reporting: [2] Error: Installation failed for component Microsoft Application Error Reporting. MSI returned error code 2
[09/27/11,21:23:52] VS70pgui: [2] DepCheck indicates Microsoft Application Error Reporting is not installed.
[09/27/11,21:23:52] VS70pgui: [2] DepCheck indicates VC 9.0 Runtime (x86) was not attempted to be installed.
[09/27/11,21:23:52] VS70pgui: [2] DepCheck indicates VC 10.0 Runtime (x86) was not attempted to be installed.
[09/27/11,21:23:53] VS70pgui: [2] DepCheck indicates VC 10.0 Runtime (x64) was not attempted to be installed.
[09/27/11,21:23:53] VS70pgui: [2] DepCheck indicates Microsoft .NET Framework 4 was not attempted to be installed.
[09/27/11,21:23:53] VS70pgui: [2] DepCheck indicates Microsoft Visual Studio 2010 64bit Prerequisites (x64) was not attempted to be installed.
[09/27/11,21:23:53] VS70pgui: [2] DepCheck indicates Microsoft Visual F# 2.0 Runtime was not attempted to be installed.
[09/27/11,21:23:53] VS70pgui: [2] DepCheck indicates Microsoft Visual Studio Macro Tools was not attempted to be installed.
[09/27/11,21:23:53] VS70pgui: [2] DepCheck indicates TFS Object Model (x64) was not attempted to be installed.
[09/27/11,21:23:53] VS70pgui: [2] DepCheck indicates .NET Framework 4 Multi-Targeting Pack was not attempted to be installed.
[09/27/11,21:23:53] VS70pgui: [2] DepCheck indicates Microsoft Visual Studio 2010 Professional - ENU was not attempted to be installed.
[09/27/11,21:23:53] VS70pgui: [2] DepCheck indicates Microsoft Web Deployment Tool (x64) was not attempted to be installed.
[09/27/11,21:23:53] VS70pgui: [2] DepCheck indicates Microsoft ASP.NET MVC 2 - Visual Studio 2010 Tools was not attempted to be installed.
[09/27/11,21:23:53] VS70pgui: [2] DepCheck indicates Microsoft ASP.NET MVC 2 was not attempted to be installed.
[09/27/11,21:23:54] VS70pgui: [2] DepCheck indicates Microsoft Silverlight was not attempted to be installed.
[09/27/11,21:23:54] VS70pgui: [2] DepCheck indicates Microsoft Silverlight 3 SDK was not attempted to be installed.
[09/27/11,21:23:54] VS70pgui: [2] DepCheck indicates Microsoft Visual Studio 2010 Tools for Office Runtime (x64) was not attempted to be installed.
[09/27/11,21:23:54] VS70pgui: [2] DepCheck indicates Microsoft Office Developer Tools (x64) was not attempted to be installed.
[09/27/11,21:23:54] VS70pgui: [2] DepCheck indicates Dotfuscator Software Services - Community Edition was not attempted to be installed.
[09/27/11,21:23:54] VS70pgui: [2] DepCheck indicates Crystal Reports templates for Visual Studio 2010 was not attempted to be installed.
[09/27/11,21:23:54] VS70pgui: [2] DepCheck indicates Microsoft SQL Server Compact 3.5 SP2 (x86) ENU was not attempted to be installed.
[09/27/11,21:23:54] VS70pgui: [2] DepCheck indicates Microsoft SQL Server Compact 3.5 SP2 (x64) ENU was not attempted to be installed.
[09/27/11,21:23:54] VS70pgui: [2] DepCheck indicates Visual Studio 2010 Tools for SQL Server Compact 3.5 SP2 ENU was not attempted to be installed.
[09/27/11,21:23:54] VS70pgui: [2] DepCheck indicates Microsoft Sync Framework Runtime v1.0 (x64) ENU was not attempted to be installed.
[09/27/11,21:23:54] VS70pgui: [2] DepCheck indicates Microsoft Sync Services for ADO.NET v2.0 (x64) ENU was not attempted to be installed.
[09/27/11,21:23:55] VS70pgui: [2] DepCheck indicates Microsoft Sync Framework Services v1.0 (x64) ENU was not attempted to be installed.
[09/27/11,21:23:55] VS70pgui: [2] DepCheck indicates Microsoft Sync Framework SDK v1.0 (x64) ENU was not attempted to be installed.
[09/27/11,21:23:55] VS70pgui: [2] DepCheck indicates VC 10.0 Designtime (x64) was not attempted to be installed.
[09/27/11,21:23:55] VS70pgui: [2] DepCheck indicates Microsoft SQL Publishing Wizard 1.4 was not attempted to be installed.
[09/27/11,21:23:55] VS70pgui: [2] DepCheck indicates Microsoft SQL Server System CLR Types was not attempted to be installed.
[09/27/11,21:23:55] VS70pgui: [2] DepCheck indicates Microsoft SQL Server System CLR Types (x64) was not attempted to be installed.
[09/27/11,21:23:55] VS70pgui: [2] DepCheck indicates Microsoft SQL Server 2008 R2 Management Objects was not attempted to be installed.
[09/27/11,21:23:55] VS70pgui: [2] DepCheck indicates Microsoft SQL Server 2008 R2 Management Objects (x64) was not attempted to be installed.
[09/27/11,21:23:55] VS70pgui: [2] DepCheck indicates Microsoft SQL Server 2008 Express Service Pack 1 (x64) was not attempted to be installed.
[09/27/11,21:23:55] VS70pgui: [2] DepCheck indicates Microsoft SQL Server 2008 R2 Data-Tier Application Framework was not attempted to be installed.
[09/27/11,21:23:56] VS70pgui: [2] DepCheck indicates Microsoft SQL Server 2008 R2 Data-Tier Application Project was not attempted to be installed.
[09/27/11,21:23:56] VS70pgui: [2] DepCheck indicates Microsoft SQL Server 2008 R2 Transact-SQL Language Service was not attempted to be installed.
[09/27/11,21:23:56] VS70pgui: [2] DepCheck indicates Microsoft SharePoint Developer Tools was not attempted to be installed.
[09/27/11,21:23:56] VS70pgui: [2] DepCheck indicates Microsoft Visual Studio 2010 ADO.NET Entity Framework Tools was not attempted to be installed.
[09/27/11,21:23:56] VS70pgui: [2] DepCheck indicates Microsoft Help Viewer 1.0 x64 was not attempted to be installed.
[IMG]http://i52.tinypic.com/11hcn0o.jpg[/IMG]
A: Are you installing over the network? There's at least some indication that you can solve this by copying the ISO locally, or that the ISO you are using is corrupted and needs to be re-downloaded..
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572591",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: SQL 2008 + IIS Application Pool: Failed to generate a user instance of SQL Server due to failure in retrieving the user's local application data path I´m having trouble connecting to SQL Server 2008 R2 Express with Northwind database using ApplicationPoolIdentity in IIS 7.5, resulting in the following error message:
Failed to generate a user instance of SQL Server due to failure in retrieving the user's local application data path. The connection will be closed.
notes:
*
*I´m using Windows 7/VS 2010/IIS 7.5/SQL Server 2008 R2 Express (all in the same machine).
*my site is using "ASP.NET v4.0" application pool;
*ASP.NET v4.0 application pool is using ApplicationPoolIdentity as Identity;
*the SQL Server 2008 R2 express has the Login "IIS APPPOOL\ASP.NETv4.0" with the server role sysadmin granted;
*the Northwind database has the user "IIS APPPOOL\ASP.NET v4.0" configured with the following permitions: db_accessadmin, db_backupoperator, db_datareader, db_datawriter, db_ddladmin, db_securityadmin;
*the w3wp.exe process is running with the user "IIS APPPOOL\ASP.NETv4.0"
*I can see that the user profile folder is created (C:\Users\ASP.NET v4.0);
*the same problem occurs using the application pool "DefaultAppPool".
If I change the ApplicationPoolIdentity user to another user that has rights to access the database it works.
Additional informations:
connection string:
<connectionStrings>
<add name="NorthwindEntities" connectionString="metadata=res://*/NorthwindModel.csdl|res://*/NorthwindModel.ssdl|res://*/NorthwindModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=NOTEBOOK\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
</connectionStrings>
Could anyone help me to solve this issue?
Thanks in advice.
A: It looks like you're trying to use SQL Server Express's "user instancing" feature, i.e. your connection string looks like:
AttachDBFilename=|DataDirectory|xxxxxx.mdf;User Instance=true
This won't work for ApplicationPoolIdentity accounts in IIS7.5. For more information see this MS Knowledgebase article:
Problems with SQL Server Express user instancing and ASP.net Web Application Projects
Web applications built with Visual Studio 2005, Visual Studio 2008, or
Visual Studio 2010 and that rely on user instancing with either SQL
Server Express 2005 or SQL Server Express 2008 do not work with the
new application pool identity. These products were developed and
tested against application pools running with the older NETWORK
SERVICE account.
Also Microsoft discourage using this feature now:
This feature will be removed in a future version of Microsoft SQL
Server. Avoid using this feature in new development work, and plan to
modify applications that currently use this feature.
If you've not already done so, I would attach the database to SQL Express and use a regular SQL connection string instead, just like you'd do in a production environment. You may need to enable TCP/IP for your SQL Express instance using the SQL Server Configuration Manager if it's not already enabled:
And ensure that port 1433 is configured as well on the next tab of that dialogue.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572594",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: serialport responding to EventHandler, but not ReadExisting or ReadLine? i have a program that's reading from serial port in c#. i need to quickly write to a port, read from it, then close it. i cannot leave it open. i understand that serial ports read and write slowly, I've tried to set the ReadTimeout and WriteTimeout properties high, and added a thread.Sleep to try to drag the read and write times out for the devices. here's a little bit of code:
my method to write to port:
private void CheckPorts(string testMessage)
{
foreach (string s in SerialPort.GetPortNames())
{
portNumber = Int32.Parse(s.Remove(0, 3));
testSerial = new SerialPort(s, baudRate, Parity.None, 8, StopBits.One);
if (testSerial.IsOpen)
{
testSerial.Close();
}
testSerial.ReadTimeout = 2000;
testSerial.WriteTimeout = 1000;
testSerial.Open();
if (testSerial.IsOpen)
{
string received;
testSerial.DiscardInBuffer();
try
{
//testSerial.DataReceived += new SerialDataReceivedEventHandler(testSerialPort_DataReceived);
testSerial.Write(testMessage);
System.Threading.Thread.Sleep(2000);
received = testSerial.ReadExisting(); //EITHER I USE THIS OR EVENT HANDLER, NOT BOTH
}
catch (TimeoutException e)
{
testSerial.Close();
continue;
}
if (received.Length > 0)
{
MessageReceived(received);
}
testSerial.Close();
}
}
}
private void testSerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string received = testSerial.ReadExisting();
int y = received.IndexOf("\r");
while (y == -1)
{
received = received + testSerial.ReadExisting();
y = received.IndexOf("\r");
}
if (testSerial.IsOpen)
{
testSerial.Close();
}
}
i'm wondering, if i absolutely have to use datahandler, how do i keep the serial port open long enough to read from it, but close the serialport before the next port needs to be opened?
see, the first method gets called a few times, and it iterates through a foreach loop, trying a message on a few ports, then trying to read a response. so, at some point i have to close the ports, or else the next time it goes through it, it doesn't work properly because the port is still open
HERE'S MY UPDATED CODE (still not working):
private void CheckPorts(string testMessage, int baudRate)
{
foreach (string s in SerialPort.GetPortNames())
{
var interval = 3000; // ms
var timer = new System.Timers.Timer(interval);
timer.Elapsed += (o, e) =>
{
timer.Enabled = false;
if (testSerial.IsOpen)
testSerial.Close(); // may not be necessary with Dispose?
testSerial.Dispose();
timer.Dispose();
};
portNumber = Int32.Parse(s.Remove(0, 3));
testSerial = new SerialPort(s, baudRate, Parity.None, 8, StopBits.One);
testSerial.ReadTimeout = 2000;
testSerial.WriteTimeout = 2000;
if (testSerial.IsOpen)
{
testSerial.Close();
}
testSerial.Open();
timer.Enabled = true;
if (testSerial.IsOpen)
{
string received;
//testSerial.DiscardInBuffer();
//autoEvent = new AutoResetEvent(false);
try
{
// testSerial.DataReceived += new SerialDataReceivedEventHandler(testSerialPort_DataReceived);
// autoEvent.Reset();
lblPortNum.Content = s;
lblPortNum.Refresh();
testSerial.Write(testMessage);
//System.Threading.Thread.Sleep(2000);
//testSerial.NewLine = "\r\n";
byte[] rBuff = new byte[2];
int rCnt = testSerial.Read(rBuff, 0, 2);
System.Text.Encoding enc = System.Text.Encoding.ASCII;
received = enc.GetString(rBuff);
//received = testSerial.ReadLine();
}
catch (TimeoutException e)
{
testSerial.Close();
continue;
}
if (received.Length > 0)
{
MessageReceived(received, Int16.Parse(s.Remove(0, 3)));
}
/*
if (autoEvent.WaitOne(2000))
{
// the port responded
// testSerial.Close();
autoEvent.Dispose();
lblPortNum.Content = "HEY I RESPONDED";
}
else
{
testSerial.Close();
autoEvent.Dispose();
continue;
// port did not respond within 2 seconds
}*/
//testSerial.Close();
}
}
}
UPDATED AGAIN (still not working properly)
private void CheckPorts(string testMessage, int baudRate)
{
foreach (string s in SerialPort.GetPortNames())
{
portNumber = Int32.Parse(s.Remove(0, 3));
// MUST BE LOCAL
var serialOneOfMany = new SerialPort(s, baudRate, Parity.None, 8, StopBits.One);
serialOneOfMany.ReadTimeout = 2000;
serialOneOfMany.WriteTimeout = 2000;
if (serialOneOfMany.IsOpen)
{
serialOneOfMany.Close();
}
// timer must be defined _after_ serialOneOfMany
var interval = 3000; // ms
var timer = new System.Timers.Timer(interval);
timer.Elapsed += (o, e) =>
{
timer.Enabled = false;
if (serialOneOfMany.IsOpen)
serialOneOfMany.Close(); // may not be necessary with Dispose?
serialOneOfMany.Dispose();
timer.Dispose();
};
if (serialOneOfMany.IsOpen)
{
string received;
try
{
lblPortNum.Content = s;
lblPortNum.Refresh();
serialOneOfMany.Write(testMessage);
byte[] rBuff = new byte[2];
int rCnt = serialOneOfMany.Read(rBuff, 0, 2);
System.Text.Encoding enc = System.Text.Encoding.ASCII;
received = enc.GetString(rBuff);
}
catch (TimeoutException e)
{
serialOneOfMany.Close();
continue;
}
if (received.Length > 0)
{
CheckIfTheMessageMatches(received, Int16.Parse(s.Remove(0, 3)));
}
}
}
}
so with this update, it just blows through the code, i can step through the code line by line, but it doesn't stop for 3 seconds at all. if i run it without any debugging breaks, it just goes through it i a fraction of a second
UPDATE 10-25-11
private void CheckPorts(string testMessage, int baudRate)
{
foreach (string s in SerialPort.GetPortNames())
{
string received = "";
testSerial = new SerialPort(s,baudRate, Parity.None, 8, StopBits.One);
lblStatus.Content = "Scanning...";
lblStatus.Refresh();
if (testSerial.IsOpen)
{
testSerial.Close();
}
else
{
testSerial.Open();
}
if (testSerial.IsOpen)
{
try
{
testSerial.NewLine = "\r";
lblPortNum.Content = s;
lblPortNum.Refresh();
testSerial.WriteTimeout= 500;
testSerial.ReadTimeout = 1000;
testSerial.WriteLine(testMessage);
System.Threading.Thread.Sleep(500);
/*THIS DOESN'T WORK
byte[] buffer = new byte[testSerial.BytesToRead];
int rCnt = testSerial.Read(buffer, 0, buffer.Length);
received = enc.GetString(buffer);*/
//received = Convert.ToString(testSerial.BaseStream.Read(buffer, 0, (int)buffer.Length));
received = testSerial.ReadLine();
int y = received.IndexOf("\r");
while (y == -1)
{
received = received + testSerial.ReadExisting();
y = received.Length;
}
if (lblInfo.Dispatcher.Thread == Thread.CurrentThread)
{
CheckIfTheMessageMatches(received, s);
received = received + lblInfo.Content;
lblInfo.Content = received;
}
else
{
lblInfo.Dispatcher.Invoke(DispatcherPriority.Normal, new ThreadCheck(threadCheck), received);
}
if (testSerial.IsOpen)
{
testSerial.Close();
}
/*I USE THIS WITH THE sPort.Read() METHOD
while (rCnt > 0)
{
if (lblInfo.Dispatcher.Thread == Thread.CurrentThread)
{
CheckIfTheMessageMatches(received, s);
rCnt = 0;
received = received + lblInfo.Content;
lblInfo.Content = received;
}
else
{
lblInfo.Dispatcher.Invoke(DispatcherPriority.Normal, new ThreadCheck(threadCheck), received);
}
}
*/
if (testSerial.IsOpen)
{
testSerial.Close();
}
}
catch (TimeoutException e)
{
testSerial.Close();
continue;
}
received = null;
}
}
lblStatus.Content = "Finished Scanning.";
lblPortNum.Content = "";
}
UPDATED CODE
here's some new code, still not working, dataeventhandler not even called once. i know it's getting messages because i have another program that works with the serial devices
private void CheckPorts(string testMessage, int baudRate)
{
foreach (string s in SerialPort.GetPortNames())
{
var serialOneOfMany = new SerialPort(s, baudRate, Parity.None, 8, StopBits.One);
serialOneOfMany.ReadTimeout = 700;
serialOneOfMany.WriteTimeout = 100;
var interval = 500; // ms
var timer = new System.Timers.Timer(interval);
timer.Elapsed += (o, e) =>
{
timer.Enabled = false;
if (serialOneOfMany.IsOpen)
serialOneOfMany.Close(); // may not be necessary with Dispose?
serialOneOfMany.Dispose();
timer.Dispose();
};
timer.Enabled = true;
lblStatus.Content = "Scanning...";
lblStatus.Refresh();
if (serialOneOfMany.IsOpen)
{
serialOneOfMany.Close();
}
else
{
serialOneOfMany.Open();
}
if (serialOneOfMany.IsOpen)
{
string received;
try
{
lblPortNum.Content = s;
lblPortNum.Refresh();
serialOneOfMany.WriteLine(testMessage);
System.Threading.Thread.Sleep(400);
serialOneOfMany.DataReceived += new SerialDataReceivedEventHandler(testSerialPort_DataReceived);
}
catch (TimeoutException e)
{
serialOneOfMany.Close();
continue;
}
}
}
lblStatus.Content = "Finished Scanning.";
lblPortNum.Content = "";
}
private void testSerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort receivingSerial = sender as SerialPort;
string received = receivingSerial.ReadExisting();
int y = received.IndexOf("\r");
while (y == -1)
{
received = received + receivingSerial.ReadExisting();
y = received.IndexOf("\r");
}
if (lblInfo.Dispatcher.Thread == Thread.CurrentThread)
{
string name = receivingSerial.PortName;
received = received + lblInfo.Content;
lblInfo.Content = received;
CheckIfTheMessageMatches(received, name);
}
else
{
lblInfo.Dispatcher.Invoke(DispatcherPriority.Normal, new ThreadCheck(threadCheck), received);
}
if (receivingSerial.IsOpen)
{
receivingSerial.Close();
}
}
A: You should be able to do these simultaneously (assuming that's ok). You would then close them as the DataReceived event is raised (extraneous code removed). Just don't close the port in CheckPorts.
private void testSerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort localSerialPort = sender as SerialPort;
... // use localSerialPort instead of global/class variable
if (localSerialPort.IsOpen)
{
localSerialPort.Close();
}
}
EDIT: Responding to comment.
You can always add a timer on the fly. If you put this in the foreach loop, you'll get a timer for every serial port that will dispose its given serial port after 3 seconds. It's important here that the timer is declared within the foreach loop.
var interval = 3000; // ms
var timer = new System.Timers.Timer(interval);
timer.Elapsed += (o,e) =>
{
timer.Enabled = false;
if (testSerial.IsOpen)
testSerial.Close(); // may not be necessary with Dispose?
testSerial.Dispose();
timer.Dispose();
}
timer.Enabled = true;
EDIT: Code updated so I'll update
Scope is very important with the code I provided. You should get rid of the non-local testSerial or use an entirely different name here.
portNumber = Int32.Parse(s.Remove(0, 3));
// MUST BE LOCAL
var serialOneOfMany = new SerialPort(s, baudRate, Parity.None, 8, StopBits.One);
serialOneOfMany.ReadTimeout = 2000;
serialOneOfMany.WriteTimeout = 2000;
if (serialOneOfMany.IsOpen)
{
serialOneOfMany.Close();
}
// timer must be defined _after_ serialOneOfMany
var interval = 3000; // ms
var timer = new System.Timers.Timer(interval);
timer.Elapsed += (o, e) =>
{
timer.Enabled = false;
if (serialOneOfMany.IsOpen)
serialOneOfMany.Close(); // may not be necessary with Dispose?
serialOneOfMany.Dispose();
timer.Dispose();
};
A: Check this info from Microsoft:
This method returns the contents of the stream and internal buffer of the SerialPort object as a string. This method does not use a time-out. Note that this method can leave trailing lead bytes in the internal buffer, which makes the BytesToRead value greater than zero.
Why don't use the usual Read method SerialPort.Read (Byte[], Int32, Int32)
A: Please have a look at this (I also used in an answer to a serial port related question asked by darthwillard). All the ports are opened one after another, the DataReceived events are bound (all you need to do there is to test the incoming message), but no waiting is required. The timer event handler can close all the ports or keep the one you want to use etc. I hope it helps!
private List<SerialPort> openPorts = new List<SerialPort>();
private void button3_Click(object sender, EventArgs e)
{
int baudRate = 9600;
string testMessage = "test";
txtPortName.Text = "Testing all serial ports";
foreach (string s in SerialPort.GetPortNames())
{
SerialPort newPort = new SerialPort(s, baudRate, Parity.None, 8, StopBits.One);
if (!newPort.IsOpen)
{
try
{
newPort.Open();
}
catch { }
}
if (newPort.IsOpen)
{
openPorts.Add(newPort);
newPort.DataReceived += new SerialDataReceivedEventHandler(serialOneOfMany_DataReceived);
newPort.Write(testMessage);
}
else
{
newPort.Dispose();
}
}
txtPortName.Text = "Waiting for response";
tmrPortTest.Enabled = true;
}
private void serialOneOfMany_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
txtPortName.Text = ((SerialPort)sender).PortName;
}
private void tmrPortTest_Tick(object sender, EventArgs e)
{
tmrPortTest.Enabled = false;
foreach (SerialPort port in openPorts)
{
if (port.PortName != txtPortName.Text)
{
port.Close();
port.Dispose();
}
}
}
A: Try setting your event handler before you write to the port, and then see if it doesn't catch your break point.
A: You can't use Thread.Sleep. It blocks the read from the device. You need to spawn a new thread.
A: You may be best with BackgroundWorker. Eg:
BackgroundWorker worker=new BackgroundWorker();
worker.DoWork += (s, dwe) =>
{
// do your serial IO here
worker.RunWorkerCompleted += (s, rwe) =>
{
// check for rwe.Error and respond
};
worker.RunWorkerAsync();
A: open the port in public form1
just after/below the InitializeComponent(); myport.open
and close the after data is received.
worked!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572596",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: mysql, permissions for different users to access different tables I would like to understand how hard this is to implement.
In unix, there are unix groups where certain people with a group can access certain folders and files.
I would like to apply the same concept into MYSQL where people could only access, view certain tables or even same tables but different rows ...
How can I achieve this? Would I have to use a different database system?
Gordon
A: This is a very common and simple approach. You can create users and specify which databases/tables they can access and what type of operations they can execute. See the mysql documentation on this
For instance:
--create the user
CREATE USER 'gordon'@'localhost' IDENTIFIED BY 'yourpassword';
--specify table and specific operations for that user
GRANT SELECT,UPDATE,DELETE,INSERT ON database.table TO 'gordon'@'localhost';
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572598",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to get the cursor in UITextView without keyboard? I am developing a program in which I have UITextView in that I need a cursor without the key board.In this cursor is show only with the keyboard if I hide the keyboard cursor will also get hide.How can I get the cursor without the key board ?
A: The cursor is displayed as long as you UITextView is being edited.
Thus, you can change its inputView view to some other view if you need to, and it will be displayed instead of the keyboard.
See http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/UIResponder_Class/Reference/Reference.html
With this method you can add your custom inputView, a UIPickerView for example, or as you say you want you can add a minimalist hidden UIView.
If you want to restrict UITextField content, you still need to implement UITextFieldDelegate, as the user can still paste content to your text field!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572599",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Change case of specified characters in a string I have all-one-case strings representing postal addresses stored in a database, but I want to capitalize US state abbreviations (e.g. " ca " to " CA ") when the abbreviation is separated from the rest of the string by a space on either side.
The lousy way I could do it would be to have 50 statements like
If addressString.Contains(" al ") Then addressString.Replace(" al ", " AL ")
If addressString.Contains(" ak ") Then addressString.Replace(" ak ", " AK ")
...
Edit: That is a really lousy way! Here's what I did instead:
addressString = StrConv(addressString, VbStrConv.ProperCase)
'This needed to be done anyway, but it turns " ak " into " Ak ".
Static stateAbbrevs As New List(Of String)(New String() {" Ak ", " Al ", " Ar "...})
For Each a In stateAbbrevs
If addressString.Contains(a) Then
addressString= addressString.Replace(a, a.ToUpper)
End If
Next
A: Just store them in an array i guess...
Dim States() as string = new string(){" al "," al "}
For i = 0 to States.Length -1
If addressString.Contains(States(i)) Then addressString = addressString.Replace(States(i), States(i).ToUpper)
Next i
A: The real question is where to store the list of abbreviations. - in the program, in a database, in a flat or xml file. All of these are easy to turn into a list of strings, and then iterate over that list replacing each occurence in your target string.
Private states as list(of string)
Private Function CapitalizeState(ByVal addressText As String) As String
Dim result as string = addresstext
For each st as string in states
result = Replace( result, st, st, CompareMethod := CompareMethod.Text)
Next
Return result
End Function
Initializing the list and optimpizations are left as an exercise....
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572611",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Envers query returns a lazy result instead of an eager one I have an Envers query that returns a lazy result although the field is defined in hibernate-mapping with lazy="false".
I have looked it up at the Hibernate-Envers forums and didn't find any useful information.
So this is what i have:
hibernate-mapping -
This is the result during run-time
Any idea about what am I doing wrong or how can i get the real object instead of the lazy one?
Thanks in advance.
A: Eager loading is not supported by Envers. All relationships are lazy.
Source
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572613",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Android - alter Orange Gradient at top and bottom of scrollable Views? In Android 2.3.x (and maybe previous versions?) when working with any scrollable Views, like a ListView or ScrollLayout, etc, when you reach the top or bottom of the list, a orange gradient appears to indicate that you are at the top or bottom of the list and can't scroll any farther. The gradient gets bigger as you try to scroll farther off the screen. I don't know what the name is of this type of widget in the SDK.
Anyways, how to do I alter it, change colors, get rid of it, etc?
A: ListView.setOverscrollHeader(Drawable drawable);
ListView.setOverscrollFooter(Drawable drawable);
A: Have a look at this
change gradient colour at end of ListView
Override setOverScrollMode method
@Override public void setOverScrollMode(int mode) {
if (mode != OVER_SCROLL_NEVER) {
if (mEdgeGlowTop == null) {
final Resources res = getContext().getResources();
final Drawable edge = res.getDrawable(R.drawable.overscroll_edge);
final Drawable glow = res.getDrawable(R.drawable.overscroll_glow);
mEdgeGlowTop = new EdgeGlow(edge, glow);
mEdgeGlowBottom = new EdgeGlow(edge, glow);
}
} else {
mEdgeGlowTop = null;
mEdgeGlowBottom = null;
}
super.setOverScrollMode(mode); }
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572617",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Passing POST parameters - no URL. Where are they exactly? I'm designing a simple web appliance that takes temperature and humidity readings and I want to post them to a remote server and have them added to a MySQL table of data.
I understand that GET is the wrong way to do this because of the idempotency problem. However, what is the syntax or method for doing this with a POST if you can't just cobble up a URL and call the page with it?
I'm working at a fairly low level on the client side - a microprocessor with an Ethernet library. It has a client.open() interface, and then I can send "print" statements to the open client connection.
Does anyone know what the server is supposed to see to receive a post and a bunch of arguments?
K
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572620",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Behaviour of generator in lambda safe against future changes? I have the following function:
| def line_reader_iter(file_object):
| while True:
| a_line = file_object.readline()
| if len(a_line)==0: raise StopIteration
| yield a_line[:-1]
and somewhere I say:
| line_reader = lambda: next(line_reader_iter(infile))
Clearly, the lambda only works because there seems to be a difference in compile-time vs. run-time behaviour which is very welcome: the line_reader_iter() puts the reference to the iterator object into the lambda expression instead of the creation of a generator object each time the lambda is evaluated. BUT: is this portable and stable behaviour? I am just a Python novice and I don't know if my code is in a grey area with respect to the Python execution model. Can someone enligthen me?
slarti
A: I think you are actually misunderstanding why this works. Each time you call line_reader() a new line_reader_iter generator is created. It appears to work because you use the same infile each time, and each call to readline() will return the next line of the file.
Consider the following simpler example:
>>> counter = lambda: next(iter(range(10)))
>>> counter()
0
>>> counter() # each time the lambda is called, a new range iter is created
0
You can get the behavior you want by using the following:
line_reader = line_reader_iter(infile).next
Here is how this would work with my range example:
>>> counter = iter(range(10)).next
>>> counter()
0
>>> counter() # yay, we are actually using the same iterator
1
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572626",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: I can not write in file i use tomcat5.32 + cpanel .
my code is :
<%
String path = application.getRealPath("");
path +="/as.txt" ;
FileOutputStream fos = new FileOutputStream(path);
fos.write("this is test ?".getBytes());
fos.flush();
fos.close();
%>
when requested get this error :
java.io.FileNotFoundException: /home/domainname/public_html/ROOT/as.txt (Permission denied)
java.io.FileOutputStream.open(Native Method)
java.io.FileOutputStream.<init>(FileOutputStream.java:179)
java.io.FileOutputStream.<init>(FileOutputStream.java:70)
org.apache.jsp.newjsp2_jsp._jspService(newjsp2_jsp.java:61)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:98)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:369)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:308)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:259)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
the perms is 0644 but my program can not write in own files .
please help me
A: The error is quite clear, you don't have write permissions to the file.
Your permission, 0644 adds Read/Write rights only to the user owning the file. Either
make your Tomcat user the owner, or include the user to the files group and apply the permission 0664.
A: 1) Ensure that the 'user' that is attempting to write to this file actually has permissions. JVM writing to the disk may not use the same Permissions as the User who launched the JVM.
2) Ensure all steps of that dir path actually exist prior to attempting to write to a file.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572634",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: LNK2038, iterator mismatch error, need to ignore I'm getting the linker error LNK2038 when trying to convert a VS2008 project to VS2010. This error occurs when two different projects are compiled in which one is using _DEBUG preprocessor macro, and the other is not. Basically I have a 3rd party library that only has release .libs, so when I try and use that library when building my project in debug mode I get this mismatch.
I understand why Microsoft is giving this error (STL iterator safety), however our project does not use Microsoft's STL, we use STLPort, so this error means nothing to our project. I just need a way to prevent it from doing this check.
Inside of the STL includes there is a file called yvals.h, which includes the #pragma detect_mismatch definition for the various _ITERATOR_DEBUG_LEVEL settings. That set of definitions is wrapped in an #ifndef _ALLOW_ITERATOR_DEBUG_LEVEL_MISMATCH, #endif. However, even if I define _ALLOW_ITERATOR_DEBUG_LEVEL_MISMATCH as a preprocessor macro for my entire project I'm still getting the same linker error. I can even alter yvals.h to define that macro and it does nothing (I'm assuming because the STL itself would need to be recompiled).
So my question is basically, what steps can I take make _ALLOW_ITERATOR_DEBUG_LEVEL_MISMATCH actually work as intended so that my project doesn't do this check anywhere when compiling in VS2010?
EDIT: I know this is a late response but I just found this post and realized I didn't post the solution. As others mentioned there was a mismatch in the libraries. As it turns out VS2010 changes the default directories for certain projects (I found a thread on MSDN at one point full of complaints about it), and that directory change had caused VS2010 to look in the wrong directory for the debug library, and it was finding the release library instead.
A: You must use the same version of the standard library, compiled with the
same options, if you expect to successfully link. If you use STLPort,
then you can only link with libraries which use the STLPort, not with
libraries which use the VC++ standard implementation. If you mix,
either you will fail to link, or you will get strange runtime errors.
The problem is that things like std::vector<>::iterator may be defined
completely differently; depending on where and how they are used, you
will find yourself using an instance constructed in a different library,
with a different layout.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572636",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How do I know if two vectors are near parallel I am having some trouble finding parallel vectors because of floating point precision. How can I determine if the vectors are parallel with some tolerance?
I also need a check for orthogonality with tolerance.
A: If you have 3D vectors the answer is simple. Compute the cross product and if it is nearly zero, your vectors are nearly parallel:
http://mathworld.wolfram.com/ParallelVectors.html
For 2d vectors you can convert them into 3D vectors just by adding a coordinate with zero
(1;2) => (1;2;0), (4; 5.6) => (4; 5.6; 0) and so on
Two vectors are orthogonal or perpendicular, if there dot product ist zero:
http://mathworld.wolfram.com/CrossProduct.html
-edit
http://mathworld.wolfram.com/Perpendicular.html
A: For vectors v1 and v2 check if they are orthogonal by
abs(scalar_product(v1,v2)/(length(v1)*length(v2))) < epsilon
where epsilon is small enough. Analoguously you can use
scalar_product(v1,v2)/(length(v1)*length(v2)) > 1 - epsilon
for parallelity test and
scalar_product(v1,v2)/(length(v1)*length(v2)) < -1 + epsilon
for anti-parallelity.
A: If you're working with 3D vectors, you can do this concisely using the toolbelt vg. It's a light layer on top of numpy and it supports single values and stacked vectors.
import numpy as np
import vg
v1 = np.array([1.0, 2.0, 3.0])
v2 = np.array([-2.0, -4.0, -6.0])
vg.almost_collinear(v1, v2)
# True
I created the library at my last startup, where it was motivated by uses like this: simple ideas which are verbose or opaque in NumPy.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572640",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: How to do a "git checkout -b " from a remote tag I'm trying to create a branch from a remote tag, but it seems there's no way to do it. When I try
git checkout -b test origin/deploy
where origin is the remote and deploy is the tag I want to check out, but I get
fatal: git checkout: updating paths is incompatible with switching branches.
Did you intend to checkout 'origin/deploy' which can not be resolved as commit?
UPDATE:
I've just discovered that
git fetch --all -t
was not working properly for me. While it downloads all branches, it does not download all tags, so when I checked out deploy it was and old tag. Now I execute
git fetch --all && git fetch -t
This way when I create a new branch based on a tag
git checkout -b test deploy
the new branch is up to date with the last deploy.
A: You need to run
git pull
git checkout -b <new-branch-name> remotes/origin/<source-branch-name>
A: I'm not sure you can do this directly. You're probably stuck with doing a fetch and then a checkout:
git fetch origin
git checkout -b test tag-name
By the way, I wouldn't recommend using a tag name like "deploy".
A: I'm not a git guru, but I had used something like this before and it seemed to have worked fine:
git pull (or fetch, just need to make sure you are updated)
git checkout -b test remotes/origin/deploy
A: to list all the tags
git fetch
git tags -l
to create a local branch that points to the tag
git checkout tags/<tag_name> -b <branch_name>
git checkout -b <branch_name> tags/<tag_name>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572647",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "34"
}
|
Q: Rails 3 skip validations and callbacks I have a particularly complex model with validations and callbacks defined. The business needs now calls for a particular scenario where adding a new record requires skipping the validations and callbacks. What's the best way to do this?
A: Use ActiveRecord::Persistence#update_column, like this:
Model.update_column(field, value)
A: My take was like this (note: this disables callbacks on create, for update, delete and others you need to add them to array).
begin
[:create, :save].each{|a| self.class.skip_callback(a) } # We disable callbacks on save and create
# create new record here without callbacks, tou can also disable validations with
# .save(:validate => false)
ensure
[:create, :save].each{|a| self.class.set_callback(a) } # and we ensure that callbacks are restored
end
A: I would recommend NOT using the skip_callback approach since it is not thread safe. The sneaky save gem however is since it just runs straight sql. Note this will not trigger validations so you will have to call them yourself (ex: my_model.valid?).
Here are some samples from their docs:
# Update. Returns true on success, false otherwise.
existing_record.sneaky_save
# Insert. Returns true on success, false otherwise.
Model.new.sneaky_save
# Raise exception on failure.
record.sneaky_save!
A: If the goal is to simply insert or update a record without callbacks or validations, and you would like to do it without resorting to additional gems, adding conditional checks, using RAW SQL, or futzing with your exiting code in any way, it may be possible to use a "shadow object" which points to your existing db table. Like so:
class ImportedUser < ActiveRecord::Base
# To import users with no validations or callbacks
self.table_name = 'users'
end
This works with every version of Rails, is threadsafe, and completely eliminates all validations and callbacks with no modifications to your existing code. Just remember to use your new class to insert the object, like:
ImportedUser.new( person_attributes )
A: This works in Rails 3:
Model.skip_callback(:create)
model.save(:validate => false)
Model.set_callback(:create)
(API docs and related question)
A: What about adding a method to your model that let's you skip the callbacks?
class Foo < ActiveRecord::Base
after_save :do_stuff
def super_secret_create(attrs)
self.skip_callback(:create)
self.update_attributes(attrs)
self.save(:validate => false)
self.set_callback(:create)
end
end
If you end up using something like this, I would recommend using self in the method instead of the model name to avoid connascence of name.
I also ran across a gist from Sven Fuchs that looks nice, it's here
A: I wrote a simple gem for skipping validations adhoc, but it could probably be updated to include skipping call backs as well.
https://github.com/npearson72/validation_skipper
You could take the can_skip_validation_for in the gem and add functionality for also skipping callbacks. Maybe call the method can_skip_validation_and_callbacks_for
Everything else would work the same. If you want help with doing that, let me know.
A: This hack worked for me at last (redefined _notify_comment_observer_for_after_create method for the object):
if no_after_create_callback
def object._notify_comment_observer_for_after_create; nil; end
end
A: None of these will work if your validations are written into the database itself.
+------------------------------------+--------------------------------------------------+------+-----+--------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------------------------------+--------------------------------------------------+------+-----+--------------------+----------------+
| status | enum('Big','Small','Ugly','Stupid','Apologetic') | NO | | Stupid | |
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572652",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "74"
}
|
Q: Is it necessary to have Email field in ASP.NET CreateUserWizard Control? I had done the registration using ASP.NET CreateUserWizard Control. In here I want to use email address as the username. I had problem removing Email field from the control. In the web.config file I used requiresUniqueEmail="false".
I achieve this by hiding the email field and autofilled the field with username.
There is a way shown here of doing that.
I just wondering if there is any other better way of doing this.
Thanks
A: Have you tried setting the CreateUserWizard.RequireEmail property to false like so:
<asp:CreateUserWizard ID="CreateUserWizard1" runat="server"
RequireEmail="false" ...
A: You can change the RequireEmail property to true or false.
You can find more from CreateUserWizard.RequireEmail Property
<asp:CreateUserWizard RequireEmail="True|False" />
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572653",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Where's the bug in this BitTorrent client's piece verification process? I've been working on writing a BitTorrent client in C in my spare time. However -- seemingly at random -- my client will fail to verify that a received piece of a torrent is correct with the message:
Failed to verify piece: #4
Background: a .torrent file contains the relevant metadata for the file-to-be-downloaded, including a SHA1 hash of each piece (a block of the file-to-be-downloaded), so -- after downloading a piece -- I take its SHA1 hash and compare it to the one provided by the torrent's metadata file.
Here's the code that handles verification:
int verify_piece (void* addr, uint64_t piece_length, unsigned char* piece_sha)
{
SHA_CTX sha;
unsigned char sha1result[20];
SHA1_Init(&sha);
SHA1_Update(&sha, addr, piece_length);
SHA1_Final(sha1result, &sha);
if (memcmp(sha1result, piece_sha, 20)) {
printf("Expected: ");
print_sha1(piece_sha);
printf("Received: ");
print_sha1(sha1result);
return 0;
} else
return 1;
}
In an attempt to track down the bug, I rigged up two functions: write_incorrect_piece() and write_correct_piece(). The first function, write_incorrect_piece() is called when verify_piece() fails. It writes the piece that failed verification to a file so that I can inspect it with hexdump.
void write_incorrect_piece (void* piece, uint32_t piece_length, uint32_t index)
{
FILE* failed_piece = fopen("failed_piece.out", "w+");
write(fileno(failed_piece), piece, piece_length);
fclose(failed_piece);
printf("ERROR: Wrote piece #%d to failed_piece.out for inspection with hexdump.\n",
index);
write_correct_piece(piece_length, index);
exit(1);
}
As you can see, write_incorrect_piece() takes the parameters void* piece, which is a pointer to the piece which failed verification, uint32_t piece_length, which is the length of the piece, and uint32_t index which is the index of the piece which failed verification. It then copies the incorrect piece to a file called failed_piece.out.
You'll notice that before calling exit(), write_incorrect_piece() calls the function write_correct_piece(). This is the second function I wrote to help with debugging this error. It takes a known good version of the file that the torrent client is attempting to download (known_good.iso) and then copies the relevant piece to a file (correct_piece.out) so that I can compare it to the file containing the incorrect piece.
void write_correct_piece (uint32_t piece_length, uint32_t index)
{
FILE* known_good = fopen("known_good.iso", "r+");
FILE* correct_piece = fopen("correct_piece.out", "w+");
/* get file size for MMAPing */
struct stat st;
stat("known_good.iso", &st);
long size = st.st_size;
void* addr = mmap(0,
size,
PROT_READ | PROT_WRITE,
MAP_SHARED,
fileno(known_good),
0);
write(fileno(correct_piece), addr + piece_length * index, piece_length);
munmap(addr, size);
fclose(known_good);
fclose(correct_piece);
}
I then took the two written files and formatted them with hexdump so that the output would be human readable and then tried to compare them via diff, like so
$ hexdump failed_piece.out > failed_piece.dump
$ hexdump correct_piece.out > correct_piece.dump
$ diff correct_piece.dump failed_piece.dump
To my surprise, diff didn't output anything. The files are exactly the same. Why, then, was the SHA1 hash of the piece different from the one expected by the torrent file? Perhaps, I then thought, the SHA1 hash from the metadata file was incorrect. If that's the case, I would expect the client to always fail to verify piece #4, so I modified the torrent client's scheduler to only attempt to download piece #4 to see if it does, in fact, always fail verification.
Successfully downloaded piece: #4
Wtf? Now I'm at an impasse. I figure a couple of different things could be causing this:
*
*There actually is a bug in the client's network code, but I have introduced a bug in write_incorrect_piece() and write_correct_piece() so that it produces two identical files regardless of the integrity of the inputs.
*There is a bug in verify_piece(), causing it to fail sporadically.
*I have failed to consider something.
For the life of me, however, I can't find any problems with any of the above code, so I'm hoping you fine folks can point out what I'm missing.
The entire source of the client is at https://github.com/robertseaton/slug.
Edit: Replaced strncmp() with memcmp() in verify_piece() and cleaned up both write_incorrect_piece() and write_correct_piece().
Edit: Here's an example of the SHA1 hashes on a failed piece that seems correct when I manually diff it. As you can see, the hashes are not similar at all:
Expected: 239 66 216 164 16 120 73 24 1 236 116 173 144 85 243 152 160 165 64 231
Received: 214 94 49 185 54 159 255 201 214 137 102 23 223 76 102 138 89 94 154 69
Failed to verify piece: #13
A: Okay, so if we have a look at the invocation of verify_piece(), we see this:
if (verify_piece(p->torrent->mmap + index * p->torrent->piece_length,
p->torrent->piece_length, p->torrent->pieces[index].sha1)) {
Now, trivially, we know that the first and second parameters are correct since it is later reused when the program calls write_incorrect_piece() and we have already verified that its output is correct. So, we are free to focus on the third parameter, p->torrent->pieces[index].sha1.
At first glance, the parameter looks correct, since we are using index throughout the function. However, consider, what if index -- while perfectly valid on a correctly sorted array -- is being used as an index to an array that no longer contains the pieces in the assumed order?
Viola! Here's the culprit (in __schedule()):
qsort(t->pieces, t->num_pieces, sizeof(struct Piece), rarest);
Comment out the call to qsort() and the client runs as expected.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do you manage and use "Many to many" core data relationships? I'm creating an app and trying to use core data, because it seems like it's the objective-C approved way to create a data storage system. The use case I have involves "many to many" relationships, like you'd normally see in a standard SQL system. I understand that objective C is not a database and works differently. I've also reviewed the documentation here:
http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/CoreData/Articles/cdRelationships.html#//apple_ref/doc/uid/TP40001857-SW10
And several other places. And yet, I'm still having trouble. Can someone explain to me what you would do if you have a use case where you'd need to use a SQL cross reference table? For example:
Managers | Employees
Manager may have several employees, but the employees might also have several manager. In SQL, I'd create a cross reference table and then use that.
Example: http://www.tomjewett.com/dbdesign/dbdesign.php?page=manymany.php
Can someone explain how you could do that in Core data?
According to the core data documentation, they say this:
"You define a many-to-many relationship using two to-many relationships. The first to-many relationship goes from the first entity to the second entity. The second to-many relationship goes from the second entity to the first entity. You then set each to be the inverse of the other. (If you have a background in database management and this causes you concern, don't worry: if you use a SQLite store, Core Data automatically creates the intermediate join table for you.)"
But, besides "not being worried," I don't know how this could possibly work?
A: Peter: "I have nine bosses, Bob."
Bob: "Say again?"
Peter: "Nine."
Take your brain out of the database. Do not ask how to access a cross-reference table. Ask how to find the employees for a manager or the managers for an employee.
If you use a custom subclass of NSManagedObject, you can declare the properties as documented. Then you can simply say:
NSSet *mgrsEmployees = mgr.employees;
NSSet *employeesMgrs = employee.managers;
That will not give you all the employees and all the managers, only all the employees for that manager and all the managers for that employee. To change relationships:
[mgr addEmployeesObject:newEmployee];
[newEmployee addManagersObject:mgr]; // not necessary, automatic if you define inverse
[mgr removeEmployeesObject:transferredEmployee];
[transferredEmployee removeManagersObject:mgr]; // not necessary
[newMgr addEmployeesObject:transferredEmployee];
[transferredEmployee addManagersObject:newMgr]; // not necessary
You only need to do either one of each pair of statements, and it will implicitly do the other, provided you have defined managers and employees as inverses of each other.
If you don't use a custom subclass, accessing is a little more verbose
NSSet *mgrsEmployees = [mgr valueForKey:@"employees"];
NSSet *employeesMgrs = [employee valueForKey:@"managers"];
NSMutableSet *changeMgrsEmployees = [mgr mutableSetValueForKey:@"employees"];
[changeMgrsEmployees addObject:newEmployee];
// not necessary
NSMutableSet *changeEmployeesMgrs = [employee mutableSetValueForKey:@"managers"];
[changeEmployeesMgrs addObject:mgr];
Etc.
A: If your question is "how you could do that in core data", the answer is exactly as you describe. Create a to-many relationship in each entity, and define each as the inverse of the other.
If your question is "how could this possibly work", you might find it useful to look at the sqlite database that is created from your model to see how it sets things up. CoreData is pretty good at making it so you shouldn't care about the details, but if you insist on understanding the details there's nothing stopping you from looking at the data to see what it is doing.
Once you have this in place, you would traverse the relationship as necessary to get the attributes you want. You can do that in code using NSManagedObject instances. For example:
NSManagedObject *manager = // get a reference to a manager here
NSSet *employees = [manager valueForKey:@"employees"];
for (NSManagedObject *employee in employees) {
NSString *employeeName = [employee valueForKey:@"name"];
// Do whatever else you want here
}
This sample can also be simplified using direct property access rather than KVO syntax, but you get the idea.
If you are looking to traverse this many-to-many relationship more directly as part of a fetch query, then you can do some things with predicates to get what you want. Refer to Apple's predicate programming guide for examples of what you can put in a predicate
A: Let's say you have two entities in your database, employees and managers. They would look something like this in the code:
@interface Employee : NSManagedObject
{
}
@property (nonatomic, retain) NSNumber * id;
@property (nonatomic, retain) NSSet* managers;
@interface Manager : NSManagedObject
{
}
@property (nonatomic, retain) NSNumber * id;
@property (nonatomic, retain) NSSet* employees;
So let's say you wanted to retrieve all the employees for manager number 1, you would just have to get the manager object from the database:
NSNumber *managerID = [NSNumber numberWithInt:1];
NSEntityDescription * entityDescription = [NSEntityDescription entityForName:@"Manager" inManagedObjectContext:managedObjectContext];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:entityDescription];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K == %d", @"id", managerID];
[request setPredicate:predicate];
NSArray *array = [managedObjectContext executeFetchRequest:request error:&error];
Manager *manager = [array objectAtIndex:0];
and then you would have all its employees in the employees property:
NSSet *allHisEmployees = manager.employees;
It would be exactly the same to retrieve the managers for a given employee.
I hope it clears things up
A: The simple answer is to mark the relationship as one to many from both ends when setting up core data in xCode. That in essence creates a many to many. It's in the apple docs somewhere, but I can't find the URL.
A: Possibly what you are stuck on is how to get from the abstract data model realm to a set of objects that you use in code. If so, look into using mogenerator:
http://rentzsch.github.com/mogenerator/
That's a command line utility (not sure how well the XCode integration works these days) where you point it at a model, and it gives you sets of data objects you can use. You need to have an object name set for each entity in addition to the entity name.
The generated data objects have the calls like employee.managers, which would give you a set of Manager entities for an employee, and vice-versa.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572657",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "26"
}
|
Q: How do I delete a SQLite DB on my Android Emulator? I assume that this is the solution to the problem. The error I keep getting says in a raw query I pass that a certain table does not exist. I have since changed the name of this class and every instance of it in the code, but it only returns an error on one line only. Eclipse still thinks it is using the old code. I do not know what to think other than it is using the old database table names. Any help on this would be appreciated.
I have tried the suggestions given, but it still refers to old code. I am not using the table name classes. I am using the table name class in my statements...
09-27 13:02:15.100: ERROR/AndroidRuntime(7530): java.lang.RuntimeException: Unable to start activity ComponentInfo{gpa.calc/gpa.calc.GPACalculator}: android.database.sqlite.SQLiteException: no such table: classes: , while compiling: SELECT DISTINCT year, COUNT(*) FROM classes
A: If you are using Eclipse Goto Menu Windows->Show View->Other...->
Under Android, Pick File Explorer,
on the console, expand data, expand data again. expand your application in context, select the db file on this console's top right corner you ll find a red - symbol.
that should do it.
A: The DB of the application you are developing should be able to be cleared by going to Settings->Applications->Your Application->Clear Data. Then you should have no DB for your corresponding application anymore.
A: 1) run ddms.
2) Choose adv
3) File explorer
4) data/data/yourapp/database
5) select and delete
A: I periodically delete and create a new AVD to clear out code that is still hanging around. Wiping user data only clears the non-public data. Also, some 'crashes' seem to leave the emulator in a state that doesn't allow clean reloads.
I also 'pull' data off of the emulator to an external file when I want to checkpoint database updates. If things go south, I can create a new AVD and SD image. Then push the external database to the new SD image.
It seems that emulators don't always reinit cleanly after they've been used a few times.
Note: Snapshots do not restore 'public' data on an SD card disk image.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is it possible to create a C# class from xml? Is it possible to create a C# class from xml?
suppose my xml is like,
<Person>
<Name>aaaa</Name>
<Email>bbb</Email>
</Person>
then Person would be the classname and name and email must be my properties. And how would it handle collections or potential sub objects?
<Person>
<Name>aaaa</Name>
<Email>bbb</Email>
<PhoneNumbers>
<Number Type="Cell">5555555</Number>
<Number Type="Home">5555554</Number>
</PhoneNumbers>
</Person>
A: You can use XSD.exe to generate a class
http://msdn.microsoft.com/en-us/library/x6c1kb0s(v=VS.100).aspx
A: The XML Schema Definition (xsd.exe) tool allows you to generate common language runtime classes from XML files. More info can be found here.
A: Assuming you mean xml serialization, you can use this as an example. Note the use of the Xml attributes to control the serializion/deserialization:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Xml.Serialization;
namespace ThrowAwayCSConsole
{
class Program
{
static void Main(string[] args)
{
//Create an instance of the Person
Person p = new Person { Name = "John Doe", Email = "jdoe@someisp.com" };
p.PhoneNumbers.Add(new PhoneNumber { Type = "Home", Number = "999-555-1234" });
p.PhoneNumbers.Add(new PhoneNumber { Type = "Work", Number = "999-555-9876" });
StringBuilder output = new StringBuilder();
XmlSerializer xSer = new XmlSerializer(typeof(Person));
//serialize it to xml
using (StringWriter wrt = new StringWriter(output))
{
xSer.Serialize(wrt, p);
}
//Print the output
Console.WriteLine(output.ToString());
//Deserialize the xml string back to an instance of Person
Person p2 = null;
using (StringReader rdr = new StringReader(output.ToString()))
{
p2 = xSer.Deserialize(rdr) as Person;
}
//Use p2 instance here
Console.WriteLine("\r\nName: {0}, Email: {1}, has {2} phone numbers:", p2.Name, p2.Email, p2.PhoneNumbers.Count);
foreach (var number in p2.PhoneNumbers)
{
Console.WriteLine(" {0}: {1}", number.Type, number.Number);
}
Console.ReadLine();
}
}
[Serializable]
[XmlInclude(typeof(PhoneNumber))]
public class Person
{
public string Name { get; set; }
public string Email { get; set; }
[XmlArrayItem("Number")]
public List<PhoneNumber> PhoneNumbers { get; set; }
public Person()
{
PhoneNumbers = new List<PhoneNumber>();
}
}
[Serializable]
public class PhoneNumber
{
[XmlAttribute]
public string Type { get; set; }
[XmlText]
public string Number { get; set; }
}
}
The output from this code is:
<?xml version="1.0" encoding="utf-16"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Name>John Doe</Name>
<Email>jdoe@someisp.com</Email>
<PhoneNumbers>
<Number Type="Home">999-555-1234</Number>
<Number Type="Work">999-555-9876</Number>
</PhoneNumbers>
</Person>
Name: John Doe, Email: jdoe@someisp.com, has 2 phone numbers:
Home: 999-555-1234
Work: 999-555-9876
Hope this helps
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572659",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: problem capturing delimiter with preg_split I have a pipe-delimited dump file from an SQL Server, and I want to import it into MySQL. The lines are delimited by \r\n, and that sequence also occurs in some fields! So I want to use a regular expression to find the actual lines and make an INSERT statement out of them.
However, I'm having trouble including the delimiter in my match string. I thought using PREG_SPLIT_DELIM_CAPTURE would do the trick but apparently I'm doing something wrong. My delimiter is three spaces followed by three numbers, which is actually the id that I need for the row:
$ cat test.php
<?
$string = ' 897|a|Hello\r\n 583|b|Line\r\nBreak\r\n 332|c|Yet\r\nMore\r\nLine\r\nBreaks\r\n';
$lines = preg_split( '/ \d{3}\|/', $string, NULL, PREG_SPLIT_DELIM_CAPTURE);
print_r($lines);
$ php test.php
Array
(
[0] =>
[1] => a|Hello\r\n
[2] => b|Line\r\nBreak\r\n
[3] => c|Yet\r\nMore\r\nLine\r\nBreaks\r\n
)
My delimiters are missing.
$ php -v
PHP 5.3.3-7+squeeze1 with Suhosin-Patch (cli) (built: Mar 18 2011 17:22:52)
Copyright (c) 1997-2009 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies
What am I doing wrong, or how do I get what I want?
A: You need to group your delimiter into parenthesis, or else the _DELIM_CAPTURE will have no effect.
$lines = preg_split( '/ (\d{3}\|)/', $string, NULL, PREG_SPLIT_DELIM_CAPTURE);
Here, the manual mentions it en passant as flag description:
PREG_SPLIT_DELIM_CAPTURE
If this flag is set, parenthesized expression in the delimiter pattern will be captured and returned as well.
A: Above answer will give you delimiter in separate array element.
Check this one instead:
preg_split how to include the split delimiter in results?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572661",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Table annotation in jpa with portion of the table name dynamically in JPA annotation @Table(x+"_Name"),
I want the x to be fed by spring config file.
Is it possible in JPA? actually all our db tables name have prefix with application name, and I want to use that prefix at dynamically configure by passing to spring bean config.
in spring config:
<bean id="x" class="java.lang.String">
<constructor-arg value="JOE" />
</bean>
A: Unfortunately, You can't. Any value you will set as @Table annotation parameter you will receive
"The value for annotation attribute Table.name must be a constant expression" error
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572665",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: time limit function execution in PHP or anything else I could say that my question is related to PHP, but what I'm more concerned is proper logic of programming in situation where function execution can go on indefinitely.
What is the proper way of monitoring time that it takes to execute some function and how to stop this execution and go on with the rest of the program?
OK, I know that for example there is a set_time_limit() function that returns fatal error but I don't want this, I want my code to just continue after x seconds, or maybe after time exceeded throw an exception, catch it and do something else?
Is writing some kind of a "watchdog" function solution and how is this done?
Thank you for any help that you can provide, any link, any article that addresses this problem in a way that it "should" be done.
BR,
Newman
A: PHP doesn't provide a general way to timeout a function. But many components where this problem is common let you define a timeout.
Examples:
*
*The HTTP Stream Wrapper allows you to specify a timeout option:
file_get_contents('http://example.com', false, stream_context_create(
array('http' => array('timeout' => 10 /* seconds */))
));
*PDO (database abstraction layer) allows you to set a timeout using the PDO::ATTR_TIMEOUT attribute (note that this attribute may mean different things with different database drivers):
$pdo->setAttribute(PDO::ATTR_TIMEOUT, 10 /* seconds */);
*You can set a connection timeout when using FTP:
$ftp = ftp_connect('example.com', 21, 10 /* seconds */)
Similarly all other extensions that access potentially remote resources will provide such timeout parameters or options.
A: In PHP in particular, I don't think you have a valid way to control the execution time for your functions from outside of them.
Like you said, things like set_time_limit will throw a Fatar Error and kill your script.
I would suggest messuring your excecution time from within your functions, using things like microtime() and throw an exception if the time limit is exeeded; an exception that you'll be able to catch outside and continue act accordingly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572666",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: I can't see changes when updating css files for Magento 1.5 although I have cleared the cache I edited and uploaded a css file to my Magento 1.5 site. I refreshed the cache and also refreshed the browser cache but I could see any changes reflected to the site. What should I do?
A: Did you check that Magento is sending the correct CSS file from the correct theme?
This might seem like a basic mistake, but it happens more often than you think especially if you have multiple design/theme folders. View source of HTML and just make sure that the page is using the CSS file you modified.
If magento is not sending the correct CSS,
check in admin -> System -> Design -> Themes -> Skin or your phtml code.
When you include your CSS file from PHP(template) code, make sure you use
href="<?php echo $this->getSkinUrl('css/fileName.css')?>"
Also, you can clear cache directly by deleting folders in from magento/var/cache/
If Magento is sending the correct CSS file, then the last thing you can do is adding a version name to the CSS from the layout or from phtml code. Just convert fileName.css to fileName.css?v=01 or something, then the browser will download the latest change.
Hope one of these will solve your problem.
A: If you are running some caching script on a load balancer (eg varnish) make sure you restart that too or run the clear cache comment there.
Magento also has a Flush Javascript/CSS cache, have you tried clearing that.
If this all doesn't apply/work just delete everything in the /var/cache/ folder ;)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572673",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: nsdateformatter format Aug 8, 2011 11:40 how do i format Aug 8, 2011 11:40 into nsdate using nsdatepicker?Im trying to use
[dateFormatter setDateFormat:@" MMM d, YYYY HH:mm"];
but it doesnt work
A: Try this
iPhone format strings are in Unicode format. Behind the link is a table explaining what all the letters above mean so you can build your own
NSString *dateString = @"Aug 8, 2011 11:40";
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:@"MMM dd, yyyy hh:mm"];
NSDate *date = [format dateFromString:dateString];
NSLog(@"date: |%@|", date);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572678",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: how to close a blocking socket while it is waiting to receive data? I have a service that uses a blocking socket to receive data. The problem I have is that I do not know how to properly close the socket if it is still waiting for data. Below is a short snip of how I am opening and waiting for data: I do not want to implement timeouts as according to the python documentation the socket must be blocking in order to use makefile.
I may be going about this completely wrong as I am new to programming with sockets.
EDIT:
It should be noted that the I cannot alter how the server operates.
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
reader = s.makefile("rb")
line = reader.readline()
A: There is a quite simple solution. Given a socket and a reader file object like rfile = socket.makefile('rb'), in order to make rfile.readline() return immediately when the socket is closed, you need to execute the following in a separate thread:
socket.shutdown(socket.SHUT_RDWR)
socket.close()
Calling socket.shutdown() will make rfile.readline() return an empty str or bytes, depending on the version of Python (2.x or 3.x respectively).
A: One solution to close this socket is to ask the server to close it.
If server close the client socket, the client will receive a "Connection reset by peer" error, and it may break the blocking receive.
Another solution would be to not use readline() and put a timeout on your socket (indefinite wait could wait.... indefinitely)
A: I believe that if you just go ahead and close it, from another thread, then the thread that was trying to read from it will return with an error. If you don't have multiple threads, then you will have to refactor to use non-blocking mode (option os.O_NONBLOCK when you open the socket).
A: As you can see from the variety of other somewhat confused, often fragile or dangerous answers, this is a tricky question. Fortunately, you can side-step all of these issues by using non-blocking sockets instead. Consider this approach (using Twisted for simplicity):
from twisted.internet.protocol import ClientFactory
from twisted.protocols.basic import LineOnlyReceiver
from twisted.protocols.policies import TimeoutMixin
from twisted.internet import reactor
class YourClientProtocol(LineOnlyReceiver, TimeoutMixin):
def connectionMade(self):
# Initiate the timeout
self.setTimeout(30)
def lineReceived(self, line):
# Reset the countdown
self.resetTimeout()
# And process the line somehow
if line == "great justice":
print "for the win!"
def timeoutConnection(self):
# Report the timeout
print "Timed out waiting for a line"
# Drop the connection
self.transport.loseConnection()
def connectionLost(self, reason):
# Let the program complete
reactor.stop()
# Set up a connection
clientFactory = ClientFactory()
clientFactory.protocol = YourClientProtocol
reactor.connectTCP(HOST, PORT)
# Start the main loop, which can handle timed and
# network events simultaneously
reactor.run()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572682",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: android layout problem with image length I have an image of a line and I want it to go from end to end (left to right). However thats not happening ! And I am not sure why - I have used fill_parent as the width. Any help ?
<ImageView
android:id="@+id/twsep1"
android:src="@drawable/separator"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_below="@+id/twedit11"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"/>
screenshot:
full layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/backgroundnr"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:paddingTop="5dp"
android:paddingBottom="5dp">
<ImageView
android:id="@+id/twicon"
android:layout_height="90px"
android:layout_width="120px"
android:paddingTop="5dp"
android:paddingBottom="10dp">
</ImageView>
<TextView
android:text="I like:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/twlabel1"
android:textSize="18px"
android:layout_toRightOf="@+id/twicon"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:paddingTop="5dp"
android:paddingBottom="5dp">
</TextView>
<EditText
android:id="@+id/twedit11"
android:layout_height="wrap_content"
android:text=""
android:inputType="textMultiLine"
android:lines="1"
android:layout_width="fill_parent"
android:textSize="18px"
android:layout_below="@+id/twlabel1"
android:layout_toRightOf="@+id/twicon"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:paddingTop="5dp"
android:paddingBottom="5dp">
</EditText>
<ImageView
android:id="@+id/twsep1"
android:src="@drawable/separator"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_below="@+id/twedit11"
android:paddingTop="5dp"
android:paddingBottom="5dp">
</ImageView>
<TextView
android:text="Write a comment:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/twlabel3"
android:textSize="18px"
android:layout_below="@+id/twsep1"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:paddingTop="5dp"
android:paddingBottom="5dp">
</TextView>
<EditText
android:id="@+id/twedit22"
android:layout_height="wrap_content"
android:text=""
android:inputType="textMultiLine"
android:lines="10"
android:layout_width="fill_parent"
android:textSize="18px"
android:layout_below="@+id/twlabel3"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:paddingTop="5dp"
android:paddingBottom="5dp">
</EditText>
<TextView
android:text="Press TWEET to publish."
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/twlabel5"
android:textSize="18px"
android:layout_below="@+id/twedit22"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:layout_centerHorizontal="true">
</TextView>
<ImageView
android:id="@+id/twsep2"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:src="@drawable/separator"
android:layout_below="@+id/twlabel5"
android:paddingTop="5dp"
android:paddingBottom="5dp">
</ImageView>
<Button
android:id="@+id/twButton"
android:text="Tweet"
android:background="@drawable/ebutton"
android:layout_width="200px"
android:layout_height="50px"
android:layout_below="@+id/twsep2"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:layout_centerHorizontal="true">
</Button>
</RelativeLayout>
A: Maybe ....
android:paddingLeft="0dp"
android:paddingRight="0dp"
?
A: you have used both
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
try after removing both the above. If you still face problem then specify what exactly are you getting or if possible attach a screen shot.
A: With your width set to fill_parent you do not need:
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
This may be causing a weird issue, but also you do not need these lines either because they will cause padding to each side.
android:paddingLeft="5dp"
android:paddingRight="5dp"
With a more complete layout posted we can give you a better answer.
A: Have a look at ScaleType. I think what you need is fitXY.
Just add android:scaleType="fitXY" to your ImageView.
I would also look into NinePatches for that purpose.
A: If you could post code for it's parent layout, it could be of some help.
What about it's parent Layout, how have you mapped it, is the parent's width "wrap_content" or a "value" or "fill_parent" or what? may be this image's immediate parent may himself be contained w.r.t his parent or his width parameter. Jus check it out.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572683",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Sort string items in a datatable as int using c# I have some numeric codes stored in a DataTable. When I try to sort it using DataView it sorts the column by string. What is the easiest way to sort the data as integer/number?
DataView view = dt.DefaultView();
view.Sort = "Code asc";
dt = view.ToTable();
Data in datatable:
128, 123, 112, 12, 126
after sort it shows:
112, 12, 123, 126, 128
expected result:
12, 112, 123, 126, 128
A: One option is to add a Calculated column with the right type and sort on it.
Like this:
dt.Columns.Add( "Int32_Code", typeof( int ), "Code" );
dt.DefaultView.Sort("Int32_Code");
dt = dt.DefaultView.ToTable();
A: When you are creating a column in data table, define it as typeof(int)
dt.Columns.Add("Code", typeof(int));
A: Here is working example. You can create another DataTable via Clone, and change the data type of the column to Int and copy the data.
DataTable dt = GetTable(); // Assume this method returns the datatable from service
DataTable dt2 = dt.Clone();
dt2.Columns["Code"].DataType = Type.GetType("System.Int32");
foreach (DataRow dr in dt.Rows)
{
dt2.ImportRow(dr);
}
dt2.AcceptChanges();
DataView dv = dt2.DefaultView;
dv.Sort = "Code ASC";
A: create a new column in datatable as given below and sort on new column code_int
Dt.Columns.Add("Code_int", typeof(Int16), "Convert(Code, 'System.String')");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572685",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Question about using FacesValidator (JSF Validation) and Bean Validation on one Field i have an email field
which i want to validate that it's valid email, and validate that it doesn't exist in the database, so i used for valid email pattern the @Email from hibernate in the bean:
@NotBlank(message = "{email.required}")
@Email(message = "{invalid.email}")
@Size(max = 25, message = "{long.value}")
and in the jsf page:
<f:validator binding="#{emailExistValidator}" />
my questions:
*
*What happens first, the faces validator or the bean validation ?
*What do you think about this mixing between bean validation and
FacesValidator, is it bad practice,if so what do you suggest ?
A:
1- What happens first, the faces validator or the bean validation?
JSF conversion and validation will run first in the order it is been declared on the component, with required first. If any of it fails, then the remnant of JSF validation and all the bean validation is completely skipped, else all of the bean validation is executed.
2- What do you think about this mixing between bean validation and FacesValidator, is it bad practice, if so what do you suggest?
Hard to answer. It solely depends on the functional requirements and the purpose of the validator and how closely tied the validation is to the model or the view.
If the validation needs to run everytime the model property is set (so, it's closely tied to the model), then bean validation would be preferred. But if validation needs to run only once, e.g. during registration (so, it's closely tied to a specific view), then JSF validation would be preferred.
For example, if you're checking the email syntax pattern, then bean validation would make more sense, e.g.:
@Pattern(regexp = "([^.@]+)(\\.[^.@]+)*@([^.@]+\\.)+([^.@]+)", message = "Email is not in valid format")
private String email;
If you're checking the email existance against the DB, then a JSF validator would make more sense since you don't want it to unnecessarily be executed on every property set. DB calls are not cheap per se.
Again, this is subjective. See what fits the business requirements the best. Maybe you're required to validate it on every property set, for example.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572686",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Equivalent of "sizeof() of C" in Java
Possible Duplicate:
In Java, what is the best way to determine the size of an object?
What is the technique to retrieve the # of bytes occupied by a class object/variable in Java?
Looking for an equivalent for SizeOf() operator in C.
A: I've used the SizeOf() project on Sourceforge before with decent success:
http://sourceforge.net/projects/sizeof/
However, based on how the JVM works, Sizeof for java is, at best, an intelligent guess based on predefined parameters rather than actually measuring the size of the memory allocation.
...so use this as a source of information rather than gospel!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572688",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Python datetime randomly breaking This isn't the first time this has happened to me so now I'm looking for an answer because I'm completely stumped.
I have code running in a production environment for over 3 months now and it worked absolutely fine, then out of no where I started to get errors in python.
'method_descriptor' object has no attribute 'today'
Exception Value:
'method_descriptor' object has no attribute 'today'
Exception Location: /admin/views/create.py in process, line 114
/admin/views/create.py in process
order = Orders(uid=0, accepted=0, canview='', files=0, date=datetime.date.today(), due=dueDate,
As you can see, I'm using the following which works absolutely fine from the python shell:
>>> import datetime
>>> datetime.date.today()
>>> datetime.date(2011, 9, 27)
A: Your code is importing datetime.datetime somewhere, instead of just datetime, e.g. from datetime import datetime.
>>> import datetime
>>> datetime.datetime.date.today()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'method_descriptor' object has no attribute 'today'
A: --> from datetime import datetime
--> datetime.date.today()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'method_descriptor' object has no attribute 'today'
Either your datetime import is being overridden by a subsequent import, or some other code is injecting a different datetime into your module.
Update
from ... import * is meant to populate the current namespace with whatever is in ... -- not strange at all. Presumably you have those functions in admin.helpers.functions for that very purpose.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572690",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: jQuery Disable Enter Key after Enter Key has been hit when Enter key has already been disabled I have disabled my enter key so that I can do an ajax submission, but I want to make sure that the form isn't submitted twice if the user hits enter twice before the response from the server comes back.
Here I have disabled the enter key and assigned a function to it called submitForm():
$(document).ready(function(){
offset = $("#quantity").html();
$("#lastName").focus();
$(document).bind("keypress" , function(e){
if (e.which == 13 && (!$("#notes").is(":focus")) && (!$("#submit").is(":focus"))) {
submitForm(); return false;
}
})
$("#submit").click(function(){ submitForm(); });
});
I tried to bind() again elsewhere, but it didn't do anything. I tried preventDefault() in various places, but I think I'm either putting it in the wrong place, or else that's the wrong thing to do. I can't seem to get this to work.
I found this: How to disable Enter/Return Key After a function is executed because of it?, but it doesn't answer my question because in the poster's example, the script checks to see whether there is anything in the box, but I want to check to see whether I have submitted or not. I'm not sure how to do that. What I would really like to do is disable the enter key until I hear back from the server on the ajax call. Here is submitForm():
function submitForm() {
$.post("/ajax/files" , $("#files").serialize(), function(data){
filesReset();
if (data != "") {
$("#lastInsert table tbody:last").prepend(data);
$("#lastInsert table tbody:last tr:first").find("td").hide();
$("#lastInsert table tbody:last tr:first").find("td").fadeIn(1000);
$("#lastInsert table tbody:last tr:first").effect("highlight" , {"color": "aqua"}, 1000);
$("#lastInsert table tbody:last tr:last").remove();
} else {
alert("Insert rejected: either insufficient criteria or the server is down.");
$("#hidden").click();
}
});
}
I would prefer not to have to do anything on the server-side, because I need this submit functionality to be as fast as possible (this will be a fast paced data entry form).
A: Make use of a variable like this:
$(function(){
var running = false;
$(document).bind("keypress" , function(e){
if (e.which == 13) {
if(running === false) {
running = true;
submitForm();
}
return false;
}
})
$("#submit").click(function(){
if(running === false) {
running = true;
submitForm();
}
});
});
A: It's easier just to change your submit button you a regular button an use the onclick event to submit the form using JavaScript. That way pressing enter does nothing. Disable the button when it's clicked and enable it on success of your Ajax call.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7572696",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.