text stringlengths 8 267k | meta dict |
|---|---|
Q: Which way is better? Storing the DOM objects in Array of objects or Direct dom manipulation? The title may not be too clear but let me explain what I mean by "Which way is better? Storing the DOM objects in Array of objects or Direct dom manipulation?".
I have a list of DOM objects for explanation:
<ul>
<li></li>
...
</ul>
The lis are dynamic and they are updated based on certain operations.
Our requirement is, to check if the list already contains an element with the same text as the new one so for example consider a file listing and you rename a node and if the name already exists, remove all the DOM object which contain the same text and generate the latest one (hope that's pretty much clear).
Now, me and one of my colleague is having a discussion and the discussion is as follows,
My colleague says, store the DOM objects in an array of object and then append them to the list and when the supposedly rename operations is performed, loop through that array of object which stores the reference to the DOM element and do the removing and then generating the new node operation because he believes fetching the element from DOM is gonna be more inefficient.
My idea is, do not store the list and consume the memory as the DOM may get updated at any given point of time so each time you wanna remove and add a node fetch the list do the looping and perform the operations because I believe if you store the list you are consuming the memory and once you update the DOM you'll again have to update the array or else it will store the reference to the old DOM object and that's gonna make it more inefficient.
So please help me understand which method/idea do you think is efficient and why?
A: Even if you maintain an array of DOM elements, Javascript is still going to have to search the DOM for the elements when you update them. I think the level of complexity you are adding by creating is completely unnecessary. Assuming the custom array method would be more efficient also pretty much assumes that you are going to be able to make this code more efficient than the browsers developers were able to make the Javascript engine in their respective browsers. Probably not a safe bet.
A: no point of storing data in an array. just use powerful DOM handling framework like jQuery and just work on directly with the DOM.
A: There is no need to maintain an extra array. Most DOM retrieval methods return a NodeList [MDN], which is a live collection of DOM elements, i.e. the collection is always updated when some modification happend.
Thus you can do:
var list_elements = yourlist.getElementsByTagName('li');
and list_elements will always refer to all li descendents of your list.
Update: Of course you can also just keep a reference to yourlist and access the li elements with yourlist.children [MDN].
You can save yourself the extra step and retrieving the elements every time you want to make a modification by keeping a reference to that collection around.
It won't use more memory either (I think) because you just keep a reference to DOM elements (which already exist). When you delete a node, it is removed from the collection automatically, so you don't have to worry about keeping references to "dead" DOM nodes.
A: On rename operation- Loop through the file list for duplicates...if any duplicate is found-prompt the user to choose a different name else go ahead and rename it.
Why would you go for one more array of objects just to loop through when you have the original list unless you want to maintain the original file list array for some other use?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526617",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Invoke call on released COM object I create a COM object used for automation tasks of some application. When this happens application is started and its' main window is displayed.
The problem happens when user closes the main application window. Next Invoke call to the COM object does not work. The problem is that it does not fail and it does not report an error. If I put a debugger breakpoint in next line of code, it is never reached. If I surround the Invoke call with try/catch, no exception is caught. In release build it just crashes.
How is this supposed to work? Since I use CComDispatchDriver as a wrapper around IDispatch* I would expect that my AddRef would keep the COM object alive even if user closed the application. I was hoping of at least getting some HRESULT as an error.
A: What probably happened is that your application called CoUninitialize when exiting. CoUninitialize causes all COM object to be discarded, thus if you ever interact with the COM object after calling CoUninitialize, you'll crash.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526618",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Monodevelop compiler crash I'm trying to get Mono to work on OSX, but i'm getting a strange error when trying to compile.
I get one error The compiler appears to have crashed. Check the build output pad for details.
The ouput is:
Building: DnsResolver (Debug)
Performing main compilation...
Corlib too old for this runtime.
Loaded from: /Applications/MonoDevelop.app/Contents/MacOS/lib/moonlight/2.0/mscorlib.dll
Corlib too old for this runtime.
Loaded from: /Applications/MonoDevelop.app/Contents/MacOS/lib/moonlight/2.0/mscorlib.dll
Build complete -- 1 error, 0 warnings
--------------------- Færdig ---------------------
Build: 1 error, 0 warnings
I simply cannot find a solution to this Corlib problem. I hope someone can help me.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526620",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Using PHP to convert from one date format to another I'm looking to convert a date from one format to another.
This is my current date format:
2011-08-15 15:35:58
and I need to convert it into:
Mon, 15/08/2011 15:35
I can quite easily create this by cutting the last 3 characters from the time and then using str_replace to change '-' into '/' and so on, but I was wondering if there is there is a way to do this automatically using the date() function or something similar. I am also not sure how to generate the day of the week e.g. 'Mon', 'Tues' etc.
Hope someone can help.
Thanks.
A: This can be done easily using a combination of date() and strtotime():
$newDate = date('D, d/m/Y H:i', strtotime($oldDate));
A: Use strtotime and date functions:
$d = strtotime("2011-08-15 15:35:58");
var_dump(date( 'D, d/n/Y H:i',$d));
A: This code work fine:
<?
$time = strtotime("2011-08-15 15:35:58");
echo date("D, d/m/y H:m", $time);
But be carefull, strtotime depends on timezone settings.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526621",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Matplotlib - global legend and title aside subplots I've started with matplot and managed some basic plots, but now I find it hard to discover how to do some stuff I need now :(
My actual question is how to place a global title and global legend on a figure with subplots.
I'm doing 2x3 subplots where I have a lot of different graphs in various colors (about 200). To distinguish (most) of them I wrote something like
def style(i, total):
return dict(color=jet(i/total),
linestyle=["-", "--", "-.", ":"][i%4],
marker=["+", "*", "1", "2", "3", "4", "s"][i%7])
fig=plt.figure()
p0=fig.add_subplot(321)
for i, y in enumerate(data):
p0.plot(x, trans0(y), "-", label=i, **style(i, total))
# and more subplots with other transN functions
(any thoughts on this? :)) Each subplot has the same style function.
Now I'm trying to get a global title for all subplots and also a global legend which explains all styles. Also I need to make the font tiny to fit all 200 styles on there (I don't need completely unique styles, but at least some attempt)
Can someone help me solve this task?
A: In addition to the orbeckst answer one might also want to shift the subplots down. Here's an MWE in OOP style:
import matplotlib.pyplot as plt
fig = plt.figure()
st = fig.suptitle("suptitle", fontsize="x-large")
ax1 = fig.add_subplot(311)
ax1.plot([1,2,3])
ax1.set_title("ax1")
ax2 = fig.add_subplot(312)
ax2.plot([1,2,3])
ax2.set_title("ax2")
ax3 = fig.add_subplot(313)
ax3.plot([1,2,3])
ax3.set_title("ax3")
fig.tight_layout()
# shift subplots down:
st.set_y(0.95)
fig.subplots_adjust(top=0.85)
fig.savefig("test.png")
gives:
A: For legend labels can use something like below. Legendlabels are the plot lines saved. modFreq are where the name of the actual labels corresponding to the plot lines. Then the third parameter is the location of the legend. Lastly, you can pass in any arguments as I've down here but mainly need the first three. Also, you are supposed to if you set the labels correctly in the plot command. To just call legend with the location parameter and it finds the labels in each of the lines. I have had better luck making my own legend as below. Seems to work in all cases where have never seemed to get the other way going properly. If you don't understand let me know:
legendLabels = []
for i in range(modSize):
legendLabels.append(ax.plot(x,hstack((array([0]),actSum[j,semi,i,semi])), color=plotColor[i%8], dashes=dashes[i%4])[0]) #linestyle=dashs[i%4]
legArgs = dict(title='AM Templates (Hz)',bbox_to_anchor=[.4,1.05],borderpad=0.1,labelspacing=0,handlelength=1.8,handletextpad=0.05,frameon=False,ncol=4, columnspacing=0.02) #ncol,numpoints,columnspacing,title,bbox_transform,prop
leg = ax.legend(tuple(legendLabels),tuple(modFreq),'upper center',**legArgs)
leg.get_title().set_fontsize(tick_size)
You can also use the leg to change fontsizes or nearly any parameter of the legend.
Global title as stated in the above comment can be done with adding text per the link provided:
http://matplotlib.sourceforge.net/examples/pylab_examples/newscalarformatter_demo.html
f.text(0.5,0.975,'The new formatter, default settings',horizontalalignment='center',
verticalalignment='top')
A: suptitle seems the way to go, but for what it's worth, the figure has a transFigure property that you can use:
fig=figure(1)
text(0.5, 0.95, 'test', transform=fig.transFigure, horizontalalignment='center')
A: Global title: In newer releases of matplotlib one can use Figure.suptitle() method of Figure:
import matplotlib.pyplot as plt
fig = plt.gcf()
fig.suptitle("Title centered above all subplots", fontsize=14)
Alternatively (based on @Steven C. Howell's comment below (thank you!)), use the matplotlib.pyplot.suptitle() function:
import matplotlib.pyplot as plt
# plot stuff
# ...
plt.suptitle("Title centered above all subplots", fontsize=14)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526625",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "164"
} |
Q: Help with a basic SQL query How do I write an SQL query to find out which employees are from a single location where employee and location are different table.
select count(*) from employee;
The above gives only the count of employees but I need to display their name and location
A: COUNT will obviously give you only the count of the number of employees.
For specific columns such as 'name' and 'location', just do:
SELECT e.name, l.location
FROM employee e
JOIN location l ON e.location_id = l.location_id
(or JOIN on whatever is the common association column between the employee and location table)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526626",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: Grammar To Parse Multiline Comments and String Literals Simultaneously I am trying to parse C++/Java style source files and would like to isolate comments, string literals, and whitespaces as tokens.
For whitespaces and comments, the commonly suggested solution is (using ANTLR grammar):
// WS comments*****************************
WS: (' '|'\n'| '\r'|'\t'|'\f' )+ {$channel=HIDDEN;};
ML_COMMENT: '/*' (options {greedy=false;}: .)* '*/' {$channel=HIDDEN;};
SL_COMMENT: '//' (options {greedy=false;}: .)* '\r'? '\n' {$channel=HIDDEN;};
But, the problem is that my source files also consist of string literals e.g.
printf(" /* something looks like comment and whitespace \n");
printf(" something looks like comment and whitespace */ \n");
The whole thing inside "" should be considered a single token but my ANTLR lexer rules obviously will consider them a ML_COMMENT token:
/* something looks like comment and whitespace \n");
printf(" something looks like comment and whitespace */
But I cannot create another lexer rule to define a token as something inside a pair of " (assuming the \" escape sequence is handled properly), because this would be considered as a string token erroneously:
/* comment...."comment that looks */ /*like a string literal"...more comment */
In short, the 2 pairs /**/ and "" will interfere with one another because each can contain the start of the other as its valid content. So how should we define a lexer grammar to handle both cases?
A:
JavaMan wrote:
I am trying to parse C++/Java style source files and would like to isolate comment, string literal, and whitespace as tokens.
Shouldn't you match char literals as well? Consider:
char c = '"';
The double quote should not be considered as the start of a string literal!
JavaMan wrote:
In short, the 2 pairs /**/ and "" will interfere with one another.
Err, no. If a /* is "seen" first, it would consume all the way to the first */. For input like:
/* comment...."comment that looks like a string literal"...more comment */
this would mean the double quotes are also consumed. The same for string literals: when a double quote is seen first, the /* and/or */ would be consumed until the next (un-escaped) " is encountered.
Or did I misunderstand?
Note that you can drop the options {greedy=false;}: from your grammar before .* or .+ which are by default ungreedy.
Here's a way:
grammar T;
parse
: (t=.
{
if($t.type != OTHER) {
System.out.printf("\%-10s >\%s<\n", tokenNames[$t.type], $t.text);
}
}
)+
EOF
;
ML_COMMENT
: '/*' .* '*/'
;
SL_COMMENT
: '//' ~('\r' | '\n')*
;
STRING
: '"' (STR_ESC | ~('\\' | '"' | '\r' | '\n'))* '"'
;
CHAR
: '\'' (CH_ESC | ~('\\' | '\'' | '\r' | '\n')) '\''
;
SPACE
: (' ' | '\t' | '\r' | '\n')+
;
OTHER
: . // fall-through rule: matches any char if none of the above matched
;
fragment STR_ESC
: '\\' ('\\' | '"' | 't' | 'n' | 'r') // add more: Unicode esapes, ...
;
fragment CH_ESC
: '\\' ('\\' | '\'' | 't' | 'n' | 'r') // add more: Unicode esapes, Octal, ...
;
which can be tested with:
import org.antlr.runtime.*;
public class Main {
public static void main(String[] args) throws Exception {
String source =
"String s = \" foo \\t /* bar */ baz\";\n" +
"char c = '\"'; // comment /* here\n" +
"/* multi \"no string\"\n" +
" line */";
System.out.println(source + "\n-------------------------");
TLexer lexer = new TLexer(new ANTLRStringStream(source));
TParser parser = new TParser(new CommonTokenStream(lexer));
parser.parse();
}
}
If you run the class above, the following is printed to the console:
String s = " foo \t /* bar */ baz";
char c = '"'; // comment /* here
/* multi "no string"
line */
-------------------------
SPACE > <
SPACE > <
SPACE > <
STRING >" foo \t /* bar */ baz"<
SPACE >
<
SPACE > <
SPACE > <
SPACE > <
CHAR >'"'<
SPACE > <
SL_COMMENT >// comment /* here<
SPACE >
<
ML_COMMENT >/* multi "no string"
line */<
A: Basically your problem is: inside a string literal, comments (/* and //) must be ignored, and vice versa. IMO this can only be tackled by sequential reading. when walking through the source file on a character-by-character basis, you might approach this as a state machine with the states Text, BlockComment, LineComment, StringLiteral.
This is a hard problem to try to solve with regex, or even a grammar.
Mind you, any C/C++/C#/Java lexer also needs to handle this exact same problem. I'm quite sure it employs a state machine-like solution. So what I'm suggesting is, if you can, customize your lexer in this way.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Mongoose : Inserting JS object directly into db Ok so I have a JS object that is being POSTed via AJAX to the nodejs backend. I want to insert this js object directly into my mongoose db as the object keys already match up perfectly with the db schema.
I currently have this (not dynamic and overly complex):
app.post('/items/submit/new-item', function(req, res){
var formContents = req.body.formContents,
itemModel = db.model('item'),
newitem = new itemModel();
newitem.item_ID = "";
newitem.item_title = formContents.item_title;
newitem.item_abv = formContents.item_abv;
newitem.item_desc = formContents.item_desc;
newitem.item_est = formContents.item_est;
newitem.item_origin = formContents.item_origin;
newitem.item_rating = formContents.item_rating;
newitem.item_dateAdded = Date.now();
newitem.save(function(err){
if(err){ throw err; }
console.log('saved');
})
res.send('item saved');
});
But want to trim it down to something like this (sexy and dynamic):
app.post('/items/submit/new-item', function(req, res){
var formContents = req.body.formContents,
formContents.save(function(err){
if(err){ throw err; }
console.log('saved');
})
res.send('item saved');
});
A: If you use a plugin like this with mongoose (http://tomblobaum.tumblr.com/post/10551728245/filter-strict-schema-plugin-for-mongoose-js) you can just put together an array in your form, like newitem[item_title] and newitem[item_abv] -- or item[title] and item[abv]
You could also just pass the whole req.body if the elements match up there. That MongooseStrict plugin will filter out any values not explicitly set in your schema, but it still leaves checking types and validation up to mongoose. With proper validation methods set in your schema, you will be safe from any injection attacks.
EDIT: Assuming you have implemented the plugin, you should be able to use this code.
app.post('/items/submit/new-item', function(req, res){
new itemModel(req.body.formContents).save(function (e) {
res.send('item saved');
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526639",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Any ideas why excel interop reads many decimals as -2146826246? I'm absolutely sure that I haven't changed a thing.
For some reason, excel interop has started reading cells with decimals with same mystic value:
-2146826246
I'm absolutely clueless on what to do next, what to look for.
OS: windows7 enterprise edition, MSOffice: 2010 professional plus
Any ideas what this could be?
Recent updates:
A: It is not that unusual. When you convert it to hex, you get 0x800A07FA. Which is an error code. The last 4 digits is the Excel error, producing 2042. Google "Excel error 2042", first hit tells you it means "match not found" or "#N/A".
That's as much as I can reverse-engineer. Start by taking a critical look at the error handling in your code. Don't mess with the install.
A: I am not familiar with Excel Interop but this appears to be related to a limitation of .net's understanding of Excel's various CVErr values.
There is an excellent write up on this at: dealing with cverr values
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526640",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Updating a Page after Binding Data to it in WP7 we have code that is getting data from the server,the data is unzipped and parsed then the name of the files along with the icons related to them are supposed to be displayed on the UI, we are using a listbox and trying bind these 2 elements to the listbox, the data is getting bound but we are not able to update the page after binding.`
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Image Source="{Binding Icon, Mode=OneWay}" Grid.Column="0" HorizontalAlignment="Center" Grid.Row="1"/>
<TextBlock Padding="10" Text="{Binding Widget, Mode=OneWay}" FontSize="20" Grid.Row="2" Grid.RowSpan="2" TextWrapping="Wrap" Grid.ColumnSpan="2" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>`
A: Make sure that:
*
*UIManager class is set as a dataContext for your XAML control.
*UIManager has to implement INotifyPropertyChanged in order to notify the UI that the collection you are binding to has changed (has some items added to it in your case).
*Most important - use Output windows to locate all XAML binding issues.
class UIManager: INotifyPropertyChaged
{
private ObservableCollection<ItemsList> _displayItem;
public ObservableCollection<ItemsList> DisplayItem
{
get
{
return _displayItem;
}
set
{
if(value != _displayItem)
{
_displayItem=value;
NotifyPropertyChanged("DisplayItem");
}
}
public UIManager()
{
DisplayItem = new ObservableCollection<ItemsList>();
DisplayCat(DataManager.getInstance().displayName, DataManager.getInstance().icons);
}
public void DisplayCat(string[] DisplayNames, BitmapImage[] Icon)
{
ObservableCollection<ItemsList> tmpColl = new ObservableCollection<ItemsList>();
for (int i = 0; i < DataManager.getInstance().count; i++)
{
tmpColl.Add(new ItemsList { Widget = DisplayNames[i], Icon = Icon[i] });
}
DisplayItem = tmpColl;
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526650",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Zend Framework or Symfony2 I know this question has been asked several times, but I would like to explain my position and would love if someone who has expertise with both can give me a good answer for that.
I am currently working on 2 big projects, which are dedicated and run on their own debian server. I am very experienced with PHP3+, means I always did the hardcode PHP way since around 10 years now, had my own file structure, libraries etc.
Now for those 2 projects I need to have a) security, b) liabilty and c) an easy implemention (which is for me time saving).
As I understood so far, both are good frameworks. Zend Framework is very modular, so I can basically choose what functions I wanna have, please correct me if I am wrong - and it's more "original"-PHP oriented, which would give a good base to start with.
Symfony - on the other hand - is very community oriented and comes with a lot of stuff. I signed up for the symfony google group and get questions and answers all day. So in terms of getting support, I think symfony would be the choice.
Now: The framework basically is needed for a project with a very secure area for clients, a registration and intelligent functions that correspond with the database. I also need to migrate old data from an existing mysql database. I'd need a couple of self-written php functions, jquery and the paypal api. (both projects are actually heavily payment and calculation oriented)
A: Since you are starting a new project, the only objective argument in favor of Symfony I can give you is that their next-generation (PHP 5.3 oriented) framework is out and stable. Zend Framework 2 on the other hands is still in the works and from what I learned not close to being ready for production. So in that regard Symfony2 could be a better decision for the long term right now.
On the other hand, you might have a bit harder time learning Symfony2 coming from PHP in the old days, as it will not only introduce you to PHP5 OO programming, but also some new concepts of PHP 5.3. You probably should familiarize yourself with PHP5.3 first. Also the new version is still in it's infancy stages, community support is good already, but arguably it doesn't have the same plugin/bundle support yet as you would find for a more established framework.
In the end it will boil down to personal preference though, as I do believe that symfony1, Symfony2 or Zend Framework 1 are all valid choices for a new project on this day.
A: I think it's very much based on personal taste. Both frameworks are perfect for creating professional web applications.
I had to make the same decision about two years ago, and chose for Symfony. Mainly because it's easy to create new projects, and you can create your first prototype really quickly and advance/improve from there on. I tried to do the same with Zend Framework, but to me, ZF is more about "configuration", and that configuration part was not immediately clear to me (but probably that got improved a bunch).
And indeed, I also like the community behind Symfony, there are a lot of great plugins available, and it has well written documentation (at least 1.4).
And it's also possible to use ZF components in Symfony. (For instance the Zend_Search_Lucene).
But again: it's about personal taste. Create a blog in both Symfony and ZF and choose what works best for you. :-)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526652",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to access one of multiple traits of superclass? I have a trait which is implemented from some other traits. Each of these traits override the behavior of the supertrait and are mixed-in to a class:
trait T {
def name = "t"
}
trait T1 extends T {
abstract override def name = "t1"
}
trait T2 extends T {
abstract override def name = "t2"
}
class C extends T with T1 with T2 {
def printName = super.name
}
Now, in class C I want to access the behavior not of the last mixed-in trait but the behavior of one of these traits. Is this possible?
A: It is possible to specialize the super-call to a specific trait:
class C extends T with T1 with T2 {
def printName = super[T1].name
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526653",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "22"
} |
Q: Installing PHPUnit without using pear How can I install PHPUnit without using PEAR (and offline)?
I'm currently using Window Vista with XAMPP.
A: You don't really want that. See the dependencies on http://www.phpunit.de/manual/current/en/installation.html - installing them manually is a pain.
What you could do is downloading all pear packages on one machine with pear download $packagename and installing them on the offline machine with pear, too - but offline.
You'll also need phpunit's channel.xml file to get the channel registered offline, http://pear.phpunit.de/channel.xml.
A: Nowadays PHPUnit is available as a single file, which takes care of all its dependencies. See this answer for installation details:
NetBeans + multiple php versions + phpUnit without PEAR
A: thz . Mine is just copy and paste the whole php folder from successor one to me . all fine now .
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to write regular matching expression. -Java I want to write matching expression to read string between parentheses () from a big string. eg: the big string is:-
(something), (something2), (something3)
How can I write matching expression for this to read something, something2, something3 in groups.
A: You can't read all those groups in one go but using Matcher#find() and this expression you might read those: \(([^\(\)]*)\) (reads: match must start with (, must contain any number of characters not being ( or ) - those form your group - , and must end with ) ).
Note that the escape in the brackets is not necessary, but done for consistency, since they are needed outside.
Pattern p = Pattern.compile("\\(([^\\(\\)]*)\\)");
Matcher m = p.matcher( "(something), (something2), (something3)" );
while(m.find())
{
System.out.println(m.group( 1 ));
}
This prints:
something
something2
something3
A: You can read all the somethings into an array with one line:
String[] somethings = input.replaceAll("(^.?*\\(|\\)[^\\(]*$)", "").split("\\).*?\\(");
Here's some test code:
public static void main(String... args) throws InterruptedException {
String input = "foo (something1) (something2), blah (something3) bar";
String[] somethings = input.replaceAll("(^[^\\(]*\\(|\\)[^\\(]*$)", "").split("\\).*?\\(");
System.out.println(Arrays.toString(somethings));
}
Output:
[something1, something2, something3]
A: Following program will get required output
public class RegexTestStrings {
public static final String EXAMPLE_TEST = "(something),(something2),(something3)";
public static void main(String[] args) {
String[] splitString = (EXAMPLE_TEST.split("\\("));
System.out.println(splitString.length);
for (String string : splitString) {
System.out.println(string.replace(")",""));
}
}
}
First, it split all starting with ( and after that replace ) to "" so you will get output as:
something,
something2,
something3
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526657",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Best place to store config and log files for a Windows service I am wondering what is the best folder to use to store config files (ini, xml) and log files for a Windows service.
According to the special folders list on msdn, it seems that CommonApplicationData (= C:\ProgramData on Windows Vista/7/Server 2008 (R2)) is the best suited place :
CommonApplicationData = The directory that serves as a common repository for application-specific data that is used by all users.
Any other advice?
A: the .NET config file generated from Visual Studio, called myService.exe.config should be saved in the same location as the exe. and it's an XML not an ini file.
Log files can be saved in a folder like C:\Logs\ServiceName or anything else you like, we usually create a network share on such folder so we can check log files also from other machines without need to connect to the server where the Windows Service is running.
A: For logging, I think the Windows Event Log is the most suitable. If you use Enterprise Library it's pretty easy to set up :)
Edit: Also, I would agree that using CommonApplicationData for config files is a good choice.
A: Without much answers, I am just resuming in the following what I think and heard/read it's best:
*
*Configuration files (ini, xml) should be stored with the exe file of the service.
*Logs: The more modular way is to use a third-party logger (such as log4net or NLog - this thread is interesting for comparison). The folder where you will store your log file doesn't really matter, as long as it meets your needs (the service should have the sufficient rights to write in the folder, think who need to access to the log file and from where).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Implementation of Automatic Update server and Client using PUSH Method i have my software(.NET) running on clients. I need to push the updates to the clients over web whenever new update available .
I thought to implement a web service which is running on the main server which broadcasts the update notifications to the client. For dat, CLient has to register their identity over the web to the server.
Server will send the notification on availability of the update. Client have to download the update from the server.(i.e.) Server will start the upload process and client have to download.
I don't want a program always running in client machine and checking for a update.
Will WCF would be the good option? .. Is that possible to implement? .. I know there are so many constraints in the networked environment. Suggestions are welcome...
A: For software updates I wouldn't do push notifications unless the client software is always running. A better option might be to have the client check with the server for new updates when the software first starts up. There is less to maintain and it's easier to implement. With push notifications there always has to be a listener on the client side and it's possible for clients to close the listener. You'll also have the overhead of maintaining a manifest of all the connections. If all the clients are running on the same network, click once deployment might be an option. It allows you to configure it so that when new updates are released the client must update.
A: Yes, you can implement push feature from server to client. You just need to maintain connected client list in your server by storing instance context object of each client using WCF service and call callback method which will be implemented at client side. So all clients will get update through callback method.
You can store instance context object of client like below, where Client list is hash table:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class HostService : IHostService
{
public bool Connect(Guid applicationId)
{
if (!ClientList.ContainsKey(applicationId))
{
IHostServiceCallback client = OperationContext.Current.GetCallbackChannel<IHostServiceCallback>();
ClientList.Add(applicationId, client);
}
}
Interface for host service :
[ServiceContract(CallbackContract = typeof(IHostServiceCallback), SessionMode = SessionMode.Required)]
public partial interface IHostService
{
[OperationContract]
bool Connect(Guid applicationId);
}
Callback class for service :
[ServiceContract]
public partial interface IHostServiceCallback
{
[OperationContract(IsOneWay = true)]
void SendNotification(string message);
}
When your server receive notification in any event handler, send it to all clients like :
private void Notification_Received(object sender, EventReceivedEventArgs e)
{
foreach (IHostServiceCallback client in ClientList.Values)
{
try
{
client.SendNotification(notificationMessage);
}
catch
{
}
}
}
In client application, you have implemented callback method like :
public partial class Window1 : Window, IHostServiceCallback
{
public void SendNotification(string message)
{
// do some operation
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526661",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it possible to conditionally use XPManifest at runtime? I'm trying to let the user choose if he wants to use themed style or not.
Is it possible to dynamically "load" the XPManifest?
If user accepts the themed style then use the manifest, otherwise use the classic theme.
At program startup after dialog with style selection closes I would like to do something like:
if UserWantsThemedStyle then
LoadManifestSomehow
else
UseClassicStyle;
Is it even possible to do it at runtime?
Thanks
A: Yes you can do this. You need to use the activation context API which allows you to activate different manifests at runtime. I have used it to enable themes in an Excel add-in.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526665",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: MessageBox.show() C# problem see this code:
ChooseGrade ChGrade = new ChooseGrade();
string GrCl = ChGrade.getGrCl().ToString(); // function getGrCl gets "public int[] grad_class=new int[2];" in ChooseGrade Class
MessageBox.Show(GrCl);
But I see in Messagebox this "System.Int32[]" instant container of grade_class Array.
Can you Help me?
A: Enumerate over the ints and add them to a string which you can then show in the MessageBox:
string message = "";
int myArray[] = ChGrade.getGrCl();
foreach(var num in myArray)
message += String.Format("{0} ", num);
MseeageBox.Show(message);
A: You need to convert the array into a String before trying to print it out.
One way can be:
var GrCl=ChGrade.getGrCl();
string output=string.Join(",", GrCl.Select(x => x.ToString()).ToArray());
MessageBox.Show(output);
Edit:
As @spender has pointed out, this won't work in this case since GrCl is an int32[] which does not have the Select method.
As other answers have shown in the meantime, a workaround is to manually iterate over the array and convert and append each element into output.
foreach (var x in GrCl){
output+=x.ToString();
}
A: The default ToString()-implementation returns the type. Since the return value of getGrCl() is an array of integer, the ToString()-method returns just this.
A: What you're getting is the type name of the object returned by the getGrCl() method. If you haven't overriden the ToString() method, that is the expected behavior.
As I can see, the object returned is an integer array so you cannot alter it's ToString() method and by default it just gives you the type name. If you want to get a string containing the values from this array either traverse the returned array and use a StringBuilder to build your string, or create a separate method in your class to handle this issue.
Hope this helps you. If you still have questions just ask!
A: This is because the int you are converting to a String is an Array. You need to either loop through the array, or choose a specific index you want to print.
ChooseGrade ChGrade = new ChooseGrade();
string GrCl = ChGrade.grad_class[0].ToString();
MessageBox.Show(GrCl);
You would need to do something like this:
grad_class[0].ToString()
A: var x = ChGrade.getGrCl();
var messageString = string.Join(",", x.Select(i => i.ToString()))
MessageBox.Show(messageString);
A: GrCl in Show() is converted to String calling ToString () method. As this method of int [] returns string "System.Int32" you see exactly It. You ca to do in such way:
public string IntArrToString (int [] arr)
{
string intArrStr = "";
foreach (int number in arr)
intArrStr += number.ToString() + " ";
return intArrStr;
}
But It is better to use StringBuilder for such cases :)
Then you can call Show like that:
MessageBox.Show (IntArrToString (ChGrade.getGrCl()));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526669",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What's the meaning of `linear convergence` in Ch 1 of the Mythical Man Month
Next, one finds that debugging has a linear convergence, or
worse, where one somehow expects a quadratic sort of approach
to the end. So testing drags on and on, the last difficult bugs taking
more time to find than the first.
From "The Mythical Man-Month, Chapter 1 The Tar Pit".
What's the meaning of linear convergence here , could you give me a popular example or a graphics?
A: What Fred Brooks means is that management expectations of the rate at which finding, fixing, testing and closing off bugs will somehow increase at a quadratic rate is unrealistic. Brooks asserts that the rate of closing off bugs is at best time linear, and may in fact be will be worse than that.
In a picture, and assuming a utopian target of exactly ZERO bugs and defects, here's "Quadratic Closure" (green), Linear Closure (orange) and a worse-case decaying exponential (Red).
I agree with Brooks - Management's expectation is based on the assumption that as developers complete coding, that more and more of the development team will be allocated to debugging, which should increase the rate of bug fixing.
However, in reality, the easy bugs get found and fixed quickly, but more insidious defects are much more difficult to find, hence the long tail often experienced on project bug closure.
There's another reason why bug counts don't burn down at linear rates or better - even in most modern, professional software development houses, more testing resources are allocated to the project later on in the development cycle than in the early stages, and of course, as more code gets developed, the more bugs are introduced, and with more testers, more bugs are found. This means that the initial bug count is hopelessly under-reported, and the total bug count will actually increase for long periods of the project.
A more useful metric is the nett rate of defect closure. Here, teams generally look for the point at which the rate of closure crosses the rate of new defects being reported - this is taken as a good sign indicative that the end of the tunnel may be in sight.
A: It means that if you are trying to debug e.g. 10 bugs, debugging each takes roughly the same amount of time, or even more than the previous... thus debugging all takes roughly 10 times as much (or more) as debugging the first.
As opposed to quadratic convergence, where debugging all would take only roughly 3 times as much.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526675",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Django delete uploaded files in schedule if it is useless I have a model in Django to keep uploaded photos properties as
class Photo(models.Model):
file = models.FileField(storage=FileSystemStorage(location=settings.MEDIA_ROOT), upload_to='uploads')
header = models.CharField(null=True,max_length=200)
added_by = models.CharField(null=True,max_length=500)
isVerified = models.BooleanField(blank=False)
This model is created through a form chain, and for some reason sometimes the photo may be uploaded but because chain is not completed, it becomes useless.
I want to write a script to delete all such files (isVerified=False) and run it in certain schedule.
How should I write that script ?
I may write a Bash script to reach all the files in a folder but how should I move on ?
Thanks
A: I would write a python script, using Django to hit the database and get everything not verified.
#!/usr/bin/env python
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
# Assuming your settings are in the same directory, called settings.py.
# This is needed to tell django where to find the database
# use "module syntax" - dots not slashes
from django.conf import settings
from models import Photo # Make sure this is after the os.environ call
for photo in Photo.objects.filter(isVerified = false):
full_path = os.path.join(settings.MEDIA_ROOT, photo.file.path)
os.unlink(full_path)
Keep in mind I haven't tested this : )
Once you've sucessfully tested it, you could then run this every say 6 hours by putting it in your crontab. Save it as say, delete_unverified_files.py, and run crontab -e. In the file that appears, put:
0 */6 * * * python /path/to/delete_unverified_files.py
If you google crontab, you'll find a lot of examples of how to write one, if you're not familiar.
A: The best approach here is to use custom django-admin commands:
https://docs.djangoproject.com/en/1.3/howto/custom-management-commands/
So crontab will just execute smth like this:
... manage.py delete_unverified_files
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526682",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there a Rx Framework function which will create an observable which ends after a timespan has elapsed? Some observables are just so needy. They want you to listen and listen and listen to all they have to say, maybe for all of time! What if I can really only handle a few seconds' of events? Could I write something like
mouseMoves.TakeFor(TimeSpan.FromSeconds(2))
Conceptually, this would create a subject which would pass along events until a certain time had elapsed, then unsubscribe to the underlying observable and mark its own sequence complete. I suspect you could write it that way by hand, but it seems like there must be some existing operators which do this. I had hoped that Observable.TimeOut would do what I want, e.g. using
mouseMoves.Timeout(TimeSpan.FromSeconds(2), Observable.Empty<T>())
But I think what it's doing is timing out the observable if the time span between observations is longer than the given value. This is useful, too, but not quite what I'm after.
A: Sounds like you need TakeUntil:
var source = Observable.FromEventPattern(...);
source.TakeUntil(Observable.Timer(TimeSpan.FromSeconds(2))
.Subscribe(_ => {});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526685",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Google String Code I'm developing a small scale website, and the client has just informed me that there are code snippets that can be used, via a contact form. Basically, a contact form will be used, then once the submission has been made, a code snippet that is placed in the thank you page, would submit the information from the form to Analytics.
I've had a look but I just can't seem to find the right snippet, has anyone used this before.
Thanks.
A: I've found an answer, the information can be found at AdWords central via Google.
www.google.co.uk/AdWords
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to use android third party library twitter and myspace in same application? I am Integration Twittor which uses signpost core 1.2 and signpost commons 4.1.2 signpost commons 4.1.1-snapshot for authorization.
But problem arises when i integrate it with MySpace app which use signpost core 1.1 sanpshot and signpost commons 4.1.1-snapshot for authorization.
it shows error
java.lang.IllegalArgumentException: already added: Loauth/signpost/commonshttp/CommonsHttpOAuthConsumer;
Conversion to Dalvik format failed with error 1
What i will do prevent this problem
Thanks for reply
A: try to change the workspace and create new project and add everything related to the project. by this the "Conversion to Dalvik format failed with error 1" will get solved.
A: Hi To Integrate Both twitter and myspace in same application.
Use SocialAuth Android Library.
Here is the link
http://code.google.com/p/socialauth-android/
You can also integrate Facebook and Linkedin in same application.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526691",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Stopping an infinite loop on a remote server PHP I have a simple infinite for loop looking like this:
set_time_limit (0);
for (;;)
{
... //Doing some stuff including to write to a file
sleep(300);
}
It's running on my server. (Shared hosting account)
How on earth can I stop it?
A: Assuming you are working with a shared hosting server, and have no access to command line or ssh or hosting support team...
your best shot would be using your website management panel to trigger php restart.
this happens when you switch php version / change php ini params such as memory limit
A: You might want to contact your hosting service and ask them to kill your script. Most likely you don't have execute-access or ssh-access. Maybe you should build a possibility to quit your program next time you create an infinite loop.
A: I logged in via SSH and tried killing the process but it didn't seem to work - possibly the incorrect process as there were quite a few there.
You can always restart apache as a last resort; that will fix it ;-)
A: kill the process. assuming you can get access to the console via ssh and your server runs on linux:
ps -ef | grep php // to get a list of php-processes
kill [process-id] // kill the process by process-id
A: You mentioned writing to a file.
But if you were writing to a database you can use your database tool to temporarily rename a field which would trigger an error and stop your script.
The woes of shared servers, rapid dev and typos.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526701",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: Query is not inserting data into db I am at a loss why my query is not inserting values into db. Even if I do echo $query or var_dump($query) there is nothing printed at all. All values are being passed successfully just not being inserted. I am getting Could not connect but I do not know why. All connections are established and as a test I took this code and ran it on its own with dummy data and it inserted the data fine. I can only think it has something to do with the $response_array. Where am I going wrong?
<?php require_once('Connections/sample.php'); ?>
<?php
session_start();
$new = 1;
$activity = 'General Contact Enquiry';
$mobile = 'Submitted from mobile';
$name = mysql_real_escape_string($_POST['GC_name']);
$department = mysql_real_escape_string($_POST['GC_department']);
$message = mysql_real_escape_string($_POST['GC_message']);
$email = mysql_real_escape_string($_POST['GC_email']);
$company = mysql_real_escape_string($_POST['GC_company']);
$position = mysql_real_escape_string($_POST['GC_position']);
//response array with status code and message
$response_array = array();
//validate the post form
//check the name field
if(empty($name)){
//set the response
$response_array['status'] = 'error';
$response_array['message'] = 'Name cannot be blank';
//check the name field
} elseif(empty($company)) {
//set the response
$response_array['status'] = 'error';
$response_array['message'] = 'You must enter a company name';
//check the position field
}elseif(empty($position)) {
//set the response
$response_array['status'] = 'error';
$response_array['message'] = 'You must enter a position';
//check the email field
} elseif(empty($email)) {
//set the response
$response_array['status'] = 'error';
$response_array['message'] = 'You must enter a valid email address';
//check the dept field
}elseif($department=="Choose Department") {
//set the response
$response_array['status'] = 'error';
$response_array['message'] = 'You must select a department';
//check the message field
}elseif(empty($message)) {
//set the response
$response_array['status'] = 'error';
$response_array['message'] = 'You must enter a message';
//check the dept field
}
else {
//set the response
$response_array['status'] = 'success';
$response_array['message'] = 'Your enquiry has been sent succesfully';
$flag=1;
}
//send the response back
echo json_encode($response_array);
if($flag == 1) {
mysql_select_db($database_sample, $sample);
$query = 'INSERT INTO feedback (company, department, name, email, position, feedback, date, new) VALUES (\''.$company.'\', \''.$department.'\', \''.$name.'\', \''.$email.'\', \''.$position.'\', \''.$message.'\', NOW() , \''.$new.'\')';
mysql_query($query) or die("Could not connect");
}
?>
A: Did you try mysql_query($query) or die (mysql_error());
Hope so you will getting right error description.
A: Use proper error checking and debugging to find out what the problem is.
That way, you can find out what goes wrong yourself! :)
For example, you could use simple echo statements to find out the following:
*
*Is $flag really 1, is that code block ever actually executed?
*What does $query contain? Is it a proper SQL query?
*Does mysql_error() say anything?
A: May be you need to verify the $query content.
Try this way,
$query = "INSERT INTO `feedback` (`company`, `department`, `name`, `email`,
`position`,`feedback`, `date`, `new`) VALUES
('$company','$department','$name','$email','$position',
'$message',NOW(),'$new')";
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526710",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: selection constraint is plsql Assume I have a table entries with columns: id, alias_one, alias_two, name.
How do I select all values from entries where there exists several names for the same alias_one / alias_two pairs provided that names are not known?
Looks like as an option, group by alias_one and alias_two can be used but somehow it fails.
A: It will return all table rows for which there's another row with the same alias_one and alias_two but different name.
select
id,
alias_one,
alias_two,
name
from
(
select
id,
alias_one,
alias_two,
name,
count (distinct name) over (partition by alias_one, alias_two) as cnt
from entries
)
where cnt > 1
A: perhaps you need to
GROUP BY ALIAS_ONE||ALIAS_TWO
OR
GROUP BY ALIAS_ONE||ALIAS_TWO
HAVING COUNT(ALIAS_ONE||ALIAS_TWO) > 1
A: EDIT: Ok, I think I understand now. Try this:
select * from entries e where (alias_one,alias_two) in (select alias_one, alias_two
from entries group by alias_one, alias_two having count(distinct name) > 1)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526712",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: possible to ignore lucene document boost? I am looking for a way to tell the lucene searcher to ignore document boosting on certain queries?
In our search results we usually work with a dominant boost-factor calculated by the age of a document while indexing (the index is rebuild nightly).
Now, I am looking for a way offer search-functionality which ignores the age, but found yet no way to override/ignore the document boost.
Best regards,
Alex
A: Are you looking for something the QueryParser would understand? Because that is simply not possible.
You're adding the boost somewhere in your code, it is not done by Lucene by default. You'll have to remove this additional piece of code, or make it optional in order to ignore the boost.
A: http://lucene.apache.org/java/3_0_0/api/core/org/apache/lucene/search/Similarity.html
From the point 6, I reckon it is impossible to ignore boosts at search time:
norm(t,d) encapsulates a few (indexing time) boost and length factors:
*
*Document boost - set by calling doc.setBoost() before adding the
document to the index.
*Field boost - set by calling field.setBoost() before adding the
field to a document.
*lengthNorm(field) - computed when the document is added to the
index in accordance with the number of tokens of this field in the
document, so that shorter fields contribute more to the score.
LengthNorm is computed by the Similarity class in effect at indexing.
When a document is added to the index, all the above factors are
multiplied. If the document has multiple fields with the same name,
all their boosts are multiplied together:
(...)
Last, note that search time is too late to modify this norm part of
scoring, e.g. by using a different Similarity for search.
A: Instead of storing your calculated-score as boost, you can store it in a new field, and by implementing CustomScoreQuery + CustomScoreProvider you can control which value(default score or your calculated-one in the field) to return
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526720",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: GWT tree with checkbox:How to get all checked tree items? I am using GWT 2.3.In my application I am using GWT Tree with check box.
Here is my code to create tree
formTree = new Tree();
if (formList != null && formList.size() > 0) {
for (Form form : formList) {
TreeItem item = new TreeItem(new CheckBox(form.getName()));
formTree.addItem(item);
}
}
In this tree I am using check box for every tree item. now on a click of button I want all the checked tree items.I am not getting How can i get all the selected tree item.Please help me out.Thanks in advance.
A: I suggest extending TreeItem to serve the actual purpose you're intending here: have it create checkbox-based item, which allows you to access the checkbox value. Currently, you'd have to loop through, get out the child of each, cast to the Checkbox class, then check the property. None of this is good practice, so extending it is really the only smart, efficient and effective way to go.
With that being said, here's how you might do it if you really had to:
for(int i = 0; i < tree.getItemCount(); i++)
{
TreeItem item = tree.getItem(i);
CheckBox itemCheckBox = (CheckBox)item.getWidget();
boolean checkBoxValue = itemCheckBox.getValue().booleanValue();
// do something w/ checkBoxValue...
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526725",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Let SWFObject update flash, but don't require it I have a game that will work better in Flash Player 11 (with Molehill) but also works in 10.3. I'd like to get players to automatically update to 11 with express install as much as possible (after it's released, of course), but don't want to force them.
I tried this way of embedding it with SWFObject:
swfobject.embedSWF(
// url
"game.swf?version=1",
// content to replace
"flashContent",
// size
"910", "658",
// flash version
"11",
// expressInstall
"playerProductInstall.swf",
// flashvars
{},
// params
{
wmode: "transparent",
allowScriptAccess: "always"
},
// object attributes
{},
// callback
function(e) {
if (e.success) {
console.log("SWF loaded", e);
gameSwf = e.ref;
} else {
console.log("SWF not loaded", e);
}
}
);
However, that will make the game require 11, which means that if express install doesn't work (Linux) or is cancelled by the user, the game is not loaded, even though it would run fine.
Is there another way to do what I want?
A: Make the required version 10.3
Then write javascript to detect if the version is 11. If not, show the update link.
Better still would be to just require fp11, it will cause no harm
A: Similar to Pravnav's answer, I would embed the game using 10.3, then place a small banner above the movie that says their version of Flash Player is out of date and the game performs best with FP 11+. Make the banner clickable and use swfobject's swfobject.showExpressInstall method to trigger Express Install.
The tricky part is Express Install support: as you said, EI doesn't work in Linux, but it also doesn't work in Google Chrome, since Chrome uses an embedded self-updating version of FP. Might be useful to write some sniffing JS that provides a link to Adobe.com for those browsers instead of using Express Install.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526726",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jQuery Mobile: selecting by ID doesn't work well I've a strange problem with jQuery Mobile... Below is the HTML code of my application:
<!-- == START MAIN PAGE == -->
<div id="mainPage" data-role="page">
<div data-role="header" data-position="fixed">
<a href="#addContactPage"
data-transition="slidedown"
data-rel="dialog"
data-icon="plus"
data-iconpos="notext">Add a contact</a>
<h1>My repertory</h1>
</div>
<div data-role="content">
<p>
Welcome to your repertory!
</p>
<ul id="contacts_list"></ul>
</div>
<div data-role="footer" data-position="fixed">
<h1>Made with <em>jQuery Mobile</em></h1>
</div>
</div>
<!-- == END MAIN PAGE == -->
<!-- == START ADD CONTACT PAGE == -->
<div id="addContactPage" data-role="page">
<div data-role="header">
<h1>My repertory: add a contact</h1>
</div>
<div data-role="content">
<form id="addContactForm" action="#mainPage">
<div data-role="fieldcontain">
<input type="submit" value="Valid" />
</div>
</form>
</div>
</div>
When the main page is shown, I want to set an item inside the <ul> list:
//When the main page is created.
$('#mainPage').live('pagecreate',function()
{
//Just after the page is shown
$(this).bind('pageshow',function()
{
alert('Event triggered!');
$('#contacts_list').html('<li>Reset list!</li>');
});
});
So, here is my problem: when I start the application, this code works and the item is set.
If I open the "add contact page" (please note it's a dialog box) and just close it, this code works well too and the expected result is done.
But if I open the "add contact page" and then submit its form, the list becomes empty!
The alert() is done, so the event is triggered... But the list is empty, like if the html() method is not called.
I've tried to alert the value of *$('#contacts_list').lenght*, and it's 1, so the jQuery object exists!
Please note that I've done nothing during the submission of the form: there is no listener on its submit event.
And if I replace the code by this one:
//When the main page is created.
$('#mainPage').live('pagecreate',function()
{
//Just after the page is shown
$(this).bind('pageshow',function()
{
alert('Event triggered!');
$(this).find('#contacts_list').html('<li>Reset list!</li>');
});
});
Then it works well!
I really don't understand...
Why the expected result is done with $(this).find('#contacts_list') and not with $('#contacts_list') ?
Thanks in advance!
A: It's looks like your submission of the form causes a second event to be bound to the pageshow. What happens if you remove (or alter) the Action on the the form? Also, try:
$(this).unbind('pageshow').bind('pageshow',function()...
EDIT
I think the outer function might well be redundant. Why not simplify the whole lot to:
$('#mainPage').live('pageshow',function()
{
alert('Event triggered!');
$(this).find('#contacts_list').html('<li>Reset list!</li>');
}
);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526728",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: GenericJDBCException in HSQL I have an entity called ProdTransaction. I am saving two records of type ProdTransaction. Both the two inserts succeed when run independently. I mean
tranDAO.save(record1) //alone works
tranDAO.save(record2) //alone works
but together running them as
tranDAO.save(record1)
tranDAO.save(record2)
HSQL throws a GenericJDBCException error.
@Entity
@Table(name = "ProdTransaction")
public class ProdTransactionextends PersistentObject implements Serializable {
private static final long serialVersionUID = 1L;
@Embedded
private ProdTranPK id;
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE)
@Column(name = "REC_ID")
private Long recId;
@Temporal(TemporalType.DATE)
private Date date1;
@Column(length = 1)
private String comment;
}
I have verified the data and it's all fine. When I run against HSQL I get:
GenericJDBCException: could not execute JDBC batch update.
But if I connect to my physical DB, and run with the same sequence, it works fine. What could be the problem in HSQL? I am using version 1.8.
A: HSQLDB batching bug was fixed, now it works ok. Problem is that if you have an error, such as a problem with your SQL statement etc, you'll only get a generic exception that doesn't really tell you anything. What I like to do is have a helper class that can execute SQL queries in batch mode and individually, and I switch to individual queries when I get weird errors from batch mode. Try that, maybe it's just a simple mistake in your SQL
A: It's also possible to disable batching in hibernate. In the hibernate session configuration, set:
hibernate.jdbc.factory_class=org.hibernate.jdbc.NonBatchingBatcherFactory
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526729",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C#, WCF, Hide web service through dll In my dll I have a server reference to a web service. This WCF web service becomes visible to my client application that uses the dll. Is there a way to prevent this?
Thanks.
A: When adding the service reference, click the "Advanced" button. This will give you the option to generate all client service classes as internal instead of public.
A: If the reference is built into the URL then you will have to handle the fact it will be visible. The alternative is to not use service references. You can still call the service without a service reference by using the WCF channel stack in code.
To do this your client only needs a references to the service interface and the types which are exposed on the service's operations. Then you can use ChannelFactory<ServiceInterface>("NameOfServiceInConfigFile").CreateChannel() to return your proxy.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526731",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: NullPointerException on CustomContact insert The code:
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
// Create raw contact
Builder builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
builder.withValue(RawContacts.ACCOUNT_NAME, "testaccount");
builder.withValue(RawContacts.ACCOUNT_TYPE, "nl.my.project.account");
builder.withValue(RawContacts.SYNC1, "username");
operationList.add(builder.build());
builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
builder.withValueBackReference(ContactsContract.CommonDataKinds.StructuredName.RAW_CONTACT_ID, 0);
builder.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, "name");
operationList.add(builder.build());
builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
builder.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0);
builder.withValue(ContactsContract.Data.MIMETYPE, "vnd.android.cursor.item/vnd.nl.my.project.profile");
builder.withValue(ContactsContract.Data.DATA1, "username");
builder.withValue(ContactsContract.Data.DATA2, "Profile");
builder.withValue(ContactsContract.Data.DATA3, "View profile");
operationList.add(builder.build());
try {
getContentResolver().applyBatch(ContactsContract.AUTHORITY, operationList);
} catch (RemoteException e) {
e.printStackTrace();
} catch (OperationApplicationException e) {
e.printStackTrace();
}
contacts.xml:
<ContactsSource xmlns:android="http://schemas.android.com/apk/res/android">
<ContactsDataKind
android:icon="@drawable/icon"
android:mimeType="vnd.android.cursor.item/vnd.nl.my.project.profile"
android:summaryColumn="data2"
android:detailColumn="data3"
android:detailSocialSummary="true" />
</ContactsSource>
Logcat:
09-23 09:09:23.981: ERROR/DatabaseUtils(223): Writing exception to parcel
09-23 09:09:23.981: ERROR/DatabaseUtils(223): java.lang.NullPointerException
09-23 09:09:23.981: ERROR/DatabaseUtils(223): at com.android.providers.contacts.ContactsProvider2.insertData(ContactsProvider2.java:2574)
09-23 09:09:23.981: ERROR/DatabaseUtils(223): at com.android.providers.contacts.ContactsProvider2.insertInTransaction(ContactsProvider2.java:2422)
09-23 09:09:23.981: ERROR/DatabaseUtils(223): at com.android.providers.contacts.SQLiteContentProvider.insert(SQLiteContentProvider.java:106)
09-23 09:09:23.981: ERROR/DatabaseUtils(223): at com.android.providers.contacts.ContactsProvider2.insert(ContactsProvider2.java:2238)
09-23 09:09:23.981: ERROR/DatabaseUtils(223): at android.content.ContentProviderOperation.apply(ContentProviderOperation.java:214)
09-23 09:09:23.981: ERROR/DatabaseUtils(223): at com.android.providers.contacts.SQLiteContentProvider.applyBatch(SQLiteContentProvider.java:216)
09-23 09:09:23.981: ERROR/DatabaseUtils(223): at com.android.providers.contacts.ContactsProvider2.applyBatch(ContactsProvider2.java:2272)
09-23 09:09:23.981: ERROR/DatabaseUtils(223): at android.content.ContentProvider$Transport.applyBatch(ContentProvider.java:193)
09-23 09:09:23.981: ERROR/DatabaseUtils(223): at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:173)
09-23 09:09:23.981: ERROR/DatabaseUtils(223): at android.os.Binder.execTransact(Binder.java:288)
09-23 09:09:23.981: ERROR/DatabaseUtils(223): at dalvik.system.NativeStart.run(Native Method)
A: Changing:
Builder builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
To:
Builder builder = ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI);
Seems to fix the NullPointerException.
A: try working like this
ArrayList ops = new ArrayList();
ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
.build());
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526743",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is it necessary to explicitly free memory in Google App Engine's Python environment? Is there a way to free memory in google's app engine? Is there a garbage collector in python?
A: Python has it's own garbage collection so there's no need to release memory manually.
A: Python itself managing the garbage collection. Normally, no need for manual memory release.
although, you can check Python GC lib, if you want to do it manually.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526746",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Enable - SP Feature fails to find the configuration section in the web apps config I have a site for which i want to activate feature using powershell
When i run the following command :
enable-spfeature FEATURE NAME -url http://URL
it throws an error :value cannot be null parameter name section.
it basically fails to find the configuration section located under the web application configuration.If i create a file with name powershell.exe.config and place it under the
powershell folder ,it works fine but i dont want to touch the system folder.
Is it possible to give powershell a path of config located int some other folder and ask it to use that while activating feature.
I have tried something like this but with no luck
$configpath = "C:\DevTools.exe.config"
[System.AppDomain]::CurrentDomain.SetData("APP_CONFIG_FILE",$configpath)
enable-spfeature Feature name -url http://url
A: Why arn't you putting the configuration information in the web application web.config file?
A: @Lee Activating the feature from powershell expects the configuration to be under the hosting process which is powershell in this case.
The solution to my problem was to load the configuration at run time as shown below and using windows powershell instead of using sharepoint management shell :
[System.AppDomain]::CurrentDomain.SetData("APP_CONFIG_FILE",$configpath)
add-type -path C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Configuration.dll
Add-PSSnapin Microsoft.Sharepoint.PowerShell
enable-spfeature $FeatureName -url http:\\url
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526748",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Maxima: How to type a term of a complicated series How do you type the following general term of a series in Maxima ?
http://www.texify.com/img/%5CLARGE%5C%21u_%7Ba%7D%5E%7Bm%2Cn%7D%28h%29%3A%3D%28-h%29%5E%7Bn-a%7D%5Csum_%7Bj%3D0%7D%5E%7Bm-n%7D%28-1%29%5Ej%5C%28%5Carray%7Ba-n%5C%5C%5Cvspace%7B3%7D%5C%5Cn%7D%5C%29%281%2Bh%29%5Ej.gif
A: Well, first the binomial can be taken outside the sum and the sum can be performed in closed form:
Anyway, the entire expression you gave is entered into maxima as
u(a, m, n) := (-h)^(n-a) * sum((-1)^j * binomial(a-n,n) * (1+h)^j, j, 0, m-n);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526754",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: default pic when using multiple nested images on paperclip I am using Paperclip to upload multiple item images. I followed some of this tutorial http://sleekd.com/general/adding-multiple-images-to-a-rails-model-with-paperclip/
My models are:
Item.rb
has_many :item_images, :dependent => :destroy
accepts_nested_attributes_for :item_images, :reject_if => lambda { |l| l['item_image'].nil? }
ItemImage.rb
class ItemImage < ActiveRecord::Base
belongs_to :item
belongs_to :user
#for image. Paperclip following Bootstrap sizes.
has_attached_file :image,
:styles => { :large => ["330x230>",:png], :medium => ["210x150>",:png], :small => ["90x90>",:png], :thumb => ["32x32>", :png] },
:default_url => '/images/missing_image_:style.png',
:storage => :s3,
:bucket => 'iscomp',
:s3_credentials => "#{RAILS_ROOT}/config/amazon_s3.yml",
:path => "iscomp/:attachment/:style/:id.:extension"
validates_attachment_presence :image
validates_attachment_size :image, :less_than => 5.megabytes
end
My issue is that because the images are stored on a second model, I am not able to access a default blank image when there are no images/records on the @item.item_image. If I had used paperclip directly on @item, Paperclip will return default image for me.
What's the best way of doing this if I do not want to keep adding in if/unless statements whenever I call for a thumbnail?
A: I don't know if you are looking for an elegant way of doing this but the way I did was to create a default image and if @item.item_image returns blank I display the default blank image. I did not use paperclip default.
A: You can solve this issue by:
Adding an itemimage_count in your migration
def self.up
add_column :item, :itemimage_count, :integer, :default => 0
Item.reset_column_information
Item.all.each do |item|
item.update_attribute :itemimage_count, item.itemimages.length
end
end
def self.down
remove_column :item, :itemimage_count
end
end
This will then associate a number of ItemImages with each Item. You can than access this counter in your views, controllers and models.
If you want to get pretty with it you can simply set a scope condition in your model.
Item.rb
scope :list, :conditions => ["itemimages_count >= 0"]
Item_controller
@itemimages = Item.list
I would personally make a partial in your views with 1 set of if else statements, whenever you want to display the images simply call out to the partial.
if Item.itemimages_count == 0
#show this image
end
#code that displays an Item's image
#show the image in itemimages
I hope this helps someone.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526756",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to check that all html tags are closed with Regex I mean that each < should have an appropriate >. A string without any < or > should be valid too.
Any idea?
A: Once, I've created a JavaScript BB-code parser, which also dealt with incorrectly closed tags. The same concept also applies to HTML (and any other markup language which rely on a tree).
*
*Define variables: var string = ""; var lastIndex = 0; var stack = []; var parsedString = ""///And some more
*Loop through the string, until a < is matched, using string.indexOf("<", lastIndex).
*Select the tag name, and search for the closing > (using an RE: /[^<]+?/). Set lastIndex to the index of this >, plus 1.
*Add this value (tagName) to an array (let's define this array: var stack = [];).
*If a closing tag is encountered, walk through the stack, from the last element and back.
*If the start tag is the last element of stack, use stack.pop(). Continue at 1.
*If the start tag isn't the last element of the array:
*
*If your tag is important, persist to find the opening tag (</div> should close any <div>, even if you have to throw away 9001 <span> declarations).
*While you walk through the array, check the status of the encountered tags: Are these "important" elements? (<strong> is less important than <div>, for example).
*If you encounter an important tag (such as <div>), while your closing tag was a </em>, ignore the closing tag and go back to 1.
When 1 evaluates to false (no < found), add the remaining string to the result resultString += string.substring(lastIndex, string.length);.
After following these steps, you've parsed a string.
A: Your string will have a tag thats not properly opened or closed, if there are two consecutive opening or closing brackets with only non-bracket characters between them.
These would be matched by
<(?=[^>]*<)|>(?=[^<]*>)
Note that this will work reliably only on html without script parts or comments! Also, this will only check the brackets. It will not check if every tag you opened is closed again. (I.e. it will detect <<a> as wrong, but not <a></b>)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526759",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to update database from datagridview bound by linq query and entity model? I bind a datagridview from a linq query, but I don't know how to make it updated to database when users makes changes on the datagridview.
var q = from w in dowacodbEntities.worksheets
where w.ContractForm_id.Equals(g_ContractID)
orderby w.id
select new
{
w.id,
w.UnitPrice,
w.LabourCost
};
BindingSource bindingSource = new BindingSource(); // use bindingsource
bindingSource.DataSource = q.ToList(); // convert linq query to bindingsource
dataGridView1.DataSource = bindingSource; // add bindingsource to datagridview
p/s : I'm using C# winform
A: I think this is the same problem
WinForms DataGridView - update database
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526761",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Programmatically show the popup from a DatePicker I'm using the DatePicker from the Silverlight Toolkit on Mango
I want to programmatically display the date picker full mode display, but I can't see any API hook to do that at the moment.
Is this possible? or do I have to implement this myself by (intelligently) writing a new control?
A: Build your own I'm afraid.
Be careful about the user expectations around opening it automatically though. ;)
A: Sadly Matt was right - there's no public or protected API to hack into and security prevents the use of Reflection - so I've +1'd his answer... and a full answer is:
*
*take the files from Silverlight.codeplex.com
*either use the whole project or create your own library with just DatePicker.cs, DateTimePickerBase.cs and the DatePicker Style template from Generic.xaml
*in your DateTimePickerBase, add:
public event EventHandler<EventArgs> PopupClosedByDateSelection;
*in ClosePickerPage() inside PopupClosedByDateSelection inside the if(_dateTimePickerPage.Value.HasValue) block, add:
if (PopupClosedByDateSelection != null)
PopupClosedByDateSelection(this, EventArgs.Empty);
This seems to work for the Back button case as well as for the cancel and OK cases.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526762",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: multiple jquery animations I have 3 divs on my page that Im trying to give an appearance of expanding out using the jquery .animate width function. The thing is I dont want them all to expand at the same time but I also dont want them to only start when the one before it has finished. Im kinda needing them to start a few miliseconds after the previous once has started so there just slightly out of sync, if that makes sense?
A: Try using .delay() before animate():
$('#mydiv').delay(200).animate
example:
http://jsfiddle.net/yF8Vx/
A: You can specify not to queue an animation as one of the options:
$('div').animate({"width": 100});
Then you could run this code in seperate window.setTimeout calls to stagger the effect.
Example - http://jsfiddle.net/6Dqus/1/
A: DEMO link
$('.box').each(function(i){ // 'i' = index
var spd = 700; // set speed (animation/delay) time
var dly = spd*i; // 700*0 = 0 ; 700*1 = 700 .....
$(this).delay(dly).animate({width: 500 },spd); // now you have proper delays.
});
EDIT :
DEMO
$('.box').each(function(i){
var dly = 400*i; // delay time is less than...
$(this).delay(dly).animate({width: 200},800); // the animation time
});
And the whole in a couple of lines.
Incredible that the above was '-1' after a Q edit 1h after my first answer.
Never mind. In a couple of lines here's your script.
By the way the above was so nicely explained that anyone could fix it in fiew seconds to get the best results. The approach was the key. Thanks! ;)
A: You could delay them with a simple timer:
// Start animation 1
setTimeout(function {
// Start animation 2
}, 100);
setTimeout(function {
// Start animation 3
}, 200);
A: Use each() width delay():
$("divs").each(function(index){
$("this").delay(index*200).animate({"width":100},500)
})
This will start next animation 200ms after starting previous one.
Fixed missing argument.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526763",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Two JFrames in one Runnable. First JFrame disappears in the application bar after calling a JFileChooser I'm trying to create a multi-windowed interface, ala GIMP. One of them allows the user to load an image, to be displayed in the frame. So, when the program loads, all windows (two for now but I plan to have three) are shown in the application bar. However, when the second* window invokes JFileChooser, it disappears in the application bar (but does not close). But if I <Super>+<Tab> or <Alt>+<Tab> it still appears there. It also reappears in the app bar when I click the "Show/Hide All Windows" button.
All JFrames are invoked from a single Runnable. Anyone else encountered this issue? How do I work around this one (i.e., make all windows visible in the application bar at all times)?
Thanks!
*I called it the second window since it is the second one that is setVisibled to true.
A: A JFrame will appear on the task bar. A JWindow or JDialog do not appear on the task bar.
A JFileChooser uses a JDialog to display the date so it will not appear on the task bar. You need to specify a JFrame as the owner of the file chooser. The file choose will still not appear on the task bar, but when you click on the icon representing the owner frame it will become visible along with the frame.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526765",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Issue with "less" filter I'm founding the compile of templates with "less" is not working properly (the css compiling doesn't work as expected) when I have too much content in my less file.
The compiling problems are with the content that are compiled at the end of the less file, in fact if I remove temporarily the content of the beginning of the file, the content at the end is compiled ok.
I have tried to compile the file from the less command line and I don't have those problems.
I'm thinking in some lack of memory as the origin of the problem...
Any idea?
Assetic 1.0.1/less 1.1.3
A: This solved my problems.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526769",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: live555 problem while streaming over the internet I've compiled with VS the live555 source code, and it works just fine if I try to stream locally a file
e.g.
Command Line:
live555.exe myfile.mp3
VLC Connection String
rtsp://169.254.1.231:8554/myfile.mp3
but if I try to stream it over the internet, VLC communicates with live555, but live555 won't send data to him
Command Line
live555.exe myfile.mp3
VLC Connection String
rtsp://80.223.43.123:8554/myfile.mp3
I've already forwarded the 8554 port (both tcp/udp) and tried to disable my firewall but this doesn't solve.
How is that?
A: To troubleshoot:
*
*Are you streaming RTP over RTSP: have you checked the "Use RTP over RTSP (TCP)" option in VLC? You can check this in VLC under the preferences: input/codecs->Demuxers->RTP/RTSP. You can try to see if this solves the problem in which case it could be that UDP is blocked.
*You speak of forwarding. Do you mean port forwarding from one machine to the RTSP server? if so-> if you are not doing RTP over RTSP, then you would also need to forward the ports for the media which is not the same as the RTSP port (554 or 8554). These ports are exchanged during the RTSP SETUP. If you do RTP over RTSP the media is interleaved over 554 or 8554 and you don't have to worry about this.
Also, another good debugging tool is the live555 openRTSP application. You can run it from the command line and specify "-t" for RTP over RTSP, which is basically what the VLC option does. You can specify "-T" for HTTP tunneling, etc and it allows you to write captured media packets to file, etc.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526770",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Python-uno package issue with python2.6 and python2.7 installed I'm working with OpenERP and a module named report_openoffice. This module needs the package python-uno installed. The problem is that i have 2 versions of python(2.6 and 2.7). When I install the package, Python2.7 can use the package python-uno but python2.6 can't. I need to use it in python2.6. Is there a way to install this package for python 2.6?
PS: I'm on Ubuntu 11.04
Thank you very much
A: I soft linked the uno.py and unohelper.py from 2.7 into 2.6 and that seems to work.
As root do (or with sudo):
$> cd /usr/lib/python2.6/dist-packages
$> ln -s /usr/lib/python2.7/dist-packages/uno.py
$> ln -s /usr/lib/python2.7/dist-packages/unohelper.py
A: python-uno is often used to drive OpenOffice/LibreOffice. However, if you just want to create reports in odt or pdf files, you can use PyQt4
A simple example to show how to write to an odt file:
>>>from pyqt4 import QtGui
# Create a document object
>>>doc = QtGui.QTextDocument()
# Create a cursor pointing to the beginning of the document
>>>cursor = QtGui.QTextCursor(doc)
# Insert some text
>>>cursor.insertText('Hello world')
# Create a writer to save the document
>>>writer = QtGui.QTextDocumentWriter()
>>>writer.supportedDocumentFormats()
[PyQt4.QtCore.QByteArray(b'HTML'), PyQt4.QtCore.QByteArray(b'ODF'), PyQt4.QtCore.QByteArray(b'plaintext')]
>>>odf_format = writer.supportedDocumentFormats()[1]
>>>writer.setFormat(odf_format)
>>>writer.setFileName('hello_world.odt')
>>>writer.write(doc) # Return True if successful
True
QTextCursor also can insert tables, frames, blocks, images. More information. More information at:
http://qt-project.org/doc/qt-4.8/qtextcursor.html
A: uno package install in python 2.7, then run following commands:
sudo apt-get install libreoffice python-genshi python-cairo python-lxml python-setuptools
sudo apt-get install libreoffice-script-provider-python
easy_install uno
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526773",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: $this->headTitle escapes data I have my page titles in the database.
For example in my db:
Brandname® - Home
Now, if I get this from my db and set the page title with $this->headTitle(), it returns Brandname&reg; - Home
Is it possible that this isn't converted? I just want to return what's in the database.
My document is set to UTF8, the view encoding is also set to UTF8. The DB is also in UTF8.
A: Auto-escaping is turned on by default, you have to call
$this->headTitle()->setAutoEscape(false);
once somewhere in your code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526775",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Encode image from url not working In my blackberry application All screen have Ad image at the bottom of the screen (Banner image) .
In Simulator application working fine but when i install app in my Strom 2 (9550) application work fine without Banner image .
i get all Banner image URL from my web service but when i tried to encode image from URL for Display in screen i cant encode image from url so apps not looks good.
see my below code for encode image
connection = (HttpConnection) Connector.open(bannerImage[i], Connector.READ, true);
inputStream = connection.openInputStream();
byte[] responseData = new byte[10000];
int length = 0;
StringBuffer rawResponse = new StringBuffer();
while (-1 != (length = inputStream.read(responseData)))
{
rawResponse.append(new String(responseData, 0, length));
}
int responseCode = connection.getResponseCode();
if (responseCode != HttpConnection.HTTP_OK)
{
throw new IOException("HTTP response code: "
+ responseCode);
}
final String result = rawResponse.toString();
byte[] dataArray = result.getBytes();
encodeImageBitmap = EncodedImage.createEncodedImage(dataArray, 0, dataArray.length);
Thanks in Advance !!
A: i got the ans for this . when we use internet using wifi than we have to pass :interface
i add the this parameter to my image url and all works fine .
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526776",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: UIFont: How to change all fonts in any view in app? Our app as many others concist of MANY different components such as UIButton, UITextField, UILabel, etc (not UISearchBar) for displaying and editing text. Most components are setup in Interface Builder. What is the most efficient way of replacing all system fonts with a custom font?
Should I categorize UIFont to always return our custom font?
Or should I iterate over all the xib-files xml and replace the font from there?
Recomendations and other options is greatly appreciated!
A: iOS 5 brings new API for customizing the standard UI that should make changing the fonts dead-easy. Depends on your OS version requirements.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526780",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Impact of Apache Log-Files to Serverperformance Im running a Apache Webserver under Windows Sever 2003.
I noticed that my logfile is bigger then 100MB. If I imagine, that Apache always has to open this file, jump to its end, add a new line and close it again, it seems a good idead to keep this log small.
But is this issue / possible performance-lack really that big?
A: Apache won't be opening and closing the file all the time - it will keep the file open with the file pointer at the end, ready to write the next line.
So the size of the logfile isn't an issue from a performance point of view.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526783",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: OpenCV CUDA running slower than OpenCV CPU I've been struggling to get OpenCV CUDA to improve performance for things like erode/dilate, frame differencing etc when i read in a video from an avi file. typical i get half the FPS on the GPU (580gtx) than on the CPU (AMD 955BE). Before u ask if i'm measuring fps correctly, you can clearly see the lag on the GPU with the naked eye especially when using a high erode/dilate level.
It seems that i'm not reading in the frames in parallel?? Here is the code:
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/video/tracking.hpp>
#include <opencv2/gpu/gpu.hpp>
#include <stdlib.h>
#include <stdio.h>
using namespace cv;
using namespace cv::gpu;
Mat cpuSrc;
GpuMat src, dst;
int element_shape = MORPH_RECT;
//the address of variable which receives trackbar position update
int max_iters = 10;
int open_close_pos = 0;
int erode_dilate_pos = 0;
// callback function for open/close trackbar
void OpenClose(int)
{
IplImage disp;
Mat temp;
int n = open_close_pos - max_iters;
int an = n > 0 ? n : -n;
Mat element = getStructuringElement(element_shape, Size(an*2+1, an*2+1), Point(an, an) );
if( n < 0 )
cv::gpu::morphologyEx(src, dst, CV_MOP_OPEN, element);
else
cv::gpu::morphologyEx(src, dst, CV_MOP_CLOSE, element);
dst.download(temp);
disp = temp;
// cvShowImage("Open/Close",&disp);
}
// callback function for erode/dilate trackbar
void ErodeDilate(int)
{
IplImage disp;
Mat temp;
int n = erode_dilate_pos - max_iters;
int an = n > 0 ? n : -n;
Mat element = getStructuringElement(element_shape, Size(an*2+1, an*2+1), Point(an, an) );
if( n < 0 )
cv::gpu::erode(src, dst, element);
else
cv::gpu::dilate(src, dst, element);
dst.download(temp);
disp = temp;
cvShowImage("Erode/Dilate",&disp);
}
int main( int argc, char** argv )
{
VideoCapture capture("TwoManLoiter.avi");
//create windows for output images
namedWindow("Open/Close",1);
namedWindow("Erode/Dilate",1);
open_close_pos = 3;
erode_dilate_pos = 0;
createTrackbar("iterations", "Open/Close",&open_close_pos,max_iters*2+1,NULL);
createTrackbar("iterations", "Erode/Dilate",&erode_dilate_pos,max_iters*2+1,NULL);
for(;;)
{
capture >> cpuSrc;
src.upload(cpuSrc);
GpuMat grey;
cv::gpu::cvtColor(src, grey, CV_BGR2GRAY);
src = grey;
int c;
ErodeDilate(erode_dilate_pos);
c = cvWaitKey(25);
if( (char)c == 27 )
break;
}
return 0;
}
The CPU implementation is the same minus using namespace cv::gpu and the Mat instead of GpuMat of course.
Thanks
A: My guess would be, that the performance gain from the GPU erode/dilate is overweighted by the memory operations of transferring the image to and from the GPU every frame. Keep in mind that memory bandwidth is a crucial factor in GPGPU algorithms, and even more the bandwidth between CPU and GPU.
EDIT: To optimize it you might write your own image display routine (instead of cvShowImage) that uses OpenGL and just displays the image as an OpenGL texture. In this case you don't need to read the processed image from the GPU back to CPU and you can directly use an OpenGL texture/buffer as a CUDA image/buffer, so you don't even need to copy the image inside the GPU. But in this case you might have to manage CUDA resources yourself. With this method you might also use PBOs to upload the video into the texture and profit a bit from asynchronity.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526786",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Is there any any way to compile & run program as big-endian on little endian pc? see i have written one program for big endian now i dont have big endian machine but i want to check whether my program will works correctly or not on big endian so how can i check that on my little endian pc.?
Is there any online virtual big-endian compiler ?
note : i have googled about this but did not get anything.
A: qemu can virtualize all sorts of architectures, amongst then big endian ones.
A: Qemu is useful as an emulator/virtualizer, i.e. for running the program, but you'll need something to compile it in the first place.
Once you have chosen a big-endian architecture supported by qemu, for example PowerPC, you'll need a cross-compiler which runs on your PC but produces binaries for this architecture (e.g. PowerPC).
If you're very lucky, your distribution contains some binaries. However, in most cases, you might be forced to compile binutils, glibc and gcc yourself.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526787",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Is it possible to use agile scrum with TFS? We're using TFS Work Items to manage our bugs and work items.
Would that be possible to use TFS for agile scrum project management? e.g. defining user stores, drawing burn down chart and cumulative chart, etc?
How?
Thanks
A: Absolutely yes.
Generate a new Team Project choosing the default process template (MSF for Agile Software Development 5.0) during the Wizard execution.
Now within this new Team Project a great deal of ready-baked reports is available, 'agile' work-item type User Story as well. Out-of-the-box sprint planning is also quite nicely delivered.
With a small time-investment for orientation, customizing & tailoring to your own needs should be possible.
A very comprehensive presentation by A.Bjork was really helpful for me.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: backbone.js: how to inline editing on attribute of a model how would i add inline editing on attributes of a model,
for example, when i have a Player model
var Player = Backbone.Model.extend({
defaults: {
id: 0,
name: '',
points: 0
},
initialize: function(){
// irrelevant stuff happening here...
},
rename: function(newName){
this.set({ name: newName });
}
});
and a playerRow view
var PlayerRow = Backbone.View.extend({
tagName: 'li',
className: 'player',
events: {
'click span.score': 'score',
'blur input.name': 'rename',
'click div.playername': 'renderRename'
},
initialize: function(){
_.bindAll(this, 'render', 'rename');
this.model.bind('change', this.render);
},
render: function(){
var template = Tmpl.render("playerRow", { model : this.model });
$(this.el).html(template);
return this;
},
renderRename: function() {
// i was thinking of switching the DOM into a textfield here
},
rename: function(){
var inpt = $(this.el).find('input.name');
var newName = (inpt.val() != '') ? inpt.val() : 'no-name';
this.model.rename(newName);
}
});
and my playerRow template
<script type="text/template" id="playerRow-template">
<% if ( model.get('name') == '' ) { %>
<div class="state-edit"><input type="text" class="name" name="name"></input></div>
<% } else { %>
<div class="playername"><%= model.get('name') %></div>
<% } %>
</script>
either i set a certain property of my model that holds the state (default or edit), which triggers a re-render and in my template instead of testing if name == '' i can test on that state property.
or i do it inline like i say in my comment in renderRename i just swap the DOM into an input field but i think this is a bad way to do it. Would this cause troubles with the already bound events? like 'blur input.name': 'rename'
i doubt creating a new view for the edit is the best way, because i want inline editing, for just this one name field, i don't want all the rest of the player template to be duplicate in the player template and the editplayer template.
so, bottomline, my question:
what is the best way, to handle inline editing
*
*a separate view
*inline just appending an input field (don't know if this works well with the bound events)
*having my model hold a state variable for this attribute (would work but sounds weird to have a model hold view related data)
A: A different option altogether:
Inline edititing making use of the html EditableContent feature. No need for changing/cluttering the DOM, great user experience if done correctly, supported in all major browsers.
A couple of js-editors make use of this, most notably Aloha Editor (check for browser support), but for attribute editing without needing much else (e.g rich text editing etc) you can easily roll your own.
EDIT: June 2012:
Rolling your own becomes much easier when using the excellent range Library:
http://code.google.com/p/rangy/
Hth,
Geert-Jan
A: I like to have an extra input field in the view that is hidden by default. (This is closest to your option (2), but it avoids conditionals in the template or adding elements on-the-fly.)
So the template might look something like this:
<div class="show-state">
... <%= name %> ...
<input type="button" value="edit"/>
</div>
<div class="edit-state"> <!-- hidden with display: none in CSS -->
... <input type="text" value="<%= name %>"/> ...
</div>
Essentially, it's a view with two states, "showing" and "editing". When the user clicks "edit", I call this.$('.show-state').hide(); this.$('.edit-state').show(); to flip the state.
Once the edit gets submitted or canceled, I just have the view rerender itself (after talking to the server and updating the model's attributes if necessary) to revert to the original "show" state and reset the input field.
P.S. Keep in mind that my code enables XSS because it does not escape name.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526799",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Simple jquery and php problem Does anyone know why this doesn't work? any help would be appreciated.
This is the HTML
Enter Code:<br/><input type="text" name="code" id="code"/><br/>
<input type="button" id="confirm" value="Confirm" onClick="confirm()"/>
This is the PHP (basically gets the value of the user input and if it's equal to the variable a echo sucess)
$code = $_POST["code"];
$a = 105678;
if($code==$a){
echo "sucess";
} else {
echo "nosucces";
}
The JavaScript (simple ajax code to alert yay on PHP sucess or nay on no sucess)
function confirm () {
$.post(
"confirm.php",
{code:$(this).val() },
function(data) {
if(data=='sucess') {
alert("yay");
} else {
alert("nay");
}
}
);
}
basically on all occasions the ouput is nay on further debugging i tried an elseif statement on the javascript asking if data is equal to nosucces but it didn't even alert anything, meaning it's not getting the data from the php
A: $(document).ready(function() {
$('#confirm').click(function() {
$.post("",{code:$('#code').val() } ,function(data)
{
if(data=='sucess')
{
alert("yay");
}
else
{alert("nay");}
});
});
});
A: Give brackets at end, so that it does understand that you are calling a function, also don't use confirm as function name, its a native JS function, use my_confirm instead.
onClick="my_confirm()"
Also $(this).val() won't work in your case use $('#code').val() instead.
A: $(document).ready(function() {
$('#confirm').click(function() {
$.ajax({
url: "confirm.php",
type: "POST",
data: "code="+$('input[name="code"]').val(),
dataType: "text",
async:false,
success: function(msg){
if(msg=='sucess'){
alert('yay');
}else{
alert('nay');
}
}
});
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526800",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Extracting values from a string in C# I have the following string which i would like to retrieve some values from:
============================
Control 127232:
map #;-
============================
Control 127235:
map $;NULL
============================
Control 127236:
I want to take only the Control . Hence is there a way to retrieve from that string above into an array containing like [127232, 127235, 127236]?
A: One way of achieving this is with regular expressions, which does introduce some complexity but will give the answer you want with a little LINQ for good measure.
Start with a regular expression to capture, within a group, the data you want:
var regex = new Regex(@"Control\s+(\d+):");
This will look for the literal string "Control" followed by one or more whitespace characters, followed by one or more numbers (within a capture group) followed by a literal string ":".
Then capture matches from your input using the regular expression defined above:
var matches = regex.Matches(inputString);
Then, using a bit of LINQ you can turn this to an array
var arr = matches.OfType<Match>()
.Select(m => long.Parse(m.Groups[1].Value))
.ToArray();
now arr is an array of long's containing just the numbers.
Live example here: http://rextester.com/rundotnet?code=ZCMH97137
A: try this (assuming your string is named s and each line is made with \n):
List<string> ret = new List<string>();
foreach (string t in s.Split('\n').Where(p => p.StartsWith("Control")))
ret.Add(t.Replace("Control ", "").Replace(":", ""));
ret.Add(...) part is not elegant, but works...
EDITED:
If you want an array use string[] arr = ret.ToArray();
SYNOPSYS:
I see you're really a newbie, so I try to explain:
*
*s.Split('\n') creates a string[] (every line in your string)
*.Where(...) part extracts from the array only strings starting with Control
*foreach part navigates through returned array taking one string at a time
*t.Replace(..) cuts unwanted string out
*ret.Add(...) finally adds searched items into returning list
A: Off the top of my head try this (it's quick and dirty), assuming the text you want to search is in the variable 'text':
List<string> numbers = System.Text.RegularExpressions.Regex.Split(text, "[^\\d+]").ToList();
numbers.RemoveAll(item => item == "");
The first line splits out all the numbers into separate items in a list, it also splits out lots of empty strings, the second line removes the empty strings leaving you with a list of the three numbers. if you want to convert that back to an array just add the following line to the end:
var numberArray = numbers.ToArray();
A: Yes, the way exists. I can't recall a simple way for It, but string is to be parsed for extracting this values. Algorithm of it is next:
*
*Find a word "Control" in string and its end
*Find a group of digits after the word
*Extract number by int.parse or TryParse
*If not the end of the string - goto to step one
realizing of this algorithm is almost primitive..)
This is simplest implementation (your string is str):
int i, number, index = 0;
while ((index = str.IndexOf(':', index)) != -1)
{
i = index - 1;
while (i >= 0 && char.IsDigit(str[i])) i--;
if (++i < index)
{
number = int.Parse(str.Substring(i, index - i));
Console.WriteLine("Number: " + number);
}
index ++;
}
Using LINQ for such a little operation is doubtful.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526803",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: POST request with image from iPad/iPhone I try to POST images to server.
I have finished it successfully like this:
I have webView, catch "right" url and switch viewControllers.
After switch them I choose image from PhotoLibrary or from camera, POST it and switch controllers back.
P.S. As u know, in mobile safary(in webview too) all "choose" buttons on sites are disabled.
I think that it isn't straightforward way, so..
My question:
Can I choose images from webview's button "choose"? I want to choose images on iDevices similar PC without another viewControllers.
I'm newbie in programming, but I have some ideas(don't know how to realize them):
1.Upload image to DOM. And use "save" button on webView.
2.Add button with selector(can I?) to webView with Javascript. And handle this selector.(smth like that) I saw similar thing for toolbar item.
A: *
*Get the image. Convert in to a base64 string (http://stackoverflow.com/questions/3889478/uiimage-to-base64-string-encoding)
*Put this string inside the value of a hidden input.
*Submit the form.
*On the server convert the base64 back to binary and save to file/DB.
(PS. File inputs are not supported in iOS safari. The choose button is just there as a placeholder, to not break any layouts. There is absolutely no code behind the element, so there is no way try to get it to work.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526804",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: NHibernate: Problem trying to save an entity containing collections I need some help.
I'm just starting out with NHibernate and I'm using Fluent for mappings. Everything seemed to work fine until today.
Here is the story:
I have two tables in my db: Store and WorkDay
The first table contains info about the store, and the WorkDay table contains info about the days of week and start/end time when the store is open.
Store contains a Guid StoreID PK column that is referenced in the WorkDay table.
So I have a mapping file for Store where I have a HasMany association with the WorkDay table, and a corresponding POCO for Store.
Now, when I fill in all the necessary data and try to persist it to database, I get an exception telling me that the insert into table WorkDay failed because the StoreID had null value and the table constraint doesn't allow nulls for that column (which is, of course, expected behavior).
I understand the reason for this exception, but I don't know how to solve it.
The reason why the insert fails is because the StoreID gets generated upon insert, but the [b]WorkDay[/b] collection gets saved first, in the time when the StoreID hasn't yet been generated!
So, how do I force NHibernate to generate this ID to pass it to dependent tables? Or is there another solution for this?
Thank you!
Here's the code for StoreMap
public class StoreMap : ClassMap<Store> {
public StoreMap() {
Id(x => x.StoreID)
.GeneratedBy.GuidComb();
Map(x => x.City);
Map(x => x.Description);
Map(x => x.Email);
Map(x => x.Fax);
Map(x => x.ImageData).CustomType("BinaryBlob");
Map(x => x.ImageMimeType);
Map(x => x.Name);
Map(x => x.Phone);
Map(x => x.Street);
Map(x => x.Zip);
HasMany(x => x.WorkDays)
.Inverse().KeyColumn("StoreID").ForeignKeyCascadeOnDelete()
.Cascade.All();
}
}
and this is for the WorkDayMap
public class WorkDayMap : ClassMap<WorkDay>{
public WorkDayMap() {
Id(x => x.WorkDayID)
.GeneratedBy.Identity();
Map(x => x.TimeOpen);
Map(x => x.TimeClose);
References(x => x.Store).Column("StoreID");
References(x => x.Day).Column("DayID");
}
}
A: NHibernate shouldn't insert the WorkDay first, so there must be an error in your code. Make sure you do all of the following:
*
*Add all WorkDay objects to the WorkDays collection.
*Set the Store property on all WorkDay objects to the parent object.
*Call session.Save() for the Store but not for the WorkDay objects.
edit: You should also note that ForeignKeyCascadeOnDelete() won't change anything at runtime. This is just an attribute for the hbm2ddl tool. If you want NHibernate to delete removed entries, use Cascade.AllDeleteOrphan().
A: It probably inserts the Workday before the Store because the first has an identity generator. This forces NH to execute an INSERT statement to generate the ID. guid.comb is generated in memory, NH doesn't need the database.
NH tries to access the db at the latest possible point in time, to avoid unnecessary updates and to make use of batches. Workday is inserted when you call session.Save, Store is inserted when it flushes the session next time (eg. on commit).
You shouldn't use the identity generator (unless you are forced to use it). It is bad for performance anyway.
If it still doesn't work, you probably need to remove the not-null constraint on the foreign key. NH can't resolve it every time. There is some smart algorithm which is also able to cope with recursive references. But there are sometimes cases where it sets a foreign key to null and updates it later even if there would be a solution to avoid it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526806",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to make php curl request wait forever for the response (after successfully sending the request) I am trying to send big zip files to a tomcat application using curl in a php script. Since it is a big zip file it is going to take some time on the tomcat server to unpack the zip file (about 2-5 minutes), but the curl request never waits more than 30 seconds before it just continue as if it had received an empty response.
Code I can reproduce problem with:
set_time_limit(0);
$uploadURL = 'http://192.168.0.2:8080/some/url/'
$userid = 'a-user';
$password = 'a-password';
$zipfile = '/tmp/myfile.zip';
$ch = curl_init($uploadURL);
curl_setopt($ch, CURLOPT_HEADER, array(
'Connection: Keep-Alive',
'Keep-Alive: 3600'
));
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
curl_setopt($ch, CURLOPT_USERPWD, $userid.":".$password);
curl_setopt($ch, CURLOPT_POST, true);
$post = array(
"uploadMode" => "uploadOnly",
"id" => $id,
"numberOfFiles" => "1",
"file"=>"@".$zipfile.";type=application/zip"
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 45);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_TIMEOUT, 200);
$response = curl_exec($ch);
The only suspect I have left is that curl makes the request and then times out due to a certain number of seconds elapsing without any bytes being sent back or forth (aka between_bytes_timeout). But I cannot find a curl option to help with that, so I am hoping it is something else.
The tomcat server is in the clear, since I can make a request to it with my browser that can lasts hours without problems.
A: Chances are, that cURL just auto-cancels the request, because of the transfer rate being too low while your Tomcat is unpacking the zip.
This happens if the average transfer rate drops below CURLOPT_LOW_SPEED_LIMIT bytes/second for CURLOPT_LOW_SPEED_TIME seconds.
Try adding the appropriate options with a high time and/or low limit, e.g.:
curl_setopt($ch, CURLOPT_LOW_SPEED_LIMIT, 1); // cancel if below 1 byte/second
curl_setopt($ch, CURLOPT_LOW_SPEED_TIME, 30); // for a period of 30 seconds
To quicktest I'd recommend to use a TIME slightly higher than your Tomcat really needs to unpack a given test zip.
A: For setting request headers, use CURLOPT_HTTPHEADER not CURLOPT_HEADER.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526808",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Is there any free online maven repository? Is there any free online private maven2 or maven3 repository? So that team can access the repository from various region.
A: I just found a free repo for personal projects. Might not be suitable for team work and/or professional use though. Note that it seems to be from Russia. I am not connected in any kind to that project so I have no idea about the privacy of the data posted there. But it seems to work ok.
https://mymavenrepo.com
I have not tried but there is also
https://bintray.com/
This one might have a better reputation :)
A: We use https://repsy.io in one of our project. It's straight simple and convenient with 1GB free limit.
A: Update: GitHub launches the Package feature in Beta which supports the Maven: https://github.com/features/package-registry
Update: the Deveo has been acquired by Perforce, see this link
As of September 12, Deveo is now Helix TeamHub. The new name and branding represent our new, integrated solution from Deveo and Perforce.
Helix TeamHub can be hosted in our cloud or on your own servers with Helix TeamHub Enterprise, powered by Helix4Git.
Have you tried Deveo, I am using this cloud service and has 1G storage for free. You can deploy the Maven repository on it.
New features in Deveo 3.17
Pull requests between repositories
Maven and Ivy repositories
Deadlines for issues
Emojis
A: I recently wrote a lightweight Google App-Engine application to host my private repositories, backed by Google Cloud Storage (which is multi-regional per default):
https://github.com/renaudcerrato/appengine-maven-repository
Thanks to Google App-Engine free quotas, and depending on the scale needed, you won't have to pay anything.
A: If you use github, you could use a private github project as your maven repository. There are instruction on how to publish your maven artifacts to github here: https://stackoverflow.com/a/14013645/82156
A: we can use dropbox for online maven repository. But it is not completely private. you can use it if it gives you enough privacy.
This is the instruction to create free maven online maven repository on dropbox
*
*Create an account on dropbox
*Download and install dropbox client
*After you install dropbox client, A folder called "Dropbox" will create in Users folder. There is a public folder in it. Create a sub folder in public folder and copy the url of that sub folder(ex: C:\Users\Lakshman\Dropbox\Public\repository)
*Execute the following command to deploy the project artifacts to this path
mvn deploy -DskipTests=true -DaltDeploymentRepository=dropbox::default::file:///C:/Users/Lakshman/Dropbox/Public/repository
*you can use this in your pom file to the above task
<distributionManagement>
<repository>
<id>dropbox.repo</id>
<url>file:///C:/Users/Lakshman/Dropbox/Public/repository</url>
</repository>
</distributionManagement>
if you have sync your local folder with dropbox it will automatically upload artifacts to online repository. you can get the link by login to Dropbox and go to public folder and click copy public link.
This solution got from here and referenced this also.
A: For this purpose you could use a SVN repository. Some of them are available for private usage for free. Take a look on Maven: Commit single artifact to svn repository
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526814",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "32"
} |
Q: Use of "instanceof" in Java
What is the 'instanceof' operator used for?
I learned that Java has the instanceof operator. Can you elaborate where it is used and what are its advantages?
A: instanceof is used to check if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.
Read more from the Oracle language definition here.
A: instanceof can be used to determine the actual type of an object:
class A { }
class C extends A { }
class D extends A { }
public static void testInstance(){
A c = new C();
A d = new D();
Assert.assertTrue(c instanceof A && d instanceof A);
Assert.assertTrue(c instanceof C && d instanceof D);
Assert.assertFalse(c instanceof D);
Assert.assertFalse(d instanceof C);
}
A: Basically, you check if an object is an instance of a specific class.
You normally use it, when you have a reference or parameter to an object that is of a super class or interface type and need to know whether the actual object has some other type (normally more concrete).
Example:
public void doSomething(Number param) {
if( param instanceof Double) {
System.out.println("param is a Double");
}
else if( param instanceof Integer) {
System.out.println("param is an Integer");
}
if( param instanceof Comparable) {
//subclasses of Number like Double etc. implement Comparable
//other subclasses might not -> you could pass Number instances that don't implement that interface
System.out.println("param is comparable");
}
}
Note that if you have to use that operator very often it is generally a hint that your design has some flaws. So in a well designed application you should have to use that operator as little as possible (of course there are exceptions to that general rule).
A: instanceof is a keyword that can be used to test if an object is of a specified type.
Example :
public class MainClass {
public static void main(String[] a) {
String s = "Hello";
int i = 0;
String g;
if (s instanceof java.lang.String) {
// This is going to be printed
System.out.println("s is a String");
}
if (i instanceof Integer) {
// This is going to be printed as autoboxing will happen (int -> Integer)
System.out.println("i is an Integer");
}
if (g instanceof java.lang.String) {
// This case is not going to happen because g is not initialized and
// therefore is null and instanceof returns false for null.
System.out.println("g is a String");
}
}
Here is my source.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526817",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "312"
} |
Q: gtk PrintSettings default values? How can I get default print values (default printer, paper size), BEFORE running PrintOperation.run() ?
Thanks.
A: Seems this is not possible. Only way is to set up PrintSettings and PageSetup in advance and create a new PrintOperation for each call to run, and save PrintSettings after each of them.
A: Is it this you are looking for ?
http://www.pygtk.org/docs/pygtk/class-gtkprintsettings.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526818",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ChannelFactory and CreateChannel() open once or on each use I am having use of the channel in some back worker thread .
The usage is once per two seconds and the connection is always to the same server.
What is the best approach will be:
A. Open channel once as the application starts and work with it during whole application life?
It can be several weeks at least.
B . Contract Channel Factory once and on each run of my worker thread open channel and at the end close it.
Thanks for ideas .
A: ChannelFactory is a perfect candidate for caching and reusing. So creating a static ChannelFactory is perfectly acceptable. On the other hand, channels may have timeouts, they may get into a corrupted state etc. So if you are willing to take care of all those side issues you can also cache the channels but in my experience, creating channels per communication is so cheap that it is a good practice to use a channel per communication.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526824",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Can we add symbolic parameters in PDS members used in cataloged procedures? I have JCL, which is executing one catalog procedure.
In catalog procesdure one COBOL-DB2 pgm is being executed.
Below is my JCL
//A JOB (@),'CALL DB2',NOTIFY=&SYSUID
//JS010 EXEC TESTPROC
Below is my TESTPROC
//TESTPROC
//PS010 EXEC PGM=IKJEFT01,,DYNAMNBR=20
//STEPLIB DD DSN=TEST.LOADLIB,DISP=SHR
//SYSTSPRT DD SYSOUT=*
//SYSPRINT DD SYSOUT=*
//SYSUDUMP DD SYSOUT=*
//SYSTSIN DD DSN=TEST.PDS(TESTPGM),
// DISP=SHR
//SYSOUT DD SYSOUT=*
below is my SYSTIN data --TESTPGM
DSN SYSTEM(TEST)
RUN PROGRAM(TESTPGM) PLAN(TESTPLAN)
END
My query is can I use symbolic parameters in place of TESTPGM and TESTPLAN in SYSTIN data member TESTPGM?
Regards,
Saisha :)
A: As mentioned below you could have the PDS Member name become a symbolic value and then define each member in the PDS to point to a different program. Using your JCL as an example:
//TESTPROC PROC MYPGM=
//PS010 EXEC PGM=IKJEFT01,,DYNAMNBR=20
//STEPLIB DD DSN=TEST.LOADLIB,DISP=SHR
//SYSTSPRT DD SYSOUT=*
//SYSPRINT DD SYSOUT=*
//SYSUDUMP DD SYSOUT=*
//SYSTSIN DD DSN=TEST.PDS(&MYPGM),
// DISP=SHR
//SYSOUT DD SYSOUT=*
In the above example your EXEC statement would envoke the proc as:
//JS010 EXEC TESTPROC,MYPGM=TESTPGM
Another option, you could over-ride the SYSTSIN DD directly as follows:
//A JOB (@),'CALL DB2',NOTIFY=&SYSUID
//JS010 EXEC TESTPROC
//PS010.SYSTSIN DD *
DSN SYSTEM(TEST)
RUN PROGRAM(TESTPGM) PLAN(TESTPLAN)
END
/*
//
One other suggestion...
In your final implementation you might want to consider separating the
DSN SYSTEM(TEST)
from the
RUN PROGRAM(TESTPGM) PLAN(TESTPLAN)
END
The reason is that you may find you want to run the program in multiple DB2 environments, not just SYSTEM(TEST). To do this, simply add another parameter DB2SYS= and modify as follows:
//TESTPROC PROC DB2SYS=MYTEST,MYPGM=
...
//SYSTSIN DD DSN=TEST.PDS(&DB2SYS),DISP=SHR
// DD DSN=TEST.PDS(&MYPGM),DISP=SHR
where PDS Member MYTEST has the DSN SYSTEM(TEST) statement already coded.
A: The short answer is no. If you have symbolic parameters in the control cards in the PDS your SYSTSIN DD statement references, they (the symbolic parameters) will not be resolved.
One way around this is to have a separate program, executing in a separate step within your procedure prior to your PS010 step, that takes in parameters and text and writes a temporary file. The symbolic parameters will be resolved in that program's PARM=.
//PS001 EXEC PGM=LOADPARM,PARM='DSN SYSTEM(&DSNSYS)'
//SYSPRINT DD SYSOUT=*
//OUTPUT01 DD DISP=(,PASS),
// DSN=&&DSNSYS,
// AVGREC=U,
// LRECL=80,
// RECFM=FB,
// SPACE=(80,1)
//****
The hypothetical program LOADPARM would simply take its input parm and write it to OUTPUT01, being careful to pad it on the right with blanks. In PS010 you would then have a SYSTSIN that looks like...
//SYSTSIN DD DISP=(OLD,DELETE),DSN=&&DSNSYS
// DD DISP=SHR,DSN=TEST.PDS(TESTPGM)
...where the TESTPGM member looks like...
RUN PROGRAM(TESTPGM) PLAN(TESTPLAN)
END
In this manner, your cataloged procedure is ignorant of which DB2 subsystem it is accessing. That information is supplied in the execution JCL with the DSNSYS symbolic parameter.
There are other ways to approach this problem, for instance you could have a symbolic parameter that resolves to a known member in a shared PDS, having one member per DB2 subsystem.
A: Nope, we cant use the symbolic parameters inside SYSTSIN. Instead of bifurcating the SYSTSIN card into two and generalizing the DB2 subsytem i prefer to maintain separate test datacards with symbolic parameter for that member name and switch it whenever needed.
But the automating the DB2 subsystem may not result desired values all the times. Anyhow thats good effort made.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526832",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: SQL Find next Date for each Customer, SQL For each? I have some problems with an SQL statement. I need to find the next DeliveryDate for each Customer in the following setup.
Tables
*
*Customer (id)
*DeliveryOrder (id, deliveryDate)
*DeliveryOrderCustomer (customerId, deliveryOrderId)
Each Customer may have several DeliveryOrders on the same deliveryDate. I just can't figure out how to only get one deliveryDate for each customer. The date should be the next upcoming DeliveryDate after today. I feel like I would need some sort of "for each" here but I don't know how to solve it in SQL.
A: This would give the expected results using a subselect. Take into account that current_date may be rdbms specific, it works for Oracle.
select c.id, o.date
from customer c
inner join deliveryordercustomer co o on co.customerId = c.id
inner join deliveryorder o on co.deliveryOrderId = o.id
where o.date =
(select min(o2.date)
from deliveryorder o2
where o2.id = co.deliveryOrderId and o2.date > current_date)
A: You need to use a group by. There's a lot of ways to do this, here's my solution that takes into account multiple orders on same day for customer, and allows you to query different delivery slots, first, second etc. This assumes Sql Server 2005 and above.
;with CustomerDeliveries as
(
Select c.id, do.deliveryDate, Rank()
over (Partition BY c.id order by do.deliveryDate) as DeliverySlot
From Customer c
inner join DeliveryOrderCustomer doc on c.id = doc.customerId
inner join DeliveryOrder do on do.id = doc.deliveryOrderId
Where do.deliveryDate>GETDATE()
Group By c.id, do.deliveryDate
)
Select id, deliveryDate
From CustomerDeliveries
Where DeliverySlot = 1
A: Another simpler version
select c.id, min(o.date)
from customer c
inner join deliveryordercustomer co o on co.customerId = c.id
inner join deliveryorder o on co.deliveryOrderId = o.id and o.date>getdate()
group by c.id
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Java: Watching a Directory for Changes I want to create a listener to detect directory change recursively (the main directory and its subdirectories). After a web search I found this link that explains the use of the class WatchService from the Package java.nio.file that api exactly meets my needs but unfortunately it is only available in Java 7!
Then I return to search again in order to find a framework that allows the same and is compatible java 5 and java 6 but again there was a problem, because recursion is available for Windows and my application should use Linux!!
Can you offer me a solution: another framework, a way to do..
A: I think you did a good discovery job and found a wonderful library jpathwatch. I do not understand what was your problem with recursion: I have not seen any restriction for linux in this library documentation.
But if for some reason jpathwatch cannot help you on linux, it is not a problem: you can run du command yourself. See this reference: http://linux.about.com/library/cmd/blcmdl1_du.htm
If I were you I probably do the following: write simple script that runs du in loop. Then run this script from java from separate thread that is contiguously reading the script's output and analyses it.
A: This is a kind of functionality that requires support of JVM or a native library, such as the one you've found for Windows. If you can't find anything in Java for Linux, I suggest asking for a binary Linux library (in a different question) and then build a Java native class on top of that.
I hope other people will help you better.
A: To do this on Linux you need to use Java 7, or a native library that uses inotify. Have you considered the JNotify library? It looks like it handles recursion into subdirectories, including newly created ones.
A: Have a look at http://download.oracle.com/javase/tutorial/essential/io/notification.html
"The java.nio.file package provides a file change notification API, called the Watch Service API. This API enables you to register a directory (or directories) with the watch service. When registering, you tell the service which types of events you are interested in: file creation, file deletion, or file modification. When the service detects an event of interest, it is forwarded to the registered process. The registered process has a thread (or a pool of threads) dedicated to watching for any events it has registered for. When an event comes in, it is handled as needed."
Update: Ooops, just realized you already saw this. I didn't realize this was only in Java 7 :-(
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526840",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Keeping address space size to 4 GB in 64 bit I want to keep some applications to run with a 4 GB address space within a 64 bit OS running on a 64 bit processor (x86 xeon, 8 core). I know there is an option to compile with -m32 option, but at this moment the computer I'm working with, doesn't have the required support for compiling with -m32, so I can't use it, neither I can install anything on that computer as I don't have any rights.
Now my question is if there is any possibility to restrict address space to 4 GB. Please don't ask me why I want to do so, just tell me how if that is possible. Thanks.
A: You could try using setrlimit to impose a virtual memory limit on the process during its initialization, via the RLIMIT_AS attribute. I have used setrlimit to increase resource allocations to a user space process before, but I don't see why it wouldn't work in the other direction as well.
A: The ulimit/setrlimit mechanism, accessible in bash via ulimit, can do this with minor drawbacks.
ulimit -v 4000000
should limit the memory available to the current process group to 4 GB.
However, it limits the total size of your address space mappings, and does not limit your mappings' offset
- you still may have pointers larger than 2^32.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526842",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I change this code to handle recurringpayment? I am trying to implement Direct payment method as I have user's credit card information etc in my database. This is the sample that I am referring:
using System;
using System.Collections.Generic;
using System.Text;
using com.paypal.sdk.services;
using com.paypal.sdk.profiles;
using com.paypal.sdk.util;
using com.paypal.soap.api;
namespace ASPDotNetSamples
{
public class DoDirectPayment
{
public DoDirectPayment()
{
}
public string DoDirectPaymentCode(string paymentAction, string amount, string creditCardType, string creditCardNumber, string expdate_month, string cvv2Number, string firstName, string lastName, string address1, string city, string state, string zip, string countryCode, string currencyCode)
{
com.paypal.soap.api.DoDirectPaymentReq req = new com.paypal.soap.api.DoDirectPaymentReq();
NVPCallerServices caller = new NVPCallerServices();
IAPIProfile profile = ProfileFactory.createSignatureAPIProfile();
/*
WARNING: Do not embed plaintext credentials in your application code.
Doing so is insecure and against best practices.
Your API credentials must be handled securely. Please consider
encrypting them for use in any production environment, and ensure
that only authorized individuals may view or modify them.
*/
// Set up your API credentials, PayPal end point, API operation and version.
profile.APIUsername = "sdk-three_api1.sdk.com";
profile.APIPassword = "QFZCWN5HZM8VBG7Q";
profile.APISignature = "AVGidzoSQiGWu.lGj3z15HLczXaaAcK6imHawrjefqgclVwBe8imgCHZ";
profile.Environment = "sandbox";
caller.APIProfile = profile;
NVPCodec encoder = new NVPCodec();
encoder["VERSION"] = "51.0";
encoder["METHOD"] = "DoDirectPayment";
// Add request-specific fields to the request.
encoder["PAYMENTACTION"] = paymentAction;
encoder["AMT"] = amount;
encoder["CREDITCARDTYPE"] = creditCardType;
encoder["ACCT"] = creditCardNumber;
encoder["EXPDATE"] = expdate_month;
encoder["CVV2"] = cvv2Number;
encoder["FIRSTNAME"] = firstName;
encoder["LASTNAME"] = lastName;
encoder["STREET"] = address1;
encoder["CITY"] = city;
encoder["STATE"] = state;
encoder["ZIP"] = zip;
encoder["COUNTRYCODE"] = countryCode;
encoder["CURRENCYCODE"] = currencyCode;
// Execute the API operation and obtain the response.
string pStrrequestforNvp = encoder.Encode();
string pStresponsenvp = caller.Call(pStrrequestforNvp);
NVPCodec decoder = new NVPCodec();
decoder.Decode(pStresponsenvp);
return decoder["ACK"];
}
}
}
This is the link:
https://cms.paypal.com/cms_content/US/en_US/files/developer/nvp_DoDirectPayment_cs.txt
This works fine but my only question is how do I handle recurringpayment with this? What changes should I make in the sample?
Thanks in advance :)
A: Check the PayPal API Reference.
There is a method named CreateRecurringPaymentsProfile
Also read Handling Recurring Payments
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I change a filename on-download with javascript? The script adds a download link for videos (on a specific site). How do I change the filename to something else while downloading?
Example URL:
"http://website.com/video.mp4"
Example of what I want the filename to be saved as during download:
"The_title_renamed_with_javascript.mp4"
A: You can't do this with client-side JavaScript, you need to set the response header...
.NET
Response.AddHeader("Content-Disposition", "inline;filename=myname.txt")
Or PHP
header('Content-Disposition: inline;filename=myname.txt')
Also available in other server-side languages of your choice.
A: The filename for downloading is set in the header (take a look at "Content-Disposition"), wich is created on server-side.
There's no way you could change that with pure javascript on a file you're linking to unless you have access to the server-side (that way you could pass an additional parameter giving the filename and change the server-side behaviour to set the header to match that... but that would also be possible with pure html, no need for javascript). Conclusion: Javascript is absolute useless to achive what you want.
A: This actually is possible with JavaScript, though browser support would be spotty. You can use XHR2 to download the file from the server to the browser as a Blob, create a URL to the Blob, create an anchor with its href property set to that URL, set the download property to whatever you want the filename to be, and then click the link. This works in Google Chrome, but I haven't verified support in other browsers.
window.URL = window.URL || window.webkitURL;
var xhr = new XMLHttpRequest(),
a = document.createElement('a'), file;
xhr.open('GET', 'someFile', true);
xhr.responseType = 'blob';
xhr.onload = function () {
file = new Blob([xhr.response], { type : 'application/octet-stream' });
a.href = window.URL.createObjectURL(file);
a.download = 'someName.gif'; // Set to whatever file name you want
// Now just click the link you created
// Note that you may have to append the a element to the body somewhere
// for this to work in Firefox
a.click();
};
xhr.send();
A: You can probably do this with a Chrome userscript, but it cannot be done (yet) with Greasemonkey (Firefox) javascript.
Workaround methods (easiest to hardest):
*
*Add the links with Greasemonkey but use the excellent DownThemAll! add-on to download and rename the videos.
*Download the videos as-is and use a batch file, shell-script, Python program, etc. to rename them.
*Use Greasemonkey's GM_xmlhttpRequest()Doc function to send the files to your own web application on a server you control.
This server could be your own PC running XAMPP (or similar).
*Write your own Firefox add-on, instead of a Greasemonkey script. Add-ons have the required privileges, Greasemonkey does not.
A: AFAIK, you will not be able to do this right from the client itself. You could first upload the file onto the server with the desired name, and then serve it back up to the end user (in which case your file name would be used).
A: Just in case you are looking for such a solution for your nasty downloading chrome extension, you should look into chrome.downloads API, it needs additional permission ('downloads') and allows you to specify filename. https://developer.chrome.com/extensions/downloads
However there is a problem I'm facing right now. The chrome extension I'm refactoring has 600k+ user base and adding a new permission would disable the extension for all of them. So it is no-go solution for me, but if you are developing a new extension you definitely should use it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526849",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: How does UIWebview do its rendering in iOS? I have been using UIWebView to render file formats such as Keynote, Pages, Numbers, PPT, etc. Also, I tried accessing the various document attributes via stringByEvaluatingJavaScriptFromString: such as title, width, height, innerHTML, etc. and web view returns valid values for these.
So, my question is, how does UIWebView actually work? Does it convert everything to HTML before rendering? How does it return attributes such as innerHTML for non-html files?
A: It would be crazy for Apple to convert most formats to HTM.
A: The various formats you listed are most likely rendered by Webkit plug-ins.
Check out the documentation at http://developer.apple.com/library/mac/#documentation/InternetWeb/Conceptual/WebKit_PluginProgTopic/WebKitPluginTopics.html. Plug-ins can also be written to allow Objective-C methods to be called from a scripting environment. It is possible that this would allow attributes such as innerHTML to be returned.
I have not actually developed any of these plug-ins but it does appear to allow UIWebView to be extended to render formats such as PPT and also to expose attributes. Based on this I do not believe that content is being converted to HTML but instead is custom drawn but exposes attributes such as width, height, etc through the plug-in.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Why do std::function instances have a default constructor? This is probably a philosophical question, but I ran into the following problem:
If you define an std::function, and you don't initialize it correctly, your application will crash, like this:
typedef std::function<void(void)> MyFunctionType;
MyFunctionType myFunction;
myFunction();
If the function is passed as an argument, like this:
void DoSomething (MyFunctionType myFunction)
{
myFunction();
}
Then, of course, it also crashes. This means that I am forced to add checking code like this:
void DoSomething (MyFunctionType myFunction)
{
if (!myFunction) return;
myFunction();
}
Requiring these checks gives me a flash-back to the old C days, where you also had to check all pointer arguments explicitly:
void DoSomething (Car *car, Person *person)
{
if (!car) return; // In real applications, this would be an assert of course
if (!person) return; // In real applications, this would be an assert of course
...
}
Luckily, we can use references in C++, which prevents me from writing these checks (assuming that the caller didn't pass the contents of a nullptr to the function:
void DoSomething (Car &car, Person &person)
{
// I can assume that car and person are valid
}
So, why do std::function instances have a default constructor? Without default constructor you wouldn't have to add checks, just like for other, normal arguments of a function.
And in those 'rare' cases where you want to pass an 'optional' std::function, you can still pass a pointer to it (or use boost::optional).
A: One of the most common use cases for std::function is to register callbacks, to be called when certain conditions are met. Allowing for uninitialized instances makes it possible to register callbacks only when needed, otherwise you would be forced to always pass at least some sort of no-op function.
A: The answer is probably historical: std::function is meant as a replacement for function pointers, and function pointers had the capability to be NULL. So, when you want to offer easy compatibility to function pointers, you need to offer an invalid state.
The identifiable invalid state is not really necessary since, as you mentioned, boost::optional does that job just fine. So I'd say that std::function's are just there for the sake of history.
A:
True, but this is also true for other types. E.g. if I want my class to have an optional Person, then I make my data member a Person-pointer. Why not do the same for std::functions? What is so special about std::function that it can have an 'invalid' state?
It does not have an "invalid" state. It is no more invalid than this:
std::vector<int> aVector;
aVector[0] = 5;
What you have is an empty function, just like aVector is an empty vector. The object is in a very well-defined state: the state of not having data.
Now, let's consider your "pointer to function" suggestion:
void CallbackRegistrar(..., std::function<void()> *pFunc);
How do you have to call that? Well, here's one thing you cannot do:
void CallbackFunc();
CallbackRegistrar(..., CallbackFunc);
That's not allowed because CallbackFunc is a function, while the parameter type is a std::function<void()>*. Those two are not convertible, so the compiler will complain. So in order to do the call, you have to do this:
void CallbackFunc();
CallbackRegistrar(..., new std::function<void()>(CallbackFunc));
You have just introduced new into the picture. You have allocated a resource; who is going to be responsible for it? CallbackRegistrar? Obviously, you might want to use some kind of smart pointer, so you clutter the interface even more with:
void CallbackRegistrar(..., std::shared_ptr<std::function<void()>> pFunc);
That's a lot of API annoyance and cruft, just to pass a function around. The simplest way to avoid this is to allow std::function to be empty. Just like we allow std::vector to be empty. Just like we allow std::string to be empty. Just like we allow std::shared_ptr to be empty. And so on.
To put it simply: std::function contains a function. It is a holder for a callable type. Therefore, there is the possibility that it contains no callable type.
A: Actually, your application should not crash.
§ 20.8.11.1 Class bad_function_call [func.wrap.badcall]
1/ An exception of type bad_function_call is thrown by function::operator() (20.8.11.2.4) when the function wrapper object has no target.
The behavior is perfectly specified.
A: There are cases where you cannot initialize everything at construction (for example, when a parameter depends on the effect on another construction that in turn depends on the effect on the first ...).
In this cases, you have necessarily to break the loop, admitting an identifiable invalid state to be corrected later.
So you construct the first as "null", construct the second element, and reassign the first.
You can, actually, avoid checks, if -where a function is used- you grant that inside the constructor of the object that embeds it, you will always return after a valid reassignment.
A: In the same way that you can add a nullstate to a functor type that doesn't have one, you can wrap a functor with a class that does not admit a nullstate. The former requires adding state, the latter does not require new state (only a restriction). Thus, while i don't know the rationale of the std::function design, it supports the most lean & mean usage, no matter what you want.
Cheers & hth.,
A: You just use std::function for callbacks, you can use a simple template helper function that forwards its arguments to the handler if it is not empty:
template <typename Callback, typename... Ts>
void SendNotification(const Callback & callback, Ts&&... vs)
{
if (callback)
{
callback(std::forward<Ts>(vs)...);
}
}
And use it in the following way:
std::function<void(int, double>> myHandler;
...
SendNotification(myHandler, 42, 3.15);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526853",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: How to codify and store dynamic permission constraints? I have been through this subject before, but haven't found a neat solution yet.
Say we have an application where customers can book a course using the website, and admin staff can also book courses on customers' behalf using a backend system. I'm trying to establish a way to let HR administrators codify constraints applied to permissions like can_make_booking, as the permission isn't just a boolean and shouldn't be hard-coded into the application.
At the moment, customers can make a booking as long as the course date is a date at least 'n' days standard notice in the future, they are booking no more than the number of places available and they are paying at least the amount due (or nil if their account is set to invoice). Managers can book using the backend application, as long as the appointment date is any time after now.
I envision something like this. Let HR administrators add permission constraints like the following:
role permission constraint
-------- ------------ ----------
customer make_booking 1
customer make_booking 2
customer make_booking 3
manager make_booking 5
Then a table of constraints,
constraint property operator value OR_parent
---------- ------------ -------- -------------------------- ---------
1 $course_date >= strtotime("+$notice days") NULL
2 $places_booked <= $places_available NULL
3 $paid >= $total NULL
4 $send_invoice == TRUE 3
5 $course_date >= strtotime("now") NULL
Chaining these constraints for the customer role would build something like the following evaled code (constraint #4 is paired with #3 as part of an OR sequence):
if($course_date >= strtotime("+$notice days") && $places_booked <= $places_available && ($paid >= $total || $send_invoice == TRUE)){
// make the booking
}
Each rule could be used independently at each stage, such as JavaScript and form validation, to give feedback if the booking can't be made for some reason.
However, say HR want to change the rule for customers so that they are only allowed to book 3 places at a time, and the $paid amount must be at least the $deposit amount? Ideally, I'd like to allow them to build these php rules dynamically, without giving them access to the hard-written code. The properties and values could be sanitized so that evaling code isn't a problem. I don't want to hard-code every combination of each rule as for some cases, there would be no clear way to guess an HR admin's logic in advance.
I've looked at the Zend_ACL version of assertions, but they don't seem to offer the dynamism I'm looking for. What would be a good way to implement these dynamic constraints? Any thoughts from other environments? Thanks!
Some more insight into the problem from a CUSEC presentation by Zed Shaw talking about why "the ACL is dead" - http://vimeo.com/2723800
A: Well, this is one of the areas that still elicit a rather big deal of discussion. As some say[who? - think it was Atwood among other people, but a link escapes me], an application that can do everything has already been made; it's called C. What you want to do borders quite nearly the 'too generalized' area, although I can see the value in not needing a programmer every time a business rule changes.
If I'd have to implement such a system, I guess I'd try and break it down into domains. You've done a relatively good job of it already with the second table. Just normalise that into separate domains that are used to compound business rules. You create a business rule which is comprised of 1 or many constraints OR-ed together. Each constraint needs a property that is restricted with an operator against a term. Terms can be tricky, since they can be anything from a property to a function, to a compound function. It's probably easiest to check your business rules to see what you need. Start with, say, properties, booleans and commonplace things like 'NOW'.
So the schema itself would, for example, be comprised of the rules, which contain multiple constraints (obvious benefit being that you could tie these to any [user group/offer/timespan/other domain] you want). These are, in turn, comprised of properties, which would compare with one of the operators (reference table mostly so you can enter custom descriptive names for non-programmers, but you may choose to enter a custom functions in it at some point) and, of course one of the terms. The last part being the most complex one, so you'd probably have to qualify it with an ID in term_types so you'd know whether you're comparing to another property or a function. You can also just VARCHAR it and create the field with PHP, which shouldn't be too difficult, given how you have all the options in properties and/or functions.
It's a very open-ended system (and there are probably better ways of going at it), so it's probably not worth doing unless you know that you'll need a high degree of dynamism in business rules.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526855",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: unable to connect to JSON service in android application of Titanium studio i am trying to do login application which takes id and password..when i click on logi button then it will connect to our local server by JSON..with the specified URL..the code is..
var loginReq = Titanium.Network.createHTTPClient();
loginReq.onload = function()
{
var json = this.responseText; alert(json);
var response = JSON.parse(json);
if (response.data.status == "success")
{ alert("Welcome ");
}
else
{ alert(response.data.status);
}
};
loginReq.onerror = function(event)
{
alert(event.toSource());
//alert("Network error");
};
loginBtn.addEventListener('click',function(e)
{ if (username.value != '' && password.value != '')
{
var url = 'our local url action=login&id='+username.value+'&pwd='+password.value;
loginReq.open("POST",url);
loginReq.send();
}
else
{
alert("Username/Password are required");
}
});
Here it is not connecting our URl..so it is entering into loginReq.onerror function...instead of loginReq.onload function..why it is throwing run time error.. The same code working fine with Iphone..
The Run Time Error is..
TypeError:Cannot call property toSource in object{'source':[Ti.Network.HttpClient],specified url} is not a function,it is a object.
This is wat the error..please let me Know...
A: Apparently the toSource() function does not exist in android, as it is an object. Try debugging and see what the object event contains.
You could do that by adding a line above the alert line, and adding a debug line to it.
Look in debug mode and see all variables
A: "toSource()" is not a documented function for either platform, and I also do not see it in the source for Titanium Mobile. If you aren't getting the error on iOS, I'm guessing it is because the error handler isn't getting called. Perhaps your emulator or device does not have internet access, whereas your iOS simulator or device does?
Regardless, error handling in the HTTPClient normally looks something like this:
loginReq.onerror = function(e)
{
Ti.API.info("ERROR " + e.error);
alert(e.error);
};
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526860",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why I can't call std::mismatch function for the second time? I use STL's mismatch function to help me to find common directory path. In doing so, I use multimap::equal_range to get range of equal elements.
For my sample program (please see fro you reference), I got a vector vPathWithCommonDir filled with 3 elements such as "C:/MyProg/Raw/", "C:/MyProg/Subset/MTSAT/" and "C:/MyProg/Subset/GOESW/", when iterating the multimap mmClassifiedPaths for the first time. I then passed this vector to FindCommonPath function, and returned a common path "C:/MyProg" what I wanted. When looping for the second time, it's not necessary to call FindCommonPath function because there is only one element. When iterating for the third time, I got a vector vPathWithCommonDir filled with 2 elements, namely "D:/Dataset/Composite/" and "D:/Dataset/Global/". A fatal error occurred when I called FindCommonPath function passed with vPathWithCommonDir for the second time. I could not solve this problem.
Would you please help me? Thank you very much!
// TestMismatch.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <algorithm>
#include <map>
#include <vector>
#include <string>
std::string FindCommonPath(const std::vector<std::string> & vDirList, char cSeparator) ;
int _tmain(int argc, _TCHAR* argv[])
{
std::vector<std::string> vDirList;
// Populate the vector list
vDirList.push_back("C:/XML/");
vDirList.push_back("C:/MyProg/Raw/");
vDirList.push_back("C:/MyProg/Subset/MTSAT/");
vDirList.push_back("C:/MyProg/Subset/GOESW/");
vDirList.push_back("D:/Dataset/Composite/");
vDirList.push_back("D:/Dataset/Global/");
vDirList.push_back("E:/Dataset/Mosaic/");
std::multimap<std::string, std::string> mmClassifiedPaths;
for (std::vector<std::string>::iterator it = vDirList.begin(); it != vDirList.end(); it++)
{
std::string sPath = *it;
std::string::iterator itPos;
std::string::iterator itBegin = sPath.begin();
std::string::iterator itEnd = sPath.end();
// Find the first occurrence of separator '/'
itPos = std::find( itBegin, itEnd, '/' );
// If found '/' for the first time
if ( itPos != itEnd )
{
// Advance the current position iterator by at least 1
std::advance(itPos, 1);
// Find the second occurrence of separator '/'
itPos = std::find( itPos, itEnd, '/' );
// If found '/' for the second time
if ( itPos != itEnd )
{
std::string sFound = sPath.substr(0, itPos - itBegin);
mmClassifiedPaths.insert( std::pair<std::string, std::string>(sFound, sPath) );
}
}
}
//std::multimap<std::string, std::string>::iterator it;
std::vector<std::string> vPathToWatch;
std::pair<std::multimap<std::string, std::string>::iterator, std::multimap<std::string, std::string>::iterator> pRet;
for (std::multimap<std::string, std::string>::iterator it = mmClassifiedPaths.begin();
it != mmClassifiedPaths.end(); it++)
{
size_t nCounter = (int)mmClassifiedPaths.count(it->first);
pRet = mmClassifiedPaths.equal_range(it->first);
if (nCounter <= 1)
{
vPathToWatch.push_back(it->second);
continue;
}
std::vector<std::string> vPathWithCommonDir;
for (std::multimap<std::string, std::string>::iterator itRange = pRet.first; itRange != pRet.second; ++itRange)
{
vPathWithCommonDir.push_back(itRange->second);
}
// Find the most common path among the passed path(s)
std::string strMostCommonPath = FindCommonPath(vPathWithCommonDir, '/');
// Add to directory list to be watched
vPathToWatch.push_back(strMostCommonPath);
// Advance the current iterator by the amount of elements in the
// container with a key value equivalent to it->first
std::advance(it, nCounter - 1);
}
return 0;
}
std::string FindCommonPath(const std::vector<std::string> & vDirList, char cSeparator)
{
std::vector<std::string>::const_iterator vsi = vDirList.begin();
int nMaxCharsCommon = vsi->length();
std::string sStringToCompare = *vsi;
for (vsi = vDirList.begin() + 1; vsi != vDirList.end(); vsi++)
{
std::pair<std::string::const_iterator, std::string::const_iterator> p = std::mismatch(sStringToCompare.begin(), sStringToCompare.end(), vsi->begin());
if ((p.first - sStringToCompare.begin()) < nMaxCharsCommon)
nMaxCharsCommon = p.first - sStringToCompare.begin();
}
std::string::size_type found = sStringToCompare.rfind(cSeparator, nMaxCharsCommon);
return sStringToCompare.substr( 0 , found ) ;
}
A: You have to ensure that there are at least as many items in both iterator ranges provided to mismatch - it does not do any checking.
The fix would be to do a distance check between the ranges and provide the smaller one as the first range and the larger range as second.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526861",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Automatic adjustment of 3 parameters to minimize standard deviation Situation:
I am currently developing a Java application based on rules. Every rule has 3 numeric parameters to influence a database communication. I am measuring a value, that is affected by this rules and calculate the standard deviation of the measured values. The standard deviation should be as small as possible.
Question:
I am wondering if it is possible to do this automated? I can already start a test scenario automatically and I can calculate the standard deviation automatically. So, now I am looking for mechanism to adjust the parameters according to the measured values. Any ideas?
Thanx.
PS: I know, it's a very general question...
A: As Peter says, you have to minimize a function f(a,b,c). There are a lot of elaborate methods for well behaving functions. Eg for functions which can be differentiated, or for so called convex functions. In your case you have a function where we do not know very much about. So f could have different local minima which kills many established minimization methods.
If a simple evaluation of a parameter set a,b,c is fast, you can try some kind of coordinate descent. This is not the best method, brute force but easy for you to implement. I will name the standard deviation achieved by (a,b,c) as s(a,b,c):
I give you some python style pseudo code, which should be easy to read:
def improve(a,b,c):
eps = .01
s1 = s(a*(1+eps), b, c)
s2 = s(a, b*(1+eps), b, c)
s3 = s(a, b, c*(1+eps))
s4 = s(a*(1-eps), b, c)
s5 = s(a, b*(1-eps), c)
s6 = s(a, b, c*(1-eps))
# determine minimal of (s1....s6) and take index:
i = argmin (s1....s6)
# take parameters which lead to miminal si:
if i==1:
a = a*(1+eps)
if i==2:
b = b*(1+eps)
...
if i==6:
c = c*(1-eps)
return a,b ,c
You have to start with some values (a,b,c) and this function should give you a new triple (a,b,c) which leads to less variation. Now you can apply this step as often as you want.
Maybe you have to adapt eps, that depends on how fast s(a,b,c) changes if you make little modifications on a, b, or c.
This is not the best solution, but an easy to try hands-on approach.
A: Fortunately there are a number of general solutions. It should be a matter of solving the function to minimise the result. If you have a function x= f(a,b,c) you want to find a, b, c which gives a minimal x. The simplest approach is trial an error, but you can improve on this by using a binary search and linear interpolation (assuming the topology is relatively simple) There are more complex approaches but you may not need them.
Do you know what the actual function is? If its a pure standard deviation you can make a,b,c the same e.g. the average, and your standard deviation will be 0.
A: If you don't know anything about f, I think I would run random samples for some time and have a look at the results. Then you can decide whether you want to do a gradient descent or something else.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526869",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Problem on sorting an array I have problem in sorting an array in ascending form and i don't know how to fix it.
string[] filePath = Directory.GetFiles(fbdialog.SelectedPath.ToString(), "*", SearchOption.AllDirectories);
Array.Sort(filePath);
Here are the values of an filePath.
"C:\\Documents and Settings\\20110909\\DAR-AAP070127-20110909.ods"
"C:\\Documents and Settings\\20110909\\DAR-ALA061452-09050909.xls"
"C:\\Documents and Settings\\20110819\\DAR-AAP070127-20110819.xls"
I want to look like this..
"C:\\Documents and Settings\\20110909\\DAR-AAP070127-20110909.ods"
"C:\\Documents and Settings\\20110819\\DAR-AAP070127-20110819.xls"
"C:\\Documents and Settings\\20110909\\DAR-ALA061452-09050909.xls"
Thanks in Advance.
A: Sort by filename:
var result = filePath.OrderBy(p => Path.GetFileName(p));
A: Here's a version using some LINQ.
Note also that if you only need the file names, not the files themselves, then DirectoryInfo.GetFiles() can be used rather than Directory.GetFiles().
var filePaths = new DirectoryInfo(fbdialog.SelectedPath.ToString())
.GetFiles("*", SearchOption.AllDirectories)
.OrderBy(f => f.Name)
.Select(f => f.FullName);
A: To sort by "EmpNo" e.g. "AAP070127":
string[] sortedFiles = Directory
.GetFiles(fbdialog.SelectedPath, "*", SearchOption.AllDirectories)
.OrderBy(n => Path.GetFileName(n).Split('-')[1])
.ToArray();
Update
And without Linq as you mention using C# 2.0. The following uses a custom comparer to compare only the "EmpNo" codes in your file names. The solution expects your file names to be well-formed i.e. for them to contain an "EmpNo" in the format of your example file names.
[Test]
public void Sort()
{
string[] files = Directory
.GetFiles(fbdialog.SelectedPath, "*", SearchOption.AllDirectories);
Array.Sort(files, new EmpNoFileComparer());
}
private class EmpNoFileComparer : IComparer<string>
{
public int Compare(string x, string y)
{
string empNoX = Path.GetFileName(x).Split('-')[1];
string empNoY = Path.GetFileName(y).Split('-')[1];
return empNoX.CompareTo(empNoY);
}
}
A: using System.Linq; // requires .NET 3.5+
IEnumerable<string> r =
new DirectoryInfo(fbdialog.SelectedPath) // no need for ToString()
.GetFiles("*", SearchOption.AllDirectories)
.Select(f => f.Name) // DAR-ALA061452-09050909.xls
.Select(f => f.Substring(4, 9)) // ALA061452
.OrderBy(f => f);
or shorter:
new DirectoryInfo(fbdialog.SelectedPath)
.GetFiles("*", SearchOption.AllDirectories)
.OrderBy(f => f.Name.Substring(4, 9));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526873",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ABCPDF 6 Component Problem - Output Printing Small We're using the ABCPDF Version 6 component to create PDF's from ASP .NET. The output works fine the majority of the time but will suddenly switch to small output i.e. the content get's condensed to 1/8th of it's original size.
Has anyone else experienced this problem, any help much appreciated.
A: I contacted websupergoo the makers of abcpdf who responded quickly with the following...
"These scaling issues can arise when someone remotely logs into your
server and changes the screen resolution, out from under Internet
Explorer and ABCpdf. Our newer versions of ABCpdf handle this
situation better."
I can confirm this is the problem in our situation RDP'ing to the server with different resolutions can effect the output of the abcpdf component. More detailed information on the problem is as follows.
"On some machines we see interactions between the video driver and
MSHTML. On these machines MSHTML doesn't like the screen resolution
changing and can change the way it handles content if this happens.
Typically this occurs when someone logs onto the machine either
locally or remotely using a different screen resolution."
As a resolution to our problem we are going to include in our code a check for the desktop resolution, if it has changed the service will be restarted. websupergoo provided us with some sample code for checking the resolution, the code is property of websupergoo so unfortunately I can't post here.
I hope the info above helps others with the same problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526874",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Are unit tests useful for real?
Possible Duplicate:
Is Unit Testing worth the effort?
I know what is the purpose of unit tests generally speaking, but I found some things that bother me.
1)
Purpose of tests early bug discovery. So, in some of later iterations, if I make some changes in code, automated test have to alarm me and tell me that I've screwed up some long ago forgotten piece of my software.
But, say that I have class A and say that is interact with some others class' instance, call it class B.
When one writes unit test for class A, he has to mock class B.
So, in some future, if one makes some changes in class B, and that causes some bugs, they will reflect only in class B's unit test, not in A's ('cause A's test doesn't use real class B, but it's mock with fixed inputs and outputs).
So, I can't see how could unit test do early notifying of made bugs that one isn't aware of? I'm aware of possible bugs in class that I'm changing, I do not need unit test for it, I need test to alarm me of consequences of my changes that makes bug in some "forgotten" class, and that isn't possible with unit tests. Or am I wrong?
2)
When writing mocks and right expectations of calling methods, their inputs and returning values, one has to know how class-under-test is going to be implemented.
And I think that that contradicts with test driven development. In TDD one writes tests first, and, driven by them, one writes a code.
But I can't write right expectations (and tests in general) unless I write code that has to be tested. That contradicts with TDD, right?
Both of those problems could be solved if I used real objects instead of mocks. But that isn't unit testing then, right? In unit test class-under-test has to be isolated form the rest of the system, not using real classes but mocks.
I'm sure that I'm wrong somewhere, but I cannot find where. I've been reading and reading and I can't find what have I understood wrong.
A: I have just implemented TDD and unit testing for the first time. I think its great, and I have never used it in a contiguous integration environment, where I imagine its even more valuable.
My process:
*
*Create the skeleton of class where business logic will go (be it a
serivce layer, or domain object, etc).
*Write the test, and define the
method names and required functionaility in the test - which then prompts my
ide to write the skelton method (a small but nice plus)
*Then write the actual class methods being tested.
*Run tests, debug.
I can now no longer write code without first writing its test, it really does aid develop. You catch bugs straight away, and it really helps you mentally order your code and development in a structured simple manner. And of course, any code that breaks existing functionality is caught straightaway.
I have not needed to use mock objects yet (using spring I can get away with calling service layer, and controller methods directly).
A: Strictly speaking, you spend more time in writing unit test rather than concentrating on the actual code.
there is no way you can achieve 100% code coverage. I do unit test my application, but I feel its not worth it. But not every one agrees with it.
If you change a piece of code, your unit test fail and figure out why its failing but for me its not worth it.
I am not big fan of Unit testing... You mock everything but mocking is big task..........
But now a days companies are trying for TDD approach.
A: Simple answer: Yes, they are useful for real.
TDD is nice and all in theory but I've hardly ever seen seen it done in practice. Unittests are not bound to tdd, however. You can always write unittests for code that works to make sure it still works after changes. This usage of unittests have saved me countless hours of bugfixing because the tests immediately pointed out what went wrong.
I tend to avoid mocks. In most cases, they're not worth it in my opinion. Not using mocks might make my unittest a little more of an integrationtest but it gets the job done. To make sure, your classes work as designed.
A: Unit Tests itself aren't stupid, it depends of your project.
I think Unit Tests are good, not just in TDD development but in any kind of project. The real pro for me is that if you wrap crucial code in your project with Unit Tests, there's a way to know if what you meant with it is still working or not.
For me, the real problem is that if someone is messing your code, there should be a way for him/her to know if the tests are still succedding, but not by making them run manually. For instance, lets take Eclipse + Java + Maven example. If you use Unit tests on your Maven Java Project, each time anyone build it, the tests run automatically. So, if someone messed your code, the next time he build it, he'll get a "BUILD FAILED" Console error, pointing that some Unit Tests failed.
So my point is: Unit Tests are good, but people should know that they're screwing things up without running tests each time they change code.
A: 0) No, it doesn't. Sound stupid, I mean. It is a perfectly valid question.
The sad fact is that ours is an industry riddled with silver bullets and slick with snake oil, and if something doesn't make sense then you are right to question it. Any technique, any approach to any part of engineering is only ever applicable in certain circumstances. These are typically poorly documented at best, and so it all tends to deteriorate into utterly pointless my-method-is-better-than-yours arguments.
I have had successes and failures with unit testing, and in my experience it can be very useful indeed, when correctly applied.
It is not a good technique when you're doing a massive from-scratch development effort, because everything is changing too rapidly for the unit tests to keep up. It is an excellent technique when in a maintenance phase, because you're changing a small part of a larger whole which still needs to work the way it's supposed to.
To me, unit testing is not about test-driven development but design-by-contract: the unit test checks that the interface has not been violated. From this, it's pretty easy to see that the same person should not be writing a unit and its corresponding unit test, so for very small-scale stuff, like my own pet projects, I never use it. In larger projects, I advocate it - but only if design-by-contract is employed and the project recognizes interface specifications as important artefacts.
Unit testing as a technique is also sensitive to the unit size. It is not necessarily the case that a class is testable on its own, and in my experience the class is generally too small for unit testing. You don't want to test a class per se, you want to test a unit of functionality. Individually deployable (installable) binaries, eg jars or DLLs, make better candidates in my book, or packages if you're in a Java-style language.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526877",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How can I read Chinese TEXT from a PDF file using PoDoFo's "podofotxtextract" (C++) sample I am using PoDoFo 0.9.1 library to read a PDF file which contains Chinese characters on Win32 XP Chinese version OS.
I found PoDoFo's sample project "podofotxtextract" can read PDF in English gracefully, however, when I opened a Chinese PDF file, nothing parsed out. anyone has suggestion? thanks a lot.
A: I use Objective C to add an annotation on an existing PDF file.
btw: just try
PdfString pdfString(reinterpret_cast<const pdf_utf8*>("the chars you read ..."));
that's some code below ...
PdfPage* pPage = doc->GetPage(pageIndex);
if (! pPage) {
// couldn't get that page
return;
}
PdfAnnotation* anno;
anno = pPage->CreateAnnotation(ePdfAnnotation_Text, rect);
PdfString sTitle(reinterpret_cast<const pdf_utf8*>([@"中国" UTF8String]));
PdfString sContent(reinterpret_cast<const pdf_utf8*>([@"这是一个中文测试"UTF8String]));
// to parse this annotation
// anno->GetContents().GetStringUtf8().c_str()
anno->SetTitle(sTitle);
anno->SetContents(sContent);
anno->SetOpen(bOpen);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526878",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JEditorPane and custom editor kit I've a trivial question. I need to load an existing file into JEditorPane using custom editor kit.
I've a editor kit, a file with some extension and I need to force the JEditorPane to recognize my file and use my editor kit. I've found only, that's possibile, but nowhere how.
The kit is based on HTML and the file too. If file has the .html extension, it works, but when I rename the file to .xhtbm, it is opened as plain text. The content type is set to text/plain, but I'm unable to register my editor kit for this type, because there is already registered another editor kit for this content type.
Actually the question is: Is really possible to associate some editor kit with some file type?
A: Set your EditorKit and user the kit's read() method passing the file there.
The reader used in the read method should understand how to parse the content.
A: Thanks a lot Stanislav. In his example (see the last page of article, method initEditor()) I found the proper way. The mistake was in the order of commands. That works:
public void openFile(String fileName) throws IOException {
editor.setEditorKit(new ModifiedHTMLEditorKit());
ModifiedHTMLDocument doc = (ModifiedHTMLDocument)editor.getDocument();
try {
editor.getEditorKit().read(new FileReader(fileName), doc, 0);
}
catch (BadLocationException b) {
throw new IOException("Could not fill data into editor.", b);
}
}
Then I call openFile("test.xhtbm") and all goes without friction.
A: You Could:
static{
// register EditorKit for plaintext content
JEditorPane.registerEditorKitForContentType( "text/plain", "HtmlEditorKit" );
}
before your:
public static void main(String[] args){...}
Sorry for the Late Response!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526883",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: IE automation send the HTTP Post directly to the form action using VBA I am having some automation trouble.
I am using HTML Object Library to automate an download. At the end of the automation process, I have to click a submit button of a form and then the download starts.
When I try to handle the dialog with the winapi32 function like this:
hWndDialog = 0
'Wait until the dialog is open
While hWndDialog = 0
hWndDialog = FindWindow(vbNullString, "Dateidownload")
Wend
'get the handle of the button
hWndDialogSpeichern = FindWindowEx(hWndDialog, 0, "Button", "&Speichern")
Call SetForegroundWindow(hWndDialog)
'send message
lRetval = SendMessage(hWndDialogSpeichern, &H5, ByVal 0&, ByVal 0&)
Nothing happens. I read something, that this isn't possible, because the dialog is modal?
So I try to send the POST data directly to the form's action. I think this is the best possibility even.
But I don't know what to send to the server.
Here the form in the html page:
<form action="/smarti/bismt/bismt/resexport" method="post">
<input class="active" type="button" onclick="submitform()" name="button_export" value="Export">
submitform() only check some values and then calls:
document.forms[0].submit();
However, when I send a POST request to "/smarti/bismt/bismt/resexport" I only get the page. I don't know how to set up the request header. Tried to use firebug, to see what is sending to the form, but saw nothing I recognized.
A: Did you try adding a question mark ? and then the names of the text input boxes? Like http://zip4.usps.com/zip4/zcl_3_results.jsp?zip5=92101.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526889",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: eclipse builds all projects even on issuing build for single project There seems to be some issue with Eclipse VERSION 3.7
When I compile some single project ( though ant or though buildProject) , Eclipse starts building all projects in workspace and that takes a long amount of time.
I have tried building project in two ways -
*
*right click ant file, select Run as And Build
*Right Click project in Eclipse , select Build Project.
Both ways Eclipse starts building other open projects first.
is there any ways we can avoid it.
A: Three options I can think of:
*
*Disable automatic building (Preferences->General->Workspace).
*Change the build order to compile the project you need first (Preferences->General->Workspace->Build Order).
*Close any projects you don't want built.
None of these is ideal, but they may be an improvement.
A: I have checked the options you have in the current Eclipse release, Indigo.
*
*Use automatic building: See the Menu Project > Build Automatically. If that is on, Eclipse builds on its own only when there are changes to files, and it will build incrementally. I suspect that this option is off for you.
*If the option is not used, you can start a build by doing Project > Build All or Project > Build Project. As the menu entries say, only the first one will build all your projects. Perhaps you are using the keybinding that starts that menu entry? CTRL-B? This will only do anything if something has changed.
*When doing a clean build, there comes a popup (see below) with some options in it. If you set the right options, only the project you have selected will be cleaned and then built.
So only the options Clean projects selected below combined with Build only the selected projects will do what you want.
I do not understand why an Ant build (started in Eclipse) of one project will lead to a rebuild of all projects in the same workspace. There is no connection at all from the Ant build to the eclipse projects. The only reason I could imagine is, that the Ant build touches something, which is then dirty, and that leads to a new build. Perhaps you should add information about your build file, the directory structure you work on, ...
A: Shortcut Key Method
Another way is to change the shortcut key for building a project eg. Ctrl-B to only Build Project, instead of Build All.
*
*Go to Window -> Preferences
*In General -> Keys, find "Build" in the filter
*There are two cases, Build All and Build Project.
*Personally, I set Ctrl-B to Build Project by pressing Ctrl-B in the Binding Box
*Next I set Ctrl-A Ctrl-B sequence to build all Projects
Try it out
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526892",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Storing ab object in a class library I have an object (a system GUID) I need to use repeatedly in my class library. I would like to store it somewhere. Whats the best way to do that? Im thinking i could serialize and deserialize the object but it dosent seem like the simplest solution.
A: Just convert it into a string, store this in your Resources/App.Confing/Whatever (even as a constant in some of your classes) and use the constructor of Guid with the string overload to load it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526893",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Internationalization with Javascript variables I am using one API which has its own javascript. Now in that javascript file they have declared few variables as follows :
monthNames: ['January','February','March','April','May','June','July','August','September','October','November','December'],
monthNamesShort: ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
dayNames: ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],
dayNamesShort: ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']
In my application we have implemented internationalization. How can I implement internationalization for above declared variables ?
A: I'd suggest some sort of internationalization wrapper. Something along the lines of the following pseudo code:
var i18n = {
longNames: true;
getMonth: function(i) {
if (longNames)
return monthNames[i];
else
return monthNamesShort[i];
},
getDay: function() {
....
},
...
}
If you further wish to translate e.g., the monthNames array you could try something like the following. Using the same principle as above you can also wrap it to abstract away the language configuration from each call.
var monthNames = {
"English": ["January", "February", ..., "December"]},
"French": ...
...
]
var englishMonth = monthNames["English"][0]; // January in english
};
A: Especially for date and time formatting, I have to suggest Globalize.
It also have ability to simply translate resources (although you would need to write out translated resources from the backend either way).
BTW. If you need some kind of Calendar control, you could use jQuery UI Datepicker, which has built-in (partial) support for i18n and some publicly available localization files.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526902",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to load files/images in qt webkit from sqlite database? I've got a bunch of encrypted data in SQLite via SQLCipher.
How can I load it into Qt WebKit?
I suppose that it can be done via definition of a new QDirModel.
Maybe there is another way to do so by using other crypto store method?
A: SOLVED
I've reimplemented QNetworkReply and QNetworkAccessManager
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526904",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Obtain background image width is possible to get background image width which is defined in CSS?
body {
background-image: url('background.jpg');
}
I need something like this:
window.getComputedStyle(document.body, 'background-width');
A:
is possible to get background image width which is defined in CSS?
I don't think so, but you should be able to use a little trick : Load the image into an img element as described in this question.
If you do this after the document has been fully loaded, the browser should fetch the image from the cache.
A: var u = window.getComputedStyle(document.body, 'background-image');
u = u.replace(/url\(/, '').replace(/\)/, '');
var w = 0;
var i = new Image();
i.onload = function( ){ w = this.width; alert(w); }
i.src = u;
warning: i have ommitted a case, when body has no background image specified, keep that in mind.
A: It's impossible to do this directly without some sort of work around.
*
*Use JQuery to detect what image the background has, with the imagesLoaded (recommended) or onImagesLoad plugin.
*Use the JQuery Dimensions plugin to get the image size.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526907",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to pass submitted value of JSF custom component to managed bean? I have created a custom component. I add a dynamic input text box to it (from the encode function).
The component is correctly is rendered as HTML.
But I want to bind the value of the text box to some property on the Managed Bean. So some other developer can use the component on his jsp with his managed bean.
I want to know, what should I do, so that the value entered in the text box (which my component dynamically creates) is set to the some Managed bean property.
A: You need to ensure that your custom component class extends UIInput and that you're in the encodeEnd() method of your renderer writing the component's client ID as name attribute of the HTML input element. Then you can in the overriden decode() method of your renderer just grab the submitted value from the request parameter map with the component's client ID as parameter name and set it as UIInput#setSubmittedValue() and let JSF do the remnant of the job of converting, validating and updating the model value.
@Override
public void decode(FacesContext context, UIComponent component) {
// Do if necessary first validation on disabled="true" or readonly="true", if any.
// Then just get the submitted value by client ID as name.
String clientId = component.getClientId(context);
String submittedValue = context.getExternalContext().getRequestParameterMap().get(clientId);
((UIInput) component).setSubmittedValue(submittedValue);
}
Unrelated to the concrete problem, are you aware of the new composite component support in JSP's successor Facelets? I have the impression that you don't necessarily need a custom component for this purpose. Or are you really restricted to using the legacy JSP as view technology in spite of that you're already on JSF 2.x? See also When to use <ui:include>, tag files, composite components and/or custom components?
A: Well, the problem is solved.
In the encodeEnd() method I added the element as
HtmlInputHidden hidden = new HtmlInputHidden();
hidden.setParent(this);
hidden.setId("someId");
ValueExpression ve = getValueExpression("value");
hidden.setValueExpression("value", ve);
hidden.encodeBegin(context);
hidden.encodeEnd(context);
This seems to have some problem.
Then I changed this to ...
HtmlInputHidden hidden = new HtmlInputHidden();
hidden.setId("someId");
ValueExpression ve = getValueExpression("value");
hidden.setValueExpression("value", ve);
this.getChildren().add(hidden);
hidden.encodeBegin(context);
hidden.encodeEnd(context);
The use of this.getChildren().add(); solved my problem
P.S. Obviously before adding the element, it needs to be checked if the element is already present.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526916",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to replace exec command with system command in php Here is my Code to Generate PHP certification
To Generate CSR
if(isset($_POST['gencsr']))
{
AddLog("sslconfig.php","gencsr",ERR_ERROR);
/* Storing the values entered by the user for re-display in case a validation check fails */
$_SESSION['dummycountryname'] = trim($_POST["countryname"]);
$_SESSION['dummyprovince'] = trim($_POST["province"]);
$_SESSION['dummylocalityname'] = trim($_POST["localityname"]);
$_SESSION['dummyorganizationname'] = trim($_POST["organizationname"]);
$_SESSION['dummyorganizationunit'] = trim($_POST["organizationunit"]);
$_SESSION['dummycommonname'] = trim($_POST["commonname"]);
$_SESSION['dummyemail'] = trim($_POST["email"]);
if($_POST['countryname']=='')
{
unset ($_SESSION['dummycountryname']);
seterror('0:|: :|: Please enter country name.');
header("Location: ssl.php");
exit;
}
if(strlen($_POST['countryname'])!=2)
{
unset ($_SESSION['dummycountryname']);
seterror('0:|: :|: Please enter country name in two letters.');
header("Location: ssl.php");
exit;
}
if(!eregi("^[a-zA-Z]+$",$_POST['countryname']))
{
unset ($_SESSION['dummycountryname']);
seterror('0:|: :|: Please enter valid country name.');
header("Location: ssl.php");
exit;
}
if($_POST['province']=='')
{
unset ($_SESSION['dummyprovince']);
seterror('0:|: :|: Please enter province name.');
header("Location: ssl.php");
exit;
}
if(!eregi("^[a-zA-Z0-9]([a-zA-Z0-9 \.-]+)*[a-zA-Z0-9\.]$",trim($_POST['province'])))
{
unset ($_SESSION['dummyprovince']);
seterror('0:|: :|: Please enter valid province name.');
header("Location: ssl.php");
exit;
}
if($_POST['localityname']=='')
{
unset ($_SESSION['dummylocalityname']);
seterror('0:|: :|: Please enter locality name.');
header("Location: ssl.php");
exit;
}
if(!eregi("^[a-zA-Z0-9]([a-zA-Z0-9 \.-]+)*[a-zA-Z0-9\.]$",trim($_POST['localityname'])))
{
unset ($_SESSION['dummylocalityname']);
seterror('0:|: :|: Please enter valid locality name.');
header("Location: ssl.php");
exit;
}
if($_POST['organizationname']=='')
{
unset ($_SESSION['dummyorganizationname']);
seterror('0:|: :|: Please enter organization name.');
header("Location: ssl.php");
exit;
}
if(!eregi("^[a-zA-Z0-9]([a-zA-Z0-9 \.-]+)*[a-zA-Z0-9\.]$",trim($_POST['organizationname'])))
{
unset ($_SESSION['dummyorganizationname']);
seterror('0:|: :|: Please enter valid organization name.');
header("Location: ssl.php");
exit;
}
if($_POST['organizationunit']=='')
{
unset ($_SESSION['dummyorganizationunit']);
seterror('0:|: :|: Please enter organizational unit name.');
header("Location: ssl.php");
exit;
}
if(!eregi("^[a-zA-Z0-9]([a-zA-Z0-9 \.-]+)*[a-zA-Z0-9\.]$",trim($_POST['organizationunit'])))
{
unset ($_SESSION['dummyorganizationunit']);
seterror('0:|: :|: Please enter valid organizational unit name.');
header("Location: ssl.php");
exit;
}
if($_POST['commonname']=='')
{
unset ($_SESSION['dummycommonname']);
seterror('0:|: :|: Please enter common name.');
header("Location: ssl.php");
exit;
}
$pos = strpos($_POST['commonname'],'.');
if($pos===false)
{
unset ($_SESSION['dummycommonname']);
seterror('0:|: :|: Please enter valid common name.');
header("Location: ssl.php");
exit;
}
$hostname = substr($_POST['commonname'],0,$pos);
$domainname = strstr($_POST['commonname'], '.');
$domainname = substr($domainname,1);
AddLog("sslconfig.php",$hostname,ERR_DEBUG_HIGH);
AddLog("sslconfig.php",$domainname,ERR_DEBUG_HIGH);
if(!validateHostName($hostname)||$hostname=="")
{
unset ($_SESSION['dummycommonname']);
seterror('0:|: :|: Please enter valid common name.');
$error_text="Please enter valid common name.'";
AddLog("sslconfig.php",$error_text,ERR_DEBUG_HIGH);
header("Location: ssl.php");
exit;
}
if(!validateDomainName($domainname))
{
unset ($_SESSION['dummycommonname']);
seterror('0:|: :|: Please enter valid common name.');
$error_text="Please enter valid common name.'";
AddLog("sslconfig.php",$error_text,ERR_DEBUG_HIGH);
header("Location: ssl.php");
exit;
}
if(!validateEmail($_POST['email']))
{
unset ($_SESSION['dummyemail']);
seterror('0:|: :|: Please enter valid email address.');
header("Location: ssl.php");
exit;
}
$dn = array("C" => "".trim($_POST['countryname']),
"ST" => "".trim($_POST['province']),
"L" => "".trim($_POST['localityname']),
"O" => "".trim($_POST['organizationname']),
"OU" => "".trim($_POST['organizationunit']),
"CN" => "".trim($_POST['commonname']),
"emailAddress" => "".trim($_POST['email']));
// Generate a new private (and public) key pair
$privkey = openssl_pkey_new();
AddLog("sslconfig.php","privkey:".$privkey,ERR_DEBUG_HIGH);
$csr = openssl_csr_new($dn,$privkey);
openssl_csr_export($csr, $csrout);
sendmail($csrout);
AddLog("sslconfig.php","csr:".$csr,ERR_DEBUG_HIGH);
openssl_csr_export_to_file ($csr,"/portal/data/config/certificate/CSR.crt");
openssl_pkey_export_to_file ($privkey,"/portal/data/config/certificate/pk.key");
unsetSessionVariables();
header("Location: ssl.php");
exit;
}
and for del
// To Delete CSR
if(isset($_POST['delcsr']))
{
if(unlink("/portal/data/config/certificate/pk.key") && unlink("/portal/data/config/certificate/CSR.crt"))
seterror('8:|: :|: CSR deleted successfully.');
else
seterror('0:|: :|: CSR deletion failed.');
unsetSessionVariables();
header("Location: ssl.php");
exit;
}
Now I want
*
*Replace exec command with system command in php
*And my new path is:
Generating a cert request
openssl req -new -nodes -out /portal/data/config/certificate/vendor/requests/couffin-req.pem -keyout /portal/data/config/certificate/vendor/requests/couffin-req.key -subj "/C=IN/ST=MAHARASHTRA/L=MUMBAI/O=Couffin Inc/OU=Sales/CN=www.couffin.itpl" -config /portal/data/config/certificate/vendor/openssl.cnf
Signing a cert request
openssl ca -policy policy_anything -batch -out /portal/data/config/certificate/vendor/certs/couffin-cert.pem -config /portal/data/config/certificate/vendor/conf/openssl.cnf -infiles /portal/data/config/certificate/vendor/requests/couffin-req.pem
Here some of the function i m using exec there
for example
function isp7bcertificate($p7btmpfilename)
{
$cmd = 'openssl pkcs7 -in '.$p7btmpfilename;
exec($cmd,$array1,$error_code);
if($error_code==0) // p7b certificate is PEM encoded
{
$error_text="certificate is in PEM p7b format";
AddLog("sslconfig.php",$error_text,ERR_DEBUG_HIGH);
return true;
}
// // p7b certificate is DER encoded
$cmd = 'openssl pkcs7 -inform DER -in '.$p7btmpfilename;
exec($cmd,$array1,$error_code);
if($error_code==0)
{
$error_text="certificate is in DER p7b format";
AddLog("sslconfig.php",$error_text,ERR_DEBUG_HIGH);
return true;
}
$error_text="certificate is not in p7b format";
AddLog("sslconfig.php",$error_text,ERR_DEBUG_HIGH);
return false; // certificate not in p7b format.
}
and here
function uploadcert($certfilename,$pkfilename)
{
$folderpath = '/portal/data/config/certificate/';
$tmpfolderpath = '/portal/data/config/certificate/tmp/';
$error_text="upload cert called";
AddLog("sslconfig.php",$error_text,ERR_DEBUG_HIGH);
if(!file_exists($tmpfolderpath.$certfilename))
{
$error_text="Certificate file not found.";
AddLog("sslconfig.php",$error_text,ERR_DEBUG_HIGH);
return "0:|: :|: Certificate file not found.";
}
else
{
$error_text="Certificate file present.";
AddLog("sslconfig.php",$error_text,ERR_DEBUG_HIGH);
}
if(!file_exists($tmpfolderpath.$pkfilename))
{
$error_text="Private key file not found.";
AddLog("sslconfig.php",$error_text,ERR_DEBUG_HIGH);
return "0:|: :|: Private key file not found.";
}
else
{
$error_text="Privatekey file present.";
AddLog("sslconfig.php",$error_text,ERR_DEBUG_HIGH);
}
// To fix Bug 5468 Starts
if(!isbase64certificate($tmpfolderpath.$certfilename))
{
$error_text="Output : Failed to upload certificate.";
AddLog("sslconfig.php",$error_text,ERR_ERROR);
return "0:|: :|: Failed to upload certificate.";
}
//Fix for Bug 5195
//Check if a private key corresponds to a selected certificate.
$cert_content = file_get_contents($tmpfolderpath.$certfilename);
$priv_key_content = file_get_contents($tmpfolderpath.$pkfilename);
$error_text="openssl_x509_check_private_key called";
AddLog("sslconfig.php",$error_text,ERR_DEBUG_HIGH);
$output = openssl_x509_check_private_key($cert_content,$priv_key_content);
$error_text="Output:".$output;
AddLog("sslconfig.php",$error_text,ERR_DEBUG_HIGH);
if($output)
{
$error_text="Output : Private Key OK";
AddLog("sslconfig.php",$error_text,ERR_DEBUG_HIGH);
}
else
{
$error_text="Output : Private Key NOT OK";
AddLog("sslconfig.php",$error_text,ERR_ERROR);
return "0:|: :|: Private key does not correspond to selected certificate.";
}
//first rename the current localhost.crt and localhost.key as old. and then copy new files.
if (!copy($folderpath.'localhost.crt', $tmpfolderpath.'oldlocalhost.crt'))
{
$error_text="error in localhost.crt copy to oldlocalhost.crt";
AddLog("sslconfig.php",$error_text,ERR_ERROR);
return "0:|: :|: Certificate file corrupted.";
}
else
{
$error_text="localhost.crt copied to oldlocalhost.crt";
AddLog("sslconfig.php",$error_text,ERR_DEBUG_HIGH);
}
if (!copy($folderpath.'localhost.key', $tmpfolderpath.'oldlocalhost.key'))
{
//if copy of private key is failed restore the old localhost.crt
copy($tmpfolderpath.'oldlocalhost.crt', $folderpath.'localhost.crt');
$error_text="error in localhost.key copy to oldlocalhost.key";
AddLog("sslconfig.php",$error_text,ERR_ERROR);
return "0:|: :|: Private key file corrupted.";
}
else
{
$error_text="localhost.key copied to oldlocalhost.key";
AddLog("sslconfig.php",$error_text,ERR_DEBUG_HIGH);
}
$outcert = copy($tmpfolderpath.$certfilename, $folderpath.'localhost.crt');
$outpk = copy($tmpfolderpath.$pkfilename, $folderpath.'localhost.key');
if((!$outcert) || (!$outpk))
{
copy($tmpfolderpath.'oldlocalhost.crt', $folderpath.'localhost.crt');
copy($tmpfolderpath.'oldlocalhost.key', $folderpath.'localhost.key');
$cmd = 'service httpd restart';
exec($cmd,$array1,$error_code);
$error_text="Certificate and Private key copy error";
AddLog("sslconfig.php",$error_text,ERR_ERROR);
return "0:|: :|: Certificate and Private key copy error.";
}
$cmd = 'service httpd restart';
exec($cmd,$array1,$error_code);
if($error_code!=0)
{
//httpd fail to start. Restore to original files
copy($tmpfolderpath.'oldlocalhost.crt', $folderpath.'localhost.crt');
copy($tmpfolderpath.'oldlocalhost.key', $folderpath.'localhost.key');
$cmd = 'service httpd restart';
exec($cmd,$array1,$error_code);
$error_text="httpd fail to restart with new files";
AddLog("sslconfig.php",$error_text,ERR_ERROR);
//seterror('0:|: :|: Certificate and Private key mismatched.');
return "0:|: :|: Certificate and Private key mismatched.";
}
else
{
copy($tmpfolderpath.'oldlocalhost.crt', $folderpath.'localhost.crt');
copy($tmpfolderpath.'oldlocalhost.key', $folderpath.'localhost.key');
$cmd = 'service httpd restart';
exec($cmd,$array1,$error_code);
$error_text="httpd restart successful with new files";
AddLog("sslconfig.php",$error_text,ERR_DEBUG_HIGH);
return "success";
}
}
A: this might be a very short answer, but i don't know what else should be said:
since there aren't any exec-commands in your code, theres nothing to replace. conclusion: it's already done.
for replacing exec/system in general, thats just a small change in code:
exec($command,$return,$error);
simply gets
$return = system($command,$error);
for more information, read the documentation for exec() and for system()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526918",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Add modifier key to scroll a tab page Is it possible to add a modifier key (such as Ctrl) to the mouse wheel scroll on a tabPage?
EDIT :
Because I have controls on the tabPage that requires the use of the mouse wheel, I'd like to add a modifier key to the mouse wheel scroll on the tabPage. This way, the user will be able to play with the controls with the mouse wheel and will be able to scroll down or up the tabPage by using Ctrl + the mouse wheel.
A: The only way to do that is inherit from TabPage and handle the WM_MOUSEWHEEL event:
public class MyTabPageHandlingCTRL : System.Windows.Forms.TabPage
{
const int WM_MOUSEWHEEL = 0x20A;
protected override void WndProc(ref System.Windows.Forms.Message m)
{
if (m.HWnd != this.Handle)
return;
if (m.Msg == WM_MOUSEWHEEL &&
(Control.ModifierKeys & Keys.Control) != Keys.Control)
{
return; // don't propagate the event
}
base.WndProc(ref m);
}
}
Of course in your TabControl.TabPages you must add MyTabPageHandlingCTRL instead of the simple TabPage.
A: are you intend to detect when mouse scrolling and with ctrl being hold, you wanna treat them as tab changing?
create the 3 events handling for the mouse-scrolling and keydown, keyup event.
on a flag when the ctrl is down. negate the flag when that key is up
when mouse-scrolling event kick-in detect if the flag is on, then do your trick.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526919",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: export git => svn When I received the task there was not any repository. And my lead asked me to send snapshots by mail.
I started development using git init.
Now the project received repository - but svn one.
Is it possible to commit into it whole my git commits with proper comments, diff's, etc?
If yes - help me please with commands.
If not - how to do it better?
just git clone my repo into svn local copy and svn add each dir?
thank you.
I hope there is a way to reintegrate my git repo into svn and continue development (locally) with git. :)
A: There is a tool git-svn which allows bidirectional communication between a git repo and a svn repo.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526920",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: WCF data contract question I have this data contract:
[DataContract(Namespace = Constants.ServiceNamespace)]
public enum UserEntityType
{
User = 0,
Group = 1,
IPAddress = 2
}
[DataContract(Namespace = Constants.ServiceNamespace)]
//[KnownType(typeof(UserEntity))]
public class UserEntity
{
[DataMember]
public UserEntityType EntityType;
[DataMember]
public string Value;
}
[DataContract(Namespace = Constants.ServiceNamespace)]
public class TemporaryPolicyData
{
[DataMember]
public DateTime EndTime;
[DataMember]
public string URL;
}
[DataContract(Namespace = Constants.ServiceNamespace)]
//[KnownType(typeof(TemporaryPolicyData))]
//[KnownType(typeof(UserEntity))]
public class TemporaryWhitelistData
{
[DataMember]
public UserEntity User;
[DataMember]
public TemporaryPolicyData Data;
}
[DataContract(Namespace = Constants.ServiceNamespace)]
//[KnownType(typeof(TemporaryWhitelistData))]
//[KnownType(typeof(UserEntity))]
public class WhitelistPolicyData
{
[DataMember]
public IEnumerable<TemporaryWhitelistData> TemporaryData;
[DataMember]
public IEnumerable<string> Websites;
[DataMember]
public IEnumerable<UserEntity> Users;
}
I get this error:
An unhandled exception of type
'System.ServiceModel.CommunicationException' occurred in
mscorlib.dll
Additional information: There was an error reading from the pipe: The
pipe has been ended. (109, 0x6d)
This seems to be related to the data contract defined above, because if I simplify it, it returns data.
The operation method that gives this error is:
[OperationContract]
WhitelistPolicyData GetWhitelistPolicy();
A: I think there has to be a more meaningful inner exception of type SerializationException.
The only thing i see is the missing [EnumMember] attributes on your enumeration. Try this:
[DataContract]
public enum UserEntityType
{
[EnumMember]
User = 0,
[EnumMember]
Group = 1,
[EnumMember]
IPAddress = 2
}
See the docu on msdn for an explantion. When putting [DataContract] on an enumeration you have to specify the [EnumMember] attribute as well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526925",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: problem of insert multiple values with WHERE NOT EXISTS I want to insert multiple records from the form into table named 'user' with the 'items' value submitted from the form do not exist in another table name 'order'. There is only 2 field in the 'order' table that is id and items.
Here is my code:
INSERT INTO user (id, username, email, address, items)
SELECT '$username1', '$email1', '$address1', '$items1'
UNION ALL
SELECT '$username2', '$email2', '$address2', '$items2'
UNION ALL
SELECT '$username3', '$email3', '$address3', '$items3'
FROM DUAL
WHERE NOT EXISTS(SELECT item FROM order)
Lets say 'items' table contain 2 set it data:
id items
1 table01
2 chair01
So when I insert data with:
john, john@hotmail.com, 12, Street, nail01
jennifer, jennifer@yahoo.com, 13, Street, table01
peter, peter@live.com, 14, Street, spoon01
(defintely these data are keyin in the form)
Supposely the second record will not insert into 'user' table since in 'items' table already contain this item.
But now the result is the 1st and 2nd data will insert into 'user' table while 3rd data is not. I try with many times with other code but is still not success.
Can anyone give me a suggestion?
Thanks.
A: I am a little confused with what you are trying to do, correct me if I'm wrong but this is what I understand from your question:
You want to add data into a Users table from a form, but you only want to add user which have order an item that does not already exist in the items table?
------ This now confirmed ------
Right well this is how I would go about it.
so you are collecting the data from the form using the POST method.
$_POST['email'] and so on. You want to make sure that the data collected is 100% clean so I use a handly little cleanString function I created...
function cleanString($var)
{
$var = strip_tags($var); //Removes all HTML tags
$var = htmlentities($var); //Converts characters into HTML entities
$var = stripslashes($var); //Removes any backslashes
return mysql_real_escape_string($var); // Escapes all special characters
}
and would use it like this...
$email = cleanString($_POST['email']);
$item = cleanString($_POST['item']);
etc...
with all of your clean data you now want to check if the item exists from the order table. so do a query along these lines:
$query = "SELECT items FROM order WHERE items=".$item;
$result = mysql_query($query);
Then check if a result was found
if(mysql_num_rows($result) > 0)
{
// Result found do not process...
}
else
{
// Result not found, process...
$query = "INSERT INTO user ...";
}
if you are doing multiple inserts in one go you can wrap this all in a while or foreach loop to process it all in one go. although considering it coming from a form I guess you will only have 1 input at a time?
hope this helps.
------- adding a while loop ------
so you are wanting to add multiple records in one go, this entirely depends on how you are collecting the data from the form, to give an exact answer I will need a bit more information about how you are collecting the data from the form. Do you have 3 of each field to add 3 people at once, or are you saving all the data to an array for processing later?
something along these lines will work if you are putting everything into an array
foreach ($array as $user)
{
$item = $user['item']
etc...
$query = "SELECT items FROM order WHERE items=".$item;
$result = mysql_query($query);
if(mysql_num_rows($result) > 0)
{
// Result found do not process...
}
else
{
// Result not found, process...
$query = "INSERT INTO user ...";
}
}
This will take each user one by one, get all the data for that user, check if the item exists and then process if it does not exist.
You can also do it with a while loop, but this way is hard to explain without knowing how you are acquiring the data
A: This seems like Oracle syntax... Is it?
INSERT INTO user (id, username, email, address, items)
You require id to be inserted but do not do this. That is okay if it is populated by a sequence and trigger, but don't require it to be inserted.
INSERT INTO user (username, email, address, items)
SELECT '$username1', '$email1', '$address1', '$items1'
UNION ALL
SELECT '$username2', '$email2', '$address2', '$items2'
UNION ALL
SELECT '$username3', '$email3', '$address3', '$items3'
FROM DUAL
WHERE NOT EXISTS(SELECT item FROM order)
*
*You need 'FROM DUAL' in each union-part
*Your WHERE-clause only affects the 3rd select
*It also makes not much sense: 'select this row if there are no rows in the table order'. You will need to specify your exclusion. I added a join (WHERE a.items = items), so now a row will only be inserted when there exists no row in the order table where the item already exists. It seems dodgy, you need to provide more info on this.
Probably you meant
INSERT INTO user (username, email, address, items)
SELECT username, email, address, items FROM (
SELECT '$username1' username, '$email1' email, '$address1' address, '$items1' items
FROM DUAL
UNION ALL
SELECT '$username2' username, '$email2' email, '$address2' address, '$items2' items
FROM DUAL
UNION ALL
SELECT '$username3' username, '$email3' email, '$address3' address, '$items3' items
FROM DUAL
) a
WHERE NOT EXISTS(SELECT 1 FROM order WHERE a.items = items)
If your table 'order' has a Unique key defined on the 'items' column, then yes, your insert will fail when you try to insert a new item. A better practice would be to first query your order-table to check if this item already exists, and if not, create it.
Like AdriftUniform says, clearer info is needed!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526929",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Prevent automatic screen lock in iPad I am downloading some contents from the server and after sometimes the screen is locked down. The downloading is happening in the background. And I am showing a video after download completes. And in this case, i.e, when the screen is locked, after downloading completes all I can see is just a black screen (After unlocking).
In the simulator, I could see the video playing.. but the video has already been started.
Is there any way to prevent the iPad from being Screen Lock? (Other than setting it in the settings menu)
A: This may help you
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Rails alternative for only_provides I'd like to limit response formats available for a single action inside a controller. What I have so far (and works):
class SomeController < ApplicationController
respond_to :json, :html
...
def show
respond_to do |format|
format.html { render :edit }
end
end
end
This is not as DRY as I'd like. In Merb you could do only_provides :html inside a method to get about the same effect. Is there something like that in Rails 3?
A: class SomeController < ApplicationController
respond_to :json, :except => :show
respond_to :html
def show
end
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526935",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Nested/Inheriting Layout pages not working I have the following layout pages
_StyledLayout.cshtml:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>@ViewBag.Title</title>
<script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@RenderSection("Head", false)
</head>
<body>
@RenderBody()
</body>
</html>
_StyledPageLayout.cshtml:
@{
Layout = "~/Views/Shared/_StyledLayout.cshtml";
}
@section Head
{
<script src="@Url.Content("~/Scripts/jquery-ui.min.js")" type="text/javascript"></script>
}
@RenderBody()
Details.cshtml:
@using System.Data;
@model ASPNETMVC3.Models.ConfigModel
@{
ViewBag.Title = "Details";
Layout = "~/Views/Shared/_StyledPageLayout.cshtml";
}
@section Head
{
<script type="text/javascript">
var oTable;
$(document).ready(function () {
$(".datepicker").datepicker({ dateFormat: 'dd/mm/yy' });
});
</script>
}
<h2>
Details</h2>
In this setup when I go to Details I get the error: *The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_StyledPageLayout.cshtml": "Head".*
What am I doing wrong?
A: _StyledPageLayout.cshtml:
@section Head
{
@if (IsSectionDefined("Head"))
{
// If the view contains a Head section use that instead
@RenderSection("Head")
}
else
{
// The view doesn't have a Head section => use some default output
<script src="@Url.Content("~/Scripts/jquery-ui.min.js")" type="text/javascript"></script>
}
}
A: Essentially the same as the accepted answer but a little neater if you don't require a default rendering would be...
@section Head
{
@RenderSection("Head", false)
}
...where the 'false' indicates that the section is not required.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526939",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Configuring physical memory for linux kernel I have an embedded board (MIPS architecture) running linux 2.6.29 with u-boot as the bootloader. I have 512MB(bytes) of DDR3 RAM.
The problem is, Linux is able to use only around 128MB of it. I tried changing the memory size while kernel compilation, but the kernel crashes while booting up.
Can somebody please help me with this?. I even tried passing mem=512MB as kernel command line parameter from uboot, but that didn't work.
A: No experience with MIPS boards but a problem i've encountered on ARM is that the physical memory isn't mapped to 512 M of contiguous address space but split. Look at the memmap parameter for the kernel, and at the documentation for your board.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526941",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: In JavaScript, how do you determine the current event if not passed as arg? In an arbitrary JavaScript function, I wish to determine the upstream event.
The event listener function did not pass the event do the current function. As far as I know, window.event is not WC3 and not available.
function listener(e) { subfunc(e.target); }
function subfunc( element) {
// here I wish to know which if any event responsible for me being called
var event = ?;
switch( event.type ) { ... }
}
How does function subfunc() determine the current event?
(Apologize if question asked before - seems it must have been - but cannot track it down.)
A: That's not possible. There's only one property which can be accessed through another, reliable way: event.target = this (Provided that the function is called from within the scope of the event listener).
The event object should be passed to subfunc.
A: You can do:
function listener(e) { subfunc.call(this, e); }
function subfunc( e ) {
var element = this; //<- 'this' points to your element, 'e.type' is event type
switch( e.type ) { ... }
}
Also other way:
function listener(e) { subfunc.call(e, e.target); }
function subfunc( element ) {
var event = this; //<- 'this' points to your event object
switch( event.type ) { ... }
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526949",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: TableLayout inside ScrollView I want to make something like
In Eclipse in UI tool all looks OK, but when i test app on Emulator or device
bottom buttons appears on top of the fields.
I want:
buttons - at the bottom ;
first and second field ;
third field must take all free space between 1 and 2 fields and buttons.
If I use only RelativeLayout -> all UI is OK(But there is problem with Soft-keyboard)
But when I use RelativeLayout inside ScrollView the above mentioned problem is being appeared.
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scroller"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true">
<RelativeLayout
android:padding="5dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
......
Maybe someone faced with some problem.
Thanks in advance.
A: use following code in xml
<ScrollView>
<LinearLayout >
<LinearLayout android:orientation="vertical" >
<EditText />
<EditText />
<EditText />
</LinearLayout>
<LinearLayout android:orientation="horizontal" >
<Button />
<Button />
</LinearLayout>
</LinearLayout>
it may solve your problem
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526954",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Detecting and hiding UIAlertView (or displaying a view over it) Whenever my app becomes active I show a screen (it's a UIImageView which I add to my subview) and a UIActivityIndicator while I synchronize my data.
However if there was a UIAlertView (and I guess UIActionSheet would also) displaying the moment the user pressed the home button, when he comes back the screen and the UIActivityIndicator show but the alert view is over them.
I see two ways of facing this problem: getting the alertview to hide or showing my screen differently.
Any thoughts on how to solve my problem?
A: Do the question only concern UIAlertView produced by your own app or also other alertviews?
Namely do want have to also consider (and find a way to hide) alert views displayed by Push Notifications from other apps, or SMS alerts, etc? If so, this will likely be complicated!
If you only want to consider UIAlertViews of your own applications, don't you need to show the alertview again once the synchronisation of your data has finished? Because if you simply find a way to dismiss the alertview but never show it again, the user will probably miss some information here.
There is no easy/build-in way to do that anyway. Dismissing the alertview will probably generate side-effects, as the alertview could then be considered as validated and the code you have written to handle the buttonClicked event will then probably be triggered whereas in your case it probably isn't meaningful.
But actually hiding the alertview while the data is synching seems a bad idea for me (only my opinion): because if you hide the alertview, the user won't have any other choice than waiting for the data to sync, w/o having anything else to do. Whereas if you let the alertview visible, it will give him a chance at least to be informed of sthg and take time to read the alert while the data is synching.
[EDIT] Here is what I tried. This works, but the glow that is below UIAlertViews when onscreen is still visible even after hiding the alertviews.
Note that even if there is a way to hide this glow, I'm not sure doing this will be acceptedwhen submitting your app to the AppStore.
LCAlertView.h
@interface LCAlertView : UIAlertView
+(void)setAlertViewsVisible:(BOOL)isVisible;
@end
LCAlertView.m
#import "LCAlertView.h"
static UIView* __alertsParentWindow;
static int __alertsCount = 0;
@implementation LCAlertView
+(void)setAlertViewsVisible:(BOOL)isVisible {
__alertsParentWindow.hidden = !isVisible;
}
-(void)didMoveToWindow {
if (self.window != nil) {
// showing
__alertsParentWindow = [self.window retain];
++__alertsCount;
} else {
// hiding
--__alertsCount;
[__alertsParentWindow release];
if (__alertsCount==0) __alertsParentWindow = nil;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526955",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Duplicate Classnames after installing iCalendar gem I just tried to deal with iCalendar gem, but it seems iCalendar has a class named Event, and my app also have a class named Event
I guess there is a way to scope one or another class name, but i just don't know how.
Here's an example of what i'd like to do :
Event.new => ActiveRecord Model
Icalendar::Event.new => Icalendar Event class
Thank you.
A: Hoe about wrapping up the iCalendar gem in a module and then instantiating from e.g. Icalendar::CalEvent or something?
require 'icalendar'
module Icalendar
CalEvent = Event
end
BTW: you could just use the name Event, but there will be a warning about reassigning to a constant.
A: Force ruby to look for top-level class definitions when accessing your model, via ::Event.new. Including :: before class name signifies that class is not in any module, as opposed to Icalendar::Event that is in Icalendar module.
Or, if iCalendar does not provide the namespace, you can do it for your class, defining it as
module MyStuff
class Event
end
end
and using MyStuff::Event for your model, and ::Event for iCal one.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526956",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: mysqldump stops before dumping structure I've got a batch file running on a Windows server that dumps all my MySQL databases out once a day.
There's about 20 databases on the server and everything works fine except for one database.
The command is set to zip up the resulting dump using gZip. The database in question completes its dump with no errors, but when I open the gz file I can only see the standard mysqldump headers, the 'create database if not exists' line and the 'use xxxx' line.
Then, nothing!
The same command is running on all other databases and outputting correctly, so I assume it must be a problem with the database itself - but it's all running fine and I can export with a GUI tool with no problems.
For reference, the database contains only 12 tables, all InnoDB, and is only about 3.3MB in size. No foreign keys, referential integrity, clever indexes or whatnot. There are a couple of simple views in the database and thinking about it, this may be the only one on the server containing views... is there an issue with dumping databases containing views?
The command I'm using to dump is as follows:
%mysqldir%\bin\mysqldump.exe
--user=%dbuser% --password=%dbpass% --databases %%f --opt --quote-names
--allow-keywords
--complete-insert | %zip%\gzip.exe -9 > %backupdir%\%%f\%%f%fn%.sql.gz
Obviously there are some variables in there, but should all be self explanatory.
Any help much appreciated.
Cheers.
A: Have you checked to see if you have the proper permissions to access the database in question?
Check the result code. There may have been errors in the db.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7526957",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.