text
stringlengths 8
267k
| meta
dict |
---|---|
Q: How to call Html.Display for a custom object, not the whole Model? I have the following view-model for my MVC3 Razor view:
public class UserProfileModel
{
public Person[] Persons { get; set; }
//some other fields
}
I want to display all the persons in my Razor view like:
foreach (var person in Model.Persons)
{
<div>
@* some custom formatting *@
@Html.Display(person)
</div>
}
@Html.Display or @Html.DisplayFor seems to not work for me..
I can create a separate stongly-typed view using Person as a model and call @Html.DisplayForModel there, but is there a way to go without a separate view?
A: Create a partial view file called Person.cshtml inside ~/Views/Shared/DisplayTemplates. Make it strongly typed to Person class.
Implement the structure of your view.
Then when you call it like below (on your case), you will get what you expected :
foreach (var person in Model.Persons)
{
<div>
@* some custom formatting *@
@Html.DisplayFor(m => person)
</div>
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620573",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Can't get Spring to inject my dependencies I've been trying to get Spring to inject an @Autowired dependency into my application without avail. What am I doing wrong?
I created a bean called TimeService. Its job is to return the current time to anyone that asks.
package com.foxbomb.springtest.domain.time;
import java.util.Date;
import org.springframework.stereotype.Service;
@Service
public class TimeService {
public TimeService() {
super();
System.out.println("Instantiating TimeService...");
}
public Date getTime() {
return new Date();
}
}
Of course, I need to tell Spring about this, so I added the following to web.xml:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
Great, and some Spring configuration:
<?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">
<context:annotation-config base-package="com.foxbomb.springtest.domain" />
</beans>
Now all we need is a calling class that would like to use this dependency. Unfortunately, the @Autowired here seems to do nothing:
package com.foxbomb.springtest;
import...
@Configurable
public class TimeManager {
public TimeManager() {
super();
System.out.println("Instantiating TimeManager...");
}
@Autowired
private TimeService timeService;
public Date getTime() {
return timeService.getTime();
}
}
And lastly, a JSP that wants to display the time:
<%@page import="com.foxbomb.springtest.ApplicationContextImpl"%>
<%@page import="com.foxbomb.springtest.TimeManager"%>
<html>
<head>
<title>Spring Test</title>
</head>
<body>
<h1>Autowired Dependencies....</h1>
<p>
Time is now <%=new TimeManager().getTime()%>!
</p>
</body>
</html>
But all I get is:
java.lang.NullPointerException
com.foxbomb.springtest.TimeManager.getTime(TimeManager.java:26)
A: When you access TimeManager object like this:
Time is now <%=new TimeManager().getTime()%>!
Spring does not know anything about this class. You are basically creating a new object, that's it!
Probably Spring creates an instance of TimeManager and injects dependencies properly (however you should use @Service rather than @Configuration annotation), but you are not using this instance in your JSP. Instead you are creating new, unmanaged instance, that is completely independent and unaware of Spring and dependencies...
I think this will work:
<%= WebApplicationContextUtils.
getWebApplicationContext(application).
getBean(TimeManager.class).
getTime() %>
Ugly? Sure. Because the whole approach of accessing services from JSP (view) is ugly. You should at least have a servlet that accesses Spring beans and puts result in request attributes. These attributes can then be accessed in JSP that you forward to - without ugly scriptlets.
If you really want to do this "the right" way, try Spring MVC or other popular Java web framework.
A: The @Autowire annotation in TimeManager was not recognized, because you told spring to start searching for annotation configuration information in the wrong package.
TimeManager is in com.foxbomb.springtest.
You have this configuration:
<context:annotation-config base-package="com.foxbomb.springtest.domain"/>
Notice that "com.foxbomb.springtest != com.foxbomb.springtest.domain".
Change your configuration to include this:
<context:annotation-config base-package="com.foxbomb.springtest"/>
Edit: Spring must instantiate TimeManager.
You will need to:
*
*Have TimeManager be a data member of the controller class.
*@Autowire TimeManager into the controller class (or get it from spring somehow).
*Add the TimeManager to some appropriate scope (maybe session, maybe request, maybe application).
*Access this TimeManager on your jsp page. Maybe something like this: It is now ${MyTimeManager.time} balonia watch time.
A: I tend to agree with @TomaszNurkiewicz; use a framework. However, a framework is way overkill for a lot of applications. If it's overkill for you, this answer details how to do it without all the manual work of getting the bean yourself. IMO doing it manually defeats the purpose.
A: You should be using @Component (or a child stereotype annotation) rather than @Configuration, and annotating your TimeManager with that. @Configuration is used for Java based container configuration, which is not what you are doing here.
A: Finally!
I got it working with the code in the above example. The trick was to set up Aspect/J and Weaving. This allows the @Configurable annotated class to automatically realize that its dependent on Spring to inject dependencies.
There wasn't much wrong with the base package :) I accidentally made a xml typo, trying to add the base-package attribute to the context:annotation-config tag. The correct definition was:
<context:annotation-config/>
<context:component-scan base-package="com.foxbomb.springtest"/>
I need actually eventually need to change it to com.foxbomb.springtext to include the class that was trying to access the bean too - as in the end it's also annotated.
Thanks everyone for your help!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620574",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Select the first radio button of multiple radio buttons groups with jQuery I would like to automatically select the first radio button of multiple radio buttons groups.
<div class="element">
<input type="radio" name="group1" value="1">
<input type="radio" name="group1" value="2">
<input type="radio" name="group1" value="3">
</div>
<div class="element">
<input type="radio" name="group2" value="1">
<input type="radio" name="group2" value="2">
<input type="radio" name="group2" value="3">
</div>
Here is the thing, while this works:
$('.element').each(function(){
$(this).find('input[type=radio]:first').attr('checked', true);
});
I can't figure out why I can't make it work using the :first selector using the each() method
The code below doesn't work: it only selects the first radio button in the first div, can you tell me why?
$('.element input[type=radio]:first').each(function(){
$(this).attr('checked', true);
});
Thanks
A: The simplest way is to use the :first-child selector. As opposed to :first, which only returns the first of the matched elements, :first-child will return any element that is the first child of its parent element:
//returns the first radio button in group1, and the first one in group2 as well.
$('.element input[type=radio]:first-child');
See Rob W's answer for an explanation of why your code isn't working.
A: The first selector loops through each .element. The second selector loops through each element input[type=radio]:first, which consists of only one element.
I've translated your code to a human-readable sequence:
*
*Select .elementGo through each .elementFind the first occurence of a radio input elementSet checked=true.
*Select the first radio input element which is a child of .element.Loop through each element which matches the selector (just one)Set checked=true.
Alternative ways:
//Alternative method
$('element').each(function(){
$('input[type=radio]', this).get(0).checked = true;
});
//Another method
$('element').each(function(){
$('input[type=radio]:first', this).attr('checked', true);
});
A: Try using nth-child:
$('.element').each(function(){
$(this).find('input[type=radio]:nth-child(1)').attr('checked', true);
});
A: You can also do this with Radio Button Class Name
<div class="element">
<input class="radio_btn" type="radio" name="group1" value="1">
<input class="radio_btn" type="radio" name="group1" value="2">
<input class="radio_btn" type="radio" name="group1" value="3">
</div>
<div class="element">
<input class="radio_btn" type="radio" name="group2" value="1">
<input class="radio_btn" type="radio" name="group2" value="2">
<input class="radio_btn" type="radio" name="group2" value="3">
</div>
<script>
$('.radio_btn:first').attr('checked', true);
</script>
A: For me, first-child did not work, and I did not use each for loop the elements,
This worked for me,
$('.element input[type=radio]:first').attr('checked', true);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620576",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Amazon Web Service Usage Cost through Command Line I am working on Amazon Web Service (EC2, S3) to set up an instances given the following detail on the account. (I don't have administrative rights to the Amazon account through the web browser)
*
*Amazon Account Number
*Access Key ID
*Secret Access Key
Do anyone know how can I check the total usage cost spent through command line interface? I wouldn't want to give the owner a surprise of how much Amazon have charged him at the end of the month.
P.S.: To date of writing Amazon does not provide account charges information through the command line or API (According to @Eric Hammond). If Amazon does in the later date, please give me a head up. Thanks!
A: Amazon AWS does not currently provide account charges information through the command line or API.
Accrued account charges can be viewed through a login on the AWS web site:
http://aws-portal.amazon.com/gp/aws/developer/account/index.html?ie=UTF8&action=activity-summary
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620578",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Individual and not continuous JTable's cell selection Is there any clean way to allow a user to select multiple non continuos cells of a JTable?
Or I'm forced to implement my own ListSelectionModel?
I played around with setCellSelectionEnabled() and setSelectionModel() methods on JTable but I can only select groups of continuous cells.
EDIT:
I tried @mKorbel nice SSCCE. It works fine for list but it seems not fully working on tables. Here's an SSCCE:
import java.awt.Component;
import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class TableSelection extends JFrame{
String[] columnNames = {"First Name",
"Last Name",
"Sport",
"# of Years",
"Vegetarian"};
Object[][] data = {
{"Kathy", "Smith",
"Snowboarding", new Integer(5), new Boolean(false)},
{"John", "Doe",
"Rowing", new Integer(3), new Boolean(true)},
{"Sue", "Black",
"Knitting", new Integer(2), new Boolean(false)},
{"Jane", "White",
"Speed reading", new Integer(20), new Boolean(true)},
{"Joe", "Brown",
"Pool", new Integer(10), new Boolean(false)}
};
public TableSelection(){
JPanel main= new JPanel();
JTable table = new JTable(data, columnNames){
@Override
protected void processMouseEvent(MouseEvent e) {
int modifiers = e.getModifiers() | InputEvent.CTRL_MASK;
// change the modifiers to believe that control key is down
int modifiersEx = e.getModifiersEx() | InputEvent.CTRL_MASK;
// can I use this anywhere? I don't see how to change the modifiersEx of the MouseEvent
MouseEvent myME = new MouseEvent((Component) e.getSource(), e.getID(), e.getWhen(), modifiers, e.getX(),
e.getY(), e.getXOnScreen(), e.getYOnScreen(), e.getClickCount(), e.isPopupTrigger(), e.getButton());
super.processMouseEvent(myME);
}
};
JScrollPane pane = new JScrollPane(table);
main.add(pane);
this.add(main);
this.setSize(800, 600);
this.setVisible(true);
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new TableSelection();
}
}
I can select non-contiguous row but not single cells. I mean, I would like to be able to select cell 0,0 and 3,3 for example.
A: *
*If isn't defined for JTable#setSelectionMode(ListSelectionModel.SINGLE_SELECTION), then CTRL + MOUSE_CLICK
*Or do you mean remember last selected?
*ListSelectionModel is used by both JTable and JList.
import java.awt.Component;
import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;
import javax.swing.*;
public class Ctrl_Down_JList {
private static void createAndShowUI() {
String[] items = {"Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat"};
JList myJList = new JList(items) {
private static final long serialVersionUID = 1L;
@Override
protected void processMouseEvent(MouseEvent e) {
int modifiers = e.getModifiers() | InputEvent.CTRL_MASK;
// change the modifiers to believe that control key is down
int modifiersEx = e.getModifiersEx() | InputEvent.CTRL_MASK;
// can I use this anywhere? I don't see how to change the modifiersEx of the MouseEvent
MouseEvent myME = new MouseEvent((Component) e.getSource(), e.getID(), e.getWhen(), modifiers, e.getX(),
e.getY(), e.getXOnScreen(), e.getYOnScreen(), e.getClickCount(), e.isPopupTrigger(), e.getButton());
super.processMouseEvent(myME);
}
};
JFrame frame = new JFrame("Ctrl_Down_JList");
frame.getContentPane().add(new JScrollPane(myJList));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
createAndShowUI();
}
});
}
A: Use MULTIPLE_INTERVAL_SELECTION, shown in How to Use Tables: User Selections.
Addendum: Because the MULTIPLE_INTERVAL_SELECTION of ListSelectionModel is also available to JList, you may be able to leverage the latter's HORIZONTAL_WRAP to get non-contiguous selection, as shown below.
Console:
[Cell:06]
[Cell:06, Cell:16]
[Cell:06, Cell:16, Cell:18]
[Cell:06, Cell:08, Cell:16, Cell:18]
Code:
import java.awt.*;
import java.util.Arrays;
import javax.swing.*;
import javax.swing.event.*;
/**
* @see http://stackoverflow.com/questions/7620579
* @see http://stackoverflow.com/questions/4176343
*/
public class ListPanel extends JPanel {
private static final int N = 5;
private DefaultListModel dlm = new DefaultListModel();
private JList list = new JList(dlm);
public ListPanel() {
super(new GridLayout());
for (int i = 0; i < N * N; i++) {
String name = "Cell:" + String.format("%02d", i);
dlm.addElement(name);
}
list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
list.setVisibleRowCount(N);
list.setCellRenderer(new ListRenderer());
list.addListSelectionListener(new SelectionHandler());
this.add(list);
}
private class ListRenderer extends DefaultListCellRenderer {
public ListRenderer() {
this.setBorder(BorderFactory.createLineBorder(Color.red));
}
@Override
public Component getListCellRendererComponent(JList list, Object
value, int index, boolean isSelected, boolean cellHasFocus) {
JComponent jc = (JComponent) super.getListCellRendererComponent(
list, value, index, isSelected, cellHasFocus);
jc.setBorder(BorderFactory.createEmptyBorder(N, N, N, N));
return jc;
}
}
private class SelectionHandler implements ListSelectionListener {
@Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
System.out.println(Arrays.toString(list.getSelectedValues()));
}
}
}
private void display() {
JFrame f = new JFrame("ListPanel");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new ListPanel().display();
}
});
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620579",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: When a method depends on another method What is the best way to deal with the following situation in JavaScript.
I have three methods (m1, m2, m3) and the last one (m3) depends from the results of the others two (m1, m2).
In this way it works, but I am curious to know if there is a better way to write the code in this situation, especially for future developers that will read the code.
var O = function () {
this.p = 0;
}
O.prototype.makesomething = function () {
var that = this;
that.m1();
that.m2();
that.m3();
}
O.prototype.m1 = function () {O.p++}; // it changes the value O.p
O.prototype.m2 = function () {O.p++}; // it changes the value O.p
O.prototype.m3 = function () {return O.p}; // m3 depends by m1, m2 because it needs to get the update value of O.p
A: First, I don't know for sure, but putting this.p = 0 inside O does not make sense in combination with O.p. You probably mean this.p inside m3, when referring to the instance.
Anyway, if you are looking for readability, you could make some simple but idiomatic functions like this: http://jsfiddle.net/ZvprZ/1/.
var O = function () {
this.p = 0;
}
O.prototype.makesomething = function () {
var that = this;
var result = when( that.m1(), that.m2() )
.then( that.m3() );
return result;
}
O.prototype.m1 = function () {this.p++};
O.prototype.m2 = function () {this.p++};
O.prototype.m3 = function () {return this.p};
The when/then can be rather straight-forward since it does not do anything than making it more readable:
(function(window) {
var when, then, o;
when = function() {
return o; // just return the object so that you can chain with .then,
// the functions have been executed already before executing
// .when
};
then = function(a) {
return a; // return the result of the first function, which has been
// executed already (the result is passed)
};
o = { when: when,
then: then };
window.when = when; // expose
window.then = then;
})(window);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620588",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Getting iframes source? I have an iframe on my website that displays different site.
Is it possible to grab & store/save source of the iframed site?
A: The same-origin policy in the browser will prevent you from accessing the internal content of a div loaded from another domain.
A: You can always just $iframeSource = file_get_contents("http://iframe-source-url/"); it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620591",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jquery cookie, save cookies in where? Maybe this is a basic question. but I still not sure jquery cookie, save cookies in where?
like this one: http://code.google.com/p/cookies/wiki/Documentation
the cookies save in server part or in custom browser part?
I guess save in custom browser part. jquery cookie just is a tool, it should be like php cookie/session, save each cookie depends on different URL.
But when I see it need set domain and path. I am puzzed, if it depends on different URL, why not use domain + window.location.hash? the path for what?
A: "JQuery cookie" is a simple tool which makes use of document.cookie. This basic JavaScript feature stores cookies at the user's browser.
A cookie can be defined with some properties:
*
*max-age - Expiration date in seconds (Jquery implementation: {expires: __} in days)
*domain - By default, a cookie is saved at the current domain. It's however possible to change the domain to any domain from the current subdomain to the top domain (sub.sub2.top.nl -> sub2.top.nl -> top.nl, but not another.top.nl).
*path - By default, the cookie is applied to /. It's possible to change this default, so that only a specific directory is matched.
*secure - This flag can be added through passing secure: true in JQuery. When this option is set, cookies are targeted at the HTTPS protocol only.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620597",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Using database connection as a class: best practice? I have db class which initiates connection to the database and all the queries are run through it.
Now I am having troubles with the fact that I don't know how to use it within other objects and also how to use it within functions.
For example if there is an object to process and display some data, then do I extend this object to the db class or else how do I get the connection for the $db in this class.
Also, how do I use the db connection in a function outside a class. Do I post the db class as a parameter or do I use GLOBAL $db;
All the "do I" are actually "should I", so please advice me what is best for performance and other pros and cons.
A: Usually frameworks provide a singleton instance of the database connection, which can be obtained via static method (or global function) that returns the encapsulated (static private) instance. This instance is created when the first call to this method is executed, for the next calls, it simply returns it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620598",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Updating Widgets from a Service via RemoteViews - OK on a phone, not working on the Emulator I've created a WidgetProvider and a Service which triggers on the system TIME_TICK - that part is working fine, Log messages show the Service is working AOK and it looks great on an actual phone.
To update my Widgets I use code like this (editted for clarity so it might have a typo)
Log.d("xxx","Updating");
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.main);
views.setTextViewText(R.id.appwidget_text, "Some Text" + System.currentTimeMillis());
ComponentName thisWidget = new ComponentName(context, SWClockWidgetProvider.class);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
manager.updateAppWidget(thisWidget, views);
On my phone (an HTC Desire running 2.2) it's perfect, the Widgets update bang-on the minute, every minute.
On the emulator (running 2.2) Log messages appear (e.g. the service is working) but widgets aren't updated.
Now I call that code in 2 places - from the onUpdate method of the Provider (so that it puts something into the Widgets when they're first displayed) and from the Service's listener (to update them)
Now here's the weird bit - in my manifest I originally declared my service like this
service android:name=".SWClockWidgetService"
When I changed that to explicitly mention the package (which is identical to the Provider's package of course)
service android:name="com.somewhatdog.swclockwidget.SWClockWidgetService"
the initial update (called from the Provider onUpdate) works BUT subsequent calls from the Service's listener still don't!?
Note: Originally I made the Service an inner-class of the provider but that didn't work on a phone OR emulator - no idea if that's related...
Anyway - I'm mystified - same Android on phone and emulator - one works, one doesn't (which means the odds of this working on other devices are moody to say the least??)
I'm more than a bit lost here - any advice apprec.
p.s. I've tested this on an emulator running 1.6 no joy - it works on an emulator running 2.1r1 and 2.3.3 tho, so who knows...
A: The emulator widget update seems to be a bit dodgy. There are two known issues with it:
*
*updateAppWidget(...) calls may only work on emulators that have been restarted at least once.
*Running more than one emulator at a time may interfere with widget updating.
A: Much further experimentation suggests that Widget updating within the Emulator is just broken.
Even if you deploy new code, existing Widgets remain unchanged!
Testing using Androidx86 suggests the problem is confined to the emulator tho - so I guess I'll use that for Widget testing instead...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620604",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Trouble with jScrollPane I have used jScrollPane on my site. I'm also using ajax to update the data on the same div where the jScrollPane is used. Now, when i append the returned data to the div, the scrollbar is not visible on the appended text. It may because the jQuery function is called when the document loads but now any ideas to solve this problem?
A: You need to use the auto reinitialise function in jScrollPane when inserting content dynamicly, something like this:
$(function() {
$('.scroll-pane').jScrollPane({autoReinitialise: true, showArrows:true, scrollbarWidth: 16, arrowSize: 15});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620613",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Cannot use onItemSelectListener() with Spinner with One Item So I have a spinner (spinner2 here) which is populated via an ArrayAdapter from an SQLite table. On selecting an item I want it
*
*deleted from the DB
*deleted from the spinner
The code below actually works. Except when the spinner has only one item. When that happens
it seems onItemSelected is not called at all.
I get the following LogCat
10-01 22:30:55.895: WARN/InputManagerService(1143): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@45a06028
Oh and when two items are populating the spinner, spinner.getcount() shows two items, so it's not some strange case of the system thinking the spinner is empty or something like that.
This is the code:
public class SpinnerItemSelectListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if(parent == spinner2){
if(autoselected){
autoselected=false;
}
else{
//uniqvalarray is the arraymade from pulling data from SQLite and populaitng array adapter
Integer i = uniquevalarray.get(pos);
deleteRow(i);//deletes the row from the database and repopulates the above array.
autoselected=true;//just a boolean to stop autoslecting in onCreate()
//makeAlert(i);initially wanted to make alert box.
loadSpinner2();//reloads the spinner with new data
}
}
}
public void onNothingSelected(AdapterView parent) {
//TODO
}
}
A: The spinner runs this way : Only fire when you change the selected item . If you dont change that element , cause its the only one that exist , it can't change .
The solution i think you must use is using a button next to the spinner to throw the delete funcions.
You must think that Spinner is not made to be with an unique element , cause only changes usually when you change the selected one . then the natural solution can be that .
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620618",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What's the behavioral difference between HTTP Keep-Alive and Websockets? I've been working with websockets lately in detail. Created my own server and there's a public demo. I don't have such detailed experience or knowledge re: http. (Although since websocket requests are upgraded http requests, I have some.)
On my end, the server reports details of each hit. Among them are a bunch of http keep-alive requests. My server doesn't handle them because they're not websocket requests. But it got my curiosity up.
The whole big thing about websockets is that the connection stays alive. Then you can pass messages in both directions (simultaneously even). I've read that the Keep-Alive HTTP connection is a relatively new development (I don't know how many years in people time, just that it's only included in the latest standard - 1.1 - is that actually old now?)
I guess I can assume that there's a behavioral difference between the two or there would have been no reason for a websocket standard? What's the difference?
A: You should read up on COMET, a design pattern which shows the limits of HTTP Keep-Alive. Keep-Alive is over 12 years old now, so it's not a new feature of HTTP. The problem is that it's not sufficient; the client and server cannot communicate in a truly asynchronous manner. The client must always use a "hanging" request in order to get a message back from the server; the server may not just send a message to the client at any time it wants.
A: HTTP vs Websockets
REST (HTTP)
*
*Resources benefit from caching when the representation of a resource changes rarely or multiple clients are expected to retrieve the resource.
*HTTP methods have well-known idempotency and safety properties. A request is “idempotent” if it can be issued multiple times without resulting in unique outcomes.
*The HTTP design allows for responses to describe errors with the request, with the resource, or to provide nuanced status information to differentiate between success scenarios.
*Have request and response functionality.
*HTTP v1.1 may allow multiple requests to reuse a single connection, there will generally be small timeout periods intended to control resource consumption.
You might be using HTTP incorrectly if…
*
*Your design relies on a client polling the service often, without the user taking action.
*Your design requires frequent service calls to send small messages.
*The client needs to quickly react to a change to a resource, and it cannot predict when the change will occur.
*The resulting design is cost-prohibitive. Ask yourself: Is a WebSocket solution substantially less effort to design, implement, test, and operate?
WebSockets
*
*WebSocket design does not allow explicit or transparent proxies to cache messages, which can degrade client performance.
*WebSocket protocol offers support only for error scenarios affecting the establishment of the connection. Once the connection is established and messages are exchanged, any additional error scenarios must be addressed in the messaging layer design, but WebSockets allow for a higher amount of efficiency compared to REST because they do not require the HTTP request/response overhead for each message sent and received.
*When a client needs to react quickly to a change (especially one it cannot predict), a WebSocket may be best.
*This makes the protocol well suited to “fire and forget” messaging scenarios and poorly suited for transactional requirements.
*WebSockets were designed specifically for long-lived connection scenarios, they avoid the overhead of establishing connections and sending HTTP request/response headers, resulting in a significant performance boost
You might be using WebSockets incorrectly if..
*
*The connection is used only for a very small number of events, or a very small amount of time, and the client does not - need to quickly react to the events.
*Your feature requires multiple WebSockets to be open to the same service at once.
*Your feature opens a WebSocket, sends messages, then closes it—then repeats the process later.
*You’re re-implementing a request/response pattern within the messaging layer.
*The resulting design is cost-prohibitive. Ask yourself: Is a HTTP solution substantially less effort to design, implement, test, and operate?
Ref: https://blogs.windows.com/buildingapps/2016/03/14/when-to-use-a-http-call-instead-of-a-websocket-or-http-2-0/
A: A Keep Alive HTTP header since HTTP 1.0, which is used to indicate a HTTP client would like to maintain a persistent connection with HTTP server. The main objects is to eliminate the needs for opening TCP connection for each HTTP request. However, while there is a persistent connection open, the protocol for communication between client and server is still following the basic HTTP request/response pattern. In other word, server side can't push data to client.
WebSocket is completely different mechanism, which is used to setup a persistent, full-duplex connection. With this full-duplex connection, server side can push data to client and client should be expected to process data from server side at any time.
Quoting corresponding entries on Wikipedia for reference:
1) http://en.wikipedia.org/wiki/HTTP_persistent_connection
2) http://en.wikipedia.org/wiki/WebSocket
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620620",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "46"
} |
Q: Understanding the "using" statement in asp.net 4.0 - C# Are there any difference between these 2 codes ? Which one should be used ?
asp.net 4.0 , c#
code 1 :
using System;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data;
public static class DbConnection
{
public static string srConnectionString = "server=localhost;database=mydb;uid=sa;pwd=mypw;";
public static DataSet db_Select_Query(string strQuery)
{
DataSet dSet = new DataSet();
try
{
using (SqlConnection connection = new SqlConnection(srConnectionString))
{
connection.Open();
SqlDataAdapter DA = new SqlDataAdapter(strQuery, connection);
DA.Fill(dSet);
}
return dSet;
}
catch
{
if (srConnectionString.IndexOf("select Id from tblAspErrors") != -1)
{
using (SqlConnection connection = new SqlConnection(srConnectionString))
{
connection.Open();
strQuery = strQuery.Replace("'", "''");
SqlCommand command = new SqlCommand("insert into tblSqlErrors values ('" + strQuery + "')", connection);
command.ExecuteNonQuery();
}
}
return dSet;
}
}
public static void db_Update_Delete_Query(string strQuery)
{
try
{
using (SqlConnection connection = new SqlConnection(srConnectionString))
{
connection.Open();
SqlCommand command = new SqlCommand(strQuery, connection);
command.ExecuteNonQuery();
}
}
catch
{
strQuery = strQuery.Replace("'", "''");
using (SqlConnection connection = new SqlConnection(srConnectionString))
{
connection.Open();
SqlCommand command = new SqlCommand("insert into tblSqlErrors values ('" + strQuery + "')", connection);
command.ExecuteNonQuery();
}
}
}
}
code 2 :
using System;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data;
public static class DbConnection
{
public static string srConnectionString = "server=localhost;database=mydb;uid=sa;pwd=mypw;";
public static DataSet db_Select_Query(string strQuery)
{
DataSet dSet = new DataSet();
try
{
using (SqlConnection connection = new SqlConnection(srConnectionString))
{
connection.Open();
using (SqlDataAdapter DA = new SqlDataAdapter(strQuery, connection))
{
DA.Fill(dSet);
}
}
return dSet;
}
catch
{
using (SqlConnection connection = new SqlConnection(srConnectionString))
{
if (srConnectionString.IndexOf("select Id from tblAspErrors") != -1)
{
connection.Open();
strQuery = strQuery.Replace("'", "''");
using (SqlCommand command = new SqlCommand("insert into tblSqlErrors values ('" + strQuery + "')", connection))
{
command.ExecuteNonQuery();
}
}
}
return dSet;
}
}
public static void db_Update_Delete_Query(string strQuery)
{
try
{
using (SqlConnection connection = new SqlConnection(srConnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(strQuery, connection))
{
command.ExecuteNonQuery();
}
}
}
catch
{
strQuery = strQuery.Replace("'", "''");
using (SqlConnection connection = new SqlConnection(srConnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand("insert into tblSqlErrors values ('" + strQuery + "')", connection))
{
command.ExecuteNonQuery();
}
}
}
}
}
A: If you have ReSharper to do it for you or are willing to download them manually, you could look at the source code for SqlCommand and SqlDataAdapter and see if their Dispose() method actually does anything. If not, it's probably safe to leave out the using statements around them.
A: What you should take in consideration is the fact that the using clause is used to make sure that the objects you use inside the brackets of that using clause are disposed correctly into memory.
So, I think you should use the second code example.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620623",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: iPhone stack scroll view I have implemented stack scroll view in iphone using this blog.
but i am facing one problem
When user is clicking on details view i want show detailview on complete screen.
When user is clicking on it again i want show show it like default stack scroll view with menu option.
I am trying this but not getting any success, have any one tried same thing?
A: Just make custom Scrollview, then you will get separate touch event.
I think this may solve your problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620624",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ec2, tomcat7 and 503 error I have Amazon's out of the box instance with Tomcat7 (ami-518e4c38), deployed a war file to it, but keep getting 503 error.
I've set the connector to listen on port 80 in server.xml, in the default security group I got 80 (HTTP) set to 0.0.0.0/0
I'm assuming that I don't have to start/stop tomcat manually, should start when the instance is launched. Am I correct on this one?
When I ping localhost (while ssh'ed into the instance ) 2 times on port 80 I get:
2 packets transmitted, 2 received, 0% packet loss, time 999ms
Any help will be most appreciated.
A: Seriously, this isn't an answer, you should describe your initial situation and what you did in your answer and accept it.
I just want to clear up what happened, and I would need your feedback to understand more about it.
Initially you had a 503 error, which means service unavailable, normally Tomcat is configured behind Apache, and with this I mean that the Apache server gets (all) the requests and may forward (some of) them to Tomcat, if configured to do so.
If you get a 503 error, it means there is some server up and running to reply to you and that should be Apache. If I shut down Tomcat and try to request an URL that would be forwarded to Tomcat I get:
Service Temporarily Unavailable
The server is temporarily unable to service your request due to maintenance downtime or capacity problems. Please try again later.
Apache/2.2.17 (Ubuntu) Server at private.it Port 80
That's why my first thought was to check if Tomcat was running. Then you did:
$ ps fax | grep tomcat
And you got that tomcat was actually running:
1127 pts/0 S+ 0:00 _ grep tomcat 987 ? Sl 0:42 /usr/lib/jvm/jre/bin/java -classpath /opt/tomcat7/bin/bootstrap.jar:/opt/tomcat7/bin/tomcat-juli.jar -Dcatalina.base=/opt/tomcat7 -Dcatalina.home=/opt/tomcat7 -Djava.awt.headless=true -Djava.endorsed.dirs=/opt/tomcat7/endorsed -Djava.io.tmpdir=/opt/tomcat7/temp -Djava.util.logging.config.file=/opt/tomcat7/conf/logging.properties -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager org.apache.catalina.startup.Bootstrap start
Another reason could be that the connection Tomcat-Apache is not configured correctly. However then you posted that Tomcat was trying to bind port 80 and failing:
Sep 30, 2011 4:07:51 AM org.apache.coyote.AbstractProtocol init SEVERE: Failed to initialize end point associated with ProtocolHandler ["http-bio-80"] java.net.BindException: Address already in use :80
I tried to replicate that error, I went in my conf/server.xml file and change the connector to listen on port 80 instead of 8080:
<!-- A "Connector" represents an endpoint by which requests are received
and responses are returned. Documentation at :
Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
Java AJP Connector: /docs/config/ajp.html
APR (HTTP/AJP) Connector: /docs/apr.html
Define a non-SSL HTTP/1.1 Connector on port 8080
-->
<Connector port="80" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
I start tomcat and monitor the log:
bin/startup.sh && tail -f logs/catalina.out
And I get an exception that is similar to what you get, but not exactly the same:
SEVERE: Failed to initialize end point associated with ProtocolHandler ["http-bio-80"]
java.net.BindException: Permission denied <null>:80
Now if I check whether Tomcat is running I find that is indeed running. While without checking I'd have supposed that in a case like that the server would have just gave up and quit. In my case the correction would be, either shut down Apache and use Tomcat directly, which is not advisable for high traffic sites or move Tomcat back to port 8080 and install mod_jk.
The installation of mod_jk enables the communication between Apache and Tomcat. Then in the virtual host configuration I'd mount a folder or the root folder and do some URL rewriting if necessary:
JkMount /webappname/* ajp13_worker
RewriteEngine on
RewriteRule ^/nametoshow/(.*)$ /webappname/$1 [PT,QSA]
And everything should work. However, I am not sure how you solved the bind error, you didn't say.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620625",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to put programmatically iCarousel in View? I want four ScrollViews like iCarousel's CoverFlow in View programmatically. My Code is
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[super viewDidLoad];
//set up data
wrap = YES;
self.items = [NSMutableArray array];
for (int i = 0; i < NUMBER_OF_ITEMS; i++)
{
[items addObject:[NSNumber numberWithInt:i]];
}
carousel1 = [[carousel1 alloc] init];
carousel2 = [[carousel2 alloc] init];
carousel3 = [[carousel3 alloc] init];
carousel4 = [[carousel4 alloc] init];
carousel1.frame = CGRectMake(0, 0, 320, 120);
carousel2.frame = CGRectMake(0, 120, 320, 120);
carousel3.frame = CGRectMake(0, 240, 320, 120);
carousel4.frame = CGRectMake(0, 360, 320, 120);
carousel1.delegate = self;
carousel2.delegate = self;
carousel3.delegate = self;
carousel4.delegate = self;
carousel1.dataSource = self;
carousel2.dataSource = self;
carousel3.dataSource = self;
carousel4.dataSource = self;
[self.view addSubview:carousel1];
[self.view addSubview:carousel2];
[self.view addSubview:carousel3];
[self.view addSubview:carousel4];
//configure carousel
carousel1.type = iCarouselTypeCoverFlow2;
carousel2.type = iCarouselTypeCoverFlow2;
carousel3.type = iCarouselTypeCoverFlow2;
carousel4.type = iCarouselTypeCoverFlow2;
}
but fail with four warnings with out placing the carousels view on the View. Please help me to overcome this problem. Thanks in advance.
A: Shouldn't you be initialising them with [[iCarousel alloc] init] instead of [[carousel1 alloc] init]?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620628",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I avoid mirror effect of image in coverflow I have downloaded a coverflow sample from the link
http://www.macresearch.org/cocoa-tutorial-image-kit-cover-flow-and-quicklook-doing-things-we-shouldnt-are-too-fun-resist.
I need open flow effect but I dont need miror effect of images.Is it possible to do it.Is there any API available in IKImageFlowView class.
Any help would be appreciated.
A: There is no API available for IKImageFlowView. It is a private class. That's why the blog post is titled "doing things we shouldn't." If you look at the project in the blog post, you will find a reverse-engineered IKImageFlowView.h. That's as much information as is available. You can use class-dump as noted in the blog post and see if you can find the IKImageFlowViewDelegate protocol if there is one (this class appears to take a delegate). That might allow you to configure it.
Note that Apple may change this class at any time.
You are probably better off using a third-party implementation like MBCoverFlowView or OpenFlow.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: GWT - Convert Date formatting I have following method:
public static String formatDate(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
Calendar today = Calendar.getInstance();
Calendar yesterday = Calendar.getInstance();
yesterday.add(Calendar.DATE, -1);
DateFormat timeFormatter = new SimpleDateFormat("hh:mma");
DateFormat dateTimeFormatter = new SimpleDateFormat("MMM d, yyyy - hh:mma");
if (calendar.get(Calendar.YEAR) == today.get(Calendar.YEAR) && calendar.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR) && calendar.get(Calendar.HOUR_OF_DAY) == today.get(Calendar.HOUR_OF_DAY) && calendar.get(Calendar.MINUTE) == today.get(Calendar.MINUTE)) {
return "few seconds ago ";
} else if (calendar.get(Calendar.YEAR) == today.get(Calendar.YEAR) && calendar.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR) && calendar.get(Calendar.HOUR_OF_DAY) == today.get(Calendar.HOUR_OF_DAY)) {
return "few minutes ago ";
} else if (calendar.get(Calendar.YEAR) == today.get(Calendar.YEAR) && calendar.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR)) {
return "today " + timeFormatter.format(date);
} else if (calendar.get(Calendar.YEAR) == yesterday.get(Calendar.YEAR) && calendar.get(Calendar.DAY_OF_YEAR) == yesterday.get(Calendar.DAY_OF_YEAR)) {
return "yesterday " + timeFormatter.format(date);
} else {
return dateTimeFormatter.format(date);
}
}
How do I write this in client side GWT?
A: There are four ways to do this that occur to me:
*
*Don't do it on the client side, but on the server side.
Calendar is not emulated in GWT on the client side.
*If you must do this on the client side, try using the deprecated methods
in the Date class. They still work, and they've all been deprecated
in favour of methods in Calendar, so you'd just be rolling back the
clock a bit.
*Speaking about rolling back the clock, you could
also just roll forward, as it were. Calendar emulation is coming to
GWT, at least that's what I've read. You could do (1) for now, then
move that method to the client when Calendar arrives. Alternately,
you could do (2) for now, and swap it for your original
Calendar-based code when Calendar arrives.
*Use the getTime() method on Date (which is not deprecated and is emulated by GWT on the client side) and do straight-up integer comparisons to determine what string to return. getTime() returns milliseconds, so "a few seconds ago" would be a difference of 60,000 milliseconds or less, "a few minutes ago" would be a difference of 3,600,000 milliseconds or less, and so on.
Go for 4.
Use the methods in com.google.gwt.i18n.client.DateTimeFormat to do your date/time formatting.
A: gwttime is a port of Joda-Time to GWT, and it is very useful for dealing with periods of time and durations.
In your case, you could construct either DateTimes or LocalDateTimes, and then construct a Period with both of them to find the number of seconds, minutes, hours, days, etc. between them.
For instance:
private static int daysBetween(LocalDateTime start, LocalDateTime end) {
return new Period(start, end, PeriodType.days()).getDays();
}
This would find the number of full days between start and end.
You could repeat this for seconds, minutes, etc. and do some fuzzy logic with the results to get to your desired output string.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620634",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Which compilation options should I use to link with Boost using cl.exe? I have a program which I would like compile using cl.exe on the command-line. This program depends on some boost libraries which I fail to link to.
The error I'm getting is:
cl /Fosamples\proxy\proxy.obj /c samples\proxy\proxy.cpp /TP /O2 /EHsc
/DBOOST_ALL_NO_LIB /DBOOST_THREAD_USE_LIB /DBOOST_SYSTEM_USE_LIB
/DBOOST_USE_WINDOWS_H /DTAP_ID=\"tap0901\" /D_WIN32_WINNT=0x0501 /MD /nologo
/Isamples\proxy /Iinclude proxy.cpp
link /nologo /MD /OUT:samples\proxy\proxy.exe /LIBPATH:samples\proxy
/LIBPATH:lib asiotap.lib libboost_system-vc100-mt-1_47.lib
libboost_thread-vc100-mt-1_47.lib ws2_32.lib gdi32.lib iphlpapi.lib
advapi32.lib samples\proxy\proxy.obj
LINK : warning LNK4044: unrecognized option '/MD'; ignored
asiotap.lib(bootp_builder.obj) : error LNK2001: unresolved external
symbol "class boost::system::error_category const & __cdecl
boost::system::system_category(void)"
(?system_category@system@boost@@YAAEBVerror_category@12@XZ)
I compiled Boost, using the following command-line, from the x64 MSVC command prompt:
.\b2.exe install toolset=msvc --prefix=C:\Boost-VC-x64
If I look inside libboost_system-vc100-mt-1_47.lib I can see that:
?system_category@system@boost@@YAABVerror_category@12@XZ
Is exported. But If you look closely it differs a bit from the one in my compilation errors:
?system_category@system@boost@@YAAEBVerror_category@12@XZ // The symbol I miss
?system_category@system@boost@@YAABVerror_category@12@XZ // The exported symbol
I guess I should either change Boost or my compilation options but fail to figure what to change exactly. Any clue ?
Thank you very much.
A: After some investigations, I realized that I compiled Boost for a x86 platform where I was linking with a x64 binary.
I thought that compiling Boost inside a Visual Studio x64 command prompt was enough but you actually have to specify:
.\b2.exe install toolset=msvc address-model=64 --prefix=C:\Boost-VC-x64
To make it work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620639",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get link of all users videos uploaded by him? I am working on facebook api and i want to get a link of users uploaded videos. i got an access_token with the permission to access photos. now how can i fetch the videos of the user using fql or graph api.
A: You would just access /me/videos via the graph api.
In FQL:
SELECT vid, owner, title, description, thumbnail_link,
embed_html, updated_time, created_time FROM video
WHERE owner=me()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620640",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: MPMovieFinishReasonPlaybackError read error log - objective-c I'm using MPMoviePlayerController to play video files. Some movies are not playing. I just recieve MPMovieFinishReasonPlaybackError. But for some reasons I can't read error log.
Here is code:
case MPMovieFinishReasonPlaybackError:
{
NSLog(@"%@",moviePlayer.errorLog);
}
break;
Error log is null. How to read Error log?
A: Are you sure you are accessing the NSError object correctly?
In case of an error, the notification contains an NSError object available using the @"error" key in the notification's userInfo dictionary.
http://developer.apple.com/library/ios/#documentation/mediaplayer/reference/MPMoviePlayerController_Class/Reference/Reference.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620646",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Get array item based on index I am trying to get an item from a char array based on the index that I have. I have used code earlier to get the index of a specified item but now I want the opposite, to get the item of the specified index. I have tried a few things but can't get it working.
I would like something like this:
char arrayChar = Array.GetItem(index [i]) // I know this isn't right but just so you get the idea.
Thanks very much!
A: Assuming your char array is called ArrayOfChars and the index is i. It should be as simple as
char arrayChar = ArrayOfChars[i];
A: var arrayChar = yourArray[index];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620648",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How can I select URLs of a particular type with XPath & Scrapy I am trying to select only links of the type http://lyricsindia.net/songs/show/* from an HTML which contains links likes this:
<a href="http://lyricsindia.net/songs/show/550" class=l>LyricsIndia.net dhiimii </a>
<a href="http://smriti.com/hindi-songs/dhiimii-dhiimii-bhiinii-bhiinii-utf8" class=l>dhiimii Songs Archive</a>
I have gone through the Scrapy documentation, but haven't been able to figure this out. Any ideas?
A: Try this XPath:
//a[starts-with(@href, 'http://lyricsindia.net/songs/show/')]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620651",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to use PHP function parameter inside array? I am trying to declare a function parameter inside my array, but I'm having trouble getting it to work. I've trimmed it down for simplicity purposes, and I have something like:
function taken_value($value, $table, $row, $desc) {
$value = trim($value);
$response = array();
if (!$value) {
$response = array(
'ok' => false,
'msg' => "This can not be blank."
);
} else if (mysql_num_rows(
mysql_query(
"SELECT * FROM $table WHERE $row = '$value'"))) {
$response = array(
'ok' => false,
'msg' => $desc." is already taken."
);
} else {
$response = array(
'ok' => true,
'msg' => ""
);
}
echo json_encode($response);
}
Notice the function parameter $desc trying to be used in the array here:
'msg' => $desc." is already taken.");
The whole function works fine EXCEPT when I try to add the $desc to the array results.
How could this be done?
A: Do you have an open resource handle to your database? You are not passing one to the query function.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620653",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Adding grid-lines to jpgraph whilst also having an alternating background? Is it possible to add (white) grid lines to a graph made from jpgraph, whilst also having an alternating background with it? I have the alternating background but I have no idea how to add the grid lines.
A: Ended up using flot instead of jpgraph.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620654",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I get the title of the current tab in Terminal using applescript? In the example below there are three tabs. Their titles are bash, less, and ssh.
How can I use applescript get the title of the currently selected tab? In this case I hope it would return less.
Picture.png http://img28.imageshack.us/img28/903/pictureqn.png
A: On OS X 10.7 try something like this:
osascript -e 'tell first window of application "Terminal" to get custom title of selected tab'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620660",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Turn off keyboard navigation on jQuery prettyphoto We are using prettyPhoto:
http://www.no-margin-for-errors.com/projects/prettyphoto-jquery-lightbox-clone/
For our portfolio. This allows us to show a video, image or SWF.
When we display a SWF game that uses the arrow keys, it conflicts with prettyPhoto navigation.
See this example of a game we have added:
http://www.letsdesign.co.uk/#!prettyPhoto/0/
This messes up worse in IE on PC.
however the game is playable on Firefox for Mac, this is the state we would like for all browsers.
We would like to find a way to turn off the navigation of PrettyPhoto (by using arrow keys), so it doesn't conflict with any in-game controls. We have other games to add, but we can't add them until this is fixed. Does anyone have a solution to this?
Thanks in advance.
A: After trying to disable keyboard shortcuts including (left and right) by setting the "keyboard_shortcuts" param to false I resorted to overriding the changePage method and called the method from the changepicturecallback method. I find this makes it easy to choose different experiences of prettyPhoto without having to edit core files (which I would never recommend).
$("a[rel^='prettyPhoto']").prettyPhoto({
changepicturecallback: function(){
$.prettyPhoto.changePage = function(){};
},
});
Take a look at the prettyPhoto params they are very powerful when combined properly.
A: In the JavaScript file of Prettyphoto set the keyboard_shortcuts to false
A: I found a really hacky way to disable the arrow key functionality. In my jquery.prettyPhoto.js file I just commented out $.prettyPhoto.changePage('previous'); and $.prettyPhoto.changePage('next');.
It will mean that arrow navigation doesn't work at all, but I don't need it for my project anyway.
A: There's a bug, unfortunately. I have modified the code and now it works great.
Here's the bug. There is a piece of code like this:
switch(t.keyCode){case 37:e.prettyPhoto.changePage("previous");t.preventDefault();break;case 39:e.prettyPhoto.changePage("next");t.preventDefault();break;case 27:if(!settings.modal)e.prettyPhoto.close();t.preventDefault();break
change this by the following one
if (settings.keyboard_shortcuts) { switch(t.keyCode){case 37:e.prettyPhoto.changePage("previous");t.preventDefault();break;case 39:e.prettyPhoto.changePage("next");t.preventDefault();break;case 27:if(!settings.modal)e.prettyPhoto.close();t.preventDefault();break}
Now the author's setting, called keyboard_shortcuts will work great if you set it to false.
This is valid for the minified code, I haven't check if the bug exists in the non-minified code (if available).
Good luck!
George
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620663",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: SQL Anywhere in PHP, can't fetch result I am using SQL Anywhere in php, i use something like this:
sasql_connect ("Uid=".$uid.";Pwd=".$password.";ServerName=".$servername.";CommLinks=tcpip(host=".$ip.";port=".$port.")");
$result = sasql_query("SELECT * FROM cars");
When i use:
while($row = sasql_fetch_array($result)) {
}
I get:
Warning: sasql_fetch_array(): 27 is not a valid SQLAnywhere result resource in ...
When i use:
echo get_resource_type($result);
I get 'SQLAnywhere result'
Also other functions like sasql_num_rows() don't work, what could be a reason this doesn't work? It looks like the resource is not recognized. I am 100% sure there is no error in the SQL query.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620665",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jQuery replace all HTML I'm trying to replace all the HTML (including the HTML tags) with another page. What I'm trying to do is having a website acting as an app even when navigating the another page.
Here is the code :
(function($) {
Drupal.behaviors.loadingPage = {
attach: function(context,settings) {
$('a').click(function(event) {
event.preventDefault();
// Create the loading icon
// ...
$.ajax({
url: $(this).attr('href'),
success: function(data) {
$('html').replaceWith(data);
}
});
});
}
};
})(jQuery);
I've tried several things. replaceWith() causes a jQuery error in jquery.js after deleting the HTML tag, I guess it is because it can't find the parent anymore to add the replacement.
The best result I got was with document.write(data). The problem is, the javascript code on the loaded page is not executed.
Anyone got a better idea ?
A: A better idea? Yeah, just load the new page normally by setting window.location instead of using AJAX. Or submit a form.
Otherwise, if you want to load something to replace all of the visible content of the current page but keep the current page's script going, put all the visible content in a frame sized to fill the browser window - which, again, you wouldn't populate using AJAX.
(I like AJAX, but I don't see why you'd use it to replace a whole page.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620669",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Static variable variables in php 5.2 I'm trying to define the following function:
function set($key, $value, $default = null)
{
if ($value)
static $$key = $value;
else
static $$key = $default;
}
But when I call it, I get the error "Parse error: syntax error, unexpected '$', expecting T_VARIABLE". I guess there is a problem with defining static variable variables, but I can't find a workaround. Can you? Thanks!
A: If I really wanted to do something like that, I'd use a static array instead:
function set($key, $value, $default = null)
{
static $values = array();
$values[$key] = is_null($value) ? $default : $value;
}
If you want to also be able to access this data, a better idea is to encapsulate it in a class.
class Registry
{
private static $values = array();
public static function set($key, $value, $default = null)
{
self::$values[$key] = is_null($value) ? $default : $value;
}
public static function get($key, $default = null)
{
return array_key_exists($key, self::$values) ? self::$values[$key] : $default;
}
}
Then you can use the class statically:
Registry::set('key', 'value', 'default');
$value = Registry::get('key', 'default');
An even better way of doing this is to not use the static keyword at all, and instead make a normal class with normal properties, then make a single instance of it and use that instance.
class Registry
{
private $values = array();
public function set($key, $value, $default = null)
{
$this->values[$key] = is_null($value) ? $default : $value;
}
public function get($key, $default = null)
{
return array_key_exists($key, $this->values) ? $this->values[$key] : $default;
}
}
You can then make an instance of the class and pass it along:
$registry = new Registry();
do_something_that_requires_the_registry($registry);
A: if you are doing this in a class, you can use the __get and __set magic functions.
I use it like this in my projects:
class foo
{
public function __set($key, $value)
{
$this->vals[$key] = $value;
}
public function __get($key)
{
return $this->vals[$key];
}
}
$foo = new foo();
$foo->bar = "test";
echo $foo->bar;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620672",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CodeIgniter SessionProblem I use CodeIgniter and save Sessions in my DB.
The following line of code will be executed if the users try to login and the login is successfull (found his data in the db):
$this -> session -> set_userdata($account_data); /login-page
After this i redirect the user to my dashboard. The dashboard tries now to read the $account_data from the session.
BUT
$this -> session -> all_userdata(); /dashboard
outputs only the standard session content from codeigniter.
I check the session after the set_userdata call (above) and the array is loaded. But there is no db-entry for this session.
Ok i call the all_userdata(); in the dashboard - it shows the standard content of the session AND the data is saved in my db.
Summary:
LoginPage - Load some Accountdata and save it in a Session. I can load the Accountdata from this session. NO db-entry
Dashboard - Session contains only the standard content of codeigniters session. DB-Entry with this data exists.
Only at the beginning of the LoginPage i destroy the session.
I'm a little bit confused, it seems the session is not "transported" to the next site.
Any tips?
Edit: Test-Case
public function testSessionStart(){
if ($this->session->userdata('key')){
}else{
$this->session->sess_destroy();
}
$this->session->set_userdata('key','12345566');
debug($this->session->all_userdata());
debug($this->session->userdata('session_id'));
echo "<br><a href='".base_url()."login/testSessionEnd'>Klick me</a>";
}
public function testSessionEnd(){
$this->session->set_userdata('sid','hasd12312kasdj89d');
debug($this->session->all_userdata());
debug($this->session->userdata('session_id'));
}
If the Start func is called, the db never get's an entry.
End func generates a new Session and save it to the db.
i have no idea why
A: You should note that You can not access the Session Data in the same page where you set Session Data. If there is no DB Entry please check your DB Structure and read this page carefully. Hope it will solve your problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620675",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Activate render man in Maya 2012 For some reason my render window in Maya doesn't work. Is there any way I can activate it by using MEL script or Python? I think it's disabled. Thanks.
A: Maybe this helps: http://3dg.me/3d-graphics/maya/fix-for-maya-2012-error-setparent-object-renderview-not-found
You can delete (save it before delete) your prefs directory. It helps sometimes
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620676",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jQuery shuffle table rows I got a table with three columns:
1 A A
2 B B
3 C C
4 D D
What I want to do is to shuffle the table rows but only the second and third column, like the example below
1 C C
2 A A
3 D D
4 B B
I found a nifty plugin wich lets the table rows to be shuffled
http://www.yelotofu.com/2008/08/jquery-shuffle-plugin/
but I want to keep the first column in it's default order.
Either I will reorder the first column after shuffling or I just shuffle
the second and third column. Either way can somebody help me out with this?
A: Fiddle: http://jsfiddle.net/tGY3g/
Here you go:
(function($){
//Shuffle all rows, while keeping the first column
//Requires: Shuffle
$.fn.shuffleRows = function(){
return this.each(function(){
var main = $(/table/i.test(this.tagName) ? this.tBodies[0] : this);
var firstElem = [], counter=0;
main.children().each(function(){
firstElem.push(this.firstChild);
});
main.shuffle();
main.children().each(function(){
this.insertBefore(firstElem[counter++], this.firstChild);
});
});
}
/* Shuffle is required */
$.fn.shuffle = function() {
return this.each(function(){
var items = $(this).children();
return (items.length)
? $(this).html($.shuffle(items))
: this;
});
}
$.shuffle = function(arr) {
for(
var j, x, i = arr.length; i;
j = parseInt(Math.random() * i),
x = arr[--i], arr[i] = arr[j], arr[j] = x
);
return arr;
}
})(jQuery)
Usage
$("table").shuffleRows()
A: To make sure only the specific table tbody is shuffled, use an ID to identify the affected table, in your JS:
/* Shuffle the table row, identify by id ---- */
$('#shuffle').shuffleRows();
In your HTML, use these:
<table id="shuffle">
<thead>...</thead>
<tbody>
<tr>....</tr>
<tr>....</tr>
<tr>....</tr>
</tbody>
</table>
so that only row in thead is shuffled.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620677",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Obtaining persistent token for accessing users data under Google domain I am trying to implement a Google APPs Marketplace application. Some parts of the application are web-based and other parts simply need offline access to users data.
During installation, the Google domain administrator grants access to the data required by the application (e.g Calendar).
For the web-based part of the application, users use OpenID+OAuth, so the application can access the user's data (this works fine).
Questions:
*
*What should be the best practice for the offline part to gain access to users data ?
*Do I have to store a persistent access token for EACH user in the domain ?
*Can I avoid the need for each user to grant access to their data (after domain administrator has already done this at the domain level) ?
*Is there a way to utilize OpenId from a background application ?
A: Since Sean M in fact answered you to the question no. 4 with his comment, I will handle other three:
You can use 2-legged oAuth. Using 2-legged oAuth, application can access services and data that were granted to it during installation process (for example Read/Write access to Calendar) without any additional approval from user.
In 2-legged oAuth there are no tokens. Instead, the app is provided with oAuth key and secret and uses these to access Google services and read/write data.
More reading:
http://code.google.com/intl/cs/googleapps/marketplace/tutorial_java.html#Integrate-OAuth
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620679",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How can I get django redirect to work when using jquery mobile? I posted a question earlier about why django redirect was not working correctly, but quickly remove it because I discovered the when I took jquery mobile out of the equation, django is working fine.
I have a form which I am submiting and varifying in django in the usual manner. This is working fine. The problem comes when after the form is submited I want to redirect to a different url.
When I do this without jquery mobile, I simply user:
response("myurl")
which works fine, but When I use jquery mobile I am redirected to the correct page, but the browser url does not change.
This causes all manner of problems because I am using variables in my django url regex, and without the correct url nothing works correctly.
Has anyone else had a similar problem when using jquery mobile and django together? If so what did you do about it? Failing that, can anyone shed any light on why this is happening?
A: After a lot of goggling I ended up back at a question on stackoverflow which I had not spotted as it was only tagged as a jquery question and did not mention django in the title either.
error-with-redirects-in-jquery-mobile
This suggests specifying data-url to set the url.
In my websites base template file I setup the data-url with a code block marker like this:
<div id="page" name="page" data-role="page" data-url="{% block data-url %}/root/{% endblock %}" class="type-interior">
then in the individual page templates I am then able to set to specify the url like this:
{% block data-url %}/root/myurl/{% endblock %}">
I am not sure if this is the optimal solution as of course this means that I have to include the data-url block in every template, but it does work
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620680",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: emulating iPad, iPhone on Windows Is there any emulator for doing this? I want to create some checks of how an HTML5 app is displayed on this devices but I don't have any.
A: The official iOS simulator is only available for OSX
A: Apple licenses doesn't allow you to use their software on a non-Apple machine. So you should get a Mac laptop/computer or ask someone to borrow it for some time.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620685",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How can I get the column names from an Excel sheet? I have a database table. Is there a query that gets the names of the columns in a table?
Example:
Name || Age || Gender
Tom || 30 || male
Kate || 20 || Female
I want a query to get the column names: Name , Age, Gender
Thanks you
edit: Sorry about some missing info:
I am using an OleDB connection in C# to read data from an excel sheet
A: You can retrieve a list of columns in a table like:
select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'YourTable'
INFORMATION_SCHEMA is an ISO standard, so it works on most databases.
A: I believe you're after the SHOW COLUMNS query.
SHOW COLUMNS FROM mytable
More info: http://dev.mysql.com/doc/refman/5.0/en/show-columns.html
A: i wanted to upload the columns of a table from Excel, so I uploaded the table in a Dataset and then checked the column names and inserted in database. you can get an idea from the below code
for (int i = 0; i < dsUpload.Tables[0].Columns.Count; i++)
{
if (dsUpload.Tables[0].Columns[i].ColumnName.ToString() != "")
{
// Assigning ColumnName
objExcelUpload.ColumnName = dsUpload.Tables[0].Columns[i].ColumnName.ToString().Replace("'", "''").Replace("<", "<").Replace(">", ">").Trim();
if (!objExcelUpload.ifColumnNameExist("insert"))
{
if (objExcelUpload.ColumnName != "")
{
objExcelUpload.insertColumns();
}
}
else
{
ErrorLabel.Text = "The column name already exists. Please select a different name.";
return;
}
}
}
Here ds Upload is a dataset name
and the code useful for you is
objExcelUpload.ColumnName = dsUpload.Tables[0].Columns[i].ColumnName.ToString()
which is checked in a loop of all the available columns
for (int i = 0; i < dsUpload.Tables[0].Columns.Count; i++)
Let me know if you need any clarification :-)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620690",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: cvpolyline color line I try to execute the following code:
CvScalar color = CV_RGB(255,0,0);
cvPolyLine( imageBin, &PointArray, &n, 1,1,color, 1, 8 );
The source image is a binary image. The points are valid and, nothing happens to my image, no red line is draw.
Thanks in advance.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620692",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Search NSMutableArray Hi what I want to do is search an NSMutable array for the string str or the header label in the view. If the word already exists in the array then I want to delete it. Otherwise I want to add it. Here's my code so far.
-(IBAction)add:(id)sender{
NSMutableArray *array=[[NSUserDefaults standardUserDefaults] mutableArrayValueForKey:@"favorites"];
NSString *str=header.text;
}
A: See the manual: NSArray Class Reference
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620694",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Input view for textfields in table view I Have an UITableView with textfields in each row.
I want to access these textfields each in a different way like adding a picker view for one textfield, navigating to another view when clicked on one text field.
i know how to do it when these textfields are in a normalview but i never have done it before on tableview.
Please help.
A: Your question is where to put the code to handle user interaction with your table view cells. Well the proper place to do that is the didSelectRowAtIndexPath: method of your table view controller.
However, there are a few caveats.
*
*You need to add the UITextFieldDelegate protocol to your table view controller.
*You can distinguish between the active UITextFields with tags, as suggested in other answers.
*However, recycling the cells can lead to big confusion about the text fields. So make sure you update that id tag in the part of cellForRowAtIndexPath: that is not creating new cells.
*You should not use a UITextField when you want another controller to pop up. In this case, just use a UILabel or the provided textLabel property of UITableViewCell. Push another controller when the user selects the row.
*Only use a UITextField if you want the keyboard to pop up without leaving the table view.
A: i think you need to give tag to each textfield like
textfield.tag = indexpath.row;
according to tag you can move ahead...
A: And one more thing while assigning tag to text field, don't forgot to this line
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:nil] autorelease];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620696",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Where can I find a reference of the CG shader language? I am new to shaders and I would like to find a list of all (or most/common) functions, variables, availeble to write CG shaders.
A: This should get you started: http://http.developer.nvidia.com/Cg/index.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620697",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Passing back an Image from OpenCV /C++ to .NET C# I have to write some code to read back an image in C# which is processed in OpenCV/C++. C# does not understand OpenCV image formats so I have to do some sort of conversions before I can write a wrapper in .NET. What would be the best approach to return the image from C to C#? That is, should I expose the raw bytes and image dimensions that would be readable in C# or is there any better approach?
Thanks for the reply.
A: Write a C++/CLI wrapper that creates a Bitmap and returns it to .NET client.
OR
If you don't expect image to be larger than few MBs and there are no strict performance requirements in terms of no. of parallel calls then you might as well return the byte* by saving the image to an inmemory bitmap
OR
If it makes sense in your scenario then the caller can also specify a file path where the image can be saved after processing. This is however not very reusable.
OR
You can write the image to ILockBytes and return pointer to that. .NET client can read from that. This is Windows specific
A: Or, if you just wanted to use C# exclusively, you should check out EmguCV. They have wrapped most of the library for use with C#.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620707",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Should I keep an instance of DbContext in a separate thread that performs periodic job I have a class Worker which sends emails periodically,I start in Global.asax.cs on App_start()
public static class Worker
{
public static void Start()
{
ThreadPool.QueueUserWorkItem(o => Work());
}
public static void Work()
{
var r = new DbContext();
var m = new MailSender(new SmtpServerConfig());
while (true)
{
Thread.Sleep(600000);
try
{
var d = DateTime.Now.AddMinutes(-10);
var ns = r.Set<Notification>().Where(o => o.SendEmail && !o.IsRead && o.Date < d);
foreach (var n in ns)
{
m.SendEmailAsync("[email protected]", n.Email, NotifyMailTitle(n) + " - forums", NotifyMailBody(n));
n.SendEmail = false;
}
r.SaveChanges();
}
catch (Exception ex)
{
ex.Raize();
}
}
}
}
So I keep this dbcontext alive for the entire lifetime of the application is this a good practice ?
A: DbContext is a very light-weight object.
It doesn't matter whether your DbContext stays alive or you instantiate it just before making the call because the actual DB Connection only opens when you SubmitChanges or Enumerate the query (in that case it is closed on end of enumeration).
In your specific case. It doesn't matter at all.
Read Linq DataContext and Dispose for details on this.
A: I would wrap it in a using statement inside of Work and let the database connection pool do it's thing:
using (DbContext r = new DbContext())
{
//working
}
NOTE: I am not 100% sure how DbContext handles the db connections, I am assuming it opens one.
It is not good practice to keep a database connection 'alive' for the lifetime of an application. You should use a connection when needed and close it via the API(using statement will take care of that for you). The database connection pool will actually open and close connections based on connection demands.
A: I agree with @rick schott that you should instantiate the DbContext when you need to use it rather than keep it around for the lifetime of the application. For more information, see Working with Objects (Entity Framework 4.1), especially the section on Lifetime:
When working with long-running context consider the following:
*
*As you load more objects and their references into memory, the
memory consumption of the context may increase rapidly. This may cause
performance issues.
*If an exception causes the context to be in an unrecoverable state,
the whole application may terminate.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620709",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: fluid image width, matching height I am trying (if it is at all possible) to use css to make an image 100% the width of a fluid div, but as the images are square (and will be distorted if not square) I want to be able to match the height to the width... for fluid width I am using:
.img{
max-width: 100%;
width: 100%;
min-width: 400px;
}
which works fine for setting the width on all major browsers, but I just cant figure out how to match the height to the width :/
A: Try throwing in height:auto into your class.
.img{
max-width: 100%;
width: 100%;
min-width: 400px;
height: auto; // <-- add me
}
As mentioned in the comments though, most browsers should be adjusting and scaling the images correctly. But glad this could help.
A: Now, with CSS3 there is new units that are measured relative to the viewport, (browser window), if you want a fluid image with respect to the window this it works better in most use cases than "%". These are vh and vw, which measure viewport height and width, respectively.
.img{
max-width: 100vw;
width: 100vw;
min-width: 400px;
height: auto;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620710",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Get Request id's per app From documentation:
If a user clicks 'Accept' on a request, they will be sent to the canvas URL of the application that sent the request. This URL will contain an additional parameter, request_ids, which is a comma delimited list of Request IDs that a user is trying to act upon:
http://apps.facebook.com/[app_name]/?request_ids=[request_ids]
How to get all request id's for the current app without knowing their id's and getting them from url?
A: You could use a FQL query:
SELECT recipient_uid, request_id, app_id
FROM apprequest
WHERE recipient_uid = me() AND app_id = 182197005148613
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: DataContractSerializer and Dictionary fails when reading I'm using DataContractSerializer to serialize an object that contains a Dictionary<string,object> member, which is marked with [DataMember()]. The idea is to have a flexible bag of object attributes, and I don't know what those attributes could be.
This works great when I'm putting int, double and string objects into the dictionary, but when I put a List<string> in it fails to deserialize the object with:
System.InvalidOperationException: Node type Element is not supported in this operation.
The entire dictionary is serialized to XML, and it looks pretty reasonable:
<Attributes xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<d2p1:KeyValueOfstringanyType>
<d2p1:Key>name</d2p1:Key>
<d2p1:Value xmlns:d4p1="http://www.w3.org/2001/XMLSchema" i:type="d4p1:string">Test object</d2p1:Value>
</d2p1:KeyValueOfstringanyType>
<d2p1:KeyValueOfstringanyType>
<d2p1:Key>x</d2p1:Key>
<d2p1:Value xmlns:d4p1="http://www.w3.org/2001/XMLSchema" i:type="d4p1:double">0.5</d2p1:Value>
</d2p1:KeyValueOfstringanyType>
<d2p1:KeyValueOfstringanyType>
<d2p1:Key>y</d2p1:Key>
<d2p1:Value xmlns:d4p1="http://www.w3.org/2001/XMLSchema" i:type="d4p1:double">1.25</d2p1:Value>
</d2p1:KeyValueOfstringanyType>
<d2p1:KeyValueOfstringanyType>
<d2p1:Key>age</d2p1:Key>
<d2p1:Value xmlns:d4p1="http://www.w3.org/2001/XMLSchema" i:type="d4p1:int">4</d2p1:Value>
</d2p1:KeyValueOfstringanyType>
<d2p1:KeyValueOfstringanyType>
<d2p1:Key>list-of-strings</d2p1:Key>
<d2p1:Value>
<d2p1:string>one string</d2p1:string>
<d2p1:string>two string</d2p1:string>
<d2p1:string>last string</d2p1:string>
</d2p1:Value>
</d2p1:KeyValueOfstringanyType>
</Attributes>
Note the list-of-strings at the end there. It's got all the values but nothing indicating that it's a List<string> or anything.
What's the correct way of handling this situation?
A: Try using the KnownTypeAttribute so that DataContractSerializer knows about the List<string> type. Unfortunately, that seems to go against your idea of not having to know about the types before hand.
I'm basing this on the following code, which uses DataContractSerializer to serialize a Dictionary<string, object> containing List<string>:
Dictionary<string,object> dictionary = new Dictionary<string, object>();
dictionary.Add("k1", new List<string> { "L1", "L2", "L3" });
List<Type> knownTypes = new List<Type> { typeof(List<string>) };
DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string,object>), knownTypes);
MemoryStream stream = new MemoryStream();
serializer.WriteObject(stream, dictionary);
StreamReader reader = new StreamReader(stream);
stream.Position = 0;
string xml = reader.ReadToEnd();
If you knownTypes is not provided to the DataContractSerializer, it throws an exception.
SerializationException: Type
'System.Collections.Generic.List`1[[System.String, mscorlib,
Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'
with data contract name
'ArrayOfstring:http://schemas.microsoft.com/2003/10/Serialization/Arrays'
is not expected. Consider using a DataContractResolver or add any
types not known statically to the list of known types - for example,
by using the KnownTypeAttribute attribute or by adding them to the
list of known types passed to DataContractSerializer.
A: WCF has no way of knowing that what you have is a List<string> there - notice that all the other <Value> elements have a "type hint" (the i:type attribute). If you want to deserialize it, it needs to have the marking, and you also need to tell WCF that List<string> is a "known type" - see below. For more information on known types (and why they're needed) there are many good resources in the web.
public class StackOverflow_7620718
{
public static void Test()
{
Dictionary<string, object> dict = new Dictionary<string, object>
{
{ "name", "Test object" },
{ "x", 0.5 },
{ "y", 1.25 },
{ "age", 4 },
{ "list-of-strings", new List<string> { "one string", "two string", "last string" } }
};
MemoryStream ms = new MemoryStream();
XmlWriter w = XmlWriter.Create(ms, new XmlWriterSettings
{
Indent = true,
Encoding = new UTF8Encoding(false),
IndentChars = " ",
OmitXmlDeclaration = true,
});
DataContractSerializer dcs = new DataContractSerializer(dict.GetType(), new Type[] { typeof(List<string>) });
dcs.WriteObject(w, dict);
w.Flush();
Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));
ms.Position = 0;
Console.WriteLine("Now deserializing it:");
Dictionary<string, object> dict2 = (Dictionary<string, object>)dcs.ReadObject(ms);
foreach (var key in dict2.Keys)
{
Console.WriteLine("{0}: {1}", key, dict2[key].GetType().Name);
}
}
}
A: I had a similiar idea number of times, and I implemented it with additional field holding assembly qualified names of all Dictionary items. It populates list on every item addition or rewrite, then uses it on serialization and uses XmlReader to extract type information, build list of types and deserialize object.
Code:
[DataContract]
public class Message
{
[DataMember] private List<string> Types = new List<string>();
[DataMember] private Dictionary<string, object> Data = new Dictionary<string, object>();
public object this[string id]
{
get => Data.TryGetValue(id, out var o) ? o : null;
set {
Data[id] = value;
if (!Types.Contains(value.GetType().AssemblyQualifiedName))
Types.Add(value.GetType().AssemblyQualifiedName);
}
}
public byte[] Serialize()
{
var dcs = new DataContractSerializer(typeof(Message), Types.Select(Type.GetType));
using (var ms = new MemoryStream()) {
dcs.WriteObject(ms, this);
return ms.ToArray();
}
}
public static Message Deserialize(byte[] input)
{
var types = new List<string>();
using (var xr = XmlReader.Create(new StringReader(Encoding.UTF8.GetString(input)))) {
if (xr.ReadToFollowing(nameof(Types))) {
xr.ReadStartElement();
while (xr.NodeType != XmlNodeType.EndElement) {
var res = xr.ReadElementContentAsString();
if (!string.IsNullOrWhiteSpace(res))
types.Add(res);
}
}
}
var dcs = new DataContractSerializer(typeof(Message), types.Select(Type.GetType));
using (var ms = new MemoryStream(input))
if (dcs.ReadObject(ms) is Message msg)
return msg;
return null;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620718",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Not able to access cookie in javascript at path / I am using jQuery to access/set the cookies. I have planted a cookie named CookieNo1 at path /.
I planted this using the url localhost:8080/audi.
The cookie value is stored, which I checked manually on the firefox cookies. Now when I try to access the same cookie, using the url localhost:8080/audi/products using $.cookie('CookieNo1');
This doesn't seem to retrieve the value of the cookie. It returns a null value. However when I try to write the cookie using the same localhost:8080/audi/products url, it overwrites the previous cookie value. Please help me with this issue.
All I need is $.cookie('CookieNo1') to return the previous cookie value instead of null.
Thanks in advance
A: You have to set the expiry date. Otherwise, the cookie is removed at the end of the session. In JQuery: $("CookieNo1", "value", {expires: 7}) (this cookie stays for 7 days).
In JavaScript:
document.cookie = "CookieNo1=value; max-age=604800";
max-age sets the maximum lifetime of a cookie, in seconds.
EDIT
Quote from comments:
@RobW I added the cookie using jquery on the page
http://localhost:8080/audi with the code $.cookie("asdftraffic",
valueToSet, { expires: 30, path: '/', secure: true }); I try to
retrieve the cookie from the url http://localhost:8080/audi/products
using '$.cookie('asdftraffic');' which returns null.
Your issue is caused by secure: true. This attribute requires the cookie to be transmitted over a secure connection (https). Remove the secure: true flag if you're not using an encrypted connection.
A: First you set the cookie:
var myvalue = 100, 2000, 300;
$.cookie("mycookie", myvalue);
Then you get the cookie:
var getmycookie = $.cookie("mycookie");
var myvalues = getmycookie.split(",");
var firstval = myvalues[0];
var secondval = myvalues[1];
var thirdval = myvalues[2];
Should'nt be much harder.
When not specifying an expiration, the cookie is deleted on session end i.e. when the browser is closed.
EDIT: You can also specify the path:
$.cookie("mycookie", myvalue, {
expires : 10, //expires in 10 days
path : '/products', //The value of the path attribute of the cookie
//(default: path of page that created the cookie).
domain : 'http://localhost:8080', //The value of the domain attribute of the cookie
//(default: domain of page that created the cookie).
secure : true //If set to true the secure attribute of the cookie
//will be set and the cookie transmission will
//require a secure protocol (defaults to false).
});
I would think something like this would do:
var myvalue = 100, 2000, 300;
$.cookie("mycookie", myvalue, {path : '/audi/products'});
Oh, and a session ends when the browser is closed, not when the page is unloaded, so a session cookie will do.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620725",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: LinqPad Can I connect/and query a runtime object I have a List with a lot of nested objects. And lines down a Linq Query very, very big.
I execute and put a breakpoint here and ask... Can I connect LinqPad to Visual Studio debugger or take the dll, exe, anything, for get this list, and after in LinqPad make simplified query.
In LinqPad connections wizard exist these options: Linq to SQL, Entity Framework or (Linq to SQL "default") WCF Data Services, Microsoft DataMarketService. And none of them seems make this work.
A: If you have a method that returns the big list, you can call that from LINQPad. To do that, press F4 in LINQPad, add a reference to your assembly (.dll or .exe) and optionally add the namespace of your class to namespace imports.
This won't connect you to VS debugger, but directly to the class you are creating.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620734",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Echo defined constant depending on variable without if() in PHP The title might be a bit confusing, but w/e.
Is it possible to do something like this?
define('test_1', 'test1');
define('test_2', 'test2');
define('test_3', 'test3');
$test='2';
echo test_$test;
I simply want to echo one of those defined constants (in this case 2) depending on what $test is, without using if() or switch().
A: You should be sorted with the following:
echo constant('test_'.$test);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620735",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Jquery:Sum values of checkbox on same row to textfield on same row I have some checkboxes with values which need sum up. When the checkboxes are checked the values get added in an array and displayed. Here is a demo link: http://jsfiddle.net/maxwellpayne/gKWmB/
However when I go to a new row it continues summing my values instead of starting afresh emptying the array on row change.The HTML code is long so please view it at the link provided.
Here is the jquery code summing them up:
var total_array = new Array();
var total_amount = 0;
$("#dailyexpense input[type=checkbox]:checked ").live('change', function() {
var check_id = $(this).attr('id');
var valu = $(this).val();
$("#tdtotals input[type=text]").each(function() {
totals_id = $(this).attr('id');
if (totals_id == check_id) {
total_array.push(valu);
total_amount = eval(total_array.join('+')).toFixed(2);
$(this).val(total_amount);
}
});
});
All help will be appreciated
PS: However is editing the code in jsfiddle and distorting everything, stop it.
A: Try this:
http://jsfiddle.net/gKWmB/3/
Basically we rethink the structure. If a checkbox value changes we get its parent row. Then we find all checkboxes in that row. Finally we total them and display.
//watch checkboxes
$('tr input[type=checkbox]').change( function(){
var total = 0;
//total all sibling checkboxes
$(this).parents('tr').find('input[type=checkbox]:checked').each( function() {
total += parseInt($(this).val());
});
//display the result
$(this).parents('tr').find('input[type=text]:last').val(total);
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620736",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Rails 3: Infinity sessions lifetime Now my rails session ends when i close browser. Its' not than i want. I need to create applciations where sessions never ends.
How can i do it?
Thanks.
A: Make a cookie that will login your user every time (s)he visits your site. If that's what you really want.
Know that when your user closes the browser, the session will not "really" end. Since HTTP is stateless, your server will not know when the browser is closed. Hence, this will not end the session.
So, if you want the session to never end, do as what I said in the first paragraph. But think about the consequences when your users are at a public terminal, like an airport. If somebody logs in your site and closes the browser, and somebody else visits your very site, this person will have previous persons' credentials. Do you really want that?
A: In Rails, there are many gems to handle this. It sounds like you need to read up on sessions first. This is not a Rails-specific or Rails-innovated concept. Basically, you need to create users with passwords that you store in a database in an encrypted manner. As @darioo said, you don't want every user to have the same session, do you?
Once you've read up on the philosophy (google it for a few minutes), then you should look at the following gems:
*
*Devise: https://github.com/plataformatec/devise
*Warden (used by devise, et. al.): https://github.com/hassox/warden
You can then add devise to your Gemfile and progress from there.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620738",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Learning how to actually draw with HTML5 canvas I'm trying to learn how to draw to canvas, I read alot of resources it all teachs you about the API and how to use it to draw etc and I found nice resources out there, the problem is now i know how to use the API methods to draw but still I can't figure out how to draw!
Don't get me wrong, I'm not looking forward to learn art concepts etc, I'm talking about simple shapes like a heart or a diamond by example, how do I figure out the coordinates, the x and y of everything I know how to draw an arc but how do I figure out the control points coordinate by example?
In vector drawing softwares you get visual feedbacks while your drawing and I know its harder and more complicated with canvas, but I don't know what or how I should improve this ability. I don't even know what abilities I have to improve...
Do I have to be good in math?
Can any body direct me to the right way to really learn how to draw to HTML5 Canvas?
A: Being good in math is helpful. Drawing "special" shapes is all about defining them as shapes you already know how to paint. A heart for instance, is 2 arcs with 2 diagonal lines, which I'm sure you know how to draw. A diamond is 4 diagonal lines, where every 2 opposing lines are parallel, and all of them are equal in length.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620740",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Which class owns methods and attributes Let's say we have this code:
class C(CC):
a = 1
b = 2
def __init__(self):
self.x = None
self.y = 1
How can I quickly find out in Python where is the attribute or method defined? If it belongs to ancestor class or if it's the method of class C. You can see attributes a, b, x, y . Must they belong to class C? or can they be from ancestor classes? When does the type is assigned to the variable?
Why not rather use
class C(CC):
a = 1
b = 2
x = None
y = 1
thank you
A: In the first example, a and b are attributes of the C class object. (Think "static" attributes.) And x and y are attributes of C instances. (So, regular instance attributes.)
In the second example, all four are attributes of C, not of its instances.
In Python, you can't "declare" attributes as defined by a specific class, which means there are no attribute definitions to inherit to begin with. (More or less, but I'm not going to muddle the waters by introducing __slots__). You can find method definitions by searching for "def method_name(", and method definitions are inherited as in most OO languages.
Confusingly, you can access class attributes through instances of a class, then if you assign a new value to that attribute, a new instance attribute is created:
In [1]: class C(object): a=1
In [2]: c1 = C()
In [3]: c1.a
Out[3]: 1
In [5]: c1.__dict__
Out[5]: {}
In [6]: c1.a=2
In [7]: c1.__dict__
Out[7]: {'a': 2}
In [8]: c2 = C()
In [9]: c2.a
Out[9]: 1
Which does let you give instance attribute default values by using class attributes. I don't believe this is a very common thing to do though – I favour using default values to __init__() arguments.
A: Why not rather use
class C(CC):
a = 1
b = 2
x = None
y = 1
This is not the same thing. This has four class-level attributes which are shared by all objects of class C.
This, is different. It has two class-level attributes shared by all objects of class C and two instance variables which are unique to each object of class C.
class C(CC):
a = 1
b = 2
def __init__(self):
self.x = None
self.y = 1
Your two code samples are very different. They cannot be compared.
To answer your other question, we use GREP and other tools to search the source. It's easy.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620741",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Deferred object confusion The following snippet works as expected:
function boxAnimation() {
var dfd = $.Deferred();
$('div').fadeIn('slow', dfd.resolve);
return dfd.promise();
}
$(function () {
boxAnimation().done(
function () { $(this).animate({ 'margin-top': 50 }); },
function () { $(this).animate({ 'margin-left': 150 }); },
function () { $(this).animate({ 'margin-top': 250 }); },
function () { $(this).animate({ 'margin-left': 350 }); }
).fail(function () { alert('failed'); });
});
However in this one the differed object is neither rejected or resolved.
Please tell me where am I going wrong.
function boxAnimation() {
var dfd = $.Deferred();
var randomNum = Math.floor(Math.random() * 5);
$('div').fadeIn('slow', function () {
if (randomNum == 1) {
dfd.reject;
}
else {
dfd.resolve;
}
});
return dfd.promise();
}
$(function () {
boxAnimation().done(
function () { $(this).animate({ 'margin-top': 50 }); },
function () { $(this).animate({ 'margin-left': 150 }); },
function () { $(this).animate({ 'margin-top': 250 }); },
function () { $(this).animate({ 'margin-left': 350 }); }
).fail(function () { alert('failed'); });
});
my body is:
<div id='box' style='width:200px; height:200px; border:solid 1px #222222; display:none; background:#cccccc'></div>
A: You should call functions; currently you're accessing them and leaving them untouched. By actually calling reject/resolve, you are really rejecting/resolving things.
In the fadeIn in the first example, you passed it without (). This is correct, because you should leave it untouched at that point. jQuery will internally call the function when the animation is done.
Since in the second example the calls are already in a function that is executed when the animation is done, you should call them at that point.
if (randomNum == 1) {
dfd.reject(); // '()' calls a function
}
else {
dfd.resolve();
}
Secondly, inside a done handler, this is the Deferred object. If you want to pass the div, you can do so by passing it when rejecting/resolving: http://jsfiddle.net/PrmQR/1/.
function boxAnimation() {
var dfd = $.Deferred();
var randomNum = Math.floor(Math.random() * 5);
$('div').fadeIn('slow', function () {
if (randomNum == 1) {
dfd.reject(this); // pass div
}
else {
dfd.resolve(this);
}
});
return dfd.promise();
}
$(function () {
boxAnimation().done(
function (x) { $(x).animate({ 'margin-top': 50 }); }, // x is the div
function (x) { $(x).animate({ 'margin-left': 150 }); },
function (x) { $(x).animate({ 'margin-top': 250 }); },
function (x) { $(x).animate({ 'margin-left': 350 }); }
).fail(function () { alert('failed'); });
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620743",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: python SMTP header format The following piece of code is formatting my email script correctly. It is placing the to, from, subject, and body in the correct parts of the email. My problem is that I can't figure out why it needs two returns and two newlines ("\r\n\r\n") in my connect function to display the body in the email when the rest of the headers only need one CR.
def message(self):
subject = input("What is the subject line of your message")
headers = ["from: " + self.sendfrom,
"to: " + self.sendto,
"subject: " + subject,
"content_type: text/html"]
headers = "\r\n".join(headers)
msg = input("type your message")
return headers, msg
def connect(self, headers, msg):
self.server.starttls()
self.server.login(self.usrname,self.pswd)
self.server.sendmail(self.sendfrom, self.sendto, headers + "\r\n\r\n" + msg)
print("I sent the email")
return self.server
Thanks!
A: Because of the standard, body must be separated from the headers with an empty line.
A message consists of header fields and, optionally, a body. The body
is simply a sequence of lines containing ASCII characters. It is
separated from the headers by a null line (i.e., a line with nothing
preceding the CRLF).
e-mail software conforms to these standards and expects an empty line for the body. If there is no empty line, it just assumes the text is part of headers, and usually these email softwares hide most headers by default.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620745",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why do these 2 RegEx benchmarks differ so much? Why do these 2 RegEx benchmarks differ so much?
They use the same RegEx, one in-place and one stored via qr//
Results:
Rate rege1.FIND_AT_END rege2.FIND_AT_END
rege1.FIND_AT_END 661157/s -- -85%
rege2.FIND_AT_END 4384042/s 563% --
Rate rege1.NOFIND rege2.NOFIND
rege1.NOFIND 678702/s -- -87%
rege2.NOFIND 5117707/s 654% --
Rate rege1.FIND_AT_START rege2.FIND_AT_START
rege1.FIND_AT_START 657765/s -- -85%
rege2.FIND_AT_START 4268032/s 549% --
# Benchmark
use Benchmark qw(:all);
my $count = 10000000;
my $re = qr/abc/o;
my %tests = (
"NOFIND " => "cvxcvidgds.sdfpkisd[s"
,"FIND_AT_END " => "cvxcvidgds.sdfpabcd[s"
,"FIND_AT_START " => "abccvidgds.sdfpkisd[s"
);
foreach my $type (keys %tests) {
my $str = $tests{$type};
cmpthese($count, {
"rege1.$type" => sub { my $idx = ($str =~ $re); },
"rege2.$type" => sub { my $idx = ($str =~ /abc/o); }
});
}
A: You are dealing with operations that are intrinsically very fast, so you need to run a few more tests to narrow down on where the speed is going. I have also switched the benchmark model from an external (letting cmpthese do it) to internal (for loop) speed magnification. This minimizes the overhead of the subroutine call and any work that cmpthese has to do. Finally, testing to see if the difference scales with magnitude is important (in this case it doesn't).
use Benchmark 'cmpthese';
my $re = qr/abc/o;
my %tests = (
'fail ' => 'cvxcvidgds.sdfpkisd[s',
'end ' => 'cvxcvidgds.sdfpabcd[s',
'start' => 'abccvidgds.sdfpkisd[s',
);
for my $mag (map 10**$_, 1 .. 5) {
say "\n$mag:";
for my $type (keys %tests) {
my $str = $tests{$type};
cmpthese -1, {
'$re '.$type => sub {my $i; $i = ($str =~ $re ) for 0 .. $mag},
'/abc/o '.$type => sub {my $i; $i = ($str =~ /abc/o) for 0 .. $mag},
'/$re/ '.$type => sub {my $i; $i = ($str =~ /$re/ ) for 0 .. $mag},
'/$re/o '.$type => sub {my $i; $i = ($str =~ /$re/o) for 0 .. $mag},
}
}
}
10:
Rate $re fail /$re/ fail /$re/o fail /abc/o fail
$re fail 106390/s -- -8% -72% -74%
/$re/ fail 115814/s 9% -- -70% -71%
/$re/o fail 384635/s 262% 232% -- -5%
/abc/o fail 403944/s 280% 249% 5% --
Rate $re end /$re/ end /$re/o end /abc/o end
$re end 105527/s -- -5% -71% -72%
/$re/ end 110902/s 5% -- -69% -71%
/$re/o end 362544/s 244% 227% -- -5%
/abc/o end 382242/s 262% 245% 5% --
Rate $re start /$re/ start /$re/o start /abc/o start
$re start 111002/s -- -3% -72% -73%
/$re/ start 114094/s 3% -- -71% -73%
/$re/o start 390693/s 252% 242% -- -6%
/abc/o start 417123/s 276% 266% 7% --
100:
Rate /$re/ fail $re fail /$re/o fail /abc/o fail
/$re/ fail 12329/s -- -4% -77% -79%
$re fail 12789/s 4% -- -76% -78%
/$re/o fail 53194/s 331% 316% -- -9%
/abc/o fail 58377/s 373% 356% 10% --
Rate $re end /$re/ end /$re/o end /abc/o end
$re end 12440/s -- -1% -75% -77%
/$re/ end 12623/s 1% -- -75% -77%
/$re/o end 50127/s 303% 297% -- -7%
/abc/o end 53941/s 334% 327% 8% --
Rate $re start /$re/ start /$re/o start /abc/o start
$re start 12810/s -- -3% -76% -78%
/$re/ start 13190/s 3% -- -75% -77%
/$re/o start 52512/s 310% 298% -- -8%
/abc/o start 57045/s 345% 332% 9% --
1000:
Rate $re fail /$re/ fail /$re/o fail /abc/o fail
$re fail 1248/s -- -8% -76% -80%
/$re/ fail 1354/s 9% -- -74% -79%
/$re/o fail 5284/s 323% 290% -- -16%
/abc/o fail 6311/s 406% 366% 19% --
Rate $re end /$re/ end /$re/o end /abc/o end
$re end 1316/s -- -1% -74% -77%
/$re/ end 1330/s 1% -- -74% -77%
/$re/o end 5119/s 289% 285% -- -11%
/abc/o end 5757/s 338% 333% 12% --
Rate /$re/ start $re start /$re/o start /abc/o start
/$re/ start 1283/s -- -1% -75% -81%
$re start 1302/s 1% -- -75% -80%
/$re/o start 5119/s 299% 293% -- -22%
/abc/o start 6595/s 414% 406% 29% --
10000:
Rate /$re/ fail $re fail /$re/o fail /abc/o fail
/$re/ fail 130/s -- -6% -76% -80%
$re fail 139/s 7% -- -74% -79%
/$re/o fail 543/s 317% 291% -- -17%
/abc/o fail 651/s 400% 368% 20% --
Rate /$re/ end $re end /$re/o end /abc/o end
/$re/ end 128/s -- -3% -76% -79%
$re end 132/s 3% -- -76% -78%
/$re/o end 541/s 322% 311% -- -10%
/abc/o end 598/s 366% 354% 11% --
Rate /$re/ start $re start /$re/o start /abc/o start
/$re/ start 132/s -- -1% -77% -80%
$re start 133/s 1% -- -76% -79%
/$re/o start 566/s 330% 325% -- -13%
/abc/o start 650/s 394% 388% 15% --
100000:
Rate /$re/ fail $re fail /$re/o fail /abc/o fail
/$re/ fail 13.2/s -- -8% -76% -78%
$re fail 14.2/s 8% -- -74% -76%
/$re/o fail 55.9/s 325% 292% -- -8%
/abc/o fail 60.5/s 360% 324% 8% --
Rate /$re/ end $re end /$re/o end /abc/o end
/$re/ end 12.8/s -- -3% -75% -79%
$re end 13.2/s 3% -- -75% -78%
/$re/o end 52.3/s 308% 297% -- -12%
/abc/o end 59.7/s 365% 353% 14% --
Rate $re start /$re/ start /$re/o start /abc/o start
$re start 13.4/s -- -2% -77% -78%
/$re/ start 13.6/s 2% -- -77% -78%
/$re/o start 58.2/s 334% 328% -- -6%
/abc/o start 62.2/s 364% 357% 7% --
You can easily see that the tests are falling into two categories, the ones with /.../o in the source, and the ones without. Since this is a syntatic difference, it gives you clues that it is probably a case that the compiler is optimizing (or that the runtime is allowed to cache in some way). (removing checks of the variables after they have been done once, simplifying the stack, it is hard to say without looking at the source).
The results are probably also dependent on the version of perl being used. The above tests are run on v5.10.1
A: First, the /o does noting because you don't interpolate into that pattern.
Now on to the question.
1/661157 s - 1/4384042 s = 0.000,001,3 s
1/678702 s - 1/5117707 s = 0.000,001,3 s
1/657765 s - 1/4268032 s = 0.000,001,3 s
So =~ $re takes an extra 1.3 microsecond (or 0.68 on my machine). There are three extra Perl ops in the =~ $re case, and that accounts for some of it. I'm not sure why three, though. One is to fetch $re, but I don't know what the other two do.
>perl -MO=Concise,-exec -e"$x =~ /abc/"
1 <0> enter
2 <;> nextstate(main 1 -e:1) v:{
3 <#> gvsv[*x] s
4 </> match(/"abc"/) vKS/RTIME
5 <@> leave[1 ref] vKP/REFC
-e syntax OK
>perl -MO=Concise,-exec -e"$x =~ $re"
1 <0> enter
2 <;> nextstate(main 1 -e:1) v:{
3 <#> gvsv[*x] s
4 <1> regcreset sK/1
5 <#> gvsv[*re] s
6 <|> regcomp(other->7) sK/1
7 </> match() vKS/RTIME
8 <@> leave[1 ref] vKP/REFC
-e syntax OK
1.3 microsecs seems a bit excessive, but it's not really a significant amount.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620747",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How should i classify the nested class given in this example? I was going thru ThreadLocal class and found below example
public class UniqueThreadIdGenerator {
private static final AtomicInteger uniqueId = new AtomicInteger(0);
private static final ThreadLocal < Integer > uniqueNum =
new ThreadLocal < Integer > () {
@Override protected Integer initialValue() {
return uniqueId.getAndIncrement();
}
};
public static int getCurrentThreadId() {
return uniqueId.get();
}
} // UniqueThreadIdGenerator
Wondering the class ThreadLocal created above should be classified as inner class/anonymous class? Not Sure.
A: It's anonymous because it doesn't have a name. Well, not one that has been explicitly created in code anyway, but that's beside the point.
A: It's an anonymous subclass of ThreadLocal.
An inner class is a class which is declared inside of another class declaration, using the class keyword. For example, Bar is an inner class of Foo below:
class Foo {
int a;
boolean b;
class Bar {
String s;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620751",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: change text size of checkbox via c# code I create many checkboxes dynamically in c# ( windows forms ). I want to assign the sizes of the checkboxes' texts. But I couldn't find a way. I want something like that :
CheckBox[] chk = new CheckBox[ff.documentColumnCount];
chk[i].Font.Size = 8.5; // but of course this line doesn't work
what can I do about this,thanks for helping..
A: Something like this perhaps:
chk[i].Font = new Font(chk[i].Font.FontFamily, 8.5f);
A: The Font property is immutable (see Remarks). You have to assign the Font property a new instance of the Font class with the properties that you want.
chk[i].Font = new Font( chk[i].Font.FontFamily, 8.5 );
A: You did not initialized the array. You just declared that there is an array chk of size ff.DocumentCount
Try fix it to the following:
CheckBox[] chk = new CheckBox[ff.documentColumnCount];
for(int i=0; i < ff.documentColumnCount; i++)
{
chk[i] = new CheckBox() { Location = new Point(0, i * 50), Font = new Font(FontFamily.GenericSansSerif, 8.5f) };
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620752",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Stopping Background Service Music package com.falling.inairproandmark;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
public class BackgroundSoundService extends Service {
private static final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.bgmusic);
player.setVolume(100,100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
public void onStart(Intent intent, int startId) {
// TODO
}
public IBinder onUnBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public void onStop() {
}
public void onPause() {
}
@Override
public void onDestroy() {
player.stop();
player.release();
}
@Override
public void onLowMemory() {
}
}
I don't understand coding much...
But what I'm trying to do is play the music thru-out the activities.
Let's say I have 10 activities... I want the music to play while i go through them and when I get a call or exit the application by pressing Home key... Music stops or at least pauses... how do i do that?
Thanks
Wahid
A: You need to launch separate service (different intent filter in the Manifest for the same serivce) in onStartCommand() you'll check the action of the intent i.e if the action has the same value as the one you specified for intent action in the manifest file and if the action matches the intent filter action name then just stop the service.
Example from one of my projects:
In the manifest file:
<service android:name=".MyPlayerService" android:permission="android.permission.MODIFY_AUDIO_SETTINGS">
<intent-filter >
.... some other filters
<action android:name="com.my.player.EXIT"/>
....
</intent-filter>
</service>
In the onStartCommand():
Here we can see the need of specifying action name, which is used to distinguish numerous actions within the same service.
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.i("ON START COMMAND", "Huston, we have a lift off!");
if(intent.getAction().equals("com.my.player.EXIT")
{ // means that you have envoked action that will has to stop the service
MyPlayerService.this.stopSelf(); // See the note below
}else if(//some other actions that has to be done on the service)
}
Note:
Note that here you can simply stop the MediaPlayer from playing or pause it using .stop() or .pause(),or just terminate the service as I provided above.
Now back to the activity. Catching Home button is not good idea. But this you can do in the onDestroy() method, where the activity is not in the stack i.e just before it is destroyed. Here you just launch intent that will signal the service to stop working.
Example:
Intent exit = new Intent("com.my.player.EXIT"); //intent filter has to be specified with the action name for the intent
this.startService(exit);
Read more on Android Dev about stopSelf()
If you are trying this approach starting the MediaPlayer good practice will be to make the playing has its own action name in the intent filter, and do the same checking in the onStartCommand()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620758",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Difference between defaultselenium.shutdownseleniumserver and seleniumserver.stop 1) What is the difference between defaultSelenium.shutDownSeleniumServer() and seleniumServer.stop() ?
I observe that when I just use
defaultSelenium.stop();
seleniumServer.stop();
the browser closes but the server does not shut down. If that is the case, what is the use of seleniumServer.stop()?
2) Is this the right sequence of commands? If not, what is and why?
defaultSelenium.stop();
defaultSelenium.shutDownSeleniumServer();
seleniumServer.stop();
A: Answer to this question can be found on this thread.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620764",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: LINQ in a method to use in _Layout.cshtml I am simply trying to retrieve some data from a database, and display it on the _Layouts.cshtml file. And i wanna do this in the with a method in the models folder, right??
My following script down here works, but it's not pretty, take a look.
Here is my model:
namespace MvcBreakingNews.Models
{
public class ListCategories
{
public IList<string> arrTest() {
IList<string> myList = new List<string>();
DataClassesDataContext dt = new DataClassesDataContext();
var q = from c in dt.categories select c;
foreach (var item in q)
{
myList.Add(item.category1.ToString());
}
return myList;
}
}
}
}
And here is my _Layout.cshtml
@using MvcBreakingNews.Models
...
@{
ListCategories objC = new ListCategories();
foreach (var item in objC.arrTest())
{
<li><a href="#">@item</a></li>
}
}
Now what i want to do, or what i think i want to do. Is to get rid of the foreach loop in my method and send the array directly to the _Layout.cshtml
How would i do this?
A: You can use the ToList() extension method:
public IList<string> arrTest()
{
DataClassesDataContext dt = new DataClassesDataContext();
var q = from c in dt.categories
select c.category1.ToString();
return q.ToList();
}
Or you could return q directly, which would require changing the return type:
public IQueryable<string> arrTest()
{
DataClassesDataContext dt = new DataClassesDataContext();
return from c in dt.categories
select c.category1.ToString();
}
A: Best way of achieving this is to create a BaseController and makes all of your controllers derived from that BaseController.
What your new BaseController does is to pass a model for every single time. I hope you got the idea.
Here is a good example :
How to create a strongly typed master page using a base controller in ASP.NET MVC
A: The shortest way to do the same using Lembda expression is as follows.
public IList<string> arrTest()
{
DataClassesDataContext dt = new DataClassesDataContext();
return dt.categories.select(c=>c.category1.ToString()).ToList();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620765",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: GAE-Sessions: Where is settings.py? I'm using GAE-Sessions with Google App Engine. In the readme file it says "If you want to gae-sessions with Django, add 'gaesessions.DjangoSessionMiddleware' to your list of MIDDLEWARE_CLASSES in your settings.py file." Problem is I don't have a "settings.py" file, nor is one created when a App Engine project is created. What settings.py file is GAE-Sessions referring to?
A: I am using gae-sessions with google appengine django. What I have is a file in the same level as app.yaml which I call it appengine config.
The contents are
from gaesessions import SessionMiddleware
import logging
def webapp_add_wsgi_middleware(app):
app = SessionMiddleware(app, cookie_key="ExampleofarandomKEYforcookieswritewhatyouwant")
return app
In the same level I have also placed the gaesessions folder with the __init__.py file.
A: Download django-nonrel and use the django-admin.py helper to create all the boilerplate project, including settings.py file.
Documentation here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620771",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Executing code after clearInterval I have a setInterval calling a loop which displays an animation.
When I clearInterval in response to a user input, there are possibly one or more loop callbacks in queue. If I put a function call directly after the clearInterval statement, the function call finishes first (printing something to screen), then a queued loop callback executes, erasing what I wanted to print.
See the code below.
function loop() {
// print something to screen
}
var timer = setInterval(loop(), 30);
canvas.onkeypress = function (event) {
clearInterval(timer);
// print something else to screen
}
What's the best way to handle this? Put a delay on the // print something else to screen? Doing the new printing within the loop?
Edit: Thanks for the answers. For future reference, my problem was that the event that triggered the extra printing was buried within the loop, so once this executed, control was handed back to the unfinished loop, which then overwrote it. Cheers.
A: You could also use a flag so as to ignore any queued functions:
var should;
function loop() {
if(!should) return; // ignore this loop iteration if said so
// print something to screen
}
should = true;
var timer = setInterval(loop, 30); // I guess you meant 'loop' without '()'
canvas.onkeypress = function (event) {
should = false; // announce that loop really should stop
clearInterval(timer);
// print something else to screen
}
A: First of all, you probably meant:
var timer = setInterval(loop, 30);
Secondly, are you sure calling clearInterval does not clean the queue of pending loop() calls? If this is the case, you can easily disable these calls by using some sort of guard:
var done = false;
function loop() {
if(!done) {
// print something to screen
}
}
var timer = setInterval(loop(), 30);
canvas.onkeypress = function (event) {
clearInterval(timer);
done = true;
// print something else to screen
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620774",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Stupid thing on checks and sums - Python Which is more CPU intensive, to do an if(x==num): check, or to do a sum x+y?
A: Your question is somewhat incomplete because you are comparing two different operations. If you need to add two things together then testing x==y isn't going to get you anywhere. So presumably you want to compare
if y != 0:
sum += y
with
sum +=y
It's a lot more complex for interpreted languages like Python, but on the hardware a test for non-zero introduces a branch and that in itself can be expensive. But I wouldn't want to say which would be faster without timing.
Throw into the equation different performance characteristics of different architectures and you have another confounding factor.
As always, you are best to write your code in the most natural maintainable way first and then time it. If you feel you need to extract more performance use a profiler to find hot spots and then optimise.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620775",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Comparing String with String Values
Possible Duplicate:
Java String.equals versus ==
I have a string called DomainType which usually holds values like "edu,com,org..etc" from a url. I used an if else statement to help check the data type and output a JOptionPane. For some reason whenever you type any domain type, It gives you the last option.
Here is a Snippet from the code I wrote:
DomainType = URL.substring(URLlength - 3, URLlength);
if (DomainType == "gov") {
JOptionPane.showMessageDialog(null, "This is a Government web address.");
}
else if (DomainType == "edu") {
JOptionPane.showMessageDialog(null, "This is a University web address.");
}
else if (DomainType == "com") {
JOptionPane.showMessageDialog(null, "This is a Business web address.");
}
else if (DomainType == "org") {
JOptionPane.showMessageDialog(null, "This is a Organization web address");
}
else {
JOptionPane.showMessageDialog(null, "This is an unknown web address type.");
}
so the DomainType gives me edu or com no problem but i think it's my if statement I'm not doing right.
A: When comparing strings, never use ==, use equals. So, instead of
DomainType == "org"
use
DomainType.equals("org")
Why? == will compare references. That means: memory values. And they may not be equal for your strings. equals will compare values, and that is what you want.
A: To compare content use equals, not == (which compares references):
if (DomainType.equals("gov")) {
A: On a side note, a mega-if is probably not the most elegant way to do that - http://www.antiifcampaign.com/ - sorry, just being pedantic.
The .equals() method is the right way to compare objects indeed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620779",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Sql query causes python to crash The following query causes python to crash ('python.exe has encountered a problem ...'
Process terminated with an exit code of -1073741819
The query is:
create temp table if not exists MM_lookup2 as
select lower(Album) || lower(SongTitle) as concat, ID
from MM.songs
where artist like '%;%' collate nocase
If I change from "like" to = it runs as expected, eg
create temp table if not exists MM_lookup2 as
select lower(Album) || lower(SongTitle) as concat, ID
from MM.songs
where artist = '%;%' collate nocase
I am running python v2.7.2, with whatever version of sqlite that ships in there.
The problem query runs without problem outside python.
A: You didn't write the database system/driver you are using. I suspect that your SQL is the problem. The % characters needs to be escaped. Possibly the db driver module tries to interpret %, and %) as format chars, and it cannot convert non-existing parameter value into a format that is acceptable by the database backend.
Can you please give us concrete Python code? Can you please try to run the same query but putting the value of '%,%' into a parameter, and pass it to the cursor as a parameter?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620783",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: SQLite/JDBC inner join I have found what appears to be a bug in the SQLite JDBC driver, but I thought I'd see if someone could spot any boneheaded errors on my part. I have the following query:
SELECT
SKU_ATTR_VALUE.*,
Product.ProductID
FROM
SKU_ATTR_VALUE
INNER JOIN SKU
ON SKU_ATTR_VALUE.SkuID=SKU.SkuID
INNER JOIN Product
ON SKU.ProductID=Product.ProductID
WHERE Product.ProductID=?
Pretty simple. I can run this in the SQLite database browser, replacing the ? with 1, and it returns 18 rows, which is just what it should do. Only 18 rows match the condition. But when I run this in Java, and pass in the value 1, I get 817 values back. And that's not a Cartesian join; there are 864 possible values in SKU_ATTR_VALUE. The results I get back have at least one value for each record in Product too...so I really can't imagine what is happening.
I've been looking at this a while and I'm completely stumped. Googling it doesn't seem to turn anything up. Yes, I'm sure that I'm running the Java query against the same SQLite database as in the SQLite browser.
The name of the SQLite jar is sqlitejdbc-v056.jar. It is based on SQLite 3.6.14.2.
Here is the Java code that sets up the query:
String sql = "SELECT SKU_ATTR_VALUE.*, Product.ProductID " +
"FROM SKU_ATTR_VALUE " +
" INNER JOIN SKU ON SKU_ATTR_VALUE.SkuID=SKU.SkuID " +
" INNER JOIN Product ON SKU.ProductID=Product.ProductID " +
"WHERE Product.ProductID=?";
ps = conn.prepareStatement(sql);
ps.setInt(1, productID);
ResultSet rs = ps.executeQuery();
A: According to this document section "5.0 Joins" : you can try to rewrite your query like this :
SELECT
SKU_ATTR_VALUE.*,
Product.ProductID
FROM
Product, SKU, SKU_ATTR_VALUE
WHERE
Product.ProductID=?
AND SKU.ProductID=Product.ProductID
AND SKU_ATTR_VALUE.SkuID=SKU.SkuID
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620792",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: c++ linker error when method is defined out of header file
Possible Duplicate:
Where to define C++ class member template function and functors that instantiate it?
inclusion of header files in case of templates
I am using class templates. I have several methods in my my class and if I define them in the .cpp file I am getting the linker error
error LNK2019: unresolved external symbol
Do all methods in template classes need to be defined in the header file? It makes my code look yucky but if it's the only way I am fine with it.
A:
Do all methods in template classes need to be defined in the header file?
Yes. But you can still factor out the parts that don't rely on template arguments and put those in a regular modules as ordinary functions or as a mixin class:
class NonTemplatedOpsMixin
{
int bar(); // defined elsewhere
};
template <typename T>
class TemplatedStuff : private NonTemplatedOpsMixin
{
T foo(T &x) { x += bar(); }
};
A:
Do all methods in template classes need to be defined in the header file?
Yes: for compiler to instantiate the template method definition, it must have the body of the method available to it.
It makes my code look yucky
One common technique is to have separate sections in your header:
template <typename T> class Foo {
int Method();
};
// Other classes ...
// Now supply implementation details, not relevant to users of the class
template <typename T> int Foo<T>::Method()
{
// implementation
}
// Other implementations
Another technique is to move bodies into a separate header file, e.g. foo-inl.h, and #include "foo-inl.h" from foo.h
A:
Do all methods in template classes need to be defined in the header file?
Yes
It makes my code look yucky but if it's the only way I am fine with it.
In that case, you can include the .cpp file in the header as:
//filename.h
template<typename T>
class whatever
{
//...
};
#include "filename.cpp" //write this at the bottom of filename.h
It's equivalent to providing all the template definitions in the header itself, but physically you've two files.
Alright, as the comment says, the build-system might not be happy with the extension .cpp, in that case, you can choose .h instead (or .hpp). It's safe now.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620803",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Weird imoperfection in Ruby blocks
Possible Duplicate:
What is the difference or value of these block coding styles in Ruby?
# This works
method :argument do
other_method
end
# This does not
method :argument {
other_method
}
Why?
It seems like the interpreter is confused and thinks that the { ... } is a hash.
I always get angry when an interpreter can't understand a code that is actually valid. It resembles PHP that had many problems of this kind.
A: It doesn't think it's a hash - it's a precedence issue. {} binds tighter than do end, so method :argument { other_method } is parsed as method(:argument {other_method}), which is not syntactically valid (but it would be if instead of a symbol the argument would be another method call).
If you add parentheses (method(:argument) { other_method }), it will work fine.
And no, the code is not actually valid. If it were, it would work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620804",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Working with Resources and User-defined Control Properties I am creating a custom control and it is a button. It may has a type and a specified image according to its type. Its type may be:
public enum ButtonType
{
PAUSE,
PLAY
}
Now I can change its appearance and Image with a method:
public ButtonType buttonType;
public void ChangeButtonType(ButtonType type)
{
// change button image
if (type == ButtonType.PAUSE)
button1.Image = CustomButtonLibrary.Properties.Resources.PauseButton;
else if (type == ButtonType.PLAY)
button1.Image = CustomButtonLibrary.Properties.Resources.PlayButton;
buttonType = type;
}
OK, this method doesn't seems so good, for example maybe later I wish to have another type STOP for example for this button, I want just add its image to resources and add it to ButtonType enum, without changing this method.
How can I implement this method to be compatible with future changes?
A: One thing you can do is turn ButtonType into a base class (or an interface, if you prefer):
public abstract class ButtonType
{
public abstract Image GetImage();
}
Then each of your types becomes a subclass:
public class PauseButtonType : ButtonType
{
public Image GetImage()
{
return CustomButtonLibrary.Properties.Resources.PauseButton;
}
}
public class PlayButtonType : ButtonType
{
public Image GetImage()
{
return CustomButtonLibrary.Properties.Resources.PlayButton;
}
}
Your image changing method then becomes:
private ButtonType buttonType; // public variables usually aren't a good idea
public void ChangeButtonType(ButtonType type)
{
button1.Image = type.GetImage();
buttonType = type;
}
This way when you want to add another type, you add another ButtonType subclass and pass it to your ChangeButtonType method.
Since this method is on your custom button class, I would probably take this a bit further and encapsulate style/appearance in a class:
public class ButtonStyle
{
// might have other, non-abstract properties like standard width, height, color
public abstract Image GetImage();
}
// similar subclasses to above
And then on the button itself:
public void SetStyle(ButtonStyle style)
{
this.Image = style.GetImage();
// other properties, if needed
}
You could set up button behaviours (i.e. actions they perform when they're clicked) in a similar way with a ButtonAction base class and assigning specific actions like Stop and Play when you want to change the button's purpose and style.
A: Don`t know if this is the best option, but you can create a custom property to your enum, containing the image
public enum ButtonType
{
[ButtonImage(CustomButtonLibrary.Properties.Resources.PauseButton)]
PAUSE,
[ButtonImage(CustomButtonLibrary.Properties.Resources.PlayButton)]
PLAY
}
I won't go into detail about this, as this is easy to google for... In fact, this is a good resource to start:
http://joelforman.blogspot.com/2007/12/enums-and-custom-attributes.html?showComment=1317161231873#c262630108634229289
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620806",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Zend_Cache memfs file vs APC I just wanted to ask if anybody has got any experience with PHP Caching, or even in particular Zend_Cache with respect to using as backend a file on memfs in contrast to using APC for data caching.
The advantage of using memfs would be the ability to using tags for cleaning from cache tagged variables.
Thanks in advance!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620807",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rails design pattern: multiple "perspectives" of the same object I have a Project, which can bee seen by Manager, Contractor, Worker etc. Each of these roles can see some part of a project but not the other. Furthermore, some actions won't be available for past projects.
I currently have one view for each role and conditional on project status. That's a lot of views. How should I DRY it up?
Thank you.
A: How about permissions for each role (for example Ability in cancan), and then using those permissions on each relevant attribute of Project? You'd have conditional code for every field/attribute, but at least you only have to write it once.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620808",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: TextWrapping not working on horizontal StackPanel I have a panorama item
<controls:PanoramaItem Header="Stream" Margin="0,-16,0,0">
<ListBox Margin="0,-16,0,0" ItemsSource="{Binding Items}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="6,0,0,10">
<StackPanel Margin="6,0,0,10" Orientation="Horizontal">
<Image Source="{Binding ProfileImage}"
VerticalAlignment="Top"
Margin="0,4,0,0"
Width="48" Height="48"
/>
<!-- This doesn't work -->
<TextBlock Text="{Binding ProfileName}"
TextWrapping="Wrap"
Style="{StaticResource PhoneTextTitle2Style}"/>
<TextBlock Text="{Binding RelativeTime}"
Margin="2,10,0,2"
Style="{StaticResource PhoneTextSubtleStyle}"/>
</StackPanel>
<!-- This works -->
<StackPanel Margin="0,-4,0,17" Orientation="Vertical">
<TextBlock Text="{Binding Content}"
TextWrapping="Wrap"
Style="{StaticResource PhoneTextNormalStyle}"/>
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</controls:PanoramaItem>
I need to make ProfileName text wrap and I would like, if possible, to make RelativeTime to float right.
How can I do it?
A: Makes sense, in a horizontal StackPanel there is no obvious Width constraint to make the Textblock wrap. You could add such a constraint, but that requires providing Pixels.
Just looking at the XAML I think that maybe you want a Grid with 3 columns here, not a StackPanel.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620809",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: WCF 4 - TransportWithMessageCredential using X.509 certificates for transport and message security I'm trying to make a WCF4 service hosted on IIS which will use X.509 certificates for message security and SSL with required mutual authentication for transport security (project specification requires the use of WS-Security AND SSL, AFAIK only one is usually the way to go, but never mind).
I made my TestRootCA and used it to issue a server certificate (localhost) and a client certificate (TestUser). I first wanted to establish and test transport security only, so I configured IIS to use https, configured SSL certificate (localhost cert that I made), and configured IIS to require a client certificate from clients. I then modified service web.config, made the corresponding svcutil.conf and ran svcutil that successfully made client proxy class and app.config for my test WinForms app. I set the certificate when creating proxy client by calling:
var client = new ServiceClient();
client.ClientCredentials.ClientCertificate.SetCertificate(System.Security.Cryptography.X509Certificates.StoreLocation.CurrentUser, System.Security.Cryptography.X509Certificates.StoreName.My, System.Security.Cryptography.X509Certificates.X509FindType.FindBySubjectDistinguishedName, "CN=TestUser");
MessageBox.Show(client.GetData(42));
So far so good. But when I modify service's web.config to use TrasportWithMessageCredential (instead of Transport) and specify "Certificate" as the clientCredentialType for message security I get HTTP 403 - The HTTP request was forbidden with client authentication scheme 'Anonymous', even though I specified "Certificate".
My final web.config looks like this:
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="wsHttpEndpointBinding">
<security mode="TransportWithMessageCredential">
<transport clientCredentialType="Certificate"/>
<message clientCredentialType="Certificate"/>
</security>
</binding>
</wsHttpBinding>
</bindings>
<services>
<service behaviorConfiguration="serviceBehavior" name="Service">
<endpoint binding="wsHttpBinding" bindingConfiguration="wsHttpEndpointBinding" name="wsHttpEndpoint" contract="IService" />
<endpoint address="mex" binding="wsHttpBinding" bindingConfiguration="wsHttpEndpointBinding" name="mexEndpoint" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="serviceBehavior">
<serviceMetadata httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
and my client app.conf:
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="wsHttpEndpoint" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false" />
<security mode="TransportWithMessageCredential">
<transport clientCredentialType="Certificate"/>
<message clientCredentialType="Certificate"/>
</security>
</binding>
</wsHttpBinding>
</bindings>
<client>
<endpoint address="https://localhost/WCFTestService/Service.svc" binding="wsHttpBinding" bindingConfiguration="wsHttpEndpoint" contract="IService" name="wsHttpEndpoint" />
</client>
</system.serviceModel>
Any ideas?
EDIT:
I've managed to get it working by changing IIS SSL settings for Client certificate from require to accept. It seems that when I introduce message security using certificates over transport security using SSL, the client uses the certificate for message signing but not for mutual authentication over SSL (it tries to log on as anonymous even though it has a certificate assigned).
Not sure why this is happening, I'd like some comment from an expert :).
A: As stated in the question, I got it working by changing IIS SSL settings for Client certificates from require to accept. Then in the service entry point I programmaticaly check the remote user's certificate (if its not null and valid).
A: You must specify the certificates to use to encrypt the message in the behavior section since these could be different as the ones used to establish the https channel
it would look like this in the server
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="serviceBehavior">
<serviceCredentials>
<serviceCertificate findValue="ServerCertificate"
storeLocation="CurrentUser"
storeName="My"
x509FindType="FindByIssuerName" />
<clientCertificate>
<certificate findValue ="ClientCertificate"
storeLocation="CurrentUser"
storeName="My"
x509FindType="FindByIssuerName"/>
<authentication certificateValidationMode ="PeerTrust"/>
</clientCertificate>
</serviceCredentials>
<serviceMetadata httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
and do the same in the client, that would look like this
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="wsHttpEndpoint" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false" />
<security mode="TransportWithMessageCredential">
<transport clientCredentialType="Certificate"/>
<message clientCredentialType="Certificate"/>
</security>
</binding>
</wsHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="ClientCredentialsBehavior">
<clientCredentials>
<clientCertificate x509FindType="FindBySubjectName"
findValue="ClientCertificate"
storeLocation="CurrentUser"
storeName="My"/>
<serviceCertificate>
<defaultCertificate x509FindType="FindBySubjectName"
findValue="ServerCertificate"
storeLocation="CurrentUser"
storeName="My"/>
</serviceCertificate>
</clientCredentials>
</behavior>
</endpointBehaviors>
</behaviors>
<client>
<endpoint address="https://localhost/WCFTestService/Service.svc" binding="wsHttpBinding" bindingConfiguration="wsHttpEndpoint" contract="IService" name="wsHttpEndpoint" behaviorConfiguration="ClientCredentialsBehavior" />
</client>
</system.serviceModel>
Off course, you have to set the right location and name of the certificates, in the server and client.
I hope this still helps
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620810",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Java Program execution in cmd without using set path or system variables I'm trying to execute a simple java program ("HelloWorld") in command prompt without using the set path option or setting the system variable. Suppose the java program is in D:\My_Programs and the java executable files are in C:\Program Files\Java\jdk1.6.0_24\bin. Here's what I did to compile:
C:\Program Files\Java\jdk1.6.0_24\bin>javac D:\My_Programs\HelloWorld.java It is creating a .class file but the same strategy for execution creates an exception:
C:\Program Files\Java\jdk1.6.0_24\bin>java D:\My_Programs\HelloWorld
Exception in thread "main" java.lang.NoClassDefFoundError: D:\My_Programs\HelloW
orld
Caused by: java.lang.ClassNotFoundException: D:\My_Programs\HelloWorld
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
Could not find the main class: D:\My_Programs\HelloWorld. Program will exit.
Can someone suggest on how to execute this file.
Thanks in advance for your help.
The code:
class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
A: Please try this one:
C:\Program Files\Java\jdk1.6.0_24\bin>java -cp D:\My_Programs HelloWorld
or even that one:
C:\anywhere> C:\Program Files\Java\jdk1.6.0_24\bin\java -cp D:\My_Programs HelloWorld
The -cp tells the java executable where to look for the class HelloWorld. Giving a file-like argument D:\My_Programms\HelloWorld where Java assumes a pure packagename+classname will not work.
A: Since you were in the Java directory rather than the directory of your program when you ran javac the class file is probably there as well. That's generally a bad thing - you want javac and java to be in your path so you can execute them while you're in your program directory. And then you can execute the program using java HelloWorld
A: You can try this way java -cp "D:\My_Programs" HelloWorld,the precondition is that HelloWorld.java you compiled is a main class.
A: java -cp D:\My_Programs HelloWorld
Because the directory hierarchy from the class hierarchy to be considered.
A: You can also try with changing your directory in cmd by cd D:\My_Programs and then execute java HelloWorld. it will execute the file. The only pre condition is that class file should be present at that location.
A: Before running the .java file in cmd, rename the file to the class name only then will it work. For example in this case, save the notepad file as 'HelloWorld.java'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620811",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ListView Image Selection Mask I have a ListView in View = LargeIcons. I added an icon which I have done as PNG (black with white background, 32bit ARGB) and two icons I have done with System.Drawing.Graphics (white background, Pixelformat 32bppArgb).
When I selected the icons in the list, the PNG is masked/highlighted fine, but my custom icons drawn programatically have awful artefacts when masked/highlighted (last two ones in the screenshot).
Have a look:
How can I render my icons as fine as the external graphic?
Generation code:
Bitmap bmp = new Bitmap(THUMB_WIDTH, THUMB_HEIGHT, formatThumbs);
using(Graphics g = Graphics.FromImage(bmp))
{
g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy;
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
g.Clear(Color.White);
g.DrawEllipse(penThumbLine, 1, 1, THUMB_WIDTH - 2, THUMB_HEIGHT - 2);
}
return bmp;
When I change the Clear color to Color.Transparent there is no highlight visible when the entry/icon is selected. The ImageList TransparentColor is Color.Transparent.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620812",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: OpenGL custom transformation trouble I am trying to cast a shadow with a projection transformation. But it seems that OpenGL doesn't like my matrix as it does not draw anything after glMultMatrix. After I pop my matrix everything's ok.
I'm also using JOGL, maybe the problem's with that, but I doubt it since my custom translation and rotation matrices work fine.
The matrix looks like this:
lightPosition = {x, y, z, 1}
planeEquation = {a, b, c, d}
pl = a*x + b*y + c*z + d
a*x-pl b*x c*x d*x
a*y b*y-pl c*y d*y
a*z b*z c*z-pl d*z
a b c d-pl
Now this is a matrix which I calculated, but I also used two other flavors I searched for on the internet; one a bit different, and another which is exactly like mine times -1.
Is this enough information? Or should I submit code also?
Maybe it's my plane equation?
three points on plane = p0, p1, p2
v0 = p1 - p0
v1 = p2 - p0
n = {a, b, c} = v0 (cross) v1
d = -(n (dot) p0)
planeEquation = {a, b, c, d}
Does it sound familiar to anyone? Or it's just a code thing?
EDIT: There's this test that I'm trying to do, and that to draw a single vertex point with and without the matrix (for an x-z plane and a {0, 20, 0} spot light), and with an orthogonal projection matrix. Also, I'm trying to calculate myself the normalized device coordinates of that vertex by getting OpenGL's projection and model view matrices and multiplying it with them, and normalizing with the w coordinate.
What I get is that without my "shadow matrix" it displays the point nicely and it seems my calculations of the vertex match what I'm seeing. But with my "shadow matrix" I get nothing, although the vertex's coordinates lie within the [-1,1] range on all axes.
This is just too strange...
EDIT: added test program here: https://gist.github.com/e0c54d5ab3cbc92dffe6
A: It may, that you simply transposed the matrix passed to OpenGL. OpenGL's matrix indexing is a bit counterintuitive at first (it makes sense though, if you understand the matrix as a row vector of column vectors) OpenGL indices the following:
0 4 8 c
1 5 9 d
2 6 a e
3 7 b f
In contrast to the C row major ordering
0 1 2 3
4 5 6 7
8 9 a b
c d e f
A: Figured it out (this is the author of the question). It was just a typo, I didn't calculate the plane's normal in the right direction...
It's not like I said it to be (v0 X v1) it was accidentally (v1 X v0). You can see it in the code. So, if the plane is directed the other way, you can't project on it.
Because it's a silly mistake like that. For all you wanting to know the math behind this matrix projection on a plane, I'll try to explain it:
Before I begin, I assume a little rough knowledge of linear algebra. Not much is needed.
Let's say we have a plane with normal N, with a point Q on it. For every point P, (P-Q).N=0 (that's a dot product) if (and only if) P is on the plane, since the vectors (P-Q) and N are perpendicular.
Now let's assume we also have a (fixed spot light) point S. We would like to project a point P on our plane from that spot light. This means we would like to find the point R, that is somewhere on the line defined by the points P and S, and that is also on the plane. In other words, find a scalar t, such that S+t(P-S)=R, such that R is on the plane. (P-S) is the direction vector from the spot light through the point P. We "walk" on that vector a certain amount t, starting from the point S until we land on the plane.
From 2 paragraphs ago, we learned a nice trick to know if a point is on the plane or not. So if we apply that on R we get that R is on the plane if (and only if):
N.(R-Q)=0
N.R-N.Q=0
N.R=N.Q
N.(S+t(P-S))=N.Q
N.S+tN.(P-S)=N.Q
t=(N.Q-N.S)/(N.(P-S))
Now, if we put this back in the definition of R:
R=S+(N.Q-N.S)*(1/(N.(P-S))*(P-S)
Let's define N.(P-S) to be k
kR=(N.(P-S))*S+(N.Q-N.S)*P-(N.Q-N.S)*S
kR=(N.P)*S+(N.Q-N.S)*P-(N.Q-N.S)*S-(N.S)*S
kR=(N.P)*S+(N.Q-N.S)*P-(N.Q)*S
Let's remind ourselves what we know, and what we don't know, and what we want to know. We know N and Q and S. P is given to us, and we would like to find R. In other words, we would like to express R given P, and using N, Q and S. Let's continue breaking this down a bit further,
kR=(N_x*P_x+N_y*P_y+N_z*P_z)*S+(N.Q-N.S)*P-(N.Q)*S
R is point, so let's define each of its coordinates, with the coordinates of P (and also S because we also have him on the right side of the equation there).
kR_x=[N_x*S_x+(N.Q-N.S)]P_x+[N_y*S_x]P_y+[N_z*S_x]P_z-(N.Q)*S_x
kR_y=[N_x*S_y]P_x+[N_y*S_y+(N.Q-N.S)]P_y+[N_z*S_y]P_z-(N.Q)*S_y
kR_z=[N_x*S_z]P_x+[N_y*S_z]P_y+[N_z*S_z+(N.Q-N.S))]P_z-(N.Q)*S_z
It may seem like we didn't get anything, since we got that k on our left side, and we still need to divide by it (and that k is defined by P none the less!). Not to worry, because OpenGL uses four element vectors and not three. That last fourth element is used for translation matrices and perspective depth interpolation. For our needs right now, all we should know is that openGL divides the coordinates of each vertex by it's fourth element. This means is that that dreaded k is our fourth element. we get:
R_w=k
R_w=N.(P-S)
R_w=N.P-N.S
R_w=[N_x]P_x+[N_y]P_y+[N_z]P_z-N.S
Alright, we defined our R through P, using N, S and Q. Let's put that in a matrix M. We want:
M*P=R
So,
M=
N_x*S_x + (N.Q-N.S), N_y*S_x, N_z*S_x, -(N.Q)*S_x
N_x*S_y, N_y*S_y + (N.Q-N.S), N_z*S_y, -(N.Q)*S_y
N_x*S_z, N_y*S_z, N_z*S_z + (N.Q-N.S), -(N.Q)*S_z
N_x, N_y, N_z, -(N.S)
While staring at this, remember that since P is a point it's fourth element is 1. (!=0, to be precise but we can assume it's a device normalized vertex)
About the plane equation. The plane equation is a vector, which has its first three elements as the normal. And its fourth element is its signed distance from the origin. Another way to calculate the distance of the plane from the origin is:
Given a point Q on the plane with normal N, the plane's distance from the origin is |N.Q|
Pretty simple, right? This is correct since :
N.Q=|N|*|Q|*cos(N,Q)
and |N|=1, giving us:
N.Q=|Q|*cos(N,Q)=|Q|*d/|Q|=d
where d is the distance to the plane from the origin. Or, it's the size of the vector N; and N's magnitude is the size of the distance to the plane from the origin. You can see that by drawing the plane, choosing some point Q on the plane, drawing the normal N reaching out to the plane from the origin, and looking at the triangle made from the lines made by the two vectors and the plane.
In the above matrix replace -N.Q with d (the last element in the plane equation) and you're done. (d = -N.Q). That matrix given point P, will project it onto the plane defined by N and Q, from the spot light defined by S.
Hope that teaches you something new. If I made a mistake, comment and I'll fix it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620813",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I convert MD5 hex strings to base-64 MD5 strings? I have a bunch of MD5-hashed passwords which I would like to convert to crypt-style MD5.
If I have the plaintext I can easily create both:
% echo -n 'testpass' | md5sum
179ad45c6ce2cb97cf1029e212046e81 -
% echo -n 'testpass' | openssl passwd -1 -stdin -salt ''
$1$$JN/baUhJCUwYKagp48tsP0
But how do I convert 179ad45c6ce2cb97cf1029e212046e81 to JN/baUhJCUwYKagp48tsP0?
A: The first string is in hex and the second string is a base64.
A MD5 hash is a 128bit number .. The ways it can chosen to be printed can be either as a hexdecimal string or as a base64 encoded string -- both are just representations of the 128 bit number.
However ms5sum and openssl passwd will not encrypthash the the password to the same 128 hash value, so the same password will not yield the same 128bit number, so in your examples one password-hash will not translate to the other
A: You say you have some MD5 hashed passwords that you want to convert to "crypt-style" MD5. If that is the case then you're likely wanting to generate a file you can use for authenticating Apache users. Unfortunately, you likely can't do this from plain MD5 hash values.
Apache's MD5-Crypt hash algorithm isn't an MD5 sum of the password alone. Neither is the -1 variant. The two append something to or otherwise modify the input password not including salt to give the resulting hash. If indeed you have the MD5 hash values using the method you describe piping a string to md5sum, that resulting hash cannot be reversed to anything you can then hash to an htpasswd compatible hash.
Sorry
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620817",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Save Numbers in File into a 2D Array i have some numbers in my file like this:
22 33 44 55
11 45 23 14
54 65 87 98
and i want to save them(after i split) in a two dimension array like:
x[0][1]==33
how can i do that??
edit:
i wrote some parts of it,i put comment in code:
StreamReader sr = new StreamReader(@"C:\Users\arash\Desktop\1.txt");
string[] strr;
List<List<int>> table = new List<List<int>>();
List<int> row = new List<int>();
string str;
while ((str = sr.ReadLine()) != null)
{
strr = str.Split(' ');//here how should i save split output in two dimension array??
}
TIA
A: One way of doing it can be like this:
StreamReader sr = new StreamReader(@"C:\Users\arash\Desktop\1.txt");
List<int[]> table = new List<int[]>();
string line;
string[] split;
int[] row;
while ((line = sr.ReadLine()) != null) {
split = line.Split(' ');
row = new int[split.Count];
for (int x = 0; x < split.Count; x++) {
row[x] = Convert.ToInt32(split[x]);
}
table.Add(row);
}
table can then be accessed like this:
table[y][x]
A: By using nested loop you can easily create multidimensional array.
Nest two loops, the outer iterating over lines in the input, the inner over numbers in a line.
Or you can you Linq
var myArray = File.ReadAllLines(@"C:\Users\arash\Desktop\1.txt")
.Where(s=> !string.IsNullOrWhiteSpace(s))
.Select(l => l.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries)
.Select(n => Convert.ToInt32(n)).ToArray()).ToArray();
myArray[0][1] gives you 33
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620828",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Whats the most efficient way to loop through an array and insert data I have an array in php which is populated via XML. this array holds roughly 21000 items.
I am currently looping through the array, checking if the name node exists in the database (mysql) if it does update it, else insert new data and store the row id of the inserted/updated row, i then in the same loop insert more data into another table and link it to the first table:
http://pastebin.com/iiyjkkuy
the array looks like this: http://pastebin.com/xcnHxeLk
Now due to the large amount of nodes in the array (21000) this is exceeding the 300 sec (5 mins) max execution time on my dev system..
What is the best way to loop through an array of this size and insert data?
just some more information on this. I am using expression engine 1.8.6 (work reasons) and i have to use its built in database class.
the reason for the select statements before each insert/update is to grab the row ID for future statements. The data has to be structured in the DB in a certain way, for example:
each source node has a papergroup node - this needs inserting / updating first
then each paper name node needs to be linked to the paper group in the same table
sourceid etc are then inserted into a sources table with a link to there parent paper in the papers table so basic db schema is this:
papergroup inserted into papers table
paper name inserted into papers table with papers.PID as the link to the papger group papers.ID
sources are inserted into the sources table and linked to papers table on source.paperID
the basic structure of the XML source that populates the array is as follows:
<sources>
<source>
<sourceid>1</sourceid>
<papername>test</papername>
<papergroup>test group</papergroup>
<papertype>Standard</papertype>
<sourcename> test source</sourcename>
<sourcesize>page</sourcesize>
</source>
</sources>
the above is not a full segment but it shows the point about all the information being sent in one section. Hope this helps.
Ok I manage to get some timings. It takes 1:35:731 to get the XML it then takes between 0:0:025 and 0:0:700 to do an array loop (select, insert/update)
A: Every time you insert a record is another round trip to the database.
I wonder if your life would be better if you could batch those SQL commands into a single round trip and execute them all at once? You'd cut down on the network latency that way.
The best way to figure out how to optimize anything is to have some hard data as to where the time is being spent. Find out what's taking the most time, change it, and re-measure. Repeat the exercise until you get acceptable performance.
I don't see any data from you. You're just guessing, and so is everyone else who answers here (including me).
A: I'll write it as algorithm.
Store the first array inside of a new variable. $xmlArray;
SELECT the table to compare against from the databse and store it in a variable. $tableArray
foreach through $xmlArray and compare against $tableArray
Save the needed updates into a new array, $diffArray;
Prepare a statement using PDO prepare() and bindParam()
foreach through $diffArray, change the parameters only and execute()
This should be the most efficient way to do what you need.
A: I guess the simplest and one of the way is create batch array for insertion of say around 1500 records and do a batch insert. I tried this with 2k insert in while loop and single insert then it took 27 secs to insert 2000 records but with a single insert batch it took only .7 sec...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620831",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Server Client Program in Java I'm implementing a program where the controller(server) calls the agent(client) periodically and sends it IP address.
Controller.java
public class Controller {
static int discoveryInterval;
NetworkDiscovery n1;
Controller(){
discoveryInterval=6000;
}
public static void main(String[] args) throws IOException {
Timer t1=new Timer();
t1.schedule(new NetworkDiscovery(), discoveryInterval);
}
}
NetworkDiscovery.java-
import java.io.*;
public class NetworkDiscovery extends TimerTask {
protected DatagramSocket socket = null;
protected BufferedReader in = null;
public NetworkDiscovery() throws IOException {
this("NetworkDiscovery");
}
public NetworkDiscovery(String name) throws IOException {
super(name);
socket = new DatagramSocket(4445);
}
public void run() {
try {
byte[] buf = new byte[256];
// receive request
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
// figure out response
String dString = InetAddress.getLocalHost().toString();
buf = dString.getBytes();
// send the response to the client at "address" and "port"
InetAddress address = packet.getAddress();
int port = packet.getPort();
packet = new DatagramPacket(buf, buf.length, address, port);
socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
}
socket.close();
}
}
On the Agent(client's side)-
Agent.java
public class Agent {
ackDiscovery ackDisc=new ackDiscovery();
public static void main(String[] args) throws SocketException,UnknownHostException,IOException {
ackDiscovery ackDisc=new ackDiscovery();
ackDisc.ackInfo();
}
}
And ackDiscovery.java-
public class ackDiscovery {
int agentListenPort;
void ackDiscovery(){
agentListenPort=4455;
}
public void ackInfo() throws SocketException, UnknownHostException, IOException{
// get a datagram socket
DatagramSocket socket = new DatagramSocket();
// send request
byte[] buf = new byte[256];
InetAddress address = InetAddress.getByName(MY_IP);
DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 4445);
socket.send(packet);
// get response
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
// display response
String received = new String(packet.getData());
System.out.println("Data received:"+ received);
socket.close();
}
}
When I run the Controller(Server), the Agent's(client's) side get executed only once though the Controller is still listening. Also, if I re-run the agent, nothing happens. Can someone please help me?
A: If you look at the definitions of the schedule method here:
http://download.oracle.com/javase/7/docs/api/java/util/Timer.html
You can see that the method with a single long parameter, will only execute once.
What you're looking for is the one with two long parameters. This will wait for delay ms and then execute every period ms.
The one you are using will only execute once after delay ms.
You may also want to look at either using non-blocking io (java.nio.*) for receiving connections or using a receive timeout. This way you won't have multiple threads running at once.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620833",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: c++ request for member `A' in `B', which is of non-class type `C' I get the error message request for member 'namn' in 'post', which is of non-class type 'telefonbok[10]', or similar versions of it.
I think it has to do with the following bit of code:
struct telefonbok
{
string namn;
string nummer;
};
int main()
{
int i, ja, nej;
telefonbok post[10];
What am I doing wrong?
The errors are targeted at:
cin>>post.namn;
and
cin>>post.nummer;
Here is the full code, sorry about the Swedish:
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
struct telefonbok
{
string namn;
string nummer;
};
int main()
{
int i, ja, nej;
telefonbok post[10];
bool svar; //behövs för frågan om man vill fortsätta.
for (i=0; i<10; i++)
{
cout<<"Lagg till en post i telefonboken."<<endl;
cout<<"Ange personens namn"<<endl;
cin>>post.namn;
cout<<"Ange personens nummer :"<<endl;
cin>>post.nummer;
cout<<"Vill du mata in en post till? (ja/nej)"<<endl;
cin>>svar;
if (svar == nej) break; //stoppar slingan om man svarar nej
}
system("PAUSE");
return 0;
}
Thank you for any help that you may be able to provide.
A: post is an array, so accessing one member you need to do cin>>post[index].namn; instead of cin>>post.namn;
You want to access a single post element in the array, and a member of that element.
A: You have an array of telefonbok objects, you need to specify to which one you want to read the information.
So the lines should read something like:
cin >> post[i].namn; //i is an index to the array; the for loop variable.
A: cin>>post.namn;
post is an array. So that should be something like this:
cin>>post[i].namn;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620837",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: iOS didSelectRow and setString I am created list of fonts via tableView , and when user tab any of cells the string of font should be change according to the cells , But I don't know why my code does not work !
my tableview opens with UIPopOverViewContoller : here is my code :
.h
@interface FontViewController : UITableViewController <UITableViewDelegate , UITableViewDataSource , UINavigationControllerDelegate> {
NSMutableArray *listOfFonts;
}
@property (nonatomic, retain) NSMutableArray *listOfFonts;
.m
#import "FontViewController.h"
#import "xxxAppDelegate.h"
#import "xxxViewController.h"
@implementation FontViewController
- (void)viewDidLoad
{
listOfFonts = [[NSMutableArray alloc] init];
[listOfFonts addObject:@"font1"];
[listOfFonts addObject:@"font2"];
[listOfFonts addObject:@"font3"];
[listOfFonts addObject:@"font4"];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//TableView Codes ....
cell.textLabel.text = [listOfFonts objectAtIndex:indexPath.row];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
xxxAppDelegate *appDelegate =
[[UIApplication sharedApplication] delegate];
appDelegate.viewController.detailItem = [listOfFonts objectAtIndex:indexPath.row];
}
xxxViewController.h :
@interface {
NSString *fontString;
id detailItem;
}
@property (nonatomic ,retain) NSString *fontString;
@property (nonatomic, retain) id detailItem;
xxxViewController.m :
@synthesize detailItem ,fontString;
- (void)setDetailItem:(id)newDetailItem {
if (detailItem != newDetailItem) {
[detailItem release];
detailItem = [newDetailItem retain];
//---update the view---
fontString = [detailItem description];
}
}
//here is the custom font codes : (I am using special fonts which does not works with UIApplicationFont in app plist)
(CTFontRef)newCustomFontWithName:(NSString *)fontName
ofType:(NSString *)type
attributes:(NSDictionary *)attributes
{
// the string of cell should be equal to the pathForResource:fontString for example font1 , font 2 ...
NSString *fontPath = [[NSBundle mainBundle] pathForResource:fontString = [detailItem description] ofType:@"ttf"];
NSData *data = [[NSData alloc] initWithContentsOfFile:fontPath];
CGDataProviderRef fontProvider = CGDataProviderCreateWithCFData((CFDataRef)data);
[data release];
/// blah alah blah
}
Here is debugger messages in setDetailItem
NSLog(@"fontString: %@, assigned: %@ in controller: %@", fontString, [detailItem description], self);
2011-10-02 23:12:57.036 Medad[558:10d03] fontString: (null), assigned: font1 in controller: < myAppViewController: 0x7078a30>
2011-10-02 23:12:58.015 Medad[558:10d03] fontString: (null), assigned: font2 in controller: < myAppViewController: 0x7078a30>
2011-10-02 23:12:58.475 Medad[558:10d03] fontString: (null), assigned: font3 in controller: < myAppViewController: 0x7078a30>
2011-10-02 23:13:00.365 Medad[558:10d03] fontString: (null), assigned: font4 in controller: < myAppViewController: 0x7078a30>
my problem is this line:
fontString this should be changed as cell selecting ...
NSString *fontPath = [[NSBundle mainBundle] pathForResource:???fontString????? ofType:@"ttf"];
I would be grateful if somebody help me thanks
A: Set breakpoints in various locations in your code, especially in the tableView:didSelectRowAtIndexPath: and setDetailItem: methods to check if they are called.
*
*If they aren't, you probably forgot to set the delegate of your UITableView (you may have set your viewController being the tableview's dataSource but forgot the delegate?).
*If they are, check in the debugger (or using NSLog) the values of the various objects to check if there are nil objects (sending a message to nil has no effect)
I would bet that you forgot to link the delegate outlet of your UITableView to the proper object (typically your ViewController). If that's not the cause, we definitely need more information and you need to debug your code step by step using breakpoints and the debugger.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620842",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Jquery blur function: Run second function after first. How? I am trying to get a second function to run based on the results of the first.
$('#email').blur(function () {
id = $(this).attr('id');
$(myObj).data(id,"");
is_email(id); // If it's a valid email, it does this: $(myObj).data(id,"ok");
// Now if it's a valid email address, I want to run a second function to see if
// it's already taken.
if ($(myObj).data("email") == "ok") {
$(myObj).data("email",""); // Resets the value...
is_taken(id, "employees", "email"); // To test it again...
}
});
The first part works fine, but when I get to if($(myObj).... it is never checked. I'm assuming because this is set on the same blur event. I thought by putting it AFTER the first function, it would check the value of this object after the first function was complete. My guess is that it's checking if the value is "ok" before the first function has had a chance to return the value.
A: Because the functions use AJAX, the second is being invoked before the first AJAX call returns and sets the data value. The key letter in AJAX is the first 'A' - asynchronous, meaning the code flow continues without waiting for the response. You can avoid this (and avoid using data to store the intermediate results) by changing your is_email function to accept a callback. Run the second function as the callback when the AJAX call completes depending on the result of the first call.
function is_email( id, type, check, callback )
{
var that = this;
$.post( '/email/check', $('#'+id).val(), function(result) {
if (result == 'ok') {
if (callback) {
callback.call(that,id,type,check);
}
}
}
}
Used as:
is_email(id, "employees", "email", istaken);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android back button In my app I have a button that if the user clicks than a text box appears on the screen
(I use the setVisibility from GONE to VISIBILE).
the problem I have is when the user presses the BACK button on the device : it closes my app.
Is there any way that when the user presses the BACK button than my code will be called (so I can set the visibility to GONE) ?
A: Override onBackPressed() with your desired functionality.
The default implementation just calls finish() to close the current activity.
A: The following works since API level 1:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
//Do whatever you want
//AND
//return true to tell the framework you did handle the back key
return true;
}
//This is not the back key, just ask the framework to behave as usual.
return super.onKeyDown(keyCode, event);
}
Starting from API level 5 (android 2.0) you can also use:
@Override
public void onBackPressed() {
// Do something (or nothing) here
return;
}
See this android developer blog message for a complete overview.
A: public boolean onKeyDown(int keyCode, KeyEvent keyEvent) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
// Put your code here
}
return true;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620847",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Where is the thread going when a future leaves scope? With threads I know that terminate() is called when the thread-variable leaves scope:
size_t fibrec(size_t n) {
return n<2 ? 1 : fibrec(n-2)+fibrec(n-1);
}
int main() {
std::thread th{ fibrec, 35 };
// no join here
} // ~th will call terminate().
ths destructor will call terminate() when it leaves scope.
But what about futures? Where is the thread they run going? Is it detached? How is it ended?
#include <iostream>
#include <future> // async
using namespace std;
size_t fibrec(size_t n) {
return n<2 ? 1 : fibrec(n-2)+fibrec(n-1);
}
struct Fibrec {
size_t operator()(size_t n) { return fibrec(n); }
const size_t name_;
Fibrec(size_t name) : name_(name) {}
~Fibrec() { cerr << "~"<<name_<< endl; }
};
void execit() {
auto f1 = async( Fibrec{33}, 33 );
auto f2 = async( Fibrec{34}, 34 );
// no fx.get() here !!!
}; // ~f1, ~f2, but no terminate()! Where do the threads go?
int main() {
auto f0 = async( Fibrec{35}, 35 );
execit();
cerr << "fib(35)= " << f0.get() << endl;
}
When execit() is left the futures f1 and f2 are destroyed. But their threads should still be running? The destructor of Fibrec is called, of course. But where are the threads going? The program does not crash, so I guess, the become joined? Or maybe detached? Or are they stopped or canceled? I believe that is not trivially done in C++11?
A: The future is the result of the async operation, it's is not a thread by itself. The async function spawns a new thread to do the computation, and when that is finished, the result is written to a future object.
Depending on the implemented policy, you will either have to call .get() or .wait() on the future to get the result. Invoking this will do the work on the thread on which it is called
If policy is std::launch::async then runs INVOKE(fff,xyz...) on its
own thread. The returned std::future will become ready when this
thread is complete, and will hold either the return value or exception
thrown by the function invocation. The destructor of the last future
object associated with the asynchronous state of the returned
std::future shall block until the future is ready.
If policy is std::launch::deferred then fff and xyz... are stored
in the returned std::future as a deferred function call. The first
call to the wait() or get() member functions on a future that shares
the same associated state will execute INVOKE(fff,xyz...)
synchronously on the thread that called wait() or get().
A: Here is a very basic std::async implementation(without a task-pool or std::launch stuff):
template< class Function, class... Args>
std::future<typename std::result_of<Function(Args...)>::type>
async( Function&& f, Args&&... args )
{
std::packged_task<F(Args...)> task(std::forward<F>(f), std::forward<Args>(args)...);
auto ret = task.get_future();
std::thread t(std::move(task));
t.detach();
return ret;
}
You see that the actually computation is done in a detached thread. The future is just a synchronization object. std::packaged_task is just another wrapper for the std::promise set_value/set_exception logic.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620860",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Zend ACL class not being found by FrontController I think its a simple path issue here - but I've spent last 2 hours trying various combinations but not able to resolve this. The code is working fine on my windows system but when I upload it to my hosting site on linux OS - it doesn't find the ACL file.
This is how the paths are defined in my index.php
// Define path to application directory
defined('APPLICATION_PATH') || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(realpath(APPLICATION_PATH . '/../library'), get_include_path(),
)));
This is the line in application.ini
resources.frontController.plugins.acl = "Ed_Controller_Plugin_Acl"
This is the bootstrap.php relevant code
protected function _initAutoload()
{
.......
Zend_Loader_Autoloader::getInstance()->registerNamespace('Ed_');
.......
}
These are the errors I am getting on the linux system and the ACL doesn't work
[Sat Oct 01 14:26:44 2011] [error] [client 122.164.175.204] PHP Warning: include_once(Ed/Controller/Plugin/Acl.php): failed to open stream: No such file or directory in /home/webadmin/dezyre.com/library/Zend/Loader.php on line 146
[Sat Oct 01 14:26:44 2011] [error] [client 122.164.175.204] PHP Warning: include_once(): Failed opening 'Ed/Controller/Plugin/Acl.php' for inclusion (include_path='/home/webadmin/dezyre.com/application/../library:/home/webadmin/dezyre.com/library:.:/usr/share/pear:/usr/share/php') in /home/webadmin/dezyre.com/library/Zend/Loader.php on line 146
[Sat Oct 01 14:26:44 2011] [error] [client 122.164.175.204] PHP Fatal error: Class 'Ed_Controller_Plugin_Acl' not found in /home/webadmin/dezyre.com/library/Zend/Application/Resource/Frontcontroller.php on line 117
Thanks for your time
Appreciate it
A: Remember that *ix is all case sensitive with file names. Therefore directories must start with in uppercase. If they don't, Windows won't complain - but Linux will.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620864",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jQuery .css() not working in IE 6,7,8 and Firefox, but works in Chrome, Safari, Opera UPDATE: THIS HAS BEEN SOLVED.
I'm trying to change the default style of an Assistly site through JavaScript, because the stylesheet is not editable by me. It's working fine in Chrome, Safari, Opera, and IE9; but not in IE 6,7,8 or any Firefox.
In the code below the first two lines that are setting an h2 and an image are working across all browsers, but the .css() lines are not. Why would .css() not work in certain browsers?
Here is the code.
<script type="text/javascript">
jQuery(document).ready(function(){
$("#support-header .wrapper h2").first().html('<h2>Real Estate Help</h2>');
$("#company-header .wrapper").html('<a href="http://help.mysite.com/"><img src="http://www.mysite.com/logo-red.png" /></a>');
$("body").css({'background': '#FFFFFF !important'});
$("#company-header").css({'background': 'none !important'});
$("#support-header").css({'background': 'none !important', 'border-bottom': 'none', 'padding': '0'});
$("#company-support-portal").css({'background-image': 'url(http://www.mysite.com/container-bg2.jpg) !important', 'background-repeat': 'repeat-x', 'margin-top': '10px'});
});
</script>
A: I will add to what others have said: I suspect the problem may be related to the !important flag.
The question is why do you need it? You're setting this on an inline style, so that ought to override any other styles anyway; the only thing that won't be overridden by default on an inline style is another style that is marked !important, so I assume that's what you're trying to do.
The trouble is that as soon as you use !important, you're basically telling the browser that this style should trump everything else; inheritance and precedence go out of the window.
If you have multiple !important styles on the same element, both will have equal precedence, so you can never really be sure what's going to happen. Some browsers will pick up one, some the other.
The real lesson to be taken from this is to avoid using !important in your stylesheets, unless it is absolutely unavoidable, and certainly avoid it for anything that you will subsequently want to override.
Due to the way CSS arranges things in order of precedence and inheritance, there are in fact very very few cases where !important is actually needed. There is almost always an alternative (better) way of doing it.
So the short answer: Re-work your stylesheets to get rid of the !important markers. Your jQuery code is not going to work correctly until you do this (and in fact, looking at the number of !important markers in your site, your CSS on its own might already be struggling to get things right as it is)
A: Remove !important from the your code. !important should only be used within stylesheets, not within inline attributes.
A: In IE, it works well to use
element.css('property', 'value')
Although you then need a separate line for every property.
Note: you can specify important easily with
$.('#elid').css('display', 'block !important')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620865",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to play a sound with JS?
Possible Duplicate:
Playing sound notifications using Javascript?
I'm making a game in JS, and I need a proper way to play a sound when something happens. How do you do that with JS/HTML5? I saw this article, but even with their example, it doesn't really work! Sometimes I do hear that bird, but only for a short time, and I can't get it to work anymore then.
A: HTML5 has the new <audio>-Tag that can be used to play sound. It even has a pretty simple JavaScript Interface:
<audio id="sound1" src="yoursound.mp3" preload="auto"></audio>
<button onclick="document.getElementById('sound1').play();">Play it</button>
A: You can make use of the HTML5 <audio> tag: http://jsfiddle.net/STTnr/.
var audio = document.getElementById('audio');
setTimeout(function() {
audio.play(); // play it through JavaScript after 3 seconds
}, 3000);
HTML:
<audio src="something" id="audio"></audio>
Just hide the element itself:
#audio {
display: none;
}
Do note that no browser supports all formats. This can be frustrating, but you can supply your audio in several formats.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620871",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How should one implement GetHashCode()?
Possible Duplicate:
Create a hashcode of two numbers
I have following class:
public struct Test
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
public override int GetHashCode()
{
return Prop1.GetHashCode() ^ Prop2.GetHashCode();
}
}
Today I found out that I'm computing GetHashCode in a wrong way - if both properties are the same it always returns 0. How to do it the right way?
A: There is no single correct way to implement GetHashCode. Since your properties are strings there are an infinate number of possible combinations of values. The hash code is an Int32 so there only 2^32 possible values. Therefore, the HashCode cannot be unique for every possible value of Prop1 & Prop2. You have discovered one point where the value repeats and that is where Prop1 = Prop2. The idea of the hash code is that you get a fairly even distribution of values based upon the data you are expecting. If you exepect prop1 and prop2 to rarley be equal during execution, then its probably not an issue. However, if you expect prop1 and prop2 to be equal most of the time, then you should probably use a different algorithim for the hash code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620876",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Understanding how to use CGI and POST I'm trying to understand how I can use Python and javascript so that I can use POST/GET commands. I have a button that sends a request to server-side python, and should return a value. I understand how to print out a response, but I want to pass a value to a javascript variable instead of just print thing the response.
For example, my javascript sends a string to the python file using the jquery POST function:
<script>
function send(){
$.ajax({
type: "POST",
url: "pythondb.py",
data:{username: 'william'},
async: false,
success: function(){
alert('response received')
},
dataType:'json'
});
}
</script>
Then using the python cgi module I can print out the value of username:
#!/usr/bin/env python
import cgi
print "Content-Type: text/html"
print
form = cgi.FieldStorage()
print form.getvalue("username")
however I am not receiving the data in the same way that the php echo function works. Is there an equivalent to 'echo' for the python cgi module?
I have read this question which explains the different python frameworks that can be used to communicate between browser and server; for the moment I was hoping to keep things as simple as possible and to use the cgi module, but I don't know if that is the best option.
A: Your success: function can take a parameter, to which jQuery will pass the contents of the response from the AJAX request. Try this and see what happens:
<script>
function send(){
$.ajax({
type: "POST",
url: "pythondb.py",
data:{username: 'william'},
async: false,
success: function(body){
alert('response received: ' + body);
},
dataType:'json'
});
}
</script>
P.S. Why are you using async: false? That kind of defeats most of the point of AJAX.
A: Your json is not in proper json format.
According to http://api.jquery.com/jquery.parsejson/,
*
*username needs to be in quotes
*you can only use double quotes
It would look like this:
{"username": "william"}
Also, your alert should have a semi colon on the end. I can't guarantee this answer will fix your problem, but it may be that your data isn't getting passed to cgi at all.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620879",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Error while compiling Ethos framework I'm trying make Ethos framework on Mac OS Lion.
git://git.dronelabs.com/ethos
Here result of ./configure:
Ethos 0.2.3
Prefix...................: /usr/local
Debug level..............: minimum
Maintainer Compiler flags: no
Build API reference......: no
Enable test suite........: yes
Bindings
GObject Introspection....: no
Vala Bindings............: no
Python Bindings..........: no
Javascript Bindings......: no
Now type `make' to compile ethos
Then I do sudo make, and while compiling arise an error:
Making all in c-plugins
CC libsample.so
Undefined symbols for architecture x86_64:
"_ethos_plugin_get_type", referenced from:
_my_plugin_get_type in cc3gPLKS.o
_my_plugin_class_init in cc3gPLKS.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status
make[3]: *** [libsample.so] Error 1
make[2]: *** [all-recursive] Error 1
make[1]: *** [all-recursive] Error 1
make: *** [all] Error 2
How can I fix it?
A: I found that Ethos can be installed on Mac OS X 10.7 after the following modifications:
1)Edit file: ethos_dir/ethos/ethos_manager.c (:194):
FROM:
while (NULL != (filename = g_dir_read_name (dir))) {
if (g_str_has_suffix (filename, "." G_MODULE_SUFFIX)) {
abspath = g_build_filename (loaders_dir, filename, NULL);
loader = ethos_manager_create_plugin_loader (manager, abspath);
if (loader != NULL)
loaders = g_list_prepend (loaders, loader);
g_free (abspath);
}
}
TO:
while (NULL != (filename = g_dir_read_name (dir))) {
#ifdef __APPLE__
gchar* suffix = "dylib"; // to able find ethos-plugin-loader
#else
gchar* suffix = ("." G_MODULE_SUFFIX);
#endif
if (g_str_has_suffix (filename, suffix)) {
abspath = g_build_filename (loaders_dir, filename, NULL);
loader = ethos_manager_create_plugin_loader (manager, abspath);
if (loader != NULL)
loaders = g_list_prepend (loaders, loader);
g_free (abspath);
}
}
2)Disable making for: ethos-dir/tests,
Change in Makefile.am
FROM:
line#: contents
02: SUBDIRS = c-plugins manager-dep
30: manager_sources = manager.c
31: plugin_info_sources = plugin-info.c
TO:
02: #SUBDIRS = c-plugins manager-dep
30: #manager_sources = manager.c
31: #plugin_info_sources = plugin-info.c
This is necessary because, while making process it cannot find libethos.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620884",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: log4j:ERROR Error occured while converting date I found this exception in my logs:
log4j:ERROR Error occured while converting date.
java.lang.NullPointerException
at java.lang.System.arraycopy(Native Method)
at java.lang.AbstractStringBuilder.getChars(AbstractStringBuilder.java:328)
at java.lang.StringBuffer.getChars(StringBuffer.java:201)
at org.apache.log4j.helpers.ISO8601DateFormat.format(ISO8601DateFormat.java:130)
at java.text.DateFormat.format(DateFormat.java:316)
at org.apache.log4j.helpers.PatternParser$DatePatternConverter.convert(PatternParser.java:443)
at org.apache.log4j.helpers.PatternConverter.format(PatternConverter.java:65)
at org.apache.log4j.PatternLayout.format(PatternLayout.java:506)
at org.apache.log4j.WriterAppender.subAppend(WriterAppender.java:310)
at org.apache.log4j.WriterAppender.append(WriterAppender.java:162)
at org.apache.log4j.AppenderSkeleton.doAppend(AppenderSkeleton.java:251)
at org.apache.log4j.helpers.AppenderAttachableImpl.appendLoopOnAppenders(AppenderAttachableImpl.java:66)
at org.apache.log4j.Category.callAppenders(Category.java:206)
at org.apache.log4j.Category.forcedLog(Category.java:391)
at org.apache.log4j.Category.info(Category.java:666)
at org.obliquid.db.ConnectionManager.releaseConnection(ConnectionManager.java:313)
at org.obliquid.db.ConnectionManager.finalize(ConnectionManager.java:331)
at java.lang.ref.Finalizer.invokeFinalizeMethod(Native Method)
at java.lang.ref.Finalizer.runFinalizer(Finalizer.java:83)
at java.lang.ref.Finalizer.access$100(Finalizer.java:14)
at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:160)
I think it could be caused by my log4j.properties file, in particular by ConversionPattern. Any idea on how to fix?
#Updated at Wed Sep 14 21:57:51 CEST 2011
#Wed Sep 14 21:57:51 CEST 2011
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.rootLogger=INFO, stdout
log4j.appender.R.File=yamweb.log
log4j.appender.R.MaxFileSize=1000KB
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.stdout.layout.ConversionPattern=%d [%t] %-5p %c - %m%n
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.logger.yamweb=DEBUG
log4j.logger.org.springframework=INFO
log4j.logger.org.springframework.beans=DEBUG
log4j.logger.com.amazonaws=WARN
UPDATE: Actually, looking at the PatternLayout JavaDoc, I don't even mention a date format.
d Used to output the date of the logging event. The date conversion specifier may be followed by a date format specifier enclosed between braces. For example, %d{HH:mm:ss,SSS} or %d{dd MMM yyyy HH:mm:ss,SSS}. If no date format specifier is given then ISO8601 format is assumed.
I've added an explicit conversion pattern: %d{yyyy-MM-dd HH:mm:ss} [%t] %p %c - %m%n-- looking at the log and I will let you know if it helps.
UPDATE 2: the problem didn't happen anymore.
A: It seems this is a very rare situation. Googling for the error turned up the following discussion from 2006, something to do with class un-loading:
http://comments.gmane.org/gmane.comp.jakarta.log4j.user/13835
I did look at the code in question. If lastTimeString was somehow
not initialized on class reload, then there could be a NPE on the
call to getChars(). However, short of a some failure in the VM or a
class reloading hack, I don't see how lastTimeString could be null.
EDIT: See question above for a solution:
I've added an explicit conversion pattern: %d{yyyy-MM-dd HH:mm:ss} [%t] %p %c - %m%n
This also seemed to work for the following question: NPE with Perf4j and Log4j.
A: I've just stumbled upon this exception, and it was solved by removing log4j.jar from the portlet (or servlet, whatever) folder.
A: I know it's an old thread, but I fixed this problem by restarting the server. Yeah, cliche answer, but worth a try
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620886",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Array entry as references function argument Probably simple question, but I am always a little bit confused with references and arrays as arguments. Is the following valid in C++? That is, does array[0] have the value 10 after call of function1, if the snippet comiples at all?
void function1(int &data)
{
data = 10;
}
void function2(void)
{
int array[2];
function1(array[0]);
}
Thanks for clarification.
A: Yes, it will, and that's perfectly valid code.
A:
Is the following valid in C++?
Yes.
That is, does array[0] have the value 10 after call of function1, if the snippet comiples at all?
Yes.
Try compiling, run and experiment. Then ask the next - and slightly better - question.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620899",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: In-App Purchases: Crash when view disappear My application has a tabbar that contains 4 view controllers. The third view controller contains a "store in-app purchases". In this controller I use an object that manages in-app purchases (product request, purchase, transaction etc...) that allow me to get and show price description ecc.
The problem is: If I change tabs while the request started the app crashes sometimes, but not always.
I've to cancel the request in viewDidDisappear?
[productsRequest cancel] this code crashes.
A: I have the same issue.
To fix it cancel request and all be fine.
var request: SKProductsRequest! //global to cancel when disappear
//request products when you want (viewDidLoad for example)
request = SKProductsRequest(productIdentifiers: productID as! Set<String>)
request.delegate = self
request.start()
And when disapear viewcontroller:
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
request.delegate = nil;
request.cancel()
SKPaymentQueue.defaultQueue().removeTransactionObserver(self)
}
A: Your problem has probably nothing to do with in-app purchase. Somewhere in your code you're sending a message to an object which has been released. Running the analyzer can help you find the bug, but it may not be necessary this time. If [productsRequest cancel] crashes, then probably productsRequest has too low retain count.
A: Remove the TransactionObserver while your viewDidDisappear:
[[SKPaymentQueue defaultQueue]removeTransactionObserver:self];
If you go back from the Inapp viewcontroller to another viewcontroller,then
[[SKPaymentQueue defaultQueue]removeTransactionObserver:self];
[self dismissViewControllerAnimated:YES completion:NULL];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620901",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jQuery slideDown not fluid I am working on a jQuery menu for my friend. The menu is done, the only problem is that the slide down is not fluid and I can't find the problem here.
jQuery code:
$.fn.vmenu=function(settings)
{
vMenu={
init: function(elem) {
$(elem).find('li').each(function(){
var u=$(this).children('ul');
if (u.length>0) {
$(this).addClass('has_child');
}
var a=$(this).children('a');
if (a.hasClass('active')) {
$(this).addClass('active').parents('li').addClass('open');
}
});
$(elem).find('ul').each(function(){
var o=$(this).find('li.open');
var a=$(this).find('a.active');
if (o.length == 0 && a.length==0) {
$(this).css('display','none');
}
});
$(elem).find('a').click(function(){
return vMenu.click($(this));
});
},
click: function(elem) {
var l=$(elem).parent('li');
var u=$(l).children('ul');
if (u.length == 0) {
return this.forward(elem);
}
if ($(l).hasClass('open')) {
$(l).removeClass('open');
$(l).find('ul').stop(true,true).slideUp(300);
$(l).find('li').removeClass('open');
if($(l).children('a').hasClass('open')) {
$(l).children('a').css({color:'#939393'});
$(l).children('a').removeClass('open');
}
} else {
$(l).addClass('open');
$(u).stop(true,true).slideDown(300);
$(l).children('a').css({color:'#F37121'});
$(l).children('a').addClass('open');
}
return false;
},
forward: function(elem) {
return true;
}
}
vMenu.init($(this));
}
$(document).ready(function(){
$('#vmenu').vmenu();
});
CSS code:
/* ### partner box ### */
.partnerBox { padding-top: 52px; width: 253px; float: left; background: url('http://www.realbingo.nl/images/partner-top.png') left top no-repeat; }
.partnerBox .bottom { padding-bottom: 12px; float: left; background: url('http://www.realbingo.nl/images/paasbonus-bottom.png') left bottom no-repeat; }
.partnerBox .mid { padding: 0 20px 0 15px; width: 218px; float: left; background: url('http://www.realbingo.nl/images/paasbonus-mid.png') left top repeat-y; }
.partnerBox h3 { padding-left: 5px; margin-top: -36px; color: #fff; font-size: 20px; }
.partnerBox ul { padding: 0px 0 0 0; margin-bottom: -5px; overflow: hidden; width: 100%; }
.partnerBox li { padding-left: 5px; font-size: 13px; float: left; list-style: none; width: 208px; line-height: 39px; border-bottom: 0px; }
.partnerBox li a { padding-left: 9px; color: #939393; text-decoration: none; display: block; background: url('http://www.realbingo.nl/images/arrow1.png') left center no-repeat; }
.partnerBox li a:hover { color: #F37121 !important; }
#vmenu li { border-bottom: #ece3e3 solid 1px; }
#vmenu li > ul > li { border-bottom: 0px; height: 30px; line-height: 30px; margin-top: -8px;}
.text ul{ line-height: 18px; margin-bottom: 2px; }
HTML code:
<div class="partnerBox">
<div class="bottom">
<div class="mid">
<h3>Linkpartners</h3>
<ul id="vmenu">
<li><a href="#">Bingo</a>
<ul>
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
</ul>
</li>
<li><a href="#">Roulette</a>
<ul>
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
</ul>
</li>
<li><a href="#">Poker</a>
<ul>
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
</ul>
</li>
<li class="text"><a href="#">Tekst</a>
<ul>
Dit is een lap tekst die door en door gaat tot het einde.. en verder... :D:D:D:D:D:D:D:D
</ul>
</li>
</ul>
</div>
</div>
</div>
Any tips and/or ideas to make the code more efficient are very appreciated too.
A: If you're talking about the slideDown jumping when it gets to the bottom of the reveal it is likely to be caused by the bottom margin on the ".text ul" CSS. jQuery can't calculate the height including margins.
If you're talking about the slideDown content moving around during the animation, this is often related to the top padding of either the element you're sliding or the first child element.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620902",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Need advice on designing an index to keep track of users that are not subscribed to a document in the system I have a table for Projects, a table for Documents (with a FK to Projects), and a table for users with a relationship to projects and documents. Users can be subscribers to a document and that is how they have a relationship to the document.
Users are considered team members on a project. A document can only assigned to one project at a time. Only users, from the "Project Team" can be subscribed to a document.
What I am struggling with, in my application, is that admins are able to add users as subscribers to a document. However, the admin can only pick from a list of unsubscribed users. Those unsubscribed users are members of the project team, like I said above.
Right now, I am creating 2 queries on my database to pull all the subscribed users and the entire list of team members. I then compare the list and only pull the team members that are not subscribed.
I am not sure if I should even index this type of data or just pull from the database directly. If I should use an index, this data needs to be updated quickly becuase the admins need that unsubscribed list rather fast.
This is what my query looks like going against Entity Framework 4.1:
var currentSubscribers = _subscriptionRepository.Get(s => s.DocumentId == documentId).Select(s => s.Contact).ToList();
if (projecTeamMembers != null)
{
var availableSubscribers = (projecTeamMembers.Where(
p => !(currentSubscribers.Select(c => c.Id)).Contains(p.Id))).ToDictionary(c => c.Id, c=> c.LastName + ", " + c.FirstName);
return availableSubscribers;
}
else
{
return null;
}
This works great in EF, but I have been thinking of indexing my data using Lucene.Net and need some advice on if I should do this or not.
A: Write this query indide your data repository where you have access to the Database context
var q = from m in dbContext.ProjecTeamMembers
where !(from s in dbContext.Subscribers
where s.DocumentId == documentId &&
s.Contact.Id == p.Id
select s).Any()
select m;
var availableSubscribers = q.ToDictionary(m => m.Id, c=> m.LastName + ", " + m.FirstName);
A: The best way I have found to do something like this is, using Lucene.net, is to keep an index of subscribers and an index of all team members. And compare the two. It's faster than pulling form the database each time.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620904",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: RegExp in preg_match function returning browser error The following function breaks with the regexp I've provided in the $pattern variable. If I change the regexp I'm fine, so I think that's the problem. I'm not seeing the problem, though, and I'm not receiving a standard PHP error even though they're turned on.
function parseAPIResults($results){
//Takes results from getAPIResults, returns array.
$pattern = '/\[(.|\n)+\]/';
$resultsArray = preg_match($pattern, $results, $matches);
}
Firefox 6: The connection was reset
Chrome 14: Error 101 (net::ERR_CONNECTION_RESET): The connection was
reset.
IE 8: Internet Explorer cannot display the webpage
UPDATE:
Apache/PHP may be crashing. Here's the Apache error log from when I run the script:
[Sat Oct 01 11:41:40 2011] [notice] Parent: child process exited with
status 255 -- Restarting.
[Sat Oct 01 11:41:40 2011] [notice]
Apache/2.2.11 (Win32) PHP/5.3.0 configured -- resuming normal
operations
Running WAMP 2.0 on Windows 7.
A: Simple question. Complex answer!
Yes, this class of regex will repeatably (and silently) crash Apache/PHP with an unhandled segmentation fault due to a stack overflow!
Background:
The PHP preg_* family of regex functions use the powerful PCRE library by Philip Hazel. With this library, there is a certain class of regex which requires lots of recursive calls to its internal match() function and this uses up a lot of stack space, (and the stack space used is directly proportional to the size of the subject string being matched). Thus, if the subject string is too long, a stack overflow and corresponding segmentation fault will occur. This behavior is described in the PCRE documentation at the end under the section titled: pcrestack.
PHP Bug 1: PHP sets: pcre.recursion_limit too large.
The PCRE documentation describes how to avoid a stack overflow segmentation fault by limiting the recursion depth to a safe value roughly equal to the stack size of the linked application divided by 500. When the recursion depth is properly limited as recommended, the library does not generate a stack overflow and instead gracefully exits with an error code. Under PHP, this maximum recursion depth is specified with the pcre.recursion_limit configuration variable and (unfortunately) the default value is set to 100,000. This value is TOO BIG! Here is a table of safe values of pcre.recursion_limit for a variety of executable stack sizes:
Stacksize pcre.recursion_limit
64 MB 134217
32 MB 67108
16 MB 33554
8 MB 16777
4 MB 8388
2 MB 4194
1 MB 2097
512 KB 1048
256 KB 524
Thus, for the Win32 build of the Apache webserver (httpd.exe), which has a (relatively small) stack size of 256KB, the correct value of pcre.recursion_limit should be set to 524. This can be accomplished with the following line of PHP code:
ini_set("pcre.recursion_limit", "524"); // PHP default is 100,000.
When this code is added to the PHP script, the stack overflow does NOT occur, but instead generates a meaningful error code. That is, it SHOULD generate an error code! (But unfortunately, due to another PHP bug, preg_match() does not.)
PHP Bug 2: preg_match() does not return FALSE on error.
The PHP documentation for preg_match() says that it returns FALSE on error. Unfortunately, PHP versions 5.3.3 and below have a bug (#52732) where preg_match() does NOT return FALSE on error (it instead returns int(0), which is the same value returned in the case of a non-match). This bug was fixed in PHP version 5.3.4.
Solution:
Assuming you will continue using WAMP 2.0 (with PHP 5.3.0) the solution needs to take both of the above bugs into consideration. Here is what I would recommend:
*
*Need to reduce pcre.recursion_limit to a safe value: 524.
*Need to explicitly check for a PCRE error whenever preg_match() returns anything other than int(1).
*If preg_match() returns int(1), then the match was successful.
*If preg_match() returns int(0), then the match was either not successful, or there was an error.
Here is a modified version of your script (designed to be run from the command line) that determines the subject string length that results in the recursion limit error:
<?php
// This test script is designed to be run from the command line.
// It measures the subject string length that results in a
// PREG_RECURSION_LIMIT_ERROR error in the preg_match() function.
echo("Entering TEST.PHP...\n");
// Set and display pcre.recursion_limit. (set to stacksize / 500).
// Under Win32 httpd.exe has a stack = 256KB and 8MB for php.exe.
//ini_set("pcre.recursion_limit", "524"); // Stacksize = 256KB.
ini_set("pcre.recursion_limit", "16777"); // Stacksize = 8MB.
echo(sprintf("PCRE pcre.recursion_limit is set to %s\n",
ini_get("pcre.recursion_limit")));
function parseAPIResults($results){
$pattern = "/\[(.|\n)+\]/";
$resultsArray = preg_match($pattern, $results, $matches);
if ($resultsArray === 1) {
$msg = 'Successful match.';
} else {
// Either an unsuccessful match, or a PCRE error occurred.
$pcre_err = preg_last_error(); // PHP 5.2 and above.
if ($pcre_err === PREG_NO_ERROR) {
$msg = 'Successful non-match.';
} else {
// preg_match error!
switch ($pcre_err) {
case PREG_INTERNAL_ERROR:
$msg = 'PREG_INTERNAL_ERROR';
break;
case PREG_BACKTRACK_LIMIT_ERROR:
$msg = 'PREG_BACKTRACK_LIMIT_ERROR';
break;
case PREG_RECURSION_LIMIT_ERROR:
$msg = 'PREG_RECURSION_LIMIT_ERROR';
break;
case PREG_BAD_UTF8_ERROR:
$msg = 'PREG_BAD_UTF8_ERROR';
break;
case PREG_BAD_UTF8_OFFSET_ERROR:
$msg = 'PREG_BAD_UTF8_OFFSET_ERROR';
break;
default:
$msg = 'Unrecognized PREG error';
break;
}
}
}
return($msg);
}
// Build a matching test string of increasing size.
function buildTestString() {
static $content = "";
$content .= "A";
return '['. $content .']';
}
// Find subject string length that results in error.
for (;;) { // Infinite loop. Break out.
$str = buildTestString();
$msg = parseAPIResults($str);
printf("Length =%10d\r", strlen($str));
if ($msg !== 'Successful match.') break;
}
echo(sprintf("\nPCRE_ERROR = \"%s\" at subject string length = %d\n",
$msg, strlen($str)));
echo("Exiting TEST.PHP...");
?>
When you run this script, it provides a continuous readout of the current length of the subject string. If the pcre.recursion_limit is left at its too high default value, this allows you to measure the length of string that causes the executable to crash.
Comments:
*
*Before investigating the answer to this question, I didn't know about PHP bug where preg_match() fails to return FALSE when an error occurs in the PCRE library. This bug certainly calls into question a LOT of code that uses preg_match! (I'm certainly going to do an inventory of my own PHP code.)
*Under Windows, the Apache webserver executable (httpd.exe) is built with a stacksize of 256KB. The PHP command line executable (php.exe) is built with a stacksize of 8MB. The safe value for pcre.recursion_limit should be set in accordance with the executable that the script is being run under (524 and 16777 respectively).
*Under *nix systems, the Apache webserver and command line executables are both typically built with a stacksize of 8MB, so this problem is not encountered as often.
*The PHP developers should set the default value of pcre.recursion_limit to a safe value.
*The PHP developers should apply the preg_match() bugfix to PHP version 5.2.
*The stacksize of a Windows executable can be manually modified using the CFF Explorer freeware program. You can use this program to increase the stacksize of the Apache httpd.exe executable. (This works under XP but Vista and Win7 might complain.)
A: I ran into the same problem. Thanks a lot for the answer posted by ridgerunner.
Although it is helpful to know why php crashes, for me this does not really solve the problem. To solve the problem, I need to adjust my regex in order to save memory so php won't crash anylonger.
So the question is how to change the regex. The link to the PCRE manual posted above already describes a solution for an example regex that is quite similar to yours.
So how to fix your regex?
First, you say you want to match "a . or a newline".
Note that "." is a special character in a regex that does not only match a dot but any character, so you need to escape that. (I hope I did not get you wrong here and this was intended.)
$pattern = '/\[(\.|\n)+\]/';
Next, we can copy the quantifier inside the brackets:
$pattern = '/\[(\.+|\n+)+\]/';
This does not change the meaning of the expression. Now we use possessive quantifiers instead of normal ones:
$pattern = '/\[(\.++|\n++)++\]/';
So this should have the same meaning as your original regex, but work in php without crashing it.
Why? Possessive quantifiers "eat up" the characters and do not allow to backtrack. Therefore, PCRE does not have to use recursion and stack will not overflow. Using them inside the brackets seems to be a good idea as we do not need the quantification of the alternative this often.
To sum up, best practice seems to be:
*
*use possessive quantifiers where possible. This means: ++, *+, ?+ {}+ instead of +, *, ?, {}.
*move quantifiers inside of alternative-brackets where possible
Following these rules I was able to fix my own problem, and I hope this will help somebody else.
A: I had the same problem and you need to chenge the pattern to something like
$pattern = '|/your pattern/|s';
The 's' on the end basically means treat the string as a single line.
A: preg_match returns the number of matches found for the pattern. When you have a match, it is causing a fatal error in php (print_r(1), for instance, causes the error). print_r(0) (for when you change the pattern and have no matches) doesn't and just prints out 0.
You want print_r($matches)
As an aside, your pattern is not escaped properly. Using double quotes means you need to escape the backslashes in front of your brackets.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620910",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: What are some handy tricks for submitting Grails forms? Everybody's aware of passing parameters to a controller via a html form:
<g:form action="save">
<g:textField name="text1" />
</g:form>
And I'm vaguely aware of being able to structure these parameters into some sort of object notation in Grails:
<g:form action="save">
<g:textField name="text.a" />
<g:textField name="text.b" />
</g:form>
With very little idea how they are structured in the controller (objects? hashmaps? I recall having to use .value at some point using the latter example).
So I guess this question is really two questions:
*
*How does Grails handle parameters in object notation like the second example? Can you stick them into arrays too?
*What are some other tricks regarding form submission and its parameters that can make forms with very complex and iterative data trivial to handle in the controller? For instance, ATG allows you to bind form fields to beans and walk its entire property graph to find the property you need to set.
A: The second notation "text.a" is used to disambiguate data conversion from properties to domain objects. For example, if you have 2 domain objects each with a property "a", if you do domObj1.properties = params and domObj2.properties = params the value will go to both domain objects which may not be what you want. So in your view you should have variables domObj1.a and domObj2.a and in your grails controller you can instantiate using def domObj1 = new DomObj1(params["domObj1"])
By your second question if you mean whether you can iterate over objects, you very well can, using GPath syntax in a ${} wrapper, for e.g check out the code in the id property below.
<td><g:remoteLink controller="device" action="getDevice" id="${objInstance.prop1.prop2.id}" update="propDetail">${fieldValue(bean: objInstance.prop1, field: "prop1")}</g:remoteLink></td>
The example above also shows an ajax way of form submission from grails gsp.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620912",
"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.