text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Identifying DNS packets When looking a packet byte code, how would you identify a dns packet.
The IP header's protocol field would tell that a UDP frame follows, but inside the UDP frame no protocol field exists to specify what comes next and, from what I can see, there is nothing inside the frame that would uniquely identify it as a dns packet.
A: Other than it being on port 53, there's a few things you can look out for which might give a hint that you're looking at DNS traffic.
I will refer to the field names used in §4.1 of RFC 1035 a lot here:
1 1 1 1 1 1
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ID |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|QR| Opcode |AA|TC|RD|RA| Z | RCODE |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| QDCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ANCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| NSCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ARCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
As you can see above the header is 12 bytes long - a 2 byte ID, 2 bytes of flags, and 4 x 2 bytes of counts.
In any DNS packet the QDCOUNT field will be exactly one (0x0001). Technically other values are allowed by the protocol, but in practise they are never used.
In a query (QR == 0) the ANCOUNT and NSCOUNT values will be exactly zero (0x0000), and the ARCOUNT will typically be 0, 1, or 2, depending on whether EDNS0 (RFC 2671)and TSIG (RFC 2845) are being used. RCODE will also be zero in a query.
Responses are somewhat harder to identify, unless you're observing both sides of the conversation and can correlate each response to the query that triggered it.
Obviously the QR bit will be set, and as above the QDCOUNT should still be one. The remaining counters however will have many and varied permutations. However it's exceedingly unlikely that any of the counters will be greater than 255, so you should be able to rely on bytes 4, 6, 8 and 10 all being zero.
Following the headers you'll start to find resource records, the first one being the actual question that was asked (§4.1.2). The unfortunate part here is that the designers of the protocol saw fit to include a variable length label field (QNAME) in front of two fixed fields (QTYPE and QCLASS).
[To further complicate matters labels can be compressed, using a backwards pointer to somewhere else in the packet. Fortunately you will almost never see a compressed label in the Question Section, since by definition you can't go backwards from there. Technically a perverse implementor could send a compression pointer back into the header, but that shouldn't happen].
So, start reading each length byte and then skip that many bytes until you reach a null byte, and then the next two 16 bit words will be QTYPE and QCLASS. There are very few legal values for QCLASS, and almost all packets will contain the value 1 for IN ("Internet"). You may occasionally see 3 for CH (Chaos).
That's it for now - if I think of anything else I'll add it later.
A: How about checking the port number? Should be 53 for both source and target port.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565300",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: Where to keep h:messages in a h:datatable while validating two h:columns I am using one h:selectbooleancheckbox in each row to make 2 columns editable.
Have a look at my JSF page
<h:dataTable id="editTable" styleClass = "listtable" value="#{bean.GroupList}" var="group" border="1" first="0" rows="8" width="75%" frame="hsides" rules="all" cellpadding="5" headerClass="tableheading" rowClasses="firstrow, secondrow">
<f:facet name="header">
<h:outputText value="Groups"></h:outputText>
</f:facet>
<h:column>
<f:facet name="header">
<h:outputText value="GroupId"></h:outputText>
</f:facet>
<h:outputText value="#{group.Id}" rendered="#{not bean.checked[group.Id]}"></h:outputText>
<h:inputText value="#{group.Id}" rendered="#{bean.checked[group.Id]}" required="true"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="GroupName"></h:outputText>
</f:facet>
<h:outputText value="#{group.Name}" rendered="#{not bean.checked[group.Id]}"></h:outputText>
<h:inputText value="#{group.Name}" rendered="#{bean.checked[group.Id]}" required="true"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Check to Enable/Disable"></h:outputText>
</f:facet>
<h:selectBooleanCheckbox value="#{bean.checked[group.Id]}" />
</h:column>
</h:dataTable>
I have required="true" for GroupId and GroupName columns.
I am not getting where to keep h:messages for each column to display requiredmessage
Please help.
A: You need to use <h:message> instead to display errors specific to an input element. The <h:messages> will display all messages which are not covered by any <h:message>.
<h:column>
<f:facet name="header">
<h:outputText value="GroupId"></h:outputText>
</f:facet>
<h:outputText value="#{group.Id}" rendered="#{not bean.checked[group.Id]}"></h:outputText>
<h:inputText id="groupId" value="#{group.Id}" rendered="#{bean.checked[group.Id]}" required="true"/>
<h:message for="groupId" />
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="GroupName"></h:outputText>
</f:facet>
<h:outputText value="#{group.Name}" rendered="#{not bean.checked[group.Id]}"></h:outputText>
<h:inputText id="groupName" value="#{group.Name}" rendered="#{bean.checked[group.Id]}" required="true"/>
<h:message for="groupName" />
</h:column>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565302",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Combining several images in Java I have these several images which I need to be combined using BufferedImage in java. The logic of the program is this:
The user will be asked to input data (5 times) then the inputted value will be generated to image (I'm done coding with this part). My problem is how can I Combine them into one image only. Thanks!
A: You can create another new image. Depending on how you would like to combine the images you have two possibilities:
*
*Call getGraphics() on the newly create BufferedImage and use drawImage() multiple times to draw your other images into the newly created one (for example to create a tiled image with all the images you create beforehand)
*Call getRaster() on the newly create BufferedImage and use the methods of this object to draw information from your other images into this image (this way you can achieve any blend effects you might need)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565306",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SBJSONParser on large integer I'm using json-framework to parse JSON data in an iPhone project. But there's a large number in the json data, such as 10432159274, it will make NSNumber overflow. In the SBJsonParser.h, the doc says Numbers in JSON will be converted to NSNumber or NSDecimalNumber. How can I use it so the large integer will be parsed as a NSDecimalNumber? Thanks.
A: I find the solution, updating to the newest version of SBJSON will solve it. The new version using numberWithLongLong to represent integers that has up to 19 digit.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565307",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Javascript "SCRIPT5: Access is denied" opening PDF from script I've read many other posted questions on SO and so far have found nothing to help me solve my problem.
We have a web form that runs on our LAN opening up PDF files in Javascript using the OPEN function.
For the longest time there have been no problems.
Today two of the four users reported that the form was not opening the PDF file anymore.
The other two users are not experiencing any problems.
I now get the same problem on my work machine and home machines (through the VPN), both win7 64 boxes, when trying to use the same web form. The users with the problem have a winXP box and a win7 pro box respectively.
The users with no issues have winXP boxes, for whatever this OS information is worth.
The following Javascript returns SCRIPT5: Access is denied. in IE9 and Access is denied opening file from script in Firefox or Chrome.
var path = 'file://server1//Temp/file.pdf';
var newWin;
if(path != '') {
newWin = open(path,'pdf');
}
I'm at my wits end. What is going on here?? I have frustrated users waiting in the morning, any help?? =)
A: Solution for IE:
On client IE browser do next:
*
*in IE open Internet Options dialog
*Go to Security Tab
*Select Local intranet icon and click on Sites button. In IE9 click Advanced button.
*Add into list address of web-server from you load a page with code in Question (example: http://intranetHttpServer).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565310",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: 1 outlet connects 2 UILabel? Is it possible to connect 1 outlet from file's owner to 2 UILabels from the same view?
I try to do that, but every time I connect the outlet to the other label, it automatic disconnect from outlet to the old label?
Any ideas?
Thanks a lot!
A: No, it's not possible. When you add such outlet you say: "I want reference to the object of class UILabel be saved in that variable." So you can save two different values in one variable.
A: You could use an IBOutletCollection instead of an IBOutlet. Otherwise, what you are asking for does not make any sense. What are you trying to acheive?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565312",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Setting up a eclipse project for learning gcc I cloned git repository for gcc from github.com.
Now I want to navigate the code from eclipse. I have indigo eclipse in windows.
How to setup the project(like setting the include paths), so that issues like:
"GC_NOT_ALPHA not resolved" doesnot come up.
A: Got the answer. Just add the include paths to the C/C++ Include paths in Project/Properties in Eclipse. Then right click Project-> Index -> Rebuild. The indexer of eclipse ran for around 20 mins. It built the index for the project. And now I am able to navigate the project efficiently. And even the "Symbol could not be resolved" errors disappeared.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565314",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Pre-processing C code with GCC I have some C source files that need to be pre-processed so that I can use another application to add Code Coverage instrumentation code in my file.
To do so, I use GCC (I'm using this on a LEON2 processor so it's a bit modified but it's essentially GCC 3.4.4) with the following command line:
sparc-elf-gcc -DUNIT_TEST -I. ../Tested_Code/0_BSW/PKG_CMD/MEMORY.c -E > MEMORY.i
With a standard file this works perfectly, but this one the programmer used a #ifndef UNIT_TEST close and no matter what I do the code won't be pre-processed. I don't understand why since I'm passing -DUNIT_TEST to GCC explicitly defining it.
Does anyone have any clue what could cause this? I checked the resulting .i file and as expected my UNIT_TEST code is not present in it so I get an error when instrumenting it.
A: Anything wrapped in an #ifndef will only be parsed if it's NOT defined so you need to remove that definition to get all the code that is inside that block. GCC can't spit out preprocessed info for all the #ifdef and #ifndef if at preprocessing times symbols are/aren't defined.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565316",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Question on object lifetime : N3242 Draft A point from C++11 n3242 "Duration of subobjects, object lifetime", 3.8/1:
The lifetime of an object is a runtime property of the object. An object is said
to have non-trivial initialization if it is of a class or aggregate type and it
or one of its members is initialized by a constructor other than a trivial
default constructor [ Note: initialization by a trivial copy/move constructor
is non-trivial initialization. — end note ]
The lifetime of an object of type T begins when:
*
*storage with the proper alignment and size for type T is obtained, and
*if the object has non-trivial initialization, its initialization is complete.
The lifetime of an object of type T ends when:
*
*if T is a class type with a non-trivial destructor (12.4), the destructor call starts, or
*the storage which the object occupies is reused or released.
Here they said about trivial or nontrivial copy/move constructor with object lifetime. Can any one explain this with some example program?
And the change of an point describes when the lifetime of an object of type T begins, but they didn't mention when T ends. Why?
A:
Here they said about trivial or nontrivial copy/move constructor with object lifetime. Can any one explain this with some example program?
It's just semantics. In all cases, this can be translated to "the object's lifetime begins when the constructor has finished running". The quote is just being thorough because trivial construction doesn't really involve any such execution.
It's not easy to give an "example" of this point; I could show you trivial and non-trivial constructors, but it wouldn't really tell you anything so I'm not going to.
And the change of an point describes when the lifetime of an object of type T begins, but they didn't mention when T ends. Why?
Yes they did. It should be clearer now that I reformatted the quote in your question.
A: In general an object is alive when its constructor has run to completion and lives until the start of its destructor.
An exception is types that are so trivial that there is no constructor run for them, for example after the code
int* p = (int*)malloc(1024);
you have a bunch of ints that are alive, even though they are not initialized in any way and no constructors have been executed. Still, they are there and you can assign them values.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565321",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: iPhone - How to rotate compass for North magneticHeading I have a compass/image where the needle should always point North.
I have the compass needle/dial rotating using the following conditional statement:
double heading = newHeading.magneticHeading;
if( heading >= 0.0 && heading <= 23.0) {
needleView.transform=CGAffineTransformMakeRotation(heading);
NSLog(@"N");
currentDirLabel.text = @"N";
}
I was wondering if anyone knew how I'd go about rotating the needleView to always point North.
Here's the code I'm using to rotate the needleView UIView:
- (void)rotateImage:(UIImageView *)image duration:(NSTimeInterval)duration
curve:(int)curve degrees:(CGFloat)degrees
{
// Setup the animation
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:duration];
[UIView setAnimationCurve:curve];
[UIView setAnimationBeginsFromCurrentState:YES];
// The transform matrix
CGAffineTransform transform =
CGAffineTransformMakeRotation(DEGREES_TO_RADIANS(degrees));
image.transform = transform;
// Commit the changes
[UIView commitAnimations];
}
To clarify: the UIView (needleView) is spinning as the magneticHeading changes. I'm looking to always lock the the image in the Northerly direction (in this case the part of the image with the North needle)
thanks for any help.
A: this book: Oreilly.Basic.Sensors.in.iOS.Jul.2011 helped me solved this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565325",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: cache and jQuery.get I have a mobile app using cache via manifest file working and being in cache very well.
How can I get to information on the server. jQuery.post works no issues but jQuery.get will not because the browser just checks the local CACHE. Is there away of to make .get work.
Putting a random key after ? has zero effect. Is this something browsers willjust not allow going forward?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565329",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to connect sql database that is not in the same LAN I am trying to connect to sql server 2005 database. It's not in the same LAN. I am Getting error like
An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider: TCP Provider, error: 0 - A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.)
in local LAN i am able to connect with using 'IP & TCP\IP port number' and 'instance name'
is there any solution for this
A: Did you enable remote connections in SQL Server?
See this KB article by Microsoft "How to configure SQL Server 2005 to allow remote connections"
A: Probably it is not "not in your LAN" but "not reachable by your network". There is a high difference and without any additional information that is as good as you will get an answer.
Make sure you can establish a basic network connection first (i.e. for example PING or telnet to the port to see that it opens). It can be a firewall between telling you to get lost.
A: Talk to your network administrator - you don't seem have a route to that subnet from where you are on the network, OR the traffic is being block by a firewall, OR you have an incorrect port or IP in your connection string.
A: There can be lots of reasons for this.
The remote SQL Server is behind a firewall / traffic not routed properly / remote access is not enabled on the sql server / serverside software firewall etc.
You should probably lookup some tutorial on how to setup a Windows Server + MS SQL for remote connections.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565334",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to set focus on the WPF DataGrid or its first row? I have WPF DataGrid placed on the Window. I have a button which performs some business logic and populates the grid.
I want to set focus on the DataGrid (preferably first row in the DataGrid) when i TAB from the button. I have set the TabIndex but somehow the focus does not come on the DataGrid.
The relevant part of the form's XAML is here:
<StackPanel Orientation="Vertical" Grid.Column="2" Margin="20,10,10,10">
<Button Content="Search"
Height="25" HorizontalAlignment="Right" Margin="0,-25,0,0"
Name="btnSearch" VerticalAlignment="Top" Width="75" **TabIndex="1300"** Click="btnSearch_Click" Keyboard.KeyDown="btnSearch_PreviewKeyDown" LostFocus="btnSearch_LostFocus"/>
</StackPanel>
<DataGrid AutoGenerateColumns="False" Grid.Column="1" Margin="20,160,10,10" Name="dataGridOrganisations" **TabIndex="1400"**
BorderThickness="2" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Focusable="True"
ScrollViewer.VerticalScrollBarVisibility="Auto" ScrollViewer.HorizontalScrollBarVisibility="Auto" GridLinesVisibility="None"
ItemsSource="{Binding}" CanUserReorderColumns="False" CanUserResizeRows="False" IsReadOnly="True" SelectionChanged="dataGridOrganisations_SelectionChanged" Keyboard.PreviewKeyDown="dataGridOrganisations_PreviewKeyDown" >
<DataGrid.Columns>
<DataGridTextColumn Header="Shortname" Width="100" Binding="{Binding ShortName}" />
<DataGridTextColumn Header="Internal Code" Width="100" Binding="{Binding LocalID}"/>
<DataGridTextColumn Header="Name" Width="*" Binding="{Binding Name}"/>
</DataGrid.Columns>
</DataGrid>
When I added following code on Button's LostFocus event, it highlights the first row. But when I use 'down' arrow key to select next row in the grid; instead of going to next row it first sets focus on the 'Search' button and next time goes to second row!
if (this.dataGridOrganisations != null && this.dataGridOrganisations.HasItems)
{
this.dataGridOrganisations.Focus();
if (dataGridOrganisations.Items != null && dataGridOrganisations.Items.Count > 0)
{
DataGridRow firstRow = this.dataGridOrganisations.ItemContainerGenerator.ContainerFromItem(dataGridOrganisations.Items[0]) as DataGridRow;
if (firstRow != null)
{
firstRow.IsSelected = true;
}
}
}
How to set focus on the DataGrid (or its first row)? Why TabIndex does not work here?
A: You do not even need a tab-index if there are no focusable controls between the Button and DataGrid in the control hierarchy. You have quite a few handlers and everything seems a bit convoluted to me. I cannot spot anything in that code (maybe someone else can of course), my suggestion would be that you try to simplify your code until it works again as it should by default. e.g. this code's tabbing should work:
<StackPanel>
<Button Content="Lorem Ipsum"/>
<DataGrid ItemsSource="{Binding Source={StaticResource Items}}">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Name}"/>
</DataGrid.Columns>
</DataGrid>
</StackPanel>
Also, why the large tab-index delta? If you were to use 1301 & 1302 there could not be any value between so it should automatically be safer code.
A: Add following code in datagrid of xaml
SelectedIndex="0" Loaded="DataGrid_Loaded"
add below code in .cs file
private void DataGrid_Loaded(object sender, RoutedEventArgs e)
{
DataGrid dataGrid = sender as DataGrid;
dataGrid.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
}
A: DataGrid1.SelectedIndex = 0;
DataGrid1.Focus();
You can put any integer you want to the selectedindex.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565337",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Java HashMap not finding key, but it should I have a strange issue occuring in my application, I will quickly explain global architecture and then my problem in depth.
I use a service to populate a HashMap<DomainObject,Boolean> coming from my database (JPA driven) which is in turn returned to my view, via an EJB remote method call (using Apache Wicket). In this part, I add a new DomainObject to the map returned in order to store any new value from my end user.
The problem occurs when the user hit the "add" button in its browser, I try to retrieve the newly created item in my map, but it fails. By playing with the debugger I face the following things.
Assuming HashMap<DomainObject, Boolean> map and DomainObject do are the two variables interesting I have the following results in the debugger
map.keySet(); gives me an object corresponding to do (even the @whatever simili-reference is identical), hashcode() on both objects returns similar value and equals() between the two returns true
map.containsKey(do); returns false
map.get(do); returns null, weird because my key seems to be in the map.
Assuming my newly created item is the first key enumerated by keySet(), I do the following :
map.get(new ArrayList(map.keySet()).get(0)), and it returns null.
If it can help, by attaching breakpoints to my DomainObject.equals() and DomainObject.hashcode() methods I found that map.get() is only calling hashcode() and not equals().
The only workaround I found is to recreate a new map on top of the existing one new HashMap(map), in this new map, I have no problem at all looking up an object by its key.
I hope someone here can give my a pointer on what happens, thanks.
Environment used :
*
*Sun Java 1.6.0_26 x64 under OS X 10.7.1
*OpenJDK 1.6.0_18 x64 under Debian 6.0.2 (2.6.32)
*Apache Wicket 1.4.17
*Oracle Glassfish 3.1.1
*JBoss Hibernate 3.6.5
DomainObject code :
public class AssetComponentDetailTemplate extends BaseEntite<Long> {
public enum DataType {
TXT,
DATE,
INT,
JOIN,
LIST,
COULEURS,
REFERENCE
}
public enum Tab {
IDENTITE,
LOCALISATION,
CYCLE_DE_VIE,
FINANCE,
RESEAU,
DETAIL
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
@Enumerated(EnumType.STRING)
private DataType dataType;
private Integer classNameId;
private Long orderId;
private Long nextAssetComponentDetailTemplateId;
private String unit;
@Enumerated(EnumType.STRING)
private Tab tab;
@Column(nullable = false)
private Long uniqueOrganizationId;
@OneToMany(fetch = FetchType.LAZY)
@JoinColumn(name = "idAssetComponentDetailTemplate", insertable = false, updatable = false)
private List<AssetComponentDetailJoin> assetComponentDetailJoins;
private Boolean mandatory = false;
public AssetComponentDetailTemplate() {
}
public Long getId() {
return id;
}
public void setId(final Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public DataType getDataType() {
return dataType;
}
public void setDataType(final DataType dataType) {
this.dataType = dataType;
}
public Integer getClassNameId() {
return classNameId;
}
public void setClassNameId(final Integer classNameId) {
this.classNameId = classNameId;
}
public Long getUniqueOrganizationId() {
return uniqueOrganizationId;
}
public void setUniqueOrganizationId(final Long uniqueOrganizationId) {
this.uniqueOrganizationId = uniqueOrganizationId;
}
public Long getNextAssetComponentDetailTemplateId() {
return nextAssetComponentDetailTemplateId;
}
public void setNextAssetComponentDetailTemplateId(final Long nextAssetComponentDetailTemplateId) {
this.nextAssetComponentDetailTemplateId = nextAssetComponentDetailTemplateId;
}
public String getUnit() {
return unit;
}
public void setUnit(final String unit) {
this.unit = unit;
}
public Tab getTab() {
return tab;
}
public void setTab(final Tab tab) {
this.tab = tab;
}
public Long getOrder() {
return orderId;
}
public void setOrder(final Long order) {
this.orderId = order;
}
public Boolean isMandatory() {
return mandatory;
}
@Override
public String toString() {
return name;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final AssetComponentDetailTemplate that = (AssetComponentDetailTemplate) o;
if (classNameId != null ? !classNameId.equals(that.classNameId) : that.classNameId != null) {
return false;
}
if (dataType != that.dataType) {
return false;
}
if (id != null ? !id.equals(that.id) : that.id != null) {
return false;
}
if (name != null ? !name.equals(that.name) : that.name != null) {
return false;
}
if (nextAssetComponentDetailTemplateId != null ?
!nextAssetComponentDetailTemplateId.equals(that.nextAssetComponentDetailTemplateId) :
that.nextAssetComponentDetailTemplateId != null) {
return false;
}
if (orderId != null ? !orderId.equals(that.orderId) : that.orderId != null) {
return false;
}
if (tab != that.tab) {
return false;
}
if (uniqueOrganizationId != null ? !uniqueOrganizationId.equals(that.uniqueOrganizationId) :
that.uniqueOrganizationId != null) {
return false;
}
if (unit != null ? !unit.equals(that.unit) : that.unit != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (dataType != null ? dataType.hashCode() : 0);
result = 31 * result + (classNameId != null ? classNameId.hashCode() : 0);
result = 31 * result + (orderId != null ? orderId.hashCode() : 0);
result = 31 * result +
(nextAssetComponentDetailTemplateId != null ? nextAssetComponentDetailTemplateId.hashCode() : 0);
result = 31 * result + (unit != null ? unit.hashCode() : 0);
result = 31 * result + (tab != null ? tab.hashCode() : 0);
result = 31 * result + (uniqueOrganizationId != null ? uniqueOrganizationId.hashCode() : 0);
return result;
}
A: Is your DomainObject class immutable? Does it have properly implemented hashCode and equals methods?
Note that you will get into trouble if your DomainObject class is not immutable and you change the state of the object while it is in the map in a way that would change the result of calling hashCode or equals.
hashCode must be implemented in such a way that it returns the same value for two objects whenever equals returns true when comparing these objects. See the API documentation of java.lang.Object.hashCode() for detailed information.
A: [This basically expands on Jesper's answer but the details may help you]
Since recreating the map using new HashMap(map) is able to find the element I am suspecting that the hashCode() of the DomainObject changed after adding it to the Map.
For example if your DomainObject looks the following
class DomainObject {
public String name;
long hashCode() { return name.hashCode(); }
boolean equals(Object other) { /* compare name in the two */'
}
Then
Map<DomainObject, Boolean> m = new HashMap<DomainObject, Boolean>();
DomainObject do = new DomainObject();
do.name = "ABC";
m.put(do, true); // do goes in the map with hashCode of ABC
do.name = "DEF";
m.get(do);
The last statement above will return null. Because the do object you have inside the map is under the bucket of "ABC".hashCode(); there is nothing in the "DEF".hashCode() bucket.
The hashCode of the Objects in map should not change once added to map. The best way to ensure it is that the fields on which hashCode depends must be immutable.
A: Here is your clue:
hashcode() on both objects returns similar value
For the objects to be considered equal, their hash codes shouldn't just be similar, they must be identical.
If two objects have different hash codes, then as far as the container is concerned the objects are different. There's no need to even call equals().
From the Javadoc:
The general contract of hashCode is:
*
*If two objects are equal according to the equals(Object) method, then
calling the hashCode method on each of the two objects must produce
the same integer result.
If I were you, I'd take a close look at DomainObject.hashcode() and DomainObject.equals() to see what's causing the contract to be broken.
A: map.get(do) returning null could be easily explained by assuming that the Boolean value for that key might be null but map.containsKey(do) returning false would require do's hashCode to be different at the time of calling containsKey(do) to it's hashCode at the time of retrieving it from the keySet.
To see what's happening, you could (temporarily) use a more verbose implementation of HashMap...
Maybe something like this:
public class VerboseHashMap<K, V> implements Map<K, V> {
private transient final static Logger logger = Logger.getLogger(VerboseHashMap.class);
private HashMap<K, V> internalMap = new HashMap<K, V>();
public boolean containsKey(Object o) {
logger.debug("Object HashCode: " + o.hashCode());
logger.debug("Map contents:");
for (Entry<K, V> entry : internalMap.entrySet()) {
logger.debug(entry.getKey().hashCode() + " - " + entry.getValue().toString());
}
return internalMap.containsKey(o);
}
public V get(Object key) {
logger.debug("Object HashCode: " + key.hashCode());
logger.debug("Map contents:");
for (Entry<K, V> entry : internalMap.entrySet()) {
logger.debug(entry.getKey().hashCode() + " - " + entry.getValue().toString());
}
return internalMap.get(key);
}
}
You'd need to map all the other requirements of the Map interface to your internalMap as well.
Note: This code is not intended for production, nor is it in any way performance oriented, nice or unsmelly....
2nd note (after seeing your code): To use your domain-object as a key for your hashMap, you should only use the immutable parts of your object for hashCode and equals (in this case the id-value). Else lazy-loading further values would change the hashCode...
In Response to your comment:
public class Demo extends TestCase {
public void testMap() {
Map<DomainObject, String> map = new HashMap<DomainObject, String>();
DomainObject sb = new DomainObject();
map.put(sb, "Some value");
System.out.println(map.containsKey(sb));
sb.value = "Some Text";
System.out.println(map.containsKey(sb));
}
private static class DomainObject {
public String value = null;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
DomainObject other = (DomainObject) obj;
if (value == null) {
if (other.value != null)
return false;
} else if (!value.equals(other.value))
return false;
return true;
}
}
}
prints
true
false
The HashCode for the key is computed at the time of putting it into the map.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565341",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Simulating a cron job with a Task in Application Start I'm trying to find a very easy easy way to start a simple cron job for my Web Application. What I was thinking about is starting a Task in the Application_Start event. This task will have a while loop and do some action every hour or so like a normal cron job would do.
Is this a good idea or will this give some trouble?
Some of the problems I could think of are the following:
*
*The Task suddenly stops working or hangs. Maybe make some fail over
mechanism that would check if the task is still running and if not
restart it.
*Memory leaking if the Task totally goes wrong and I have to restart
the whole application.
*No control in changing the Task on the fly but this shouldn't be a
problem for the thing I want to do but for others it might be.
Does someone have any suggestions or experiences with trying this?
A: Doing cron jobs in a web application is a bad idea. IIS could recycle the application at any time and your job will stop. I would recommend you performing this in a separate windows service. You could take a look at Quartz.NET. Another possibility is a console application which does the job and which is scheduled within the Windows Scheduler.
A: Although Darin says that doing cron jobs in a web application is a bad idea (and I agree with him in some way), it may be not so bad, when used wisely and for short running jobs.
Using same Quartz.NET in web application may be quite nice, I'm using in one of my projects like this
http://bugsquash.blogspot.com/2010/06/embeddable-quartznet-web-consoles.html for small jobs and it is running nice - it's easy to monitor (easier than monitoring remote windows process), may be used on shared hosting.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565347",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Taking dump of the database without getting specific table records :Postgres Can any one tell me , How can i take database dump using pg_dump without getting specific table records.
A: If you want a table-wide filter, you can use either --exclude-table=table or --table=table to resp. exclude tables or include only the tables you want.
If you want to "filter out" some records, then you have no direct option to do it. My best advice is to:
*
*dump your full database
*restore it as another name (so you now have a copy of your
original DB)
*DELETE the records you wish to get rid of
*dump the database
This is of course quite rudimentary, and there might be other solutions suitable to your needs. E.g. dump using plain text format then manually edit the dump to remove the rows.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565350",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Get first Monday after certain date? If my app received a certain date, how can I find out the date of first next Monday?
For example, I get the date 28 Sep 2011 and I have to find out the date of the first Monday after this date.
A: Do like this:
GregorianCalendar date = new GregorianCalendar( year, month, day );
while( date.get( Calendar.DAY_OF_WEEK ) != Calendar.MONDAY )
date.add( Calendar.DATE, 1 );
You can now extract the year, day and month from date. Remember that month is 0 based (e.g. January = 0, Febuary = 1, etc.) and day is not.
A: tl;dr
LocalDate.now( ZoneId.of( "America/Montreal" ) ) // Capture the current date as seen by the people in a certain region (time zone).
.with( TemporalAdjusters.next( DayOfWeek.WEDNESDAY ) ) ; // Move to the following Wednesday.
Avoid .Date/.Calendar
The java.util.Date & .Calendar classes bundled with Java/Android are notoriously troublesome. Avoid them.
java.time – LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
Time zone
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
The time zone is crucial in determining the day and day-of-week. Use proper time zone names, never the 3 or 4 letter codes.
If you ignore time zone, the JVM’s current default time zone will be applied implicitly. This means different outputs when moving your app from one machine to another, or when a sys admin changes the time zone of host machine, or when any Java code in any thread of any app within the same JVM decides to call setDefault even during your app‘s execution.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
TemporalAdjuster
Use a TemporalAdjuster to get next day-of-week. We can use an implementation in the TemporalAdjusters (note the plural 's') class: next( DayOfWeek ). Pass an object from the handy DayOfWeek enum.
LocalDate nextWednesday = today.with( TemporalAdjusters.next( DayOfWeek.WEDNESDAY ) );
If you wanted today to be found if it is a Wednesday, then call the similar adjuster TemporalAdjusters.nextOrSame( DayOfWeek ).
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
*
*Java SE 8, Java SE 9, and later
*
*Built-in.
*Part of the standard Java API with a bundled implementation.
*Java 9 adds some minor features and fixes.
*Java SE 6 and Java SE 7
*
*Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
*Android
*
*Later versions of Android bundle implementations of the java.time classes.
*For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
Joda-Time
UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. This section left intact as history.
Here is example code using Joda-Time 2.7.
Get the time zone you desire/expect. If working in UTC, use the constant DateTimeZone.UTC.
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
Get the date-time value you need. Here I am using the current moment.
DateTime dateTime = DateTime.now( zone );
Specify the future day-of-week you want. Note that Joda-Time uses the sensible # 1 for first day of week, rather than zero-based counting found in java.util.Calendar. First day of week is Monday, per international norms and standards (not Sunday as is common in United States).
int dayOfWeek = DateTimeConstants.SATURDAY;
The withDayOfWeek command may go back in time. So we use a ternary operator (?:) to make sure we go forwards in time by adding a week as needed.
DateTime future = ( dateTime.getDayOfWeek() < dayOfWeek )
? dateTime.withDayOfWeek( dayOfWeek )
: dateTime.plusWeeks( 1 ).withDayOfWeek( dayOfWeek );
You may want to adjust the time-of-day to the first moment of the day to emphasize the focus on the day rather than a particular moment within the day.
future = future.withTimeAtStartOfDay(); // Adjust time-of-day to first moment of the day to stress the focus on the entire day rather than a specific moment within the day. Or use `LocalDate` class.
Dump to console.
System.out.println( "Next day # " + dayOfWeek + " after " + dateTime + " is " + future );
When run.
Next day # 6 after 2015-04-18T16:03:36.146-04:00 is 2015-04-25T00:00:00.000-04:00
LocalDate
If you only care about the date without any time of day, you can write similar code with the LocalDate class rather than DateTime. The "Local" means the date could apply to any locality, rather than having a specific time zone.
LocalDate localDate = new LocalDate( 2011 , 9 , 28 );
int dayOfWeek = DateTimeConstants.MONDAY;
LocalDate future = ( localDate.getDayOfWeek() < dayOfWeek )
? localDate.withDayOfWeek( dayOfWeek )
: localDate.plusWeeks( 1 ).withDayOfWeek( dayOfWeek );
When run.
Next day # 1 after 2011-09-28 is 2011-10-03
A: Get Next Monday from the date given.
//code provided by MadProgrammer at http://stackoverflow.com/questions/24177516/get-first-next-monday-after-certain-date/24177555#24177555
Calendar date1 = Calendar.getInstance();
date1.set(2014, 05, 12);
while (date1.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
date1.add(Calendar.DATE, 1);
}
System.out.println(date1.getTime());
Which outputted...
Mon Jun 16 16:22:26 EST 2014
A: I recently developed Lamma which is designed to solve this use case. Simply call next(DayOfWeek.MONDAY) on io.lamma.Date object will return the next Monday.
System.out.println(new Date(2014, 6, 27).next(DayOfWeek.MONDAY)); // Date(2014,6,30)
A: you can use strtotime():
date('Y-m-d H:i:s', strtotime( "Next Monday", strtotime('28 Sep 2011')) );
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565356",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Linq to SQL: How to save the final queries to a log file? I am looking after an application with lots of LINQ to SQL queries. This is basically SilverLight application with MVC. Some of the data loading is taking quite a bit of time. I wanted to know the exact query that is fired on SQL server. Is there any way of storing the generated T-SQL statements to some kind of a log file?
Please suggest some other possible ways as well.
A: LINQ to SQL datacontexts have a property Log that holds a reference to a TextWriter where the text of all the generated SQL queries is written to. You could for example open a StreamWriter for a disk file, then assign it to the Log property of your datacontext. See here for some nice examples: http://damieng.com/blog/2008/07/30/linq-to-sql-log-to-debug-window-file-memory-or-multiple-writers
A: Your best bet is to use the SQL Server Profiler. This will log all queries to a trace file that you can load up after tracing to see how long queries took etc.
Check out this intro.
http://msdn.microsoft.com/en-us/library/ff650699.aspx
Make sure you select the correct event such as Statement Completed.
See this post for further reference
http://weblogs.asp.net/zeeshanhirani/archive/2008/04/18/how-to-use-profiler-with-linq-to-sql-queries.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565357",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: correcting FB meta tags
Possible Duplicate:
How does Facebook Sharer select Images?
Facebook share url thumbnail problem
I discovered, after testing, that I had the wrong meta tags for image or url. After correcting the information on my webpage, FB still seems to reflect the old information. Is there something I can do to correct this? Or does FB just take a certain length of time to kick in and if so, how long?
A: Changing the tags should be enough, but there are some tags that aren't allowed to change past certain limits (check here: https://developers.facebook.com/docs/opengraph/ under "Editing Meta Tags"). You can use the linter tool to check that your tags are correct, or see, if they are wrong - why they are wrong:
https://developers.facebook.com/tools/debug
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565361",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: JSF issue about space I am a green bird in JSF, now I was puzzled by the text of it.
when I assign the value of the outputText with multi-spaces, the result shown in IE has only one space.
ex: the code is like
<h:outputText id="name" value="aa (multi-spaces here) bbb" ></h:outputText>
the result text shown in IE is "aa bbb"
can anyone tell me why the spaces disappear without trace?
A: This behaviour is defined by the HTML spec:
For all HTML elements except PRE, sequences of white space separate "words" (we use the term "word" here to mean "sequences of non-white space characters"). When formatting text, user agents should identify these words and lay them out according to the conventions of the particular written language (script) and target medium.
Note that if you are using XHTML, there are some differences in how attributes and the code point U+000C are handled.
For most text, sequences of white space are not rendered any differently from a single space.
Since this is for a outputText control, you can use a one-way converter for a no-break space solution:
package myconverters;
// imports
public class SpacePreserver implements Converter {
private static final char NO_BREAK_SPACE = '\u00A0';
public String getAsString(FacesContext context, UIComponent component,
Object value) {
if (component instanceof EditableValueHolder) {
throw new IllegalArgumentException(
"Cannot use SpacePreserver converter on editable controls.");
}
return value == null ? null : value.toString().replace(' ', NO_BREAK_SPACE);
}
public Object getAsObject(FacesContext context, UIComponent component,
String value) {
throw new UnsupportedOperationException("Output converter only");
}
}
This can be defined (among other ways) using a faces-config.xml entry:
<converter>
<converter-id>spacePreserver</converter-id>
<converter-class>myconverters.SpacePreserver</converter-class>
</converter>
You can then add this to your output control:
<h:outputText id="text1" value="a b c" converter="spacePreserver" />
This code was tested using JSF 1.1 with a UTF-8 encoded JSP 2.0 view. Note that use of a no-break space will prohibit line-wrapping.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565363",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Visual Studio Extension for Code Alignment Is there any free extension to perform code alignment, like Align Assignments with Productivity Power Tools but to align this code:
public int ID;
public string Title;
public string Text;
public decimal Factor;
in that way, or something like that?
public int ID;
public string Title;
public string Text;
public decimal Factor;
A: You can try Code alignment ;)
P.S. I haven't tried it myself but it looks like it does what you need, so if it's good you can leave a comment here, so more people will know.
A: As Pop Catalin said, Code alignment is what you're after. It's my extension, sorry for not much documentation. It's something that's so much easier to explain with videos, but I'm still to get around to it.
When you align by string it finds the first instance of the string and lines them up. For example if you were to enter '=' then
foo = bar;
foobar = foo;
would become
foo = bar;
foobar = foo;
However, your code doesn't have a common delimiter - except for the space before it. So you can use Align By Space (from the toolbar or ctrl + =, ctrl + space, but you'll have to remove what's already assigned to ctrl + =). Align By Space uses your caret location (you can still select the row you want to align, or let the extension figure it out) and aligns by the first space on each line after your caret location.
Hope that makes sense!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565367",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: WSDL and SOAP: Return object with methods Is there a way to return in soap an object with his methods? If i return xsd:struct in WSDL i only get the properties of the object but i can't use any of the methods.
For example
class person
{
var $name = "My name";
public function getName()
{
return $this->name;
}
}
So after fetching the object:
$client = new SoapClient();
$person = $client->getPerson();
echo $person->getName(); // Return "My Name";
Thanks.
A: You cannot do this with SOAP. Basically your PHP class is being mapped to an XML data structure that's defined by an XML schema. This mapping only includes properties and cannot include executable code. SOAP is designed for interoperability and naturally you cannot share code between, let's say, PHP and Java or .NET. On the receiving side your XML data structure is being transformed into a data structure of the client's programming language (a PHP class if you use SoapClient or a C# class if you use C#). As the XML data structure only carries property information the executable part of the originating class cannot be rebuilt.
But there is one thing that can help if both the SOAP server and the connecting client have access to the same code base (which means the same classes). You can define a mapping between a XML type and a PHP class in the SoapClient's constructor using the classmap-option. This allows SoapClient to map incoming XML data structures to real PHP classes - given the fact that both the server and the client have access to the relevant class definition. This allows you to use methods on the receiving side of the SOAP communication.
class book {
public $a = "a";
public $b = "c";
public function getName() {
return $this->a.' '.$this->b;
}
}
$options = array(
'classmap' => array('book' => 'book')
);
$client = new SoapClient('path/to/wsdl', $options);
$book = $client->test();
echo $book->getName();
The WSDL might look like (copied from one of the SoapClient tests and adpated):
<wsdl:definitions xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://schemas.nothing.com" targetNamespace="http://schemas.nothing.com">
<wsdl:types>
<xsd:schema targetNamespace="http://schemas.nothing.com">
<xsd:complexType name="book">
<xsd:all>
<xsd:element name="a" type="xsd:string"/>
<xsd:element name="b" type="xsd:string"/>
</xsd:all>
</xsd:complexType>
</xsd:schema>
</wsdl:types>
<message name="testRequest">
</message>
<message name="testResponse">
<part name="res" type="tns:book"/>
</message>
<portType name="testPortType">
<operation name="test">
<input message="tns:testRequest"/>
<output message="tns:testResponse"/>
</operation>
</portType>
<binding name="testBinding" type="tns:testPortType">
<soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="test">
<soap:operation soapAction="http://localhost:81/test/interface.php?class=test/dotest" style="rpc"/>
<input>
<soap:body use="encoded" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://schemas.nothing.com"/>
</input>
<output>
<soap:body use="encoded" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://schemas.nothing.com"/>
</output>
</operation>
</binding>
<service name="test">
<port name="testPort" binding="tns:testBinding">
<soap:address location="http://localhost:81/test/interface.php?class=test"/>
</port>
</service>
</wsdl:definitions>
The State of SOAP in PHP might be interesting if you're doing SOAP in PHP.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565371",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to pass two parameters in android sqlite How to pass two parameters in android sqlite query statement?
My query looks like this, but I am getting error. If I use one where condition its working fine, but I want to use two condition.
db.query(true, DB_TABLE, new String[] {KEY_ROWID,Source,
Dest}, DestStn + "=" + t ,Source + "=" +tt,null,
null, null, null, null);
A: you sould replace to "KEY_ROWID = ? AND Source = ?",
new String[] { t, tt }
Complete query:
db.query(DATABASE_TABLE, new String [] {KEY_ROWID, Source,Dest}, "Source = ? AND DestStn = ?",
new String[] { tt, t },
null,
null,
null);
A: you can use db.rawQuery(Your_Query);
i think in your case
String query = "Select * from "+DB_TABLE+ "Where" +DestStn + "=" + t +"and"+Source + "=" +tt
db.rawQuery(query);
A: Try using:
db.query(DB_TABLE, new String[] {KEY_ROWID,Source,Dest},
DestStn + "=" + t +" and "+Source + "=" +tt,null,
null, null, null, null);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565372",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to get all user roles while using entity framework I am using entity framework and membership in my asp.net application.
In one of the pages I need to show all the users and ther roles by joing "aspnet_Membership", "aspnet_Users", "aspnet_Roles" and "aspnet_UsersInRoles" tables.
But whenever i try to add all these tables in the .edmx the "aspnet_UsersInRoles" entity is not getting created instead the "aspnet_Users" and "aspnet_Roles" are getting associated with a Many to Many association. And i can't refrence the "aspnet_UsersInRoles" table, its throwing an compilation error.
Please help me to get the user roles, this is my link query
var users = (from membership in IAutoEntity.aspnet_Membership
from user in IAutoEntity.aspnet_Users
from role in IAutoEntity.aspnet_Roles
where membership.IsApproved == true & membership.UserId == user.UserId
select new { user.UserName, membership.Email, user.aspnet_Roles.TargetRoleName, membership.CreateDate, user.LastActivityDate, membership.IsApproved }).ToList();
A: Assuming that EF is modelling many-to-many association with navigation property called aspnet_Roles in the user class, your linq query is almost correct. Only issue is user.aspnet_Roles.TargetRoleName where you had tried to include many values (for role names) per user in your select.
Remember that you have many roles per user. So you can try out select as
select new { user.UserName, membership.Email, user.aspnet_Roles, membership.CreateDate ...
Note that you will get the roles collection for each user i.e. users[0].aspnet_roles will be the collection.
If there is guarantee that there will always one role associated with the user then you can use syntax such as
select new { user.UserName, membership.Email, user.aspnet_Roles.First().TargetRoleName, membership.CreateDate ...
Note that we are selecting the name of first role from roles associated with the user. If there is no role for the user then First() method will throw an exception. Besides, I am not certain if selecting only first role's name would suffice from application logic perspective.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565374",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Memory Leak in reading from sqlite database
I dont know how to remove this leaks.Cany any body please help me.Thanks
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565380",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to make the background DIV only transparent using CSS I am using CSS attrubutes :
filter: alpha(opacity=90);
opacity: .9;
to make the DIV transparent, but when I add another DIV inside this DIV it makes it transparent also.
I want to make the outer(background) DIV only transparent. How ?
A: Fiddle: http://jsfiddle.net/uenrX/1/
The opacity property of the outer DIV cannot be undone by the inner DIV. If you want to achieve transparency, use rgba or hsla:
Outer div:
background-color: rgba(255, 255, 255, 0.9); /* Color white with alpha 0.9*/
Inner div:
background-color: #FFF; /* Background white, to override the background propery*/
EDIT
Because you've added filter:alpha(opacity=90) to your question, I assume that you also want a working solution for (older versions of) IE. This should work (-ms- prefix for the newest versions of IE):
/*Padded for readability, you can write the following at one line:*/
filter: progid:DXImageTransform.Microsoft.Gradient(
GradientType=1,
startColorStr="#E6FFFFFF",
endColorStr="#E6FFFFFF");
/*Similarly: */
filter: progid:DXImageTransform.Microsoft.Gradient(
GradientType=1,
startColorStr="#E6FFFFFF",
endColorStr="#E6FFFFFF");
I've used the Gradient filter, starting with the same start- and end-color, so that the background doesn't show a gradient, but a flat colour. The colour format is in the ARGB hex format. I've written a JavaScript snippet to convert relative opacity values to absolute alpha-hex values:
var opacity = .9;
var A_ofARGB = Math.round(opacity * 255).toString(16);
if(A_ofARGB.length == 1) A_ofARGB = "0"+a_ofARGB;
else if(!A_ofARGB.length) A_ofARGB = "00";
alert(A_ofARGB);
A: I had the same problem, this is the solution i came up with, which is much easier!
Make a little 1px x 1px transparent image and save it as a .png file.
In the CSS for your DIV, use this code:
background:transparent url('/images/trans-bg.png') repeat center top;
Remember to change the file path to your transparent image.
I think this solution works in all browsers, maybe except for IE 6, but I haven't tested.
A: Just do not include a background color for that div and it will be transparent.
A: It's not possible, opacity is inherited by child nodes and you can't avoid this. To have only the parent transparent, you have to play with positioning (absolute) of the elements and their z-index
A: I don't know if this has changed. But from my experience. nested elements have a maximum opacity equal to the fathers.
Which mean:
<div id="a">
<div id="b">
</div></div>
Div#a has 0.6 opacity
div#b has 1 opacity
Has #b is within #a then it's maximum opacity is always 0.6
If #b would have 0.5 opacity. In reallity it would be 0.6*0.5 == 0.3 opacity
A: .modalBackground
{
filter: alpha(opacity=80);
opacity: 0.8;
z-index: 10000;
}
A: background-image:url('image/img2.jpg');
background-repeat:repeat-x;
Use some image for internal image and use this.
A: <div id="divmobile" style="position: fixed; background-color: transparent;
z-index: 1; bottom:5%; right: 0px; width: 50px; text-align:center;" class="div-mobile">
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565384",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "39"
}
|
Q: reduce the size of the image programmatically image from gridview How ca we compare data from web service with data in local folder and replace the data coming from web service with our data in local folder.
Also tell me how to programatically reduce the size of the image that is displayed from gridview into Edit Text.
Size of image can be set in grid view. Is it possible to set the size of image displayed in Edit Text that is received from grid view selected image.
Please guide me in this issue. Any sample working example shall be very useful for me to understand and work accordingly.
A: Paresh is right. You should put these are 2 different questions.However for first question you can go ahead like this:
String link = "YOUR URL";(WEBSERVICE)
URL text= new URL(link);
InputStream isText = text.openStream();
byte[] bytes=new byte[isText.available()];
isText.read(bytes);
String s = new String(bytes);
System.out.println(s);
//CHECK WHAT IS THE VALUE RETURNED BY YOUR WEBSERVICE...IF IT IS A STRING AS IN THIS EXAMPLE "AVAILABLE" THEN PUT THAT CONDITION FOR COMPARING
if(s.equals("unavailable"))// THIS MAY VARY
{
//put the path of your local folder to access it
//YOUR COMPARE CONDITION
}
else
{
// else condition
}
A: For the second question : I think you can use Bitmap.createScaledBitmap where we can re-size the Bitmap image.
Can you elaborate the first question.. what kind of data are you comparing..??
A: 2) For second question,
If you are using Imageview, you can change the content in the XML file as
android:layout_height="XXdip"
android:layout_width = "XXdip"
android:layout_marginLeft="XXdip"
android:layout_marginRight = "xxdip"
I personally do not prefer hardcoding using px(pixels), If you can post your code, we can help you better.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565388",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Spring MVC: FileNotFoundException "\Uploads\MyUploads\loading.gif (The system cannot find the path specified)" Problem Context:
I am trying to persist a file, uploaded by the user, to file system.
Description:
Actually, I am using Spring MVC (3.0) and this is how I am trying to persist the file,
String orgName = file.getOriginalFilename();
String filePath = "/Uploads/MyUploads/"+ new Date().getTime()+orgName;// Unique Image Name
File dest = new File(filePath);
file.transferTo(dest);
I have a folder Uploads\MarketplaceUploads, at the root of my application. But still I am getting FileNotFoundException "\Uploads\MyUploads\loading.gif (The system cannot find the path specified)".
Below is the directory structure:
A: You should not store uploaded files in public web content.
*
*It will not work in any way when the WAR is not expanded by the container (this is configureable at server level and not controllable whenever it's a 3rd party host). You simply can't write the uploaded file to it in any way.
*All uploads will get lost whenever you redeploy (an update) of the WAR. You need to remember to backup them everytime.
*In some servers, all uploads will also get lost whenver the server is restarted. You have no control over this whenever it's a 3rd party host.
Store them outside the server's webapps folder. Provide the root of this location as an absolute disk file system path to your webapp, e.g. by a properties file or a VM argument. An alternative is to store them in a database, this is often the only solution if it's a 3rd party host which doesn't offer access to a fixed location outside the web content.
A: Ensure you add the web-app context path before using the file
String orgName = file.getOriginalFilename();
String filePath = getServletContext().getRealPath("/") + "/Uploads/MyUploads/"+ new Date().getTime()+orgName;// Unique Image Name
File dest = new File(filePath);
file.transferTo(dest);
From the javadoc of getRealPath()
Gets the real path corresponding to the given virtual path.
For example, if path is equal to /index.html, this method will return the absolute file path on the server's filesystem to which a request of the form http://://index.html would be mapped, where corresponds to the context path of this ServletContext.
The real path returned will be in a form appropriate to the computer and operating system on which the servlet container is running, including the proper path separators.
Resources inside the /META-INF/resources directories of JAR files bundled in the application's /WEB-INF/lib directory must be considered only if the container has unpacked them from their containing JAR file, in which case the path to the unpacked location must be returned.
This method returns null if the servlet container is unable to translate the given virtual path to a real path.
A: Try this instead,
String orgName = file.getOriginalFilename();
// the leading slash is important
String filePath = "/Uploads/MyUploads/"+ new Date().getTime()+orgName;
File dest = new File(req.getServletContext().getResource(filePath).toURI());
file.transferTo(dest);
Using getRealPath() is, indeed, a bad idea. Simply, because you are trying to read a resource which actually resides inside the application. Therefore, we need not use getRealPath(). Furthermore, if the application is being run from a bundled .war file, getRealPath() will return null.
Resources:
*
*Similar problem is being discussed over here, Why does getRealPath() return null when deployed with a .war file?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565397",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: create 2 vertical scrollbars in layout in android In my layout there is one Listview and multiple controls. If I create scroll view
listview scroll does not work. If I remove scroll view listview scrolling is works.
how to get both scrolls working?
Thanks in advance,
Durai
A: You cannot get both to scroll. You can define weight for your Listview while wrapping its content.
Otherwise if other controls take too much of the screen space then, instead of using a Listview, Use a Linearlayout to hold your items with a ScrollView as the parent.
A: If you really need both (ScrollView and ListView), try to reduce the width of the ListView, so that you have some free space on the left or right of the ListView, where the user can touch and scroll the ScrollView below it. Otherwise the ListView will always receive the scroll events.
I mean it like this:
-----------------------
I I I
I I I
I I I
I ListView I I
I I I
I I I
I I I
-----------------------
<---- ScrollView ---->
A: ListView comes with its own scroll and extends till the length of the list. You cannot club scroll and listview together.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565399",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How does the jqueryUI autocomplete example get away with not using $(document).ready I am determined to figure out how the example at http://jqueryui.com/demos/autocomplete/#default works without being wrapped in a $(document).ready because I just spend over an hour and a half trying unsuccessfully to reproduce this when all I needed to do was wrap it in the $(document).ready
At the very bottom of the source I see this one, but nothing to do with the autocomplete.
<script type="text/javascript">
$(document).ready(function() {
$('a').click(function(){
this.blur();
});
});
</script>
A: the $(function () {blah}) is the same as using $(document).ready. It's the third syntax in the docs.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565403",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Load a cubemap in a DDS file with DevIL I only get the first face in a cubemap. How do I access/load the other ones?
With DevIL 1.7.8 on Ubuntu Natty:
I use ilLoad or ilLoadImage to load a dds-file with 6 textures, but only the first face gets loaded.
ilGetInteger() give the results:
IL_IMAGE_DEPTH: 1
IL_IMAGE_BYTES_PER_PIXEL:4
IL_NUM_LAYERS: 0
IL_NUM_IMAGES: 0
IL_IMAGE_TYPE: 5121 (= 0x1401, not even an image type according to il.h! )
IL_IMAGE_CUBEFLAGS: 1024
IL_ACTIVE_IMAGE: 0
IL_IMAGE_SIZE_OF_DATA: 65536 (which is 128x128x4 and match the "image size in pixels" times "bytes per pixel".)
If I try to use ilActiveImage with a value other than 0, it returns false.
I have tried Earth.dds and LightCube.dds from the RenderMonkey example textures, as well as saved my own dds-file with GIMP, but only the first face gets loaded for all of them.
Does anyone have any suggestion?
(I have compiled DevIL with ilu and ilut-support, if that would make any difference.)
A: DevIL does not have provisions for DDS Cubemaps. Neither do a surprising number of image loaders.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565404",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Underline UILabel text I have UILabel whose string is being set at runtime. The text in UILabel is centrally aligned. I want to display an underline below the label text. But the line should have X same where the text begins (consider center alignment) and width equal to text width (not label width). For underline I have created a UIView and have set its background color. But I am not able to fix length of underline as I want.
Below is the code I have used:
UILabel *blabel = [[UILabel alloc] initWithFrame:CGRectMake(XX, 6, 271, 26)];
blabel.text = [m_BCListArray objectAtIndex:tagcount];
blabel.textAlignment = UITextAlignmentCenter;
blabel.backgroundColor = [UIColor clearColor];
blabel.textColor = [UIColor whiteColor];
blabel.font = [UIFont systemFontOfSize:14];
[scrollDemo addSubview:blabel];
//underline code
CGSize expectedLabelSize = [[m_BCListArray objectAtIndex:tagcount] sizeWithFont:blabel.font constrainedToSize:blabel.frame.size lineBreakMode:UILineBreakModeWordWrap];
CGRect newFrame = blabel.frame;
newFrame.size.height = expectedLabelSize.height;
blabel.frame = CGRectMake(blabel.frame.origin.x, blabel.frame.origin.y, 271, expectedLabelSize.height);
blabel.numberOfLines = 1;
//[blabel sizeToFit];
int width=blabel.bounds.size.width;
int height=blabel.bounds.size.height;
UIView *viewUnderline=[[UIView alloc] init];
int len = [[m_BCListArray objectAtIndex:tagcount]length];
viewUnderline.frame=CGRectMake(XX, 26, len, 1);
viewUnderline.backgroundColor=[UIColor whiteColor];
[scrollDemo addSubview:viewUnderline];
[viewUnderline release];
How can I fix the width of line according to text I get?
A: Here's how I did it. Subclass UILabel and draw the line. Make sure you bring in QuartzCore
@interface MyUnderlinedLabel : UILabel
@end
#import <QuartzCore/QuartzCore.h>
@implementation MyUnderlinedLabel
-(void)drawRect:(CGRect)rect
{
[super drawRect:rect];
// Get bounds
CGRect f = self.bounds;
CGFloat yOff = f.origin.y + f.size.height - 3.0;
// Calculate text width
CGSize tWidth = [self.text sizeWithFont:self.font];
// Draw underline
CGContextRef con = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(con, self.textColor.CGColor);
CGContextSetLineWidth(con, 1.0);
CGContextMoveToPoint(con, f.origin.x, yOff);
CGContextAddLineToPoint(con, f.origin.x + tWidth.width, yOff);
CGContextStrokePath(con);
}
@end
A: I just simplified the implementation a bit:
UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 100, 320, 30)];
myLabel=[self setLabelUnderline:myLabel];
-(UILabel *)setLabelUnderline:(UILabel *)label{
CGSize expectedLabelSize = [label.text sizeWithFont:label.font constrainedToSize:label.frame.size lineBreakMode:label.lineBreakMode];
UIView *viewUnderline=[[UIView alloc] init];
CGFloat xOrigin=0;
switch (label.textAlignment) {
case NSTextAlignmentCenter:
xOrigin=(label.frame.size.width - expectedLabelSize.width)/2;
break;
case NSTextAlignmentLeft:
xOrigin=0;
break;
case NSTextAlignmentRight:
xOrigin=label.frame.size.width - expectedLabelSize.width;
break;
default:
break;
}
viewUnderline.frame=CGRectMake(xOrigin,
expectedLabelSize.height-1,
expectedLabelSize.width,
1);
viewUnderline.backgroundColor=label.textColor;
[label addSubview:viewUnderline];
[viewUnderline release];
return label;
}
A: UILabel *blabel = [[UILabel alloc] initWithFrame:CGRectMake(XX, 6, 271, 26)];
blabel.text = [m_BCListArray objectAtIndex:tagcount];
blabel.textAlignment = UITextAlignmentCenter;
blabel.backgroundColor = [UIColor clearColor];
blabel.textColor = [UIColor whiteColor];
blabel.font = [UIFont systemFontOfSize:14];
[scrollDemo addSubview:blabel];
//underline code
CGSize expectedLabelSize = [[m_BCListArray objectAtIndex:tagcount] sizeWithFont:blabel.font constrainedToSize:blabel.frame.size lineBreakMode:UILineBreakModeWordWrap];
UIView *viewUnderline=[[UIView alloc] init];
viewUnderline.frame=CGRectMake((blabel.frame.size.width - expectedLabelSize.width)/2, expectedLabelSize.height + (blabel.frame.size.height - expectedLabelSize.height)/2, expectedLabelSize.width, 1);
viewUnderline.backgroundColor=[UIColor whiteColor];
[scrollDemo addSubview:viewUnderline];
[viewUnderline release];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565407",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Fail to launch multiple setInterval I am building a function to update a HTML node's background position at a regular basis. The function works for a single node, but when called upon multiple node (in the following example), only the last node is affected by this function.
According to the alert(index) within the function, setInverval() is called for each node.
I cannot figure out why it doesn't take effect.
http://jsfiddle.net/GqNgs/1/
var bgImgAnimate = function (settings) {
$.each(settings.nodeList, function (index, node) {
thisNode = $(node);
var thisPosition;
setInterval(function () {
alert(index);
//calculate the position before position the image
thisPosition = - settings.frameWidth * settings.currentFrame;
thisNode.css('backgroundPosition', (thisPosition + 'px') + ' ' + (settings.verticalPos + 'px'));
}, settings.interval);
});
};
var settings = {
nodeList: $('#star1, #star2, #star3'),
verticalPos: 0,
currentFrame: 1,
frameWidth: 26,
startTime: 2,
frameNumber: 10,
interval: 200
}
bgImgAnimate(settings);
A: Your variable thisNode is global, so once you execute your function you quickly loop through all three elements (what you call nodes), but when that's done, all three functions that will execute at the interval will refer to a single element (and therefore only that one will be changed, the fact that your alerts showed you the correct answer, is because each alert references a differently and correctly scoped index value).
Simple fix, change:
thisNode = $(node);
to:
var thisNode = $(node);
http://jsfiddle.net/GqNgs/2/
As an aside, it would probably be more scalable to set only one interval function, and each time it's called move the background (or do whatever manipulation you want) on all elements, rather than an interval for each element.
A: It is because of you iterate nodeList and you ASSIGN thisNode each time and then you pass it to the interval. But what happens is that thisNode is three times rewrited (after the loop it reffers to the LAST node) and AFTER that three intervals are executed all with the same thisNode variable which at the moment is the LAST node.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565408",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Where is the bug in my polynomial calculation code? my aim is to compare the two different method to calculate a polynomial..
but if you run it on a mac (my computer is MacBook Air)
you will find the two results are different...
.but....
if you delete the "/* ... */" part OR delete the two "//" before "for ..."
it works fine...
plus..it works fine on linux...
can anyone tell me why?..
here is my program:
#define MAX_NUM 10
#define TEST_TIME 1
#define test_type double
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
test_type normal_method(test_type *a, test_type x, int degree)
{
test_type s = 0.0;
test_type e = 1.0;
for (int i = 0; i <= degree; i++) {
s += a[i] * e;
e *= x;
}
printf("%lf\n", s);
return s;
}
test_type horner_method(test_type *a, test_type x, int degree)
{
test_type s = a[degree];
for (int i = degree - 1; i >= 0; i--) {
s *= x;
s += a[i];
}
printf("%lf\n", s);
return s;
}
void generate_data(test_type *a, test_type *x, int degree)
{
srand( time(NULL) );
for (int i = 0; i <= degree; i++) {
a[i] = (test_type)(rand() % MAX_NUM + 1) / (test_type)(rand() % MAX_NUM + 1);
*x = (test_type)(rand() % MAX_NUM + 1) / (test_type)(rand() % MAX_NUM + 1);
}
}
int main()
{
const int degree = 10;
test_type a[degree];
test_type x;
generate_data(a, &x, degree);
//Just by clear the /**/ below, the program will work fine....
/*
printf("x = %lf\n", x);
for (int i = 0; i <= degree; i++) {
printf("%lf\n", a[i]);
}
*/
clock_t begin, end;
// Or clear the two // below, it will work fine too....
begin = clock();
// for (int i = 0; i < TEST_TIME; i++)
normal_method(a, x, degree);
end = clock();
printf("The normal method used %d clock times\n", end - begin);
begin = clock();
// for (int i = 0; i < TEST_TIME; i++)
horner_method(a, x, degree);
end = clock();
printf("The horner method used %d clock times\n", end - begin);
return 0;
}
A: You are accessing memory that is out of bounds of the array you create in main and use in the other functions. This happens in at least three places.
*
*The loop bounds in normal_method go from zero to ten:
for (int i = 0; i <= degree; i++) { // a[degree] is out of bounds
*On the first line of horner_method you are accessing memory that is out of bounds of your array:
test_type s = a[degree]; // a[degree] is out of bounds
*The loop bounds in generate_data are incorrect the same way as in normal_method:
for (int i = 0; i <= degree; i++) { // a[degree] is out of bounds
A: You shouldn't use %lf to print a double. Just %f is fine. You probably confused that with scanf, which needs the l.
With the compiler warning options -Wall -Wextra -Wformat=2 gcc should tell you what's wrong in your code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565411",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Edit text in C# console application? Is there a way to edit text in a C# console application? In other words, is it possible to place pre-defined text on the command line so that the user can modify the text and then re-submit it to the app?
A: Yes. You need to use method SetCursorPosition of Console. Example:
Console.WriteLine("hello");
Console.SetCursorPosition(4, 0);
Console.WriteLine(" ");
It will display 'hell'
You need custom realization of ReadLine method which let you to edit n-symbols (default string) in Console and return string from a user. This is my example:
static string ReadLine(string Default)
{
int pos = Console.CursorLeft;
Console.Write(Default);
ConsoleKeyInfo info;
List<char> chars = new List<char> ();
if (string.IsNullOrEmpty(Default) == false) {
chars.AddRange(Default.ToCharArray());
}
while (true)
{
info = Console.ReadKey(true);
if (info.Key == ConsoleKey.Backspace && Console.CursorLeft > pos)
{
chars.RemoveAt(chars.Count - 1);
Console.CursorLeft -= 1;
Console.Write(' ');
Console.CursorLeft -= 1;
}
else if (info.Key == ConsoleKey.Enter) { Console.Write(Environment.NewLine); break; }
//Here you need create own checking of symbols
else if (char.IsLetterOrDigit(info.KeyChar))
{
Console.Write(info.KeyChar);
chars.Add(info.KeyChar);
}
}
return new string(chars.ToArray ());
}
This method will display string Default. Hope I understood your problem right (I doubt in it)
A: One thing that came to my mind is to...simulate keystrokes.
And a simple example using SendKeys:
static void Main(string[] args)
{
Console.Write("Your editable text:");
SendKeys.SendWait("hello"); //hello text will be editable :)
Console.ReadLine();
}
NOTE: This works only on active window.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565415",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
}
|
Q: FFT image comparison (theoretical) Can anybody explain me (simplified) what happen if I do an image comparison with FFT? I somehow don't understand how it's possible to convert a picture into frequencies and how this is used to differentiate between two images. Via Google I can not find a simple description, which I (as non mathematic/informatic) could understand.
Any help would be very appreaciated!
Thanks!
A: Alas, a good description of an FFT might involve subjects such as the calculus of complex variables and the computational theory of recursive algorithms. So a simple description may not be very accurate.
Think about sound. Looking at the waveform of the sound produced by two singers might not tell you much. The two waveforms would just be a complicated long and messy looking squiggles. But a frequency meter could quickly tell you that one person was singing way off pitch and whether they were a soprano or bass. So you might be able to determine that certain waveforms did not indicate a good match for who was singing from the frequency meter readings.
An FFT is like a big bunch of frequency meters. And each scan line of a photo is a waveform.
Around 2 centuries ago, some guy named Fourier proved that any reasonable looking waveform squiggle could be matched by an appropriate bunch of just sine waves, each at a single frequency. Other people several decades ago figured out a very clever way of very quickly calculating just which bunch of sine waves that that was. The FFT.
A: Discrete FFT transforms a (2D) matrix of let's say, pixel values, into a 2D matrix in frequency domain. You can use a library like FFTW to convert an image from the ordinary form to the spectral one. The result of your comparison depends on what you really compare.
Fourier transform works in other dimensions than 2d, as well. But you'll be interested in a 2D FFT.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565417",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How display section of time in different text field? I have three text field in which i want to show the current time. In the first text field,it shows only hours , in second text field it shows only minute and in last one it shows am or pm. For getting current time I use this code but how do I show according to my requirement?
code...
- (void)viewDidLoad {
NSDate* date = [NSDate date];
//Create the dateformatter object
NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
//Set the required date format
[formatter setDateFormat:@"HH:MM"];
//Get the string date
NSString* str = [formatter stringFromDate:date];
//Display on the console
NSLog(@"%@",str);
//Set in the lable
time_label.text=[NSString stringWithFormat:@"%@ AM",str];
[super viewDidLoad];
}
Thanks in advance...
A: NSDate* date = [NSDate date];
//Create the dateformatter object
NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
//Set the required date format
[formatter setDateFormat:@"hh MM a"];
//Get the string date
NSString* str = [formatter stringFromDate:date];
//Display on the console
NSLog(@"%@",str);
NSMutableArray *Arr=[str componentsSeparatedByString:@" "];
textFeild1.text=[Arr objectAtIndex:0]; //hoursTextFeild
textFeild2.text=[Arr objectAtIndex:1]; //minutesTextFeild
textFeild3.text=[Arr objectAtIndex:2];//Am/Pm TextFeild
A: - (void)viewDidLoad {
NSDate* date = [NSDate date];
//Create the dateformatter object
NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
//Set the required date format
[formatter setDateFormat:@"HH:MM"];
//Get the string date
NSString* str = [formatter stringFromDate:date];
//Display on the console
NSLog(@"%@",str);
//Set in the label
//seperate its components
NSMutableArray *array = [str componentsSeperatedByString:@" "];
[firstTextField setText:[array objectAtIndex:0]];
[secondTextField setText:[array objectAtIndex:1]];
[thirdTextField setText:@"AM/PM"];
[super viewDidLoad];
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565418",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What's the extra time for when loading web page in rails? I got a page which is generated in a few milliseconds.
Completed 200 OK in 83ms (Views: 75.9ms)
When I try to load this page with "time wget http://localhost:3000/search", I fould that it takes 1.5 seconds.
real 0m1.562s
user 0m0.001s
sys 0m0.003s
There's no js execution time in it as it's not loaded in browser. So what's the extra time for? Is there any tools that can figure out time cost details in rails?
Thanks.
A: If Rails is loaded up in development, the controllers are not cached (by default) which can add to latency and might not be captured by Rails' measurement (can't say I've looked).
Another thing to look at is the Rack server in use. WEBrick works like a champ but is painfully slow; Thin and Unicorn are significantly faster at servicing requests. I would consider looking into using Rack middleware or Rails Metal if you need an action to be optimized for speed.
At the TCP level, the localhost->127.0.0.1 DNS lookup will take some small amount of time. Also, wget has to establish a new socket to the app. Neither of these will be measurable by the app itself.
For what it's worth, that same experiment against a Rails 2.3.12 app running on Unicorn 4.0.1 hitting the login page:
Completed in 16ms (DB: 4) | 302 Found [http://localhost/]
real 0m0.407s
user 0m0.000s
sys 0m0.010s
Update 9/28/2011:
Digging in at the HTTP layer, curl supports tracing a URL request with timestamp outputs:
curl --trace-ascii trace.log --trace-time http://localhost:3000
To dig a bit further and see the actual calls, try using strace with timing mode on:
strace -T curl http://localhost:3000
Example output from both of these is available as a gist.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565419",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Create and clean DB setup only once for testing all DAOs Does anybody knows a way to achieve the following flow for testing DAOs:
*
*Run SQL script to create common DB setup (insert data into all tables)
*Test DAO1
*Test DAO2
*…
*Clean-up DB Data created in Step 1
Using Spring, Hibernate, JUnit, Maven stack.
I understand that best practice would be that we create data for each test DAO (@BeforeClass) and clean-up the same after all tests are done (@AfterClass).
But in our case there are just too many dependencies between different database tables (client’s legacy DB :-( can’t do anything about that at the moment). Populating each table with test data requires data in many other tables as well. So, creating data individually for each DAO would be very tough and time consuming. So, we really need to create DB test data only once.
I’ve created test data using static block in BaseDAO (extended by each DAO Test Class) – which obviously runs only once. But problem how to clean-up the same when all tests (of all DAO Test subclasses) get completed. An @AfterClass teardown method in base class will run each time after a DAO Test class completes.
Please advise.
A: If you're using Maven, a good option is to use DBUnit. It lets you export test data from the database (or just write it in XML), to be imported for your tests. It has a Maven plugin which will do what you require.
A: In Spring 3:
<jdbc:embedded-database id="dataSource">
<jdbc:script location="classpath:schema.sql"/>
<jdbc:script location="classpath:test-data.sql"/>
</jdbc:embedded-database>
Documentation. To clean up the database after tests, create a Spring bean that will be picked up only during tests:
@Service
public class DbCleanup {
@Resource
private DataSource ds;
@PreDestroy
public cleanUpDb() {
//do your cleanup with DB
}
}
A: I use the following solution.
(1) I have a simple interface called Fixture
package com.obecto.fixtures;
public interface Fixture {
void prepare();
}
(2) I prepare an SQL fixture to populate an empty database - this can be done either through entities or by executing SQL like this:
package com.avaco2.fixtures;
import java.util.logging.Logger;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.test.jdbc.SimpleJdbcTestUtils;
import com.obecto.fixtures.Fixture;
@Component(value="logEventsSQLFixture")
public class LogEventsSQLFixture implements Fixture {
private static String IMPORT_SQL = "import-LogEvents.sql";
private static Logger LOG = Logger.getLogger(LogEventsSQLFixture.class.getName());
@Autowired
private BasicDataSource dataSource;
@Override
public void prepare() {
SimpleJdbcTemplate jdbcTemplate = new SimpleJdbcTemplate(dataSource);
Resource sqlScript = new ClassPathResource(IMPORT_SQL);
try {
SimpleJdbcTestUtils.executeSqlScript(jdbcTemplate, sqlScript, true);
} catch (Exception e) {
LOG.severe("Cannot import " + IMPORT_SQL);
}
}
}
(3) Inject your fixtures into the Test class and prepare-them in the @Before-method.
Always use another database for the tests, so you can safely use the create-drop setting of hibernate. To reload the context before each test method you can use the following annotation - @DirtiesContext(classMode=ClassMode.AFTER_EACH_TEST_METHOD)
A: Nobody suggested annotating with @Transactional attribute for each test. Provided the db engine supports it, that should take care of rolling back the state. See here or stackoverflow link for more on this.
A: Usually I back up entire db instance (actually I'm working with Oracle and imp/exp are great tools). SQL Server and the alikes have replication method. Once you've got your data ready, just export the entire instance and load it before testing.
Once the test is done, drop the DB and recreate. (dumping and loading an entire DB with native programs can be faster than expected )
Regards
PS: if you can, just build up a clone db on a virtual machine then save a snapshot ov the virtual machine (so you can restore it later on).
A: You can also use a DB mockup tool such as Acolyte ( https://github.com/cchantep/acolyte ) in which case you don't need to clean data, being sure which data is available in which JDBC for which test, without altering the JDBC based code you want to test.
Note: I am the author of Acolyte.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565420",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Insert Image to a Document I am new to VC++, I want to know if it is possible to insert an image created by my kinect camera to a RTF doc or MSWord doc using VC++ in a Win32Console Application? Any pointers on how can I achieve my goal? Thanks!
A: Yes, it is possible. I assume that you already have a way to get the image from the camera and save it to a file. RTF (specification) is an utter pig, but the spec will tell you how to add an image. Parsing an existing file to figure out where to add the image though, or creating a new file with the image already present, is an exercise I'll leave to you.
If you have any experience with COM then adding an image to a Word document might prove easier. This MSDN page (link) will help.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565424",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Core Data get sum of values. Fetched properties vs. propagation I'm relatively new to Core Data (coming from an SQLite background). Just finished reading the 'Core Data for iOS' book but I'm left with a number of baffling questions when I started modelling an app which has the following model:
*
*'Accounts' entity which has a to-many 'transactions' relationship and a 'startingBalance' property
*'Transaction' entity which has a to-many 'payments' relationship (and an inverse to Accounts)
*'Payment' entity which contains details of the actual 'amount' paid
For performance reasons I wanted to de-normalize the model and add a 'TotalAmountSpent' property in the 'Accounts' entity (as suggested by the book) so that I could simply keep updating that when something changed.
In practice this seems difficult to achieve with Core Data. I can't figure out how to do this properly (and don't know what the right way is). So my questions are:
a) Should I change the 'TotalAmountSpent' to a Fetched Property instead? Are there performance implications (I know it's loaded lazily but I will almost certainly be fetching that property for every account). If I do, I need to be able to get the total amount spent against the 'startingBalance' for a given period of time (such as the last three days). This seems easy in SQL but how do I do this in Core Data? I read I can use a @sum aggregate function but how do I filter on 'date' using @sum? I also read any change in the data will require refreshing the fetched property. How do I 'listen' for a change? Do I do it in 'Payment' entity's 'willSave' method?
b) Should I use propagation and manually update 'TotalAmountSpent' each time a new payment gets added to a transaction? What would be the best place to do this? Should I do it in an overridden NSManagedObject's 'willSave' method? I'm then afraid it'll be a nightmare to update all corresponding transactions/payments if the 'startingBalance' field was updated on the account. I would then have to load each payment and calculate the total amount spent and the final balance on the account. Scary if there are thousands of payments
Any guidance on the matter would be much appreciated. Thanks!
A: If you use a fetched property you cannot then query on that property easily without loading the data into memory first. Therefore I recommend you keep the actual de-normalized data in the entity instead.
There are actually a few ways to easily keep this up to date.
*
*In your -awakeFromFetch/-awakeFromInsert set up an observer of the relationship that will impact the value. Then when the KVO (Key Value Observer) fires you can do the calculation and update the field. Learning KVC and KVO is a valuable skill.
*You can override -willSave in the NSManagedObject subclass and do the calculation on the save. While this is easier, I do not recommend it since it only fires on a save and there is no guarantee that your account object will be saved.
In either case you can do the calculation very quickly using the KVC Collection Operators. With the collection operators you can do the sum via a call to:
NSNumber *sum = [self valueForKeyPath:@"transactions.@sum.startingBalance"];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565425",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Keybinding on a treeview item, with CommandParameter I'm trying to execute a command located on my ViewModel, using a TreeViewItem with a KeyBinding, and a MenuContext.
Currently, using the context menu, the command is invoked on the correct ViewModel instance.
However, when I select a TreeViewItem and press the "C" key, the command is invoked on the "root" ViewModel.
I tried extending KeyBinding class as well ( Keybinding a RelayCommand ) with no luck.
Maybe I'm going to the wrong path : I just want to display the correct MessageBox, if I use the context menu or the key.
Code sample for a WPF project named WpfTest.
MainWindow.xaml
<Window x:Class="WpfTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:WpfTest"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TreeView ItemsSource="{Binding}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Child}" DataType="{x:Type vm:ViewModel}">
<TextBlock Text="{Binding Name}" />
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu>
<MenuItem Header="{Binding Name}" Command="{Binding SomeCommand}" CommandParameter="{Binding}"/>
</ContextMenu>
</Setter.Value>
</Setter>
<Setter Property="vm:MyAttached.InputBindings">
<Setter.Value>
<InputBindingCollection>
<KeyBinding Key="C" Command="{Binding SomeCommand}" CommandParameter="{Binding}"/>
</InputBindingCollection>
</Setter.Value>
</Setter>
</Style>
</TreeView.ItemContainerStyle>
</TreeView>
</Grid>
</Window>
MainWindow.xaml.cs:
namespace WpfTest
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Input;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new List<ViewModel>
{
new ViewModel
{
Name = "Parent",
Child = new ObservableCollection<ViewModel>
{
new ViewModel { Name = "Child 1" },
new ViewModel { Name = "Child 2" },
new ViewModel { Name = "Child 3" }
}
}
};
}
}
public class ViewModel
{
public string Name { get; set; }
public ObservableCollection<ViewModel> Child { get; set; }
public ICommand SomeCommand { get; set; }
public ViewModel()
{
this.SomeCommand = new RelayCommand<ViewModel>(OnCommandExecuted);
}
private void OnCommandExecuted(ViewModel parameter)
{
MessageBox.Show("CommandExecuted on " + Name + " with parameter " + parameter.Name);
}
}
public class MyAttached
{
public static readonly DependencyProperty InputBindingsProperty =
DependencyProperty.RegisterAttached("InputBindings", typeof(InputBindingCollection), typeof(MyAttached),
new FrameworkPropertyMetadata(new InputBindingCollection(),
(sender, e) =>
{
var element = sender as UIElement;
if (element == null) return;
element.InputBindings.Clear();
element.InputBindings.AddRange((InputBindingCollection)e.NewValue);
}));
public static InputBindingCollection GetInputBindings(UIElement element)
{
return (InputBindingCollection)element.GetValue(InputBindingsProperty);
}
public static void SetInputBindings(UIElement element, InputBindingCollection inputBindings)
{
element.SetValue(InputBindingsProperty, inputBindings);
}
}
public class RelayCommand<T> : ICommand
{
readonly Action<T> _execute = null;
public RelayCommand(Action<T> execute) { _execute = execute; }
public bool CanExecute(object parameter) { return true; }
public void Execute(object parameter) { _execute((T)parameter); }
public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } }
}
}
A: Here is the problem: The Style only creates one InputBindingCollection for all ListViewItems, you have to be very careful with Setter.Values for that reason.
And here is the fix:
<TreeView ItemsSource="{Binding}">
<TreeView.Resources>
<!-- x:Shared="False" forces the new creation of that object whenever referenced -->
<InputBindingCollection x:Shared="False" x:Key="InputBindings">
<KeyBinding Key="C" Command="{Binding SomeCommand}" CommandParameter="{Binding}" />
</InputBindingCollection>
</TreeView.Resources>
<!-- ... -->
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<!-- ... -->
<Setter Property="vm:MyAttached.InputBindings" Value="{StaticResource InputBindings}"/>
</Style>
</TreeView.ItemContainerStyle>
</TreeView>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565428",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Warning: This page calls for XML namespace http://primefaces.prime.com.tr/ui declared with prefix p but no taglibrary exists for that namespace I'm trying to start with Primefaces 2.2.1, but I can't. I have the following definition in pom.xml:
<repository>
<id>prime-repo</id>
<name>PrimeFaces Maven Repository</name>
<url>http://repository.primefaces.org</url>
<layout>default</layout>
</repository>
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>2.2.1</version>
</dependency>
But I recevie the following error message:
Warning: This page calls for XML namespace http://primefaces.prime.com.tr/ui declared with prefix p but no taglibrary exists for that namespace.
with this simple code:
<?xml version='1.0' encoding='UTF-8' ?>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.prime.com.tr/ui">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
Hello from Facelets
<p:editor />
</h:body>
</html>
A: Include the tag lib as :
xmlns:p="http://primefaces.org/ui"
And the dependency in pom.xml as :
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>3.0.M4</version>
</dependency>
I was also facing the same issue. This solution fixed my problem.
A: You should have the <repository> between <repositories> :
Try this:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.test</groupId>
<artifactId>jsf_primefaces</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>jsf_primefaces</name>
<description>JSF PrimeFaces</description>
<packaging>war</packaging>
<repositories>
<repository>
<id>prime-repo</id>
<name>PrimeFaces Maven Repository</name>
<url>http://repository.primefaces.org</url>
<layout>default</layout>
</repository>
</repositories>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>2.2.1</version>
</dependency>
......other dependencies.........
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>el-api</artifactId>
<version>2.2</version>
</dependency>
......other dependencies.........
</dependencies>
</project>
A: Their servers must be down right now because I cannot navigate to their forums either.
They are located in Turkey, I believe so they usually go down for nightly maintenance about this time.
A: If you have been using Eclipse's Export WAR function, you need to explicitly add the dependency into the WAR assembly.
Your answer is here: Eclipse exporting JAR in WAR
A: For me, this was the solution, change the old tag and instead use the following:
xmlns:p="http://primefaces.org/ui"
A: Try use xmlns:p="http://primefaces.org/ui"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565431",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Android in accessing value of a string I am working on android. i want to access the file from server. if i write my url in this way:
URL sourceUrl = new URL("http://192.168.1.214/MusicApplication/searchsongxml.php?");
then it works correctly.
But if i declare the server name in strings.xml as follows:
<resources>
<string name="SERVER_NAME">http://192.168.1.214/</string>
</resources>
and try to access the url like this:
URL sourceUrl = new (getString(R.string.SERVER_NAME)+"MusicApplication/searchsongxml.php");
then this create an exception and my application halts.
Please tell me what mistake i have done.
A: try this
URL sourceUrl = new URL(your_context.getString(R.string.SERVER_NAME)+"MusicApplication/searchsongxml.php");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565435",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: OOP concepts in Python Can any one suggest any links where Python object oriented concepts are clearly explained with example..
Data Abstraction
Encapsulation
Class
Object
Datahiding
Inheritance
Polymorphism
A: Here is a good starting point: Introduction to OOP with Python.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565439",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MySQL select rows where values in one field match values in another table I have the following tables:
*
*tbljobpost with fields job_id int, job_title varchar(50), skill_cat_id varchar(50)
*tblappskills with fields app_control Int, skill_cat_id Varchar(50)
tbljobpost:
+-------------------------------------+
| job_id | job_title | skill_cat_id |
+-------------------------------------+
| 1 | Programmer | 1,2,3,4,5,6,7 |
+-------------------------------------+
tblappskills:
+-----------------------------+
| app_control | skill_cat_id |
+-----------------------------+
| 1 | 1,2,4,5,6 |
| 2 | 1,2,3,7,4 |
| 3 | 1,2,3,4,5,6,7 |
| 4 | 7,1,4,5,6,2,3 |
+-----------------------------+
How can I query or filter the tblappskills that is the same skill_cat_id separated with comma from tbljobpost?
And the result will come like this:
+-----------------------------+
| app_control | skill_cat_id |
+-----------------------------+
| 3 | 1,2,3,4,5,6,7 |
| 4 | 7,1,4,5,6,2,3 |
+-----------------------------+
A: Your solution does not fit first normal form
You should store skill categories in separate cells like this:
+----------------------------+
| app_control | skill_cat_id |
+----------------------------+
| 1 | 1 |
| 1 | 2 |
| 2 | 1 |
| 4 | 4 |
+----------------------------+
Then, you can easily JOIN the tables and select the rows matching the value you want. It does not matter that app-control-id appears more than once in the table. However, if you decide to put additional data to that table, you should do it in separate table to avoid redundancy, like this:
Your new table (contains detail information about app-control) is related to the table I have mentioned above as 1 : (0..N). It's hard to explain but easy to design. If you study the normal forms mentioned above, you will understand this easily.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565442",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: User Management in ASP.Net MVC 3 i have a project using ASP.Net MVC 3, and now i want to make user management.
i want to make it like this one : http://mrgsp.md:8080/awesome/user
how to make that user management ?
thanks a lot
A: I created a Model which references the MembershipUser but also allows for creating and editing users.
namespace MyProject.Models
{
public class AccountUser
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
public virtual Guid UserId { get; set; }
[Display(Name="User Name")]
public virtual string UserName { get; set; }
[Display(Name = "E-mail")]
public virtual string Email { get; set; }
public virtual string Password { get; set; }
[Display(Name = "Approved")]
public virtual bool IsApproved { get; set; }
/* contructors based on string GUID or actual */
public AccountUser() { }
public AccountUser(string UID)
{
UserId = new Guid(UID);
Initialize();
}
public AccountUser(Guid UID)
{
UserId = UID;
Initialize();
}
/* loads Membership User into model to access other properties */
public virtual MembershipUser User
{
get
{
// note that I don't have a test for null in here,
// but should in a real case.
return Membership.GetUser(UserId);
}
}
/* do this once when opening a user instead of every time you access one of these three *
* as well as allow override when editing / creating */
private void Initialize()
{
UserName = User.UserName;
Email = User.Email;
IsApproved = User.IsApproved;
}
}
}
With this built, I created a Controller with my default data Context to allow it to create scaffolding for me. Then I removed the Context from the Controller.
namespace MyProject.Controllers
{
[Authorize]
public class AccountUserController : Controller
{
public ViewResult Index()
{
var memberList = Membership.GetAllUsers();
var model = new List<AccountUser>();
foreach (MembershipUser user in memberList)
{
model.Add(new AccountUser(user.ProviderUserKey.ToString()));
}
return View(model);
}
public ViewResult Details(Guid id)
{
AccountUser accountuser = new AccountUser(id);
return View(accountuser);
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(AccountUser myUser)
{
if (ModelState.IsValid)
{
Membership.CreateUser(myUser.UserName, myUser.Password, myUser.Email);
return RedirectToAction("Index");
}
return View(myUser);
}
public ActionResult Edit(Guid id)
{
AccountUser accountuser = new AccountUser(id);
return View(accountuser);
}
[HttpPost]
public ActionResult Edit(AccountUser accountuser)
{
if (ModelState.IsValid)
{
return RedirectToAction("Index");
}
return View(accountuser);
}
public ActionResult Delete(Guid id)
{
AccountUser accountuser = new AccountUser(id);
return View(accountuser);
}
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(Guid id)
{
AccountUser accountuser = new AccountUser(id);
Membership.DeleteUser(accountuser.User.UserName);
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
//db.Dispose();
base.Dispose(disposing);
}
}
}
The Views should all be pretty straight forward, but here's one for consistency
@model MyProject.Models.AccountUser
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>AccountUser</legend>
<div class="editor-label">
@Html.LabelFor(model => model.UserName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.UserName)
@Html.ValidationMessageFor(model => model.UserName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Password)
</div>
<div class="editor-field">
@Html.PasswordFor(model => model.Password)
@Html.ValidationMessageFor(model => model.Password)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
It was definitely a little tricky overall, mostly with getting the Model correct to allow you to read in from Membership as well as get a reasonable set of Views created. I actually did most of them by hand, but this will save you some time. Note that I omitted editing Password or Roles, but if you get this far, you shouldn't be too far off.
The following links were helpful:
*
*Alternative User management in ASP.NET MVC
*http://joymonscode.blogspot.com/2012/01/creating-simple-aspnet-mvc-3-razor.html
A: Create a new project mvc3 and download the awesome project from the Package Manager:
PM> Install-Package MvcProjectAwesome
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565444",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Change Vagrant port forwarding on a running system I have a Vagrant system up and running and I want to apply a change to it which is as little as changing one of the forwarding rules.
From this page:
Forwarded ports are applied during vagrant up like any other
configuration. But if you already have a running system, calling
vagrant reload will apply them without re-importing and re-building
everything.
Note that forwarding ports requires a virtual machine restart since
VirtualBox won’t pick up on the forwarded ports until it is completely
restarted.
Sounds exactly like what I want! But if I try a vagrant reload all of my Chef recipes are reloaded and since the full process takes about half an hour, I have to go to the kitchen and grab the nth cup of coffee.
Is there any way to apply Vagrantfile changes on a running system without going trough the whole provisioning process? I cannot drink so much coffee.
A: Have you tried using the VirtualBox user interface to add the new port forwarding rule manually? Open VirtualBox and select the running VM, then hit Settings->Network->Port Forwarding and add the new rule to, for example, forward 127.0.0.1:2223 to 10.0.2.15:22. After doing this I was able to connect to my VM on ports 2222 (as per usual) and 2223 (the new rule).
Naturally, you would add this new rule to your Vagrantfile at the same time to ensure that the mapping becomes permanent after the eventual restart.
Also, if your VM provisioning takes so long, have you considered moving some of the chef/puppet steps into the actual base box? For example, perhaps you are installing a bunch of server software that takes a while to install. Repackaging the box with this software already installed could dramatically reduce your Vagrant startup time.
Hope this helps!
A: you can do
vagrant reload --no-provision
and it should run without chef, puppet, etc.
although it will still reboot the vm- feels like "But if you have an already running system..." is maybe a bit misleading.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565446",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "33"
}
|
Q: Soccer query - How to extract these data? I have a Soccer website, and I have a calendar of the match organized in this MySql table (called calendario) :
TEAM1 TEAM2 V1 V2 DAY ID_SEASON
team1 | team2 | 3 | 1 | day1 | 1
team3 | team4 | 1 | 2 | day1 | 1
team1 | team4 | 0 | 0 | day2 | 1
team3 | team2 | 4 | 2 | day2 | 1
team1 | team3 | 2 | 3 | day3 | 1
team4 | team2 | 0 | 1 | day3 | 1
team1 | team2 | 3 | 1 | day1 | 2
team3 | team4 | 1 | 2 | day1 | 2
team1 | team4 | 0 | 0 | day2 | 2
team3 | team2 | 4 | 2 | day2 | 2
team1 | team3 | 2 | 3 | day3 | 2
team4 | team2 | 0 | 1 | day3 | 2
and I extract my result with this (long) query :
select
squadra,
sum(punteggio) as punti,
sum(if(fatti!='-' and fatti != 's',1,0)) as gioc,
sum(if(punteggio=3,1,0)) as vt,
sum(if(punteggio=1,1,0)) as nt,
sum(if(punteggio=0 and fatti != '-' and fatti != 's' ,1,0)) as pt,
sum(if(punteggio=3 and dove = 'C',1,0)) as vc,
sum(if(punteggio=1 and dove = 'C',1,0)) as nc,
sum(if(punteggio=0 and dove = 'C' and fatti != '-' and fatti != 's',1,0)) as pc,
sum(if(punteggio=3 and dove = 'T',1,0)) as vf,
sum(if(punteggio=1 and dove = 'T',1,0)) as nf,
sum(if(punteggio=0 and dove = 'T' and fatti != '-' and fatti != 's',1,0)) as pf,
abs(sum(fatti)) as gtf,
abs(sum(subiti)) as gts,
sum(if(dove='C',fatti,0)) as gfc,
sum(if(dove='C',subiti,0)) as gsc,
sum(if(dove='T',fatti,0)) as gff,
sum(if(dove='T',subiti,0)) as gsf,
(sum(if(punteggio=1 and dove = 'C',1,0)) * -2) +
(sum(if(punteggio=0 and dove = 'C' and fatti != '-' and fatti != 's',1,0)) * -3) +
(sum(if(punteggio=3 and dove = 'T',1,0)) * 2) -
(sum(if(punteggio=0 and dove = 'T' and fatti != '-' and fatti != 's',1,0))) as mi
from (
select team1 as squadra, v1 as fatti, v2 as subiti,'C' as dove,
case
when v1 > v2 then 3
when v1 = v2 and v1 <> '-' and v1 <> 's' then 1
else 0
end as punteggio
from calendario
union all
select team2 as squadra, v2 as fatti,v1 as subiti,'T',
case
when v2 > v1 then 3
when v2 = v1 and v2 <> '-' and v2 <> 's' then 1
else 0
end as punteggio
from calendario
) as tab
group by squadra
order by punti desc
unfortunatly, this extract ALL result from that table.
In fact I need to extract only results of the season 2 (ID_SEASON=2).
How can I do it?
A: Try with:
select
squadra,
sum(punteggio) as punti,
sum(if(fatti!='-' and fatti != 's',1,0)) as gioc,
sum(if(punteggio=3,1,0)) as vt,
sum(if(punteggio=1,1,0)) as nt,
sum(if(punteggio=0 and fatti != '-' and fatti != 's' ,1,0)) as pt,
sum(if(punteggio=3 and dove = 'C',1,0)) as vc,
sum(if(punteggio=1 and dove = 'C',1,0)) as nc,
sum(if(punteggio=0 and dove = 'C' and fatti != '-' and fatti != 's',1,0)) as pc,
sum(if(punteggio=3 and dove = 'T',1,0)) as vf,
sum(if(punteggio=1 and dove = 'T',1,0)) as nf,
sum(if(punteggio=0 and dove = 'T' and fatti != '-' and fatti != 's',1,0)) as pf,
abs(sum(fatti)) as gtf,
abs(sum(subiti)) as gts,
sum(if(dove='C',fatti,0)) as gfc,
sum(if(dove='C',subiti,0)) as gsc,
sum(if(dove='T',fatti,0)) as gff,
sum(if(dove='T',subiti,0)) as gsf,
(sum(if(punteggio=1 and dove = 'C',1,0)) * -2) +
(sum(if(punteggio=0 and dove = 'C' and fatti != '-' and fatti != 's',1,0)) * -3) +
(sum(if(punteggio=3 and dove = 'T',1,0)) * 2) -
(sum(if(punteggio=0 and dove = 'T' and fatti != '-' and fatti != 's',1,0))) as mi
from (
( select team1 as squadra, v1 as fatti, v2 as subiti,'C' as dove,
case
when v1 > v2 then 3
when v1 = v2 and v1 <> '-' and v1 <> 's' then 1
else 0
end as punteggio
from calendario WHERE ID_SEASON = 2 )
union all
( select team2 as squadra, v2 as fatti,v1 as subiti,'T',
case
when v2 > v1 then 3
when v2 = v1 and v2 <> '-' and v2 <> 's' then 1
else 0
end as punteggio
from calendario
WHERE ID_SEASON = 2 )
) as tab
group by squadra
order by punti desc
A: My request:
select
squadra,
sum(punteggio) as punti,
sum(if(fatti!='-' and fatti != 's',1,0)) as gioc,
sum(if(punteggio=3,1,0)) as vt,
sum(if(punteggio=1,1,0)) as nt,
sum(if(punteggio=0 and fatti != '-' and fatti != 's' ,1,0)) as pt,
sum(if(punteggio=3 and dove = 'C',1,0)) as vc,
sum(if(punteggio=1 and dove = 'C',1,0)) as nc,
sum(if(punteggio=0 and dove = 'C' and fatti != '-' and fatti != 's',1,0)) as pc,
sum(if(punteggio=3 and dove = 'T',1,0)) as vf,
sum(if(punteggio=1 and dove = 'T',1,0)) as nf,
sum(if(punteggio=0 and dove = 'T' and fatti != '-' and fatti != 's',1,0)) as pf,
abs(sum(fatti)) as gtf,
abs(sum(subiti)) as gts,
sum(if(dove='C',fatti,0)) as gfc,
sum(if(dove='C',subiti,0)) as gsc,
sum(if(dove='T',fatti,0)) as gff,
sum(if(dove='T',subiti,0)) as gsf,
(sum(if(punteggio=1 and dove = 'C',1,0)) * -2) +
(sum(if(punteggio=0 and dove = 'C' and fatti != '-' and fatti != 's',1,0)) * -3) +
(sum(if(punteggio=3 and dove = 'T',1,0)) * 2) -
(sum(if(punteggio=0 and dove = 'T' and fatti != '-' and fatti != 's',1,0))) as mi
from (
select team1 as squadra, v1 as fatti, v2 as subiti,'C' as dove, ID_SEASON,
case
when v1 > v2 then 3
when v1 = v2 and v1 <> '-' and v1 <> 's' then 1
else 0
end as punteggio
from calendario
union all
select team2 as squadra, v2 as fatti,v1 as subiti,'T' as dove, ID_SEASON,
case
when v2 > v1 then 3
when v2 = v1 and v2 <> '-' and v2 <> 's' then 1
else 0
end as punteggio
from calendario
) as tab
where ID_SEASON = 2
group by squadra
order by punti desc
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565450",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Reload tab in android I have tabhost in my application(2 tabs),when i select tab2 the content has been dislayed has a list view ,again i have list click event here to move further another list view,here the 2tab already in selected mode and it's focus not been changed,when i click the 2tab again i need it to reload its content has loaded initially with first list view content.how can i get it.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TabHost tabHost = getTabHost();
tabHost.addTab(tabHost.newTabSpec("tab1")
.setIndicator("OPT")
.setContent(new Intent(this, TabGroup1Activity.class)));
tabHost.addTab(tabHost.newTabSpec("tab2")
.setIndicator("EDIT")
.setContent(new Intent(this, TabGroup2Activity.class)));
tabHost.setCurrentTab(1);
}
A: You could also re-issue another intent to refresh the tab
A: try public void onResume() {} method
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565455",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android Table Row Image dimension I want to put one image on the beginning of each row in my application . The problem is, the image is too big and when I put it there, it occupies the whole screen.
main.xml :
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:scrollbars="vertical"
>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:id="@+id/tableView"
android:layout_height="fill_parent"
android:layout_weight=".90"
android:stretchColumns="1"
></TableLayout>
</ScrollView>
This is how I add the image :
TableLayout tableView = (TableLayout) findViewById(R.id.tableView);
TableRow row = new TableRow(this);
ImageView im;
im = new ImageView(this);
im.setImageResource(R.drawable.rss);
row.addView(im);
tableView.addView(row, new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
I add the rows dynamically so, I want to add the image the same way.
PS: There is no change if I replace
TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
with
TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
I would like to make the image much smaller. Could you help me out?
A: add the imageview this way..
im.setScaleType(ImageView.ScaleType.CENTER_CROP );
row.addView(im, new TableRow.LayoutParams(width, height));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565456",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to display hours between two dates in mysql Two datefield
<input type="text" name="from date" >
<input type="text" name="to date" >
Example : If fromdate is 2011-09-12 and todate is 2011-09-15
ouput should display :
display every hour
2011-09-12 00:00:00
2011-09-12 01:00:00
2011-09-12 02:00:00
2011-09-12 03:00:00
2011-09-12 04:00:00
.
.
.
.
.
2011-09-15 23:00:00
it is possible in mysql code or php
A: Try this:
<?php
$from_date_time = strtotime($_POST['from_date']);
$to_date_time = strtotime($_POST['to_date']);
while ($from_date_time < $to_date_time) {
echo date('Y-m-d H:i:s', $from_date_time);
$from_date_time += 3600;
}
A: hello in MS SQL server 2005 you can do this by the following code of using CTE..
declare @dateh table(ind int identity(1,1),date1 smalldatetime,date2 smalldatetime)
insert into @dateh select '1/1/2011','1/2/2011'
select * from @dateh
;with T as
(
select date1,date2 from @dateh as d
union all
select dateadd(hh,1,date1),date2 From T
where dateadd(hh,1,date1)<= date2
)
Select date1 from T
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565463",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Display value in a loop I am using Spring MVC 3. From my controller I set value
mav = new ModelAndView();
mav.setViewName("reports");
mav.addObject("ReportList", ReportList);
return mav;
In JSP
<c:forEach var="list" items="${ReportList}">
$(list.name)
</c:forEach>
ReportList has a size of 7. ReportList is a list of Report class having name as instance with proper getters and setters.
When I run it in browser it displays $(list.name) 7 times.
Its not displaying proper names.
A: These brackets: { }
<c:forEach var="list" items="${ReportList}">
${list.name}
</c:forEach>
A: It should be ${list.name} ...
A: You should use the <c:out> tag to render the value of the name attribute. #{list.name} might work as well (replace ( with {).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565469",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Appying Background Color to entire line of Text I have a RichTextBox in a WPF Application. I would like to apply alternate coloring to each lines of texts. I have set the Background property to be of the desired color, but due to differences in text length, only the portion containing text gets the background color. How to set properties so that the entire line is set to the desired background color.
One non-elegant solution is to, pad some spaces, but if RichTextBox layout changes, then the code needs to be changed by trial and error basis.
Any better approach?
A: If all the lines are the same height, then you can apply a background graphic to the RichTextBox itself, which would have the same effect (set dimensions / colours as appropriate):
<RichTexBox>
<RichTexBox.Background>
<VisualBrush TileMode="Tile" Viewport="0 0 100 100" ViewportUnits="Absolute">
<VisualBrush.Visual>
<StackPanel>
<Rectangle Width="100" Height="50" Fill="Red" />
<Rectangle Width="100" Height="50" Fill="Blue" />
</StackPanel>
</VisualBrush.Visual>
</VisualBrush>
</RichTexBox.Background>
</RichTexBox>
A: Try to use List which highlights the rows of lines with a background color. Refresh the ListItem collection (according to the number of lines in the text) when anyone changes Text in RichTextBox.TextChanged event.
<RichTextBox>
<RichTextBox.Document>
<FlowDocument>
<List>
<ListItem Background="Red" />
<ListItem Background="Green"/>
<ListItem Background="Yellow"/>
</List>
</FlowDocument>
</RichTextBox.Document>
</RichTextBox>
I think you can change the bulleted look n feel of the list by overriding its style.
A: I wanted to know how to make this work with Items generated dynamically. For my actual case, I used extra spaces. For now, this is the way for me to go.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565471",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: get current lat long without GPS in blackberry storm 2 i m working with the application which are needed to get current lat long of user .
in our area GPS is not working so how to get lat long without gps system
A: You can send your wifi and/or cellid info to google (or to RIM's own service but that is still alpha quality) and it will tell you your lat-long, see method here:
Cell triangulation on BlackBerry
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565474",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Disposing Custom Class : Setting NULL VS .Dispose
Possible Duplicate:
Calling null on a class vs Dispose()
Just want some information regarding Disposing an Object.
I have create a Employee Class which i inherit from IDISPOSIBLE Interface. Below is the sample Code
public class Employee : IDisposable
{
private Int32 _RunID;
public Int32 RunID { get { return _RunID; } set { _RunID = value; } }
public void Dispose()
{
//Dispose(true);
}
}
Now my Question is, it a Good Coding Practice to Dispose every class we create and implementing/Inheriting it with IDisposible Interface even i have seen many other people code they directly set ObjEmployee = null; so just got confused which is good setting NULL or Implementing it With IDisposible Interface or None Of the Above ?
A: It depends, do you have managed resources (File handles, sockets, connections, etc....) that need to be gotten rid of along with your object? If yes then you need a Dispose() if your class contains basic types or just information you do not need to dispose and setting to null will give a hint to the GC to clear that memory.
A: When you set ObjEmployee = null, you only mark the object instance to be ready for the Garbage Collector, but you have no influence over when the actual clean-up would take place, and it may take a while. When you use the Dispose() method, the GC runs immediately and frees the memory the object was using.
A: The fundamental question, in deciding whether a class should implement IDisposable, is whether instances of that class have taken on the responsibility of seeing that other entities get cleaned up; typically those other entities will be altering their behavior on behalf of the IDisposable object and at the expense of other entities, and the IDisposable object is responsible for letting them know when they no longer need to do so.
For example, if any code, anywhere, uses the C function fopen() to open for read-write access a file which is located on a server, the server will alter its behavior by forbidding anyone else from accessing the file until it receives word that the program that opened it has no more need of it. When the program no longer needs exclusive use of the file, it can call fclose() which will in turn cause the server to be notified that the file should again be available to other applications.
If a method in a C# class calls a routine which calls fopen(), and that routine returns after putting the FILE* in a place the C# program knows about but nothing else does, that method takes on a responsibility for seeing that fclose() must somehow get called with that FILE*. The file needs to be fclosed(), and nothing else in the system has the information or impetus necessary to do so, so the responsiblity falls to that C# class.
If the C# method were to return without storing the FILE* anywhere, the file would never get closed, and nobody else, anywhere in the universe, would be able to use it unless or until the application exits. If the C# method has to exit without yielding exclusive use of the file, it must store the FILE* in a way that will ensure that someone, somewhere, will clean it up after exclusive use is no longer required. The normal pattern would be for the method to store the FILE* in a class field, and for class containing the method to implement IDisposable by copying and blanking that field, seeing if it was non-blank, and if it was non-blank, calling fclose() the stored FILE*.
The important thing to realize is that when an object is destroyed by the garbage collector, the system won't care what's in any of the object fields. It won't even look at them. What matters is whether the object has any unfulfilled responsibilities for ensuring that outside entities, which may not even be on the same machine, are informed when their services are no longer needed.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565481",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Minimisation problem in Python, fmin_bfgs won't work but fmin will, 'Matrices not aligned' I have a function in python which takes a vector and returns a real number. I am using the scipy.optimize fmin and fmin_bfgs functions to find the argument which gives the function its approx minimum value. However, when I use fmin I get an alright answer (quite slowly) but when I switch to fmin_bfgs, I get an error saying "Matrices are not aligned". Here's my function:
def norm(b_):
b_ = b_.reshape(int(M),1) #M already given elsewhere
Yb = np.dot(Y,b_) #Y already given elsewhere
B = np.zeros((int(M),int(M)))
for j in xrange(int(M)):
B[j][j] = -t[j+1]*np.exp(-t[j+1]*Yb[j]) #The t[j] are already known
P = np.zeros((int(M),1))
for j in xrange(int(M)):
P[j][0] = np.exp(-t[j+1]*Yb[j])
diff = np.zeros((int(M),1)) #Functions d(i,b) are known
for i in xrange(1,int(M)-1):
diff[i][0] = d(i+1,b_) - d(i,b_)
diff[0][0] = d(1,b_)
diff[int(M)-1][0] = -d(int(M)-1,b_)
term1_ = (1.0/N)*(np.dot((V - np.dot(c,P)).transpose(),W))
term2_ = np.dot(W,V - np.dot(c,P)) #V,c,P,W already known
term1_ = np.dot(term1_,term2_)
term2_ = lambd*np.dot(Yb.transpose(),diff)
return term1_ + term2_
Here's how I call fmin_bfgs:
fmin_bfgs(norm, b_guess,fprime=None,
args=(),gtol=0.0001,norm=0.00000000001,
epsilon=1.4901161193847656e-08,maxiter=None,
full_output=0, disp=1, retall=0, callback=None)
When I call fmin it works fine, just too slowly to be useful (I need to optimise several times). But when I try fmin_bfgs I get this error:
Traceback (most recent call last):
File "C:\Program Files\Wing IDE 101 4.0\src\debug\tserver_sandbox.py", line 287, in module
File "C:\Python27\Lib\site-packages\scipy\optimize\optimize.py", line 491, in fmin_bfgs old_fval,old_old_fval)
File "C:\Python27\Lib\site-packages\scipy\optimize\linesearch.py", line 239, in line_search_wolfe2 derphi0, c1, c2, amax)
File "C:\Python27\Lib\site-packages\scipy\optimize\linesearch.py", line 339, in scalar_search_wolfe2 phi0, derphi0, c1, c2)
File "C:\Python27\Lib\site-packages\scipy\optimize\linesearch.py", line 471, in _zoom derphi_aj = derphi(a_j)
File "C:\Python27\Lib\site-packages\scipy\optimize\linesearch.py", line 233, in derphi return np.dot(gval[0], pk)
ValueError: matrices are not aligned
Any ideas why this might happen? All the matrices I have supplied the function are aligned correctly (and the function works since fmin worked). Help much appreciated!
A: It seems that one of the programs just ended up dealing with numbers that were too large for it to handle. Shame it couldn't tell me it was doing that properly. I worked around it though, so no more problem. Sorry if this wasted your time.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565482",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why does this SQL query take 8 hours to finish? There is a simple SQL JOIN statement below:
SELECT
REC.[BarCode]
,REC.[PASSEDPROCESS]
,REC.[PASSEDNODE]
,REC.[ENABLE]
,REC.[ScanTime]
,REC.[ID]
,REC.[Se_Scanner]
,REC.[UserCode]
,REC.[aufnr]
,REC.[dispatcher]
,REC.[matnr]
,REC.[unitcount]
,REC.[maktx]
,REC.[color]
,REC.[machinecode]
,P.PR_NAME
,N.NO_NAME
,I.[inventoryID]
,I.[status]
FROM tbBCScanRec as REC
left join TB_R_INVENTORY_BARCODE as R
ON REC.[BarCode] = R.[barcode]
AND REC.[PASSEDPROCESS] = R.[process]
AND REC.[PASSEDNODE] = R.[node]
left join TB_INVENTORY as I
ON R.[inventid] = I.[id]
INNER JOIN TB_NODE as N
ON N.NO_ID = REC.PASSEDNODE
INNER JOIN TB_PROCESS as P
ON P.PR_CODE = REC.PASSEDPROCESS
The table tbBCScanRec has 556553 records while the table TB_R_INVENTORY_BARCODE has 260513 reccords and the table TB_INVENTORY has 7688. However, the last two tables (TB_NODE and TB_PROCESS) both have fewer than 30 records.
Incredibly, when it runs in SQL Server 2005, it takes 8 hours to return the result set.
Why does it take so much time to execute?
If the two inner joins are removed, it takes just ten seconds to finish running.
What is the matter?
There are at least two UNIQUE NONCLUSTERED INDEXes.
One is IX_INVENTORY_BARCODE_PROCESS_NODE on the table TB_R_INVENTORY_BARCODE, which covers four columns (inventid, barcode, process, and node).
The other is IX_BARCODE_PROCESS_NODE on the table tbBCScanRec, which covers three columns (BarCode, PASSEDPROCESS, and PASSEDNODE).
A: Well, standard answer to questions like this:
*
*Make sure you have all the necessary indexes in place, i.e. indexes on N.NO_ID, REC.PASSEDNODE, P.PR_CODE, REC.PASSEDPROCESS
*Make sure that the types of the columns you join on are the same, so that no implicit conversion is necessary.
A: You are working with around (556553 *30 *30) 500 millions of rows.
You probably have to add indexes on your tables.
If you are using SQL server, you can watch the plan query to see where you are losing time.
See the documentation here : http://msdn.microsoft.com/en-us/library/ms190623(v=sql.90).aspx
The query plan will help you to create indexes.
A: When you check the indexing, there should be clustered indexes as well - the nonclustered indexes use the clustered index, so not having one would render the nonclustered useless. Out-dated statistics could also be a problem.
However, why do you need to fetch ALL of the data? What is the purpose of that? You should have WHERE clauses restricting the result set to only what you need.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565484",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Ignoring Aspectj during junit tests Here is situation:
*
*We have class with defined aspect to it's methodA;
*We have JUnit test for this methodA;
When I run JUnit test it activates Aspect as well. Any thoughts how to ignore Aspects during unit tests?
I have separated tests for my Aspects and it works fine. So in my unit test I want to test only methodA without any attached aspects.
I use spring 3.0 and its aspectj support.
Thanks in advance.
Regards,
Max
A: You can disable the compile-time weaving that I assume your IDE is doing and use load-time weaving in your separated AspectJ tests.
To enable load-time weaving you have to provide a javaagent as an JVM parameter.
An example:
-javaagent:lib/spring-dependencies/spring-agent.jar
Other changes when you move from compile-time to load-time weaving
You must also provide an aop.xml file in the META-INF folder on the claspath.
For my trace example, it looks like this:
<!DOCTYPE aspectj PUBLIC
"-//AspectJ//DTD//EN" "http://www.eclipse.org/aspectj/dtd/aspectj.dtd">
<aspectj>
<weaver>
<!-- only weave classes in this package -->
<include within="aspects.trace.demo.*" />
</weaver>
<aspects>
<!-- use only this aspect for weaving -->
<aspect name="aspects.trace.TraceAspect" />
</aspects>
</aspectj>
In this configuration you can see that the TraceAspect class will be weaved with all the classes in the demo package.
Spring configuration with load-time weaving
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="traceAspect" class="aspects.trace.TraceAspect"
factory-method="aspectOf"/>
<context:load-time-weaver />
</beans>
The configuration file is almost the same as the compile-time configuration file, except it also contains a load-time weaver element.
I hope this helps!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565490",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Unable to create table in MySQL using Doctrine and Symfony2 I am working with Symfony2 and Doctrine ORM using MySql .
After creating an Entity, I am not able to create the table. It throws an exception.
anu@anu-bridge:/var/www/Symfony$ php app/console doctrine:schema:update --force --dump-sql
[Doctrine\DBAL\Schema\SchemaException]
The table with name 'product' already exists.
doctrine:schema:update [--complete] [--dump-sql] [--force] [--em[="..."]]
I tried to drop it , but still it throws the error.
anu@anu-bridge:/var/www/Symfony$ php app/console doctrine:schema:drop --force
Dropping database schema...
[Doctrine\DBAL\Schema\SchemaException]
The table with name 'product' already exists.
doctrine:schema:drop [--dump-sql] [--force] [--full-database] [--em[="..."]]
[Doctrine\DBAL\Schema\SchemaException]
The table with name 'product' already exists.
There is no tables in the database. Cleared all the cache for symfony and doctrine, but still the error is throwing.
Symfony2 version is 2.0.1 .
A: I've had a similar problem. Most likely you have two entities named Category inside different Bundles. For instance:
src/Acme/SomeBundle/Entity/Product.php
src/Acme/OtherBundle/Entity/Product.php
Comment one of these files and retry the console command.
A: I got this error when editing my Product.orm.yml file.
I added a new manyToMany relation with a Category entity, and made a mistake on the joinTable line :
manyToMany:
categories:
targetEntity: Acme\ProductBundle\Entity\Category
inversedBy: products
joinTable:
name: Product # My mistake: joinTable should be something like ProductCategory
[...]
Indeed it's a silly error, I share anyway.
A: I was getting this problem from a conflict with join table defined in an association class annotation and a join table defined in a ManyToMany annotation.
The mapping definitions in two entities with a direct ManytoMany relationship appeared to result in the automatic creation of the join table using the 'joinTable' annotation. However the join table was already defined by an annotation in its underlying entity class and I wanted it to use this association entity class's own field definitions so as to extend the join table with additional custom fields.
The explanation and solution was thanks to this post in the forum 'Doctrine Annotation Question'. This post draws attention to the Doctrine documentation regarding ManyToMany Uni-directional relationships. Look at the note regarding the approach of using an 'association entity class' thus replacing the many-to-many annotation mapping directly between two main entity classes with a one-to-many annotation in the main entity classes and two 'many-to-one' annotations in the Associative Entity class. There is an example provided in this forum post Association models with extra fields:
public class Person
{
/**
* @OneToMany(targetEntity="AssignedItems", mappedBy="person")
*/
private $assignedItems;
}
public class Items
{
/**
* @OneToMany(targetEntity="AssignedItems", mappedBy="item")
*/
private $assignedPeople;
}
public class AssignedItems
{
/**
* @ManyToOne(targetEntity="Person")
* @JoinColumn(name="person_id", referencedColumnName="id")
*/
private $person;
/**
* @ManyToOne(targetEntity="Item")
* @JoinColumn(name="item_id", referencedColumnName="id")
*/
private $item;
}
A: If you can, you can do this as this worked for me:
Drop the entire database:
app/console doctrine:schema:drop --force --full-database
Run all DB migrations:
app/console doctrine:migrations:migrate
A: I imagine It can happen quite often when copying entities. In my case it was a ORM table name annotation that was misfortunately duplicated.
/**
* @ORM\Entity()
* @ORM\Table(name="category")
* */
class Category {
A: I had this problem with an One-To-Many, Unidirectional with Join Table relation like (see doctrine doc). I did not find this error case with this relation type through the internet or stackoverflow, so i post here my solution for let help others with the same problem.
What caused this problem:
*
*After reverse engineering the legacy db tables with ORM (see doc "How to Generate Entities from an Existing Database"), all tables also only join tables recieved an entity PHP class.
*With annotations on a category entity i described the joining. Results this code:
/**
* @ORM\ManyToMany(targetEntity="Category")
* @ORM\JoinTable(name="category_child",
* joinColumns={@JoinColumn(name="category_id", referencedColumnName="id")},
* inverseJoinColumns={@JoinColumn(name="category_child_id", referencedColumnName="id")}
* )
*/
public $children;
*The @ORM\JoinTable(name="category_child" caused that doctrine wants to create this table again. One time because of the already existing Category_Child entity, and then the @ORM\JoinTable expression that points to the same table.
Solution
Solution was to delete the Category_Child entity that was created from reverse engineering. If you used Category_Child entity in some $em queries, you have to select those datas othwerwise. E.g. Through the parent that holds those child datas in an ArrayCollection, or over DBAL.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565492",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
}
|
Q: Understanding the flow of a struct in C I am trying to learn how structs work in C. I am familiar with constructors in Java. Now, I have an example of creating a tree in C with structs.
struct a_tree_node{
int value;
struct a_tree_node *leftPTR, *rightPTR;
};
I am currently trying to visualize how this works, I am a little confused because this struct contains itself.
A:
I am a little confused because this struct contains itself.
The struct doesn't contain itself, but rather two pointers to the same kind of structure. That's the key point to understand.
The struct containing itself would be nonsense and wouldn't compile because it's an infinitely recursive dependency.
A: I think your confusion is comparing a struct to a constructor in Java. The closest equivalent in Java would be class:
class ATreeNode{
int value;
ATreeNode left;
ATreeNode right;
}
As the other answers have said, the left and right node in the struct are pointers - much like (but not quite the same as) references from Java.
A: The struct doesn't contain it self. It contains two pointers to its type. A very important distinction. Pointers are not of the type the point to but can rather be dereferenced into what they point to at a later time.
A: It doesn't contain itself it contains two pointers to the same defenition. The * in front of the leftPTR and rightPTR point to memory location where other a_tree_node's are stored.
A: The struct is defined in such a way that it forms a linked list. Inside the struct you define two pointers to structs. So, the struct does not contain itself, rather, it contains two pointers to two different instantiations of a struct. It is even possible the pointer is a pointer to the struct itself.
A: When coming from Java, you already know the necessary concepts, but lack the rigor C enforces on the concepts of data and pointers. leftPtr is just like a variable of class type (like Object) in Java, that is, it points to another object, might be Null or might point to another object.
A: It's just a linked list of int representing a binary tree.
A: It contains the address of a simlar structure.
Like lets take a tree node.
it means that a single tree node also stores the address of two other similar tree nodes.
A: Here in the question contains a pointer to struct a_tree_node.
The size of a pointer type is always constant i.e. sizeof(unsigned integer)
so it won't create any problem in defining the size of a struct a_tree_node.
It will not be a nested struct... :) :)
A: struct a_tree_node{int value;struct a_tree_node *leftPTR, *rightPTR; };
This code will work fine as we are referring pointer to structure not its object as size of pointer is not data type specific. It will depend on how much bit is your OS effectively your integer will take how much byte
e.g on gcc sizeof(int) is 4 so sizeof(leftPTR) is also same
so at run time there will be no recursion sizeof(a_tree_node)=12 (Not considering structure padding as it is compiler specific)
struct a_tree_node{int value;struct a_tree_node left;};
This declaration will leads to error as compiler wouldn't be able to compute its size
goes in infite recursion.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565494",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Updating multiple rows in one query very slow performance I am looking at the best way to update multiple rows at once with a single query.
Currently I have:
UPDATE `profiles` SET `name` = CASE `id` WHEN 1 THEN 'John' WHEN 2 THEN 'Jane' END, `gender` = CASE `id` WHEN 1 THEN 'Male' WHEN 2 THEN 'Female' END WHERE `id`=1 OR `id`=2
but this takes about 4 minutes to complete (my real query is on 10 fields in a database of 20 million rows) as opposed to individual update queries that take about 1 second.
I am trying to work out why, what is actually happening? I thought that by specifying the id in the WHERE clause that this would speed it up.
A: Do you have an index on id? If not, it's a good idea to create one (Warning, this can take a long time, do this in off-peak hours):
CREATE INDEX id_idx ON profiles (id);
By the way, a query on 10 fields with 20 million rows in a table can take long, especially if there are not indices or the cache is cold.
Update: For testing and because I was curious I tried to reproduce your situation. For this I made up some test-data.
DDL: https://gist.github.com/b76ab1c1a9d0ea071965
Update Query: https://gist.github.com/a8841731cb9aa5d8aa26
Perl script to populate the table with test-data: https://gist.github.com/958de0d848c01090cb9d
However, as I already mentioned in my comment below, Mysql will prevent you from inserting duplicate data because id is your PRIMARY KEY, but not unique. If you could comment on the table schema and/or post your DDL, this would help a lot.
Good luck!
Alex.
A: Could you post the DDL for the profiles table, please? This will help to see what kind of indexes you have set up (for example - can we assume that the id column is the primary key here?). If you're using MySQL then just run 'SHOW CREATE TABLE profiles' to generate the DDL.
A couple of points that might help out:
1) Try using a BETWEEN in your WHERE clause instead of an OR. e.g.
UPDATE profiles
SET `name` =
CASE `id` WHEN 1 THEN 'John'
WHEN 2 THEN 'Jane' END,
`gender` = CASE `id`
WHEN 1 THEN 'Male' WHEN 2 THEN 'Female' END
WHERE `id` between 1 and 2;
2) Try splitting the query in separate queries to avoid using the CASE statement e.g.
update `profiles`
set `name` = 'John',
`gender` = 'Male'
where `id` = 1;
and
update `profiles`
set `name` = 'Jane',
`gender` = 'Female'
where `id` = 2;
I don't know if this is feasible since I'm not sure in what context you are using the query! Hope that helps.
A: Can you please specify all your case for all fields, so we have better idea. If you have fix case to update only for id=1 and 2 then split your query in 2 queries like :
update `profiles` set `name` = 'John', `gender` = 'Male' where `id` = 1;
update `profiles` set `name` = 'Jane', `gender` = 'Female' where `id` = 2;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565497",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Android: Live Video Streaming I have an app that download a video from ftp then save on sd card in encrypted form , when user want to see that videos , then it decrpted and then showing but i have a problem with that is takes long dely on decrption. Is there any way to play a video like live streaming when it is in decrption process.
A: To implement your streaming scheme, you need two main components: a streaming server such as a local http instance and a javax.crypto.CipherInputStream. LocalSingleHttpServer is an example of that kind of implementation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565503",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: A void* being used to maintain state... (C programming) Currently we are learning how to program AVR micro-controllers (Ansi C89 standard only). Part of the included drivers is a header that deals with scheduling ie running tasks at different rates. My question is to do with a quote from the documentation:
"Each task must maintain its own state, by using static local
variables."
What does that mean really? They seem to pass a void* to the function to maintain the state but then do not use it?
Looking at the code in the file I gather this is what they mean:
{.func = led_flash_task, .period = TASK_RATE / LED_TASK_RATE, .data = 0}
/* Last term the pointer term */
There is a function that runs with the above parameters in an array however, it only acts as a scheduler. Then the function led_flash_task is
static void led_flash_task (__unused__ void *data)
{
static uint8_t state = 0;
led_set (LED1, state); /*Not reall important what this task is */
state = !state; /*Turn the LED on or off */
}
And from the header
#define __unused__ __attribute__ ((unused))
And the passing of the void *data is meant to maintain the state of the task? What is meant by this?
Thank-you for your help
A: As you can see from the __unused__ compiler macro the parameter is unused. Typically this is done because the method needs to match a certain signature (interrupt handler, new thread, etc...) Think of the case of the pthread library where the signature is something like void *func(void *data). You may or may not use the data and if you don't the compiler complains so sticking the __unused__ macro removes the warning by telling the compiler you know what you're doing.
Also forgot about static variables as was said in the other answer static variables don't change from method call to method call so the variable is preserved between calls therefore preserving state (only thread-safe in C++11).
A: data is unused in that function (hence the __unused__). State is kept in the static variable state, which will keep its value between calls. See also What is the lifetime of a static variable in a C++ function?
A: From the documentation:
unused
This attribute, attached to a variable, means that the variable is meant to be possibly unused. GCC will not produce a warning for this variable.
A: The state must be maintained in a local static variable.
That means a variable declared inside the function with the static keyword:
static uint8_t state = 0;
in your example.
This has nothing to do with the parameter passed into the task, which in your example doesn't get used.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565507",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: What is a pull-through cache? I found a reference to this concept in the EHCache documentation, but I could not find any proper explanation of what it means.
It tried Googling around but to no avail.
A: The more common term is self populating cache.
In Ehcache docs a SelfPopulatingCache (= pull-through cache) is described as a:
A selfpopulating decorator for Ehcache that creates entries on demand.
That means when asking the SelfPopulatingCache for a value and that value is not in the cache, it will create this value for you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565514",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Persisting two entities at the same time I have been struggling with this for sometime and can't seem to get past the problem. I have a persisted entity called SiteVisit which is many-to-many related to Staff via an intermediate table called SiteVistHasStaff.
Using Netbeans, CRUD and JSf I have been able to populate these tables (using three CRUD pages) with meaningful data and created queries which display site visits for employees etc.
However to improve the user interface I am trying to create a page that allows the booking of a SiteVisit and selecting the Staff who will be attending then creating new records in the SiteVist and SiteVisitHasStaff tables when the page/form is submitted.
This seems such a simple real world task but I cannot seem to get clear the steps I need to take to achieve it. I have managed to get the data onto the same page in a selectManyMenu but then fail with persistence errors when trying to commit my selections(the site visit is created without a list of staff but the StaffVisitHasStaff record fails as there is no value for the SiteVisit id field)
Can I use the CRUD creation methods generated by netbeans, which sort of feels like the correct way as I am reusing code, but my thinking is no as they use different EntityManagers and don't appear to know about each other. Do I need to create a new bean (I've tried this unsuccessfully) with a new facade that deals with the requirement? Or is it something to do with my entity definitions.
@OneToMany(cascade = CascadeType.ALL, mappedBy = "siteVisitIdsiteVisit")
private List<SiteVisitHasStaFF> siteVisitHasStaffList;
@JoinColumn(name = "site_visit_idsite_visit", referencedColumnName = "idsite_visit")
@ManyToOne(optional = false)
private SiteVisit siteVisitIdsiteVisit;
Can anyone help or point me in the direction of an example which demonstrates how to do this I have googled, read and tried so many things I am just completely confused.
Thanks for any help you can offer.
A: Well, just a shot in the dark, I'm not that firm with Netbeans/CRUD/whatever, but in which order are you persisting your entities and which persistence error do you get exactly?
As I recall, if you have two different entity managers, initially they don't know entities persistet by the other. Additionally, you have to persist something to reference it.
So if one EM is persisting something, the entity will resist only in his persistence context until everyting is commited (end of transaction, flush,...). The other EM will not automatically detect the entity, that's what merging entities is for .
Don't know what would be applicable in your situation, but I would use one EM for all operations in one scope or merge the entities you want to use into the other EM.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565524",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: :onchange in form not working, in rails 3.1 app This is exactly my problem. In my case the :onchange function is not working, though I have added the jquery in the application.rb.
in the form, I need to alert the users
<%= telephone_field(:user, :phone_country_code, :size => 1, :onchange => "if $('user[phone_country_code]').length > 2 { alert('Your firstname needs to be shorter!'); }") %>
in application.html.rb
<%= javascript_include_tag "jquery" %>
in the console I am getting
Started GET "/assets/application.js?body=1" for 127.0.0.1 at 2011-09-27 12:36:39 +0530
Served asset /application.js - 304 Not Modified (1ms)
A: I think you have a syntax error in your javascript. Add parentheses:
if ($('user[phone_country_code]').length > 2) { alert('Your firstname needs to be shorter!'); }")
Also: strange alert for a country code..
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565525",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Jquery ColorBox: Display inline content with next and previous button I'm trying to use a Jquery Lightbox called ColorBox (http://colorpowered.com/colorbox/) but I'm running into some troubles.
I want to use the lightbox to display inline content but also have the next and previous button appear. This way, like in a photo gallery, I would be able to navigate through all the item sharing the same rel attribute with the next and previous button.
So far, my code is somewhat working. But it seems that all the element having the same rel attribute are not recognized. In fact, they only appear if I click the next and previous button beforehand.
Here is my HTML
<div id="galcontainer">
<div class="element">
<a href="link.php" rel="Catalogue" cbx="Catalogue1" class="cbx">
<img src="image.jpg" />
</a>
<div style="display:none">
<div id="Catalogue1">
Content Goes Here
</div>
</div>
</div>
<div class="element">
<a href="link.php" rel="Catalogue" cbx="Catalogue27" class="cbx">
<img src="image.jpg" />
</a>
<div style="display:none">
<div id="Catalogue27">
Content Goes Here
</div>
</div>
</div>
...
</div>
And here is the Jquery code:
$("a.cbx").click(function(){
var divtoload=$(this).attr("cbx");
var cbxgroup=$(this).attr("rel");
$(this).colorbox({rel:cbxgroup, width:"70%", maxWidth:"720px", inline:true, href:"#"+divtoload});
})
A: I was working on a similar problem. I basically simplified everything and got this working.
Javascript
<script type="text/javascript">
$(document).ready(function() {
$(".group1").colorbox({rel:'group1', inline:true, href:$(this).attr('href')});
});
</script>
Content
<p><a class="group1" href="#box1">Grouped Photo 1</a></p>
<p><a class="group1" href="#box2">Grouped Photo 2</a></p>
<p><a class="group1" href="#box3">Grouped Photo 3</a></p>
<div id="box1">
Some text in box 1 Some text in box 1
Some text in box 1
Some text in box 1
Some text in box 1
Some text in box 1
</div>
<div id="box2">
Some text in box 2
Some text in box 2
Some text in box 2
Some text in box 2
Some text in box 2
</div>
<div id="box3">
Some text in box 3
Some text in box 3
Some text in box 3
Some text in box 3
Some text in box 3
</div>
A: I add a new element often, soo adding a new element to the begining would take longer than I want. So I automated this procedure and generated code looks exactly like yours(in your post), but colorbox doesn't work. Does anyone now how to fix it(if possible)? Help would be greatly appreciated.
If I edit your code like this
<div class="links">
<p><a class="group1">Grouped Photo 1</a></p>
<p><a class="group1">Grouped Photo 2</a></p>
<p><a class="group1">Grouped Photo 3</a></p>
</div>
<div class="boxes">
<div>
Some text in box 1 Some text in box 1
Some text in box 1
Some text in box 1
Some text in box 1
Some text in box 1
</div>
<div>
Some text in box 2
Some text in box 2
Some text in box 2
Some text in box 2
Some text in box 2
</div>
<div>
Some text in box 3
Some text in box 3
Some text in box 3
Some text in box 3
Some text in box 3
</div>
</div>
And javascript:
$('.links a').each(function(index) {
q(this).attr("href","#box"+index);
});
$('.boxes div').each(function(index) {
q(this).attr("id","#box"+index);
});
This goes through all the links and adds them the same id as the link has in href attribute
A: I know this is an old question. But found a different solution. The developer of the plugin recommend it: https://github.com/jackmoore/colorbox/issues/600
<a href='#' id='open'>Open inline group</a>
<div style='display:none'>
<div class='inline'>
<div style='padding:10px; background:#fff;'>
<p><strong>This content comes from a hidden element on this page.</strong></p>
</div>
</div>
<div class='inline'>
<div style='padding:10px; background:#fff;'>
<p><strong>2. This content comes from a hidden element on this page.</strong></p>
</div>
</div>
<div class='inline'>
<div style='padding:10px; background:#fff;'>
<p><strong>3. This content comes from a hidden element on this page.</strong></p>
</div>
</div>
<div class='inline'>
<div style='padding:10px; background:#fff;'>
<p><strong>4. This content comes from a hidden element on this page.</strong></p>
</div>
</div>
</div>
<script>
var $group = $('.inline').colorbox({inline:true, rel:'inline', href: function(){
return $(this).children();
}});
$('#open').on('click', function(e){
e.preventDefault();
$group.eq(0).click();
});
</script>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565532",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Absolute url overwiritten as a Relative URl when adding a new html element like iframe etc (i.e adding the a base address at prefix of URL supplied) I am trying to add an iframe to my website. The problem is that our CMS automatically overrides the src address given ex: I set the absolute url (source address) to http://www.youtube.com/embed/RE6C1AoWy3M and when the page is rendered the src is modified as shown.
The base address is being added. This was set as we normaly upload images/files on our file system.
Any idea how can I override this, maybe embed some javascript function. I do not have access to .cs/ Asp.net pages.
A: You can create an inline script that will render the iframe during the page load.
Example:
<html>
<head>
<title>example</title>
</head>
<body>
<!-- Your normal HTML/text here -->
<!-- add the script where you wanted the iframe to be -->
<script type='text/javascript'>
document.write("<iframe src='http://www.youtube.com/embed/RE6C1AoWy3M'></iframe>");
</script>
<!-- Your remaining HTML/text here -->
</body>
</html>
A: This has finally worked. I am creating the iFrame as shown below not using the CMS drag/drop html objects and modify the src attribute.
var el = document.createElement("iframe");
el.setAttribute('id', 'ifrm');
// Here I am getting the object to append the iframe to
var elem = document.getElementById("td1");
// Append iframe to this element.
elem.appendChild(el);
el.setAttribute('src', 'http://www.youtube.com/embed/RE6C1AoWy3M');
</script>
Although this solved my problem, I am open to new maybe better suggestions. I am willing to learn from other's experience.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565536",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: width/height after transform How do I retrieve the width and height properties after I've applied transform: rotate(45deg);?
Like, 11x11 square after rotation becomes 17x17 (Chrome result), but javascript still returns original width/height - 10x10.
How do I get this 17x17?
A: I made a function for this, domvertices.js
It computes the 4 vertices 3d coordinates of any, deep, transformed, positioned DOM element -- really just any element: see the DEMO.
a b
+--------------+
| |
| el |
| |
+--------------+
d c
var v = domvertices(el);
console.log(v);
{
a: {x: , y: , z: },
b: {x: , y: , z: },
c: {x: , y: , z: },
d: {x: , y: , z: }
}
With those vertices, you can compute anything among: width, height... Eg, in your case:
// norm(a,b)
var width = Math.sqrt(Math.pow(v.b.x - v.a.x, 2) + Math.pow(v.b.y - v.a.y, 2));
See the README for more infos.
--
It is published as a npm module (with no dep), so just install it with:
npm install domvertices
Cheers.
A: Instead of calculating it yourself, you can get this via the HTMLDOMElement's getBoundingClientRect().
This will return an object with the correct height and width, taking into account the transformation matrix.
jsFiddle.
A: In case you're looking for a function to programmatically calculate these values...
// return an object with full width/height (including borders), top/bottom coordinates
var getPositionData = function(el){
return $.extend({ width : el.outerWidth(false), height : el.outerHeight(false) }, el.offset());
};
// get rotated dimensions
var transformedDimensions = function(el, angle){
var dimensions = getPositionData(el);
return { width : dimensions.width + Math.ceil(dimensions.width * Math.cos(angle)), height : dimensions.height + Math.ceil(dimensions.height * Math.cos(angle)) };
}
Here's a little something I put up. Probably not the best thing ever, but does the job for me.
A: Even if you rotate something the dimensions of it do not change, so you need a wrapper.
Try wrapping your div with another div element and count the wrappers dimensions:
<style type="text/css">
#wrap {
border:1px solid green;
float:left;
}
#box {
-moz-transform:rotate(120deg);
border:1px solid red;
width:11px;
height:11px;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
alert($('#box').width());
alert($('#wrap').width());
});
</script>
</head>
<body>
<div id="wrap">
<div id="box"></div>
</div>
</body>
Redited: the wrapper solution is not working properly, as the wrapper is not automatically adjusted to the contents of the inner div. Follow the mathematical solution:
var rotationAngle;
var x = $('#box').width()*Math.cos(rotationAngle) + $('#box').height()*Math.sin(rotationAngle);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565542",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "35"
}
|
Q: SQLAlchemy ForeignKey can't find table Getting this error when I try to instantiate the ConsumerAdvice class.
Foreign key associated with column 'tbConsumerAdvice.ConsumerAdviceCategory_ID'
could not find table 'tbConsumerAdviceCategories' with which to generate a
foreign key to target column 'ID_ConsumerAdviceCategories'
class ConsumerAdviceCategory(Base):
__tablename__ = 'tbConsumerAdviceCategories'
__table_args__ = {'schema':'dbo'}
ID_ConsumerAdviceCategories = Column(INTEGER, Sequence('idcac'),\
primary_key=True)
Name = Column(VARCHAR(50), nullable=False)
def __init__(self,Name):
self.Name = Name
def __repr__(self):
return "< ConsumerAdviceCategory ('%s') >" % self.Name
class ConsumerAdvice(Base):
__tablename__ = 'tbConsumerAdvice'
__table_args__ = {'schema':'dbo'}
ID_ConsumerAdvice = Column(INTEGER, Sequence('idconsumeradvice'),\
primary_key=True)
ConsumerAdviceCategory_ID = Column(INTEGER,\
ForeignKey('tbConsumerAdviceCategories.ID_ConsumerAdviceCategories'))
Name = Column(VARCHAR(50), nullable=False)
Category_SubID = Column(INTEGER)
ConsumerAdviceCategory = relationship("ConsumerAdviceCategory",\
backref=backref('ConsumerAdvices'))
def __init__(self,Name):
self.Name = Name
def __repr__(self):
return "< ConsumerAdvice ('%s') >" % self.Name
A: I also hit this error. In my case the root cause was that I attempted to define different sqlalchemy base classes:
Base1 = declarative_base(cls=MyBase1)
Base1.query = db_session.query_property()
Base2 = declarative_base(cls=MyBase2)
Base2.query = db_session.query_property()
I had a ForeignKey relationship from one class that derives from Base1 to another class that derives from Base2. This didn't work -- I got a similar NoReferencedTableError. Apparently classes must derive from the same Base class in order to know about each other.
Hope this helps someone.
A: Define the FK including schema: dbo.tbConsumerAdviceCategories.ID_ConsumerAdviceCategories
A: That didn't solve my problem, I had to use.
ConsumerAdviceCategory_ID = Column(INTEGER,
ForeignKey('tbConsumerAdviceCategories.ID_ConsumerAdviceCategories',
schema='dbo'))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565549",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: how to sort an array of objects by the parents of the objects I have the following model objects:
Participants.rb
belongs_to :user
belongs_to :board
Users.rb
has_many :participants
Boards.rb
has_many :participants
I want to sort the following array by the name of the users when I get the information from the database; i.e. something like:
participants = get_current_board.participants.where(:role => "Participant").order(participants.user.name)
How can I do this?
A: Try -
participants.sort {|x,y| x.user.name <=> y.user.name }
A: To let your database to the sorting:
participants = get_current_board.participants.where(:role => "Participant").joins(:user).order(:users => :name)
A: participants = get_current_board.participants.includes(:user).where(:role => "Participant").order(:users=>:name)
You are use this with eager loading
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565558",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to execute JavaScript in Ruby written Webdriver test? Is there a known solution to perform Eval (Javascript execution) in Webdriver, Ruby bindings?
The equivalent of the following example in Java.
WebElement element = driver.findElement(By.id( "foo" ));
String name = (String) ((JavascriptExecutor) driver).executeScript(
"return arguments[0].tagName" , element)
A: Thank you for posting this answer. It helped me a lot. I was googling the whole day to figure out how to execute JavaScript code within Ruby.
@driver.execute_script("arguments[0].scrollIntoView(true);", element )
By doing so, I was able to scroll into the specific element before click event. This might help others a bit.
I had to use JavaScript alternative because for some reason this wasn't: working for me element.location_once_scrolled_into_view
Thanks.
A: The equivalent Ruby would be:
name = driver.execute_script("return arguments[0].tagName" , element)
(to get the tag name you could also just call element.tag_name)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565562",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: MySQL: SELECT DISTINCT from multiple tables I have database with several tables in it. For sake of example I will simplify it and try to explain in detail.
One table is called Products, another called Brands, and the last one is called Categories.
As you might guessed each Product can have only one Category assigned. Also, each Product can have only one Brand assigned. These are the relationships.
So, on one page I have links with Brands as parameter that I pass to details page where I list all Products from specific Brand. On that page I also have filter by Categories that filters only products from selected Brand by that filter.
E.g. Sony -> then filter applied from drop down is dSLR -> Results of Sony brand dSLR camera products.
What I would like is to have that Categories filtered so that if Brand doesnt have specific category it doesnt even show on that drop down filter.
E.g. Categories are predefined as: dSLR, Video, Cell phone, Shoes
Sony have loads of Products, but doesnt make shoes, so I would like to have it excluded from that filter list on details page.
Hope you understood what I want here...
Any suggestion is more than welcomed :)
A: Well, you should be able to JOIN the three tables like so:
SELECT DISTINCT c.category_id, c.category_name
FROM products p
JOIN categories c ON p.category_id = c.category_id
JOIN brands b ON p.brand_id = b.brand_id
WHERE b.brand_name='Sony';
and then display the products like so:
SELECT p.product_id, p.product_name
FROM products p
JOIN categories c ON p.category_id = c.category_id
JOIN brands b ON p.brand_id = b.brand_id
WHERE b.brand_name='Sony' AND c.category_id='1234';
As danishgoel already noted, make sure you have the proper indices on your tables, since this is a quite expensive query.
A: One way is to select the list of distinct categories from the products of a specific brand.
You can do it like:
SELECT DISTINCT(cat_id) FROM PRODUCTS WHERE brand_id = 'sony'
Now you have only those categories that are available for sony products
The above query might be a little slow to run on each page request. You can speed it up by creating an INDEX on brand_id, cat_id
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565573",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jquery number compare I met a trouble to compare number in jquery. test code here:
<script src="jquery.js"></script>
<script>
jQuery(document).ready(function(){
var val1 = $("#aaa").attr('title');
var val2 = $("#bbb").html();
if(val1>=val2){
$("#ccc").html(val1);
}else{
$("#ccc").html(val2);
}
});
</script>
<div id="aaa" title="1">aaa</div>
//set title=1 show 1, set title=2 show 111
<div id="bbb">111</div>
<div id="ccc"></div>
As code show, two number from html dom. now I set number in div#aaa[title], if set number one, it is right, and if set number 2, the result is wrong. Where is the problem? Thanks.
A: You need to compare int values, not a strings
jQuery(document).ready(function(){
var val1 = parseInt($("#aaa").attr('title'));
var val2 = parseInt($("#bbb").html());
if(val1>=val2){
$("#ccc").html(val1);
}else{
$("#ccc").html(val2);
}
});
Code: http://jsfiddle.net/BCKKr/
A: You are comparing strings, convert them to int with parseInt(value, 10);
var val1 = parseInt($("#aaa").attr('title'), 10);
var val2 = parseInt($("#bbb").html(), 10);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565574",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Set value for a parameter in app.yml in symfony I'm using Symfony Propel. I want change my app.yml variable value inside a for loop.
My code is
for($i=0;$i<5;$i++)
{
$previousValue = sfConfig::get('app_url');
sfConfig::set('app_url', $previousValue+1);
echo sfConfig::get('app_url');
}
I have set default value for url = 0
When i run this i'm getting value as 1 but it should be 4. When i run the page again then it should end up with 8, run again then 16 and so on.
What am i doing wrong.please help me.
A: When you use sfConfig::set() you are only setting this value for the current runtime. You are not permanently editing app.yml.
While technically it would be possible to edit YAML files with PHP, I would not suggest it, as it's overly complicated compared to other alternatives, and symfony caches the parsed YAML files anyway.
You are better off storing this kind of values in your database. A simple query will suffice to increment your value.
Also check my answer in a related question: edit values in app.yml by backend
A: sfConfig 1 is not the good way to store persistent data, use sfStorage 2 instead, else each time you request your page your value is reseted to your initial value.
Your example :
app.yml
all:
url: 0
indexSuccess.php
for($i=0;$i<5;$i++) {
$previousValue = sfConfig::get('app_url');
sfConfig::set('app_url', $previousValue+1);
echo sfConfig::get('app_url');
}
Output :
12345
But each time your relaunch it, you will have the same output.
Ps: When you declare or initialize a config value, don't forget to clean your cache (php symfony cc)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565585",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Pattern matching with more than one match Consider the following Scala code.
val a = "both"
a match {
case "both" | "foo" => println ("foo") // case 1
case "both" | "bar" => println ("bar") // case 2
}
I would like match to work so that if a == "both", Scala will execute both cases. Is this possible or are there any alternatives to achieve what I want?
A: At risk of being Captain Obvious, in a case like this it would be simplest just to forget pattern matching and use if.
if (a == "both" || a == "foo") println("foo")
if (a == "both" || a == "bar") println("bar")
If the repetition of a == worries you, you could instead write
if (Set("both", "foo")(a)) println("foo")
if (Set("both", "bar")(a)) println("bar")
using the fact that the apply method on Set does the same as contains, and is a bit shorter.
A: match executes one, and only one, of the cases, so you can't do this as an or in the match. You can, however, use a list and map/foreach:
val a = "both"
(a match {
case "both" => List("foo", "bar")
case x => List(x)
}) foreach(_ match {
case "foo" => println("foo")
case "bar" => println("bar")
})
And you're not duplicating any of the important code (in this case the printlns).
A: Standard pattern-matching will always match on only exactly one case. You can get close to what you want by using the fact that patterns can be treated as partial functions (see the Language Specification, Section 8.5, Pattern Matching Anonymous Functions) and by defining your own matching operator, though:
class MatchAll[S](scrutinee : =>S) {
def matchAll[R](patterns : PartialFunction[S,R]*) : Seq[R] = {
val evald : S = scrutinee
patterns.flatMap(_.lift(evald))
}
}
implicit def anyToMatchAll[S](scrut : =>S) : MatchAll[S] = new MatchAll[S](scrut)
def testAll(x : Int) : Seq[String] = x matchAll (
{ case 2 => "two" },
{ case x if x % 2 == 0 => "even" },
{ case x if x % 2 == 1 => "neither" }
)
println(testAll(42).mkString(",")) // prints 'even'
println(testAll(2).mkString(",")) // prints 'two,even'
println(testAll(1).mkString(",")) // prints 'neither'
The syntax is slightly off the usual, but to me such a construction is still a witness to the power of Scala.
Your example is now written as:
// prints both 'foo' and 'bar'
"both" matchAll (
{ case "both" | "foo" => println("foo") },
{ case "both" | "bar" => println("bar") }
)
(Edit huynhjl pointed out that he gave a frighteningly similar answer to this question.)
A: Just match twice:
val a = "both"
a match {
case "both" | "foo" => println ("foo") // Case 1
}
a match {
case "both" | "bar" => println ("bar") // Case 2
}
A: One possible way could be:
val a = "both"
a match {
case "foo" => println ("foo") // Case 1
case "bar" => println ("bar") // Case 2
case "both" => println ("foo"); println ("bar")
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565599",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: YouTrack java.lang.OutOfMemoryError - Teamcity integration We are getting the error below which is causing YouTrack to crash.
We are using YouTrack to scan TeamCity for changes which I beleive is causing the issue below.
How much memory should YouTrack need to run with TeamCity integration and which config should we use to allow for this increase memory usage?
Error Message:
26 Sep 2011 22:20:00,043 ERROR [SuccessfulBuild_Then] [ssor0] Error while processing Teamcity integration for project [Connectors]
java.lang.OutOfMemoryError
at java.util.zip.Inflater.init(Native Method)
at java.util.zip.Inflater.<init>(Unknown Source)
at java.util.zip.ZipFile.getInflater(Unknown Source)
at java.util.zip.ZipFile.getInputStream(Unknown Source)
at java.util.zip.ZipFile.getInputStream(Unknown Source)
at java.util.jar.JarFile.getInputStream(Unknown Source)
at sun.net.www.protocol.jar.JarURLConnection.getInputStream(Unknown Source)
at com.sun.jersey.spi.service.ServiceFinder.parse(ServiceFinder.java:455)
at com.sun.jersey.spi.service.ServiceFinder.access$300(ServiceFinder.java:144)
at com.sun.jersey.spi.service.ServiceFinder$AbstractLazyIterator.hasNext(ServiceFinder.java:529)
at com.sun.jersey.spi.service.ServiceFinder.toClassArray(ServiceFinder.java:373)
at com.sun.jersey.core.spi.component.ProviderServices.getServiceClasses(ProviderServices.java:295)
at com.sun.jersey.core.spi.component.ProviderServices.getProviderAndServiceClasses(ProviderServices.java:274)
at com.sun.jersey.core.spi.component.ProviderServices.getProvidersAndServices(ProviderServices.java:181)
at com.sun.jersey.core.spi.factory.InjectableProviderFactory.configure(InjectableProviderFactory.java:104)
at com.sun.jersey.api.client.Client.<init>(Client.java:209)
at com.sun.jersey.api.client.Client.<init>(Client.java:150)
at com.sun.jersey.api.client.Client.create(Client.java:472)
at jetbrains.charisma.teamcity.rest.TeamcityRest.<init>(TeamcityRest.java:60)
at jetbrains.charisma.teamcity.rest.TeamcityRest.<init>(TeamcityRest.java:66)
at jetbrains.charisma.teamcity.rest.TeamcityRest.create(TeamcityRest.java:249)
at jetbrains.charisma.teamcity.persistence.TeamcityBuildConfMappingImpl.process(TeamcityBuildConfMappingImpl.java:140)
at jetbrains.charisma.teamcity.persistence.TeamcityIntegration_watchNewSuccessfulBuild_Then.run(TeamcityIntegration_watchNewSuccessfulBuild_Then.java:26)
at jetbrains.mps.businessRules.runtime.impl.RuleJobImpl._execute(RuleJobImpl.java:68)
at jetbrains.mps.businessRules.runtime.impl.RuleJobImpl.access$000(RuleJobImpl.java:14)
at jetbrains.mps.businessRules.runtime.impl.RuleJobImpl$1.run(RuleJobImpl.java:46)
at jetbrains.mps.businessRules.runtime.TransactionalExecutor.execute(TransactionalExecutor.java:23)
at webr.framework.controller.BeanContainerAwareExecutorWrapper.execute(BeanContainerAwareExecutorWrapper.java:23)
at jetbrains.mps.businessRules.runtime.impl.RuleJobImpl.execute(RuleJobImpl.java:44)
at sun.reflect.GeneratedMethodAccessor106.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.util.MethodInvoker.invoke(MethodInvoker.java:276)
at org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean$MethodInvokingJob.executeInternal(MethodInvokingJobDetailFactoryBean.java:260)
at org.springframework.scheduling.quartz.QuartzJobBean.execute(QuartzJobBean.java:86)
at org.quartz.core.JobRunShell.run(JobRunShell.java:202)
at com.jetbrains.teamsys.core.execution.RunnableJob.execute(RunnableJob.java:25)
at com.jetbrains.teamsys.core.execution.Job.run(Job.java:75)
at com.jetbrains.teamsys.core.execution.ThreadJobProcessor.executeJob(ThreadJobProcessor.java:110)
at com.jetbrains.teamsys.core.execution.JobProcessorQueueAdapter.doJobs(JobProcessorQueueAdapter.java:86)
at com.jetbrains.teamsys.core.execution.ThreadJobProcessor.run(ThreadJobProcessor.java:89)
at com.jetbrains.teamsys.core.execution.ThreadJobProcessor$1.run(ThreadJobProcessor.java:25)
at java.lang.Thread.run(Unknown Source)
Please Note: This error happens several times before completely crashing.
A: Josh,
Try to increase JVM heap size that YouTrack uses:
Open YouTrack service properties ("YouTrack Web Service" under Computer Management -> Services and Applications -> Services) and set the following line into start parameters input
++JvmOptions "-Xmx1024M"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565603",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Android: How to add a vertical progress bar to a home screen widget? I need to put a vertical scroll bar in a home screen widget, and after searching many times, I can't find a convenient solution that works on API3 and above!
I tried many solutions:
- using bitmap created at run-time, but on some displays it never reach 100%
- a patch9 bitmap, but the scroll bar display gets completely messed up when the progress is near 0.
- using the addView() with 100 existing layout and it works great, except it's only available since API7!
- including all 100 layouts and showing only one at a time, work fine, but what a mess to include those in my 8 different widget layouts!
I tried to use the weight programmatically but it's not possible either, any other solution to resize a view based on a %?
Here is one progress bar layout I currently use:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<ImageView android:layout_weight="11" android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<ImageView android:src="@drawable/scale"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:layout_weight="89" />
</LinearLayout>
A: Only solution I found so far is to have all the possible progress levels ready to use in various Xml layout files.
On Android API < 7, all those need to be included in a single xml layout and shown/hidden at run-time, while on Android API >= 7, one can actually use addRemoteView() to include the desired layout in a much more efficient way!
A: You should use ScrollView! You must place this within a layout. By default, scrollview is for Vertical Scroll. If you want horizontal scroll you must specify HorizontalScrollView. Hope this helps
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565604",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Help designing manager class I'm designing a UI manager class that will manage all my UI elements (this is for an XNA game, so there is no existing UI framework) but I'm wondering how to deal with situations where I want the UI manager to have special access to data in the UI elements that other classes can't access.
For example, I want to have a SetFocus method to focus a specific element and this method needs to ensure that the previously focused element loses focus. The individual UI elements themselves can't handle this because they don't have access to the list of UI elements, which means the manager has to handle it, but how can I allow the manager and only the manager to set the variable on a UI element?
The thought occurs to me to just store the currently focused element on the manager, however I don't particularly like that solution and, given a single UI element, I would like to query it to find out if it has focus. Even if it makes sense to store the currently focused element on the manager since its just a single variable, there are other things I need to deal with that would require arrays to associate the data with the elements if its stored on the manager, and that just seems to defeat the purpose of OOP.
I know I don't need to have it so that the manager is the only one with access to this data, I could just make all the data public, but that's not good design...
A: What you are looking for is a C# equivalent of the C++ friend concept. As you read in the linked post 'the closest that's available (and it isn't very close) is InternalsVisibleTo' (citing Jon Skeet). But using InternalsVisibleTo in order to accomplish what you want would mean you'd have to break up your complete application into a library per class, which would probably create a DLL hell.
Building upon MattDavey's example got me:
interface IFocusChecker
{
bool HasFocus(Control control);
}
class Manager : IFocusChecker
{
private Control _focusedControl;
public void SetFocus(Control control)
{
_focusedControl = control;
}
public bool HasFocus(Control control)
{
return _focusedControl == control;
}
}
class Control
{
private IFocusChecker _checker;
public Control(IFocusChecker checker)
{
_checker = checker;
}
public bool HasFocus()
{
return _checker.HasFocus(this);
}
}
Whether a Control has focus is now only stored in the Manager and only the Manager can change the focused Control.
A little example how to put things together, for completeness:
class Program
{
static void Main(string[] args)
{
Manager manager = new Manager();
Control firstControl = new Control(manager);
Control secondControl = new Control(manager);
// No focus set yet.
Console.WriteLine(string.Format("firstControl has focus? {0}",
firstControl.HasFocus()));
Console.WriteLine(string.Format("secondControl has focus? {0}",
secondControl.HasFocus()));
// Focus set to firstControl.
manager.SetFocus(firstControl);
Console.WriteLine(string.Format("firstControl has focus? {0}",
firstControl.HasFocus()));
Console.WriteLine(string.Format("secondControl has focus? {0}",
secondControl.HasFocus()));
// Focus set to firstControl.
manager.SetFocus(secondControl);
Console.WriteLine(string.Format("firstControl has focus? {0}",
firstControl.HasFocus()));
Console.WriteLine(string.Format("secondControl has focus? {0}",
secondControl.HasFocus()));
}
}
A: Having a variable on a control itself which is implicitly relative to the state of other controls is probably a poor design decision. The concept of "focus" is of concern at a much higher level, either a window or better yet, a user (the user is the one doing the focusing). So it's at the window or user level that a reference to the focused control should be stored, but in addition to that, there ought to be a way for controls to be notified when they gain/lose focus from the user - this could be done via events on the user/manager or by any standard notification pattern.
class Control
{
public Boolean HasFocus { get; private set; }
internal void NotifyGainedFocus()
{
this.HasFocus = true;
this.DrawWithNiceBlueShininess = true;
}
internal void NotifyLostFocus()
{
this.HasFocus = false;
this.DrawWithNiceBlueShininess = false;
}
}
class User // or UIManager
{
public Control FocusedControl { get; private set; }
public void SetFocusOn(Control control)
{
if (control != this.FocusedControl)
{
if (this.FocusedControl != null)
this.FocusedControl.NotifyLostFocus();
this.FocusedControl = control;
this.FocusedControl.NotifyGainedFocus();
}
}
}
Disclaimer: I've never written a UI library and I may be talking complete nonsense..
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565606",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: how to create sub menu in magento admin using module I'm developing magento module.I would like to add menu in admin section.
like.
admin-> catalog -> Attributes -> Manage Attribute-> Here mymenu
Magento version 1.5.1.0
How can i do this ?
A: in your module's adminhtml.xml put the following:
<config>
<menu>
<catalog>
<children>
<attributes>
<children>
<attributes>
<children>
<submenu translate="title" module="catalog">
<title>submenu submenu</title>
<action>adminhtml/catalog_product_attribute_submenu/</action>
</submenu>
</children>
</attributes>
</children>
</attributes>
</children>
</catalog>
</menu>
</config>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565614",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to check a checkbox is not selected <li>
<label><spring:message code="label.roles"/></label>
<form:checkbox path="roleIds" value="1" />
<label><spring:message code="label.users"/></label>
</li>
<li>
<label> </label>
<form:checkbox path="roleIds" value="2" />
<label><spring:message code="label.articles"/></label>
</li>
<li>
<label> </label>
<form:checkbox path="roleIds" value="3" />
<label><spring:message code="label.contents"/></label>
</li>
<li>
Now what i want is to give an error message if any of checkbox is not selected , how can i do it Using jquery
A: if ($("input[name='roleIds']:checked").length == 0) {
alert("at least one checkbox must be checked");
}
A: if ($("input[name=roleIds]").not(":checked").length) {
alert("some checkboxes aren't checked");
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565617",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to reorder this array? I have a database table as follows:
This returns all column titles in the pic, but the one's that are most important are slug, and parent (not sure about id_button).
The array gets ordered automatically by id_button ASC, which really irks me. But, anyways, this is not important, as I need to order it completely different, or re-order it after the array is populated.
The array returns this, by order of id_button:
$new_menu_buttons = array(
0 => array(
'id_button' => 1,
'parent' => 'help',
'position' => 'child_of',
'slug' => 'testing',
),
1 => array(
'id_button' => 2,
'parent' => 'packages',
'position' => 'after',
'slug' => 'sub_test_1',
),
2 => array(
'id_button' => 3,
'parent' => 'google.com',
'position' => 'after',
'slug' => 'another_test',
),
3 => array(
'id_button' => 4,
'parent' => 'testing'
'position' => 'child_of',
'slug' => 'google.com',
)
);
I need to order it so that if a slug is found within any parent, than the slug that is in the parent needs to be loaded before the one that has it defined within the parent.
Its not important if it is directly before it. For example, you see testing is the first slug that gets returned, and yet the parent for this is the last slug (google.com). So as long as the slug row where the parent is defined gets ordered so that it is BEFORE the row that has the slug value in the parent column, everything is fine.
So in this situation, it can be reordered as any of these 3 ordered arrays below:
$new_menu_buttons = array(
0 => array(
'id_button' => 1,
'parent' => 'help',
'position' => 'child_of',
'slug' => 'testing',
),
1 => array(
'id_button' => 2,
'parent' => 'packages',
'position' => 'after',
'slug' => 'sub_test_1',
),
2 => array(
'id_button' => 4,
'parent' => 'testing',
'position' => 'child_of',
'slug' => 'google.com',
),
3 => array(
'id_button' => 3,
'parent' => 'google.com'
'position' => 'after',
'slug' => 'another_test',
)
);
OR this...
$new_menu_buttons = array(
0 => array(
'id_button' => 1,
'parent' => 'help',
'position' => 'child_of',
'slug' => 'testing',
),
1 => array(
'id_button' => 4,
'parent' => 'testing',
'position' => 'child_of',
'slug' => 'google.com',
),
2 => array(
'id_button' => 2,
'parent' => 'packages',
'position' => 'after',
'slug' => 'sub_test_1',
),
3 => array(
'id_button' => 3,
'parent' => 'google.com'
'position' => 'after',
'slug' => 'another_test',
)
);
OR even this...
$new_menu_buttons = array(
0 => array(
'id_button' => 1,
'parent' => 'help',
'position' => 'child_of',
'slug' => 'testing',
),
1 => array(
'id_button' => 4,
'parent' => 'testing',
'position' => 'child_of',
'slug' => 'google.com',
),
2 => array(
'id_button' => 3,
'parent' => 'google.com'
'position' => 'after',
'slug' => 'another_test',
),
3 => array(
'id_button' => 2,
'parent' => 'packages',
'position' => 'after',
'slug' => 'sub_test_1',
)
);
All 3 of these ordered arrays will work because the array with the slug that matches the parent is before the array with the matching parent, and since the slug value, sub_test_1 doesn't match any of the parent values this array order is unimportant, so that array can be located anywhere within the array.
How can I do this? I'm thinking of just looping through the array somehow and trying to determine if the slug is in any of the parents, and just do a reordering somehow...
In short, the slug needs to be ordered before the parent ONLY if there is a parent that matches a slug within the array. Otherwise, if no match is found, the order isn't important.
A: As Niko suggested, databases support powerful sorting functionality, so you normally can best solve this by telling the database in which order to return the data. If the data is queried with SQL, that's the ORDER BY clause. This is specified in the documentation of your database, assuming you're using MySQL 5.0: http://dev.mysql.com/doc/refman/5.0/en/sorting-rows.html
If you can not influence the order on the database level, you're in the need to sort the array in PHP. You actually have an array of arrays, in which the outer array is just a list having the id (primary key) of each row and the other fields as a fieldname -> value array as a value (inner array).
Your sort is *user-defined` - you specify the sort order. A common way is to have a sort function that compares two entries which each other. That sort function needs to decide which of those two is of a higher sort-order than the other (or both have the same weight). In you case one item is higher than the other if one is the child of the other.
That's the general principle. You define the sort function that decides (the so called callback function), and PHP takes care to feed it with the array data to sort with the usortDocs function.
A sub-problem you need to solve then is to decide whether or not a child exists in the whole array (an item with a slug having the same value as parent). As this all looks like it can be a bit more complex, it's wise to encapsulate this all into a class of it's own.
Example / Demo:
class menuButtons
{
/**
* @var array
*/
private $buttons;
public function __construct(array $buttons)
{
$this->buttons = $buttons;
}
public function sortChildsFirst()
{
$buttons = $this->buttons;
usort($buttons, array($this, 'sortCallback'));
return $buttons;
}
private function sortCallback($a, $b)
{
// an element is more than any other if it's parent
// value is any other slugs value
if ($this->slugExists($a['parent']))
return 1;
return -1;
}
private function slugExists($slug)
{
foreach($this->buttons as $button)
{
if ($button['slug'] === $slug)
return true;
}
return false;
}
}
$buttons = new menuButtons($new_menu_buttons);
$order = $buttons->sortChildsFirst();
Note: This code is exploiting the fact that your sort order is only roughly specified. You only wrote that you need to have children before parents, so if you take all children first, this will always be the case. It's not that each parent will directly follow the child.
Nevertheless, this skeleton class can work as a base to further improve the search functionality as it's fully encapsulated. You can even change the whole sort method, e.g. to completely write one of your own even w/o usort, like outlined below. The main code does not need to change as it's only making use of the sortChildsFirst method.
A: You can sort an array once populated using the usort() function.
http://php.net/manual/en/function.usort.php
A: Since your structure is tree-alike, the first thing that comes to mind is to build a tree out of it. It goes like this:
$tree = array();
foreach($array as $e) {
$p = $e['parent'];
$s = $e['slug'];
if(!isset($tree[$p]))
$tree[$p] = new stdclass;
if(!isset($tree[$s]))
$tree[$s] = new stdclass;
$tree[$s]->data = $e;
$tree[$p]->sub[] = $tree[$s];
}
This creates a set of objects, with the members data and sub = list of child objects.
Now we iterate the tree and for each "root" node, add it and its children to the sorted array:
$out = array();
foreach($tree as $node)
if(!isset($tree[$node->data['parent']]))
add($out, $node);
where add() is
function add(&$out, $node) {
if(isset($node->data))
$out[] = $node->data;
if(isset($node->sub))
foreach($node->sub as $n)
add($out, $n);
}
hope this helps.
A: Ok, first let me thank you all for your detailed explanations. They are very intuitive. However, I found another way, can you guys let me know if you spot anything wrong with this method here please?
Click here to see a Demo of this working!
$temp_buttons = array();
foreach($new_menu_buttons as $buttons)
$temp_buttons[$buttons['parent']] = $buttons['slug'];
dp_sortArray($new_menu_buttons, $temp_buttons, 'slug');
// The $new_menu_buttons array is now sorted correctly! Let's check it...
var_dump($new_menu_buttons);
function dp_sortArray(&$new_menu_buttons, $sortArray, $sort)
{
$new_array = array();
$temp = array();
foreach ($new_menu_buttons as $key => $menuitem)
{
if (isset($sortArray[$menuitem[$sort]]))
{
$new_array[] = $menuitem;
$temp[$menuitem['parent']] = $menuitem['slug'];
unset($new_menu_buttons[$key]);
}
}
$ordered = array();
if (!empty($new_array))
{
foreach ($new_array as $key => $menuitem)
{
if (isset($temp[$menuitem[$sort]]))
{
$ordered[] = $menuitem;
unset($new_array[$key]);
}
}
}
else
{
$new_menu_buttons = $new_menu_buttons;
return;
}
$new_menu_buttons = array_merge($ordered, $new_array, $new_menu_buttons);
}
Seems to work in all instances that I tested, but ofcourse, their could be a flaw in it somewhere. What do you all think of this?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565620",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Lockable Surface in WPF I want a custom Control in WPF which have a appearance similar to HTML, we use for showing Images in the centre of the screen with the whole screen locked and only image is showing.
I dont want to show images, I want to show UserControls within this section.
Can someone give suggestions of this?
A: In Windows applications this is generally achieved using a modal dialog, i.e. you create a normal WPF window and show it using ShowDialog.
A: In your Window, put all your controls in a single Grid, with a Border control (that contains your image) as the last item in the Grid (which means it will display on top of the other items). Toggle its Visibility via binding or code. Adjust styles as required.
<Window>
<Grid>
<!-- window controls go here --->
<Border Visibility="..." Background="#80000000"> <!-- EDITED -->
<!-- overlaid image (and/or other controls) goes here --->
<Image
Source="..."
Width="..."
Height="..."
HorizontalAlignment="Center"
VerticalAlignment="Center" />
</Border>
<Grid>
</Window>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565621",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Compile test program with wxWidgets in MAC OS: MAC X 10.7.0
The Mac OS X install an older version of wxMac(wxMac-2.8.8.1) in /usr, but I install a newer one(wxMac-2.8.12.0) in /usr/local. To install it, I compile the new one with the flag:
arch_flags="-arch i386"
./configure CFLAGS="$arch_flags" CXXFLAGS="$arch_flags" CPPFLAGS="$arch_flags" LDFLAGS="$arch_flags" OBJCFLAGS="$arch_flags" OBJCXXFLAGS="$arch_flags" --enable-unicode --enable-debug --disable-shared
Then I write a simple program(hello2.cpp) to test it:
#include "wx/wx.h"
class HelloWorldApp : public wxApp
{
public:
virtual bool OnInit();
private:
wxButton *button;
};
IMPLEMENT_APP(HelloWorldApp)
bool HelloWorldApp::OnInit()
{
wxFrame *frame = new wxFrame((wxFrame*) NULL, -1, _T("Hello wxWidgets World"));
frame->CreateStatusBar();
frame->SetStatusText(_T("Hello World"));
button = new wxButton((wxFrame *)frame, -2, _T("123"));
frame->Show(TRUE);
SetTopWindow(frame);
return true;
}
I compile this test program in the command line with the flag:
g++ hello2.cpp /usr/local/bin/wx-config --cxxflags --libs -o hello2
But I receive some warnings and errors. I am a newbie in Mac programming, so I don't know the reason. I just have to say: help!
Here is the result of compiling:
ld: warning: in /usr/local/lib/libiconv.dylib, file was built for unsupported file format which is not the architecture being linked (i386)
Undefined symbols:
"_libiconv_open", referenced from:
wxMBConv_iconv::wxMBConv_iconv(wchar_t const*)in libwx_base_carbonud-2.8.a(baselib_strconv.o)
wxMBConv_iconv::wxMBConv_iconv(wchar_t const*)in libwx_base_carbonud-2.8.a(baselib_strconv.o)
wxMBConv_iconv::wxMBConv_iconv(wchar_t const*)in libwx_base_carbonud-2.8.a(baselib_strconv.o)
wxMBConv_iconv::wxMBConv_iconv(wchar_t const*)in libwx_base_carbonud-2.8.a(baselib_strconv.o)
wxMBConv_iconv::wxMBConv_iconv(wchar_t const*)in libwx_base_carbonud-2.8.a(baselib_strconv.o)
wxMBConv_iconv::wxMBConv_iconv(wchar_t const*)in libwx_base_carbonud-2.8.a(baselib_strconv.o)
wxMBConv_iconv::wxMBConv_iconv(wchar_t const*)in libwx_base_carbonud-2.8.a(baselib_strconv.o)
wxMBConv_iconv::wxMBConv_iconv(wchar_t const*)in libwx_base_carbonud-2.8.a(baselib_strconv.o)
"_libiconv", referenced from:
wxMBConv_iconv::GetMBNulLen() const in libwx_base_carbonud-2.8.a(baselib_strconv.o)
wxMBConv_iconv::WC2MB(char*, wchar_t const*, unsigned long) constin libwx_base_carbonud-2.8.a(baselib_strconv.o)
wxMBConv_iconv::WC2MB(char*, wchar_t const*, unsigned long) constin libwx_base_carbonud-2.8.a(baselib_strconv.o)
wxMBConv_iconv::MB2WC(wchar_t*, char const*, unsigned long) constin libwx_base_carbonud-2.8.a(baselib_strconv.o)
wxMBConv_iconv::MB2WC(wchar_t*, char const*, unsigned long) constin libwx_base_carbonud-2.8.a(baselib_strconv.o)
wxMBConv_iconv::wxMBConv_iconv(wchar_t const*)in libwx_base_carbonud-2.8.a(baselib_strconv.o)
wxMBConv_iconv::wxMBConv_iconv(wchar_t const*)in libwx_base_carbonud-2.8.a(baselib_strconv.o)
"_libiconv_close", referenced from:
wxMBConv_iconv::~wxMBConv_iconv()in libwx_base_carbonud-2.8.a(baselib_strconv.o)
wxMBConv_iconv::~wxMBConv_iconv()in libwx_base_carbonud-2.8.a(baselib_strconv.o)
wxMBConv_iconv::~wxMBConv_iconv()in libwx_base_carbonud-2.8.a(baselib_strconv.o)
wxMBConv_iconv::~wxMBConv_iconv()in libwx_base_carbonud-2.8.a(baselib_strconv.o)
wxMBConv_iconv::~wxMBConv_iconv()in libwx_base_carbonud-2.8.a(baselib_strconv.o)
wxMBConv_iconv::~wxMBConv_iconv()in libwx_base_carbonud-2.8.a(baselib_strconv.o)
ld: symbol(s) not found
collect2: ld returned 1 exit status
A: I uninstall wxMac-2.8.12.
I installl wxWidgets-2.9.2(./configure --enable-unicode --enable-debug --disable-shared)
I compile the test program with g++ hello2.cpp `/usr/local/bin/wx-config --cxxflags --libs` -o hello2 again. There only one warning:
ld: warning: in /System/Library/Frameworks//QuickTime.framework/QuickTime, missing required architecture x86_64 in file
I think that's OK.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565623",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is there a way to override the "key" function for list.max() and list.sort() in the class of the list items? I have multiple subclasses of a superclass that store something in a instance_of_a_class.value and I override __cmp__() to provide reasonable ==, <, > etc. comparisons.
However, I have multiple places in my code where I do
min(list_of_instances_of_class, key=lambda _: _.value) or max(list_of_instances_of_class, key=lambda _: _.value) and an occasional sorted(...
Is there a function to override in the class so that I don't have to specify the key function for each call to the said functions or do I need to subclass list and override the max, min and sorted methods?
A: Just implement __lt__:
class Obj(object):
def __init__(self, value):
self.value = value
def __lt__(self, other):
return self.value < other.value
def __repr__(self):
return 'Obj(%r)' % self.value
obj_list = [Obj(2), Obj(1), Obj(4), Obj(3)]
print max(obj_list)
print min(obj_list)
print sorted(obj_list)
__cmp__ is deprecated, and all of the functions that you mentioned use only __lt__ not the other comparisons.
If for some reason you really can't have them compare this way, you can do something like:
from operator import attrgetter
from functools import partial
valget = attrgetter('value')
maxval = partial(max, key=valget)
minval = partial(max, key=valget)
sortedval = partial(sorted, key=valget)
sortval = partial(list.sort, key=valget)
Where you call them just as maxval(obj_list) instead of max(obj_list) etc., and sortval(obj_list) to sort in-place instead of obj_list.sort()
A: Not directly, no. The simplest thing would probably be to define specific functions that you use in place of min/max/sorted. e.g.
from functools import partial
min_myclass = partial(min, key = operator.attrgetter('value'))
max_myclass = partial(max, key = operator.attrgetter('value'))
...
min_myclass(list_of_instances_of_myclass)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Array selector function by property value I have:
var array = [ { key: '1' }, { key: '2' }, { key: '3' } ]
I want:
var obj = getFirstItem(array, 'key', '2');
And as a result:
obj = { key: '2' }
Is there such function in JavsScript or jQuery?
A: I don't know of a built in function. However, it would be trivial to implement it yourself:
var data = [ { key: '1' }, { key: '2' }, { key: '3' } ];
function getFirstItem(input, key, value) {
for(var i = 0; i < input.length; i++) {
if(input[i][key] === value)
return input[i];
}
}
console.log(getFirstItem(data, "key", 2));
A: I don't think jQuery is really necessary here. The function is as simple as:
function getFirstItem(arr, k, v){
for(var i=0;i<arr.length;i++){
var obj = arr[i];
if(obj[k] == v)
return obj;
}
return null;
}
Live example: http://jsfiddle.net/QARAd/
A: Like others have said it's quite simple to just loop over the array yourself.
However there is a filter method in JS 1.5 (Apparently not supported in IE8 and lower, although the link has a compatibility work around)
var myarray = [ { key: '1' }, { key: '2' }, { key: '3' } ]
function getFirstItem(myarray, key) {
var result = myarray.filter(function(element, index, array) {
return element.key == key;
});
if (result.length)
return result[0];
return null;
}
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter
JSFiddle Example
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565631",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Preview Image while file uploading using "UPLOADIFY" I am uploading the file using the script from "UPLOADIFY" site, The image is uploading successfully, But Now I want to preview the image on my UI Page, I have written some script (Converted image into Base 64 Encrypted code) to preview the image.
Both the functionalities are working fine individually, But I am unable to execute both functionalities one by one. Here is the code I have used Please help Me.
$(document).ready(function() {
$('#file_upload').uploadify({
'uploader' : '/js/uploadify/uploadify.swf',
'script' : 'index.php',
'fileExt' : '*.jpeg;*.gif;*.png',
'fileDesc' : 'Image Files',
'buttonText' : 'Select File',
'sizeLimit' : 102400,
'onSelect' : function() {preview(this);}
});
});
A: I'm assuming you would like to preview the image onSelect... That is not possible due to security measures in modern browsers which prevent local (user-local) images from being displayed. This means that in order to preview the image you must first upload it (for example, set the upload mode to 'auto' and then onComplete add the temporary image to a div) and then the user would have a button of some sort to 'confirm' that the temporary image is indeed the desired one. That button would then move the temporary image to a definitive folder and add it to the database.
Sorry for not adding code, but I think you can easily manage to do it on your own. There are some great tutorials around too.
Cheers
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565637",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why i am not able to load Advertisement sometimes? I have implemented AdMob to My Application from this Docunemtation: Here
I can see the ad perfectly as I want. But some times I cant able to see the advertisements. If i refresh the activity, it will show me the Advertisement again. and ita work perfectly.
But when i am not able to see the advertisement at that time i got the message at catlog like:
09-27 12:58:54.451: INFO/Ads(940): onFailedToReceiveAd(Ad request successful, but no ad returned due to lack of ad inventory.)
I dont know where is the Problem ?
Why I am not able to see the Add sometimes ??
Please give the way if I am wrong regarding it.
Thanks.
A: AdMob ads appear at a specified interval depending on the network traffic. If there is no congestion in the traffic, the ads appear each time you see your app else you see the message in your log saying no ad returned. However have a quick walkthrough with your code and keep testing your app after giving some gap.
With regard to refresh, in your AdMob account, go to setting, there you can specify the time when do you want the ads to refresh. There is still a possibility of the same ads appearing again and again.
Why dont you use the latest Google AdSense-SDK? Google AdSense has good ads.
A: I was also faced this issue but There is no any issue at our end, Admob is not appear sometime so may be it is problem at AdMob end like as server problem, netproblem...etc
A: All that is needed to add AdSense ads is to press a button to enable Google AdSense in the App Settings in your app on admob.com.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Indent the text in a UITextField My question is as simple as the title, but here's a little more:
I have a UITextField, on which I've set the background image. The problem is that the text hugs so closely to it's edge, which is also the edge of the image. I want my text field to look like Apple's, with a bit of horizontal space between the background image and where the text starts.
A: You have to subclass and override textRectForBounds: and editingRectForBounds:. Here is a UITextfield subclass with custom background and vertical and horizontal padding:
@interface MyUITextField : UITextField
@property (nonatomic, assign) float verticalPadding;
@property (nonatomic, assign) float horizontalPadding;
@end
#import "MyUITextField.h"
@implementation MyUITextField
@synthesize horizontalPadding, verticalPadding;
- (CGRect)textRectForBounds:(CGRect)bounds {
return CGRectMake(bounds.origin.x + horizontalPadding, bounds.origin.y + verticalPadding, bounds.size.width - horizontalPadding*2, bounds.size.height - verticalPadding*2);
}
- (CGRect)editingRectForBounds:(CGRect)bounds {
return [self textRectForBounds:bounds];
}
@end
Usage:
UIImage *bg = [UIImage imageNamed:@"textfield.png"];
CGRect rect = CGRectMake(0, 0, bg.size.width, bg.size.height);
MyUITextField *textfield = [[[MyUITextField alloc] initWithFrame:rect] autorelease];
textfield.verticalPadding = 10;
textfield.horizontalPadding = 10;
[textfield setBackground:bg];
[textfield setBorderStyle:UITextBorderStyleNone];
[self.view addSubview:textfield];
A: My 2 cents:
class PaddedTextField : UITextField {
var insets = UIEdgeInsets.zero
var verticalPadding:CGFloat = 0
var horizontalPadding:CGFloat = 0
override func textRect(forBounds bounds: CGRect) -> CGRect {
return CGRect(x: bounds.origin.x + insets.left, y: bounds.origin.y + insets.top, width: bounds.size.width - (insets.left + insets.right), height: bounds.size.height - (insets.top + insets.bottom));
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
return textRect(forBounds: bounds)
}
}
A: A good approach to add padding to UITextField is to subclass UITextField , overriding the rectangle methods and adding an edgeInsets property. You can then set the edgeInsets and the UITextField will be drawn accordingly. This will also function correctly with a custom leftView or rightView set.
OSTextField.h
#import <UIKit/UIKit.h>
@interface OSTextField : UITextField
@property (nonatomic, assign) UIEdgeInsets edgeInsets;
@end
OSTextField.m
#import "OSTextField.h"
@implementation OSTextField
- (id)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
self.edgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
}
return self;
}
-(id)initWithCoder:(NSCoder *)aDecoder{
self = [super initWithCoder:aDecoder];
if(self){
self.edgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
}
return self;
}
- (CGRect)textRectForBounds:(CGRect)bounds {
return [super textRectForBounds:UIEdgeInsetsInsetRect(bounds, self.edgeInsets)];
}
- (CGRect)editingRectForBounds:(CGRect)bounds {
return [super editingRectForBounds:UIEdgeInsetsInsetRect(bounds, self.edgeInsets)];
}
@end
A: This is the quickest way I've found without doing any subclasses:
UIView *spacerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
[textfield setLeftViewMode:UITextFieldViewModeAlways];
[textfield setLeftView:spacerView];
In Swift:
let spacerView = UIView(frame:CGRect(x:0, y:0, width:10, height:10))
textField.leftViewMode = UITextFieldViewMode.Always
textField.leftView = spacerView
Swift 5:
let spacerView = UIView(frame:CGRect(x:0, y:0, width:10, height:10))
textField.leftViewMode = .always
textField.leftView = spacerView
A: I turned this into a nice little extension for use inside Storyboards:
public extension UITextField {
@IBInspectable public var leftSpacer:CGFloat {
get {
return leftView?.frame.size.width ?? 0
} set {
leftViewMode = .Always
leftView = UIView(frame: CGRect(x: 0, y: 0, width: newValue, height: frame.size.height))
}
}
}
A: I suggest converting your UITextField to a UITextView and setting the contentInset. For example to indent by 10 spaces:
textview.contentInset=UIEdgeInsetsMake(0, 10, 0, 0);
A: Sometimes the leftView of the textField is a Apple's magnifying glass image.
If so, you can set an indent like this:
UIView *leftView = textField.leftView;
if (leftView && [leftView isKindOfClass:[UIImageView class]]) {
leftView.contentMode = UIViewContentModeCenter;
leftView.width = 20.0f; //the space you want indented.
}
A: If you don't want to create @IBOutlet's could simply subclass (answer in Swift):
class PaddedTextField: UITextField {
override func awakeFromNib() {
super.awakeFromNib()
let spacerView = UIView(frame:CGRect(x: 0, y: 0, width: 10, height: 10))
leftViewMode = .always
leftView = spacerView
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565645",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "79"
}
|
Q: Comparing files between 2 workspaces in Eclipse I've got two different workspaces for two different projects I'm working on, however some of the code I checked out is from the same package spread across the two workspaces...and I have a feeling I've changed different parts of the packages across the two workspaces
Is there anyway to use the "Compare With" feature of Eclipse across the two workspaces? The only way I've found is to take the file, rename them, put them in the same director, refresh, and then select the two files and compare with...is there something better/easier?
A: i really like the AnyEdit Plugin (http://andrei.gmxhome.de/anyedit/). It provides some adittional "Compare With" Functions:
*
*Compare / Replace with
Clipboard Editors, Navigator, Project Explorer If some text is selected in editor, then only this selection will be compared, otherwise entire editor
*Compare / Replace with
Workspace File... Editors, Navigator, Project Explorer If some text is selected in editor, then only this selection will be compared, otherwise entire editor
*Compare / Replace with
External File... Editors, Navigator, Project Explorer If some text is selected in editor, then only this selection will be compared, otherwise entire editor
*Compare / Replace with
Opened Editor...
Works very good to me.
A: Something better:
If you work with (and modify) the same source code base in different workspaces, I'd rather create one workspace containing both projects as well as the shared code. Then use working sets to switch between your different projects. In my opinion everything else is a recipe for disaster. Using this approach you can easily use eclipse's built-in compare features.
A: INFO:
If you want to compare two file, you can use any external comparing editors other than Eclipse compare.
Ex : Beyond Compare Editor.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565648",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Getting list of file handlers in an eclipse rcp project I'm developing a RCP application. In a project workspace, I get file/folder handlers of known files to me by getFile(String name) and getFolder(String name) methods.
Is there a method which returns array/list of files which matches a regex? (Like getFiles("*.txt")).
EDIT:
This works.
IResource members[] = aFolder.members();
for (int i = 0; i < members.length; i++) {
if (members[i].getName().endsWith(".java")) {
//Do something
}
}
A: If you know that the files/folders are all immediate children of the specified folder - aFolder above - then you code is fine (see note below).
But if you want to access files at any level in the tree, then I would recommend to use the visitor construct: IResource.accept(IResourceProxyVisitor visitor, int memberFlags). There are a number of different versions of this, so you better check which match your needs best.
Note: One advantage of the IResourceProxyVisitor over the other methods and over the explicit version that you have shown, is the fact that this version does not check the file system whether the resource still exists or not and therefore it is extremely fast.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565653",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I remove all but some records based on a threshold? I have a table like this:
CREATE TABLE #TEMP(id int, name varchar(100))
INSERT INTO #TEMP VALUES(1, 'John')
INSERT INTO #TEMP VALUES(1, 'Adam')
INSERT INTO #TEMP VALUES(1, 'Robert')
INSERT INTO #TEMP VALUES(1, 'Copper')
INSERT INTO #TEMP VALUES(1, 'Jumbo')
INSERT INTO #TEMP VALUES(2, 'Jill')
INSERT INTO #TEMP VALUES(2, 'Rocky')
INSERT INTO #TEMP VALUES(2, 'Jack')
INSERT INTO #TEMP VALUES(2, 'Lisa')
INSERT INTO #TEMP VALUES(3, 'Amy')
SELECT *
FROM #TEMP
DROP TABLE #TEMP
I am trying to remove all but some records for those that have more than 3 names with the same id. Therefore, I am trying to get something like this:
id name
1 Adam
1 Copper
1 John
2 Jill
2 Jack
2 Lisa
3 Amy
I am not understanding how to write this query. I have gotten to the extent of preserving one record but not a threshold of records:
;WITH FILTER AS
(
SELECT id
FROM #TEMP
GROUP BY id
HAVING COUNT(id) >=3
)
SELECT id, MAX(name)
FROM #TEMP
WHERE id IN (SELECT * FROM FILTER)
GROUP BY id
UNION
SELECT id, name
FROM #TEMP
WHERE id NOT IN (SELECT * FROM FILTER)
Gives me:
1 Robert
2 Rocky
3 Amy
Any suggestions? Oh by the way, I don't care what records are preserved while merging.
A: You can do it using CTE
CREATE TABLE #TEMP(id int, name varchar(100))
INSERT INTO #TEMP VALUES(1, 'John')
INSERT INTO #TEMP VALUES(1, 'Adam')
INSERT INTO #TEMP VALUES(1, 'Robert')
INSERT INTO #TEMP VALUES(1, 'Copper')
INSERT INTO #TEMP VALUES(1, 'Jumbo')
INSERT INTO #TEMP VALUES(2, 'Jill')
INSERT INTO #TEMP VALUES(2, 'Rocky')
INSERT INTO #TEMP VALUES(2, 'Jack')
INSERT INTO #TEMP VALUES(2, 'Lisa')
INSERT INTO #TEMP VALUES(3, 'Amy')
SELECT *
FROM #TEMP;
WITH CTE(N) AS
(
SELECT ROW_NUMBER() OVER(PARTITION BY id ORDER BY id)
FROM #Temp
)
DELETE CTE WHERE N>3;
SELECT *
FROM #TEMP;
DROP TABLE #TEMP
A: I will change your select like this (not tested)
select name from #temp group by name having count(id) > 3
then you can implement your query in a delete statement using your select as a where clause
A: in inner query you can use row_number function over (partition by id)
and then in outer query you have to give condition like below
select id,name from (
SELECT id,name, row_number() over (partition by id order by 1) count_id FROM #test
group by id, name )
where count_id <=3
A: If i got your question right, you need to get rows when id occurrence 3 or more times
select t1.name,t1.id from tbl1 t1
inner join tbl1 t2 on t1.id = t2.id
group by t1.name, t1.id
having count(t1.id) > 2
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565664",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Nancy with Razor: Views are cached, making development really hard I'm new to Nancy and Razor (and MVC). If I make a change to a view I have to restart the application somehow (change web.config, restart dev server etc) for the change to take affect.
I think the cache may be Razor's static dictionary? It stores each compiled view?
No doubt this is great for production, but how do I turn it off for development?
I want to be able to modify a view, save, build and see the change.
Any advise greatly appreciated. Thanks.
A: This will be fixed for 0.8, but for now you can turn the caching off by adding a line to your bootstrapper's InitializeInternal like this:
public class CustomBootstrapper : DefaultNancyBootstrapper
{
protected override void InitialiseInternal(TinyIoC.TinyIoCContainer container)
{
base.InitialiseInternal(container);
#if DEBUG
StaticConfiguration.DisableCaches = true;
#endif
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565669",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Open video from a URL on webView Iphone In my Iphone app I open a URL on a webview.This URL contains videos. When I open a video it is not played fullscreen and if I rotate the screen it is not rotating. How can I manage this video ? I don't have any player. Can anyone help me ?
Please help...
A: these two links can help you ... especially the first one..
http://iphoneincubator.com/blog/audio-video/how-to-play-youtube-videos-within-an-application
http://apiblog.youtube.com/2009/02/youtube-apis-iphone-cool-mobile-apps.html
A: You do not technically need a "media player", just load a supported media URL into a UIWebView and it should play automatically. I would not recommend making this a habit, but its a quick solution.
A: i think your webpage contains <video> tag in it. That's why its not getting full screen.
try to play the video with <a href="url of your video">video</a>
You will surely get the full screen video
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565670",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Upload file that is in the cpan database I have a small module on CPAN - http://search.cpan.org/~bessarabv/.
I made a mistake and at first uploaded file SQL-Easy-0.04.tar.gz and only then SQL-Easy-0.03.tar.gz After that CPAN thought that the 0.03 is the latest version of the module.
To fix this problem I've requested the deletion of the 0.04.
0.04 was deleted and the 0.03 became the latest version. Now I'm uploading file SQL-Easy-0.04.tar.gz to cpan, but I get the error when I try to upload It:
Submitting query
Could not enter the URL into the database. Reason:
Duplicate entry 'B/BE/BESSARABV/SQL-Easy-0.04.tar.gz' for key 1
This indicates that you probably tried to upload a file that is
already in the database. You will most probably have to rename
your file and try again, because PAUSE doesn't let you upload
a file twice.
I'm not sure that this is a correct behavior: I've deleted the file, so the record in the database should also be deleted.
Is there any way of uploading file to cpan without renaming it?
A: Release version 0.05 - there is no harm in having multiple versions, or even skipping a version number if you need to (do keep a Changes file as part of your distributions and put in comments about what has changed, even if "0.05 released because of mistake in 0.04").
As pointed out in the comments, people might have 0.04 installed already (even if it was only uploaded an hour or so ago). Releasing a different 0.04 would prevent them getting the upgrade and also cause other problems with CPAN Testers etc which is why the system stops you uploading something of the same name.
The delete option is there so you can remove older versions, not so you can re-upload them.
A: Is there any way of uploading file to cpan without renaming it? Well, "PAUSE doesn't let you upload a file twice" would seem to say no.
A: Forget about 0.04, just upload 0.05, no kittens or baby seals will die.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565671",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Generics in Scala: implementing an interface/trait twice? Given a generic interface such as the following
interface I<T> {
void m(T t);
}
I can in C# create a class that implements I twice (or more) with different types supplied for T, e.g.
class C : I<int>, I<String> {
public void m(int i) { }
public void m(String s) { }
}
This cannot be done in Java due to erasure of the generic type info, but can something like this be achieved in Scala?
A: No. Mixing in the same trait is only possible in Scala if the 2 types with which the trait (interface) is parametrized with types that conform to each other and the trait is not mixed into the same class twice directly. To ensure that the 2 types conform to each other, you will generally have to make the type parameter covariant (+).
For example, this is not allowed:
scala> trait A[+T] { def foo: T = sys.error() }
defined trait A
scala> class C extends A[AnyRef] with A[String]
<console>:8: error: trait A is inherited twice
class C extends A[AnyRef] with A[String]
But this is:
scala> trait A[+T] { def foo: T = sys.error() }
defined trait A
scala> class C extends A[AnyRef]
defined class C
scala> class B extends C with A[String]
defined class B
Note that in this case you will not obtain the overloading semantics as is the case with C#, but the overriding semantics - all the methods in A with the conforming signature will be fused in one method with the most specific signature, choosing the method according to linearization rules, rather than having one method for each time you've mixed the trait in.
A: No, it can't. Generally what I do in this case is
class C {
object IInt extends I[Int] { ... }
object IString extends I[String] { ... }
...
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565673",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: enumerating all possible strings of length K from an alphabet in Python
Possible Duplicate:
is there any best way to generate all possible three letters keywords
how can I enumerate all strings of length K from an alphabet L, where L is simply a list of characters? E.g. if L = ['A', 'B', 'C'] and K = 2, I'd like to enumerate all possible strings of length 2 that can be made up with the letters 'A', 'B', 'C'. They can be reused, so 'AA' is valid.
This is essentially permutations with replacement, as far as I understand. if theres a more correct technical term for this, please let me know.... its essentially all strings of length K that you can make by choosing ANY letter from the alphabet L, and possibly reusing letters, in a way that is sensitive to order (so AB is NOT identical to BA according to this.) is there a clearer way to state this?
in any case i believe the solution is:
[ ''.join(x) for x in product(L, repeat=K) ]
but i am interested in other answers to this, esp. naive approaches versus fast Pythonic ones, and discussions of speed considerations.
A: this is part of the Python Documentation
EDIT2: of course the right answer is the product, thanks for the comment
print [''.join(x) for x in product('ABC', repeat=3)]
prints 27 elements
['AAA', 'AAB', 'AAC', 'ABA', 'ABB', 'ABC', 'ACA', 'ACB', 'ACC', 'BAA', 'BAB',
'BAC', 'BBA', 'BBB', 'BBC', 'BCA', 'BCB', 'BCC', 'CAA', 'CAB', 'CAC', 'CBA',
'CBB', 'CBC', 'CCA', 'CCB', 'CCC']
@agf gave the right answer before
A: You can use itertools:
n = 3
itertools.product(*['abc']*n)
This gives you 27 elements as you expected.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565675",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to add entity to multiple tables? I have 2 tables in my DB: Students and StudentsHistory. The idea is that every change in the Students table must create a new record in the StudentsHistory table (e.g. when I edit a student, 2 operations must be performed: UPDATE on Students and INSERT on StudentsHistory).
How can I do this with Entity Framework 4.1 Code-First without creating 2 classes and having them mapped? I want to have only Student class and somehow tell EF to save the Student object to 2 tables.
Anyone can help?
PS It should be done in code, not using SQL triggers or something.
A: It is not possible. You must create two classes, map them and handle creation in your business logic. The auto magic you are looking for can be performed only by database triggers.
A: Like Ladislav said, you cannot map 2 tables to one entity. You may want to think about creating an audit for student history.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565680",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jQuery modification needed in script Here is a jQuery script for sliding in letters, but how do I remove the last class of "fade out" so that the letters remain at their final position? Here is the demo:
http://blog.waiyanlin.net/example/jquery/flyingtext.html
and here is the script for it:
$(document).ready(function(){
$('.container .flying-text').css({opacity:0});
$('.container .active-text').animate({opacity:1, marginLeft: "350px"}, 1000);
var int = setInterval(changeText, 1000);
function changeText(){
var $activeText = $(".container .active-text");
var $nextText = $activeText.next();
if($activeText.next().length == 0) $nextText = $('.container .flying-text:first');
$activeText.animate({opacity:0}, 1000);
$activeText.animate({marginLeft: "-100px"});
$nextText.css({opacity: 0}).addClass('active-text').animate({opacity:1, marginLeft: "350px"}, 500, function() {
$activeText.removeClass('active-text');
});
}
});
A: This is extremely easy, 2 modifications are required. Remove animation, and clear timeout. You should have been able to figure this out yourself.
$(document).ready(function(){
$('.container .flying-text').css({opacity:0});
$('.container .active-text').animate({opacity:1, marginLeft: "350px"}, 1000);
var intval = setInterval(changeText, 1000);
function changeText() {
var $activeText = $(".container .active-text");
var $nextText = $activeText.next();
if ($activeText.next().length == 0) clearInterval(intval);
$nextText.css({opacity: 0}).addClass('active-text').animate({opacity:1, marginLeft: "350px"}, 500, function(){
$activeText.removeClass('active-text');
});
}
});
As per comments, here is a link to the working jsfiddle example: http://jsfiddle.net/Q8ZGA/
A: If I understand you correct you need to leave text after animation. In this case remove this string:
$activeText.animate({opacity:0}, 1000);
$activeText.animate({marginLeft: "-100px"});
Because you are fading it out.
Code (without interval): http://jsfiddle.net/uedt6/4/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7565681",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.