text stringlengths 8 267k | meta dict |
|---|---|
Q: Compile Attempt Gives crt1.o/'start'/undefined reference to 'main'/exit status message I am working from a book: TCP/IP Sockets in C and its website code.
I am trying to build a client and server based on those files. My make gives lots of
error related to not being able to find functions from DieWithMessage.c
Here it is:
#include <stdio.h>
#include <stdlib.h>
#include "Practical.h"
void DieWithUserMessage(const char *msg, const char *detail) {
fputs(msg, stderr);
fputs(": ", stderr);
fputs(detail, stderr);
fputc('\n', stderr);
exit(1);
}
void DieWithSystemMessage(const char *msg) {
perror(msg);
exit(1);
}
When I do gcc DieWithMessage.c, I get the following error:
/usr/lib/i386-linux-gnu/gcc/i686-linux-gnu/4.5.2/../../../crt1.o: In function _start':
(.text+0x18): undefined reference tomain'
collect2: ld returned 1 exit status
How do I compile this by itself so that the errors will stop happening when using the makefile?
Thanks for any help.
A: Your C code needs a main function if you're going to try an link/run it. This is a requirement for hosted C applications under the standard.
That error message indicates what's wrong. The C runtime/startup code (CRT) has an entry point of start which sets up the environment then calls your main. Since you haven't provided a main, it complains.
If you only want to generate an object file for later linking with a main (see here for one description of the process), use something like:
gcc -c -o DieWithMessage.o DieWithMessage.c
(-c is the "compile but don't link" flag). You can then link it later with your main program with something like (although there are other options):
gcc -o myProg myProg.c DieWithMessage.o
If you want a placeholder main to update later with a real one, you can add the following to your code:
int main (void) { return 0; }
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542354",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there a better way of linking transitions in Corona Lua? I'm currently animating a trash can when something gets dragged and dropped onto it with this code:
local trashUp
local trashDown
trashUp = function()
transition.to(
trash, {time=100, xScale=1.2, yScale=1.2, onComplete=trashDown })
end
trashDown = function()
transition.to(
trash, {time=100, xScale=1, yScale=1})
end
and then calling trashUp() when I want to start the animation.
The code works fine, but I can't help feel it could be coded better. Two functions to animate an object!
Is there any way I can do this more efficiently?
A: Well you could do it in a single function by setting the second transition with delay; refer to this code example: http://developer.anscamobile.com/reference/index/transitionto
Depending on your situation however that's not necessarily less complicated, because now you have to keep track of two transitions simultaneously instead of just one transition at a time. In the code you posted you aren't keeping track of the transitions, but you probably should be in case you need to cancel them before the transition is complete (eg. the player switches scenes in the middle of the transition).
A: You can do it by coding the onComplete function inline with the first transition call:
animateTrash = function()
transition.to(
trash,
{ time=100, xScale=1.2, yScale=1.2, onComplete=
function()
transition.to(
trash,
{time=100, xScale=1, yScale=1})
end
})
end
This won't be any more efficient, but it does keep everything to do with animating the trashcan in one place. I think this approach could get quickly out of hand, though, especially if you were doing anything other than the transitions when animating the trashcan, e.g., updating your program's state, or creating/destroying other objects, etc.
Echoing jhocking's answer, this approach doesn't support canceling either.
A: This question is pretty old, but since I was trying to do the same thing, I figured I should share what I came up with. This sequentially executes transitions that are passed in as variable args. If onComplete is supplied, it is called as its transition completes.
local function transitionSequence(target, step, ...)
local remaining_steps = {...}
if #remaining_steps > 0 then
local originalOnComplete = step.onComplete
step.onComplete = function(target)
if originalOnComplete then
originalOnComplete(target)
end
transitionSequence(target, unpack(remaining_steps))
end
transition.to(target, step)
else
transition.to(target, step)
end
end
Example:
transitionSequence(myImage,
{xScale=0.5, onComplete=function(t) print("squeeze") end},
{xScale=1, onComplete=function(t) print("relax") end},
{yScale=2, onComplete=function(t) print("stretch") end},
{yScale=1, onComplete=function(t) print("relax again") end})
A: transition.to( trash, {time=t, delta=true, xScale=1.5, transition=easing.continousLoop} )
Also very useful for purposes like that:
easing.sin = function( f, a )
return function(t, tmax, start, d)
return start + delta + a*math.sin( (t/tmax) *f * math.pi*2 )
end
end
easing.sinDampened = function( f, a, damp )
return function(t, tmax, start, d)
return start + delta + a*math.sin( damp^(t/tmax) *f * math.pi*2 )
end
end
...etc
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542357",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Actual key assigned to JavaScript keyCode I have setup an event listener:
editor.addEventListener('keydown', function(e) {
if (e.shiftKey === false) {
alert(String.charFromCode(e.keyCode).toLowerCase());
}
else {
alert(String.charFromCode(e.keyCode));
}
}, false);
When the user presses 2 along with shift, how do I know if I should output (@) or (")? Each users' character mapping is different per locale.
A: Short answer: you really can't. Use a keypress or keyup listener, and compare the old (textbox, I assume?) value to the new one to see what actually happened.
A: Use the keypress event instead. It will reliably (barring a few edge cases) detect the character typed.
There are a few browser oddities (such as some non-printable keys generating keypress events with key codes in the which property in some browsers) that prevent the following example from being 100% perfect which you can read about in great detail at the definitive page on JavaScript key events.
Example:
editor.addEventListener('keypress',
function(e)
{
var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
alert( String.charFromCode(charCode) );
},
false);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542358",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do you shrink contents to fit a div? I am on a project and I have been assigned the task of modifying a report page to make it printable. The report uses PHP to generate tables within divs, but the divs are sometimes greater than 1 page length on print. So, what ends up happening is the tables/divs get broken once the page length runs out. The end result is a cluttered mess.
I have modified the print.css with the tag:
.general_report {
page-break-after: always;
}
with all the divs looking like:
<div class="general_report">
Which cleans up the report a little bit (ie, each section starts with a new page). But this seems to waste quite a bit of paper, and doesn't solve the problem of mid-table page breaking. My other idea was to auto-shrink the contents of the divs to fit 1 page exactly. None of our divs are > 2 pages, so if this was possible I think it would be a good solution... But is this possible? Is there a way for css to adjust font sizes to fit div length?
I googled scale contents to fit div, but everyone seems to be wanting the opposite of what I want (ie, div fits to content, not content fits to div).
Does anyone have any help they can provide? A general example of printing html tables neatly would work, too, as all the results I was able to find involves the non-browser supported CSS (i.e., doesn't work): "page-break-inside: avoid".
Thank you in advance.
A: Follwing post explains what you can do to fit text in a DIV with certain width and height: http://www.dhtmlgoodies.com/?whichScript=text_fit_in_box
Does that work for you?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542362",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How can I update the project files using git effectively? I have an old web application 'A' which is a running under version control of git.
I recently rewrote the whole structure, but wrote this in different place and this new files are not under version control of git. This new project is 'B'
What is a best way that I can commit 'B' to the git repository that is keep tracking of 'A'?
No contents in git repository 'A' will be needed because everything is in 'B', but I want 'B' to use the git repository that 'A' have been using.
Do I just force commit in this case?
A: If you delete the contents of A, then copy over the contents of B into A, you will have all of your removes, unversioned files and modifications still tracked under git.
Simply commit these changes and you'll have your history linear and correct.
A: I think you should copy B over A's working tree, then do all the commits you want in A until there's nothing left to be commited.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542363",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: SQL result set needs pivot display within asp.net/mvc3 webgrid or raw html table? What is the cleanest way to transform/pivot the following result set (top - raw data) and display/create in another view in a webgrid or html table (bottom - % of data) using razor?
Hotels are going to be dynamic (added all the time). Thx!
A: Why can't you try the below?
SELECT Region,
HotelA
, HotelB
, HotelC
FROM ( SELECT Hotel ,region
, cast(hotelregioncount as numeric(18,2))/cast(totalhotelcount as numeric(18,2)) A
FROM hoteltable
) p PIVOT ( SUM(A)
FOR hotel
IN (HotelA,HotelB,HotelC)
) AS pvt
A: And here is what you want to make the columns dynamic
DECLARE @query NVARCHAR(4000)
DECLARE @cols NVARCHAR(2000)
SELECT @cols = STUFF(( SELECT DISTINCT TOP 100 PERCENT
'],[' + t2.Hotel
FROM hoteltable AS t2
ORDER BY '],[' + t2.Hotel
FOR XML PATH('')
), 1, 2, '') + ']'
SET @query =
'SELECT Region,
' + @cols + '
FROM ( SELECT Hotel ,region
, cast(hotelregioncount as numeric(18,2))/cast(totalhotelcount as numeric(18,2)) A
FROM hoteltable
) p PIVOT ( SUM(A)
FOR hotel
IN (' + @cols + ')
) AS pvt'
execute(@query)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542370",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: MySQL wrap join condition with another condition? I've made a query that works as needed when there is at least 1 row in the url_status table where u.urlid = us.urls however it won't work if this isn't true. What could I do to overcome this?
SELECT u.*, COUNT(*) AS historySize
FROM host_urls u, url_status us
WHERE u.publicationid = 1
AND us.urlid = u.urlid
GROUP BY u.urlid
A: You could use an outer join, specifically a left join, which will return at least one result row for each row in host_urls, even if it has no corresponding rows in url_status.
SELECT u.*, COUNT(*) AS historySize
FROM host_urls u
LEFT JOIN url_status us
ON us.urlid = u.urlid
WHERE u.publicationid = 1
GROUP BY u.urlid
You can replace the COUNT(*) with COUNT(us.urlid) (or another column from url_status) if it's important that historySize be zero when there were no matching rows in url_status.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542373",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Asynchronous Plug-in in Dashboard Widget I'm building a Dashboard Widget where I use a plugin on native code to handle certain operations.
The problem is one of those methods takes a few seconds and the interface freezes, so...
It's there a way to do an Asynchronous method that can be called by the Javascript and then when it's done, a callback is used?
A: So, a little more digging I found there is a method called callWebScriptMethod:withArguments: that allows me to do it Asynchronously.
More info here:
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/WebKit/Classes/WebScriptObject_Class/Reference/Reference.html#//apple_ref/doc/c_ref/WebScriptObject
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542377",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Java Dateformat -- Can I compare input to certain formats and parse the input based on the format that it is matched to? For example:
A user can enter 01/23/1983 or 1/23/1983
How would I use DateFormat to write up two different kinds of formats like (MM/DD/YYYY) and (M/DD/YYYY) and compare them to the actual date to see which one matches the date so I could parse it successfully?
A: A common solution when dealing with multiple input formats is to try a series of expected formats in a loop until one succeeds, or all fails. E.g.,
public Date parseDate(List<DateFormat> formats, String text) {
for(DateFormat fmt : formats) {
try {
return fmt.parse(inputDate);
} catch (ParseException ex) {}
}
return null;
}
List<DateFormat> formats = Arrays.asList(new SimpleDateFormat("MM/dd/yyyy"));
Date d1 = parseDate(formats, "01/23/1983");
Date d2 = parseDate(formats, "1/23/1983");
A: Because Johan posted an incorrect solution, I feel obliged to post the correct one. "MM/dd/yyyy" will format both of your test Strings:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatTest {
public static void main(String[] args) {
String[] tests = {"01/23/1983", "1/23/1983", "1/3/1983"};
String formatString = "MM/dd/yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(formatString);
for (String test : tests) {
Date date = null;
try {
date = sdf.parse(test);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(date);
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542378",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Spring-JSF2 Integration: Target Unreachable, identifier 'customerBean' resolved to null I'm trying a simple integration of Spring 3 and JSF 2 using annotations only (not using faces-config.xml to define managed beans) and I'm stuck with an error.
The error is:
javax.el.PropertyNotFoundException: /customer/add.xhtml @11,70 value="#{customerBean.firstName}": Target Unreachable, identifier 'customerBean' resolved to null
This is the page: add.xhtml
<h:body>
<h:form>
<label>First Name <h:inputText value="#{customerBean.firstName}" /></label><br />
<label>Last Name <h:inputText value="#{customerBean.lastName}" /></label><br />
<label>Email <h:inputText value="#{customerBean.email}" /></label><br />
<h:commandButton value="Add" action="#{customerBean.add}" />
</h:form>
</h:body>
This is the bean: CustomerBean.java
package com.devworkzph.customer.sample.bean;
@Component
@Qualifier("customerBean")
@SessionScoped
public class CustomerBean implements Serializable{
private String firstName;
private String lastName;
private String email;
public String add(){
// code
}
//getters and setters
}
This is a part of my applicationContext.xml
<context:annotation-config />
<context:component-scan base-package="com.devworkzph.customer.sample" />
This is a part of my web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
Does anyone know what I'm doing wrong here?
Thanks!
A: I just changed CustomerBean.java to have the following annotations:
@Component
@Scope("session")
Then added SpringBeanFacesELResolver in faces-config.xml. I had it commented out before, not knowing that I needed it even if I won't use faces-config to define CustomerBean.
<?xml version="1.0"?>
<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
version="2.0">
<application>
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
</application>
</faces-config>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542380",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: vim: how to specify arrow keys In vim, when using map commands you must specify keys. For example <CR> <ESC> <F1>. What are the corresponding ones for the arrow keys?
A: If you don't know the internal code for a certain key, type
CtrlK and then the function key. For example, this
sequence followed by the up arrow key will output:
<Up>
You can learn more about this command in the documentation for both insert
and command mode. The specific ways to map a special key are given in the
documentation with the tag :map-special-keys. Additionally, you can find a
handy table with :h key-notation.
A: Quite literal:
<Left>
<Right>
<Up>
<Down>
As noted in the comments, find this and more in this tutorial.
A: And
<C-Right>
for Control key and Right.
For example, I used the following mappings (in my .vimrc) to cycle through my open buffers:
nnoremap <silent> <C-Right> :bn<CR>
nnoremap <silent> <C-Left> :bp<CR>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542381",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "59"
} |
Q: Get values from json_encode with jQuery I insert several(array) value with json_encode in one row from database table, now want echo they as order with jquery.
This is output from my PHP code:
[{
"guide": null,
"residence": [{
"name_r": "jack"
}, {
"name_r": "jim"
}, {
"name_r": "sara"
}],
"residence_u": [{
"units": ["hello", "how", "what"],
"extra": ["11", "22", "33"],
"price": ["1,111,111", "2,222,222", "3,333,333"]
}, {
"units": ["fine"],
"extra": ["44"],
"price": ["4,444,444"]
}, {
"units": ["thanks", "good"],
"extra": ["55", "66"],
"price": ["5,555,555", "6,666,666"]
}]
}]
I want as(output):
jack hello & 11 & 1,111,111 how & 22 & 2,222,222 what & 33
& 3,333,333,
jim fine & 44 & 4,444,444
sara thanks & 55 & 5,555,555 good & 66 & 6,666,666
How is it?
A: Assuming
*
*you already know how make the ajax request that fetches this information from your PHP script
*there is always one element in the top-level array (if not, you could add one more level of iteration)
*by output you mean access the corresponding elements - I've put in calls to console.log but you could alert() or put into a DOM element or whatever
you could do something like this in jQuery (here's an example fiddle without the network part. You'll see the output in your console)
var data = response[0]; //response is the data received by the jQuery ajax success callback
var residences = data.residence;
var residence_u = data.residence_u;
$.each(residences, function(index, val){
var name = val.name_r;
console.log(name);
var info = residence_u[index]; //get the corresponding residence_u element
$.each(info.units, function(index, val){
var unit = val;
var extra = info.extra[index];
var price = info.price[index];
console.log( val + " & " + extra + " & " + price);
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542382",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Good features of paths for machine learning I'm looking into ML problems (mostly density estimation and anomaly detection) with paths made up of coordinates (GPS). Other than the coordinates themselves and deltas (changes between adjacent coordinate points) and polar coordinates what are some other good features? What features make intuitive attributes like straightness, curvy-ness, smoothness, and loopy-ness explicit?
A: For straightness/curviness you may want to calculate an approximate first derivative of the curve, for smoothness the second and higher derivatives.
If by loopiness you mean the tendency to return to places several times, you could for instance count how many segments intersect each other.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542384",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Binary Search Tree Preorder Traversal I have a question regarding preorder traversal of binary search tree. I know what the algorithm has to be like, its pretty simple:
void preOrder(Node node) {
print(node);
if (node.left() != null)
preOrder(node.left());
if (node.right() != null)
preOrder(node.right());
}
For some reason, my function prints out only the left side subtree of the root node, and it prints out the lowest node twice. I ran a search method on one of the items on the right side and it returned true so I assume my insertion is working properly. Why is this happening?
My code is below. The public method calls the private one. In the private one, the first two if-statements are there to print the left and right nodes connected to that node. The last two do the actual recursive algorithm.
public void print() {
if (root == null)
System.out.println("Tree is empty");
else
print(root);
}
private void print(NodeBST node) {
printOut(node);
if (node.left() != null) {
System.out.print("Left: ");
printOut(node.left());
}
else
System.out.println("No left");
if (node.right() != null) {
System.out.print("Right: ");
printOut(node.right());
}
else
System.out.println("No right");
System.out.println("");
if (node.left() != null) {
node = node.left();
print(node);
}
if (node.right() != null) {
node = node.right();
print(node);
}
}
A: Well one bug you have is that you overwrite node on the line just before the first print(node) and then reuse the modified version again straight afterwards. Presumably you want node to be the original value when doing the if(node.right() != null) test?
You can avoid this by e.g. just calling print(node.left()); in the first if.
A: struct node *MakeBst(int preOrder[],int str,int end)
{
struct node *newnode;
if(str>end)
return NULL;
newnode = malloc(sizeof(node));
if(!newnode)
return NULL;
if(str == end)
return newnode;
newnode->data = preOrder[str];
str++;
x = search_Index(number>preOrder[str-1]);
newnode->left = MAkeBst(preOrder,str,x-1);
newnode->right = MAkeBst(preOrder,x-1,end);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542385",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how can I align to middle by height I want to create image box(with image).
It's ugly when text is in the top of box.
How can I align text to middle?
I tried to use vertical-align, but it seems, that it don't works
Demo of my code
EDIT:
Your solution works fine with short messages.
But if they will be multi-lined, it is ugly again.
Is it possible to not increase size of line If we don't need it?
A: If you want to middle align a block with multiple lines, you can use display:inline-block around that block. So if you have:
<div class="messageInfo">
<div class="messageInner">You are logged out<br>You are crazy<br> gogo</div>
</div>
with
.messageInfo{
background: lightskyblue;
background-image: url(http://i.stack.imgur.com/Z6lkS.png) ;
background-repeat: no-repeat;
min-height: 32px;
vertical-align: middle;
padding-left:32px;
line-height:32px;
}
add
.messageInner {
display:inline-block;
line-height:1.2em;
vertical-align:middle;
}
See http://jsfiddle.net/yNpRE/1/ and http://jsfiddle.net/yNpRE/
Be warned though, that while this works in modern browsers, it doesn't work with IE7 or earlier.
A: What usually works fine is line-height:
line-height: 32px;
http://jsfiddle.net/DhHnZ/2/
A: Set the line-height to the height of the div.
So
.messageInfo{
background: lightskyblue;
background-image: url(http://i.stack.imgur.com/Z6lkS.png) ;
background-repeat: no-repeat;
min-height: 32px;
vertical-align: middle;
padding-left:32px;
line-height:32px; //ADD THIS
}
Working example: http://jsfiddle.net/jasongennaro/DhHnZ/1/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542387",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Q: Django auth context processor: not to query for user for each request I enabled django auth middleware, so now I have a user variable in my request context.
In this case for each page request user object is queried from the database. Is it possible to set up this middleware to use a cached user object (for example, that was placed by me in the session)?
User objects are not updated frequently, so I don't need to have an extra DB query for each page.
Thanks.
A: Yes of course you can do this, and I think that it's also a good idea :)
I did this with a custom auth backend in which the get_user method tries to retrieve the user from cache (and then from db in case of cache miss).
A: Yes, you can store the user in the session.
The only thing you have look out for is that if you make changes to that user object, that users who are logged into your system while you push an update might not have that change (ie a property you added).
Just make sure you make your middleware check the object, or write some code somewhere that can. This might be something you only drop in for a release of a user change, and then pull out after the release. (if you're using the django auth user, you prolly wont be changing it at all)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542388",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SQL Database design for huge datasets I have a customer that has the following data structure... for each patient, there may be multiple samples, and each sample may, after processing, have 4 million data objects. The max number of samples per patient is 20. So a single patient may end up with 80 million rows of data, and of course there will be many many hundreds of patients eventually.
In setting up a database to store the objects (which each contain about 30 fields of statistics and measurements) the challenge is pretty clear- how to manage this vast amount of data?
I was thinking that I would have one database, with a table for each sample- so each table may have at most 4 million records.
A colleague of mine had an interesting suggestion which was to take it one step further- create a new database per patient and then have a table per sample. His thinking was that having 1 log per patient, being able to move databases on a per patient basis, etc was good. I can't disagree with him.
Is this reasonable? Is it a bad idea for some reason to have many databases?
Thoughts? Thank you!
A: While the idea is interesting from privacy and migration standpoint, it is NOT a good idea to have a single database per patient. Think about managing, backing up, having files for each patient database. I'm even not sure if DBMS can handle millions of databases at the same time in an instance or a server.
What I would do is, accept the volumetric data as facts of live and deal with it in the type of parameters and tables you choose. Let the DBMS worry about the schale of it. Make sure you have a deployment model allowing to scale-up and scale-out your tables. A table per entity, at least would be wise, so for patient, measurement, etc.
Just, do what you are good in as a developer and let the DBMS do what it is created for.
A: When working with that much data, you will definitely want to explore MySQL and RDBMS alternatives. Have you looked into any noSQL solutions? (i.e. key value stores). There are several open source solutions, some of which would immediately not be right for this application given that any data loss is probably unacceptable.
Perhaps try looking at Apache's Cassandra http://cassandra.apache.org/. Its a distributed database system (key-value store), but can run on a single node as well. It would allow you to store all of your data for each patient under a single key value "i.e. Patient1" and then from there you could organize your data into whatever key-value structure is best for querying in your application.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542390",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Convert array of unsigned char (byte) into unsigned short in C++ I have array^ byteArray and I need to extract bytes in Little Endian sequence to make unsigned shorts and ints. I've tried every combination of the following I can think of so am asking for help.
int x = UInt32(byteArray[i]) + (UInt32)(0x00ff) * UInt32(byteArray[i + 1]);
int x = UInt32(byteArray[i]) + UInt32(0x00ff) * UInt32(byteArray[i + 1]);
int x = byteArray[i] + 0x00ff * byteArray[i + 1];
The problem is the least significant byte (at i+1) I know it is 0x50 but the generated short/int reports the lower byte as 0x0b. The higher byte is unaffected.
I figure this is a sign error but I can't seem to be able to fix it.
A: You are using managed code. Endian-ness is an implementation detail that the framework is aware of:
array<Byte>^ arr = gcnew array<Byte> { 1, 2, 3, 4 };
int value = BitConverter::ToInt16(arr, 1);
System::Diagnostics::Debug::Assert(value == 0x302);
Whether the framework's assumptions are correct depends on where the data came from.
A: The proper way to generate an 16 bit int from two 8 bit ints is value = static_cast< int16_t >( hibyte ) << 8 | lobyte;
A: int y = byteArray[i] | byteArray[i + 1] << 8;
is what you need to use. (see also Convert a vector<unsigned char> to vector<unsigned short>)
A: You want to do this instead
int x = UInt32(byteArray[i]) | (UInt32(byteArray[i + 1]) << 8);
Your multipliers are messing things up.
A: You have to multiply the second byte with 0x0100 instead of 0x00ff.
It's like in the decimal system, where you multiply by ten, not by nine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542391",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to implement hover effect that fades in when you hover over the left side (previous function) slides in and fades darker and vice versa for the right
here's what I got so far thanks to Deleteman
http://jsfiddle.net/pQzWp/
A: I would try to do the following:
Inside the block element that holds the image, add two block elements like this:
#element1 {
position:absolute;
left:0;
top:0
width:30%;
height:100%;
}
#element2 {
position:absolute;
right:0;
top:0
width:30%;
height:100%;
}
And the position of the image container, set it the position to be "relative".
Now, you can set events like this:
$("#element1").mouseover(function() {
//show "prev" link
});
$("#element2").mouseover(function() {
//show "next" link
});
Hope it helps!
Edit
Check it out: http://jsfiddle.net/pQzWp/7/
Changed your framework to JQuery, since I don't know much about mootools, you can change the fadeIn and fadeOut effect for whatever you want.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542393",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to extract classes out of Python modules? I'm trying to write a script that takes two Bots and then feeds them to an engine for them to play a game. As an example usage:
$:python rungame.py smartbot.py dumbbot.py
Detected SmartBot in smartbot.py...
Detected DumbBot in dumbbot.py...
Running game...
The problem I'm having is that I have no idea how to detect/get the Bot objects out of the modules that are provided via the command line. (If it helps any, I wouldn't at all mind enforcing conventions.) How do I do this?
A: You'd probably need the class name as well a module name. With that, you could use this:
getattr(__import__(module_name), class_name)
If you don't want to make them specify a class name, you might be able to find a class that ends with Bot:
module = __import__(module_name)
clazz = None
for attribute_name in dir(module):
attribute = getattr(module, attribute_name)
if attribute_name.endswith('Bot') and callable(attribute):
clazz = attribute
break
However:
Explicit is better than implicit. —The Zen of Python
So I'd stick with the first approach of letting them specify the module and class name.
A: One of the most common patterns for this problem is to define in your API that the object must have a particular name; For instance, you might call that special variable bot:
# smartbot.py
class SmartBot(object):
"A very smart bot!"
bot = SmartBot()
# dumbbot.py
class DumbBot(object):
"A dumb bot bot!"
bot = DumbBot()
# rungame.py
import sys
for source in sys.argv[1:]:
l = {}
execfile(source, l)
bot = l["bot"]
print "Detected %s in %s..." % (type(bot).__name__, source)
print "Running game..."
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542405",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How do I replace vowels in a list with underscore? I have a list of characters (basically a word) and I want to substitute the vowels in the word by underscore ['_'] and return a new list.
eg:
?-sub([s,e,g,e,d],A).
A=[s,_,g,_,d]
My attempt built the new list in the reverse order then finally when it exited from the predicate call it dismantle everything and declare that it found the goal without the output string!
The algorithm I used is: pick element of a list and check whether it is a vowel or not and append the ['_'] or the element itself to the new list.
sub([],B).
sub([X|T1],Y):-
((vocal(X), append(['_'],Y,Z));
(not(vocal(X)), append([X],Y,Z))),
sub(T1,Z).
vocal(a).
vocal(e).
vocal(i).
vocal(o).
vocal(u).
A: In SWI-Prolog:
sub(In, Out) :-
maplist(vowel_to_underscore, In, Out).
vowel_to_underscore(Vowel, '_') :-
vocal(Vowel),
!.
vowel_to_underscore(X, X).
vocal(a).
vocal(e).
vocal(i).
vocal(o).
vocal(u).
A: The first thing you should do: pay attention to the warnings.
Surely the compiler warned you about the singleton in the base case of the recursion.
sub([], []).
sub([X|Xs], [Y|Ys]) :-
(vocal(X), '_' = Y ; X = Y),
!, sub(Xs, Ys).
Please note that in Prolog the = doesn't means assign, but unification. You should understand this and (if you really want to understand Prolog) why your solution reverses the input. Try to write reverse/2 by yoursef!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542406",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I know if a variable is private? I've never understood private variables. I know how to make them, (using the Module Pattern, right) but I don't see what's so private about them. I illustrated an explanation on jsFiddle -- http://jsfiddle.net/fufWX/
Can you explain how that _private variable really is private when it is still accessible from the outerscope? And what are the use for private variables in the first place!? Thanks.
var Module = (function() {
var _private = "My private variable";
return {
get: function() { return _private; },
set: function(e) { _private = e; }
};
})();
var obj = {};
// How is that variable private when I can simply obtain it like this:
obj.get = Module.get; // ??
obj.set = Module.set; // ??
obj.get(); // "My private variable"
A: There's no such thing as a truly private variable in JavaScript. There are only local variables.
In your example, _private is "private" because, outside of the anonymous function, it is only accessible via the get and set functions your have provided. Without those functions, _private would be totally inaccessible outside of the anonymous function.
Further reading:
*
*Private Members in JavaScript
*OOP in JS, Part 1 : Public/Private Variables and Methods
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542412",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Generating news from db table I'm trying to generate news from db table.
My table look like that
And the function that generated news from db table
function generateNews ($lang, $db)
{
$title = 'title_' . $lang;
$short = 'short_' . $lang;
$detailed = 'detailed_' . $lang;
$result=$db->query("SELECT id, $title as title, $short as short, $detailed as detailed, ndate FROM news");
while($row=$result->fetch_object()) {
$title=makeEntry ('title', $row->title);
$stitle=makeEntry ('stitle', $row->short);
$content=makeEntry ('content',$row->detailed);
$footer=makeEntry ('footer',$row->ndate);
echo makeEntry ('entry',$title.$stitle.$content.$footer);
}
}
function makeEntry ($part,$data)
{
if($part=='title')
return '<h3 class="entry-header">'.$data.'</h3>'."\n";
else if ($part=='stitle')
return '<h4 class="entry-stitle">'.$data.'</h4>'."\n";
else if ($part=='content')
return '<div class="entry-content"><p>'.$data.'</p></div>'."\n";
else if ($part=='footer')
return '<div class="entry-footer">'.$data.'</div>'."\n";
else if ($part=='entry')
return '<div class="entry">'.$data.'</div>'."\n";
}
It works, but this code is very simple so I feel like it could be shortened. Any suggestions?
BTW. Don't post about sql injection holes. I already whitelisted table column names
A: Using a switch case control structure would get you rid of these elseif ($part == )statements.
A: Here's another possible solution:
function makeEntry($part,$data)
{
$results = array( 'title' => '<h3 class="entry-header">'.$data.'</h3>'."\n",
'stitle' => '<h4 class="entry-stitle">'.$data.'</h4>'."\n",
//etc etc....
);
return $results[$part];
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542415",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Cannot run background process on Amazon Linux Instance, but runs on MAC OS X I cannot run a background process in Amazon Linux instance, but The same runs on Mac OS X
I'm trying to run a php script thru cmd line.
It runs fine on Amazon Linux, if I dont append & character at the end.
If i append &, it is having a T as its STAT
Following is what happens
[root@someIp somePath]# php /path/to/myPhpScript.php arg1 arg2 arg3 > /dev/null 2>log.txt &
[1] 17849
[root@someIp somePath]# jobs
[1]+ Stopped php /path/to/myPhpScript.php arg1 arg2 arg3 > /dev/null 2>log.txt
[root@someIp somePath]# bg 1
[1]+ php /path/to/myPhpScript.php arg1 arg2 arg3 > /dev/null 2>log.txt &
[1]+ Stopped php /path/to/myPhpScript.php arg1 arg2 arg3 > /dev/null 2>log.txt
[root@someIp somePath]#
But if I run without & it completes fine.
[root@someIp somePath]# php /path/to/myPhpScript.php arg1 arg2 arg3
Prints some output...
Prints some output...
Prints some output...
Prints some output...
Done...
[root@someIp somePath]#
Same situation: https://forums.aws.amazon.com/thread.jspa?messageID=281552
Thanks!
A: I figured it out myself.
For some reason, It is being stopped becos it thinks it requires some kind of input from the keyboard.
As:
0 : Standard Input (Generally the Keyboard)
1 : Standard Output (Generally the Monitor)
2 : Standard Error
So I added the standard input to read from /dev/null.
I modified my cmd as follows:
# php /path/to/myPhpScript.php arg1 arg2 arg3 0</dev/null 1 >/dev/null 2>log.txt &
OR
# php /path/to/myPhpScript.php arg1 arg2 arg3 </dev/null >/dev/null 2>log.txt &
Thanks! :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542416",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Python Challenge #2 - For loop problem Python Challenge #2
Answer I found
FILE_PATH = 'l2-text'
f = open(FILE_PATH)
print ''.join([ t for t in f.read() if t.isalpha()])
f.close()
Question: Why is their a 't' before the for loop t for t in f.read().
I understand the rest of the code except for that one bit.
If I try to remove it I get an error, so what does it do?
Thanks.
A: This is a list comprehension, not a for-loop.
List comprehensions provide a concise way to create lists.
[t for t in f.read() if t.isalpha()]
This creates a list of all of the alpha characters in the file (f). You then join() them all together.
You now have a link to the documentation, which should help you comprehend comprehensions. It's tricky to search for things when you don't know what they're called!
Hope this helps.
A: [t for t in f.read() if t.isalpha()] is a list comprehension. Basically, it takes the given iterable (f.read()) and forms a list by taking all the elements read by applying an optional filter (the if clause) and a mapping function (the part on the left of the for).
However, the mapping part is trivial here, this makes the syntax look a bit redundant: for each element t given, it just adds the element value (t) to the output list. But more complex expressions are possible, for example t*2 for t ... would duplicate all valid characters.
A: note the following is also valid:
print ''.join(( t for t in f.read() if t.isalpha()))
instead of [ and ] you have ( and )
This specifies a generator instead of a list.
generator comprehension
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: set JList icon with DefaultListCellRenderer? The code below is supposed to get the default directory icon from the JFileChooser and then use that icon in my custom "Recent Directories" list which is provided as an accessory to the JFileChooser dialog. Can someone please explain why the below code does not work (particularly why setIcon on the DefaultListRenderer doesn't do the trick), and tell me how to put the icon next to each item in the JList? I would prefer to avoid implementing my own ListCellRenderer unless that is the only way to make this work.
import java.awt.*;
import java.io.File;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class Chooser extends JPanel {
private static final String[] BUTTON_TEXTS = { "Hello", "Goodbye",
"Hello Goodbye", "Adios", "This is a long String for WTF", "Hello",
"Goodbye", "Hello Goodbye", "Adios", "This string WTF" };
public Chooser(Icon icon) {
this.setLayout(new BorderLayout());
JPanel labelPanel = new JPanel(new BorderLayout());
JLabel label = new JLabel("Recent Directories:");
labelPanel.add(label, BorderLayout.LINE_START);
labelPanel.setBackground(Color.LIGHT_GRAY);
labelPanel.setBorder(new EmptyBorder(5, 10, 5, 0));
DefaultListModel model = new DefaultListModel();
JList list = new JList(model);
DefaultListCellRenderer renderer = (DefaultListCellRenderer)list.getCellRenderer();
renderer.setIcon(icon);
for (String s : BUTTON_TEXTS) model.addElement(s);
list.setBorder(new EmptyBorder(0, 5, 5, 0));
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
// respond to selection here
}
});
add(labelPanel, BorderLayout.PAGE_START);
// add(new JScrollPane(buttonPanel), BorderLayout.CENTER);
add(new JScrollPane(list), BorderLayout.CENTER);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
JFileChooser fileChooser = new JFileChooser();
Icon icon = fileChooser.getIcon(new File("."));
/*JFrame frame = new JFrame();
frame.setSize(100,100);
JPanel temp = new JPanel();
JLabel tlbl = new JLabel("picture");
tlbl.setIcon(icon);
temp.add(tlbl);
frame.add(temp);
frame.setVisible(true);*/
Chooser c = new Chooser(icon);
fileChooser.setAccessory(c);
fileChooser.showOpenDialog(null);
}
}
A: The DefaultListCellRenderer clears the icon whenever its getListCellRendererComponent method is called.
Instead you can interfere with the renderer's method by subclassing DefaultListCellRenderer like that:
list.setCellRenderer(new DefaultListCellRenderer() {
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
label.setIcon(icon);
return label;
}
});
A:
The tip of using a custom cell renderer, extended to include a few other tips specific to dealing with File and Icon objects in a JList.
import java.awt.*;
import java.io.File;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.filechooser.FileSystemView;
public class Chooser extends JPanel {
private static final File[] RECENT_DIRECTORIES = File.listRoots();
public Chooser() {
this.setLayout(new BorderLayout());
JPanel labelPanel = new JPanel(new BorderLayout());
JLabel label = new JLabel("Recent Directories:");
labelPanel.add(label, BorderLayout.LINE_START);
labelPanel.setBackground(Color.LIGHT_GRAY);
labelPanel.setBorder(new EmptyBorder(5, 10, 5, 0));
JList list = new JList(RECENT_DIRECTORIES);
list.setCellRenderer(new DefaultListCellRenderer() {
FileSystemView fsv = FileSystemView.getFileSystemView();
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (value instanceof File) {
label.setIcon(fsv.getSystemIcon((File)value));
}
return label;
}
});
list.setBorder(new EmptyBorder(0, 5, 5, 0));
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
// respond to selection here
}
});
add(labelPanel, BorderLayout.PAGE_START);
add(new JScrollPane(list), BorderLayout.CENTER);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFileChooser fileChooser = new JFileChooser();
Chooser c = new Chooser();
fileChooser.setAccessory(c);
fileChooser.showOpenDialog(null);
}
});
}
}
Summary
In summary, those tips are:
*
*Use a custom cell renderer (as mentioned by Howard)
*Don't use String objects in the JList to represent File objects. Use the File.
*Use meaningful names for the class attributes. E.G. BUTTON_TEXTS -> RECENT_DIRECTORIES
*Provide the File[] to the constructor of the Jlist - there is no need to iterate the array and add each item.
*Use FileSystemView.getSystemIcon(File) to get around the dull icons spat out by each PLAF. The Icon instances in the list look odd beside the icons used in the original left hand pane (starting with "1 Media" etc.). They would match if the PLAF were set to the system PLAF. The point is that FSV will provide the nicer Icon regardless of PLAF.
*Start the GUI on the EDT.
For even more tips (it's tip-a-palooza!), see File Browser GUI.
I did not understand the tip about "PLAF" (I also don't know what PLAF means).
Lucky Google does. Try searching on it and select the first link that mentions 'Java' (here it is the 2nd link).
I did notice that the folder icon that results from using your code is different than the folder/directory icon on the JFileChooser. The JFC's icon is blue and look more java-y. The getIcon() call that I used in my original code does work but I'm not sure how the same icon with a call similar to yours (FileSystemView.getSystemIcon() or similar)
All the icons seen in the File Browser (FileBro) GUI screen shot were made using the file chooser getIcon() method, but they look like the ones in your example that were produced by the FSV, right? The reason they look like the FSV icons seen in the Metal screenshot is that the PLAF was the system default for FileBro ('Windows' PLAF). When a GUI uses the 'native' PLAF for that OS, the icons returned for the file chooser match those returned by the FSV.
If you need more specific answers after doing some research and looking closely at the main() of FileBro to see how it sets the PLAF, ask more specific questions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542423",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to organization JavaScript code in project for maintainability? Am primarily a PHP developer, but of late I've being playing with alot of JavaScript, mostly in jQuery.
The problem is that the code is getting harder to debug and this made harder because I have event listeners littered across the HTML.
The code handles AJAX calls and DOM manipulation.
A: Separation of concerns
This means you have three types of files, HTML, CSS and JS.
You do not mix any HTML, CSS or JS. Each one of them is in its own file.
Merely by keeping everything seperate and never using inline javascript or inline CSS you can solve most your code organization problems.
Another technique is packagers and minifiers.
My packagers of choice are browserify (js) and less (css)
Packagers mean you have all your code in many files/modules split by good design. Then because sending many small files is expensive you use a build-time packager to turn all your js into one js file and all your css into one css file.
As for JS itself, I tend to go further and use a module loader. Browserify is both a packager and a module loader.
Module loaders mean you define small modules and load/require them when you need to and where you need to.
I also implement event driven architecture and the mediator pattern to keep my code highly loosely coupled. One could go further and implement something like the blackboard system but I havn't tried this personally.
A: You may consider to use CommonJS "require" to separate javascript code in many files, then use browserify or Webpack. Another option is Cor which is a language that compiles to javascript focused on organization, cleanness, and development experience.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542424",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: playing a video on the page in silverlight I looked around on google and I'm not so sure what would be the best (in my case, fastest to build) way to have a video file that's on the server (what format should I store it in? wmv?) play on an aspx web page using .net 4.
I'd like to use silverlight with this snippet that I found online:
<MediaElement x:Name="MyVid"
Source="http://abc.xyz.com/MyVid.wmv"
Height="250"
Width="350"
AutoPlay="False"/>
If you have experienced this situation and have suggestions that'd be great.
Thanks.
A: If your target requirements allow it, you should use Html 5 video tag. There are some good articles explaining how to use it.
To synthetise, you can use the video like this :
<video width="400" height="222" controls="controls">
<source src="video.mp4" type="video/mp4" />
<source src="video.webm" type="video/webm" />
<source src="video.ogv" type="video/ogg" />
message if the browser is not html5 compliant here
</video>
You can specify several source, in order to support a larger number of browser (unfortunately, even if the video tag is standard, the CODEC are not).
Another good article is available in the Msdn France - "cahiers de vacances". The 1st volume is explaining the approach, and also the alternative for non-html5 browser, which consists in putting either a flash or SilverLigth player in place of the video tag.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542425",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: inotify and bash I am trying to make a bash script with inotify-tools that will monitor a directory and alter all new files by removing lines containing "EE". Once altered it will move the files to another directory
#!/bin/sh
while inotifywait -e create /home/inventory/initcsv; do
sed '/^\"EE/d' Filein > fileout #how to capture File name?
mv fileout /home/inventory/csvstorage
fi
done
Please help?
A: By default, the text output from inotifywait -e CREATE is of form
watched_filename CREATE event_filename
where watched_filename represents /home/inventory/initcsv and event_filename represents the name of the new file.
So, in place of your while inotifywait -e ... line, put:
DIR=/home/inventory/initcsv
while RES=$(inotifywait -e create $DIR); do
F=${RES#?*CREATE }
and in your sed line use $F as the Filein name. Note, the $(...) construction is posix-compatible form of process substitution (often done using backticks) and the ${RES#pattern} result is equal to $RES with the shortest pattern-matching prefix removed. Note, the last character of the pattern is a blank. [See update 2]
Update 1 To handle file names that may contain whitespace, in the sed line use "$F" instead of $F. That is, use double quotes around the reference to value of F.
The RES=... and F=... definitions do not need to use double quotes, but it is ok to use them if you like; for example: F=${RES#?*CREATE } and F="${RES#?*CREATE }" both will work ok when handling filenames containing whitespace.
Update 2 As noted in Daan's comment, inotifywait has a --format parameter that controls the form of its output. With command
while RES=$(inotifywait -e create $DIR --format %f .)
do echo RES is $RES at `date`; done
running in one terminal and command
touch a aa; sleep 1; touch aaa;sleep 1; touch aaaa
running in another terminal, the following output appeared in the first terminal:
Setting up watches.
Watches established.
RES is a at Tue Dec 31 11:37:20 MST 2013
Setting up watches.
Watches established.
RES is aaa at Tue Dec 31 11:37:21 MST 2013
Setting up watches.
Watches established.
RES is aaaa at Tue Dec 31 11:37:22 MST 2013
Setting up watches.
Watches established.
A: Quoting the man page of inotifywait:
inotifywait will output diagnostic information on standard error and event information on
standard output. The event output can be configured, but by default it consists of lines
of the following form:
watched_filename EVENT_NAMES event_filename
watched_filename
is the name of the file on which the event occurred. If the file is a directory, a
trailing slash is output.
In other words, it prints the names of the files to standard output. So, you need to read them from standard output and operate on them to do what you want to do.
A: The output from inotifywait is of the form:
filename eventlist [eventfilename]
If your file names can contain spaces and commas, this gets tricky to parse. If it only contains 'sane' file names, then you can do:
srcdir=/home/inventory/initcsv
tgtdir=/home/inventory/csvstorage
inotifywait -m -e create "$directory" |
while read filename eventlist eventfile
do
sed '/^"EE/d'/' "$srcdir/$eventfile" > "$tgtdir/$eventfile" &&
rm -f "$srcdir/$eventfile
done
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "30"
} |
Q: How to unpublish an Akka Camel consumer? My Camel consumer actor won't get unpublished after I sent a message to it. This prevents the application from shutting down. It works if I just start and stop the actor without sending any messages. What am I missing here?
Example code:
import akka.actor.Actor
import Actor._
import akka.event.EventHandler
import akka.camel.{CamelContextManager, CamelServiceManager, Message, Consumer}
object Test {
def main(args: Array[String]): Unit = {
val consumer = actorOf(new Actor with Consumer {
def endpointUri = "direct:test"
def receive = {
case msg: Message => println(msg.bodyAs[String])
}
})
val service = CamelServiceManager.startCamelService
service.awaitEndpointActivation(1) {
consumer.start()
}
// If I comment out this row, it works
CamelContextManager.mandatoryTemplate.requestBody("direct:test", "testing")
service.awaitEndpointDeactivation(1) {
consumer.stop()
}
service.stop
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542431",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Referencing an id from separate XUL files If I have two different XUL files, is it possible for the javascript in one to reference a XUL id that is defined in the other? I want to use javascript in a separate xul file to edit the XUL in another one.
A: You can do reference any JS files inside a XUL file & It will be the same If you want to the same JS files in another XUL file.
For example:
<?xml version="1.0"?>
<?xml-stylesheet type="text/css" href="chrome://global/skin/" ?>
<?xml-stylesheet type="text/css"href="chrome://hello/skin/browserOverlay.css" ?>
<!DOCTYPE overlay SYSTEM
"chrome://hello/locale/browserOverlay.dtd">
<overlay id="xulschoolhello-browser-overlay"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<script type="application/x-javascript"
src="chrome://hello/content/browserOverlay.js" />
<script type="application/x-javascript" src="chrome://hello/content/javaLoader.js" />
<script type="application/x-javascript" src="chrome://hello/content/window.js" />
</overlay>
If you want to use JS inside XUL, it's possible but in this case you can't link this JS functions to another XUL.
Type this inside the XUL file:
<script type="application/x-javascript">
<![CDATA[
// your code here
]]>
</script>
I would recommend to use JS files separately & you can link them to any number of XUL files as I explained above.
References : https://developer.mozilla.org/en/Building_an_Extension
https://developer.mozilla.org/en/Setting_up_extension_development_environment
A: What you seem to be looking for are XUL overlays. These overlays can be registered in your chrome.manifest file and will allow applying modifications to other XUL documents. For example, most Firefox extensions register an overlay for chrome://browser/content/browser.xul (the main browser window).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542437",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Convert Ruby JSON Date to Objective C NSDate I have a Ruby service which receives a JSON date like this:
/Date(1311706800000-0500)/
I need to format it in a way so that it can be read into an Objective C NSDate.
I have tried to use:
seconds_since_epoch = datestring.scan(/[0-9]+/)[0].to_i
return Time.at(seconds_since_epoch)
but that returns Mon Apr 03 10:00:00 -0600 43533.
Whats the best way to convert the JSON into a readable format for NSDate? Thanks for the help.
A: Looks like the JSON has the time in microseconds. Ruby's Time.at needs seconds and optionally, as a second argument, microseconds.
str = "1311706800000-0500"
# ignore the -0500 (might be a timezone)
secs, microsecs = str.scan(/[0-9]+/)[0].to_i.divmod(1000)
p Time.at(secs, microsecs) #=> 2011-07-26 21:00:00 +0200 with my locale
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542440",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Objective-C checking if URL exists in Command Line application I have a simple command line application to test the presence of files. The files are very large, however, and I would like to check that they are there without downloading the whole file. This is what I have but it downloads each file:
NSURL *url = [NSURL URLWithString:downloadPath];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLResponse *response = nil;
NSError **error=nil;
NSData *data=[[NSData alloc] initWithData:[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:error]];
NSInteger httpStatus = [((NSHTTPURLResponse *)response) statusCode];
if(httpStatus == 404)
{
NSLog(@"%@ NOT FOUND!",[productDic objectForKey:@"fileName"]);
}
The files I am looking for are .zip and are not found locally.
A: If you make a HEAD request instead of a GET request, you'll probably get what you're after:
NSMutableURLRequest *request = [[NSURLRequest requestWithURL:url] mutableCopy];
[request setHTTPMethod:@"HEAD"];
[request autorelease];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542444",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Stripping non A-Z characters in vector in R I have a vector of usernames that have non A-Z characters in them.
I want to be able to strip those characters out.
I was told to use letters vector but y =x[letters] doesn't seem to work.
Thanks
A: If x is your vector, use a simple pair of range regexes with gsub and replace all with the empty string. Using ^ gives the negation of the pattern:
gsub("[^a-zA-Z]", "", x)
For example, with some simple data.
gsub("[^a-zA-Z]", "", c(letters, LETTERS, "3s8t7a2c9k:o3v8e7r%F%L^O#W%&^%@#^"))
[1] "a" "b" "c" "d" "e" "f" "g" "h"
[9] "i" "j" "k" "l" "m" "n" "o" "p"
[17] "q" "r" "s" "t" "u" "v" "w" "x"
[25] "y" "z" "A" "B" "C" "D" "E" "F"
[33] "G" "H" "I" "J" "K" "L" "M" "N"
[41] "O" "P" "Q" "R" "S" "T" "U" "V"
[49] "W" "X" "Y" "Z" "stackoverFLOW"
A: Maybe this does what you want
username <- "user12_AB"
strip_non_letters <- function(s) {
idx <- which(strsplit(tolower(s),"")[[1]] %in% letters)
paste(strsplit(s, "")[[1]][idx], collapse="")
}
strip_non_letters(username)
A: similar to the above from Karsten, hope not too redundant
usernames <- c("A!ex25","Goerge?","H@rry","Dumbname89")
# a function to cut out non-letters
onlyletters <- function(x){
chars <- unlist(strsplit(x,split=""))
charsout <- chars[chars%in%c(letters,LETTERS)]
paste(charsout,sep="",collapse="")
}
sapply(usernames,onlyletters)
> A!ex25 Goerge? H@rry Dumbname89
> "Aex" "Goerge" "Hrry" "Dumbname"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542447",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Dividing variables in Objective-C so I need to divide on variable by a number.
How can I do this?
I know about the C functions of DIV and MOD, but do not know how to use them in objective-C/cocoa-touch.
Heres an example of my code.
// hide the previous view
scrollView.hidden = YES;
//add the new view
scrollViewTwo.hidden = NO;
NSUInteger across;
int i;
NSUInteger *arrayCount;
// I need to take arrayCount divided by three and get the remainder
When I try to use / or % I get the error
"Invalid operands to binary expression ('NSUInteger and int)
Thanks for any help
A: Firstly, should arrayCount really be a pointer?
Anyway, if arrayCount should be a pointer, you just need to dereference it...
NSInteger arrayCountValue = *arrayCount;
... and use the operators / (for division) and % (for getting the module):
NSInteger quotient = arrayCountValue / 3;
NSInteger rest = arrayCountValue % 3;
You can do it without the auxiliary variable too:
NSInteger quotient = *arrayCount / 3;
NSInteger rest = *arrayCount % 3;
And just remove the dereference operator * if arrayCount is not a pointer:
NSInteger quotient = arrayCount / 3;
NSInteger rest = arrayCount % 3;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542450",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Issues accessing nested JSON objects via javascript/jQuery This is the JSON i'm getting:
{"status":"failure","msg":{"name":["can't be blank"],"email":["can't be blank","is invalid"]}}
This is the javascript i'm using:
$("#sign_in_form").submit(function() {
var success_function = function(data) {
if(data.status == 'failure') {
$("#error_msg").html(data.msg.name)
}
};
$.post($(this).attr("action"), $(this).serialize(), success_function, "json");
});
The error I'm getting from Firebug is:
uncaught exception: [Exception... "Could not convert JavaScript argument arg 0 [nsIDOMDocumentFragment.appendChild]" nsresult: "0x80570009 (NS_ERROR_XPC_BAD_CONVERT_JS)" location: "JS frame :: http://localhost:3000/assets/jquery.js?body=1 :: <TOP_LEVEL> :: line 6182" data: no]
Everything works fine. My javascript can access the data.status value but using data.msg.name produces the uncaught exception.
A: try
data.msg.name[0]
Hope that helps
A: it should be
$("#error_msg").html(data.msg.name[0] || '');
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542451",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: iPhone - Storing a double value into a NSDictionary with only 7 decimals as a Number type I have a PList that contains a dictionary with some decimal values like 10.1234567, stored as Number type (tag ).
In my app, I read that plist and manipulate those values as NSNumber (double type values) with a custom class and its accessors :
@interface
...
@property(nonatomic, assign) NSNumber* someValue;
...
@end
@implementation
...
- (NSNumber*) someValue { return [self.dict objectForKey:@"val"]; }
- (void) setSomeValue:(NSNumber*)val { [self.dict setValue:val forKey:@"val"]; }
...
@end
Then in some case, I write back on the disk the plist.
I've notice a few hours ago that those values where, let's say, converted and are now something like 10.123456699999999. All of them ! ...
Woaw, I didn't expected that change.
Well, I've tried to contain the problem changing the accessors with many thing, like for example this one :
- (NSNumber*) someValue { return [self.dict objectForKey:@"val"]; }
- (void) setSomeValue:(NSNumber*)val { [self.dict setValue:
[NSNumber numberWithDouble:[[NSString stringWithFormat:@"%.7lf", [val doubleValue]] doubleValue]]
forKey:@"val"]; }
But I can't succeed keeping those value stay with their original 7 decimals.
How may I do to write only 7 decimals, without having to use something else than a Number type for the field into the dictionary (I mean, using a String wouldn't be a good solution) ?
The creation of the plist file was made by hand, with some hours of typing, typing those 7 decimal values into each field, and they weren't "converted" at that moment. They were stored with 7 decimal. So I guess there is a solution to keep those 7 decimals when writing them back by program.
A: Welcome to the wonderful world of floating-point. If you want to use floating-point values you have to be prepared for the fact that floating-point values are only rarely exactly the values you want, but more often a hair more or less.
You can use an integer (scaled as necessary), or convert to character form. There is an NSDecimalNumber class that would be precise, but it does not fit into the NSNumber scheme and will not, to my knowledge, work with JSON, et al, if that were necessary. Should work as a dictionary key though, I'd think.
A: You might want to look into IEEE standard 754-2008, and brush up on your binary. Computers don't store floating point internally using base-10 digits 0 through 9; rather, they use binary numbers 0 and 1. If you feed 10.1234567 into a computer and ask it to store that number as a 64-bit double floating-point number, the closest it can get to that value will be something like the 10.1234566999999.... that you see. And that number is actually something like 1001.00111111001101011011011 (ie, 10 + 2071259/16777216).
If you want to store exactly 7 decimal digits, then store the raw characters as a string. Or come up with some other way of storing base-10 digits, instead of base-2 binary digits.
If you want to convert a floating-point number to text with only 7 digits of precision, you can use:
NSString* output = [NSString stringWithFormat:@"%.7d",myFloat];
A: Use NSNumberFormatter when you extract the NSNumber from the plist and it should work:
NSNumberFormatter *nf = [[[NSNumberFormatter alloc] init] autorelease];
[nf setMaximumFractionDigits:7];
NSNumber *yourNumber = [nf numberFromString:[[self someValue] stringValue]];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542452",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to convert lighting effects in psd to xhtml? i have a psd that i am converting now to xhtml. the design is great and the coding is fun but the psd is full of lighting effects layers.
each element in the page (header,footer,content,buttons and menus) has at least 2 lighting effects which is basically a white brush spot with overlay mode.
i tried to do it by getting each light effect in a separate image and make them backgrounds for multiple Devs and position them where it should be but the code is getting complex which i don't like and images starts to be huge effect on page load.
i tried to get all the effects in one very big image and position it once on the whole page because the design is fixed width. thank God for that. but again the image is huge and some elements are not always there in the page to have its lighting effect.
i really don't know what else to do with them. help plz.
thanks
A: Try to flatten the lighting effect onto the image that it's highlighting. That way it's only one image, which it sounds like you already have the position for.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542453",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Cleaning/Compacting multiple states represented by boolean variables In an implementation, i have a lot of states, represented by boolean variables, in such a way that when a state is true, variable against that state is true, and many or all of the others are false. It is not a good way, and since i was only planning my solution before coding, it turned out to be like this. Now i have to clean it. What is the best possible solution to clean?
I was thinking about enum, give a name to each state, and this way one variable can contain the state name instead of multiple variables. But the problem is that there is other information associated with some states, such as one or two instances of Point or int variables, which are only for that state. How to accommodate them if enum is used?
What is the most elegant and appropriate solution in situations like these?
A: Have a look at the state design pattern to implement state machines, instead of mapping states to an enum, each state is a class, events are member functions of the state classes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542455",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I force "Compatibility View" ON in IE9 on a page with a proper Doc Type? I have a site that is nearly all standards compliant, and expects to be that way across all browsers. However, I have a specific page on my site that I want to render in a standards compliant way in Firefox, Chrome, Opera, and Safari, but due to a very annoying issue involving Zoom Levels in the Microsoft SSRS Report Viewer 10.0.0.0 control (See here for a more complete description), I need to render the page in Compatibility View mode in IE9.
A: For IE9, add <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" /> or add <?xml version="1.0" encoding="UTF-8"> as first line in your page. See http://webdesign.about.com/od/metataglibraries/p/x-ua-compatible-meta-tag.htm for details.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542456",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Program to Restrict User Access I have had this project in mind for a while but have had trouble on how to go about doing it.
What I want to code is a security application that will temporarily restrict the access of the user to just one or two selected applications.
Let's say you're bringing your laptop to a situation in which many people will be using it. You only want them to be able to browse the internet and not play games / listen to itunes / look through and mess with your files and so on. You select a program, let's say Firefox in this case, and then a master password. Only Firefox can be used and when the user tries to click outside of Firefox a prompt will appear asking for the password. Obviously CTRL+ALT+DEL would need to be restricted for this too.
I have considerable experience with Java and web dev languages along with some experience in C. However, the only applications I have coded thus far are homework style desktop applications, this seems a lot more "real world" and I don't know how to begin or what language to code it in.
What I was thinking was having the user select the .exe that he wanted to be available, and any time a new .exe was launched it would be checked to see if it was on the available list of .exes (so if Firefox.exe was enabled, Steam.exe would be force closed) but this doesn't seem a very good way of doing it.
Could you give me some pointers? I think this will need doing in C/C++ as it will be beyond the capabilites of Java. I have tried some research and I'm not asking for someone to do this for me, just a general idea how to do this properly rather than in a hacky way. Coding for Windows 7.
A: If you have a Professional, Ultimate, or Enterprise, start with Group Policy. (Start->gpedit.msc). There are settings there to restrict which programs can be launched from Explorer and prevent opening of Task Manager. Note that tis doesn;t help with launching programs from other programs, however.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542459",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Need advice for development of a graph based simulation engine Here in my university they have developed a java based application for visualizing graphs and manipulating them, something similar to GUESS but somehow with different capabilities. the website hosting the project is graphlab.sharif.edu but the server is down at the moment. anyway, we have now decided to split the program into pieces and make them publicly available so that they can be used in other applictions. more precisely, we want to make use of these parts in developing a general purpose simulation software, or at least use them in different simulation programs.
The application has a powerful core which is based on the blackboard design pattern. this is the first part to be extracted. other parts include an xml-based ui platform, a basic shell console (using beanshell), and other plugins which enhance its functionalities in different ways like integration with MATLAB and animating algorithms.
What I'm looking for is some suggestions and comments before we start applying the necessary modifications and extraction of the core. since the development of this application goes back to around 5 or 6 years ago, they haven't used some well-known technologies which are widely used today like JSON for example. also there's been no unit testing. so, if you have experience in the development of such an application, what do you suggest we should do? what technologies we'd better use and what for? is blackboard really
a good solution for such an application platform?
how do you think we should use JSON to enable developers from different languages extend the capabilities of our program?
If there's any further info you wish to know about the project please let me know,
thanks in advance
A: The problem you are facing seems pretty complex, so I only can give suggestions regarding some aspects of your question.
The first thing I would do is to actually divide the whole project into sub-modules (assuming this has not been done yet). Most likely, you will have some unpleasant surprises during this process (ie., things being dependent from each other that shouldn't, auxiliary code placed into the wrong submodule, etc.). I would also suggest you use a build tool to document these dependencies.
In case of missing unit tests, in my experience it is quite hard to write sensible unit tests after much of the project has been under development for such a long time. They likely won't be as valuable as the ones you write during development, but some may still be useful for regression testing, ie. to make sure you do not mess up refactoring or clean-up in preparation of the release: the best way to go seems to be to create new tests step-by-step, so that these check the parts of the project you are currently preparing for a release.
Finally, I suggest you make a release with minimal functionality as fast as possible. This allows others to give you honest and practical feedback (bug reports, feature requests, etc.), which may then guide your development w.r.t. releasing the other modules and follow-up versions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542465",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Week of the month I am trying to get the week number of the month and this is what I am trying to do:
x=`date +"%V"`
echo "x is $x"
y=`date +"%V" -d $(date +"%Y%m01")`
echo "y is $y"
week_of_month=$((x-y))
echo "week_of_month is $week_of_month"
and this is what I get:
x is 38
y is 38
week_of_month is 0
But if my statment is working correctly the value of y should be 35 or so. What am I doing wrong?
A: This worked for me on OS X:
week_today=$(date "+%W")
week_start_of_month=$(date -v1d "+%W")
week_of_month=$[week_today - week_start_of_month + 1]
This assumes Monday to be the first day of the week. If you want Sunday to be treated as the first day of the week instead you'd have to substitute %W with %U.
This gives a week number from 1 to 6. If you'd like to have a zero indexed week number instead just drop the + 1 in the last line.
A: echo $((($(date +%-d)-1)/7+1))
A: You cannot trust date +%V because it gives the (apparently useless) ISO week of year.
This means you get odd-ball results, like Jan.1 being the 52nd week of the year.
E.g.:
date --date='2012-01-01 12pm UTC' +%V
52
A: This seems to be the most portable solution:
#/bin/sh
_DOM=`date +%d`
_WOM=$(((${_DOM}-1)/7+1))
A: On Mac OS X, I was able to do this for the desired result.
y=`date -v1d +%V`
A: on Solaris 5.10
date +%V works fine.
refer to man pages of Date for your machine.
A: Im not a shell person, But if you want to find the week number an algorithm like this will do.
Find the offset , the date of the first sunday, for march 2012 it is 4.
(yourdate+offset)/7 will give you the week of month that it is.
you can easily do this in c# , dont know about shell.
A: For Linux, try below command
Week=$(($(date "+%W")-$(date --date="$(date --date="$(($DAY-1)) days ago")" +"%V")+1))
This will calculate the current week number and subtract the week number of start date of the month.
Remove +1 at the end if you want to start the week number of the month from '0'.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542466",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Unable to open URL stream The code below is for a Google App Engine project.
Why do I get a Stream Closed error without seeing any line returned?
I am definite that the page the URL points to is active.
URL url = new URL("http://banico.com.au");
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
resp.getWriter().println("START");
while ((line = reader.readLine()) != null)
{
reader.close();
}
resp.getWriter().println("END");
A: You should move the reader.close(); outside of the while statement.
A: I think you have to wrap the BufferedReader instantiation inside a try catch block
or no try this
URLConnection urlc=url.openConnection();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542472",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: php not sending email? I'm on a godaddy hosting account and my emails were sent fine until today. It seems as though all the emails form my site stopped sending.
<?php
$to = "myemail";
$subject = "Client Question";
$msg = "From: {$_POST['name']} \n Email: {$_POST['email']} \n Phone: {$_POST['phone']} \n Msg: {$_POST['message']}";
$headers = "From: myemail";
mail("$to", "$subject", "$msg", "$headers");
echo "<p style='color: green'>Your message was sent!</p>";
echo $mail_sent ? "Mail sent" : "Mail failed";
?>
I'm still a newbie in sending emails so I'm not so sure why is used to send however isn't anymore. Any advice on how to make it work/faster
The messages are sending I'm not receiving them though. But this is not a problem with my email since I can still receive emails from GMAIL/Yahoo
A: I wouldn't expect it to be the source of your problem, but you needn't enclose variables in quotes like
mail("$to", "$subject", "$msg", "$headers");
// instead...
mail($to, $subject, $msg, $headers);
A: Well, the following things come to my head:
*
*It could be (most likely is) a problem with the SMTP server.
*Even though headers aren't malformed or anything, it might have something to do with them.
*Last but not least, your mail might be blocked by the receiving SMTP server (uhm, maybe it uses a whitelist or something like that)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542474",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MFMailComposer -- Attach Image with HTML ON I am trying to send an email with an image attachment and HTML turned on. The problem is that when HTML is on, the image appears inline instead of as an attachment (I use gmail).
If I set isHTML:NO then the image properly shows up as a downloadable attachment. How can I send the image as an attachment with an html message?
NSData *imageAttachment = UIImageJPEGRepresentation(myUIImage,1);
MFMailComposeViewController *mailView = [[MFMailComposeViewController alloc] init];
[mailView setSubject:@"My Email Subject!"];
[mailView addAttachmentData:imageAttachment mimeType:@"image/jpeg" fileName:@"imageAttachment.jpg"];
[mailView setMessageBody:messageBody isHTML:YES];
Thanks~!!
A: Your method for attaching the image is correct, and the results you are getting are also up to par.
Either way, the end user (whether they use Gmail or not) should get the attachment.
For instance, Windows Live Mail should see it as an attachment, where as using Mail in Mac OS, you would see the image inline.
A: You have to add the images as an attachment. The rendered email that you see with HTML doesn't get rendered properly with the missing image URL.
here is an example: the caveat is that if you want to include things like a PDF you must include an image otherwise mfmailcomposer will fail... this in an apple bug.
I found the solution... Isubmitted a bug on Apple radar about it. MFMailcomposer has a bug in which you have to send an image along with your extra attachments in order to get the weird items like a pdf to work... try this and replace the pdf with your card:
MFMailComposeViewController *controller = [[MFMailComposeViewController alloc] init];
NSString *emailSubject = [NSString localizedStringWithFormat:@"MedicalProfile"];
[controller setSubject:emailSubject];
NSString *fileName = [NSString stringWithFormat:@"%@.pdf", profileName];
NSString *saveDirectory = NSTemporaryDirectory();
NSString *saveFileName = fileName;
NSString *documentPath = [saveDirectory stringByAppendingPathComponent:saveFileName];
*** YOU MUST INCLUDE AN IMAGE OR THE PDF ATTATCHMENT WILL FAIL!!!***
// Attach a PDF file to the email
NSData *pdfData = [NSData dataWithContentsOfFile:documentPath];
[controller addAttachmentData:pdfData mimeType:@"application/pdf" fileName:fileName];
// Attach an image to the email
NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"miniDoc" ofType:@"png"];
NSData *imageData = [NSData dataWithContentsOfFile:imagePath];
[controller addAttachmentData:imageData mimeType:@"image/png" fileName:@"doctor"];
[controller setMessageBody:[NSString stringWithFormat:@"%@'s Medical Profile attatched!", profileName] isHTML:NO];
[self presentModalViewController:controller animated:YES];
controller.mailComposeDelegate = self;
[controller release];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542475",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What are the common use cases for __IPHONE_OS_VERSION_MAX_ALLOWED? What are the situations in which you would use the __IPHONE_OS_VERSION_MAX_ALLOWED check? What about __IPHONE_OS_VERSION_MIN_REQUIRED?
A: It's important to understand that these are compile-time constants, they are therefore not useful for detecting at runtime what platform or OS version you are running on (e.g. detecting if you are running on iPad vs iPhone).
What these constants do is allow you to detect at compile time whether the code is being built for a given SDK or deployment target. For example, if you wrote an open source library that contains code that only works when compiled against the iOS 5 SDK, you might include this check to detect which SDK the code is being compiled for:
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 50000
//you can use iOS 5 APIs here because the SDK supports them
//but the code may still crash if run on an iOS 4 device
#else
//this code can't use iOS 5 APIs as the SDK version doesn't support them
#endif
Or alternatively, if you want to see what the minimum OS version being targeted is...
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 50000
//minimum deployment target is 5.0, so it's safe to use iOS 5-only code
#else
//you can use iOS5 APIs, but the code will need to be backwards
//compatible or it will crash when run on an iOS 4 device
#endif
This is different from detecting at runtime what OS you are running on. If you compile the code in the first example above using the iOS 4 SDK it will use your iOS 4-safe code, but won't take advantage of any iOS 5 features when run on an iOS 5 device. If you build it using the iOS 5 SDK then set the deployment target to iOS 4 and try to run it on an iOS 4 device, it will compile and install fine but may still crash at runtime because the iOS 5 APIs aren't there.
In the second example above, if you set your deployment target to iOS 4 or below then it will use the iOS 4-safe code path, but if you set the deployment target to iOS 5, it won't run at all on an iOS 4 device (it will refuse to install).
To build an app that runs on iOS 4 and 5 and is still able to take advantage of iOS 5 features if they are available, you need to do run-time detection. To detect the iOS version at runtime you can do this:
if ([[[UIDevice currentDevice] systemVersion] compare:@"5.0.1" options:NSNumericSearch] != NSOrderedAscending) {
//running on iOS 5.0.1 or higher
}
But that means keeping track of exactly which API features were added in which OS version, which is clunky and should only be done as a last resort. Usually, a better approach is to use feature detection, like this:
if ([SomeClass class]) {
//this class exists
}
if ([SomeClass instancesRespondToSelector:@selector(someMethod:)]) {
//this method exists
}
Also, to detect at runtime if you are on an iPad or iPhone, you can do this:
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
//on an ipad
}
Performing these checks at runtime allows you to create a single app that runs on multiple devices and iOS versions and is able to take advantage of the features of each platform.
A: a practical implementation/example of using instancesRespondToSelector:, expanding on @Nick Lockwood's anwser:
+(BOOL) testIsHeaderInConnectData:(NSData *) connectData {
static NSString *headString = nil;
static NSData *headData = nil;
static BOOL rangeCheckOk = NO;
static BOOL rangeCheckTestComplete = NO;
if (!rangeCheckTestComplete) {
rangeCheckOk = [NSData instancesRespondToSelector:@selector(rangeOfData:options:range:)];
headString = @"HEAD ";
headData = (rangeCheckOk?[[NSData alloc] initWithBytes:headString.UTF8String length:headString.length]:nil);
headString = (rangeCheckOk?nil:[[NSString alloc ]initWithString:headString]);
rangeCheckTestComplete = YES;
}
NSInteger testLength = connectData.length;
BOOL isHeader = testLength > 5;
if (isHeader) {
testLength = (testLength < 128?testLength:128);
if (rangeCheckOk) {
isHeader = [connectData rangeOfData:headData options:0 range:(NSRange){0,testLength}].location!=NSNotFound;
} else {
NSString *headStart = [[NSString alloc] initWithBytes:connectData.bytes length:testLength encoding:NSUTF8StringEncoding];
isHeader = [headStart rangeOfString:headString].location!=NSNotFound;
[headStart release];
}
}
return isHeader;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: help with first jquery plugin: problem with ajax() I'm experimenting with building a jquery plugin but need some help. I'm getting the following error in firebug:
Node cannot be inserted at the specified point in the hierarchy
this error popped up when I tried to implement an ajax request for populating a div. I do understand what the error is saying but I don't understand why. If you have other hints based on my code you're always welcome to announce. thank you in advance!
btw: I'm receiving a correct response from the ajax call, but I can't insert it without the error above :-(
/**
* @author kasperfish
*/
(function($){
$.fn.extend({
widgetIt: function(options) {
var defaults = {
title: 'Widget Title',
top: '50px',
left: '400px',
evenColor: '#ccc',
oddColor: '#eee',
};
var options = $.extend(defaults, options);
return this.each(function() {
var o = options;
$(this).css({'z-index': '10', display: 'inline-block', position: 'absolute', top: o.top, left: o.left});
var header = $('<div style="min-width: 150px" class="ui-widget-header widgethead"></div>');
var title =$('<div class="w_tit">' + o.title + '</div>');
var content =$('<div class="w_content"></div>');
// Append
$(title).appendTo(header);
$(header).appendTo(this);
$(content).appendTo(this);
$(this).draggable();
// Binding
$(header).dblclick(function() {
$(content).fadeToggle();
// AJAX load data
$.ajax({
url: "widgets/seedshare.widget.php",
context: content,
success: function() {
$(this).html(content);
}
});
});
});
}
});
})(jQuery);
html
<div id="adiv"></div>
on document load
$('#adiv').widgetIt();
A: You have:
$(this).html(content);
this in this scope refers to the XHR object, so you are trying to insert some content into an XHR object, which of course is pointless.
A: As Majid said, this in your ajax function points to the XHR object. If what you're trying to do is to insert the content into the header object, you can fix the problem by changing your code to this:
// Binding
$(header).dblclick(function() {
$(content).fadeToggle();
var self = this;
// AJAX load data
$.ajax({
url: "widgets/seedshare.widget.php",
context: content,
success: function() {
$(self).html(content);
}
});
});
If you're trying to insert it somewhere else in your page, use a jQuery selector for the insertion location.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542481",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: OpenGL Framebuffer, drawing to texture We have a hard time figuring out rendering to texture using framebuffer objects. We have managed to
draw our texture unto another texture, but the texture isn't centered.
If we set the the texture size to correspond to the window size, it's centered, but we want to be able to manage smaller textures.
GLuint texture[3];
unsigned int fbo;
SDL_Surface *TextureImage[1];
int LoadGLTextures( )
{
/* Load The Bitmap, Check For Errors, If Bitmap's Not Found Quit */
if ( ( TextureImage[0] = SDL_LoadBMP( "crate.bmp" ) ) )
{
/* Create The Texture */
glGenTextures( 1, &texture[0] );
/* Typical Texture Generation Using Data From The Bitmap */
glBindTexture( GL_TEXTURE_2D, texture[0] );
/* Generate The Texture */
glTexImage2D( GL_TEXTURE_2D, 0, 3, TextureImage[0]->w,
TextureImage[0]->h, 0, GL_BGR,
GL_UNSIGNED_BYTE, TextureImage[0]->pixels );
/* Linear Filtering */
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
}
/* Free up any memory we may have used */
if ( TextureImage[0] )
//SDL_FreeSurface( TextureImage[0] );
return 1;
}
void initFrameBufferTexture(void) {
glGenTextures(1, &texture[1]); // Generate one texture
glBindTexture(GL_TEXTURE_2D, texture[1]); // Bind the texture fbo_texture
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, TextureImage[0]->w, TextureImage[0]->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); // Create a standard texture with the width and height of our window
// Setup the basic texture parameters
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
//glGenerateMipmapEXT(GL_TEXTURE_2D);
// Unbind the texture
glBindTexture(GL_TEXTURE_2D, 0);
}
void initFrameBuffer(void) {
initFrameBufferTexture(); // Initialize our frame buffer texture
glGenFramebuffersEXT(1, &fbo); // Generate one frame buffer and store the ID in fbo
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo); // Bind our frame buffer
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, texture[1], 0); // Attach the texture fbo_texture to the color buffer in our frame buffer
GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT); // Check that status of our generated frame buffer
if (status != GL_FRAMEBUFFER_COMPLETE_EXT) // If the frame buffer does not report back as complete
{
exit(0); // Exit the application
}
//glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); // Unbind our frame buffer
}
int main(int argc, char *argv[])
{
gfx_manager.init(640, 480, 32);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.375f, 0.375f, 0);
glClearColor(0.3, 0.3, 0.3, 0);
glClear(GL_COLOR_BUFFER_BIT);
LoadGLTextures();
initFrameBuffer();
glMatrixMode(GL_TEXTURE);
glGenFramebuffersEXT(1, &fbo);
glBindTexture(GL_TEXTURE_2D, texture[0]);
glPushAttrib(GL_VIEWPORT_BIT);
//glGenerateMipmapEXT();
//glOrtho(0, TextureImage[0]->w, TextureImage[0]->h, 0, 0, 1);
//glViewport(0, 0, TextureImage[0]->w, TextureImage[0]->h);
glClearColor (0.0f, 0.0f, 1.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glBegin( GL_QUADS ); /* Draw A Quad */
glTexCoord2f(0.0f, 0.0f);glVertex2f(0.0f, 0.0f);
glTexCoord2f(1.0f, 0.0f);glVertex2f(0.0f + TextureImage[0]->w , 0.0f);
glTexCoord2f(1.0f, 1.0f);glVertex2f(0.0f + TextureImage[0]->w, 0.0f + TextureImage[0]->h);
glTexCoord2f(0.0f, 1.0f);glVertex2f(0.0f, 0.0f + TextureImage[0]->h);
glEnd( );
glPopAttrib();
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
glLoadIdentity();
glClearColor (0.0f, 0.0f, 1.0f, 1.0f);
glBindTexture(GL_TEXTURE_2D, texture[1]);
glLoadIdentity();
glBegin( GL_QUADS ); /* Draw A Quad */
glTexCoord2f(0.0f, 0.0f);glVertex2f(300.0f, 200.0f);
glTexCoord2f(0.0f, 1.0f);glVertex2f(300.0f , 200.0f + TextureImage[0]->h);
glTexCoord2f(1.0f, 1.0f);glVertex2f(300.0f + TextureImage[0]->w, 200.0f + TextureImage[0]->h);
glTexCoord2f(1.0f, 0.0f);glVertex2f(300.0f + TextureImage[0]->w, 200.0f);
glEnd( );
SDL_GL_SwapBuffers( );
sleep(100);
return 0;
}
A: You probably have your matrices and viewport set to match your window size. Make sure you change them to be appropriate values for your framebuffer size before drawing to it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542483",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: continued drop down boxes until I am looking for my script to accept a percentage in a drop down box, after the initial selection I want to calculate the remaining percentage and present the user with another drop down box, this would continue until there was a value of 0 left in the last box
here is my code so far, the first box works but after i have created it I lose the trigger to fire the code again ,
Am I going about this the correct way? and can anyone suggest how I can correct the maths if the first drop box value is changed, Im not looking for someone to write code and scripts for me just some sound pointers on where to go with this.
and here is the code
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
$("#choice").change(function() {
valper = $(this).val() ;
valueLeft = 100 - valper;
newline = "<tr bgcolor='#666666'><td> </td> "
newline += "<td><select id='choice'> " ;
for( i=valueLeft; i >0; i--) {
newline += "<option value=" + i + ">" + i + " % </option> " ;
}
newline += "</select></td> <td> </td> </tr> " ;
$('#selector').append(newline)
});
});
</script>
<table width="500" border="1" cellspacing="1" cellpadding="1" bgcolor="#CCCCCC" align="center">
<tr>
<td width="50">top</td>
<td> </td>
<td width="50"> </td>
</tr>
<tbody id='selector' >
<tr bgcolor="#666666" >
<td> </td>
<td>
<select id="choice" name='1' >
<?php
for ( $counter = 100 ; $counter > 0; $counter -= 1) {
echo "<option value='$counter'>$counter%</option> " ;
};
?>
</select></td>
<td> </td>
</tr>
</tbody>
<tr>
<td>Bottom</td>
<td> </td>
<td> </td>
</tr>
</table>
A: jQuery events do not fire for elements created after event registration. Either register the event handler manually on the new box or use live():
$("#choice").live('change', function() {
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542485",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Changing the iOS keyboard animation time Is there a way to change the time the iOS keyboard animation takes?
A: I've actually found a better solution. What you can do is programmatically make the textfield or textview a first responder within an animation with duration of your choice. Example for making the keyboard emerge over the course of one second might be:
[UIView animateWithDuration:1.0 animations:^
{
[myTextField becomeFirstResponder];
}];
Similarly, you can make the keyboard disappear like this:
[UIView animateWithDuration:1.0 animations:^
{
[myTextField resignFirstResponder];
}];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542495",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Galleria not clearing caption I am using Galleria and extending it to show the caption's created from image alt attributes. It works great, however if I choose to have no caption on one image, the caption from the image before is still visible, I notice also that the Galleria info container, where I get my captions from; doesn't update if the alt attribute is empty.
Is there any way to rectify this?
Here is my code.
jQuery("body").find('.galleria').galleria({
autoplay: false,
image_crop: false, // crop all images to fit
thumb_crop: false, // crop all thumbnails to fit
image_position: 'top left',
transition: 'fade', // crossfade photos
transition_speed: 700, // slow down the crossfade
show_counter: false, // crossfade photos
extend: function() {
this.bind(Galleria.IMAGE, function(e) {
var caption = this.$('info-description').html();
//alert(caption)
if(this.$('info-description').html() == ""){
jQuery("body").find('.caption').html();
}else{
jQuery("body").find('.caption').html(this.$('info-description').html());
}
})
}
});//end galleria
I know this is specialised but someone is bound to have come across this problem before. Any suggestions would be amazing.
All the best
Tara
A: Try adding an empty string when you set the caption:
jQuery("body").find('.caption').html('');
If no string is specified in html(..) then it returns the value instead of setting it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542497",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to make my 'sessions' to never expire? I'm using Zend Framework.
I want to do something similar to SO, when you are not a registered user, you keep your account as long as you remove all your cookies.
I know that session <> cookies, however what will be the best way to do that?
By the way, I'm using memcached because I plan to share sessions between frontend.
Is there any recommendations about this? because memcached data are volatile.
May I need to store them in a database instead?
A: A possible solution could be calling Zend_Session::rememberMe() in each request, once you have checked that the user is authenticated.
Hope that helps,
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542499",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: spring PropertyPlaceholderConfigurer and context:property-placeholder I have following bean declaration:
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>WEB-INF/classes/config/properties/database.properties</value>
<value>classpath:config/properties/database.properties</value>
</list>
</property>
<property name="ignoreResourceNotFound" value="true"/>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
Now I want to change above PropertyPlaceholderConfigurer to following format:
<context:component-scan base-package="org.example.config"/>
<util:properties id="jdbcProperties"
location="classpath:config/properties/database.properties"/>
*
*ignoreResourceNotFound will ignore the property while running. e.g:
When testing application WEB-INF/.. path will ignore( since maven
project and property file is under src/main/resources/..), while
launching web application, other property will ignore path, I need
to implement same with above format.
*should be able to add multiple property file like
database.properties, test.properties etc.
*in Spring 3, can I use annotation instead of these xml files for DB
loading, how can I do it? since I am using only one xml file(given
above) to load db stuff.
I am using Spring 3 framework.
A: <context:property-placeholder ... /> is the XML equivalent to the PropertyPlaceholderConfigurer. So, prefer that. The <util:properties/> simply factories a java.util.Properties instance that you can inject.
In Spring 3.1 (not 3.0...) you can do something like this:
@Configuration
@PropertySource("/foo/bar/services.properties")
public class ServiceConfiguration {
@Autowired Environment environment;
@Bean public javax.sql.DataSource dataSource( ){
String user = this.environment.getProperty("ds.user");
...
}
}
In Spring 3.0, you can "access" properties defined using the PropertyPlaceHolderConfigurer mechanism using the SpEl annotations:
@Value("${ds.user}") private String user;
If you want to remove the XML all together, simply register the PropertyPlaceholderConfigurer manually using Java configuration. I prefer the 3.1 approach. But, if youre using the Spring 3.0 approach (since 3.1's not GA yet...), you can now define the above XML like this:
@Configuration
public class MySpring3Configuration {
@Bean
public static PropertyPlaceholderConfigurer configurer() {
PropertyPlaceholderConfigurer ppc = ...
ppc.setLocations(...);
return ppc;
}
@Bean
public class DataSource dataSource(
@Value("${ds.user}") String user,
@Value("${ds.pw}") String pw,
...) {
DataSource ds = ...
ds.setUser(user);
ds.setPassword(pw);
...
return ds;
}
}
Note that the PPC is defined using a static bean definition method. This is required to make sure the bean is registered early, because the PPC is a BeanFactoryPostProcessor - it can influence the registration of the beans themselves in the context, so it necessarily has to be registered before everything else.
A: First, you don't need to define both of those locations. Just use classpath:config/properties/database.properties. In a WAR, WEB-INF/classes is a classpath entry, so it will work just fine.
After that, I think what you mean is you want to use Spring's schema-based configuration to create a configurer. That would go like this:
<context:property-placeholder location="classpath:config/properties/database.properties"/>
Note that you don't need to "ignoreResourceNotFound" anymore. If you need to define the properties separately using util:properties:
<context:property-placeholder properties-ref="jdbcProperties" ignore-resource-not-found="true"/>
There's usually not any reason to define them separately, though.
A: Following worked for me:
<context:property-placeholder location="file:src/resources/spring/AppController.properties"/>
Somehow "classpath:xxx" is not picking the file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542506",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "28"
} |
Q: "Application not installed" after reinstall sometimes When my app is installed on the Android and I want to update it, if I don't uninstall and then reinstall, sometimes an install over top of what's there works, sometimes it doesn't. I have no idea how it decides whether to allow the install or not.
There is no error message, it's just that sometimes the result message is "application installed" and sometimes it's "application not installed".
Is there something I have to do to make sure that a new version can be installed on top of the old version so that the preferences will be preserved? They get deleted on an uninstall.
Thanks!
A: When if you change your keystore.
It could happen. Keep using just one keystore.
And in my opinion, if you want to keep your preferences when you update it, you need something else.
You can keep the preferences file using external storage.
Copy and overwrite. I think it's the best way.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542512",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Re-architecting MySQL Indexes I have to re-architect the index structure because of previously bad index design.
I have some 200 tables with a few thousand up to 20 million rows per table.
It would take days to manually remove indexes and create new indexes on the life system.
So here is my thought:
*
*I erase the schema (after backup ;)
*Create a new schema
*Run a complete series with CREATE TABLE statements declaring the needed Primary Keys and indexes (takes a minute or so)
*Run a RESTORE of the DB into that new schema (This may take 2 hours - but not days)
Does that make sense?
A: I think you're proposed solution is similar, but you could start up a new replication slave and then make the changes to the schema on that machine first. As long as you are only making changes to indexes then events will continue to be re-applied with no errors.
Once the changes have completed you could then 1) promote slave to master, apply same changes on slave and then switch back or 2) stop both MySQL instances and copy across the raw data files from the slave to the master.
Using this method, the indexes are still rebuilt but it does really matter how long it takes to make the changes on the slave. The only downtime is length of time it takes to copy the files across.
There are other solutions out there that can perform non-blocking changes to tables without use of a slave such as oak-online-alter-table http://openarkkit.googlecode.com/svn/trunk/openarkkit/doc/html/oak-online-alter-table.html and a similar tool developed by Facebook http://www.facebook.com/notes/mysql-at-facebook/online-schema-change-for-mysql/430801045932.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542513",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to make sure the size of a floating point is the same across platforms? I'm writing software that has to work on different platforms. It uses floating point numbers. On all platforms, the floating point numbers have to be the same size in memory.
For integers I could use int32_t for example. How can I do this for floating point numbers?
A: If you need to force the values to the same size, you can design a representation that uses only integers of known sizes. You'd convert your floats to that format to save them, and you'd convert them back to floats when you read them.
See how can I extract the mantissa of a double for AProgrammer's explanation of the frexp() function, which will decompose a float into its (integer) exponent and a (double) mantissa. The comments following that answer will explain how to convert the mantissa to an integer.
You can save the integer mantissa and exponent, which will have fixed lengths. Then you can read them back and use the ldexp() function to re-create the original float (with some small error, of course).
A: You can't do it portably in C; you have to take what the systems provide.
That said, on all systems I know of, sizeof(float) == 4 and sizeof(double) == 8, but relying on that absolutely is dangerous.
Different machines can store the same value differently. They might use different floating-point formats, or they might all use IEEE 754. Even if they all use IEEE 754, they might store them in big-endian or little-endian order.
You must decide why you think they must all be the same size. The chances are, you are trying to take some unwarranted short cuts in relaying information between different machines. Don't take the short cuts; they will lead you into problems at some point. If you feel you must, you have to assess what your portability goals really are, and validate whether you can meet them with the design you're proposing. But be very cautious!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542516",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Call a stored procedure with parameter in c# I'm able to delete, insert and update in my program and I try to do an insert by calling a created stored procedure from my database.
This button insert I made works well.
private void btnAdd_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(dc.Con);
SqlCommand cmd = new SqlCommand("Command String", con);
da.InsertCommand = new SqlCommand("INSERT INTO tblContacts VALUES (@FirstName, @LastName)", con);
da.InsertCommand.Parameters.Add("@FirstName", SqlDbType.VarChar).Value = txtFirstName.Text;
da.InsertCommand.Parameters.Add("@LastName", SqlDbType.VarChar).Value = txtLastName.Text;
con.Open();
da.InsertCommand.ExecuteNonQuery();
con.Close();
dt.Clear();
da.Fill(dt);
}
This is the start of the button that calls the procedure named sp_Add_contact to add a contact. The two parameters for sp_Add_contact(@FirstName,@LastName). I searched on google for some good examples but found nothing interesting.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(dc.Con);
SqlCommand cmd = new SqlCommand("Command String", con);
cmd.CommandType = CommandType.StoredProcedure;
???
con.Open();
da. ???.ExecuteNonQuery();
con.Close();
dt.Clear();
da.Fill(dt);
}
A: You have to add parameters since it is needed for the SP to execute
using (SqlConnection con = new SqlConnection(dc.Con))
{
using (SqlCommand cmd = new SqlCommand("SP_ADD", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@FirstName", txtfirstname.Text);
cmd.Parameters.AddWithValue("@LastName", txtlastname.Text);
con.Open();
cmd.ExecuteNonQuery();
}
}
A: It's pretty much the same as running a query. In your original code you are creating a command object, putting it in the cmd variable, and never use it. Here, however, you will use that instead of da.InsertCommand.
Also, use a using for all disposable objects, so that you are sure that they are disposed properly:
private void button1_Click(object sender, EventArgs e) {
using (SqlConnection con = new SqlConnection(dc.Con)) {
using (SqlCommand cmd = new SqlCommand("sp_Add_contact", con)) {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@FirstName", SqlDbType.VarChar).Value = txtFirstName.Text;
cmd.Parameters.Add("@LastName", SqlDbType.VarChar).Value = txtLastName.Text;
con.Open();
cmd.ExecuteNonQuery();
}
}
}
A: As an alternative, I have a library that makes it easy to work with procs: https://www.nuget.org/packages/SprocMapper/
SqlServerAccess sqlAccess = new SqlServerAccess("your connection string");
sqlAccess.Procedure()
.AddSqlParameter("@FirstName", SqlDbType.VarChar, txtFirstName.Text)
.AddSqlParameter("@FirstName", SqlDbType.VarChar, txtLastName.Text)
.ExecuteNonQuery("StoredProcedureName");
A: public void myfunction(){
try
{
sqlcon.Open();
SqlCommand cmd = new SqlCommand("sp_laba", sqlcon);
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
sqlcon.Close();
}
}
A: cmd.Parameters.Add(String parameterName, Object value) is deprecated now. Instead use cmd.Parameters.AddWithValue(String parameterName, Object value)
Add(String parameterName, Object value) has been deprecated. Use AddWithValue(String parameterName, Object value)
There is no difference in terms of functionality. The reason they
deprecated the cmd.Parameters.Add(String parameterName, Object value) in favor of AddWithValue(String parameterName, Object value) is to give more
clarity. Here is the MSDN reference for the same
private void button1_Click(object sender, EventArgs e) {
using (SqlConnection con = new SqlConnection(dc.Con)) {
using (SqlCommand cmd = new SqlCommand("sp_Add_contact", con)) {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@FirstName", SqlDbType.VarChar).Value = txtFirstName.Text;
cmd.Parameters.AddWithValue("@LastName", SqlDbType.VarChar).Value = txtLastName.Text;
con.Open();
cmd.ExecuteNonQuery();
}
}
}
A: The .NET Data Providers consist of a number of classes used to connect to a data source, execute commands, and return recordsets. The Command Object in ADO.NET provides a number of Execute methods that can be used to perform the SQL queries in a variety of fashions.
A stored procedure is a pre-compiled executable object that contains one or more SQL statements. In many cases stored procedures accept input parameters and return multiple values . Parameter values can be supplied if a stored procedure is written to accept them. A sample stored procedure with accepting input parameter is given below :
CREATE PROCEDURE SPCOUNTRY
@COUNTRY VARCHAR(20)
AS
SELECT PUB_NAME FROM publishers WHERE COUNTRY = @COUNTRY
GO
The above stored procedure is accepting a country name (@COUNTRY VARCHAR(20)) as parameter and return all the publishers from the input country. Once the CommandType is set to StoredProcedure, you can use the Parameters collection to define parameters.
command.CommandType = CommandType.StoredProcedure;
param = new SqlParameter("@COUNTRY", "Germany");
param.Direction = ParameterDirection.Input;
param.DbType = DbType.String;
command.Parameters.Add(param);
The above code passing country parameter to the stored procedure from C# application.
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection connection ;
SqlDataAdapter adapter ;
SqlCommand command = new SqlCommand();
SqlParameter param ;
DataSet ds = new DataSet();
int i = 0;
connetionString = "Data Source=servername;Initial Catalog=PUBS;User ID=sa;Password=yourpassword";
connection = new SqlConnection(connetionString);
connection.Open();
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "SPCOUNTRY";
param = new SqlParameter("@COUNTRY", "Germany");
param.Direction = ParameterDirection.Input;
param.DbType = DbType.String;
command.Parameters.Add(param);
adapter = new SqlDataAdapter(command);
adapter.Fill(ds);
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
MessageBox.Show (ds.Tables[0].Rows[i][0].ToString ());
}
connection.Close();
}
}
}
A: Here is my technique I'd like to share. Works well so long as your clr property types are sql equivalent types eg. bool -> bit, long -> bigint, string -> nchar/char/varchar/nvarchar, decimal -> money
public void SaveTransaction(Transaction transaction)
{
using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString))
{
using (var cmd = new SqlCommand("spAddTransaction", con))
{
cmd.CommandType = CommandType.StoredProcedure;
foreach (var prop in transaction.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
cmd.Parameters.AddWithValue("@" + prop.Name, prop.GetValue(transaction, null));
con.Open();
cmd.ExecuteNonQuery();
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542517",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "167"
} |
Q: Multilingual drupal sites and... tag filtering? I'd like to build a multilingual site and I am quite new to drupal, I was wondering if I could proceed in the following way:
I could tag my entries with the world "english" and "italian", then I could display pages only with such tags to filter my site...
Generally speaking, would I be able to filter my site by tag?
Would this option be feasible? What would be the best solution to my problem?
Many thanks for any answer!
Alex
A: http://drupal.org/node/275705 (Tutorial)
http://drupal.org/project/i18n (best module for this)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542520",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rails many-to-many foreign key validation? Newbie question. I would like to add a validation step to my joint table model to make sure that an object of that type cannot be created without the two tables being joined containing the rows being references. For example:
class Appearance < ActiveRecord::Base
belongs_to :dancer
belongs_to :movie
end
class Dancer < ActiveRecord::Base
has_many :appearances, :dependent => :destroy, :foreign_key => 'dancer_id'
has_many :movies, :through => :appearances
end
class Movie < ActiveRecord::Base
has_many :appearances, :dependent => :destroy, :foreign_key => 'movie_id'
has_many :dancers, :through => :appearances
end
How do I make sure Appearance cannot be created if Dancer and Movie rows don't exist?
Thanks folks!
Edit: to answer number's proposal below:
I haven't had much luck with that unfortunately. By playing with the console (after reload) I get something like:
appearance = Appearance.new(:dancer_id = Dancer.all.first.id, :movie_id => Movie.all.first.id)
Movie.all.first.destroy
appearance.valid?
=> true
whereas I'd expect the response to be false since I just nuked the Movie row.
A: You probably want to validate for presence, something like:
class Appearance
belongs_to :movie, :inverse_of => :appearances
belongs_to :dancer, :inverse_of => :appearances
validates :movie, :dancer, :presence => true
end
class Movie
has_many :appearances, :inverse_of => :movie, ...
end
class Dancer
has_many :appearances, :inverse_of => :dancer, ...
end
Edit: Added inverse_of to the associations, which may keep an appearance from being valid if their dancer or movie is destroyed after being loaded. (Or it may not. I didn't test this, but a purpose of inverse_of is to provide better in-memory association handling).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542521",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: read irregular file into a 2-dimension array using C++ I am very new to C++. I believe there are solutions already in stackoverflow but I cannot find any.
I need to read data from a txt file into a 2 dimension array. File is like
54 3 5 678
10 1 2 3 46 8 1 1 2 3 4
9 8 10
Each line contains up to 120 integers and there are no more than 60 lines.
Your reply is high appreciated. Thanks!
Update: It is not homework. Thank you all!
A: Here goes...
Definitely the answer you need1, though very correct and true to C++ nature.
Instead of parsing to a jagged array it reads into a vector of vectors of ints. (Or, a list of sets, a stack of deques, whatever tickles your fancy).
In absense of any specs, I accept
*
*any number of lines (until the first empty one),
*any number (>0) of numbers on any line
*ignoring whitespace anywhere (besides the line ends)
*any integer numbers (including negatives...)
Cheers
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/support_istream_iterator.hpp>
#include <boost/spirit/include/karma.hpp>
namespace spirit = boost::spirit;
namespace qi = boost::spirit::qi;
namespace karma = boost::spirit::karma;
int main()
{
std::cin.unsetf(std::ios::skipws);
spirit::istream_iterator b(std::cin), e;
std::vector<std::vector<int> > vectors;
if (qi::phrase_parse(b, e, +qi::int_ % qi::eol, qi::space - qi::eol, vectors))
std::cout
<< karma::format(karma::right_align(8)[karma::auto_] % ',' % '\n', vectors)
<< std::endl;
return 0;
}
For the input shown, it prints:
54, 3, 5, 678
10, 1, 2, 3, 46, 8, 1, 1, 2, 3, 4
9, 8, 10
Update Standard Library version
See it live here: http://ideone.com/HtAAg
For fun, here is the standard-library-only version of the same. Just to show, that things don't have to be all that bad when you go without the jet propulsion libraries :)
#include <vector>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <iterator>
static void display(const std::vector<int>& v)
{
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, ",\t"));
std::cout << std::endl;
}
int main()
{
std::vector<std::vector<int> > vectors;
std::string s;
while (std::getline(std::cin, s))
{
std::istringstream iss(s);
vectors.push_back(std::vector<int>());
std::copy(std::istream_iterator<int>(iss), std::istream_iterator<int>(), std::back_inserter(vectors.back()));
}
std::for_each(vectors.begin(), vectors.end(), display);
return 0;
}
1 I'm assuming that this is homework. I'm also assuming that your teacher wants you to allocate a int[120][60] or int[60][120] (how would you know how many numbers were read per line? - you'd need extra storage)
A: My solution, just substitute cin with your file stream
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main(int argc, char* argv[]) {
string line;
int ints[60][120] = {0}, i = 0;
stringstream ss;
while (getline(cin, line)) {
ss.str(line);
for(int j = 0; j < 120 && ss; j++) {
ss >> ints[i][j];
}
ss.clear();
i++;
}
cin.ignore();
return 0;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542522",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Passing an array to a function and then changing the values? Basically, let's say I declare an array in int main() and then pass it to another function, can i then change what values the array holds? Something like:
int main()
{
myarray[3] = {4, 5, 6};
myfunc(myarray);
return 0;
}
int myfunc(int myarray[])
{
int x
cout << "Choose a number";
cin >> x
if (x == 1)
{
myarray[] = {0, 1, 3}
}
else
{
some code
}
return 6;
}
This code obviously does not compile, but I can't really think of any other ways to change the values in the array within the function.
A: You can modify elements in the array however initializer lists like this:
myarray[] = {0, 1, 3}
can only be used when you declare the array. To assign to the array you will have to assign each element individually:
myarray[0] = 0;
myarray[1] = 1;
myarray[2] = 3;
A: With the existing function signature there's no way to safely change the values. Normally you 'd do something like
myarray[0] = 0;
myarray[1] = 1;
//etc
There are many other ways to approach this as well, depending on how the values to go into the array are stored (either std::copy or std::generate might be handy here). But right now you don't have a way to know where the array ends.
To amend this, you need to pass the length of the array to the function somehow. One way is to simply pass an additional size_t length parameter. An arguably better way that works in the spirit of C++ iterators is to write the signature like
int myfunc(int* begin, int* end);
and call it with something like
myarray[3] = {4, 5, 6};
myfunc(myarray, myarray + sizeof(myarray) / sizeof(myarray[0]));
A: if (x == 1)
{
myarray[] = {0, 1, 3} // {0,1,3} is an initializer list.
}
Initializer lists are allowed only at the point of declaration. They are not allowed in assignments. And in the if statement, you are doing an assignment. The only way of modifying the array elements is by changing element at each index in the if.
myarray[0] = 0;
myarray[1] = 1;
myarray[2] = 3;
A: This: myarray[] = {0, 1, 3} - is wrong.
You should pass the length of the array, and run a loop that would change its values, instead.
You should never assume a size of the array you get in a function. If the size is constant - make it myfunc(int myarray[THE_SIZE]), otherwise it has to be myfunc(int myarray[], int size), where size is the size of the array passed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542530",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: iPhone - ASP.NET : Resume download of files Hihi all,
I would need to create a restful json wcf webservice method with .NET and c#, this webservice method will take in a couple of information to perfome some checking and validation. Once the validation is completed, it will access the protected azure blob storage to grab a file and return the stream of the file back through the webservice.
And now I have an iphone app to consume the webservice for downloading a file, but the filesize could be big enough that the download process might be interrupted before completion. What should be the best way to handle the resume download mechanism?
What I have in mind is:
*
*webservice receive the request with the file byte range as part of the parameter. Perform the required validation.
*read the file from the blob storage based on the byte range parameters and store it as a temporary file into my disk storage.
*return the bytes of the file in stream through the webservice.
*delete the temporary file.
Is this a good way of doing it? How can I depend on the Range Header for my scenario, where my file is not a static file residing at a fixed location in the server?
Thanks in advance! :)
A: Avoid WCF completely. Use ASP.NET Generic handler for this and HTTP Chunked encoding with HTTP Range header for requesting specific part of data stream. That is exactly mechanism proposed by HTTP standard for this scenario and Generic handler is the simplest way to achieve that. WCF will bring only a lot of unneeded stuff around and make this much more complex.
A: If you are serving dynamic files using ASP.NET WebForms you could look at implementing a custom Http Handler, like the one described in this article by DotNetSlackers.
If you are serving dynamic files using ASP.NET MVC then you could use Lib.Web.Mvc, a library which contains a custom set of ActionResults which respond to range requests. I am using them myself and have had no problems with them at all.
If you are serving static files via ASP.NET Webforms OR MVC then I would recommend looking at Talifun-Web which provides a nice set of Http Modules and Handlers to effectively and efficiently serve files.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542536",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: addEventListener with inexplicable undefined method error I couldn't find an answer to this problem I've been having.
function UploadBar() {
this.reader = new FileReader();
this.reader.addEventListener(
"onloadstart"
, function(evt) {alert("Hello World");}
, false
);
}
when I try to run this code it gives me an undefined_method_error in the javascript debugger in chrome. Could anyone be so kind as to tell me what is wrong here?
A: reader is not an element, so don't use .addEventListener Instead do the following.
function UploadBar() {
this.reader = new FileReader();
this.reader.onloadstart = function(e) { alert('Hello World') };
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542538",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to read in a JPG image into a 3 matrices: red, green, blue? What is the process to read in a JPG image into a 3 matrices (intensities): red, green, blue?
A: you could search for a relevant class in the java api
this might help: http://download.oracle.com/javase/6/docs/api/java/awt/image/ColorModel.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542539",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I apply the JavaScript method on my Facebook page? I found this code, and I need to display it on my page:
<script language="javascript" src="http://www.joshuaproject.net/upgotd.php" type="text/javascript"></script>
<!-- alternative for no javascript --><noscript>
<a href="http://www.joshuaproject.net/upgotdfeed.php">View Unreached People of the Day</a></noscript>
What are the steps to follow? Is it possible to do it?
A: That is, AFAIK, not possible due to security reasons. The keyword is cross-site scripting (XSS).
A: The best option would be to use the iFrame example from the link your provided. You can now add iFrames to your Facebook Page ( not individual user profiles ) using this process:
http://developers.facebook.com/blog/post/462/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542541",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: XMLHttpRequest for JSON file works perfectly in Chrome, but not in Firefox I've narrowed my problem area down to the function below. It's part of a userscript I'm writing. It works perfectly in Chrome, but doesn't work at all in Firefox/Greasemonkey. I've tinkered with it all day and have hit a brick wall. The only thing that makes sense is if JSON.parse isn't working right, which would make sense since Chrome is known to handle JSON.parse somewhat differently... but I know the JSON is perfectly formed!
function getTagline() {
var jsonfile = new XMLHttpRequest();
jsonfile.open("GET", "http://example.com/somegood.json", true);
jsonfile.onreadystatechange = function() {
if (jsonfile.readyState == 4) {
if (jsonfile.status == 200) {
var taglines = JSON.parse(jsonfile.responseText);
var choose = Math.floor(Math.random() * taglines.length);
var tagline = document.createTextNode(taglines[choose].metais);
insertTagline(tagline);
}
}
};
jsonfile.send(null);
}
Any ideas?
A: I was told that JSON is not supported without an extra library, see here the accepted answer. I also tried this
try {
clientList = JSON.parse(responseText);
} catch (e) {
alert(e.message);
}
And the message I get is "JSON is undefined". So the answer seems correct.
A: After some more troubleshooting, it turns out the was a cross-domain XHR issue. It was working in Chrome because, by default, Chrome was allowing the script on all domains. I tweaked the headers so Chrome knew to only allow the proper domains, but Firefox disallows cross-domain on XHR regardless. This was fixed by simply switching to GM_xmlhttpRequest instead, which allows cross-domain in Firefox and, thankfully, which Chrome also supports.
Thanks for the help, folks!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542542",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: use git's word-diff for latex files I would like to have git diff outputs me regular diffs for all files, except *.tex. For *.tex files, I would like to see the output of git diff --word-diff.
I was playing around with .gitattributes and .gitconfig, but the furthest I got was to get a partial display for one .tex file, followed by a crash.
Is it possible to get this behaviour?
My .gitattributes:
*.tex diff=latex
.gitconfig:
[diff "latex"]
wordRegex = "\\\\[a-zA-Z]+|[{}]|\\\\.|[^\\{}[:space:]]+"
command = ~/bin/word-diff.sh
and word-diff.sh:
#!/bin/sh
git --no-pager diff --color-words "$2" "$5"
A: Can you post (or link to) a complete example? I've set up exactly what you've described and it seems to work fine. That is, the diff output highlights words rather than lines, and all of the changes I made were included (that is, it didn't crap out early or anything). The only anomaly was that diff would always exit with:
external diff died, stopping at foo.tex.
This happens because git diff, when run in the manner in which you're using it, behaves like the standalone diff tool: it exits with a nonzero exit code if the files differ. Git doesn't expect this behavior; it assumes that your custom command will always execute successfully and that error exit codes indicate an actual problem.
Git already knows that the files are difference and does not require the external command to make this determination. The external command is strictly a formatting tool.
If you modify your diff-words.sh script to always exit successfully, things should work out better:
#!/bin/sh
git --no-pager diff --color-words "$2" "$5"
exit 0
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542543",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: How can I collect signatures from site visitors? How would I go about collecting a signature from a site visitor?
I am building my site in PHP and would like to give the user the ability to add their signature to a form. They can use their mouse to draw the signature. The signature would be compressed and added to the rest of the form data using the GD library (if possible).
I am open to using Flash, jQuery, or PHP, but I’m not sure where to start.
A: Please have a look at Capture Signature using HTML5 and iPad. The solution proposed by heycam (with a demo) uses SVG to capture the signature. This svg path is ASCII so it's very easy to manipulate and store without losing precision or quality.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542544",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: When to split an MVC view into two? I discussed best practices in MVC the other day with a colleague and he asked me how to best separate views. He was maintaining an MVC solution which had a common input form with a controller with two actions, a get action, and a post action. Both actions were returning the same view, which was filled with inline logic, and conditionals checking whether it was a post or a get.
What is the best solution for this situation?
Should the view be split into two separate views? I guess it depends on how much logic is in there, but when is too much? Is there a way to quantify when you can motivate the refactoring into two views?
A: I would definitely separate something like that into two separate views and then use partial views for the parts that are in common between them.
Composition, without inheritance and without conditional logic, is nearly always the cleaner, clearer, more maintainable way to go when it comes to planning Views.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542546",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: MySQL: create function that returns an array CREATE Function getNearIds (myLocationLon double, myLocationLat double) RETURNS WHAT
I just want to return an array of integers, after a long search: some say use Group_concat to make the list as a comma separated list then use find_in_set when calling the function. this works ok but in HQL (Hibernate query language) it doesn't.
so I need a clear way for this function to return an array of integers, what if i want to return a list of items from items table, is this possible.
I think this is very simple to do in Oracle DB or even SQL server. why is it very tough in MySQL.
please help.
A: Why not just use a stored procedure instead? You could simply have it return a result set that had rows with just one column.
Stored functions can't do what you want to do - well, I suppose you could do that group concat thing but why bother? Create the stored procedure and have it return the ints you want.
Something like:
CREATE PROCEDURE getNearIds
(myLocationLon double, myLocationLat double)
BEGIN
# whatever your logic is to get the ids...
# e.g.,
select id from locations where [whatever "near" means]
END
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542547",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do I use SetArrayRegion to map an array from a C struct to Java class array? I want to access data members of a C struct(below) and map them onto an array in my java class. I have tried to used Set<>ArrayRegion to map the values but I am going wrong somewhere. Below is an example of what I am trying to do. Can somebody please help me with the correct syntax to map the values?
c header
`
typedef struct a {
long nls;
uint8_t *lane;
long t;
} aa;
typedef struct b {
uint32_t id;
uint64_t timestamp_ms;
long num_states;
aa *move_states;
} bb;
java class
class J {
int i_id;
long timestamp_ms;
long num_states;
long[] nls;
long[][] lane;
long[] t;
}
test.c
JNIEXPORT jint JNICALL Java_com_android_...
(JNIEnv *env, jclass c, jobject obj)
{
bb c_struct;
// do some operations on c_struct to populate the structure
....
J java_class;
jFieldID fid;
jclass cls = (*env)->GetObjectClass(env,obj);
fid=(*env)->GetFieldID(env,cls,"i_id","I");
(*env)->SetIntField(env,obj,fid,c_struct.id);
... similar for timestamp_ms,num_states
// how do I map c_struct->move_states[i].nls to java_class.nls[i] ??
// also how do I map c_struct->move_states[i].lane[j] to java_class.lane[i][j]??
}`
A: Maybe you need to allocate the array to start with.
This means creating the array object with enough length NewLongArray(), using SetLongArrayRegion() to fill the array object, then using SetObjectField() to set the new array instance into java object (disarding the old one).
You can test this theory out quickly by ensuring in Java you allocate a big enough array before calling your JNI to fill it.
int SIZE = 1000; // make this big enough
J j = new J();
j.nls = new long[SIZE];
j.lane = new long[SIZE][SIZE]; // something like this multi-dimention array
j.t = new long[SIZE];
int i = callMyJniMethod(j);
Now try your GetField, SetLongArrayRegion ideas. Making sure that num_states is < 1000.
Once you have proven this to start working, you can work on how exactly you want your API to work. Ideas on this:
*
*Keep your current design, but have JNI allocate the array.
*Create a new Java object "AA" and have JNI instate one for each C++ "aa" and fill it in, and then attach an array of BB (aka J) to the J object. j.aa = new AA[num_states];
FWIW you are trying to copy the data between C++/Java (not map, as use of term map implies some kind of sharing, updating one will not update the other unless you re-copy)
FWIW "long" in C/C++ maybe 32bit on your platform, but "long" on Java is always 64bit.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542550",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Saving int/byte/string data types in Android Sorry, this might be quite a lengthy question, but how do i actually save int/byte/string data types in Android?
I do know that to save a String into the internal memory (note, not external or anything else), i have to do something like this:
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
to save the file, and:
int saveTest = fos.read();
fos.close();
to read the file from another activity or something. (Is this correct?)
But what if i want to save and read the file as an int/byte data file? Is this possible? And how would i be able to do it?
A: To save your objects you can use the ObjectOutput class to serialize them, e.g.:
// Example object which implements Serializable
Example example = new Example();
// Save an object
ObjectOutput out = new ObjectOutputStream(new FileOutputStream(new File(getCacheDir(),"")+"cacheFile.srl"));
out.writeObject( new Integer( YOUR_INT ) );
out.close();
// Load in an object
ObjectInputStream in = new ObjectInputStream(new FileInputStream(new File(new File(getCacheDir(),"")+"cacheFile.srl")));
Integer example_loaded = (Integer) in.readObject();
in.close();
Where the class Example could be any object that implements serializable or byte data, the javadocs may also help!
Hope this helps!
A: If you want to read objects, then you would create an ObjectInputStream from the FileInputStream you got. If you want to read the file as binary, then you can use the read member function that works with a byte[].
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542557",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Disadvantages of using Basic4Android? I am currently researching the pros and cons about Basic4Android. I have a good list of pros (http://www.basic4ppc.com/android/why.html) but what are some disadvantages to using this? What limitations does this tool have?
Thank-you for the help!
A: After trying virtual every platform from Basic4Android, thru Eclips, RadStudio Xe2, and Windev Mobile which I had high hopes for, I can say I strongly prefer B4A. The easiest I found by far, and the most useful examples by far. As far as limitations, I have found only a few and those are easily gotten around since you can take any Java code and wrap it in a library that B4A can use quite easily. With that capability, I can go to Eclips if needed and generate code and use it in B4A. I am not a fan of Basic. But I also do not know Java. For me that was not the issue. It was the ease of using the interface without getting lost and most important, a solid example of damn near everything the phone can do.
A: The only disadvantage I see is that not everything from the whole Android Java API is supported. There are some things (like the MapView for example) that are (currently) not usable in B4A. The most important things are available but there are still parts which need some improvement (like the homescreen widgets).
If you want to get good results very quickly and don't need to use every exotic Android feature, give it a try.
If you want access to every feature that is available in Android there is only the way to choose the Eclipse IDE and directly use Java. But you have to invest much more time for developing than you have to do with B4A.
A: As an accomplished VB.NET programmer for me there were so many traps to just getting started with Eclipse, instructions weren't clear, things just didn't work for the beginner. Two weeks of installing this and that, and still could get Hello World to run.
I have a huge codebase of functions of have written with VB.NET in the last 10 years, and getting those functions ported across, while not trivial, happens quickly. With Basic4Android I ran the 3 installs in their list, and started coding. In minutes I had accomplished more than with weeks with Eclipse.
If you are exerienced in VB, unless you have a buddy that can get you going, you are way ahead with Basic4Android.
A: Personally as a beginner to B4A and programming in general, my main hurdle is there seems to be a steep learning curve in the very beginning (which I'm still trying to ascend). I'm sure this holds true for any language/IDE. I just wish there were more tutorials geared towards users like me. The beginner's guide is great but even in there there are things I don't quite understand. I came from AppInventor in which I made 3 apps within a month. I wish Erel or some of the other users would make Youtube video tutorials!
A: My opinion is if you are familiar with VB, better to go for b4a. It is not wasting of money. May be some limitation compared to Google SDK b4a is improving in every version. Insteading of learning java and do the exercises being a VB programmer I prefer b4a. As Markus stipp states that If Erel try to incorporate mapview that would be great for supporting many applications.
I hope Erel will do it shortly :)
A: b4a uses a very "keep it simple" and easy to use interface
So does not have the incredibly complex .net wysiwyg interface.
There is a learning curve to the designer itself, but its easy to learn.
The other learning curve is learning the "keep it simple" consepts with android designs.
b4a has an abstract designer for control layouts that can also be viewed on a physical device or an emulator.
b4a now includes a wysiwyg visual designer that can be viewed on a physical device or an emulator.
Currently developers use a virtual box emulator that is very fast in comparison to the SDK and ADV Manager.
Using the virtual box emulator we can create emulators for all sized devices. Quickly and easily.
There are all kinds of step-be-step beginners guides and beginners tutorials and control tutorials with simple and advanced sample projects.
And a very active beginner, medium and advanced support developers forum.
Where just about everything you could think of has already been asked, discussed and answered.
Where beginners can feel safe in a supporting environment without the rude burntout bullies you get in other forums.
Where other rediculously overpriced products are still stuggling to come to grips with even the basic Android features, b4a already has the solutions. That are simple and easy to understand.
Have a look around for basic4android coupons to find a rediculously low price on a professional licence. WITHOUT the yearly overpriced upgrade fees.
All I can suggest is not to bring .net C++ OO mehodologies baggage mindset into the future.
And be prepared to enjoy producing real apps in a very short time.
(yeah ok, I didn't want to mention is but b4a now has classes. jeez!)
A: The only real down side I see is (potentially) wasting $49.00 ;)
Frankly, I'd encourage anyone to download the Google SDK and become familiar with Android Studio and the Java API.
But this looks like it might be very easy to get started with, shouldn't incur any runtime performance penalty, and allows you to create unencumbered (fully redistributable) APK's.
So if you prefer Basic over Java, and have a spare $49 - sure, go for it!
IMHO...
A: There are many many pros to using Basic4android. Its a neat package and well supported by the author Erel.
Pros
+ Feature-rich in terms of settings
+ Intellisense editor
+ Many libraries
+ GUI designer
+ Plain and easy to pick up language
+ Debugger
Cons
- lack of support for Object orientation
- No unique global variables within Subs
A: I have used the software and created about three apps for industrial control system monitoring. B4A had it all as far as functionality is concerned. Where it finds its limitations are the graphical editing abilities avalible to the average user. It can be very difficult to have complete control over the graphical properties of a button for example. Once you have created you interface you still dont get to see the final product until you have loaded it into the emulator (or the device), and I think most of us know how slow it can be emulating HC 3.0. I understand that realtime rendering of the form/activity can be very difficult from the software programers point of view, but it will help B4A keep its edge as other programs similiar to B4A begin to pop up.
Despite my critisims above it is well worth the 50$
A: I am a JAVA coder with OCJP.
I have done a university paper with native JAVA Android and have a game app on the playstore from that experience.
Right now I have to code an app for a client.
I am using B4A not native JAVA and eclipse because it is faster & easier
As many have said above the only disadvantage is that it may not have some features.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542560",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Right align 3 div's to the right of the page I'm trying to right align 3 div boxes in the order signin_box - signin_btn - signin_opt. My current code is swapping signin_opt with signin_box. I know I can just swap the placement in the HTML code but I want to learn how to float the correct way.
.container {
border-top: solid #27A7DF 3px;
background-color: #000;
height: 43px;
width: 100%
}
.signin_box {
height: 42px;
width: 275px;
float: right;
background-color: #323232
}
.signin_btn {
height: 42px;
width: 72px;
float: right;
background-color: #000
}
.signin_opt {
height: 42px;
width: 135px;
float: right;
background-color: #323232
}
<div class="container">
<div class="signin_box"></div>
<div class="signin_btn"></div>
<div class="signin_opt"></div>
</div>
A: When you float siblings to the right, the elements first specified in the HTML are pushed farthest right. To keep the elements in the order specified by the HTML, you need to float the container to the right and its children to the left.
A: When using float the order matters. Try using like so:
<div class="container">
<div class="signin_opt"></div>
<div class="signin_btn"></div>
<div class="signin_box"></div>
</div>
A: You probably need to add the clear: right; CSS attribute.
Fiddle: jsFiddle demo
Example:
.signin_box {
height: 42px;
width: 275px;
float: right;
background-color: yellow;
clear: right;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542563",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: UInt64 on a 32 bit system, need to generate from UInt32's or array of bytes, how? To generate UInt64 the following results in "warning C4293: '<<' : shift count negative or too big, undefined behavior"
UInt64 byteArrayToUInt64(int %stI, array<Byte>^ byteArray) {
UInt64 retV = byteArrayToUInt32(stI, byteArray);
retV |= byteArrayToUInt32(stI, byteArray) << 32;
return retV;
}
or
UInt64 byteArrayToUInt64(int %stI, array<Byte>^ byteArray) {
stI += 8;
return byteArray[stI - 8] | byteArray[stI - 7] << 0x08 | byteArray[stI - 6]
<< 0x10 | byteArray[stI - 5] << 0x18 | byteArray[stI - 4] << 0x20 | byteArray[stI - 3]
<< 0x28 | byteArray[stI - 2] << 0x30 | byteArray[stI - 1] << 0x38;
}
Unfortunately, all MS have to say about their UInt64 structure is:
The UInt64 value type represents unsigned integers with values ranging
from 0 to 18,446,744,073,709,551,615.
UInt64 provides methods to compare instances of this type, convert the
value of an instance to its string representation, and convert the
string representation of a number to an instance of this type.
Pretty useless isn't it?
A: Before shifting the value, you need to static_cast it to an UInt64. Otherwise you are shifting a 32 bit value by 32 positions, and that's undefined behavior. Shifting a 64bit value by 32 positions is ok.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542566",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to send parameters to a selector? I know to send a parameter to a selector, we use withObject, but how to handle the following case:
UIBarButtonItem* backButton = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStylePlain target:[[NavigatorUtil new] autorelease] action:@selector(back:) ];
The back method looks like:
#import "NavigationUtil.h"
@implementation NavigationUtil
+(void) back: (UINavigationController*) navigationController
{
[navigationController popViewControllerAnimated:YES];
}
@end
Now I need to send a parameter to this selector? How to?
A: What do you mean "send a parameter to this selector"? This phrase doesn't compute.
It seams to me you should RTFM a little, for example the Event Handling Guide for iOS.
In short, the button's "action" is a message that the button sends to its target. In Objective-C, a message is defined by its selector, which can more or less be seen as the method name and signature.
The button knows about three signatures for this selector: zero, one or two arguments. In your case, you use a method with one argument. You can't decide what it's going to be. This argument is always the same. It's going to be the sender, i.e. the button itself.
So that's problem #1 with your action method.
Problem #2 with your action method is that you defined it as a class method. It should be an instance method.
Now finally, if you want to reach the UINavigationController from the NavigatonUtil, you need to find another way. For example to store it beforehand as an instance variable.
A: When providing selectors as the action, you typically rely on member (iVar) variables.
In your case, store the navigation controller as an iVar and then reference it from your selectors action.
Also, you're setting it up as a code but in case you ever want to bind that method as an action in interface builder, you should make it return IBAction which the compilers resolves to void but it's a hint to interface builder. Notice it shouldn't be a class method either.
- (IBAction) back
{
[[self _navigationController] popViewControllerAnimated:YES];
}
Another option you could look into is blocks which allow for sending methods with parameters or inline providing a block of code which also helps when you want to avoid member state (for example async/concurrent code).
Checkout this SO article:
UIButton block equivalent to addTarget:action:forControlEvents: method?
Hope that helps
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542567",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: recursive stack size? class Program
{
static void Main(string[] args)
{
Test(0);
}
static void Test(int i)
{
if (i > 30000)
{
return;
}
Test(i + 1);
}
}
Why getting recursive function and throwing StackOverflowException when calling this above sample.
(Because over the default recursive stack size ?)
but i wonder how to solve this problem .
Thanks.
A: You're getting an exception because 30,000 stack frames is a rather large number :-)
You solve it by using recursion in a more circumspect manner. The ideal problems to be solved recursively are those which reduce the "search space" quickly (a).
For example, binary tree traversal where your search space is halved each time you recur:
def find (searchkey, node):
if node = NULL:
return NULL
if searchkey = node.key:
return node
if searchkey < node.key:
return find (searchkey, node.left)
return find (searchkey, node.right)
Adding two unsigned integers (and your own algorithm above) are not a good fit for recursion because you'll blow out your stack allocation long before the results are calculated.:
def add (a, b):
if a = 0:
return b
return add (a-1, b+1)
(a) Search space can be defined as your entire set of possible answers. You want to reduce it as quickly as possible.
And , as an aside, the ideal problems for recursion have nothing to do with stack space in a theoretical/mathematical sense, they're just any problem that can be expressed as:
*
*the same or similar problem with a "simpler" argument.
*a terminating condition with the "simplest" argument.
("simple" , in this sense, means approaching the terminating condition).
Theoretical/mathemeatical approaches wouldn't need to take stack space into account but we, as computer scientists, must. Reality sets limits :-)
See also When would I not use recursion? and Situations where you would convert recursion to iteration.
A: The problem is that you are doing too much recursion. Whatever you are doing that would use so many levels of recursion, should be solved using a loop instead.
Algorithms that work will with recursion doesn't use one level of recursion for each item. Typically you would split the work in half for each level, so 30000 items would need only 15 levels of recursion.
A: You are getting a StackOverflowException because your stack overflows somewhere within those 30k calls to Test. There is no way to 'solve' the problem, the stack size is limited (and pretty small as well). You could redesign your code to work in an iterative fashion.
for( int i = 0; i <= 30000; ++i )
{
Test( i );
}
However, I assume that your actual use case is more complicated than that; otherwise there is no gain from recursion.
A: While you could specify the stack size for a new thread manually, I'd use a Stack<T> or a loop (that's really all that's needed for your simplified example) so you don't need recursion at all, i.e.:
Stack<int> stack = new Stack<int>();
stack.Push(1);
while(stack.Count > 0)
{
int someValue = stack.Pop();
//some calculation based on someValue
if(someValue < 30000)
stack.Push(someValue +1);
}
A: Take a look at this question: Way to go from recursion to iteration
If your recursion is going to be 30k+ levels deep... you probably want to turn it into an iterative algorithm. The answers in that question should help.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542570",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to send a 2-D array as a reference in C++, and back? yet another beginner-to-intermediate question. I'm trying to pass a 2-D array to a function in C++. I'm aware that the array can't be sent directly to the function, so I first created a pointer (names edited but you'll get the idea):
double input[a][b] = {{0, 0}, {0, 1}, {1, 0}, {1, 1}};
Class.calculate (*(input), a, b);
Then I try to use it in said function - but seemingly I'm unaware on how to dereference the pointer to be able to handle the 2-D array again. My code (more or less):
for (int x=0; x<=a; x++){
for (int y=0; y<=b; y++){
tmpInput[x][y]= (*input)[x][y];
}
}
The compiler complains about an error, namely invalid types ‘double[int]’ for array subscript, but I still can't figure out the problem. My best bet is that I didn't dereference the 2-D array properly, but the other option is that C++ can't dereference 2-D arrays directly, instead relying in converting the array to 1-D before sending it. Any ideas?
A: Why the array cannot be sent directly to a function?
Call Class.calculate (*(input), a, b); is trying to dereference input which you can't do as it is not a pointer.
If the calculate is defined as:
Class::calculate(double *input[], size a, size b)
You can just call Class.calculate(input, a, b).
A:
I'm aware that the array can't be sent directly to the function, so I first created a pointer (names edited but you'll get the idea)
Wrong. You can pass it. Just have the calculate member function's first argument to be pointer to a pointer.
calculate( double **ptr, int rows, int columns ){
// Now access the array via ptr as usual with the [] operator.
// like ptr[0][1]
}
And call it like - Class.calculate (input, a, b);
A: No one said anything about templates yet? I'm disappointed!
You can actually pass it as a real reference without the need to pass the size as extra parameters in C++:
class Class{
public:
// ...
template<unsigned N, unsigned M>
void calculate(double (&arr)[N][M]){
// use it like normal, arr[x][y]
// ...
}
// ...
};
Example on Ideone.
Even though this doesn't answer the exact question you asked, it's always good to know such stuff. :) Templates are an important part of C++ after all, no matter if you're beginner, intermediate or a pro. You use them, though maybe not knowingly, from day 1.
A: Use Boost.MultiArray:
http://www.boost.org/doc/libs/1_47_0/libs/multi_array/doc/user.html
they support views, ranges, iterators and they abstract away memory management but still remain extremely configurable. You can pass multi_arrays by reference just like you'd expect.
if you want to learn about raw pointers (or you're writing an embedded application that needs to fit in 64k of memory or something), then it's a good idea write code that uses them. If you want to write maintainable production code, then it's a good idea to use STL/Boost and avoid raw pointers except in code that is unlikely to have to be read very much.
A: It's hard to say for sure without seeing the declaration of calculate(), but I'd guess it's an argument type mismatch. You can send your array as a double*, but not as a double** - it is an array of doubles (they're laid out linearly in memory, even if the compiler lets you treat them as a multidimensional array). But it is not an array of pointers to doubles, which is what the double** type actually means: Dereference a double** and you get a double*.
If you know that the second subscript is constant (in your case, 2), you can define calculate() to expect a N*2 array of doubles:
void calculate(double array[][2], int a)
{
//Whatever
}
Or, if both dimensions can change, just take a straight double* and to the pointer math yourself (you'll probably have to cast your array to a double* when calling this, but it'll work):
void calculate(double* array, int a, int b)
{
//To get array[i][j]:
array[i * b + j];
}
Hope this helps!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542572",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rails/ActiveRecord has_many question I am using Ruby 1.8.7 and Rails 2.3.5
So I am trying to figure out why my has_many association doesn't work properly. I have 2 tables in the database, Videos and Comments. Inside the Comments table I have a foreign key of video_id column and when posting a comment nothing shows up on my video's page because the video_id column is NULL so nothing got posted.. If I add the id of the video in the video_id column, you can view the comment. Am I missing something?
Video.rb
class Video < ActiveRecord::Base
has_many :comments
end
Comment.rb
class Comment < ActiveRecord::Base
belongs_to :video
end
comments_controller.rb
def create
@comment = Comment.new(params[:comment])
@comment.video_id = params[:video_id]
if @comment.save
flash[:notice] = 'Your comment was saved!'
else
flash[:notice] = 'Sorry, there was a problem.'
end
redirect_to videos_path
end
_form.html.erb
<% form_for :comment, :url => comments_path(@video) do |f| %>
<p>
<%= f.label :name, "Your Name" %>
<%= f.text_field :name %>
</p>
<p>
<%= f.label :body, "Your Comment" %>
<%= f.text_field :body %>
</p>
<p>
<%= f.submit "Submit", :disable_with => 'Submiting...' %>
</p>
<% end -%>
Routes.rb
ActionController::Routing::Routes.draw do |map|
map.index '/', :controller => 'homepage', :action => 'index'
map.logout '/logout', :controller => 'sessions', :action => 'destroy'
map.signout '/signout', :controller => 'sessions', :action => 'destroy'
map.login '/login', :controller => 'sessions', :action => 'new'
map.signin '/signin', :controller => 'sessions', :action => 'new'
map.register '/register', :controller => 'users', :action => 'create'
map.signup '/signup', :controller => 'users', :action => 'new'
map.activate '/activate/:activation_code', :controller => 'users', :action => 'activate', :activation_code => nil
map.resources :users
map.resource :session
map.resources :comments
map.resources :videos
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
end
A: You could use a nested resource (I think they are there in 2.3.5, not sure).
Or else you could modify your partial to pass the video_id parameter:
_form.html.erb
<% form_for :comment, :url => comments_path(@video) do |f| %>
<%= hidden_field_tag 'video_id', @video.id %>
<p>
<%= f.label :name, "Your Name" %>
<%= f.text_field :name %>
</p>
<p>
<%= f.label :body, "Your Comment" %>
<%= f.text_field :body %>
</p>
<p>
<%= f.submit "Submit", :disable_with => 'Submiting...' %>
</p>
<% end -%>
A: You're not specifying params[:video_id] correctly.
From what I can tell you want to allow users to comment on videos?
If so, I believe the real routing structure you want is:
resources :videos do
resources :comments
end
This will make a path like video_comments_path(@video) which you can POST to and in the create action do something like:
@video = Video.find(params[:video_id])
@comment = @video.comments.create(params[:comment])
Thats basically it
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542576",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Display results after form has been submitted When I submit a form with PHP that updates a column in my database, it doesn't display the updated data until after the page has been refreshed.
For example, say I want to delete the word watermelon from the following list:
apple, banana, watermelon, peach
I would have a submit button with a select form, where you select which word you want to delete (watermelon), and then press submit to delete it. The code will run a query to delete the word watermelon from the list, but when the page reloads, it is still there. You have to refresh the page to view the actual updated results.
Here is the code I'm using for my HTML form
<form action = '' method = 'POST'></form>
A: Place your database modifications before your output display in the PHP file. e,g,
show_fruits.php
<?php
// validate $_REQUEST
// call database function
?>
<html>
....
<?php /* now query for list of items after DB call above was made */ ?>
A: I think you should declare the action - in your case that should be the name of the php file you want your form to redirect.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542577",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PDO security and html special chars? Does PDO by default use html special chars? Or even better can I turn it on or off using php, I cannot find any documentation on whether this is possible or not?
Just to clarify, if using prepared statements I am nearly invincible to injection?
A:
Does PDO by default use html special chars?
No; PDO is a database library, and hence doesn't care about HTML. If you're displaying data from your database in a web page, you still need to HTML-escape it for display.
Just to clarify, if using prepared statements I am nearly invincible to injection?
As long as you don't interpolate values directly into your queries, then yes -- you are not vulnerable to SQL injection.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542579",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: new FormData() "application/x-www-form-urlencoded" Couchdb only parse application/x-www-form-urlencoded. Is there a FormData() attribute that set the enctype?
xhr.open('put',document.myForm.action,false)
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
xhr.send(new FormData(document.myForm))
A: No, the XHR2 "send" method is specified to always send FormData objects as multipart/form-data.
As ampersand suggests, one option would be to use the jquery.couch.js plugin that's built into every CouchDB instance within Futon.
If you like a bit more generic HTTP interface, Fermata also has support for URL encoded requests:
fermata.json(document.myForm.action).put({'Content-Type':"application/x-www-form-urlencoded"}, {...form fields...});
Another option would be to send JSON to your update function (which I'm assuming is the 'action' URL of your form) instead.
Of course, the trick with any of these is that you'll have to extract the form fields yourself, since there's no easy DOM-level equivalent of new FormData(document.myForm) that returns an Object instead AFAIK.
A: FormData will always be sent as multipart/form-data.
If you just post normal form data without uploading files, multipart/form-data is better.
If you want to upload files, multipart/form-data is better.
If you have to upload files with x-www-form-urlencoded, you should convert the files data to string data via base64 etc, and write special server-end code. This is strongly not recommended.
If you want to send FormData as x-www-form-urlencoded, there are 2 ways at least.
1. Send URLSearchParams directly:
// use xhr API
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
xhr.send(new URLSearchParams(formDataObj));
// or use fetch API
fetch(url, {
method: 'post',
body: new URLSearchParams(formDataObj)
});
2. Encode the content items to querystring.
function urlencodeFormData(fd){
var s = '';
function encode(s){ return encodeURIComponent(s).replace(/%20/g,'+'); }
for(var pair of fd.entries()){
if(typeof pair[1]=='string'){
s += (s?'&':'') + encode(pair[0])+'='+encode(pair[1]);
}
}
return s;
}
var form = document.myForm;
xhr.open('POST', form.action, false);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
xhr.send(urlencodeFormData(new FormData(form)));
you can also use URLSearchParams like this:
function urlencodeFormData(fd){
var params = new URLSearchParams(fd);
return params.toString();
}
For old browsers which doesn't support URLSearchParams API, you can use one of polyfills:
*
*ethanius / URLSearchParams
*WebReflection / url-search-params
A: Here's a simpler way to do it that doesn't rely on writing your own conversions:
const form = document.getElementById('my_form')
fetch(form.action,
{ body: new URLSearchParams(new FormData(form)) })
It uses the fact that the URLSearchParams constructor can accept a FormData object (anything that will iterate pairs of values, I think) and that fetch knows to convert URLSearchParams into a string and set the Content-Type header correctly.
A: Some time ago I wrote the following function. It collects form values and encodes them url encoded, so they can be sent with content type application/x-www-form-urlencoded:
function getURLencodedForm(form)
{
var urlEncode = function(data, rfc3986)
{
if (typeof rfc3986 === 'undefined') {
rfc3986 = true;
}
// Encode value
data = encodeURIComponent(data);
data = data.replace(/%20/g, '+');
// RFC 3986 compatibility
if (rfc3986)
{
data = data.replace(/[!'()*]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16);
});
}
return data;
};
if (typeof form === 'string') {
form = document.getElementById(form);
}
var url = [];
for (var i=0; i < form.elements.length; ++i)
{
if (form.elements[i].name != '')
{
url.push(urlEncode(form.elements[i].name) + '=' + urlEncode(form.elements[i].value));
}
}
return url.join('&');
}
// Example (you can test & execute this here on this page on stackoverflow)
var url = getURLencodedForm('post-form');
alert(url);
A: Further building upon the response by @cmc and combining snippets from FormData API and Codemag's Fetch API tutorial, I use the following for a POST request that requires the Content-Type to be application/x-www-form-urlencoded:
const form = document.forms.namedItem("my_form");
form.addEventListener("submit", (event) => {
event.preventDefault();
fetch(form.action, {
method: "POST",
body: new URLSearchParams(new FormData(form)),
})
.then((response) => {
if (response.ok) {
return response.json();
} else {
return response.text();
}
})
.then((data) => displayMessage(JSON.stringify(data)))
.catch((error) => {
console.error("Error: ", error);
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542586",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: Export user controls in vb 2010 to a text file Is it possible to export the user controls properties from my VB project to a text file or to excel. I have tried google ,but today google isn't my friend. I am using VB 2010 express
thanks
A: I think you are looking for something like this:
Const path = "C:\Test.txt"
Dim query = From assembly In My.Application.Info.LoadedAssemblies
From type In assembly.GetTypes
Where type.IsSubclassOf(GetType(UserControl))
From prop In type.GetProperties
Select PropInfo = String.Format("{0}{3}{1}{3}{2}",
assembly.GetName().Name,
type.Name,
prop.Name,
vbTab)
If query.Any Then
IO.File.WriteAllLines(path, query)
End If
Modify the LINQ query to your exact requirement. For example if you only want public properties with set-accessor that is writable:
Where prop.CanWrite AndAlso Not prop.GetSetMethod Is Nothing AndAlso prop.GetSetMethod.IsPublic
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542607",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Implementing Undo & Redo in the controller/view I'm using paper_trail to implement versioning in my Rails app. I've run into a bit of a head scratcher when tying the back end into my front end.
Since I allow users to update record (create new versions) via AJAX, the "undo"/"redo" functionality has to be tied to the state of the current page (somehow), rather than calculated in the controller.
One idea I had was to return the latest version number with every AJAX request, and then update my "undo" link with this version number.
Has anyone else grappled with this? What's the best way to do it?
A: I don't see anything wrong with the way you answered your own question:
One idea I had was to return the latest version number with every AJAX request, and then update my "undo" link with this version number.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542609",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Non-repeating random number generator? I created a trivia game using visual basic for applications (Excel) that chooses questions by going through a case statement where the cases are numbers. I have the program randomly select a number from 1 to the max amount of questions there are. Using this method, the game repeats questions.
Is there a way to make something that generates numbers randomly (different results every time) and doesn't repeat a number more than once? And after it's gone through all the numbers it needs to execute a certain code. (I'll put in code that ends the game and displays the number of questions they got right and got wrong)
I thought of a few different ways to do this, however I couldn't even begin to think of what the syntax might be.
A: Sounds like you need an Array Shuffler!
Check out the below link -
http://www.cpearson.com/excel/ShuffleArray.aspx
Function ShuffleArray(InArray() As Variant) As Variant()
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' ShuffleArray
' This function returns the values of InArray in random order. The original
' InArray is not modified.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim N As Long
Dim Temp As Variant
Dim J As Long
Dim Arr() As Variant
Randomize
L = UBound(InArray) - LBound(InArray) + 1
ReDim Arr(LBound(InArray) To UBound(InArray))
For N = LBound(InArray) To UBound(InArray)
Arr(N) = InArray(N)
Next N
For N = LBound(InArray) To UBound(InArray)
J = CLng(((UBound(InArray) - N) * Rnd) + N)
Temp = InArray(N)
InArray(N) = InArray(J)
InArray(J) = Temp
Next N
ShuffleArray = Arr
End Function
Sub ShuffleArrayInPlace(InArray() As Variant)
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' ShuffleArrayInPlace
' This shuffles InArray to random order, randomized in place.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim N As Long
Dim Temp As Variant
Dim J As Long
Randomize
For N = LBound(InArray) To UBound(InArray)
J = CLng(((UBound(InArray) - N) * Rnd) + N)
If N <> J Then
Temp = InArray(N)
InArray(N) = InArray(J)
InArray(J) = Temp
End If
Next N
End Sub
A: Here's yet another take. It generates an array of unique, random longs.
In this example, I use 1 to 100. It does this by using the collection object. Then you can just do a normal loop through each array element in qArray without the need to randomize more than once.
Sub test()
Dim qArray() As Long
ReDim qArray(1 To 100)
qArray() = RandomQuestionArray
'loop through your questions
End Sub
Function RandomQuestionArray()
Dim i As Long, n As Long
Dim numArray(1 To 100) As Long
Dim numCollection As New Collection
With numCollection
For i = 1 To 100
.Add i
Next
For i = 1 To 100
n = Rnd * (.Count - 1) + 1
numArray(i) = numCollection(n)
.Remove n
Next
End With
RandomQuestionArray = numArray()
End Function
A: I see you have an answer, I was working on this but lost my internet connection. Anyway here is another method.
'// Builds a question bank (make it a hidden sheet)
Sub ResetQuestions()
Const lTotalQuestions As Long = 300 '// Total number of questions.
With Range("A1")
.Value = 1
.AutoFill Destination:=Range("A1").Resize(lTotalQuestions), Type:=xlFillSeries
End With
End Sub
'// Gets a random question number and removes it from the bank
Function GetQuestionNumber()
Dim lCount As Long
lCount = Cells(Rows.Count, 1).End(xlUp).Row
GetQuestionNumber = Cells(Int(lCount * Rnd + 1), 1).Value
Cells(lRandom, 1).Delete
End Function
Sub Test()
Msgbox (GetQuestionNumber)
End Sub
A: For whatever it's worth here is my stab at this question. This one uses a boolean function instead of numerical arrays. It's very simple yet very fast. The advantage of it, which I'm not saying is perfect, is an effective solution for numbers in a long range because you only ever check the numbers you have already picked and saved and don't need a potentially large array to hold the values you have rejected so it won't cause memory problems because of the size of the array.
Sub UniqueRandomGenerator()
Dim N As Long, MaxNum As Long, MinNum As Long, Rand As Long, i As Long
MinNum = 1 'Put the input of minimum number here
MaxNum = 100 'Put the input of maximum number here
N = MaxNum - MinNum + 1
ReDim Unique(1 To N, 1 To 1)
For i = 1 To N
Randomize 'I put this inside the loop to make sure of generating "good" random numbers
Do
Rand = Int(MinNum + N * Rnd)
If IsUnique(Rand, Unique) Then Unique(i, 1) = Rand: Exit Do
Loop
Next
Sheet1.[A1].Resize(N) = Unique
End Sub
Function IsUnique(Num As Long, Data As Variant) As Boolean
Dim iFind As Long
On Error GoTo Unique
iFind = Application.WorksheetFunction.Match(Num, Data, 0)
If iFind > 0 Then IsUnique = False: Exit Function
Unique:
IsUnique = True
End Function
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542617",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Why doesnt this give me a border on each side of green? I have this page which has this this CSS
body {
background-image: url("images/BACKGROUND5.jpg");
background-repeat: no-repeat;
}
and two divs
#borderleft {
background: none repeat-y scroll 0 0 #93A87D;
clear: left;
float: left;
margin-left: -10px;
margin-top: 610px;
visibility: visible;
width: 70px;
z-index: 2;
}
#borderright {
background: none repeat-y scroll 0 0 #93A87D;
clear: right;
float: right;
margin-left: -10px;
margin-top: 610px;
position: relative;
visibility: visible;
width: 70px;
z-index: 2;
}
here is the HTML
<body>
<div id="borderleft"></div>
<div id="borderright"></div>
any ideas on how to make image in the center and the green background: none repeat-y scroll 0 0 #93A87D; on the outsides
A: One good way to do this kind of layout, when the width of both border columns is fixed, is this.
The elements are:
*
*A container <div> with position: relative
*The border <div>s with position: absolute, fixed widths, and left: 0/right:0 respectively
*A "content" <div> with margin-left and margin-right equal to the width of the border <div>s.
In the example I linked above there's no container div (the <body> element plays that role), but you will need one if you want to be able to move this arrangement around on the page as a whole.
A: Part of solution is to have your body style like this:
body {
background-image: url("images/BACKGROUND5.jpg");
background-repeat: no-repeat;
background-position: center;
}
And, instead of having
margin-top: 610px;
in left and right divs, try replace that with
height: 610px;
A: Using the image as you posted, I'd suggest something like this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542618",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: UIScrollView changes content offset on presentModalViewController A UIScrollView in my view hierarchy is acting funky whenever I present a modal view controller above it. It automatically adjusts the content offset and moves my content down about 40 pixels. I can't seem to figure out how to stop this.
After snooping around I've found that the presentModalViewController somehow triggers the private method _adjustContentOffsetIfNecessary on my UIScrollView and this is what is changing the offset.
Any idea if this is a bug on Apple's part? Or is something getting set screwy in my UIScrollView? Anyway to disable this _adjustContentOffsetIfNecessary method or at least this side effect?
A: Although it is not fancy, I solved this resetting the content offset in the viewDidAppear of the presentingViewController.
A: Try setting the property automaticallyAdjustsScrollViewInsets of your ViewController, that contains the UIScrollView, to "NO"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542624",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: iOS: Tapping on Facebook app login does not bring up allow/don't allow options for my app Problem:
I run the sample iOS SDK code for facebook connect. When Facebook app is not installed, the sample app authenticates through Safari just fine and the sample app is able to post successfully.
When native Facebook app is installed, the sample app causes the Facebook app to be launched for authentication which shows a page that is requesting login for the demo app. When I press the login, it brings up another window that has the allow/"don't allow" options. So far so good. The problem is that if I logout from within the sample app (i.e., [_facebook logout:self]) and try to login again, pressing the "login" button in the Facebook app does nothing (it's supposed to take you to the allow/"do not allow" page).
I have specified the App-ID in the sample app and I have included the fb[app-id] (e.g., fb1234) in the plist under 'URL Types' (otherwise, the Safari authentication would not have worked either).
Any help is appreciated.
A: It does not take you again to the "allow/don't allow" page because the user already gave permission to the app. The only way the page can show again is when the user revoke the access from the Facebook admin panel. I'm not sure if there's a part of the API that can actually revoke the access of the app from the iOS SDK.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542627",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I parse a string representing a sequence of arithmetic operations? I am working on a personal project and I want to take in userinput that looks like this :
1.0+2.5+3--4
and format it to something like this :
1.0 + 2.5 + 3 - -4
so far I am using the .replace("+") to .replace(" + ") and doing that for all of the operands but the problem is it makes the user input into this:
1.0 + 2.5 + 3 - - 4
Is there a way that I can make it with the negative signs. I want to do this so I could parse the numbers into doubles and add and subtract them later on.
my code for it :
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringMan {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String check = "-a1 +a2 + a3 +-a5";
check = check.replace("--", "+");
System.out.println(check);
Pattern pattern = Pattern.compile("\\s+");
Matcher matcher = pattern.matcher(check);
boolean expr = matcher.find();
String str = matcher.replaceAll(" ");
System.out.println(str);
}
}
output is:
-a1 +a2 - a3 +-a5
-a1 +a2 - a3 +-a5
the problem is I want the output to look like this:
-a1 + a2 - a3 + -a5
A: In this specific case, you can handle -- by just replacing them with +:
*
*Take input as a string from the user
*Remove all white space
*Replace all -- with +
*Continue parsing as desired
A: Start by replacing -- with +, which is mathematically equivalent. Or start by replacing -- with - -, which would keep - and 4 together.
A: I would recommend using regular expressions and their "group" functionality. I would actually remove all whitespace to make things easier, take it out of the equation, one less thing to deal with. And obviously I would recommend simplifying the string, replacing "--" with "+", "*+" with "*" and so on.
now you can use a regex on your cleaned up string.
Pattern firstPat = Pattern.compile("(((\\+|-)?)\\d+(.\\d+)?)");//for matching the first number, leading sign is optional
Pattern remainingPat = Pattern.compile("(\\+|-)(\\d+(.\\d+)?)");//for remaining numbers, leading sign is mandatory.
Pattern remainingPatWithExtOps = Pattern.compile("(\\*|/|\\+|-)(-?\\d+(.\\d+)?)");//for remaining numbers, accommodating multiply and divide with negative signs(positive signs should have been cleaned out)
Matcher match = firstPat.matcher(inputString);
now you can iterate through the string using the match.find() method. and then use match.group(1) to get the sign/operation, and use match.group(2) to get the number...
So...
Double firstnum;
boolean firstNumSigned = false;
if(match.find())
{
firstNum = Double.parse(match.group(0));// Parsing handles possible sign in string.
//obv check for exceptions during this and double check group num
String tmp = match.group(1);
firstNumSigned = tmp.equals("+") || tmp.equals("-");
}
else
{//no match means the input was probably invalid....
throw new IllegalArgumentException("What the heck were you thinking inputting that?!");
}
match = remainingPat.matcher(inputString);//use our other pattern for remaining numbers
if(firstNumSigned)
{
match.find();//a signed first number will cause success here, we need to ignore this since we already got the first number
}
Double tmpRemaingingNum;
String operation;
while(match.find())
{
operation = match.group(1);
tmpRemainingNum = Double.parse(match.group(2));
//Do what you want with these values now until match.find() returns false and you are done
}
PS: code is not tested, im fairly confident of the regex, but I'm not 100% sure about the grouping brackets on the first pattern.. might need to experiment
A: Check this ,
Read both strings and integers in between operators like '*,--,-,+"
We can read both integers and characters.
public static void main(String[] args) {
// TODO Auto-generated method stub
final Pattern remainingPatWithExt=Pattern.compile("(\\p{L}\\p{M}*)[\\p{L}\\p{M}0-9^\\-.-?_+-=<>!;]*");
String check = "a1+a2+--a7+ a3 +-a5";
Matcher matcher = remainingPatWithExt.matcher(check);
while( matcher.find())
{
System.out.println(matcher.group());
//use matcher.group(0) or matcher.group(1)
}
}
output
a1
a2
a7
a3
a5
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542628",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I return the address of a node? I want to return the address of a node after I find it.
The node object class is inside a tree class set as private (private is the node inside)
I'll show you a function that's very similar to what I want but with a bool return type.
It returns true if the node exists within the tree or false if it's not there, I only want to return the pointer or address of the node containing the element Im looking for, so I can work with it in the future.
below is the Function. (the "t" im passing is an integer)
template <class T>
class Arbol
{
private:
template <class DNodo>
class Nodo
{
public:
Nodo(const DNodo datoPasado,
Nodo<DNodo> *izqPasado=NULL,//HIJO IZQUIERDO NULL
Nodo<DNodo> *derPasado=NULL)//HIJO DERECHO NULL
: dato(datoPasado),izq(izqPasado),der(derPasado){}
Nodo();
//members
DNodo dato;
Nodo<DNodo> *izq;
Nodo<DNodo> *der;
};
Nodo<T> *raiz;//variable raiz de la clase interna
Nodo<T> *actual;//posicion actual
int contador;//contador
int altura;//altura
////////////////////////////////////////////////
public:
Arbol() : raiz(NULL), actual(NULL){};
//Iniciar(const T &t);
~Arbol();
//INSERTO EN EL ARBOL
void Insertar(const T t);
//BORRO ELEMENTO DEL ARBOL
void Borrar(const T t);
//Busca un elemento del arbol
bool Buscar(const T t);
//Busca y devuelve puntero a elemento
Nodo<T>* BuscarDevolver(const T t);
//EsVacio ????
bool EsVacio();
};
template<class T>
Node<T>* Arbol<T>::BuscarDevolver(const T t)
{
if(!EsVacio())
{
actual = raiz;
while(actual!=NULL)
if(actual->dato == t)
return actual;
else if(t < actual->dato)
{
actual = actual->izq;
}
else if(t > actual->dato)
{
actual = actual->der;
}
}
return NULL;
}
As you may noticed it Im searching for a node in an Binary tree
Thanks in advance for trying to help.
Im getting errors like "Node does not name a type"
A: Node is a nested type within Arbol, so you should actually declare your function like this:
template< class T > Arbol<T>::Node<T>* Arbol<T>::Buscar(const T t);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: PHP print from database without 'while' I need to print one row from a table so a while loop isn't necessary, is there any other method?
A: You need not while.
Just do your while condition outside while 1 time.
i.e
$a=mysql_fetch_row($sql);
//use $a
instead of
while($a=mysql_fetch_row($sql)){
//use $a
}
A: if (($dbResult = mysql_query("SELECT ... FROM ... LIMIT 1")) !== false)
{
$row = mysql_fetch_array($dbResult);
echo $row['Column_Name'];
}
Just fetch one row, no need to always loop a retrieval.
A: $results = mysql_query("SELECT * FROM my_table WHERE user_id = 1234");
$row = mysql_fetch_assoc($results);
echo ($row['user_id']);
A: Do what you would have done inside the condition of your loop, and you'll be fine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542632",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Fetch a large chunk of data with TaskQueue I'd like to fetch a large file from an url, but it always raises a DeadLineExceededError, although I have tried with a TaskQueue and put deadline=600 to fetch.
The problem comes from the fetch, so Backends cannot help here : even if i'd launched a backend with a TaskQueue, i'd had 24h to return, but there 'd be still the limit of 10 min with the fetch, ya ?
Is there a way to fetch from a particular offset of file to an other offset ? So could I split the fetch and after put all parts together ?
Any ideas ?
Actually the file to fetch is not really large : between 15 and 30 MB, but the server is likely overwhelmingly slow and constantly fired ...
A: If the server supports it, you can supply the HTTP Range header to specify a subset of the file that you want to fetch. If the content is being served statically, the server will probably respect range requests; if it's dynamic, it depends on whether the author of the code that generates the response allowed for them.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542651",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to format text in php when we have 2 or more options I'm trying to make a simple script that allow formatting text and submit it.
Here is the form:
<html>
<head>
<title>
</title>
</head>
<body>
<form method="post" action="step2.php">
<input type="text" name="text" /><br>
Red<input type="radio" name="Red" /> <br>
15px<input type="radio" name="15" /> <br>
<input type="submit" name="submit"/>
</form>
</body>
</html>
and in the step2.php at this stage i'm showing results when 2 options are selected. I'm trying to show results when only "Red" is select, when only "15px" is selecet, when both are selected and when nothing is selected.
Here is my script for the moment:
<?php
if (isset($_POST['Red']) && isset($_POST['15']) ) {
echo "<font size='15px' color=red>";
echo $_POST['text'];
echo "</font>";
}
?>
I succeeded
Thanks for answers!
the secret was in empty($varname), here's the code
<?php
if (isset($_POST['Red']) && isset($_POST['15']) ) {
echo "<font size='15px' color=red>";
echo $_POST['text'];
echo "</font>";
}
if (empty($_POST['Red']) && isset($_POST['15']) ) {
echo "<font size='15px'>";
echo $_POST['text'];
echo "</font>";
}
if (isset($_POST['Red']) && empty($_POST['15']) ) {
echo "<font color=red>";
echo $_POST['text'];
echo "</font>";
}
if (empty($_POST['Red']) && empty($_POST['15']) ) {
echo $_POST['text'];
}
?>
A: I think it's better way to do it is some XML/DOM tool
But you can use this code:
$attrs='';
if(isset($_POST['Red']))
$attrs.='color=red';
if(isset($_POST['15']))
$attrs.='size="15px";
Besides, you should know that <font> is deprecated now.
A: Radiobuttons should have the same name, otherwise use checkbox, and also better to use not numeric names for form fields
<html>
<head>
<title>
</title>
</head>
<body>
<form method="post" action="step2.php">
<input type="text" name="text" /><br>
Red<input type="checkbox" name="Red" value="Red" /> <br>
15px<input type="checkbox" name="px15" value="15" /> <br>
<input type="submit" name="submit"/>
</form>
</body>
</html>
step2.php
<?php
if (isset($_POST['Red']) && isset($_POST['px15']) ) {
echo "<font size='15px' color=red>";
echo $_POST['text'];
echo "</font>";
}
?>
A: Here is a solution :) :
<?php
if (isset($_POST['Red']) && isset($_POST['15']) ) {
echo "<font size='15px' color=red>";
echo $_POST['text'];
echo "</font>";
}
if (empty($_POST['Red']) && isset($_POST['15']) ) {
echo "<font size='15px'>";
echo $_POST['text'];
echo "</font>";
}
if (isset($_POST['Red']) && empty($_POST['15']) ) {
echo "<font color=red>";
echo $_POST['text'];
echo "</font>";
}
if (empty($_POST['Red']) && empty($_POST['15']) ) {
echo $_POST['text'];
}
?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542653",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: rails3.1 ActionController::RoutingError (No route matches [GET] "/images/up_arrow.gif"): My stylesheet has:
.asc {
font-size: 2em;
background-image: url(/images/up_arrow.gif);
}
.desc {
background-image: url(/images/down_arrow.gif);
}
The font-size works but the background image (arrow) doesn't.
I get ActionController::RoutingError (No route matches [GET] "/images/up_arrow.gif"):
I tried lots of things in routes but nothing worked.
A: Try this:
.asc { font-size: 2em; background-image: url(/assets/up_arrow.gif); }
.desc { background-image: url(/assets/down_arrow.gif); }
That's how I do it in a 3.1 app I'm working on. Your /images is probably mapped to app/public/images.
A: Finally found that I needed to do the new precompile of assets step.
'I shoulda read the manual'
Compiled assets are put in public/assets directory by default (the destination is defined in config.assets.prefix).
To create compiled versions of your assets use bundle exec rake assets:precompile
If you don't have write access for the production file system, use this task locally and then copy the compiled asset files.
The asset compilation process:
1. Concatenates & compresses all JavaScript files into one master. Uglifier is the default for the process.
2 Compresses (minifies) all CSS files into one master .css file. CSS is compressed by yui by default.
3. Allows for high level languages like coffeescript to use the assets.
Note: It is possible (though not a great idea) to disable the asset pipeline by changing config/application.rb and set
config.assets.enabled = false
You can skip the asset pipeline when creating a new application with the —skip-sprockets option, e.g. rails new appname --skip-sprockets
You can also set config.assets.compile = true This way the assets are only compiled when a request for them is made.
A: Dumb question perhaps, but are you positive that /images/up_arrow.gif exists?
When you 404 on an public asset in it just falls through to the rails router. It's not really a routing problem; you just get a routing error because there are no routes defined for static assets.
A: I had this same issue with Rails 3.2.13.
Solution was to modify the css to this:
.asc { font-size: 2em; background-image: url(up_arrow.gif); }
.desc { background-image: url(down_arrow.gif); }
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542655",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: UIScrollView inifinite scroll without paging first question here, be nice :P
I am trying to make an infinite UIScrollView (i used the "StreetScroller" apple demo project). When the UIScrollView is almost at the end of the contentSize, the contentOffset is set to the center of the contentSize and all the subviews are moved so it is transparent for the user.
It works correctly when you scroll slowly, but when you scroll too fast and that you reach the end of the UIScrollView, things become weird.
In my case i use a UIScrollView with frame.size.width = 320 and contentSize.x = 3 * frame.size.width.
And this is what happen in the logs when you scroll too fast and that you reach the end of the contentSize (so if x > 560 when scrolling to the right) :
--> The UIScrollView is scrolling because of inertia
SetContentOffset called width x : 504.730072
SetContentOffset called width x : 516.878967
SetContentOffset called width x : 528.489990
SetContentOffset called width x : 540.347656
SetContentOffset called width x : 550.754028
SetContentOffset called width x : 561.200378
--> The UIScrollView reach the end of the contentSize so we recenter
The next call of setContentOffset is for recentering the view
SetContentOffset called width x : 320.000000
--> Here is the problem, UIScrollView does not take contentOffset.x changes in account, it continues the animation with the last contentOffset.x value used....
SetContentOffset called width x : 571.421753
The next call of setContentOffset is for recentering the view
SetContentOffset called width x : 320.000000
SetContentOffset called width x : 581.283447
The next call of setContentOffset is for recentering the view
SetContentOffset called width x : 320.000000
SetContentOffset called width x : 610.100952
And this continues until the animation finishes.
If somebody has a solution for setting the contentOffset and forcing UIScrollView to update its animation :)
I read almost all the topic on stackoverflow and other websites about infinite UIScrollView, and i did not see any working solution to change the contentOffset during the animation, and i tried to recenter in all the different UIScrollView delegate methods. And i don't want to change the contentSize during scrolling (it works only when you scroll at right or bot...)
A: I just noticed this issue in the Apple StreetScroller example running in iOS Simulator 4.3.
I saw this question here: Infinite UIScrollView gets strange behavior in iOS4.3 not iOS5 and just tested in the iOS 5 simulator and can confirm that it runs as expected there.
No idea what the issue is with that same code in 4.3.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Apache mod_rewrite doesn't match URL containing percent symbol If the rule:
RewriteRule myurl /newurl
Matches:
http://localhost:8080/test/xxxmyurlyyy
Why doesn't it match this?
http://localhost:8080/test/xxxmyurly%EDyy
EDIT:
I've just discovered utf-8 encoded works just fine. If I rather use %C3%AD than %ED it's ok. I still need to enable unicode.
A: It seems to match just fine. Given this:
RewriteEngine On
RewriteLog /tmp/rewrite.log
RewriteLogLevel 5
RewriteRule myurl /stackexchange/foo.html
If I fetch this:
curl http://localhost/test/xxmyurly%EDyy
I see this in /tmp/rewrite.log:
(3) applying pattern 'myurl' to uri '/test/xxxmyurly?yy'
(2) rewrite '/test/xxxmyurly?yy' -> '/serverfault/foo.html'
And I get exactly what I expect (a document with the content "this is a test").
I suspect your problem is other than you think it is. Enable RewriteLog and
see what shows up, and then post your results here. Also, seeing more of
(ideally, all of) your configuration would help, too.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to use the vst sdk on the .net framework I like making music using mostly my computer and especially love using synthesisers. There is a wide range of synthesiser plugins available online which are quite awesome. I have downloaded the VST (Virtual Studio Technology) SDK which is the platform that most plugins I know of use.
I would like to know if you can use the SDK on the .Net framework to write plugins; the only documentation and tutorials I could find is for C++ and I'm not that trusted with C++. I could learn to use C++, I taught myself C# in a week, but to use an unknown language and to learn other new concepts don't seem like a good combination.
Could anyone just give me pointers in the right direction on how to get started and even if it is possible to program it using .Net?
Regards Charl
A: Many beginners find VST.NET the perfect choice to start off with. It comes with some samples and with VS2008/VS2010 project templates that yield working plugins. So its a great way to start.
VST.NET provides a framework that structures and groups the VST API into manageable pieces. Out of the box it provides support for common functionality such as plugin parameters and programs.
So drop by at the VST.NET codeplex site and we'll help you get started.
BTW: To my knowledge the noise project has been abandoned and although VST.NET might not appear to be very active, I still continue to react on the questions posted on its codeplex site.
A: I second obiwanjacobi's sentiment. VST.Net is about the only .Net VST bridge out there that I know of and the community is great. It's an excellent framework.
https://vstnet.codeplex.com/
As for the statement: "doubt .NET platform would be adequate concerning the raw performance that a VST plugin requires". This is entirely untrue. My tests have shown that on a decent computer, .Net can very easily handle basic synthesis without even raising the CPU level above a few percent. Of course, it's not going to match C++'s performance for very complex synthesis, but in cases like this, there's no reason why you can't fall back on C++ to do the more complex stuff. In fact that is where Vst.Net excels. It would allow you to build very complex synthesis as a VST, and then leverage that in .Net.
At the same time, I think you'd be hard pressed to say definitively that .Net couldn't do very complex synthesis as well. I haven't really tried, but there's no real obstacles when you pay attention to the performance of your code, which would go for any programming platform.
On top of all that, there is now .Net Native to add to the picture. .Net Native has the potential to be AS fast as C++.
A: I remember hearing of noisevst and VST.NET, two C# wrappers for the VST API but I don't know how stable they are. And I really doubt .NET platform would be adequate concerning the raw performance that a VST plugin requires.
So I would recommend learning a little bit of C++. Yes, C++ is so big and complex that nobody on earth knows every feature of it. But for plugin development purposes all you need to do is to implement a couple of methods. You can start from the provided samples in the VST API. Audio DSP code wouldn't look much different if you'd use C#, C++ or any other mainstream language anyway.
If you also want to implement a GUI for your plugin, that's where the things start getting hairy. VSTGUI is simple but lacks many features. I can recommend WDL's iPlug framework but that would require a little more than basic C++.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542659",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Can we post Actions on an object outside of the app (ie FB Page, FB Place)? Is it at all possible to post an action (owned by the app) to an object (NOT owned by the app)? Specifically on Faceook Page and Places, objects owned by FB.
For example I want to create an action called "shop", so that I can create the action
"John drank *Coke*"
in which Coke refers to the FB Page.
I have done a test via the Graph API Explorer and it seems that the app's action POST must refer to an object also owned by the same app. Mind you, I also do not know what shud be syntax to refer to objects owned by FB.
You can tag a place to a post but it will simply prefix it with " -at Walmart"
A: Yes, this is possible. To set the "at Walmart" part, set the action's "place" field when creating an action via a POST. For example, you can pass this:
?place=https://www.facebook.com/pages/Pizzeria-Delfina/53645450697
which should result in setting the place on an action like:
"place": {
"location": {
"city": "San Francisco, CA",
"zip": "94110",
"country": 398,
"region": 0,
"address": "3611 18th Street/2406 California St.",
"id": 2421836
},
"id": "53645450697",
"name": "Pizzeria Delfina"
},
Documentation on the basic action properties is here:
https://developers.intern.facebook.com/docs/beta/opengraph/actions/#create
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542662",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can jQuery Galleria.js load non-image file types, e.g., .html files or other content types such as HTML5 Video? I'm wondering if galleria.js, http://galleria.aino.se, can load HTML pages or just images (.png, .jpg, .gif)?
I tried just plugging in an .html file but it didn't work, was wondering if loading html files into the viewer might be an option i'm not seeing,
A: The short answer: no. Galleria is mainly an image veiwer. But you can load HTML content and place it above the image, as seen here: http://aino.github.com/galleria/demos/layer/one.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7542663",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.