text stringlengths 8 267k | meta dict |
|---|---|
Q: Is there a way to animate setClipsToBounds on UIView? I would like to clip overflowing content using setClipsToBound:YES but I want the extraneous content to fade out. Is this possible? I tried UIView beginAnimations and it doesn't seem to take effect.
A: There are a limited number of properties that are animatable and I don't think clipsToBounds is one of them. Only thing I can think of is temporarily, at least, make two copies of your view.
When both views are visible, it will look like the view does not clip. To fade to clipping, animate the alpha of the non-clipping view to 0.0. When the animation completes you can discard the non-clipping view if you want. To fade back to non-clipping, add the non-clipping view back and animate its alpha back to 1.0. When the animation is complete, you can discard the clipping view if you want. Might be necessary to set the opaque setting on the non-clipping view to NO.
If the view contains contents that have their own alpha values, it probably will not look undetectable what's happening. But otherwise it should look for all intents and purposes like fading only the out-of-bounds portions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533212",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to set SelectedItems property of GridView in WPF using MVVM I've got a gridview in my wpf application, the xaml of which looks like this:
<ListView SelectionMode="Extended" ItemsSource="{Binding AllPartTypes}"
local:DataGridService.SelectedItems="{Binding Path=SelectedPartTypes, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<ListView.View>
<GridView>
some columns...
</GridView>
</ListView.View>
</ListView>
Here is the attached behavior I'm using to get the selected items:
public static readonly DependencyProperty SelectedItemsProperty = DependencyProperty.RegisterAttached(
"SelectedItems",
typeof(IList),
typeof(DataGridService),
new UIPropertyMetadata(new List<object>() as IList, OnSelectedItemsChanged));
static SelectionChangedEventHandler GetSelectionChangedHandler(DependencyObject obj)
{
return (SelectionChangedEventHandler)obj.GetValue(SelectionChangedHandlerProperty);
}
static void SetSelectionChangedHandler(DependencyObject obj, SelectionChangedEventHandler value)
{
obj.SetValue(SelectionChangedHandlerProperty, value);
}
static readonly DependencyProperty SelectionChangedHandlerProperty =
DependencyProperty.RegisterAttached("SelectionChangedHandler", typeof(SelectionChangedEventHandler),
typeof(DataGridService), new UIPropertyMetadata(null));
//d is MultiSelector (d as ListBox not supported)
static void OnSelectedItemsChanged(DependencyObject d, DependencyPropertyChangedEventArgs args)
{
if (GetSelectionChangedHandler(d) != null)
return;
if (d is MultiSelector)//DataGrid
{
MultiSelector multiselector = d as MultiSelector;
SelectionChangedEventHandler selectionchanged = null;
foreach (var selected in (d as DataGrid).SelectedItems) // GetSelectedItems(d) as IList)
multiselector.SelectedItems.Add(selected);
selectionchanged = (sender, e) =>
{
SetSelectedItems(d, multiselector.SelectedItems);
};
SetSelectionChangedHandler(d, selectionchanged);
multiselector.SelectionChanged += GetSelectionChangedHandler(d);
}
else if (d is ListBox)
{
ListBox listbox = d as ListBox;
SelectionChangedEventHandler selectionchanged = null;
selectionchanged = (sender, e) =>
{
SetSelectedItems(d, listbox.SelectedItems);
};
SetSelectionChangedHandler(d, selectionchanged);
listbox.SelectionChanged += GetSelectionChangedHandler(d);
}
}
public static IList GetSelectedItems(DependencyObject obj)
{
return (IList)obj.GetValue(SelectedItemsProperty);
}
public static void SetSelectedItems(DependencyObject obj, IList value)
{
obj.SetValue(SelectedItemsProperty, value);
}
This works fine for getting the selected items in the viewmodel when the user clicks a button or something. My problem is that, when the screen loads, I need to highlight the items which were previously selected. I unsuccessfully tried setting the 'SelectedPartTypes' property in the constructor of the VM, assuming that the two-way binding would take care of it. Is there an easy way to show which items are selected when the control loads?
A: Can't you bind the IsSelected property in the ListBoxItem Style?
<Style TargetType="ListBoxItem">
<Setter Property="IsSelected" Value="{Binding IsSelected}" />
</Style>
If your data objects don't have a property to track selection, you may need to use a converter to return true if the current object is within SelectedPartTypes
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533221",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Why won't embedded image display? I am developing a Silverlight class library that contains several templated controls. One of these controls displays an image that is "embedded" in the class library. However, when I display the control in an application, the image does not appear.
Here is how I have the image defined in the ControlTemplate for the custom control:
<Style TargetType="local:MyControl">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:MyControl">
<Border Background="DarkGray"
HorizontalAlignment="Center"
VerticalAlignment="Center"
>
<StackPanel Orientation="Vertical"
>
<StackPanel Orientation="Horizontal">
<Image Height="102"
Margin="0,0,6,6"
Source="/Company.Product.Silverlight;component/Images/Logo.png"
VerticalAlignment="Top"
Width="145"
/>
<StackPanel Orientation="Vertical">
<TextBlock Height="23"
HorizontalAlignment="Left"
Text="{TemplateBinding Text1}"
TextWrapping="Wrap"
VerticalAlignment="Top"
Width="169"
/>
<TextBlock Height="56"
HorizontalAlignment="Left"
Text="{TemplateBinding Text2}"
TextWrapping="Wrap"
VerticalAlignment="Top"
Width="169"
/>
<TextBlock Height="23"
HorizontalAlignment="Left"
Text="{TemplateBinding Text3}"
TextWrapping="Wrap"
VerticalAlignment="Top"
Width="169"
/>
</StackPanel>
</StackPanel>
<TextBlock Height="64"
HorizontalAlignment="Left"
Margin="0,6,0,0"
Text="{TemplateBinding Text4}"
TextWrapping="Wrap"
VerticalAlignment="Top"
Width="326"
/>
<TextBlock Height="20"
HorizontalAlignment="Left"
Margin="0,6,0,0"
Text="{TemplateBinding Text5}"
TextWrapping="Wrap"
VerticalAlignment="Top"
Width="326"
/>
</StackPanel>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
The Build Action for the image file is set to Resource.
The only other thing to note is that the default namespace for the project is "Company.Product" (no .Silverlight suffix) because the majority of the code is linked from the .NET class library of that name. The assembly name is "Company.Product.Silverlight".
Any ideas why the image would not be displayed?
UPDATE
I've updated the code above to show the complete template.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533222",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Testing IE9: Is there a lab I can log into remotely to debug an IE9 issue Is there a virtual testing center 'in the cloud' that I can remote into to run different configurations of IE9? I have a heavily modified jquery plugin that some users have reported to be broken in IE9. However every configuration we have tried we are unable to reproduce the issue.
A: I don't use any cloud based solutions, but Microsoft provides (free of charge) a test VM for most versions of IE which can be used with VirtualPC. I have found it to be very useful.
http://www.microsoft.com/download/en/details.aspx?id=11575
A: You could try http://crossbrowsertesting.com - they offer one free hour of testing and there are a variety of OS / IE9 combinations.
The other possibility is browserlabs.com - they don't have OS variants, but do have access to IE debugging tools built in.
A: Saucelabs offers 45 mins/month free manual testing:
http://saucelabs.com/pricing
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533224",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Magento Fatal error: Maximum execution error solution, on WAMP While installing Magento, on WAMP I was getting timeout errors a lot like
Fatal error: Maximum execution time of 60 seconds exceeded in c:\wamp\www\magento\lib\Zend\Db\Statement\Pdo.php on line 228
I have no idea where to look to increase the execution time if needed. Can anyone help with this error?
A: You can also adjust the max_execution_time in your htaccess using
php_value max_execution_time 18000
A: This would be in your PHP ini file max_execution_time
Runtime Configuration
A: Try making sure your settings are:
*
*max_execution_time is 0 and
*max_input_time = 60 --> change max_input_time = 6000
*memory_limit = 128M --> change it to memory_limit = 512MB
after this I re-installed magento and it worked for me.
I hope this helps you.
A: change the following value in your php.ini
max_execution_time = 18000
A: I got the same problem, as suggested I did the following changes.
*
*(wampserver-path)\bin\apache(Apache Version)\bin\php.ini - Set the
value max_execution_time = 1800
*(wampserver-path)\bin\php(PHPVersion)\php.ini - Set the value
max_execution_time = 1800
But it didn't work. Then I made the next change
*
*In the host/(path-to-magento)/index.php, just after the opening <?php
tag, added the following. set_time_limit(1800);
<?php
set_time_limit(1800);
//** Other bunches of code
?>
Then tried to install a fresh copy. It worked! Hope this helps...
A: is this ok or not want is your Recommended ?
max_execution_time = 15000
max_input_time = 15000
session.gc_maxlifetime = 15000
memory_limit = -1
upload_max_filesize = 150
A: I did that by deleting the file app\etc\local.xml
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533232",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How can MEF resolve dependencies of assemblies that don't live at the root of the application? I have written my application to be a class library that is launched by a win32 MFC application. Each of my views is a separate assembly that is located with the base class library that is located in a sub-directory of the hosted MFC application.
My question is, how can I get MEF to resolve the dependencies of my exported classes using the assemblies from this sub-directory instead of the root directory?
This is what I want:
ParentFolder
myapp.exe
SubFolder
myMvvmWindow.dll
myMvvmSubWindow.dll
*Microsoft.Expression.Interactions.dll*
This is what I have to have now:
ParentFolder
myapp.exe
*Microsoft.Expression.Interactions.dll*
SubFolder
myMvvmWindow.dll
myMvvmSubWindow.dll
A: You can also do this in your app.config file:
Is it possible to set assembly probing path w/o app.config?
This is generally how I handle it.
A: MEF will not handle this scenario for you, as it uses the CLR's normal assembly loading mechanisms to find dependencies.
However, you can easily work around this for a specific subdirectory by handling AppDomain.AssebmlyResolve. If you check your sub folder for the assemblies that don't resolve in your main directory, you can load them yourself and make this function properly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533233",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: UI Controls for Java I'm looking for UI Controls for Java Applications. Just like how there are so many libraries for .Net, like Telerik, DevExpress, Infragistics, etc.
Are there similar libraries for Java Applications?
Thanks!
A: go for
*
*Qt Jambi
*jgoodies
*SwingX
*SWT
*NetBeans Platform
*Eclipse Rich Client Platform
A: This was recommended to me by a good friend from Zappos.com :: http://www.zkoss.org/
A: I think it depends in the IDE you are using. WebLogic has custom controls (http://download.oracle.com/docs/cd/E13196_01/platform/docs81/isv/controls.html) as well as instructions on how to create your own custom controls.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533241",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to use getElementById in PHP I'm trying to select all of the images of a dynamically produced page (drupal6) that have a specific ID, so I can apply a class.
I've read the docs on php.net for getElementById and setIdAttribute but the docs don't make much sense to me, and my attempts at declaring the ID then calling it don't work. I've also looked through the various similar posts here and have not fared better.
I'm really just looking for a base example of how I'm supposed to use these two functions together to get images of a specific ID.
EDIT -
I'm sorry I was vague - I can't use Jquery/javascript (it was my first choice). based on what I'm doing I can't risk a FOUC. is jquery/javascript going to be my only choice? - I would prefer PHP if possible
Thanks
Stephanie
A: Here you are some quick and dirty code to take as starting point:
$dom = new DOMDocument;
$dom->loadHTML('<p><img src="1.jpg"></p><p><img id="foo" src="2.jpg"></p><p><img src="3.jpg"></p>');
$foo = $dom->getElementById('foo');
if( !is_null($foo) && $foo->nodeName=='img' ){
$foo->setAttribute('class', 'bar');
echo $dom->saveHTML();
}
A: You should use javaScript for that. Using jQuery is pretty straightfoward
<script type='text/javascript'>
$.ready(function(){
$(".class_name").css("THE CSS YOU WANT TO APPLY TO THE ELEMENTS WITH THE CLASS 'class_name' ");
});
</script>
if you want to catch a specific image, you can use:
<script type='text/javascript'>
$.ready(function(){
var src_of_img = $("#ID_OF_IMAGE").attr("src");
alert("the src of the image with the ID you specified is: " + src_of_img);
});
</script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533244",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can i animate a div class using auto instead of a fixed number? for the life of me I cannot figure this out, I am trying to animate a div to its natural height, however jquery only lets me drop in values. I would like this to auto size depending on the amount of content...the line in the code I am having trouble with is:
$elem.addClass('current').animate({height: '100'},300);
I would like 100 to be auto. PLEASE HELP!
Here is the code:
$list.find('.st_arrow_down').live('click',function(){
var $this = $(this);
hideThumbs();
$this.addClass('st_arrow_up').removeClass('st_arrow_down');
var $elem = $this.closest('li');
var $plus = $this.closest('li').height();
$elem.addClass('current').animate({height: '100'},300);
var $thumbs_wrapper = $this.parent().next();
$thumbs_wrapper.show(200);
});
$list.find('.st_arrow_up').live('click',function(){
var $this = $(this);
$this.addClass('st_arrow_down').removeClass('st_arrow_up');
hideThumbs();
});
A: You mean computed height?
$elem.addClass('current').animate({height: $elem.height()},300);
This won’t work if you have a fixed height set for $elem using CSS.
A: The only possibility I see is to clone the node (remove the fixed height), place it somewhere offscreen, and measure it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533245",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Setting the value to list I am facing a issue in setting the value to the list of SoyFileSupplier,the list should have a value of type file,the soyfilesetParse class is used for parsing by passing a soyFileSupplier list,setting the value to a file.(sample.soy)
The sample code is as below:
public class test {
main() {
soyTree=parseSoyFiles(soyFileSuppliers);
}
}
The calling class is :
public class soyFileSetParse {
public static SoyFileSetNode parseSoyFiles(List<SoyFileSupplier> soyFileSuppliers)
throws SoySyntaxException {
IdGenerator nodeIdGen = new IntegerIdGenerator();
SoyFileSetNode soyTree = new SoyFileSetNode(nodeIdGen.genStringId(), nodeIdGen);
for (SoyFileSupplier soyFileSupplier : soyFileSuppliers) {
soyTree.addChild(parseSoyFileHelper(soyFileSupplier, nodeIdGen));
}
return soyTree;
}
}
Setting to file type :
public class SoyFileSupplier {
/**
* Creates a new {@code SoyFileSupplier} given a {@code File}.
*
* @param inputFile The Soy file.
*/
public SoyFileSupplier(File inputFile) {
this(Files.newReaderSupplier(inputFile, Charsets.UTF_8), inputFile.getPath());
}
I am not getting what i am doing wrong.
A: Since parseSoyFiles(...) is a static method of the soyFileSetParse class, you'll need to invoke it with the class name, without the need for creating an instance of the class, as in
ClassName.methodName(args)
Therefore, the content of your main() method should look as follows
SoyFileSetNode soyTree = soyFileSetParse.parseSoyFiles(soyFileSuppliers);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533254",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Changing movieclips in FlashDevelop (or other IDEs with no graphics) I am doing this:
[Embed(source = "../lib/hfront.swf")]
private var charfront1Class : Class;
private var charfront1:MovieClip = new charfront1Class;
in order to create a movieclip object in FlashDevelop. Because there is no option (like in CS5) to give a library object a class inherently.
What I need to do is be able to switch which movie clip is being displayed as my character walks about. Do I have to create a separate class for each movieclip and call them in and out of visibility?? Or is there a better way, a way to "switch" which movie clip my current class is pointing to?
Thanks
A: Firstly the embed isn't correct. If you embed an entire SWF like that you won't be able to control its timeline.
To have a MovieClip that you can manipulate you must embed a symbol of this SWF:
[Embed(source = "../lib/hfront.swf", symbol="walk")]
private var walkClass : Class;
private var walk:MovieClip = new walkClass;
[Embed(source = "../lib/hfront.swf", symbol="run")]
private var runClass : Class;
private var run:MovieClip = new runClass;
Secondly, make sure you actually call stop() for each animation or they will run (and consume CPU) even if they are off the display list.
Finally here's a (naive) example of showing the 2 embedded anims (as children of a class extending Sprite):
// current anim
private var current:MovieClip;
// showAnim("run") or showAnim("walk")
public function showAnim(anim:String):void {
if (current) { current.stop(); removeChild(current); }
current = this[anim];
addChild(current);
current.gotoAndPlay(1);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533258",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Excel VBA - Trying to pull data from directory of excel files, continued
Possible Duplicate:
Excel - VBA Question. Need to access data from all excel files in a directory without opening the files
So I've been trying to put together the code people have been sending me and this is what I've got so far...
Dim xcell As Range
Dim ycell As Range
Dim sheetname As String
Dim wbList() As String, wbCount As Integer, i As Integer
Dim wbname As String
FolderName = "\\Drcs8570168\shasad\Test"
wbname = Dir(FolderName & "\" & "*.xls")
While wbname <> ""
Set ycell = Range("a5", "h5")
Set xcell = Range("a2", "h2")
sheetname = "loging form"
ycell.Formula = "=" & "'" & FolderName & "\[" & wbname & "]" _
& sheetname & "'!" & xcell.Address
Wend
End Sub
Since I'm not that familiar with this type of code I didn't change much from what people supplied me but I'm hoping it makes some sense together. The problem seems to be that the loop won't stop and it isn't outputting anything either.
A: I'm not going to provide code, as you should work this out yourself in order to learn. (If you're looking for someone to write the entire code for you, you're at the wrong site - you need to try somewhere like Rentacoder.)
This should get you started, though...
wbList() is an array of strings. It should be where the return value of Dir() is assigned.
For each element in wbList you assign the string to wbName. That's what wbCount and i are declared for - wbCount would be the number of strings in wbList, and i would be the current index as you iterate through the array.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533262",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Is there a way to find out which variables in a knockout model are currently bound to the DOM? Is there a way to get a list of variables in a knockout model that are currently bound to the DOM?
Alternatively, is there a way to query a variable and find out if changing it would lead to a change in the DOM?
A: Using Knockout 1.3 beta, you can use ko.dataFor(element) to return the data that would be bound against the element at that level.
This means that if you had an object like:
var myObject = { id: 1, name: "Bob" }
and bound it to an element
<div id="myElement" data-bind="text: name"></div>
ko.dataFor(document.getElementById("myElement")) would return myObject and not just the name.
Prior to 1.3, inside of a jQuery Template, you can use tmplItem to return this type of data.
There is not really a way to programmatically determine if changing an observable will specifically alter a certain element.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533264",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: jQuery Box Prob I am trying to solve a rectangle problem using jQuery. Basically, I have 3 square boxes which fix inside a larger box.
I know the larger box has a max-width of 500px. I do not know what the sizes of 1, 2 or 3 will be - but I know that their aspect ratio's can change and that they must fit proportionally into the box.
How would I go about always ensuring that no matter what shape - the 3 rectangles are always proportionally sized inside the 500px box ?
A: After solving the system of equations, I believe the following is true.
w = Overall width (500)
h = Overall height
w1 = Width of B1
h1 = Height of B1
w2 = Width of B2
h2 = Height of B2
w3 = Width of B3
h3 = Height of B3
a1 = Aspect ratio of B1 (width/height)
a2 = Aspect ratio of B2 (width/height)
a3 = Aspect ratio of B3 (width/height)
w1 = (500/a2 + 500/a3) / (1/a1 + 1/a2 + 1/a3)
500 px, a1, a2, and a3 are knowns. Solve for w1, then w2, and w3. Use a1,a2, and a3 to determine h1, h2, and h3.
I believe your algorithm should be:
1: Find w1
w1 = (500/a2 + 500/a3) / (1/a1 + 1/a2 + 1/a3)
2: Find w2 and w3
w1+w2 = 500
w1+w3 = 500
3: Determine ideal h1, h2, and h3 via aspect ratio
h1 = w1/a1
h2 = w2/a2
h3 = w3/a3
4: Best-Fit h1, h2, and h3
h = h1 = max(h2+h3, h1)
h2 = h2 + ((h - (h2+h3))/2)
h3 = h3 + ((h - (h2+h3))/2)
Here are the steps I followed
Eq1: w1/a1 = h1 [aspect ratio]
Eq2: h1 = (h2 + h3) [see diagram]
Eq3: h2 = w2/a2 [aspect ratio]
Eq4: h3 = w3/a3 [aspect ratio]
Eq5: w2 = 500 - w1 [see diagram]
Eq6: w3 = 500 - w1 [see diagram]
w1/a1 = h1 [Eq1]
w1/a1 = (h2 + h3) [Eq2]
w1/a1 = (w2/a2 + w3/a3) [Eq3, Eq4]
w1/a1 = ((500 - w1)/a2 + (500 - w1)/a3) [Eq5, Eq6]
w1/a1 = 500/a2 - w1/a2 + 500/a3 - w1/a3
w1/a1 + w1/a2 + w1/a3 = 500/a2 + 500/a3
w1 * (1/a1 + 1/a2 + 1/a3) = 500/a2 + 500/a3
w1 = (500/a2 + 500/a3) / (1/a1 + 1/a2 + 1/a3)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533274",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: jQuery function (toggling src attr of the img) I kind of not familiar with all that JS stuff and everything but today I need to use some jQ magic and I read a couple of articles and here's what I've done:
$('.thumb_img').click(function() {
$(this).attr('src', $(this).attr('src').replace('img/', 'img/full/'));
})
Everything works perfectly but I need to make it toggling. The basic idea of this function is to change the src of the image user clicked (just add a "/full" in the path) and if clicked already modificated image again, delete "/full" from the path.
I really have no idea how to make it.
Thanks for any help in advance.
A: One way to do it:
$( '.thumb_img' ).click( function () {
var src = this.src;
if ( src.indexOf( '/full/' ) !== -1 ) {
src = src.replace( '/full/', '/' );
} else {
src = src.replace( 'img/', 'img/full/' );
}
this.src = src;
});
Event delegation:
$( '#images' ).delegate( '.thumb_img', 'click', function () {
var src = this.src;
if ( src.indexOf( '/full/' ) !== -1 ) {
src = src.replace( '/full/', '/' );
} else {
src = src.replace( 'img/', 'img/full/' );
}
this.src = src;
});
where #images selects the <div id="images"> element that contains all the images.
A: $('.thumb_img').click(function() {
//Store your src value so you don't need to get it again.
var src = $(this).attr('src');
//Determine whether the image is currently "full"
var full = src.indexOf('full/') > -1;
//If it's full, remove it, otherwise, put it in the src.
src = full ? src.replace('img/full/', 'img/') : src.replace('img/', 'img/full/');
//Set your SRC value
$(this).attr('src', src);
})
A: $('.thumb_img').not('.state').click(function() {
$(this).attr('src', $(this).attr('src').replace('img/', 'img/full/')).toggleClass('.state');
})
$('.thumb_img.state').click(function() {
$(this).attr('src', $(this).attr('src').replace('img/full/', 'img/')).toggleClass('.state');
})
You can use a class toggle.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533281",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Where is hcidump on an android phone? I am trying to troubleshoot a bluetooth connection and I cannot find hcidump on the Droid X2, Atrix or Galaxy.
According to this: https://sites.google.com/a/android.com/opensource/projects/bluetooth-faq I should have the BlueZ tools somewhere... question is where?!
I found and copied over binaries for l2ping, hciconfig, and hcitool from here: http://gitorious.org/android-obex/pages/Home
Where can I find the hcitool binary if it is not provided in the stock OS?
BTW, all three phones are rooted.
A: Found a binary thanks to this post. A direct link to the hcidump download is here. This binary works on the Droid X2.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533284",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Rounded Textured Segmented control style deprecated in OSX 10.7? What should I use? I'm getting this warning message when I try using "Segmented control" with style "Rounded Textured".
It is the default style in Interface Builder, so I wonder why is it complaining?
If I set to any other style, the warning goes away. But I want to use this style, so that it matches other controls in the task bar.
OSX10.7 / XCode 4.1
A: What about "automatic"? That's what's always looking good for me.
A: I've just hit this issue and the suggested fix of using "Automatic" doesn't work for me. I managed to fix it by setting the Deployment Target of the .xib to 10.6. My project's target deployment is already 10.6, so it should have been anyway.
Don't forget to unset "Use Auto Layout" if you actually want to run your App on 10.6, else it will throw an exception:
A: Using "Textured Square" worked best for me.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533285",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Java DateFormat parse() doesn't respect the timezone Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("America/New_York"));
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
df.setTimeZone(TimeZone.getTimeZone("America/New_York"));
try {
System.out.println(df.format(cal.getTime()));
System.out.println(df.parse(df.format(cal.getTime())));
} catch (ParseException e) {
e.printStackTrace();
}
Here is the result:
2011-09-24 14:10:51 -0400
Sat Sep 24 20:10:51 CEST 2011
Why when I parse a date I get from format() it doesn't respect the timezone?
A: DateFormat.parse() is NOT a query (something that returns a value and doesn't change the state of the system). It is a command which has the side-effect of updating an internal Calendar object. After calling parse() you have to access the timezone either by accessing the DateFormat's Calendar or calling DateFormat.getTimeZone(). Unless you want to throw away the original timezone and use local time, do not use the returned Date value from parse(). Instead use the calendar object after parsing. And the same is true for the format method. If you are going to format a date, pass the calendar with the timezone info into the DateFormat object before calling format(). Here is how you can convert one format to another format preserving the original timezone:
DateFormat originalDateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy");
DateFormat targetDateFormat = new SimpleDateFormat("EEE., MMM. dd, yyyy");
originalDateFormat.parse(origDateString);
targetDateFormat.setCalendar(originalDateFormat.getCalendar());
return targetDateFormat.format(targetDateFormat.getCalendar().getTime());
It's messy but necessary since parse() doesn't return a value that preserves timezone and format() doesn't accept a value that defines a timezone (the Date class).
A: You're printing the result of calling Date.toString(), which always uses the default time zone. Basically, you shouldn't use Date.toString() for anything other than debugging.
Don't forget that a Date doesn't have a time zone - it represents an instant in time, measured as milliseconds since the Unix epoch (midnight on January 1st 1970 UTC).
If you format the date using your formatter again, that should come up with the same answer as before.
As an aside, I would recommend the use of Joda Time instead of Date/Calendar if you're doing any significant amount of date/time work in Java; it's a much nicer API.
A:
DateFormat is an abstract class for date/time formatting subclasses
which formats and parses dates or time in a language-independent
manner. The date/time formatting subclass, such as SimpleDateFormat,
allows for formatting (i.e., date -> text), parsing (text -> date),
and normalization. The date is represented as a Date object or as the
milliseconds since January 1, 1970, 00:00:00 GMT.
From the spec, it return EPOCH time
A: A java.util.Date object is not a real Date-Time object like the modern Date-Time types; rather, it represents the number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT (or UTC). Since it does not hold any format and timezone information, it applies the format, EEE MMM dd HH:mm:ss z yyyy and the JVM's timezone to return the value of Date#toString derived from this milliseconds value. If you need to print the Date-Time in a different format and timezone, you will need to use a SimpleDateFormat with the desired format and the applicable timezone e.g.
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("America/New_York"));
String strDate = sdf.format(date);
System.out.println(strDate);
Note that the java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Solution using java.time, the modern API:
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("America/New_York"));
System.out.println(zdt);
// With timezone offset
OffsetDateTime odt = zdt.toOffsetDateTime();
System.out.println(odt);
// In a custom format
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss Z", Locale.ENGLISH);
String formatted = dtf.format(odt);
System.out.println(formatted);
}
}
Output:
2021-06-04T14:25:08.266940-04:00[America/New_York]
2021-06-04T14:25:08.266940-04:00
2021-06-04 14:25:08 -0400
Here, you can use yyyy instead of uuuu but I prefer u to y.
Learn more about java.time, the modern Date-Time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533290",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: vim gf with resource:// I'm working on some Firefox extensions and I'm trying to set up my vim to open modules using the gf keys.
An inclusion looks like this:
Components.utils.import("resource://grwmodules/EventProvider.jsm", scope);
which should be modules/EventProvider.jsm
I created a file to set up the environment. Here is what I have so far:
function! s:GetModuleName(name)
let l:output = a:name
if(a:name =~ "^resource://grwmodules")
let output = substitute(a:name, "resource://grwmodules", "modules", "")
endif
return l:output
endfunction
function! GetGrwFNName(name)
let l:output = s:GetModuleName(a:name)
return l:output
endfunction
set includeexpr=GetGrwFNName(v:fname)
set isf+=:
set include=Components.utils.import("resource[:/]\+.\+")
After added the isf+=: line, the :checkpath command works. But when I press gf on the file, the vim opens a new file which name would be resource://grwmodules/EventProvider.jsm. So it looks like when I press the gf it doesn't convert the name using GetGrwFNName.
Any ideas?
A: You'd have to create an autocommand FileReadCmd, e.g. what netrw has for http:// urls:
:verbose au FileReadCmd
HTH
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533294",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Bash tab completion changed behavior For a long time, I have been used to being able to type something like:
$opt/foo/m
and so on to navigate my project within different environments. It is really useful: just set up $opt (say, /home/$USER/projects/opt - and go from your dev user, to qa, to live, and $opt is $opt.
As of the release of bash4.2, this behavior has changed. Now tab completion leads to an escaped $ sign.
$opt/foo => \$opt/foo <= not at all what I meant!
While the maintainers are discussing how this should work, I would like to find a new set of habits I could use to get back to my comfort zone. What would be a good trick? Something that my fingers could learn, to have some root configured and go from there without worrying about where I am.
A: It's not perfect, but a workaround is to use ESC ctrl-e to force expansion of the variable before hitting tab (at least in emacs mode...not sure about vi mode)
A: Building on frankc's answer: Try putting the following into ~/.inputrc:
"TAB": "\M-\C-e\M-\C-t"
"\M-\C-t": complete
then start a new shell. What this does:
*
*Changes the TAB key to insert two characters: ESC-Ctrl-e ESC-Ctrl-t.
*Maps ESC-Ctrl-t to the complete function, which is what's usually invoked when you press TAB. (You could use any other key combination instead of ESC-Ctrl-t, but that one is normally unused.)
Since ESC-Ctrl-e is already mapped to the shell-expand-line function, now when you press TAB, bash first expands your variable ($opt), then autocompletes as usual.
A: The workarounds suggested here and elsewhere either failed altogether for me, or were too cumbersome to type.
Eventually, a friend recommended using zshell (zsh). It works! I did no customizations, leaving my .zshrc blank.
Now I got my tab completion back in order. It works a little differently than I am used to: a mix of old bash-style and vi-style. Pressing tab displays a list of multiple options are possible, then tabbing again will start selecting from that list and alternating, like vi.
I am pretty happy.
A: zsh solution is all that worked for me. It was trivial converting my .bashrc => .zshrc, and I have some complex shell functions/aliases.
I agree, how in the world did the bash maintainer's break this very basic tab completion functionality.
Another solution, which I've not tried is using bash from another distribution. I've only seen this in the Mint 13 release. Ubuntu/Fedora bash works fine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533296",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Workaround for Safari iframe webkit scaling bug? There seems to be a webkit scaling bug impacting Safari for Windows (v5.1) and both Safari/Chrome for Mac. When you create an iframe and use the CSS tag -webkit-transform with a 'scale' value less than 1 (say, 0.5), elements of the page are missing when it renders the scaled version of the page.
I've built the smallest test page I can to illustrate the issue:
<html>
<head>
<title>iframe webkit scale bug</title>
<style type="text/css">
iframe.preview
{
width: 1024px;
height: 768px;
border: 1px solid black;
-webkit-transform: scale(0.5);
-webkit-transform-origin: 0 0;
}
</style>
</head>
<body>
<iframe class="preview" src="http://www.google.com/"></iframe>
</body>
</html>
As a new user to stackoverflow apparently I'm not yet allowed to attach screenshots to this post. But I had 'em and was willing to share! :)
Imagine if you will, a screenshot from Chrome (success case, see the [I'm Feeling Lucky] button, as well as some links at the bottom... everything rendered OK at 50% scale).
Now imagine a screenshot from Safari (failure case, missing [I'm Feeling Lucky] button, no links at the bottom... many page elements missing).
This happens consistently for all sorts of pages brought into the iframe; elements just go missing. It also seems to happen whether or not you have a wrapper div around the iframe and constrain its dimensions (that was one workaround I tried).
Any ideas?
A: The Safari update yesterday (10/12/2011) fixes this bug. Woot.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533298",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Excel macro to comparison of rows I am trying to do below example, not able to do it.
Excel Data in Sheet1:
id Sysid option status
XYZ XT Open status_1
US XT Close Status_1
US XT Open Stauts_2
NJ XT Open Status_2
IND VX Close Status_1
BAN VX Open Status_1
CHN XY Open Status_1
YST xy Close Status_1
In above data Status_1 and Sysid defines unique record,Based on this condition i have to find out which records have open and close difference for that unique record combination. If options are different I have to copy that data to different sheet using excel macro.This should work only for id's US and CHN.Suppose if id has US ,it should compare with matching record based on sysid and Status. Any help appreciated.
Output Like below:
XYZ XT Open status_1
US XT Close Status_1
CHN XY Open Status_1
YST xy Close Status_1
A: Edited to include test for "US" or "CHN"
Sub Tester()
Const COL_ID As Integer = 1
Const COL_SYSID As Integer = 2
Const COL_STATUS As Integer = 4
Const COL_OPTION As Integer = 3
Const VAL_DIFF As String = "XXdifferentXX"
Dim d As Object, sKey As String, id As String
Dim rw As Range, opt As String, rngData As Range
Dim rngCopy As Range, goodId As Boolean
Dim FirstPass As Boolean, arr
With Sheet1.Range("A1")
Set rngData = .CurrentRegion.Offset(1).Resize( _
.CurrentRegion.Rows.Count - 1)
End With
Set rngCopy = Sheet1.Range("F2")
Set d = CreateObject("scripting.dictionary")
FirstPass = True
redo:
For Each rw In rngData.Rows
sKey = rw.Cells(COL_SYSID).Value & "<>" & _
rw.Cells(COL_STATUS).Value
If FirstPass Then
'Figure out which combinations have different option values
' and at least one record with id=US or CHN
id = rw.Cells(COL_ID).Value
goodId = (id = "US" Or id = "CHN")
opt = rw.Cells(COL_OPTION).Value
If d.exists(sKey) Then
arr = d(sKey) 'can't modify the array in situ...
If arr(0) <> opt Then arr(0) = VAL_DIFF
If goodId Then arr(1) = True
d(sKey) = arr 'return [modified] array
Else
d.Add sKey, Array(opt, goodId)
End If
Else
'Second pass - copy only rows with varying options
' and id=US or CHN
If d(sKey)(0) = VAL_DIFF And d(sKey)(1) = True Then
rw.Copy rngCopy
Set rngCopy = rngCopy.Offset(1, 0)
End If
End If
Next rw
If FirstPass Then
FirstPass = False
GoTo redo
End If
End Sub
A: Use the macro recorder and do a unique advanced filter on the data then you can do your comparisons.
http://office.microsoft.com/en-us/excel-help/filter-for-unique-records-HP003073425.aspx?CTT=3
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533300",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Reports PHPUnit ZendFramework I'm running phpunit tests with zendframework using netbeans but the reports are not being generated. The folder was created however no reports.
My directoty struture:
-application
--models
--modules
-library
-log
--report
-bootstrap.php
-phpunit.xml
phpunit.xml
<phpunit bootstrap="./bootstrap.php">
<testsuite name="Application Test Suite">
<directory>./application</directory>
</testsuite>
<testsuite name="Library Test Suite">
<directory>./library</directory>
</testsuite>
<filter>
<!-- If Zend Framework is inside your project's library, uncomment this filter -->
<!--
<whitelist>
<directory suffix=".php">../../library/Zend</directory>
</whitelist>
-->
</filter>
<logging>
<log type="coverage-html" target="./log/report" charset="UTF-8" yui="true" highlight = "true" lowUpperBound="50" highLowerBound="80" />
<log type="testdox" target="./log/testdox.html" />
</logging>
The tests are running correctly but How should I configure my phpunit.xml to generate the reports?
My PHPUnit version is 3.5.15
A: I had this problem, too, and if i remember correctly it had something to do with xdebug (or similar) not running - but in my case the command line tool has thrown some error.
A: I figured out, I tried running from terminal. It was throwing a memory exception, I increased php memory limit and works fine now.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533304",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: DotNetOpenAuth.... what is? I'm not sure what it is and what is DotNetOpenAuth. Can you explain it in few words?
I am investigating about the management of users in a web application (asp.net mvc)
A: From www.dotnetopenauth.net:
DotNetOpenAuth is a well established open source library that bring OpenID, OAuth, and ICard capabilities to the Microsoft .NET Framework.
So:
A .NET library, that is open source and which implements OpenID, OAuth and ICard. OpenID is the login mechanism used on StackOverflow, OAuth is a similar one as is ICard.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Getting attr of an option in jQuery I have a form like this:
<select name="category" id="cat">
<option value="cat1" id="hello">Category1</option>
<option value="cat2" id="hello2">Category2</option>
</select>
if i use $('#cat').val() with change function in #cat id , it displays values(cat1 or cat2).
i want to learn how can i get id or Category1(or Category2) ?
A: $('#cat option:selected').attr('id');
the selector :selected will return the selected option in a select element, or an array in case of multiple="multiple"
A: $('select').change(function() {
alert($('option:selected',this).attr('id'));
});
Fiddle: http://jsfiddle.net/each/kqb9S/
A: Instead of .val(), use .attr().
$('#cat').on('change', function() {
alert( $(this).children('option:selected').attr('id') )
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="category" id="cat">
<option value="cat1" id="hello">Category1</option>
<option value="cat2" id="hello2">Category2</option>
</select>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533306",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Django sub queries I have a basic database that I want to pull out sub data (related) in the same view:
models.py:
class InvoiceHeader(models.Model):
customer = models.CharField(max_length = 255)
number = models.IntegerField(unique = True)
class InvoiceLine(models.Model):
description = models.CharField(max_length = 255)
price = models.DecimalField(max_digits = 10, decimal_places = 2)
invoiceheader = models.ForeignKey(InvoiceHeader)
views.py:
def list_invoices(request):
invoices = InvoiceHeader.objects.all()
What I am trying to get is the invoice total in the list_invoices view which would consist of the invoicelines.price (totalled) for each invoiceheader such that in the template I can just put:
{% for invoice in invoices %}
{{ invoice.subtotal }}
{% endfor %}
I think it is something to do with def something in the models.py file but I am getting lost with this.
So any help would be much appreciated.
A: You want to use aggregation:
from django.db.models import Sum
def list_invoices(request):
invoices = Item.objects.all().annotate(subtotal=Sum('invoiceline__price'))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533309",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: PHP IF-statement to change color of table rows ? I have the following code written below. With this code I want to fetch data from MySQL database and print(echo) the result in table rows, each row with different colour. With this code data is fetched from database successfully but my condition for change color of rows is not working. Please check my code and let me know where I'm wrong.
<table width="500" align="center" style="border:1px solid;">
<?php
$query = "SELECT * FROM main_cat";
$result = mysql_query($query);
$count = mysql_num_rows($result);
while($end = mysql_fetch_array($result)){
echo "<tr>";
if($count % 2 == 0){
echo '<td bgcolor="#CCCCCC">'.$end['page_name'].'</td>';
}else{
echo '<td bgcolor="#99CC66">'.$end['page_name'].'</td>';
}
echo "</tr>";
}
?>
</table>
A: You're not initializing $count to 0 and you're not incrementing $count anywhere.
A: This should work:
<table width="500" align="center" style="border:1px solid;">
<?php
$query = "SELECT * FROM main_cat";
$result = mysql_query($query);
$i = 0;
while($end = mysql_fetch_array($result)){
echo "<tr>";
if($i % 2 == 0){
echo '<td bgcolor="#CCCCCC">'.$end['page_name'].'</td>';
}else{
echo '<td bgcolor="#99CC66">'.$end['page_name'].'</td>';
}
echo "</tr>";
$i++;
}
?>
</table>
Even better would be using CSS, namely the odd and even selectors: http://www.w3.org/Style/Examples/007/evenodd
A: You need to put a count in the while loop rather than the total number returned by the query.
Not going to write the code for you.
Before while loop set counter to zero.
In while loop check condition of counter
Then increase counter value by 1
A: If you like, you can shorten this code, and get the HTML out of the PHP code. This will allow editors like Notepad++ or NetBeans to highlight the HTML code too. Besided, you got that line of HTML only once, so it will be easier to maintain.
However, it is smartest to use css to style the alternating rows, or at least use a class to style the individual rows.
I used inline styling in my code which is dirty as it is. But bgcolor. Really? It is not even supported anymore in HTML 4.1 strict. It is old, it is icky.
<table width="500" align="center" style="border:1px solid;">
<?php
$query = "SELECT * FROM main_cat";
$result = mysql_query($query);
$i = 0;
while($end = mysql_fetch_array($result)){
$color = ($i++ % 2 == 0 ? '#CCCCCC' : '#99CC66');
$page = $end['page_name'];
?>
<tr><td style="background-color: <?=$color?>"><?=$page?></td></tr>
<?php
}
?>
</table>
Credit goes to Jeroen. It is his code I based this example on.
A: i think you should make a array of different colors and then change color of each row with change index. like this
<table width="500" align="center" style="border:1px solid;">
<?php
$query = "SELECT * FROM main_cat";
$result = mysql_query($query);
$clr=0;
$colors = array('blue','green','purple','orange','red');
while($end = mysql_fetch_array($result)){
echo '<tr style="font-size:18px;background-color:'.$colors[$clr].'">';
echo '<td bgcolor="#CCCCCC">'.$end['page_name'].'</td>';
echo '<td bgcolor="#99CC66">'.$end['page_name'].'</td>';
echo "</tr>";
$clr++;
if($clr==5)
$clr=0;
}
?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533312",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: AOL9.0 and continuously sent AJAX requests We have a campaign up and running that collects clicks. Over 50,000 clicks have been recorded from 2 different IP addresses, both with the user-agent's set to AOL9.0. I was wondering if there is a known AOL9.0 + AJAX issue or if someone is just masking their user-agent.
UA String
Mozilla/4.0 (compatible; MSIE 7.0; AOL 9.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; MDDC; BRI/1; .NET4.0C; BRI/2)
A: I do believe AOL proxies their users. Verify this by running a whois on the source IP addresses. If they are registered to AOL, then it seems likely those are proxy servers. Also check your logs to see if that UA string appears in any significant amount from other IP addresses.
As far as AJAX issues in the AOL browser, I do remember a long time ago bumping in to an issue where the response being served with Transfer-Encoding: chunked would cause the AOL browser to barf. Specifically, the chunked encoding is not 'decoded', so the hex length value is passed to your script, causing a JSON parse error. If your script expects a response and retries if it gets an error, it is possible that your code is going into an infinite retry loop.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533313",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Get rid of newline from shell commands in Ruby I am trying to run simple shell commands in my script, but am unable to get rid of new lines even using chomp or chop.
Is there something I am missing ?
u=`echo '#{l}' | cut -d: -f4`.chop()
p2=`echo '#{l}' | cut -d: -f3`.chop()
p1=`echo '#{l}' | cut -d: -f2`.chop()
h=`echo '#{l}' | cut -d: -f1`.chop()
# **Cant get newlines to go after p1 and p2 !! ??**
path="#{p1}/server/#{p2}abc"
puts path
Output:
/usr (p1)
/server
/bin (p2) abc
Expected Output:
/usr/server/binabc
Any suggestions ?
As per some suggestions, changed my code to :
h, p1, p2, u = l.split /:/
u.strip
u.chomp
puts u.inspect
Output: "string\n"
Basically I had tried using chomp before and was hitting the same problem. Do I need to call chomp in a different way or add any gem ?
A: str.chompwll remove the newline character from strings.
str.chop only removes the last character.
A: Why are you calling out to the shell for something so simple:
h, p1, p2, u = l.split /:/
A: Use either String#strip to remove all wrapping whitespace, or String#chomp (note the 'm') to remove a single trailing newline only.
String#chop removes the last character (or \r\n pair) which could be dangerous if the command does not always end with a newline.
I assume that your code did not work because the results had multiple newlines\whitespace at the end of the output. (And if so, strip will work for you.) You can verify this, however, by removing the call to chop, and then using p u or puts u.inspect to see what characters are actually in the output.
And for your information, it's idiomatic in Ruby to omit parentheses when calling methods that take no arguments, e.g. u = foo.chop.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533318",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Compare Two Tables with SQL I have two tables; one with records being recorded by operators, the other with data stored by the machines the operators are running to log down time of the machine. The data coming from the operators is one record minimum (sometimes more) per hour that the machines are operating. The data stored for downtime is a constant stream of data logging when the machines are down or when they are running.
What I want to do is take the data from the operators and compare it with the down time system to make sure that the operators are taking their weights every hour, once an hour, that the machines are operational. If the machine is down for an hour then there would be no operator record. If the machine is active during any amount of time during the hour interval, then there should be a record for that hour interval. To do this, I will need to simplify the data to one record per hour for each table and compare that there is a record for every hour on both.
My SQL knowledge isn't that broad so I don't even know if this is possible. I have tried counting items per hour and grouping data, but have not been able to successfully get them to work.
The tables reside on a Microsoft SQLExpress 2008 database. The tables themselves are lengthy.
OPERATOR Table:
Date Time Product_No Seq DateCode Internal_DateCode&ProductNo Product_Description Line Size Weight1 Weight2 Weight3 Weight4 WeightXR LSL_WT TAR_WT USL_WT LABEL MAV
8/3/11 0:37:54 1234567 23 DateCode Internal_DateCode&ProductNo Product Description L-1A 50 1575 1566 1569.5 1575.5 1573.4 1550.809 1574.623 1598.437 1564.623 1525.507 L-1A_50
DOWNTIME Table:
Line_Name Machine_Name t_stamp Shift Details Duration
R2 Changeover 9/3/11 22:17 53
R2 Filler 9/3/11 23:10 17
The machine of interest is the “Filler”, the duration is the amount of time in minutes that the machine is down.
The goal: Find out which hours the operators took weights for and which hours they did not. Find out what hours the machines were down and which hours they were active. Compare the times that the operators did not take weights with the times that the machines were active and determine if the machines were running but there are no operator records for weights when there should be.
A: ASSUMPTIONS:
1) If the Date and Time are actual date and time formats, this would be different. But without knowing, I am going to guess that they are strings (otherwise, why make them two columns?) So I'm going to guess that they are YYYY-MM-DD and HH:MI respectively.
2) It seems reasonable that the OP would want to know these facts either by SHIFT or by PRODUCT or by something. It would seem odd to just ask when they had taken weights of anything at all. I will guess that it is by ProductNo.
3) This could be done in code, but my example is easier if I create a table with the hours in it:
create table hours (hr varchar(2));
insert into hours ('01');
insert into hours ('02');
insert into hours ('03');
insert into hours ('04');
etc.
4) The tasks are somehow timebased -- that is, the report is for some specific time period. In my example, I'll choose the month of September.
Task 1: Find out which hours the operators took weights for and which hours they did not.
select h.hr, o.productno, count(*) as nbr
from hours h
left outer join operator o
on h.hr = substr (o.time, 1, 2)
where o.date between '2011-09-01' and '2011-09-30'
group by h.hr, o.productno
This should show the list of hours, and if measurements were taken, the number of times those measurements were taken in that hour for that productno. If no measurements were taken, the productno would be blank because of the outer join, which I am guessing is what the OP forgot about.
Task 2: Find out what hours the machines were down and which hours they were active.
I don't want to continue unless OP gives some clue as to my assumptions.
As it is, there is a very good chance I am completely wasting my time.
Task 3 & 4: Compare the times that the operators did not take weights with the times that the machines were active and determine if the machines were running but there are no operator records for weights when there should be.
I don't want to continue unless OP gives some clue as to my assumptions.
As it is, there is a very good chance I am completely wasting my time.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533319",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Error when compiling some simple c++ code I try to compile this cpp code on osx lion but I get an error.
#include <iostream>
using namespace std;
int main (int argc, char *argv[])
{
for(int i = 0; i < 10; i++)
{
cout << "hi";
cout << endl;
}
return 0;
}
To compile:
cc main.cpp
Error:
Undefined symbols for architecture x86_64:
"std::cout", referenced from:
_main in ccBdbc76.o
"std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)", referenced from:
_main in ccBdbc76.o
"std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)", referenced from:
_main in ccBdbc76.o
"std::basic_ostream<char, std::char_traits<char> >::operator<<(std::basic_ostream<char, std::char_traits<char> >& (*)(std::basic_ostream<char, std::char_traits<char> >&))", referenced from:
_main in ccBdbc76.o
"std::ios_base::Init::Init()", referenced from:
__static_initialization_and_destruction_0(int, int)in ccBdbc76.o
"std::ios_base::Init::~Init()", referenced from:
___tcf_0 in ccBdbc76.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status
A: Try
g++ main.cpp
This way it should work, at least using OS X
A: I'm not familiar with OSX LION. However, in the strictest sense, the errors described are not caused by the compiler, but by the linker. It seems as if the standard library is not being linked.
A: Use CC command (uppercase) to compile C++ and link to standard C++ library.
A: Normally this sort of failure happens when compiling your C++ code by invoking the C front-end. The gcc you execute understands and compiles the file as C++, but doesn't link it with the C++ libraries. Example:
$ gcc example.cpp
Undefined symbols for architecture x86_64:
"std::cout", referenced from:
_main in ccLTUBHJ.o
"std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)", referenced from:
_main in ccLTUBHJ.o
"std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)", referenced from:
_main in ccLTUBHJ.o
"std::basic_ostream<char, std::char_traits<char> >::operator<<(std::basic_ostream<char, std::char_traits<char> >& (*)(std::basic_ostream<char, std::char_traits<char> >&))", referenced from:
_main in ccLTUBHJ.o
"std::ios_base::Init::Init()", referenced from:
__static_initialization_and_destruction_0(int, int)in ccLTUBHJ.o
"std::ios_base::Init::~Init()", referenced from:
___tcf_0 in ccLTUBHJ.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status
$ g++ example.cpp
$
As you can see, using g++ makes the problems go away. The same behaviour (with slightly different messages) occurs if you use clang (which I'd recommend):
$ clang example.cpp
Undefined symbols for architecture x86_64:
"std::ios_base::Init::~Init()", referenced from:
___cxx_global_var_init in cc-IeV9O1.o
"std::ios_base::Init::Init()", referenced from:
___cxx_global_var_init in cc-IeV9O1.o
"std::cout", referenced from:
_main in cc-IeV9O1.o
"std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)", referenced from:
_main in cc-IeV9O1.o
"std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)", referenced from:
_main in cc-IeV9O1.o
"std::ostream::operator<<(std::ostream& (*)(std::ostream&))", referenced from:
_main in cc-IeV9O1.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
$ clang++ example.cpp
$
As you can see in the clang error message, you could use -v to see the linker invocation to see what's going wrong. It would show you this link line:
"/usr/bin/ld" -demangle -dynamic -arch x86_64
-macosx_version_min 10.6.8 -o a.out -lcrt1.10.6.o
/var/folders/zl/zlZcj24WHvenScwjPFFFQE+++TI/-Tmp-/cc-hdOL8Z.o
-lSystem /Developer/usr/bin/../lib/clang/3.0/lib/darwin/libclang_rt.osx.a
Or something like it - as you can see, it's linking the C runtime, not C++, and also doesn't have the C++ libraries. Using clang++ the link line is:
"/usr/bin/ld" -demangle -dynamic -arch x86_64
-macosx_version_min 10.6.8 -o a.out -lcrt1.10.6.o
/var/folders/zl/zlZcj24WHvenScwjPFFFQE+++TI/-Tmp-/cc-wJwxjP.o
/usr/lib/libstdc++.6.dylib -lSystem
/Developer/usr/bin/../lib/clang/3.0/lib/darwin/libclang_rt.osx.a
As you can see, libstdc++ is included, and presto - no link errors.
A: As of Yosemite (10.10.1), I've found that gcc with the -lc++ flag also works:
gcc -lc++ main.cpp
A: If using clang on OS X , try :
clang++ simple_cpp_program_file.cpp -o simple_cpp_program_file.out
A: Here's the solution that works on macOs Sierra:
There are two implementations of the standard C++ library available on OS X: libstdc++ and libc++. They are not binary compatible and libMLi3 requires libstdc++.
On 10.8 and earlier libstdc++ is chosen by default, on 10.9 libc++ is chosen by default. To ensure compatibility with libMLi3, we need to choose libstdc++ manually.
To do this, add -stdlib=libstdc++ to the linking command.
A: Is this GCC on Windows (MinGW) or Linux? On MinGW you need the parameters -lmingw32 -enable-auto-import. Linux might needs something similar, -enable-auto-import is most likely needed.
A: So the error ld: library not found for -lstdc++ is where the actual error lies.
To fix this, open the folder
open /Library/Developer/CommandLineTools/Packages/
Run the package macOS_SDK_headers_for_macOS_10.14.pkg
Then gem install mini_racer works!
This issue may not be only related to mini_racer as it could affect any gem that compiles an extension.。
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533321",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "49"
} |
Q: How to create a link to a Facebook object within a comment using the Facebook API I would like to be able to recreate the same comment linking ability that facebook has on their front end through the graph API (NOT javascript SDK).
For example, through the web interface I can type in @George... and then lookup one of my friends to link to in the comments. See image below.
I have been able to POST comments using the API as documented here. This is pretty simple by just POSTing to /{POST_ID}/comments with a message parameter (you can try it out here).
However, I have not found anywhere a doc to show how I can put in a link to another object within the comment post. Has anyone done this with the Facebook API?
NOTE: I have tried what one person suggested and put in a simple link. However as you can see from below, it does not give the nice formatted link of the user's name.
UPDATE: When I look what Facebook sends out on the form POST it looks like this
add_comment_text_text:post to Mark test
add_comment_text:post to @[4:Mark] test
but unfortunately, it looks like you can't post to the API in a similar manner (i.e. @[4:Mark]) and get the same results.
A: This is currently not possible with the Facebook Graph API, only the Facebook website. It has been logged as a feature request though.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533322",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to pass a variable on pushpin button press? I am currently using this code to disaply multiple pushpins based on an XML file. I have an onclick event for the pushpins also. But what I would like to do is the pass the Name var from each pushpin to another page.
I have set it up the way I thought it would work, but no value is being passed and the message box isn't showing the number from each stop. However when I set the Content of the pushpin to root.Name the number is shown on the pushpin fine.
void busStops_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
return;
var busStopInfo = XDocument.Load("Content/BusStops2.xml");
var Transitresults = from root in busStopInfo.Descendants("Placemark")
let StoplocationE1 = root.Element("Point").Element("coordinates")
let nameE1 = root.Element("name")
select new TransitVariables
(StoplocationE1 == null ? null : StoplocationE1.Value,
nameE1 == null ? null : nameE1.Value);
foreach (var root in Transitresults)
{
var accentBrush = (Brush)Application.Current.Resources["PhoneAccentBrush"];
var pin = new Pushpin
{
Location = new GeoCoordinate
{
Latitude = root.Lat,
Longitude = root.Lon
},
Background = accentBrush,
Content = root.Name,
Tag = root,
};
pin.MouseLeftButtonUp += BusStop_MouseLeftButtonUp;
BusStopLayer.AddChild(pin, pin.Location);
}
}
void BusStop_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
var bNumb = ((FrameworkElement)sender);
if (bNumb != null)
{
// Here is would like to pass the Name element from var transitresults to another page.
// The element Name is different for each pushpin and is parses from the XML
}
}
// Add properties to your class
public class TransitVariables
{
// Add a constructor:
public TransitVariables(string stopLocation, string name)
{
this.StopLocation = stopLocation;
this.name = name;
if (!string.IsNullOrEmpty(StopLocation))
{
var items = stopLocation.Split(',');
this.Lon = double.Parse(items[0]);
this.Lat = double.Parse(items[1]);
this.Alt = double.Parse(items[2]);
}
}
public string StopLocation { get; set; }
public string name { get; set; }
public double Lat { get; set; }
public double Lon { get; set; }
public double Alt { get; set; }
}
A: You can reference the Pushpin's Tag property inside of your handler:
void BusStop_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
var bNumb = ((FrameworkElement)sender);
if (bNumb != null)
{
//bNumb is of type Pushpin
//bNumb.Tag should have your id in it, I assume it's going to be an XElement object
string id = "Bus Number Should go here" ;
NavigationService.Navigate(new Uri("/TestPage.xaml?stopNumber=" + id, UriKind.Relative));
MessageBox.Show("Stop Number" + id);
}
}
A: Just in case anyone is interested. I worked it out and solved my issue. The key was setting the sender correctly and the tag.
public void BusStop_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
var item = (sender as Pushpin).Tag as TransitVariables;
if (item != null)
{
string id = item.name;
NavigationService.Navigate(new Uri("/DepBoard.xaml?ListingId=" + id, UriKind.Relative));
MessageBox.Show("Bus Stop Number " + id);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533323",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Does embedded fonts in css affect performance per usage? I know there is a performance overhead for loading the font file, but the question is, once it has been downloaded, can I use it freely any number of times on my HTML page? or does it add an overhead every time it is being used?
A: This has got to be the complete guide to font-face performance and optimisation: http://www.stevesouders.com/blog/2009/10/13/font-face-and-performance/
A: A static file will get downloaded only once per page. You can use firebug or chrome/safari's web inspectors to monitor the http requests. If the page is downloading the file twice, you will see it there.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533326",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: 400 Bad Request for URLs containing "&" on IIS7 with UrlRoutingModule I'm setting up ASP.net MVC 2.0 on an old WebForms site that runs on IIS 7. The old site has a 404 handler set up like:
<httpErrors errorMode="Custom">
<remove statusCode="404" subStatusCode="-1" />
<error statusCode="404" prefixLanguageFilePath="C:\..." path="/error404.aspx" responseMode="ExecuteURL" />
</httpErrors>
This 404 handler is used to simulate URL rewriting, so a URL like "/+yes-&-no" would get routed to it, and Server.Transfer()ed to the correct page. This all works.
When setting up ASP.net MVC 2.0, I add this to the web.config:
<modules runAllManagedModulesForAllRequests="false">
<remove name="UrlRoutingModule" />
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</modules>
Once this is added, all URLs containing an ampersand (e.g. "/+yes-&-no") return:
Bad Request
How do I keep the UrlRoutingModule enabled, and still allow URLs with ampersand?
Rejected Solutions:
*
*I was able to get these registry changes to work, but they have been vetoed out of security concerns.
*I was able to use URL Rewriting to change the "&" to "and", but that has SEO implications because that changes the <h1>, etc.
<rule name="RemoveIllegalAmpersands">
<match url="(+.)&(.))" />
<action type="Rewrite" url="{R:1}and{R:2}" />
</rule>
*I saw the requestPathInvalidCharacters, web.config element but we can't try it because we're still on .NET 3.5
Are there any other solutions that I've missed?
A: Have you taken a look at this post by Hanselman?
http://www.hanselman.com/blog/ExperimentsInWackinessAllowingPercentsAnglebracketsAndOtherNaughtyThingsInTheASPNETIISRequestURL.aspx
He describes how to tweak what characters are considered invalid (look for requestPathInvalidCharacters on his blog post).
Be aware that there are several landmines to be aware of if you tweak this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533329",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: The best overloaded method match for 'int.Parse(string)' has some invalid arguments Console.WriteLine("Enter the page that you would like to set the bookmark on: ");
SetBookmarkPage(int.Parse(Console.ReadLine));
It's the int.Parse(string) part that gives me the error message of the topic of this thread. Don't really understand what I should do, I'm parsing a string into an int and sending it with the SetBookmarkPage method, what am I missing?
SetBookmarkPage looks like this and is contained in the same class:
private void SetBookmarkPage(int newBookmarkPage) {}
A: There is no overload of int.Parse that takes a delegate. It sounds like you wanted to do
int.Parse(Console.ReadLine())
However, even then you're exposing your program to a potential exception. You should do something like this:
int bookmarkId = 0;
string info = Console.ReadLine();
if(!int.TryParse(info, out bookmarkId))
Console.WriteLine("hey buddy, enter a number next time!");
SetBookmarkPage(bookmarkId);
A: Change it to
SetBookmarkPage(int.Parse(Console.ReadLine()));
You were missing () after Console.ReadLine
A: You need to call Console.ReadLine:
SetBookmarkPage(int.Parse(Console.ReadLine()));
Note the extra () in the above.
Your current method is passing a delegate built from the Console.ReadLine method, not the result of the method being called.
That being said, if you're reading input from a user, I would strongly recommend using int.TryParse instead of int.Parse. User input frequently has errors, and this would let you handle it gracefully.
A: You want:
SetBookmarkPage(int.Parse(Console.ReadLine()));
At the moment it's viewing Console.ReadLine as a method group, and trying to apply a method group conversion - which will work if you're then using it as an argument for a method taking a Func<string> or something similar, but not for a method taking just a string.
You want to invoke the method, and then pass the result as an argument. To invoke the method, you need the parentheses.
A: You probably meant:
SetBookmarkPage(int.Parse(Console.ReadLine()));
Notice the parens after ReadLine. You are trying to pass a delegate for ReadLine instead of the return value.
A: Console.ReadLine is a method, you must invoke it with parenthesis:
SetBookmarkPage(int.Parse(Console.ReadLine()));
Without the parenthesis, the compiler thinks it is a method group.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533333",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Benefits of Continuous Integration workflow I'm currently planning a new project and considering the products I need to buy. Currently I'm quite definite we'll be using Git as a VCS, but I'm quite new to the whole Continuous Integration concept and confused about the benefits we can get from it. But I have a sense that this thing might greatly increase the future workflow of the team of about 5 developers I'm planning to gather on a JVM web project.
So my questions are:
*
*What benefits do I get from using some CI system compared to simply using some private Git repository like beanstalkapp?
*If I'll be using some CI system will I need to also setup or rent some private VCS repository or will it already be integrated in CIS?
*I find myself very trusting to all JetBrains products I know so far, so I'm considering TeamCity. Is this a good choice?
*Just in case. I'm wondering if there are some better "cutting edge" VCSs compared to Git I should consider?
A: 1) Benefits - The benefits are talked about in many places, I will just link to them as I cannot do a better job of it -
http://martinfowler.com/articles/continuousIntegration.html#BenefitsOfContinuousIntegration
http://en.wikipedia.org/wiki/Continuous_integration#Advantages
2) CI tools like Teamcity, Hudson / Jenkins and CruiseControl usually do not have integrated VCS. They have the ability to poll the VCS you are using and build, test, deploy etc. You will have to setup a separate repository with the VCS of your choice, private or otherwise.
3) TeamCity is an excellent CI tool. I am using it in my project with the full license. For a 5 developer team, I think TeamCity, with its developer focused features and setting will be a great CI tool. You might want to look at Jenkins though.
4) Hg ( mercurial) and Git are both pretty well known and "cutting edge" in the DVCS world. SVN is stil the most widely used VCS I believe. Git would be a good choice.
A: *
*The main benefit of CI (with TDD) is that it helps you identify failing code early.
*A CI tools like CruiseControl should integrate to your SVN repository with the help of plugins, but you need to check compatibility.
*Cant help you here, I don't know TeamCity, but I have used CruiseControl and I was happy with it.
*Personally I use my own subversion server. For work I always favor having full control of the supporting system. Now we are moving our VC Server to the cloud, but still setting up our own.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533336",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Java - Can't print image (to paper/printer) I am trying to print an Image using the following code, but the document simply stays in the print job queue, and refuses to print. In the (windows) print job queue I get:
DocumentName: Printing an image Status: [Nothing] Pages: 1, Size: 2.1Mb.
This does not happen with other applications using the same printer (word, etc).
Could anyone kindly show me where is my mistake? Thanks.
public static void main(String[] args) {
//new Painter();
MediaTracker tracker = new MediaTracker(new JPanel());
try {
Image img = ImageIO.read(new File(
"C:\\Users\\David\\Desktop\\print.jpg"));
tracker.addImage(img, 1);
tracker.waitForAll();
print(img);
} catch (Exception ex) {
ex.printStackTrace();
}
}
private static void print(final Image img) {
PrinterJob printjob = PrinterJob.getPrinterJob();
printjob.setJobName("Print");
ImgPrinter printable = new ImgPrinter(img);
try {
System.out.println("Printing.");
printable.printPage();
} catch (PrinterException ex) {
System.out.println("NO PAGE FOUND." + ex);
}
}
private static class ImgPrinter implements Printable {
Image img;
public ImgPrinter(Image img) {
this.img = img;
}
public int print(Graphics pg, PageFormat pf, int pageNum) {
if (pageNum != 0) {
return Printable.NO_SUCH_PAGE;
}
//BufferedImage bufferedImage = new BufferedImage(img.getWidth(null),
//img.getHeight(null), BufferedImage.TYPE_INT_RGB);
//bufferedImage.getGraphics().drawImage(img, 0, 0, null);
Graphics2D g2 = (Graphics2D) pg;
g2.translate(pf.getImageableX(), pf.getImageableY());
g2.drawImage(img, 0, 0, img.getWidth(null), img.getHeight(null), null);
return Printable.PAGE_EXISTS;
}
public void printPage() throws PrinterException {
PrinterJob job = PrinterJob.getPrinterJob();
boolean ok = job.printDialog();
if (ok) {
job.setJobName("TEST JOB");
job.setPrintable(this);
job.print();
}
}
}
Screenshot of problem:
This happens with both hardware and software printers(XPS Writer, CutePDF, Canon printer). The hardware shows "preparing.." on it's screen forever, and I think it wasted all it's ink, I'm not sure. If so, this code has been expensive to test....
None of these printers give an issue when printing from a word document or otherwise.
Edit: Can somebody suggest a software printer he or she has been successful with?
Click here for the Image I am trying to print.
Click here to see the print queue.
A: I just ran a quick test, and it works fine for me. I was able to print a png image.
Chances are there is something wrong with your printer.
Did you try printing a Word Document using the Word's print option.
Are there multiple printers assigned to your machine?
You could try restarting your printer?
Restart you machine?
You could implement a print dialog box to open up. That way you can select the printer.
See this link here. The code shows how to open up the print dialog in swing.
public void printPage() throws PrinterException
{
PrinterJob job = PrinterJob.getPrinterJob();
boolean ok = job.printDialog();
if (ok) {
job.setJobName("TEST JOB");
job.setPrintable(this);
job.print();
}
}
This way you can make sure a printer has been selected correctly.
The other thing you can use to make sure the image does not get distorted
Instead of this line
g2.drawImage(bufferedImage, 0, 0, (int) pf.getWidth(), (int) pf.getHeight(), null);
use the following line in the inner class
g2.drawImage(img, 0, 0, img.getWidth(null), img.getHeight(null), null);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533343",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: db4o : ActivationDepth seems to have no effect (?) Can someone please explain to me why setting
the Activation Depth seems to have no effect
in the code-sample below ?
This sample creates 'Block'-objects which all have
a number and a child-block.
Since the ActivationDepth is set to '2', I would expect
that only Block 01 and 02 would be retrieved from the
database, but it's possible to traverse child-blocks
all the way down to block 05 (?).
I guess this means that the whole graph of objects
is loaded instead of only level 01 and 02 and that is
just what I try to avoid by setting the Activation Depth.
Here is the complete code-sample :
import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import com.db4o.config.CommonConfiguration;
import com.db4o.config.EmbeddedConfiguration;
import com.db4o.query.Predicate;
public class Test02
{
private final String DATABASE_NAME = "MyDatabase";
public static void main(String[] args)
{
new Test02().test();
}
public void test()
{
storeContent();
exploreContent();
}
private void storeContent()
{
Block block01 = new Block(1);
Block block02 = new Block(2);
Block block03 = new Block(3);
Block block04 = new Block(4);
Block block05 = new Block(5);
Block block06 = new Block(6);
block01.setChild(block02);
block02.setChild(block03);
block03.setChild(block04);
block04.setChild(block05);
block05.setChild(block06);
ObjectContainer container = Db4oEmbedded.openFile(Db4oEmbedded.newConfiguration(), DATABASE_NAME);
try
{
container.store(block01);
container.store(block02);
container.store(block03);
container.store(block04);
container.store(block05);
container.store(block06);
}
finally
{
container.close();
}
}
private void exploreContent()
{
EmbeddedConfiguration configEmbedded = Db4oEmbedded.newConfiguration();
CommonConfiguration configCommon = configEmbedded.common();
configCommon.activationDepth(2); // Global activation depth.
ObjectContainer container = Db4oEmbedded.openFile(configEmbedded, DATABASE_NAME);
try
{
int targetNumber = 1;
ObjectSet blocks = getBlocksFromDatabase(container, targetNumber);
System.out.println(String.format("activationDepth : %s ", configEmbedded.common().activationDepth()));
System.out.println(String.format("Blocks found : %s ", blocks.size()));
Block block = blocks.get(0);
System.out.println(block); // Block 01
System.out.println(block.child); // Block 02
System.out.println(block.child.child); // Block 03 // Why are these
System.out.println(block.child.child.child); // Block 04 // blocks available
System.out.println(block.child.child.child.child); // Block 05 // as well ??
// System.out.println(block.child.child.child.child.child); // Block 06
}
finally
{
container.close();
}
}
private ObjectSet getBlocksFromDatabase(ObjectContainer db, final int number)
{
ObjectSet results = db.query
(
new Predicate()
{
@Override
public boolean match(Block block)
{
return block.number == number;
}
}
);
return results;
}
}
class Block
{
public Block child;
public int number;
public Block(int i)
{
number = i;
}
public void setChild(Block ch)
{
child = ch;
}
@Override
public String toString()
{
return String.format("Block number %s / child = %s ", number, child.number);
}
}
A: My best bet is that you are missing db4o-xxx-nqopt.jar which contains required classes for NQ optimization.
When a NQ query fails the criteria to run optimized db4o still runs your query, but this time as an evaluation whence it needs to activate all candidates.
Follows the output of DiagnoticToConsole() on such cases:
Test02$1@235dd910 :: Native Query Predicate could not be run optimized.
This Native Query was run by instantiating all objects of the candidate class.
Consider simplifying the expression in the Native Query method. If you feel that the Native Query processor should understand your code better, you are invited to post yout query code to db4o forums at http://developer.db4o.com/forums
To fix this, make sure that at least db4o-xxx-core-java5.jar, db4o-xxx-nqopt-java5.jar,
db4o-xxx-instrumentation-java5.jar and bloat-1.0.jar are in your classpath. Alternatively you can replace all these jars with db4o-xxx-all-java5.jar.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533350",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: why does ldap have all these funny two letter codes couldn't they make it simple, all you need is just uid and passwd, but they have all this stuff like cn and dn and base dn, it's too complicated
: dc=,dc=
objectclass: dcObject
objectclass: organization
o:
dc:
dn: cn=Manager,dc=,dc=
objectclass: organizationalRole
cn: Manager
A: As for the 2-letter-codes: To keep the format terse. There is "no reason" (except to not annoy the system admins more than necessary ;-) why full names couldn't have been forced.
Now as to the complexity (and it is complex!) and why all these different parts exist? Well, that's just LDAP:
The complexity and power of LDAP comes from the fact that there are bucket loads of attributes and bucket loads of objectclasses liberally scattered round in apparently randomly (and invariably unhelpfully) named schemas.
That is, LDAP is not just a user/password scheme.
Happy coding.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533360",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: using a javascript variable I'm having trouble with this script recognizing my variable as a variable. The important part of the script is as follows:
var content = 'imagereims';
var ms = content.substring(5);
$.get("../msimages/image.php", {ms: 'ms', pid: '<?php echo "$pid" ?>'}
);
I want the script to recognize the variable ms as reims, but when the page displays it doesn't recognize the content of the variable. It just repeats ms. I've tried writing the variable without single quotes and with double quotes. I get the same result.
Any suggestions. Thanks
A: You'll want to leave off the quotes on 'ms'. Try this:
var content = 'imagesreims'
var ms = content.substring(4);
$.get("../msimages/image.php", {ms: ms, pid: '<?php echo "$pid" ?>'});
'ms' is saying use this string literal as the value.
You'll also want a different substring. Try content.substring(6). content.substring(4) will yield 'esreims'.
As mentioned in another answer, you missed the ); at the end, which I've included in my answer.
A: Current your line:
var ms = content.substring(4);
is assigning ms the value esreims. See documentation here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/substring
All of these answers have pointed out errors in the code. You'll want to draw from them all.
A: Here's what you would do:
var content = 'imagesreims'
var ms = content.substring(6);
$.get("../msimages/image.php", {ms: ms, pid: '<?php echo "$pid" ?>'}
Note two things:
*
*use ms as the variable, rather than the literal 'ms'
*correct index 4 to 6, if you want reims
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533371",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Displaying realtime output from a text file on a webpage I have a program running on one of my servers and the output is being redirected to a text file. I want to be able to watch the text file like a linux "tail -f output.txt" would, but I want to watch it through a webpage.
Is this possible? How do it do it?
Thanks in advance!
A: From your linux reference I assume you use a linux/php stack?
Anyhow, you definitly need a server component (possibly a web service) that handles the file system watching and then expose the result through its web service interface. The webpage can poll that service periodically for updates on the content of that test file. Of course you have to use asynchronous calls (javascript ajax for example) from your web page to do the asynchronous polling.
There are many other elaborate solutions.. it would help if you specified you technology stack and parameters of what implementation you use.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533373",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Proper MVC way to show "no items" message in view My controllers return a list of items to my views. I need to handle the case when there are no items to show the message, "There are no items."
I can either:
*
*Check list.Count from my controller and return a view containing just that message, or
*Check list.Count from the view itself, and show the message or the items accordingly.
I read that views should not have any logic, so the pure MVC way would be #1 above. Am I wrong, or is that accepted in MVC? Many thanks.
A: Some may disagree, but i think it's unrealistic to remove all logic from the view. That is... provided we are talking about view logic.
If you set a message, you still have to perform some logic to display that message or not, especially if you want to forgo any headers for an empty output you would otherwise set.
I would suggest the biggest thing is to be consistent in how you do it... but do it however makes sense to you. Just do try to keep the logic restricted to that required to display your data.
A: That's a view's responsibility. Check the count on the model and act accordingly:
@model IEnumerable<MyViewModel>
@if (Model.Count() > 0)
{
...
}
else
{
<div>Nothing to display here</div>
}
And if you was using some Grid helper like for example MVCContrib Grid you don't even need an if in the view:
@model IEnumerable<MyViewModel>
@Html.Grid(Model)
.Empty("Nothing to display here")
.Columns(column =>
{
...
})
)
A: The view can contain view logic, but no business logic. So your option #2 should then be ok.
A: Well, you are right. your view shouldn't have any logic but your controller can.Howerver simple condition checking and looping is perfectly fine. Personally I would check the count at the controller level and then put the result in viewbag or something. Then i would check the view bag in the view.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533379",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Connecting Visual Studio 2010 to Oracle What is the easiest way to connect Visual Studio 2010 to an Oracle database not hosted on my local machine. Can anyone please link me to a tutorial that will help me do this as I have only ever connected using VB6 and ODBC. Or please provide me the steps involved in connecting Visual Studio 2010 to Oracle.
A: The easiest is probably to use ODP.net which is Oracle's official library to connect to Oracle databases (tutorials available on the linked web site)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533381",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PHP Multiple file upload to server This is my second question on the forum. I've exhausted all avenues of researching this on my own. I have an HTML form the will be processed with a script. In this form the user has the option to upload up to 10 images.... each image has its own entry field like this...
<form action="upload.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
The php is this...
$client = $_POST['company'];
$date = date("mdy");
$clientFolder = $client . $date;
mkdir('../../../uploads/' . $clientFolder . '/', 0700);
$folderPath = '../../../uploads/' . $clientFolder . '/';
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 100000))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
if (file_exists($folderPath . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
$folderPath . $_FILES["file"]["name"]);
echo "Stored in: " . $folderPath . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
I can get one file to upload correctly but not more than one. I used this tutorial. http://www.w3schools.com/php/php_file_upload.asp
Do I need to loop through these? Or do I need unique name's and id's? Any help will be appreciated! I'm new to php.... I have to say though.. I love it!!! so far...
A: I haven't browsed your full code but if you use the same name for different form elements you will lose all values except one.
There's a little exception that you'll probably want to use: adding square brackets will make PHP build an array:
<label for="file">Filename:</label>
<input type="file" name="file[]">
<label for="file">Filename:</label>
<input type="file" name="file[]">
You can use var_dump() to inspect the exact structure from $_FILES.
Secondly, the id HTML attribute is supposed to hold a unique identifier. Your client-side scripting is likely to behave wrong.
A: Maybe you want to name your inputs differently (say: file1, file2 etc) then in PHP you would do something like:
$i = 1;
while(isset($_POST['file'.$i])){
//do upload here
$i++;
}
The reason why you get only 1 file uploaded is because you named the inputs "file" (and because you don't loop through the inputs). Change that and it should be fine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533382",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Server Errors with .htaccess mod_rewrite On my localhost, there is no problem, but when I upload my .htaccess file to my 1and1 hosting account I hit a brick wall (an internal 500 server error)
Update: I found the offending code, just don't know why its broken or how to fix it (I commented out the broken line)
#RewriteRule ^([a-zA-Z_\-/]+)(\/?)$ index.php?p=$1 [R,NC,QSA,L]
RewriteRule ^([a-zA-Z_/]+)(\/?)$ index.php?p=$1 [R,NC,QSA,L]
.htaccess file contents:
AddType x-mapp-php5 .php
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !\.(jpg|jpeg|gif|png|css|js|pl|txt)$
RewriteRule ^([a-zA-Z_\-/]+)(\/?)$ /index.php?p=$1 [L]
Commenting out the final line (RewriteRule...) stops the error from happening but I obviously need this to function.
The file works fine for me on my local machine.
Well its a little different so I'll include that code too
(differences: flags, '/NEP', and the 1st line)
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !\.(jpg|jpeg|gif|png|css|js|pl|txt)$
RewriteRule ^([a-zA-Z_\-/]+)(\/?)$ /NEP2/index.php?p=$1 [NC,QSA,L]
An couple examples of the rewrites I am trying to perform:
*
*dev.mydomain.com/services/ => dev.mydomain.com/index.php?p=services
*dev.mydomain.com/quality/control => dev.mydomain.com/index.php?p=quality/control
Any help/advice you are able to give would be greatly appreciated. I really need to make this work by the end of the day.
A: The hyphen/dash in a character set functions as a range operator (think 0-9 or a-z). Having it in the middle or end of can be problematic.
Moving it to the beginning of the character set avoids this issue and means you won't have to escape it with a \:
[-a-zA-Z_/]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533385",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Socket.io handler using Gevent / Tornado & Flask can anyone show me and example of how to handle a generic socket.io connection (depends on the client browser, could be websockets, or xhr-longpolling, etc..) using gevent and flask, or maybe flask with tornado as an async server
thank you
A: TornadIO works well enough with stable version of socket.io (0.6), it integrates into any Tornado-powered application as a common request handler, wrapped around class with socket events callbacks. Works pretty stable.
But I'd recommend not to use the provided SocketServer class and just configure correctly the common HTTPServer of Tornado, just take a look at SocketServer implementation as a guideline.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533386",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How can I implement a Java interface with variadic methods in Scala? I am implementing a Java interface containing variadic methods like so:
interface Footastic {
void foo(Foo... args);
}
Is it possible to implement this interface in Scala? Variadic functions are handled differently in Scala, so the following won't work:
class Awesome extends Footastic {
def foo(args: Foo*): Unit = { println("WIN"); }
// also no good: def foo(args: Array[Foo]): Unit = ...
}
Is this even possible?
A: The code you've written works as-is.
The scala compiler will generate a bridge method which implements the signature as seen from Java and forwards to the Scala implementation.
Here's the result of running javap -c on your class Awesome exactly as you wrote it,
public class Awesome implements Footastic,scala.ScalaObject {
public void foo(scala.collection.Seq<Foo>);
Code:
0: getstatic #11 // Field scala/Predef$.MODULE$:Lscala/Predef$;
3: ldc #14 // String WIN
5: invokevirtual #18 // Method scala/Predef$.println:(Ljava/lang/Object;)V
8: return
public void foo(Foo[]);
Code:
0: aload_0
1: getstatic #11 // Field scala/Predef$.MODULE$:Lscala/Predef$;
4: aload_1
5: checkcast #28 // class "[Ljava/lang/Object;"
8: invokevirtual #32 // Method scala/Predef$.wrapRefArray:([Ljava/lang/Object;)Lscala/collection/mutable/WrappedArray;
11: invokevirtual #36 // Method foo:(Lscala/collection/Seq;)V
14: return
public Awesome();
Code:
0: aload_0
1: invokespecial #43 // Method java/lang/Object."<init>":()V
4: return
}
The first foo method with with Seq<Foo> argument corresponds to the Scala varargs method in Awesome. The second foo method with the Foo[] argument is the bridge method supplied by the Scala compiler.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533389",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Jasper Report shows message "The Report is empty"
Possible Duplicate:
“The Report is empty” - is bug?
I created iReport which execute stor proc in MS SQL server with 3 input parameters: startdate, enddate and dept_nm. In Jasper server repository I've created 3 controls with the same names. Using iReport the report i created works fine - no issues.
After I exported this report to Jasper Server and when prompt pop-ps asking to enter valid parameters - I entered valid dates and dept_nm but screen shows in the middle message "The report is empty". What is the possible problem?
Thank you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533391",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Objective-C Base class for view and text field So I'm developing a program where there are multiple little program inside. The main window show all the mini program, for the moment there is only one working but they will all be somewhat similar, so i click on the 'TimeEntry' button wich brings me to another view controller that way:
(IBAction)btnTe_clicked:(id)sender
{
TELogin *ViewTELogin = [[TELogin alloc] init];
ViewTELogin.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentModalViewController:ViewTELogin animated:YES];
[ViewTELogin release];
}
and then enter some data, validate and go to the next view controller, if i want to go back i use:
- (IBAction)btnMenu_clicked:(id)sender
{
[[self parentViewController] dismissModalViewControllerAnimated:YES];
}
so far so good, the mini app works, but the code is ugly, in each view controller I have to set a Scroll View, some constant and UITextField method like that to prevent a text field to be hidden by the keyboard:
-(void)textFieldDidEndEditing:(UITextField *)textField
{
CGRect viewFrame =self.view.frame;
viewFrame.origin.y += animatedDistance; //animated distance is a CGFloat
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
[self.view setFrame:viewFrame];
[UIView commitAnimations];
}
And I'm pretty sure it's possible to make one Base class which implements the scroll view and textfield delegate and then for each view controller i would just have to import the base class and design my interface. But everything i tried so far was just a waste of time that's why i'm calling for help.
A: Are you familiar with the MVC documentation?
If not, try making your own View class and Model class. The model class would hold your data and maybe other properties (depending on your design) and the View class would hold the UITextField and any other views already inside the ViewController.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533399",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to set SplashScreen in Eclipse? My App would load a splashScreen before launching the main window. How do you set the splashScreen running in Eclipse? There was a place to put the "splash:splashScreen.png" in NetBeans so that the App would start with the SplashScreen. Anything like that in Eclipse>
A: This link explains best how to add your splashscreen with netbeans -
http://wiki.netbeans.org/Splash_Screen_Beginner_Tutorial.
For Eclipse just add the -splash:path/to/image to VM arguments in the Debug/Run configurations panel.
A: Yes, the splash screen image has to be named splash.bmp as described here: http://www.eclipse.org/articles/Article-Branding/branding-your-application.html. The splash screen is expected to be in the same plug-in as the product. If this is not true for you, you might want to make an explicit choice in the configuration.
A: Add the
-splash:path/to/image
to VM arguments in the Debug/Run configurations under Arguments tab.
A: Credits: http://www.mkyong.com/java/how-to-change-eclipse-splash-welcome-screen-image
Short version: replace eclipse-jee-neon-R-win32\plugins\org.eclipse.platform_4.6.3.v20170301-0400\splash.bmp (your path will be very similar, navigate to it manually).
Long version:
1) Find “config.ini” file
Find the Eclipse configuration file “config.ini” in the following
location:
{eclipse.dir}\configuration\config.ini
2) Find “osgi.splashPath”
Open the “config.ini” file, find the “osgi.splashPath” to find out where
Eclipse IDE's splash image is stored, e.g.:
osgi.splashPath=platform\:/base/plugins/org.eclipse.platform
The default splash image is stored in:
{eclipse.dir}/plugins/org.eclipse.platform folder
3) Find the “splash.bmp” image
Find the “splash.bmp” image in the following location:
{eclipse.dir}/plugins/org.eclipse.platform_3.3.200.v200906111540/splash.bmp
(3.3.200.v200906111540 is the Eclipse version in this case, it may be different than yours)
4) Replace it
Replace the default “splash.bmp” image with yours (you may want to keep a backup copy of the original).
5) Done
Restart your Eclipse IDE to see the result!
And now, for the real reason I wanted to post this answer:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533403",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Can I use inline raw LaTeX in reStructuredText I am trying to embed a LaTeX variable into some reStructuredText. I know about the ".. raw::" directive, but I want this to be embedded in a paragraph of text. Specifically, I am looking to replicate the \numquestions\ and \numpoints\ variables from the template exam document. I have tried using :raw:\numquestions\, but this does not seem to be valid. Is there any way of doing this?
A: Use the raw role (the inline equivalent of the raw directive). See these references:
*
*http://docutils.sourceforge.net/FAQ.html#how-can-i-include-mathematical-equations-in-documents
*http://docutils.sourceforge.net/docs/ref/rst/roles.html#raw
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533406",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: mvc3 and entity deployment - Will Entity create tables? I'm super new to all this, so this may be a silly question.
I'm deploying a mvc3 app. Locally I have two databases, one came built in and contains the users/membership/roles, etc the other is for my dbcontext.
Local connection:
<connectionStrings>
<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
<add name="MembershipExtContext" connectionString="Data Source=|DataDirectory|invoice.sdf" providerName="System.Data.SqlServerCe.4.0"/>
</connectionStrings>
I need to deploy to (preferably) one database catalog. How do I do this? Do I need two catalogs? Will Entity still create the tables and such?
I was given a connection string for the new database.
I'm very confused. I hope someone can help.
The database on the server is sql2005. I am using entity code first.
A: You will need a connectionString for ASP.NET membership, and another for EF. It's fine if both point to the same DB.
Yes, you can use EF's DB initializer to create DB tables if you like, but it cannot create the membership tables. For that, you need to use aspnet_regsql.exe. The built in DB initialization strategies won't support evolving a schema in place, however. So you must either first create EF tables with your model and then run aspnet_regsql.exe before logging in or, perhaps preferably, use something like the forthcoming code-first migrations or the database generation power pack to evolve the DB schema in place.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533408",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Font or Images? I've been wondering about this for some time now. In the game Angry Birds whenever a pig dies, a number appears depicting the amount of points gained by killing the pig. Are those digits part of a TTF font that the developers created? Or, are they simply images imported into the program? A good indicator that they are images is if there are multiple colors used in each digit (such as a gradient), but it seems as if one constant color is used, green.
As far as my understanding goes, fonts are black and white, and one can only replace the black with one color.
So, are the numbers that appear when killing pigs in Angry birds part of a TTF font that the developers created, or just a series of images strung together?
Here is an example of what i'm talking about: Angry Birds
A: I don't know which one they're using here. I would suspect images just because Angry Birds is ported extensively, and using images means they don't have to worry about custom font support or text layout on each platform. But that's just a guess.
Just because something is a font doesn't mean it can't be drawn with a gradient. There are many ways to have gradients on fonts. A font can always be turned into a image by drawing it into a drawing context. You can then use that image as a mask on whatever gradient you like. Also, using Core Text you can convert glyphs into paths. So anything you can do with a path, you can do with a font.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533409",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Performance of running a multithreaded program on a single core by setting affinity? In short:
Under what scenarios can running a multithreaded app on a single core destroy performance?
What about setting the affinity of a multithreaded app to only use one core?
In long:
I'm trying to run the physics of a 2D engine on it's own thread. It works, and at first performance seemed normal, but I decided to tell the game to try and run at 10K FPS and the physics at 120FPS, went into Task Manager and set the affinity to where the program could only use one core.
The FPS was at ~1700 before setting the affinity to one core, afterwards it went to ~70FPS. I didn't expect that kind of decrease. I told the game to try and run at 300 FPS and physics at 60FPS.
Same thing happened.
I didn't give it much thought, so I just continued modifying the engine. I tested it again later after changing some of the drawing code, 300 FPS, 60FPS for physics. With all cores allowed it managed 300FPS just fine, with affinity to a single core FPS dropped down to 4. Now I know it can't possibly be that bad running a multithreaded app on a single core or am I ignorant of something that happens when you set the affinity to a single core.
This is about how the rendering/physics runs...
Loop starts
Gather input until (1.0 / FPS) has passed.
Call update.
Lock physics thread mutex because things in the game will be using the physics data and I don't want the engine updating anything until everything in this update call finishes.
Update everything in the game which may send a Draw function object(Holds what to draw, where to draw, how to draw) to the Render queue.
Unlock mutex.
Renderer calls operator() on each function object and removes them from queue.
update screen.
repeat loop.
Physics thread loop:
ALLEGRO_TIMER* timer(al_create_timer(1.0f / 60.0f));
double prevCount(0);
al_start_timer(timer);
while(true)
{
auto_mutex lock(m_mutex);
if(m_shutdown)
break;
if (!m_allowedToStep)
continue;
// Don't run too fast. This isn't final, just simple test code.
if (!(al_get_timer_count(timer) > prevCount))
continue;
prevCount = al_get_timer_count(timer);
m_world->Step(1.0f / 60.0f, 10, 10);
m_world->ClearForces();
}
// Note: Auto mutex is just a really simple object I created to lock a mutex in constructor and unlock it in destructor. I'm using Allegro 5's threading functions.
A:
Under what scenarios can running a multithreaded app on a single core destroy performance?
What about setting the affinity of a multithreaded app to only use one core?
In both cases, the answer is much the same. If your program is running on a single core, then only one thread runs at a time. And that means that any time one thread has to wait for another, you need the OS to perform a context switch, which is a fairly expensive operation.
When run on multiple cores, there's a decent chance that the two threads that need to interact will both be running simultaneously, and so the OS won't need to perform a context switch for your code to proceed.
So really, code which requires a lot of inter-thread synchronization is going to run slower on a single core.
But you can make it worse.
A spinlock, or any kind of busy-waiting loop will absolutely destroy performance. And it should be obvious why. You can only run one thread at a time, so if you need a thread to wait for some event, you should tell the OS to put it to sleep immediately, so that another thread can run.
If instead you just do some "while condition is not met, keep looping" busy loop, you're keeping the thread running, even though it has nothing to do. It'll continue looping *until the OS decides that its time is up, and it schedules another thread. (And if the thread doesn't get blocked by something, it'll typically be allowed to run for upwards of 10 milliseconds at a time.)
In multithreaded programming in general, and *especially multithreaded code running on a single core, you need to play nice, and not hog the CPU core more than necessary. If you have nothing sensible to do, allow another thread to run.
And guess what your code is doing.
What do you think the effect of these lines is?
if (!(al_get_timer_count(timer) > prevCount))
continue;
RUN THE LOOP!
AM I READY TO RUN YET? NO? THEN RUN THE LOOP AGAIN. AM I READY TO RUN NOW? STILL NO? RUN THE LOOP AGAIN.....
In other words, "I have the CPU now, AND I WILL NEVER SURRENDER! IF SOMEONE ELSE WANTS THE CPU THEY'LL HAVE TO TAKE IT FROM MY COLD DEAD BODY!"
If you have nothing to use the CPU for, then give it up, especially if you have another thread that is ready to run.
Use a mutex or some other synchronization primitive, or if you're ok with a more approximate time-based sleep period, call Sleep().
But don't, if you want any kind of decent performance, hog the CPU indefinitely, if you're waiting for another thread to do some processing.
A: When you look at a processor, don't look at it like a block that just calculates one thing after another. look at it as a calculator you have to reserve a time for
Windows (and all operating systems) makes sure this time is reserved for all running apps. When you run a program, the computer doesn't just do all the calculations the new program wants to, windows allocates the program a specific amount of time. When that time is over, the next program gets some time. windows does all this for you, so it's only relevant if you want to understand it.
This does effect how you look at multi-threading though, because when windows looks around and sees a multi-threaded application, it will say "i will handle this as 2 separate programs" so it allocates time for both. therefore one wont completely stop the other from doing calculations.
So no, it will not TANK performance of your program to run it multi-threaded, but it will makes other programs around it a little slower. and create a small amount of overhead. but if you are doing large calculations and it is causing your program to hang, feel free to multi-thread.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533415",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Dev Express Aspx Gridview Multi-row filter control I am utilizing the Devexpress aspxGridview control throughout my asp.net web forms application. Many of the databases that I would like to be able to visual and filter using these controls have a large number of fields in them. Here is an example below (although this is not the largest field set)
Does the control provide a way to separate these fields into multiple rows and use a preview field instead of individual columns. For example something that might look like this.
Or Even completely horizontal like this.
I realize this can probably be accomplished fairly successfully using css but based on the markup created by the control it looks like it might be a fairly time consuming task.
A: There is no proper way to force breaking the ASPxGridView's Header between multiple lines. It is possible to specify the required layout using the use grid's templates (the http://documentation.devexpress.com/#AspNet/CustomDocument3678, for instance, for keeping header functionality).
However, in this case, it is necessary to implement custom filter editors and force grid filtering programmatically. The built-in columns' headers functionality will be lost.
Probably it would be better to use the external filter for the ASPxGridView:
Filter Control - External Filter for GridView
http://demos.devexpress.com/ASPxEditorsDemos/ASPxFilterControl/FilterBuilder.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533417",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Visual Studio 2010 runtime check failure # 3 It looks like that Microsoft is backfiring again in VS2010. Here's my code
#include "string.h"
typedef struct s_test
{
unsigned char a[20];
} t_test, *p_test;
void initialize(t_test t)
{
memset(t.a, 0, 20);
}
void main()
{
t_test t;
initialize(t);
}
and it throws
Run-Time Check Failure #3 - The variable 't' is being used without being initialized.
Well...since in other cases the runtime checker does help so I'm less likely to turn it off in the solution. But how the hell should I do with this? You might suggest to change the way the argument is passed to pointers. However it would be an unpleasant experience regarding a consistent coding style. Now I feel like rawring to MS for this BRILLIANT stuff ;p
A: That's because you're passing t by value - an unitialized value. Define your initialize function as follows, so that it can actually modify the passed in object and all is well:
void initialize(t_test *pt)
{
memset(pt->x, 0, 20); // x not a
}
Also, for the sake of all that's holy, change:
void main()
to
int main()
A: Well, the error report you are getting is a perfectly valid and appropriate error report. This is exactly what you are doing: you are using an uninitialized value. You are attempting to copy an uninitialized object - in which case the report from tun-time checker is, of course, expected.
Basically, what you are doing in your code is equivalent to this
int a, b = a;
This code will trigger the same error for the very same reason. So, why are you complaining about it?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533423",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Unable to run any Android project - could not find apk error message I've recently installed the Android SDK on Windows 7. I'm editing using Eclipse. I have had no problems whatsoever on Windows XP previously, but for some reason nothing happens on Windows 7. I've given as much detail as I can below:
So, when I try to 'run' my Android project I get this...
[2011-09-23 19:32:42 - hug] ------------------------------ [2011-09-23
19:32:42 - hug] Android Launch! [2011-09-23 19:32:42 - hug] adb is
running normally. [2011-09-23 19:32:42 - hug] Could not find hug.apk!
And this is what my eclipse.ini looks like:
-vm C:\Java\jdk1.6.0_27\bin
-startup
plugins/org.eclipse.equinox.launcher_1.0.201.R35x_v20090715.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.0.200.v20090519
--launcher.XXMaxPermSize 256m
-vmargs
-Xms100m
-Xmx512m
-Dosgi.requiredJavaVersion=1.5
-Dosgi.bundlefile.limit=100
I've tried loads of different variations on the -vm variable for this file (i.e. adding javaw.exe to the end of it, just rooting it to the jdk etc.) Sometimes it won't open Eclipse at all, at other times it will open but I still can't launch a project.
When I right click on the project and try to Export Unsigned Application Package I get:
Conversion to Dalvik format failed with error 1
Conversion to Dalvik format failed with error 1
So, I'm pretty stumped. I can boot an emulator but I of course can't get a project onto that to play with it. Please help!
Thanks in advance!
A: Check your Android SDK location in Window-->Preferences, Android tab
It must help you.
A: I just answered a similar question here: could-not-find-the-apk-error
It may be due to the Android SDK Build-tools not being installed on your Windows 7 machine. If you open Eclipse and go to "Window->Android SDK Manager" then it will open the manager and you may see that the Android SDK Build-tools are not installed.
Installing the build tools and cleaning/rebuilding all of your projects may work.
Interestingly, I also get the same "Conversion to Dalvik format failed with error 1" error, but I think that's a separate issue to the "Could not find *.apk" one.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533425",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to create a accurate chronometer, matching real time? I'm working in an educational software, mostly developed using Flash AS3, and we have a chronometer which shows different values through different users.
Example: Two users starting the chronometer at same time, but along some minutes of usage, they have different values.
The current implementation uses Timer class, causing this to happen, obviously due the different average speed of each computer.
I already have an idea in mind, but I would like to have some theoretical suggestions.
Thanks in advance.
A: The Timer class is not very accurate. From the docs: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/utils/Timer.html
Depending on the SWF file's framerate or the runtime environment (available memory and other factors), the runtime may dispatch events at slightly offset intervals. For example, if a SWF file is set to play at 10 frames per second (fps), which is 100 millisecond intervals, but your timer is set to fire an event at 80 milliseconds, the event will be dispatched close to the 100 millisecond interval. Memory-intensive scripts may also offset the events.
If you're looking for a relative time since the start of your application, use flash.utils.getTimer(). http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/utils/package.html#getTimer%28%29
If you want to do more sophisticated timing, you can use the Date class. http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Date.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533427",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Compiling PJSIP for use in iOS 5 I know iOS 5 is still under NDA, but I don't think this will violate their terms.
When I try to compile PJSIP for xcode for use within iOS 5, it dosen't find gcc. "Cannot find gcc for iOS 5 SDK" is the error I get. Is there any way to remedy this? Thanks!
A: Changeset 3818 in the PJSIP codebase fixes this issue by allowing configure-iphone to find LLVM
A: Maybe your project isn't configured to use GCC!
XCode 4.2 will default to LLVM 3.0 with clang frontend (gcc command replacement)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533429",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I make my program, written in Java, usable to other people? So I've written a funny little program and I want to show it to some of my friends. My friends, not being programmers, have no idea what to do if I send them the folder containing the necessary classes and files. I want to be able to email them something (or put it on a cd/thumbdrive) that they can then double click and have it run the program. I have absolutely no clue how to make this happen. I'm taking a class and we use linux computers (I use a mac when I'm not in class) and we have to javac the .java files and then java "File name" to make it run. I have friends on Mac's and PC's and I want them to be able to just click the program and have it go....
If it makes a difference the program is written using the object draw library.
A: Use the jar command to build an executable jar file. It's basically a ZIP file with certain guarantees.
Within the jar file you will need (it's a reqirement) a /META-INF directory with a file in it called the manifest (/META-INF/MANIFEST.MF). It describes the "manifest" of the jar file, which is in some ways modeled off a shipping manifest.
Inside the MANIFEST.MF file, you need the directive
Main-Class: org.mystuff.path.Main
Which should direct the JVM to run the org.mystuff.path.Main class when the jar file is "exectued" via the command
java -jar myproject.jar
Note that JAR files tend to handle classpaths differently, in the sense that they ignore the CLASSPATH environmental variable, and the -classpath command line options. You need to add a classpath directive within the MANIFEST.MF file if you need to reference other JAR files. Use the manifest link above to see the details concerning embedding a classpath.
Depending on the simplicity of the "project", a single JAR file might be enough to ship to them; however, if you need more than that, you might find yourself having to ship a few files in a few directories. In that case, put the files (including the JAR file) and directories in a second zip file. While you could select from a number of different ways to "package" the items, I recommend
(layout inside the zip file)
/Readme.txt (a text file describing what to do for new comers)
/License.txt (a text file describing how liberal / restrictive you wish to be concerning your authorship rights.
(the license sounds like overkill, but without it nobody can prove they're not breaking the law)
/bin/myprogram.sh (shell script containing "java -jar ../lib/myprogram.jar")
/bin/myprogram.cmd (Windows batch file containing "java -jar ..\lib\myprogram.jar")
/lib/myprogram.jar (the executable jar file containing your compiled code)
/lib/otherjar.jar (other jar files, as necessary)
With such a zip-file structure, the installation instructions then become "unzip the zip file; change directory to "bin" and run "myprogram.whatever".
A: I would say use an applet then there is no need for any commands to run. Here is what you can do
*
*If you have multiple classes then create a executable jar, If don't want to create jar move all your code into one class
*Then create a class that extends Applet, You can load your program from this applet class or even better move every thing to the applet class (not the best design, but makes your life easier in this case)
*Then create a html file some thing like this, This html has script that will direct what to do to view the program
<script>
var jEnabled = navigator.javaEnabled();
if (!jEnabled){
document.write("<a href=\"http://www.java.com/en/download/help/enable_browser.xml\">Enable Java</a> on your browser to view me ");
}
</script>
<br><br>
<applet code="AppletLauncher.class" width=100 height=140/>
A: Using objectdraw to create an executable jar file:
Typically, objectdraw is used with the BlueJ IDE so these instructions are for using BlueJ and the objectdraw library.
*
*Make sure you have a Class that has the begin() method. This is the class that you run inside BlueJ and now you want to turn it into an executable jar file.
*You need to make a new Class, let's call it Main. It should look like this:
public class Main{
public static void main(String[] args){
ClassWithABeginMethod game = new ClassWithABeingMethod();
game.begin();
}
}
*Now, in BlueJ, open the Project dropdown menu. Select "Create Jar File...".
*In the dialogue box that opens:
Make sure that the Class "Main" is the one selected for the Main class option.
Under "Include user libraries", select the "objectdraw.jar" option.
Press continue.
*The new dialogue box that opens is asking where you want to save a new folder that will contain your new jar file. Name it what you would like. The result will be a new folder with the name you selected that contains a jar file of the same name.
*You're done. Use the command line prompt: "java -jar jarFileName.jar" to run your new jar file.
A: You need to tell us which IDE you are using, but just compile it into an executable jar, they work on all systems that have the java version you compile them again (so multiplatform)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533433",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Unit Testing RavenDB In my unit tests I am setting up each test to have a totally empty IDocumentSession. I do it like this:
[SetUp]
public void SetUp()
{
_store = new EmbeddableDocumentStore
{
RunInMemory = true
};
_store.Initialize();
Session = _store.OpenSession();
}
But I think this might be the reason my tests are a little slow. I was wondering if there is a simple command to delete all documents from the database.
What I want is to know is: if I can do this, and if it would improve performance.
A: The expensive call there is the _store.Initialize() -- you are forcing RavenDb to stand up a new database every test. In most cases a single database per test suite run will work.
Another option would be to use the nature or RavenDb's IDs to namespace your tests. This is pretty handy if the real issue is duplicate key errors and otherwise engineering things so you don't have a nasty cleanup.
A: I know this is an old question but as of RavenDB 2.0 (not yet stable) there is a Raven Test Helper available as a Nuget package which is really useful when it comes to unit test RavenDB.
http://ravendb.net/docs/samples/raven-tests/createraventests?version=2.0
http://nuget.org/packages/RavenDB.Tests.Helpers/2.0.2198-Unstable
A: This is the recommended approach for unit testing with ravendb
The not recommended for production basically runs in the in memory mode
If you find this to be slow, try profiling and figuring out what exactly is slowing things down
A: Try to use RunInUnreliableYetFastModeThatIsNotSuitableForProduction = true.
var _store = new EmbeddableDocumentStore()
{
Configuration =
{
RunInUnreliableYetFastModeThatIsNotSuitableForProduction = true,
RunInMemory = true,
}
};
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533435",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "30"
} |
Q: How to close split window / adjacent editor - Xcode 4 I've managed, by playing around with the menus in Xcode 4, to open a window in an adjacent editor (Navigate, open in adjacent editor). Unfortunately, I'm having trouble figuring out how to close that window. How do you do that?
A: There's a close button in the upper right corner of an assistant editor to close the editor.
The first assistant editor doesn't have buttons to add and close editors, which can be confusing.
A: Cmd+Enter
or View -> Standard Editor -> Show Standard Editor
A: I fixed this by going to 'view > editor > standard' and this reset the view to the standard one window view. I have yet to figure out why the x in the upper right corner of the new window is grayed out. Not a perfect solution, but a solution.
A: I am using XCode 13.41. There is an "X" icon at the top left corner of the editor view. (You can hover on it to reveal what it does). Click on the X to close the editor.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533440",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: How can I use Razor expressions within a Coffeescript file? I would like to do something like this in CoffeeScript so that I can move all my script off into coffe files:
$("#btnFinish").click ->
$.post "@Url.Action("Submit", "Process")", (response) ->
$("#PlaceHolderButton")
.button()
.text response
$("#btnHome").click ->
window.location.href='@Url.Action("Index","Home")'
Should I just push the url and other items I need into hidden values and query them for the later when the script runs?
I feel like I am missing a key concept or something here.
A: Try to avoid the need of mixing javascript with server side. There are always better workarounds. For example:
@Html.ActionLink("Some button", "Submit", "Process", null, new { id = "btnFinish" })
and then in your js:
$('#btnFinish').click(function() {
$.post(this.href, function(response) {
...
});
return false;
});
or if btnFinish is some div for which you cannot use a helper to generate an url, you could use HTML5 data-* attributes, like so:
<div id="btnFinish" data-url="@Url.Action("Submit", "Process")">Some button</div>
and then:
$('#btnFinish').click(function() {
var url = $(this).data(url);
$.post(url, function(response) {
...
});
return false;
});
but if you have some clickable button which you AJAXify the first approach would be semantically better because you are directly having the url as part of the href.
The same thing applies for your second example:
$('#btnHome').click(function() {
window.location.href = $(this).data('url');
});
So you no longer need any server side tags in your javascript files. Your js are completely static, combined, minified, gzipped, cached, served from a content delivery network and all the benefits related to this.
A: Well to embed Razor directly into JavaScript you would need the JavaScript to go through the Razor view engine to be evaluated before it is handed off to the browser. That doesn't happen currently but it could be done.
I've worked around this with these methods:
- hidden field approach
- <script type="text/javascript>...</script> in the view
You could use that last method and make a configuration management plug-in that would take in key-values in the view and provide a method to query for them from the JavaScript outside of the view.
There is also RazorJS which is available on Nuget:
http://nuget.org/List/Packages/RazorJS
Write Razor-Style C# or VB.NET insde your Javascript Files. Also contains an http handler for serving, when needed, those files.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533443",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Rails controller design pattern for dashboard I would like to have a Dashboard page that gather information from multiple models to a summary view (without its own model). How should I go about it the Rails way? Should I create a dashboard_controller with just index action?
Thank you.
A: just think a little less Rails. i'm assuming your dashboard contains mainly widgets? i.e. some self contained elements, whatever? why not make those widgets your model (not AR-based). encapsulate all your logic and data retrieval in your widget model(s). so now if you want to go RESTful, you could for example make a WidgetsController with an index action as dashboard. in a second step you could use your show action to provide JSON data for each widget for AJAX parts of your dashboard. etc.
just remember REST is not necessarily == CRUD, and a Model doesn't need to be a ActiveRecord model. Rails forces you into the MVC pattern, which is a great thing, and makes even poorly written Rails apps better than a lot of PHP mayhem out there, but sometimes we tend to forget that there are a lot of possibilities outside of ActionController + ActiveRecord etc.
A: What you would want is to take a look at the administration frameworks and see if that solves your needs, I like Typus and RailsAdmin Otherwise you would want to take a look at the presenter pattern and how it applies to Rails and your application. A dashboard basically would only interface with your existing models and controller logic since you dont want to end up with a situation where you have two sets of logic for each model. While the blog I linked to is from 2007 you should be able to pull some useful information off of it and get the idea of what you need to do.
If you have any questions feel free to ask.
A:
Should I create a dashboard_controller with just index action?
I prefer to put pages that do not perform CRUD upon a model (such as dashboards) in the application_controller. No need to create a dashboard_controller.
A: Would that be a use case for the Presenter pattern?
I am about to implement a ddashboard and that's the best design I think that will lead to a maintainable code base.
A: My solution is to run
rails g controller Dashboards
then manually create a app/models/dashboard.rb model which contents can be as little as
class Dashboard end
Of course the model you can put all the logic you need fishing data from other models.
Back to the controller, you create just the index action. Lastly, you manually create the app/views/dashboards/index.html.erb file with whatever content you need. Add the route and you're good to go. If you pay attention to details you can change the url from /dashboards to /dashboard. That's it, i think it's very Rails-y.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533449",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: How to defeat C# GetCallingAssembly().Location security I'm trying to load and execute an dynamically external assembly against its developer's wishes. It does a hash check on GetCallingAssembly().Location and closes.
The assembly is frequently updated so editing of the IL code to bypass this check would be possible, but would need to be done programmatically before it is loaded. This would be unreliable, and I couldn't find adequate documentation on any tools that could be used to easily patch it. I could also bypass the check altogether by just calling the later function directly if I could parse a few strings out of the assembly. This would be easier, but is the least unreliable, if anything significant was changed my code would break.
AFAIK there's no easy way I can control what is returned by GetCallingAssembly().Location of a child process. I have full privileges over the executing computer if that helps.
Otherwise I hoped I could use some sort of hook or Windows 7 feature to such to redirect a C# FileStream read from one file to another, but I don't know how I'd go about this.
Please point me towards some ideas. I know this kind of check is stupid and should be easy to bypass with the right knowledge.
Thanks
A: This site probably isn't the best place to note this is done against the writers wishes as we are all devs here.
However if I was to have to bypass something for a legal reason (research, old software, etc) I would need to patch it in a case like this. Since the call is in to a system .net library you cannot control the return without using a runtime loader to patch that function in the system lib, or patch the function in the resulting assembly. There are ways to hook the system libraries, but I'm not sure if what's intended here is legal, so I won't comment.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533456",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-6"
} |
Q: How to create a special binary tree I wish to index some data where the key is a ulong.
This ulong (64 bits) represents a combo of products,
where each bit of the ulong is a Product in the combo.
So if we get a ulong Key of value 3. That's really 1 + 2.
That means that products 1 and 2 are present in the combo.
ulong Combo1 = 1 | 2;
ulong Combo2 = 1 | 4 | 8;
If I wish to know if Combo1 shares any product with Combo2 I could simply do this:
if((Combo1 & Combo2) != 0)
{
//They share at least 1 product
}
This is very nice and fast, but it gets difficult if I have:
List<ulong> Combos = new List<ulong>();
And in it over 1 million Combo Keys (the key represents the products used).
How can I index this list of ulongs so that I can loop it and do the following:
foreach(ulong combo in Combos)
{
//Find all the combos in Combos where no product is shaded
List<ulong> WorksWith = GetFromIndexOrTree(combo);
foreach(ulong combo2 in WorksWith)
{
//Use
}
}
private List<ulong> GetFromIndexOrTree(ulong combo)
{
//magic index or tree
}
Thanks a lot for your help and for the comments.
Say I am a combo with products (red, blue, and white). I wish to find all combos that don't have any or all of my products (red, blue and white). So I shall find a combo with (yellow), (green, yellow), (green, black)...
A: Let
S be the set of products.
C ⊂ P(S) the set of combos.
F(p) = { c ∈ C | p ∉ c } the set of all combos c ∈ C that do not contain the product p ∈ S.
Then
G(X) = ∩p∈X F(p)
gives the set of combos where no combo contains any product p in the set of products X ⊂ S.
C#
List<ulong> combos = new List<ulong> { 1 | 2, 1 | 4 | 8 };
Dictionary<int, List<ulong>> dict = Enumerable
.Range(0, 64)
.ToDictionary(i => i, i => combos
.Where(combo => ((1UL << i) & combo) == 0)
.ToList());
ulong input = 1 | 2; // find all combos that don't have product 1 or 2
List<ulong> result = Enumerable
.Range(0, 64)
.Where(i => ((1UL << i) & input) != 0)
.Select(i => dict[i])
.Aggregate((a, b) => Enumerable
.Intersect(a, b)
.ToList());
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533457",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can you use the tac command in Terminal? I'm trying to search a large file in reverse order from the command line (using terminal). I found the tac command: http://clifgriffin.com/2008/11/25/tac-and-reverse-grep/
tac is the inverse of cat. However, when I try to use the tac command in terminal, it says that command doesn't exist. Is there a way I'd be able to use tac in terminal? What are some other fast ways to search a file from the end via the command line?
A: It's easy using OSX Homebrew:
brew install coreutils
Then it's available as gtac (as in GNU tac), for example:
# Find and parallel copy all files in reverse order
find . -print | gtac | parallel copy "{}" destination/
A: The MacOs version of tail support the -r ("reverse") option, and defaults
to displaying the entire file from the end. So tail -r filename should be
exactly equivalent to tac filename.
Or, you could try building tac yourself from the source code. It's part of the GNU coreutils package.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533462",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: When does Android check Min-sdk? My application is targeted for API 8 (Froyo) minimum, however I'm getting a message in the Android Market that says "This report was sent in by a pre-Froyo client, which did not include a stack trace."
When does Android check that the Min-sdk is greater than or equal to the API version on the phone. Is it at runtime or market download time?
A: Your app's minSdkVersion is filtered by the Market and the phone, however there are a few ROMs out there that disable this filtering at the phone-level. If you're seeing a report from a phone that is below your minSdkVersion it usually means the user installed the app directly, not from the market, and their phone tried to run it even though the SDK version wasn't usable by the device. This would result in a bug report being posted to the Market, but the Market app doesn't ask the device how it got the app in the first place.
You'll see this once in a really long while--it's nothing to be alarmed about.
A: I believe it filters in the market. Perhaps somebody got ahold of your APK and distributed it to a pre-Froyo phone? Just a guess.
edit - taken from the ref http://developer.android.com/guide/topics/manifest/uses-sdk-element.html: An integer designating the minimum API Level required for the application to run. The Android system will prevent the user from installing the application if the system's API Level is lower than the value specified in this attribute. You should always declare this attribute.
Perhaps you have confused minSdkVersion and targetSdkVersion?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533463",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I tell what class in the polymorphic hierarchy contains the method I'm about to call? If I have:
class A():
def f(self):
print("running function, f from class A")
class B(A):
def __init__(self):
A.__init__(self)
def f(self):
print("running function, f from class B")
and I make an instance of class B and call f on it, we all know we'll see the message about "from class B." But is there a way for me to inspect my object and make sure my sub-class has overridden my method? Something like:
obj = B()
assert(not obj.f.livesIn(A))
A: class A():
def f(self):
print("running function, f from class A")
class B(A):
def f(self):
print("running function, f from class B")
class C(A):
pass
This shows that B.f does not equal A.f. So B must override f:
obj = B()
print(obj.__class__.f == A.f)
# False
This shows that C.f equals A.f. So C must not have overridden f:
obj = C()
print(obj.__class__.f == A.f)
# True
A: If you want to force the child class to override, you can raise NotImplementedError().
Doing the inspection is possible too... And I see unutbu just posted an example, so I won't repeat it. :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533464",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: NullPointerException with JFrame At the moment all I want this program to do is run without any compile errors. Basically, what I need it to do is open the frame and then when the frame is selected, if I press the up arrow key it will set arrows[0] to true and when I release it it will set it to false (same with right, down, and left as well)...
My code will compile. However, I keep getting this error when I try to run it.
java.lang.NullPointerException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:271)
I've done a program somewhat similar to this before and I never had this problem. I originally thought it was because of the "frame.addKeyListener;" or the "frame.setFocasable(true);" but I tried taking those lines out and it still came up with the error...
Here's the code that I am running, any help to fix this problem would be helpful.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.lang.*;
public class arrowTest extends JApplet implements KeyListener {
private boolean[] arrows = new boolean[4];
private int x = 0;
private int y = 0;
public arrowTest() {
}
// Handle the key typed event from the text field.
public void keyTyped(KeyEvent e) {
System.out.println("KEY TYPED: ");
}
// Handle the key-pressed event from the text field.
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_UP) {
arrows[0] = true;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
arrows[1] = true;
}
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
arrows[2] = true;
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
arrows[3] = true;
}
}
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_UP) {
arrows[0] = false;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
arrows[1] = false;
}
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
arrows[2] = false;
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
arrows[3] = false;
}
}
public void run() {
JFrame frame = new JFrame();
JApplet applet = new arrowTest();
frame.add(applet);
frame.setTitle("arrowTest");
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 200);
frame.setVisible(true);
frame.addKeyListener(this);
frame.setFocusable(true);
}
public void main(String[] args) {
run();
}
}
A:
At the moment all I want this program to do is run without any compile errors.
For the record, your program does run without "compile errors". What's happening is you're getting an null pointer exception (NPE) thrown during the running of the program, not a compile error. You need to find out what line is causing your NPE and then fix it by making sure all reference variable have been initialized before using them.
But also, you should not be using KeyListeners for this but instead use Key Bindings -- there's a big difference. The Key Binding tutorial will explain all. It may appear a bit daunting at first, but don't give up, follow the examples, and you'll be using it in no time.
And why are you using JApplet anything when you're trying to create a JFrame? That's just a bit funky.
Edit 2
And your code won't even run since your main method is non-static. If you're running your program as an actual JFrame, then you'll need to show us the actual code that you've used. This code has no viable main method and thus isn't it.
Edit 3
No, static isn't your problem, still you need to learn to use key binding and to not mix JApplet and JFrame code in this strange chimera you've got.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533469",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Trouble displaying variable in foreach loop using multidimentional array I'm able to display id and tags in the foreach loop no problem. But I'm having trouble showing title and height. I'm not sure how to call them into the foreach loop.
I can call them in the while loop so I know that they are working.
$persons = array();
$tags = array();
while( ($row = mysqli_fetch_array( $rs, MYSQLI_ASSOC)))
{
if(!isset( $persons[$row['id']]))
{
$persons[$row['id']]['title'] = $row['title'];
$persons[$row['id']]['height'] = $row['height'];
$persons[ $row['id'] ] = array( 'id' => $row['id'], 'tag' => $row['tag']);
$tags[ $row['id'] ] = array();
}
$tags[ $row['id'] ][] = $row['tag'];
}
foreach( $persons as $pid => $p)
{
echo 'id: # ' . $p['id'] ;
echo 'title: ' . $p['title'];
echo 'height: ' . $p['height'];
echo '<a href="#">' . implode( '</a>, <a href="#">', $tags[ $p['id'] ]) . '</a>';
echo '<br /><br />';
}
A: You're overwriting $persons[ $row['id'] ] when you set the tags, so you lost the other data.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533471",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can't get this content spinning API to work with PHP Can you help me get this content spinning API working? It was wrote to work with C# but is there a way I can get it to work using PHP? I've been trying to post to the URL stated on that page using cURL, but all I'm getting back is a blank page. Here's the code I'm using:
$url = "http://api.spinnerchief.com/apikey=YourAPIKey&username=YourUsername&password=YourPassword";
// Some content to POST
$post_fields = "SpinnerChief is totally free. Not a 'lite' or 'trial' version, but a 100% full version and totally free. SpinnerChief may be free, but it is also one of the most powerful content creation software tools available. It's huge user-defined thesaurus means that its sysnonyms are words that YOU would normally use in real life, not some stuffy dictionary definition. And there's more...SpinnerChief can only get better, because we listen to our users, We take onboard your ideas and suggestions, and we update SpinnerChief so that it becomes the software YOU want!";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_PORT, 9001);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
Can anyone see something wrong I'm doing? Thanks a lot for the help.
A: The value for CURLOPT_POST should be 1, and the posted data should be set with CURLOPT_POSTFIELDS.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533472",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JavaScript inheritance: when constructor has arguments Using pure JavaScript to do inheritance, this is what I usually do:
function A() {}
A.prototype.run = function () {};
function B() {}
B.prototype = new A;
B.prototype.constructor = B;
Since there is no arguments to pass into the constructor, new A has nothing to complain about. Now, I haven't figured out a good way to do inheritance if the constructor has arguments to pass. For example,
function A(x, y) {}
A.prototype.run = function () {};
function B(x, y) {}
B.prototype = new A;
B.prototype.constructor = B;
I could pass some arbitrary values like:
B.prototype = new A(null, null);
In some cases, I may need to validate x and y in the constructor of A. In some extreme cases, I need throw errors when checking x or y. Then, there is no way for B to inherit from A using new A.
Any suggestions?
Thanks!
A: Although this is an old topic, I thought I'd respond anyway.
Two ways to do it:
Although the Pseudo Classical way is the most popular, it has its down sides since it needs to call the parent constructor once in the child constructor and once while inheriting the prototype. Besides, the child's prototype will contain all the properties of the parent constructor which will anyway get overwritten when the child constructor is called. My personal choice is Prototypal Inheritance.
1. Pseudo Classical Inheritance:
function A(x, y) {}
A.prototype.run = function () {};
function B(x, y) {
A.call(this,x,y);
}
B.prototype = new A();
B.prototype.constructor = B;
2. Prototypal Inheritance:
function A(x, y) {}
A.prototype.run = function () {};
function B(x, y) {
A.call(this,x,y);
}
B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;
A: The problem is that you can't easily create a prototype object for B since invoking the constructor of A can't be done. This is due to the parameters for the constructor being unknown before new B is executed. You need a dummy constructor function to construct a prototype for B that links to A's prototype.
B.prototype = (function(parent){
function protoCreator(){};
protoCreator.prototype = parent.prototype;
// Construct an object linking to A.prototype without calling constructor of A
return new protoCreator();
})(A);
Once you've got the prototype object for B set up, you need to ensure to call the constructor of A in the constructor of B.
function B(x, y) {
// Replace arguments by an array with A's arguments in case A and B differ in parameters
A.apply(this, arguments);
}
You should now be able to instantiate B by calling new B(x, y).
For a complete same including parameter validation in A see a jsFiddle.
In your original code you are setting B.prototype.constructor = B. I'm not getting why you are doing this. The constructor property does not influence the inheritance hierarchy for which the prototype property is responsible. If you want to have the named constructor contained in the constructor property you'd need to extend the code from above a little:
// Create child's prototype – Without calling A
B.prototype = (function(parent, child){
function protoCreator(){
this.constructor = child.prototype.constructor
};
protoCreator.prototype = parent.prototype;
return new protoCreator();
})(A, B);
Using the first definition of B.prototype you'd get the following results:
var b = new B(4, 6);
b.constructor // A
console.info(b instanceof A); // true
console.info(b instanceof B); // true
With the extended version, you'll get:
var b = new B(4, 6);
b.constructor // B
console.info(b instanceof A); // true
console.info(b instanceof B); // true
The cause for the different output is that instanceof follows up the whole prototype chain of b and tries to find a matching prototype object for A.prototype or B.prototype (in the other call). The b.constructor prototype does refers to the function that was used to define the instances prototype. In case you wonder why it does not point to protoCreator this is because its prototype was overwritten with A.prototype during the creation of B.prototype. The extended definition as show in the updated example fixes this constructor property to point to a more appropriate (because probably more expected) function.
For daily use, I'd recommend to discard the idea of using the constructor property of instances entirely. Instead do use instanceof since its results are more predictable/expected.
A: Consider this:
function B( x, y ) {
var b = Object.create( new A( x, y ) );
// augment b with properties or methods if you want to
return b;
}
And then
var b = new B( 12, 13 );
Now b inherits from an instance of A, which in turn inherits from A.prototype.
Live demo: http://jsfiddle.net/BfFkU/
Object.create isn't implemented in IE8, but one can easily manually implement it:
if ( !Object.create ) {
Object.create = function ( o ) {
function F() {}
F.prototype = o;
return new F();
};
}
This can be placed inside a ie8.js file which is loaded only for IE8 and below via conditional comments.
A: Well, if you want to make B.prototype an object that inherits from A.prototype, without executing the A constructor, to avoid all possible side-effects, you could use a dummy constructor to do it, for example:
function tmp() {}
tmp.prototype = A.prototype;
B.prototype = new tmp();
B.prototype.constructor = B;
You could create a function to encapsulate the logic of the creation of this new object, e.g.:
function inherit(o) {
function F() {}; // Dummy constructor
F.prototype = o;
return new F();
}
//...
B.prototype = inherit(A.prototype);
B.prototype.constructor = B;
If you target modern browsers, you could use the ECMAScript 5 Object.create method for the same purpose, e.g.:
B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;
//..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533473",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "47"
} |
Q: Ruby string search: which is faster split or regex? This is a two part question. Given you have an array of strings that can be split at a character (e.g. email addresses at '@' or file names at '.') which is the the most performant way of finding the characters before the split character?
my_string.split(char)[0]
or
my_string[/regex/]
The second part of the question is what's how do you write a regex to get everything before the first instance of a character. The regex below finds certain characters before a '.' (because '.' is not in the pattern) but that was my hacky way to get to a solution.
my_string[/[A-Za-z0-9\_-]+/]
thanks!
A: partition will be quicker than split as it won't continue checking after the first match.
A regular slice with index will be quicker than a regexp slice.
The regexp slice also slows down considerably as the portion of the string before the match becomes larger. It becomes slower than the original split after ~ 10 characters and then becomes a whole lot worse from there on in. If you have a Regexp without a + or * match, I think it fairs a bit better.
require 'benchmark'
n=1000000
def bench n,email
printf "\n%s %s times\n", email, n
Benchmark.bm do |x|
x.report('split ') do n.times{ email.split('@')[0] } end
x.report('partition') do n.times{ email.partition('@').first } end
x.report('slice reg') do n.times{ email[/[^@]+/] } end
x.report('slice ind') do n.times{ email[0,email.index('@')] } end
end
end
bench n, 'a@be.pl'
bench n, 'some_name@regulardomain.com'
bench n, 'some_really_long_long_email_name@regulardomain.com'
bench n, 'some_name@rediculously-extra-long-silly-domain.com'
bench n, 'some_really_long_long_email_name@rediculously-extra-long-silly-domain.com'
bench n, 'a'*254 + '@' + 'b'*253 # rfc limits
bench n, 'a'*1000 + '@' + 'b'*1000 # for other string processing
Results 1.9.3p484:
a@be.pl 1000000 times
user system total real
split 0.405000 0.000000 0.405000 ( 0.410023)
partition 0.375000 0.000000 0.375000 ( 0.368021)
slice reg 0.359000 0.000000 0.359000 ( 0.357020)
slice ind 0.312000 0.000000 0.312000 ( 0.309018)
some_name@regulardomain.com 1000000 times
user system total real
split 0.421000 0.000000 0.421000 ( 0.432025)
partition 0.374000 0.000000 0.374000 ( 0.379021)
slice reg 0.421000 0.000000 0.421000 ( 0.411024)
slice ind 0.312000 0.000000 0.312000 ( 0.315018)
some_really_long_long_email_name@regulardomain.com 1000000 times
user system total real
split 0.593000 0.000000 0.593000 ( 0.589034)
partition 0.531000 0.000000 0.531000 ( 0.529030)
slice reg 0.764000 0.000000 0.764000 ( 0.771044)
slice ind 0.484000 0.000000 0.484000 ( 0.478027)
some_name@rediculously-extra-long-silly-domain.com 1000000 times
user system total real
split 0.483000 0.000000 0.483000 ( 0.481028)
partition 0.390000 0.016000 0.406000 ( 0.404023)
slice reg 0.406000 0.000000 0.406000 ( 0.411024)
slice ind 0.312000 0.000000 0.312000 ( 0.344020)
some_really_long_long_email_name@rediculously-extra-long-silly-domain.com 1000000 times
user system total real
split 0.639000 0.000000 0.639000 ( 0.646037)
partition 0.609000 0.000000 0.609000 ( 0.596034)
slice reg 0.764000 0.000000 0.764000 ( 0.773044)
slice ind 0.499000 0.000000 0.499000 ( 0.491028)
a<254>@b<253> 1000000 times
user system total real
split 0.952000 0.000000 0.952000 ( 0.960055)
partition 0.733000 0.000000 0.733000 ( 0.731042)
slice reg 3.432000 0.000000 3.432000 ( 3.429196)
slice ind 0.624000 0.000000 0.624000 ( 0.625036)
a<1000>@b<1000> 1000000 times
user system total real
split 1.888000 0.000000 1.888000 ( 1.892108)
partition 1.170000 0.016000 1.186000 ( 1.188068)
slice reg 12.885000 0.000000 12.885000 ( 12.914739)
slice ind 1.108000 0.000000 1.108000 ( 1.097063)
2.1.3p242 holds about the same % differences but is about 10-30% quicker at everything, except for the regexp split where it slows down even more.
A: The easiest way to answer the first part is to, as always, benchmark it with your real data. For example:
require 'benchmark'
Benchmark.bm do |x|
x.report { 50000.times { a = 'a@b.c'.split('@')[0] } }
x.report { 50000.times { a = 'a@b.c'[/[^@]+/] } }
end
says (on my setup):
user system total real
0.130000 0.010000 0.140000 ( 0.130946)
0.090000 0.000000 0.090000 ( 0.096260)
So the regex solution looks a little bit faster but the difference is barely noticeable even with 50 000 iterations. OTOH, the regex solution says exactly what you mean ("give me everything before the first @") whereas the split solution gets your desired result in a slightly roundabout way.
The split approach is probably slower because it has to scan the whole string to split it into pieces, then build an array of the pieces, and finally extract the first element of the array and throw the rest away; I don't know if the VM is clever enough to recognize that it doesn't need to build the array so that's just a bit of quick guess work.
As far as your second question is concerned, say what you mean:
my_string[/[^.]+/]
If you want everything before the first period then say "everything until a period" rather than "the first chunk that is made of these characters (which happen to not contain a period)".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533479",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Why is __init__.py not being called? I'm using Python 2.7 and have the following files:
./__init__.py
./aoeu.py
__init__.py has the following contents:
aoeu aoeuaoeu aoeuaoeuaoeu
so I would expect running aoeu.py to error when Python tries to load __init__.py, but it doesn't. The behavior is the same whether PYTHONPATH is set to '.' or unset.
What's going on?
A: __init__.py makes the enclosing directory a package. It won't be executed unless you actually try to import the package directly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Partial mongodb upsert using the c# driver? Mongo version 1.8.2.
Assume I have a class like
public class Acc
{
public int _id { get; set; }
public int? Foo { get; set; }
public int? Bar{ get; set; }
}
Acc a = new Acc
{
_id = 1,
Foo = 3
};
I'd like to call
myCollection.Save(a),
such that
*
*if it doesn't exist, its inserted (easy so far)
*if it does exist, Foo is updated, but, but Bar remains whatever it currently is (perhaps non-null...)
How do I achieve this partial upsert?
Many thanks.
A: It would be quite easy to do it with 2 successive updates :
myCollection.Insert(a,SafeMode.False);
myCollection.Update(Query.EQ("_id",a._id), Update.Set("Foo",a.Foo))
You have to use the SafeMode.False to ensure that if a exists in the collection, the insert won't raise an exception.
At first you would think the order of these operations is important but it isn't : if 2 is executed first, whatever its result, 1 will silently fail.
However I don't have clue on how to use the save method to do this direclty.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533481",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: stop running php function if exceed a given time I need to parse many html files using php.
foreach($url_array as $url){
$file = file_get_contents($url);
parse_html($file);
}
For some reasons (file is too big), function parse_html() take very long time to run or has memory leak in it.
I want to monitor function parse_html(). If the running time exceed a given time, should continue to parse the next url and disregard the current one.
For most of the time, my codes runs great but there are some urls can not be parsed. There is no error output and I guess it is memory leak.
A: This can not be done as easily as you think. Since you are running on one thread only, you cannot have any checks. If this thread is blocking, it is blocking.
You need to create some sort of multi-threaded environment where you run one worker thread for the execution of parse_html() (to increase speed and take advantage of multi-core processors you could even spawn more worker threads) and another thread that checks and kills the workers if they are taking too much time.
A: Taking what @klaus said into account, you would be able to perform this check if you can edit the parse_html() function. Within the function, there are likely either a number of calls to various subfunctions or a large number of for repeat loops. You want to add a check somewhere in the functions, or at the head of the for loops, to see whether the function is taking too long to execute.
Simple pseudocode example:
function parse_html()
start_time = 0;
read file
foreach element_to_be_parsed
runtime = current_time - start_time
if runtime > (whatever)
break
end
...do parsing stuff
end
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533485",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Asp.Net MVC WebGrid helper custom attributes for table rows Is there a way to assign custom data attributes for table rows generated by the WebGrid helper in Asp.Net MVC?
What I would like to end up with is something like this:
<tr data-foo="foo"></tr>
A: No, AFAIK that's not possible. The best you could do on a tr is to apply a style and an alternating row style. I'd recommend MvcContrib Grid or Telerik Mvc Grid as more advanced alternatives to Microsoft's WebGrid helper.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533495",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Problem with position: fixed, div is not really where it should be THE PROBLEM IS SOLVED: I specified right: 0px instead of top: 0px...
I have a problem with CSS' position: fixed; both in Firefox (6.0.2), Chromium (12.0.742.112) and Konqueror (4.6.2). Consider the following example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">
<body>
<div style="background: grey; position: fixed; left: 0px; right: 0px; width: 100%; height: 100%;">
...
</div>
<div id="page2" style="margin: 50px;">
test
</div>
</body>
</html>
My aim is that the first <div> is concealing the whole viewport, but in all three browsers, it does not occludes the topmost 50+x pixels -- which is exactly the top margin of the second <div>. Can anyone tell me what the problem is and how I can fix this without dirty hacks?
Note that inserting any text between the first and the second <div> decreases the problem in the sense that only the topmost x picels are not occluded, which also can be removed by adding style="margin: 0px;" to the <body> tag. The result of the above sample code as well as the version with an "x" added between the two <div>'s in Konqueror can be seen
here:
Thanks a lot in advance!
A: You have not specified top: 0 on the fixed-position div. Why not?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533497",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How can I merge multiple lists of files together with CMake? I have a project built with CMake that needs to copy some resources to the destination folder. Currently I use this code:
file(GLOB files "path/to/files/*")
foreach(file ${files})
ADD_CUSTOM_COMMAND(
TARGET MyProject
POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy "${file}" "${CMAKE_BINARY_DIR}/Debug"
)
endforeach()
Now I want to copy more files from a different folder. So we want to copy files from both path/to/files and path/to/files2 to the same place in the binary folder. One way would be to just duplicate the above code, but it seems unnecessary to duplicate the lengthy custom command.
Is there an easy way to use file (and possibly the list command as well) to concatenate two GLOB lists?
A: The file (GLOB ...) command allows for specifying multiple globbing expressions:
file (GLOB files "path/to/files/*" "path/to/files2*")
Alternatively, use the list (APPEND ...) sub-command to merge lists, e.g.:
file (GLOB files "path/to/files/*")
file (GLOB files2 "path/to/files2*")
list (APPEND files ${files2})
A: I'd construct a list for each of the patterns and then concatenate the lists:
file(GLOB files1 "path/to/files1/*")
file(GLOB files2 "path/to/files2/*")
set(files ${files1} ${files2})
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533502",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "41"
} |
Q: Fan-Gated Facebook Tab with Rails 3 I followed a how to by CoverHound see
How to Create a Fan-gated Facebook Tab with Rails and JavaScript.
Everything went smooth up until step 3 under Serve the content for your FB App with a Rails application When previewing using my local server, I got an error. Typical rails security issue, simply solved by adding
protect_from_forgery :except => :index
to my FacebookController. From there I was golden, tested it on my live site and work swimmingly. Now to add the Gate!
Added the if statement to my facebook index.html.erb file
<% if user_likes_page? %>
<div class="fans_tickets"></div>
<% else %>
<div class="like_tickets"></div>
<% end %>
In the FacebookHelper I added the following to test for the like, and to parse the signed_request from Facebook
def user_likes_page?
fb_request = parse_signed_request
return fb_request['page']['liked'] if fb_request && fb_request['page']
end
def parse_signed_request
if params[:signed_request].present?
sig, payload = params[:signed_request].split('.')
payload += '=' * (4 - payload.length.modulo(4))
data = Base64.decode64(payload.tr('-_','+/'))
JSON.parse( data )
end
rescue Exception => e
Rails.logger.warn "!!! Error parsing signed_request"
Rails.logger.warn e.message
end
When tested on my localhost, It works great, if I haven't liked the page, I see the div with the info telling me to like the page for the contest info, when I have liked the page it shows me the info about the contests mentioned on the non-fan div. Great!
Post it to the Live server and I get an error page that shows up. In my Logs I see this...
2011-09-23 12:38:29 INFO -- Processing by FacebookController#index as HTML
2011-09-23 12:38:29 INFO -- Parameters: {"signed_request"=>"-IIMtqxxUICCyfCOxpsBMvApiaLgEZAkr1tQltvK_bI.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImlzc3VlZF9hdCI6MTMxNjgwMzEwNywicGFnZSI6eyJpZCI6IjEzNzg2NDQ2NjMxMDQwOSIsImxpa2VkIjp0cnVlLCJhZG1pbiI6dHJ1ZX0sInVzZXIiOnsiY291bnRyeSI6ImNhIiwibG9jYWxlIjoiZW5fVVMiLCJhZ2UiOnsibWluIjoyMX19fQ"}
2011-09-23 12:38:29 WARN -- !!! Error parsing signed_request
2011-09-23 12:38:29 WARN -- undefined method `encoding' for #<String:0x7f845221da58>
2011-09-23 12:38:29 INFO -- Rendered facebook/index.html.erb within /layouts/facebook (37.4ms)
2011-09-23 12:38:29 INFO -- Completed in 77ms
2011-09-23 12:38:29 FATAL --
ActionView::Template::Error (undefined method `[]' for true:TrueClass):
1: <% if user_likes_page? %>
2: <div class="fans_flames_tickets"></div>
3: <% else %>
4: <div class="like_flames_tickets"></div>
app/helpers/facebook_helper.rb:4:in `user_likes_page?'
app/views/facebook/index.html.erb:1:in `_app_views_facebook_index_html_erb___1213205873_70103145189880_0'
app/controllers/facebook_controller.rb:6:in `index'
I can't seem to figure out what would be causing this, the code doesn't look to be relying on anything from the actual server itself... Any help would be appreciated!
oh and I didn't continue on with the "How do I get the Facebook userID of the visitor viewing my fan page?" as I don't require it, its just for the like information.
UPDATE
Figured it out with debugging... should have been obvious. My Local host was implementing JSON with Guard running. With Guard only working in my development mode, JSON was installed on on development. Installed on Production and presto...
Feel kinda dumb for not having noticed this sooner! Thanks for all the help Dave & Keith
A: I'm pretty sure the undefined method 'encoding' for #<String... error has to do with running the app on ruby 1.8.7 vs. 1.9.2 or higher. i.e. it looks like your Live server is running 1.8.7 or possibly Ruby Enterprise Edition.
If you can, switch your live server to a ruby 1.9.2 version and see if that fixes it. Otherwise I'll dig in a little more this weekend.
Cheers!
-kw
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533508",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to cast a java.lang.Class to java.lang.class See the bottom for the solution.
I'm trying to write some generic handling code, but in 1 of the sub-classes, it requires a Class that is more specific.
So the base class as a field of type Class, and in the subclass I'm trying to cast that Class object to type Class which is a subclass of org.apache.hadoop.hbase.mapreduce.Mapper.
I get the following error from Netbeans:
"Incompatible types
required: java.lang.Class<org.apache.hadoop.hbase.mapreduce.TableMapper>
found: java.lang.class<capture#3 of ? extends org.apache.hadoop.mapreduce.Mapper>"
when I try the following code
Class<TableMapper> tableMapperClass = null;
if( mapperClass.equals(TableMapper.class) ) {
tableMapperClass = TableMapper.class.asSubclass(mapperClass);
//do stuff
}
and I get:
incompatible types
required: java.lang.Class<org.apache.hadoop.hbase.mapreduce.TableMapper>
found: java.lang.Class<capture#8 of ? extends org.apache.hadoop.hbase.mapreduce.TableMapper>
for
Class<TableMapper> tableMapperClass = null;
if( mapperClass.equals(TableMapper.class) ) {
tableMapperClass = mapperClass.asSubclass(TableMapper.class);
//do stuff
}
Ok, got the answer from my co-worker, looks like this should work:
Class<? extends TableMapper> tableMapperClass = null;
if( mapperClass.equals(TableMapper.class) ) {
tableMapperClass = mapperClass.asSubclass(TableMapper.class);
//do stuff
}
A: If you want to assign a class to tableMapperClass that is actually a subclass of TableMapper, then you need to change the type of the variable. Instead, use:
Class<? extends TableMapper> tableMapperClass = null;
and now you can assign TableMapper.class or any subclass to this variable. When you write Class<TableMapper> you are promising that the variable will be exactly TableMapper.class or null.
Another example:
Class<Number> number = Integer.class; // does not compile
Number number = new Integer(1); // compiles fine
Class<? extends Number> number = Integer.class; // also ok
Note that you can do different things with Class<Number> then you can with Class<? extends Number>. For example, you can call a constructor of Class<Number>, because you know the class. You can't do that with Class<? extends Number> because the constructors are not defined at compile time.
Similarly with, say, List<Number> vs List<? extends Number>. You can call list.add(7) on a variable of type List<Number>, but you can't do that on a List<? extends Number> because you don't know the type of the second list. It might be a List<Double> for example, in which case adding an Integer is not allowed.
Generics are weird. :) Hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533511",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Should hierarchy be included within css names? What is the 'best practice' in terms of including hierarchy within css names? EG:, suppose we have the following html:
<div class="foo">
<div class="$className2">
<div class="$className3">123
</div>
</div>
</div>
Should $className2 include 'foo-' as a prefix, and $className3 include both 'foo-' and $className2 as a prefix? Or should the parent class names not be included within child class names?
A: There is no need to include a parent class's name. CSS selectors will handle any parent formatting you need.
A class, should be describing the type of content you are using. For example
<div class="sidebar">
<div class="error">
</div>
</div>
It is likely that you are going to want to have formatting specific to the error class, that is irrespective of the sidebar class. In the event that you want formatting for the error class that is specific to the sidebar, a css selector could handle that for you
.sidebar > .error
or
.sidebar .error
A: Very simply, are you reusing those class names or will you be reusing those class names anywhere other than in the same kind of structure? If not then it is not necessary to limit it by parent. If you are, however, then it would be a good idea to explicitly indicate which child element is which by including their parent node selectors.
A: One thing that I do most of the time is to prepend an underscore to child classes - I would use the following css for the html from your example:
.foo { ... }
.foo ._$className2 { .. }
.foo ._$className3 { .. }
In this case, ".foo" would be wrapping something like a "foo component". And every child class that is only used inside this wrapper (meaning it wouldn't make sense on its own) is prepended with an underscore. This keeps your css clean and makes it easy for you to see whether a class is intended to be applied to elements everywhere on the page or whether it should appear in a special context.
A: There aren't hard best practices when it comes to CSS class naming. Relevant factors like how many rules you have, how modular your components are, and the scale of your website are important considerations.
For small sites, I prefer to keep the CSS classes very simple.
In your CSS, you can use a nested selector to target elements that are structured in the way you presented like this:
.foo > .bar > .baz { ... }
HTML:
<div class="foo">
<div class="bar">
<div class="baz">
...
</div>
</div>
</div>
For larger sites, or if you're looking for a prescriptive naming pattern, one popular methodology is block-element modifier (BEM).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533519",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Client Object Model access to Custom User Properties I've setup up a custom user property via central admin and set the value on a couple of my users. That said when I query the User Information List using Query Builder I'm not seeing values for the field. I've even tried specifying the fields to return via ViewFields.
Anyone have any experience with this? Any other suggestions?
Thanks!
Casey
A: i've also searched a while, but the closed i came to was this... i ended up using the UserProfileService instead, like described in this article.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533520",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Attributes on a derived type not being deserialized in a WCF client even though KnownType is used I have the following types:
public enum MyEnum
{
Value1,
Value2
}
[DataContract]
public class Configuration
{
[DataMember]
public MyEnum MyValue { get; set; }
[DataMember]
public Credentials CredentialValues { get; set; }
}
[DataContract, KnownType(typeof(CustomCredentials))]
public class Credentials
{
}
[DataContract]
public class CustomCredentials : Credentials
{
[DataMember]
public string Property1 { get; set; }
[DataMember]
public string Property2 { get; set; }
}
And on my service interface, I have a function that returns an instance of Configuration with its CredentialValues property set to a fully populated instance of CustomCredentials. I receive no errors from the client or the server, but while the data is being property serialized on the server and received by the client, the properties on CustomCredentials never have a value. What do I need to change here in order to have these properties properly deserialized on the client?
For reference, the connection between client and server is made with a DuplexChannelFactory over a NetTcpBinding using a data/service contract project that is shared by the client and service applications (the service is self-hosted), so there are no service proxy types that could need to be regenerated.
A: Added this code to the Contracts project along with your DataContracts.
[ServiceContract(Namespace = "http://schemas.platinumray.com/duplex", SessionMode = SessionMode.Required, CallbackContract = typeof(IService1Callback))]
public interface IService1
{
[OperationContract(IsOneWay = true)]
void GetData();
}
public interface IService1Callback
{
[OperationContract(IsOneWay = true)]
void SetData(Configuration config);
}
Created the service.
public class Service1 : IService1
{
public void GetData()
{
var x = new Configuration()
{
MyValue = MyEnum.Value1,
CredentialValues = new CustomCredentials { Property1 = "Something", Property2 = "Something else" }
};
OperationContext.Current.GetCallbackChannel<IService1Callback>().SetData(x);
}
}
class Program
{
static void Main(string[] args)
{
using (ServiceHost host = new ServiceHost( typeof(Service1), new Uri[] { new Uri("net.tcp://localhost:6789") }))
{
host.AddServiceEndpoint(typeof(IService1), new NetTcpBinding(), "Service1");
host.Open();
Console.ReadLine();
host.Close();
}
}
}
Created the client.
public class CallbackHandler : IService1Callback
{
public void SetData(Configuration config)
{
Console.WriteLine(config.CredentialValues.GetType().Name);
Console.WriteLine(((CustomCredentials)config.CredentialValues).Property1);
Console.WriteLine(((CustomCredentials)config.CredentialValues).Property2);
}
}
class Program
{
static void Main(string[] args)
{
// Setup the client
var callbacks = new CallbackHandler();
var endpoint = new EndpointAddress(new Uri("net.tcp://localhost:6789/Service1"));
using (var factory = new DuplexChannelFactory<IService1>(callbacks, new NetTcpBinding(), endpoint))
{
var client = factory.CreateChannel();
client.GetData();
Console.ReadLine();
factory.Close();
}
}
}
Outputs the following as expected:
CustomCredentials
Something
Something else
So this actually worked without modifying any of your data contracts... The same results if I revert to a twoway operation and just return Configuration directly without using the callback.
Also tried making Credentials abstract but could not replicate your problem.
Have I missed something?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533523",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Windows 7 - custom window menu item: GetMsgProc hook not invoked I'll get right to the point: a custom menu item that I added to the system menu of every window through Windows global hooks doesn't cause GetMsgProc to be invoked when the user clicks it.
Here is how I add the menu items:
void HookCore::AppendTasksMenu(HWND windowHandle)
{
// make the popup menu and set up the appearance flags for the sub-items
m_mnuMoveToTasks = CreatePopupMenu();
UINT tasksAppearanceFlags = MF_STRING | MF_ENABLED;
//TODO: need to make proper iterator for MenuItemList
list<MenuItemInfo*>::iterator iter;
for (iter = m_menuItems->Begin(); iter != m_menuItems->End(); iter++)
{
// check if we are adding a separator
if ((*iter)->GetSpecial() == MenuItemInfo::SEPARATOR)
{
AppendMenu(m_mnuMoveToTasks, MF_SEPARATOR, (*iter)->GetItemId(), NULL);
}
else
{
AppendMenu(m_mnuMoveToTasks,
((*iter)->IsChecked() ? tasksAppearanceFlags | MF_CHECKED : tasksAppearanceFlags),
(*iter)->GetItemId(), (*iter)->GetItemName().c_str());
}
}
// get the system menu and set up the appearance flag for our new system sub-menu
HMENU mnuSystem = GetSystemMenu(windowHandle, FALSE);
UINT itemAppearanceFlags = MF_STRING | MF_ENABLED | MF_POPUP;
AppendMenu(mnuSystem, MF_SEPARATOR, ID_MOVE_TO_TASK_SEP, NULL);
// append the sub-menu we just created
AppendMenu(mnuSystem, itemAppearanceFlags, (UINT_PTR)m_mnuMoveToTasks, MOVE_TO_TASK);
}
This creates a new sub-menu in the system menu, and the sub-menu contains my additional items. The item IDs start with 1001, and increment by 1 for each new item. The items can be checked or unchecked.
When a user clicks one of my items I'm expecting to get a WM_SYSCOMMAND message through GetMsgProc, but it never gets called. GetMsgProc does get called however a few times during the initialization with other messages. I do see the WM_SYSCOMMAND message in CallWndProcRetProc though, but it doesn't contain the correct item ID. I was expecting to get the item ID from the low-order word of wParam (as specified here: [http://www.codeproject.com/KB/dialog/AOTop.aspx]), but instead it just contains SC_MOUSEMENU.
Here is how I assign the GetMsgProc hook:
myhookdata[GET_MSG_HOOK].nType = WH_GETMESSAGE;
myhookdata[GET_MSG_HOOK].hkprc = GetMsgProc;
myhookdata[GET_MSG_HOOK].hhook = SetWindowsHookEx(
myhookdata[GET_MSG_HOOK].nType,
myhookdata[GET_MSG_HOOK].hkprc,
AppHandle, 0);
Any ideas? Are my item IDs wrong? What is the right way to get the ID of the clicked item?
Thanks!
Update:
Based on the suggestions below, I tried catching the 'WM_SYSCOMMAND' and 'WM_COMMAND' messages in CallWndProc, CallWndProcRetProc, GetMsgProc, and SysMsgProc. The item selection message wasn't delivered.
I also tried subclassing the window to which the menu belongs, and my WndProc never got the item selection message, although other messages like 'WM_MENUSELECT' and 'WM_UNINITMENUPOPUP' were delivered.
Any pointers where else to check?
Update 2:
So when I subclass/unsubclass the window, I do it in my CallWndProc hook. I subclass when I get the WM_INITMENUPOPUP message, and I unsubclass when I get the WM_MENUSELECT message for menu closing (when lParam equals NULL and HIWORD(wParam) equals 0xFFFF).
I click on the system menu (at which point the WM_INITPOPUPMENU gets raised), move the mouse cursor into my sub-menu that contains the custom items, and then click on one of the items. I log every message I get in my new WndProc during this process. Here is the list of messages I get in my WndProc during this test:
WM_INITMENUPOPUP
147 (0x0093) - what is this message?
148 (0x0094) [9 times] - what is this message?
WM_NCMOUSELEAVE
WM_ENTERIDLE [2 times]
WM_NOTIFY [2 times]
WM_ENTERIDLE [2 times]
WM_NOTIFY
WM_ENTERIDLE [11 times]
WM_MENUSELECT
WM_ENTERIDLE [5 times]
WM_MENUSELECT
WM_ENTERIDLE [6 times]
WM_MENUSELECT
WM_ENTERIDLE [7 times]
WM_MENUSELECT
WM_ENTERIDLE [8 times]
WM_NOTIFY
WM_ENTERIDLE [5 times]
WM_NOTIFY
WM_ENTERIDLE
WM_NOTIFY
WM_ENTERIDLE
WM_UNINITMENUPOPUP
WM_CAPTURECHANGED
The message I'm expecting to see when the user clicks the item is either WM_COMMAND or WM_SYSCOMMAND. I don't have much experience with windows messages or working with the Windows API. Is one of those two the right message to look for? Neither message is there, yet it should be, right? Is there something I'm missing?
A: Ok, I figured it out. I'm not sure why, but I don't see the correct message in any of the hooks. I do, however, see it in WndProc if I subclass the window. In the 2nd Update above I said that I don't see the correct message when subclassing - I was unsubclassing too soon.
So, this is how I subclass:
if (oldWndProc == -1)
{
oldWndProc = SetWindowLongPtr(hwnd, GWLP_WNDPROC, (LONG_PTR)NewWndProc);
currentSubclassedHandle = hwnd;
}
And here is how I unsubclass:
if (oldWndProc != -1)
{
SetWindowLongPtr(currentSubclassedHandle, GWL_WNDPROC, (LONG)oldWndProc);
oldWndProc = -1;
currentSubclassedHandle = NULL;
}
The message I get is WM_SYSCOMMAND, where the wParam is the custom menu item ID. This message gets delivered to the NewWndProc a little bit after the last message that I posted in the 2nd Update.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533528",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: First Letter Capitalization in CakePHP Model Name I have been having a problem lately with my CakePHP models. The capitalization of the first letter of the model name keep changing. For example
$brands = $this->brand->findAllByCompanyId($company);
$list = array();
foreach ($brands as &$brand) {
$list[] = array(
'name' => $brand['brand']['name'],
'id' => $brand['brand']['id']
);
}
For some reason, the key names would change to
$brand['Brand']['name']
$brand['Brand']['id']
Notice the change in the capitalization in the word "Brand." Does anyone have an idea why this happens, or how to force a specific capitalization?
A: One of the basic principles of CakePHP is about making life easier by following conventions. As @Neal above says, CakePHP expects the Model to be capitalised. Stick to it being capitalised and you'll make your life easier.
A: CakePHP models always capitalizes the name of the model when it is selecting it from the database.
(I am assuming that $this->brand->findAllByCompanyId($company); is doing a query)
A: You can override this by adding the line in your model.
$this->name = 'brand';
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533529",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Could someone show what a sample emacs .erc-auth.el file would look like? The ERC Manual shows code for loading authentication information:
(load "~/.emacs.d/.erc-auth")
but does not show what that auth info would look like. I'd appreciate a sample file.
A: It doesn't have any particular format. It's just another file that can contain lisp code (you're giving it to load, after all). Taking a look at the code, I'm not really sure how you would use it to set a password for use on an irc server, but you could use it to set passwords for use with nickserv; see erc-nickserv-passwords in erc-services.el.
A: In your ~/.emacs.d/.ercrc.el
(load "~/.emacs.d/.erc-auth")
And something like this in ~/.emacs.d/.erc-auth
(setq erc-nick "my-id")
(setq erc-password "my-pw")
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533530",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Is there a reason to specify DEFAULT (NULL) on a nullable column? I have a table created like this originally:
CREATE TABLE dbo.XX (
YY int DEFAULT(NULL)
)
If you do this, and then script the table later on, you will get the following code, plus a randomly named default constraint:
CREATE TABLE [dbo].XX([YY] [int] NULL)
GO
ALTER TABLE [dbo].XX ADD DEFAULT (NULL) FOR [YY]
GO
Now is there any real point in specifying DEFAULT (NULL) on a column instead of just leaving it as [YY] [int] NULL in the first place?
A: None that I can think of.
From a programming point of view NULL is the implicit default anyway without needing to (implicitly) create an actual default constraint in sys.objects.
Both of the following will end up inserting NULL without the default constraint.
INSERT INTO [dbo].XX([YY]) VALUES (DEFAULT)
INSERT INTO [dbo].XX([YY]) DEFAULT VALUES
I don't subscribe to the view in the comments that it documents you didn't "forget" to add a default constraint. Nullable columns rarely have default constraints in my experience so this would just add a load of unneeded clutter.
The more important thing to include is the column nullability - as below - so it is clear to future readers that the column is nullable and so it doesn't depend on ANSI_NULL_DFLT session options what you actually end up with.
CREATE TABLE dbo.XX (
YY int NULL
)
A: There is no need to add a DEFAULT(NULL) to nullable columns.
If data is not supplied to such columns, they will have a NULL.
The only benefit I see is the one Larry Lustig has posted in his comment to the question - it documents the fact that you have not forgotten to add a default to the nullable column.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533532",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "30"
} |
Q: Need help plotting data from a text file with Matlab
Possible Duplicate:
How to separate lines of a text file using MATLAB.like first 1-3(modes) in one group next 1-3 in second group and so on
My .txt file contains the values below. I want to group them like first 1,2 2 2 2...,3 in 1st group,second 1,2 2 2 2...,3 in 2nd group, third 1,2 2 2 2...,3 in 3rd group and so on... please help me to get code for this...**like when i call first group then 1st group values should be plotted.
**
mode x y
1 -4177 3764
2 -4177 3763
2 -4177 3760
2 -4173 3758
2 -4176 3752
2 -4179 3758
2 -4182 3769
2 -4195 3785
2 -4221 3803
2 -4251 3833
2 -4276 3866
2 -4302 3899
2 -4321 3926
2 -4392 3965
2 -4381 3955
3 -12851 -12851
1 -4396 3779
2 -4396 3778
2 -4398 3775
2 -4396 3775
2 -4396 3778
2 -4393 3787
2 -4387 3796
2 -4371 3808
2 -4338 3832
2 -4188 3949
2 -4183 3949
2 -4183 3949
3 -12851 -12851
1 4551 3725
2 4552 3724
2 4555 3719
2 4558 3716
2 4560 3713
2 4558 3713
2 4507 3764
2 4476 3800
2 4437 3842
2 4363 3904
2 4359 3916
3 -12851 -12851
1 4372 3728
2 4372 3725
2 4374 3718
2 4372 3716
2 4371 3719
2 4372 3725
2 4383 3742
2 4408 3773
2 4527 3919
2 4533 3922
3 -12851 -12851
1 312 3742
2 313 3742
2 315 3742
2 313 3742
2 312 3743
2 312 3746
2 318 3920
3 -12851 -12851
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533533",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Use MonoDroid / MonoTouch to reuse DataAccess in Mobile Application We have a .net desktop application that has a mobile component (Windows Mobile). The mobile component edits a specific subset of the system data. We would like to create an iPhone and Android version of this mobile app.
Is it possible to use MonoTouch and MonoDroid to compile a 'dll' in each of the respective environments which handles data access, so the apps can be written in the native environment but share the same data behavior? Basically, just focus on UI.
We are planning on using SQLite as the database, since it runs on all platforms, but we don't want to have to write the DDL and queries 3 times.
A: Yes. Use Mono.Data.Sqlite, which is included with both MonoTouch and Mono for Android, and provides an ADO.NET interface atop the native sqlite library.
On the Android side of things, I have found that Mono.Data.Sqlite is most stable with Android v2.2 and later (API level 8+), though others have reported that Android v2.1 works for them.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533534",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can I write a query has a conditional table selection We have 2 tables with identical structure and based on a variable I want to choose which table to select on with out having to write 2 queries in my procedure.
Is this possible?
I tried
declare @table int
set @table = 1
Select orderID, Quantity
from case when @table = 1 then tblOrders else tblSubscriptionOrders end
where filled = 0
But that did not work
A: You would need to use dynamic SQL for this (assuming you want to scale it to more than just 2 tables), which would work but is suboptimal as SQL will not generate statistics for it and have a harder time optimizing the query.
declare @table sysname
declare @SQL varchar(1000)
set @table = 'MyTable'
SET @SQL='SELECT orderID, Quantity FROM ' + QUOTENAME(@table) + ' WHERE filled=0'
exec sp_executesql @SQL
or, in a stored procedure:
CREATE PROCEDURE p_ConditionalSelect @table sysname
as
declare @SQL varchar(1000)
set @table = 'MyTable'
SET @SQL='SELECT orderID, Quantity FROM ' + QUOTENAME(@table) + ' WHERE filled=0'
exec sp_executesql @SQL
A: If it's just two tables you could do:
Declare @table = 1
SELECT *
FROM Table1
WHERE <stuff>
AND @Table = 1
UNION ALL
SELECT *
FROM Table2
WHERE <stuff>
AND @Table = 2
The filter on @table will result in only one of the two halves showing data.
A: One option is to use Dynamic SQL but if performance isn't an immediate issue, much simpler is to just UNION the tables and add a dummy [table] column to select from.
SELECT orderID, Quantity
FROM (
SELECT [table] = 1, orderID, Quantity
FROM tblOrders
UNION ALL
SELECT [table] = 2, orderID, Quantity
FROM tblSubscriptionOrders
) t
WHERE t.Table = @table
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533539",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Comparing two generic lists by ID in .NET 2.0 I am posting because I cannot find good ASP.NET 2.0 examples for this.
I have two lists I want to compare:
List 1:
List<Article> articleResult = new List<Article>();
Article has ID
List 2:
List<TaggedContent> tagResult = new List<TaggedContent>();
TaggedContent has ContentID
I want to find all tags that have a matching Article ID and
return the string TaggedContent.TagName
The return value is a List<string> of TagName.
I am using ASP.NET 2.0 (sorry!).
Can somebody help out? Thanks you.
A: Well, obviously it would be a bit easier with LINQ, but hey... I would probably write:
Dictionary<int, string> tags = new Dictionary<int, string>();
foreach (TaggedContent content in tagResult)
{
tags[content.ContentID] = content.TagName;
}
List<string> matchingTagNames = new List<string>();
foreach (Article article in articleResult)
{
string name;
if (tags.TryGetValue(article.ID, out name))
{
matchingTagNames.Add(name);
}
}
In other words, use a dictionary as an intermediate lookup from ID to name. Let me know if any of this is confusing.
A: Forgot about this:
http://www.albahari.com/nutshell/linqbridge.aspx
Have used it before, a few years ago.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533540",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Define a hierarchy of model classes in CakePHP By default CakePHP has a AppModel class and every model of an application inherits from it. A common design pattern to share logic between models is to create a behavior and configure a model to $actAs that behavior.
But what if I wanted to introduce a hierarchy of model classes like this?:
AppModel
|__ Vehicle
|__ Car
|__ Bike
|__ Helicopter
I have tried to create a Vehicle class that inherits from AppModel, and then every children class inherits from Vehicle. But CakePHP tells me it cannot find the class Vehicle.
How could I make this and where in the CakePHP directory tree should I create Vehicle?
Thanks!
A: it should not be a problem to do so
you only need to make sure you app::import() the "parent model" before you declare it.
or what did you do that the model cannot be found?
If I do sth like that I use a lib to be my "vehicle"
it does not have to be a model in the model directory
e.g. App::import('Lib', 'Vehicle');
Vehicle extends AppModel
Car extends Vehicle
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533556",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Very confusing Silverlight, Amazon S3, and clientaccesspolicy.xml problem This is an odd one.
I'm using Amazon S3 for storage of files in my Silverlight 4 application. Because of the file restrictions associated with the REST API and S3 (files have to be < 1mb for REST), I'm trying to get the SOAP calls to work.
I followed the tutorial written by Tim here http://timheuer.com/blog/archive/2008/07/05/access-amazon-s3-services-with-silverlight-2.aspx
minus the parts about CNAME's since he updated and said it was bad to do that for security,
but kept having issues connecting till it just magically started working this morning and I was able to get a list of all my buckets! So I thought it was fixed, until a few minutes ago when I restarted Chrome and then tried the application again, and it no longer connected to the SOAP endpoint and VS gave me the cross-domain error.
However, I thought about all the stuff I had done earlier to get it working, and the only thing I could think of was that I had a tab open with the clientaccesspolicy.xml file open via bucket.s3.amazonaws.com/clientaccesspolicy.xml. So I tried opening it up again in a new tab, opened my application in another, and then the SOAP calls started working! It only works when the file is open in a tab!!! I've tried it in Firefox and IE as well, same thing!
I have Fiddler, and it doesn't seem to actually ever make a call to the clientaccesspolicy.xml, unless it's hidden inside one of the SSL calls which then there's no way to tell, but there's no straight out calls to .s3.amazonaws.com/clientaccesspolicy.xml going through Fiddler like some other questions on here said there would be.
Would really appreciate some help here guys, thanks.
Edit:
Since someone will probably ask for it, this is the clientaccesspolicy.xml file I'm currently using. I know it's not the most secure, just trying to get this to work before I take the wildcards out
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-methods="*" http-request-headers="*">
<domain uri="http://*"/>
<domain uri="https://*"/>
</allow-from>
<grant-to>
<resource path="/" include-subpaths="true"/>
</grant-to>
</policy>
</cross-domain-access>
</access-policy>
Edit 2:
This appears to be an issue HTTPS. If I force my endpoint to be http, instead of the https required by Amazon, Fiddle does show SL accessing the clientaccesspolicy.xml file.
A: When you open the clientaccesspolicy.xml file in another tab I'm guessing you are passing some credentials which allows you to access it. This sets a cookie which Silverlight can then use to access the clientaccesspolicy.xml file as well. When you close the browser you lose the cookie and thus the access to the file.
A: So I figured it out.
The first problem, about why it would work if I opened it, was not because of a cookie being set (per say), but that accessing it that way over https made me accept the SSL security policy for amazon.
The second problem, I shouldn't have had to accept it. The SSL wildcard amazon uses, *.s3.amazonaws.com, doesn't match buckets that contain periods in them. So as I was following Tim's tutorial I made all my buckets like this
bucketname.domain.com
and when I tried to access it that way through SOAP (and subsequently https), it wasn't working because the wildcard wasn't being matched. Changed all my buckets to contain no buckets, and it worked.
Should also note that Tim's tutorial no longer works as he's using http and in June of this year Amazon forced SOAP calls over https, so http calls no longer work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533563",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to determine DOM position of element in a series of elements when clicked In this scenario, I have a series of list items each of which has a corresponding content area. When clicking a list item, a corresponding content area is manipulated (i.e., if the first list item is clicked, then the first content section would be manipulated).
<ul>
<li>List item</li>
<li>List item</li>
<li>List item</li>
</ul>
<div>
<section>Content section</section>
<section>Content section</section>
<section>Content section</section>
</div>
My old-school way of doing this was giving each list item and section an id, such as "li1", "li2", etc. and "section1", "section2", etc. I would then parse the integer off the id of the element that was clicked and manipulate the corresponding section.
Is there a way to determine this without needing extra id attributes? E.g., if I click the 3rd list item and know that is the 3rd, I can use document.querySelector('div:nth-child(3)') to manipulate the third content section. My question is how to know it was the 3rd element in a series that was clicked to begin with.
My first-thought solution was something like this:
var target = e.target;
var parent = e.target.parentNode;
for (var i in parent.childNodes) {
if (parent.childNodes[i].nodeType == 1 && parent.childNodes[i] == target) {
// found it... i+1
}
}
This seems like a rather expensive operation compared to just using IDs, especially if there were many more list items and content sections. I'm hoping there is some node attribute that will give me the correct DOM position that I haven't yet found.
Modern browser-only solutions welcomed.
A: So i have no ide what you are doing here but there must be a more data oriented approach to this.
Like both the li and the section is referring to the same Product or Person or something so you can find it by that reference.
otherwise you can use the previousElementSibling method to count your location like this
var position = function(el) {
var count = 1;
for(var cur = el.previousElementSibling;
cur !== null; cur = cur.previousElementSibling) {
count++;
}
return count;
};
gl
A: I’d use something like:
var target = e.target,
i = 0;
while(target = target.previousSibling) {
i += target.nodeType == 1;
}
alert('you clicked on '+i);
Fiddle: http://jsfiddle.net/K5Qg9/1/
You can also try using a data lib or assign stuff to the element expano onload:
var elems = document.getElementsByTagName('li'),
i=0;
for(; elems[i]; i++) {
elems[i].rel = i;
}
Then just fetch e.target.rel onclick. Fiddle: http://jsfiddle.net/UnrCt/
A: If you can use jQuery: $(elem).index()
A: Update 2016
Well I've run into this issue again nearly 5 years later only this time I used a much simpler solution using a built-in Array method:
var index = Array.prototype.indexOf.call(event.target.parent.children, event.target);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533564",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Get Filename from External Process File Handle for Win64bit - C# can somebody please help me.
I want to get the filename that corresponds to a file handle of an external process.
Currently i managed to do that only on Win32bit and not Win64bit.
Is code signing required to do that in Windows 64bit ?
Thanks !
A: You have to compile your application as AnyCPU (not x86), because on an x64 OS only x64 processes can access other x64 processes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533566",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to call Scala method with Class[_] parameter from Java? So I'm trying to write a Proxy client to a JSON-RPC service, in Scala. It creates a proxy Service object using a Factory that I can directly calls method and Proxy object's custom invocation handler will send the request thru the wire. The Factory is like this:
ProxyFactory.newAPIProxy(service: Class[_]): AnyRef
Then if I have a Trait like
trait EchoService {
def echo(str: String): String
}
I can get the service object with
ProxyFactory.newAPIProxy(classOf[EchoService])
Now the problem is, I want to use this client in Java classes with Java interfaces and I can't get it to compile. My interface is like:
interface EchoService {
String echo(String str)
}
and when I call
EchoService s = (EchoService) ProxyFactory.newAPIProxy(EchoService.class)
it doesn't compile... I thought .class in Java is equivalent to Class[_] in Scala. I'm new to Scala and have no idea what to search for solutions to this problem!! Please help >.<
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533568",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: java, Morphia how to compare strings when using the Morphia Find Methods Im new to this so here goes.
Trying to get a user called "Bob" from the MongoDb.
I have the:
UserData ud = MonConMan.instance().getDb().find(UserData.class, "name","bob").get();
The "bob" cannot be found if it has capital "Bob".
I understand i can get a List and do equalsIgnoreCase but are
there some Operators i can use?
I have users logging on and must test to see if they are registered. A user can type his name anyway he likes so must find a way to equalsIgnoreCase. Yea this is a problem, i cannot get all names and do equalsIgnoreCase, if there are like 10,000. One could of course initially save all user names in lowercase but that would destroy the visual appearance of the name.
looking at the wiki but cannot see any..
http://code.google.com/p/morphia/wiki/Query
A: Use java regex, like this.
String name = "bob";
Pattern pattern = Pattern.compile("^" + bob + "$", Pattern.CASE_INSENSITIVE);//This line will create a pattern to match words starts with "b", ends with "b" and its case insensitive too.
Query<UserData> query = createQuery().field("name").equal(pattern).retrievedFields(true, "id");//Replace `id` with what ever name you use in UserData for '_id'
UserData user = query.get();
if(user!=null){
//he is already registered
}
else{
//He is a new guy
}
(I am not good at regex, so you may have read about$&^somewhere. )
You should be sure that the user names you are using to validate a new user should be unique across your system.
A: You can make find a name of a UserData using this code :
Query<UserData> query = createQuery().filter("name","bob");
find(query);
In my application, this code return all UserData that haves a field name with "bob" value.
The code can be this way too :
Query<UserData> query = createQuery().field("name").equal("bob");
find(query);
These codes will be in a UserDataDao that extends BasicDao, and receives in the construtor the datastore from morphia.
A: Ended up keeping two fields like
- lowercaseusername
- originalusername
This way i could search for a user using the lowercaseusername
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7533573",
"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.