text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Group array items based on variable javascript I have an array that is created dynamic from an xml document looking something like this:
myArray[0] = [1,The Melting Pot,A]
myArray[1] = [5,Mama's MexicanKitchen,C]
myArray[2] = [6,Wingdome,D]
myArray[3] = [7,Piroshky Piroshky,D]
myArray[4] = [4,Crab Pot,F]
myArray[5] = [2,Ipanema Grill,G]
myArray[6] = [0,Pan Africa Market,Z]
This array is created within a for loop and could contain whatever based on the xml document
What I need to accomplish is grouping the items from this array based on the letters so that all array objects that have the letter A in them get stored in another array as this
other['A'] = ['item 1', 'item 2', 'item 3'];
other['B'] = ['item 4', 'item 5'];
other['C'] = ['item 6'];
To clarify I need to sort out items based on variables from within the array, in this case the letters so that all array objects containing the letter A goes under the new array by letter
Thanks for any help!
A: Try groupBy function offered by http://underscorejs.org/#groupBy
_.groupBy([1.3, 2.1, 2.4], function(num){ return Math.floor(num); });
Result => {1: [1.3], 2: [2.1, 2.4]}
A: You have to create an empty JavaScript object and assign an array to it for each letter.
var object = {};
for ( var x = 0; x < myArray.length; x++ )
{
var letter = myArray[x][2];
// create array for this letter if it doesn't exist
if ( ! object[letter] )
{
object[letter] = [];
}
object[ myArray[x][2] ].push[ myArray[x] ];
}
Demo fiddle here.
A: You shouldn't use arrays with non-integer indexes. Your other variable should be a plain object rather than an array. (It does work with arrays, but it's not the best option.)
// assume myArray is already declared and populated as per the question
var other = {},
letter,
i;
for (i=0; i < myArray.length; i++) {
letter = myArray[i][2];
// if other doesn't already have a property for the current letter
// create it and assign it to a new empty array
if (!(letter in other))
other[letter] = [];
other[letter].push(myArray[i]);
}
Given an item in myArray [1,"The Melting Pot","A"], your example doesn't make it clear whether you want to store that whole thing in other or just the string field in the second array position - your example output only has strings but they don't match your strings in myArray. My code originally stored just the string part by saying other[letter].push(myArray[i][1]);, but some anonymous person has edited my post to change it to other[letter].push(myArray[i]); which stores all of [1,"The Melting Pot","A"]. Up to you to figure out what you want to do there, I've given you the basic code you need.
A: This code will work for your example.
var other = Object.create(null), // you can safely use in opeator.
letter,
item,
max,
i;
for (i = 0, max = myArray.length; i < max; i += 1) {
item = myArray[i];
letter = myArray[2];
// If the letter does not exist in the other dict,
// create its items list
other[letter] = other[letter] || [];
other.push(item);
}
A: Good ol' ES5 Array Extras are great.
var other = {};
myArray.forEach(function(n, i, ary){
other[n[2]] = n.slice(0,2);
});
A: Try -
var myArray = new Array();
myArray[0] = [1,"The Melting Pot,A,3,Sake House","B"];
myArray[1] = [5,"Mama's MexicanKitchen","C"];
myArray[2] = [6,"Wingdome","D"];
myArray[3] = [7,"Piroshky Piroshky","D"];
myArray[4] = [4,"Crab Pot","F"];
myArray[5] = [2,"Ipanema Grill","G"];
myArray[6] = [0,"Pan Africa Market","Z"];
var map = new Object();
for(i =0 ; i < myArray.length; i++){
var key = myArray[i][2];
if(!map[key]){
var array = new Array();
map[key] = array;
}
map[key].push(myArray[i]);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596794",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Why Augment Reality does not work well in Portrait orientation As above, I need some help on AR for my windows phone. The below code is what I used:
Orientation : Portrait
XAML :
<Rectangle Margin="0,44,0,178">
<Rectangle.Fill>
<videoBrush x:Name="videoBrush" />
</Rectangle.Fill>
</Rectangle>
Code being XAML :
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
cam = new PhotoCamera();
videoBrush.SetSource(cam);
}
Problems:
1) I am holding the Phone Upright but the VideoBrush does not show image in portrait position. The image is like in Landscape. What do I need to do ?
A: Problem solved. I need to use Motion API. Thanks
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596795",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: setattribute in javascript This is my code to dynamically set the onclick attribute to links, but without me clicking the links itself, the alert is triggered.
window.onload = function() {
var links = document.getElementsByTagName("a");
for(var i=0;i<links.length;i++) {
elm = links[i];
elm.setAttribute("onclick", alert("you clicked a lik"));
}
}
A: change the corresponding line to:
elm.setAttribute("onclick", function() { alert("you clicked a link");});
If you pass as argument a function call (such as alert('msg')), the function is executed imediatley and the actual passed argument is the function's return value. All you have to do is wrap your eventHandler code into an anonymous function.
Also, you can declare a function that handles your event and send it's name as argument :
function handleClick() { alert("you clicked a link");}
elm.setAttribute("onclick", handleClick);
P.S. : I recommend using the addEventListener functionality instead of plain old onEvent inline attributes :
elm.addEventListener('click', function() { alert("you clicked a link");}, false);
A: Try to put the alert statement into an anonimous function
window.onload = function()
{
var links = document.getElementsByTagName("a");
for(var i=0; i < links.length; i++)
{
links[i].setAttribute("onclick", function () {
alert("you clicked a link");
});
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596798",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: django filter depeding on character count of the related model's fields I have two models such that
class Employer(models.Model):
code = models.CharField(null=False,blank=False,default="")
class JobTitle(models.Model):
employer = models.ForeignKey(Employer,unique=False,null=False,default=0)
name = models.CharField(max_length=1000,null=False,default="")
and I would like to get all employers whose jobtitle name is less than X chracters. How can I achive this in Django ?
Thanks
A: The correct code for this is
Employer.objects.filter(jobtitle__name__regex="^.{0,20}$")
This will select all the employers who have a job title name up to and including 20 characters long. Just replace the 20 with whatever number you need.
Note that if an Employer has multiple JobTitles whose name are less than 20 characters long, it will return that Employer in the list multiple times. If you don't want this to happen, you should add distinct() to the query as follows:
Employer.objects.filter(jobtitle__name__regex="^.{0,20}$").distinct()
You'll now only get the Employer back once, even if they have multiple short JobTitles.
A: try
Employer.objects.filter(jobtitle__name__regex="^\W{0, X}$")
When you use regex, you can filter records from database with provided regular expression. In this case all records with name which contains 0 to X signs will be returned
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596799",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Odd behaviour when doing LIKE with wildcards searching for backslash in MySQL I've encountered a very unusual problem with MySQL, involving backslashes. Basically when I do a wildcard match with LIKE for \n which is in the database as text rather than an actual newline, it will only return a match if I have just a right hand wildcard:
SELECT *
FROM `tmptest`
WHERE `a` LIKE '\\\\n%'
Now, if I query like this, it will not return anything:
SELECT *
FROM `tmptest`
WHERE `a` LIKE '%\\\\n%'
As you can see from the data I have in the table both queries should be matching. I'm not sure if it's something that I'm missing, or I'm incorrectly escaping the newline but it doesn't make sense for the first query to work and the second not.
Table structure:
CREATE TABLE IF NOT EXISTS `tmptest` (
`a` varchar(22) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
Sample data:
INSERT INTO `tmptest` (`a`) VALUES
('\\n'),
('\\n\\ndfsdfsdfs\\n');
Thanks for taking time to read this.
A: It works for me with 6 backslashes when using the left side wildcard:
mysql> SELECT * FROM `tmptest` WHERE `a` LIKE '%\\\\\\n%';
+-----------------+
| a |
+-----------------+
| \n |
| \n\ndfsdfsdfs\n |
+-----------------+
2 rows in set (0.00 sec)
Using mysqld Ver 5.1.49
@Karolis as far as i understand the expression for the LIKE operator should be parsed twice, hence \\\\ turns into \ when used with LIKE.
But how to explain this (using the expression "back\slash"):
SELECT 'back\\slash' LIKE '%back\\\\slash%'; -> TRUE (normal behaviour)
SELECT 'back\\slash' LIKE '%back\\\\\slash%'; -> TRUE (5 backslashes?)
SELECT 'back\\slash' LIKE '%back\\\\\\slash%'; -> TRUE (6 backslashes?)
SELECT 'back\\slash' LIKE '%back\\\\\\\slash%'; -> TRUE (7 backslashes?)
SELECT 'back\\slash' LIKE '%back\\\\\\\\slash%'; -> FALSE (normal behaviour, I guess..)
Nevertheless if searching only for the "\":
mysql> SELECT 'back\\slash' LIKE '%\\\\%'; --> FALSE (but should work)
mysql> SELECT 'back\\slash' LIKE '%\\\\\%'; --> TRUE (5 backslashes)
mysql> SELECT 'back\\slash' LIKE '%\\\\\\%'; --> TRUE (6 backslashes)
mysql> SELECT 'back\\slash' LIKE '%\\\\\\\%'; --> FALSE (7 backslashes)
For this particular question, one could use a different escape character | and bypass the problem altogether (if no | character occurs):
mysql> SELECT 'back\\slash' LIKE '%\\%' ESCAPE '|'; --> TRUE
So maybe some mysql guru out there can explain this. I simply can't. also tested with mysql 5.1.53 on a different machine. Same behaviour was observed. As i started by commenting, its a rather interesting question.
A: Based on the QSP answer (As I thanks him for saving my day).
I would say use 5 blackslashes.
I don't understand why like QSP and Karolis, but if you replace 1 slash by 5 slaches in mySQL (or 10 in php), it still work as QSP say.
BUT the good thing, is if you replace '\\' by 12 backslashes (or 24 in php) as QSP suggest, it won't work. But if replace it by 10 backslashes (or 20 in php) it will still work.
I hope that can help someone as QSP answer is already accepted.
EDIT :
It work fine if you do :
%\\\\\%
%\\\\\\\\\\%
%k\\\\\\\\\\s%
%\\\\\\\\\\s%
%k\\\\\s% (if only 1 slash like back\slash)
But it doesn't work if you do :
%k\\\\\\\\\\%
%k\\\\\%
%\\\\\s%
I will continue to look why.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596801",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Can somebody explain clearly what this code does? - OpenGL & SDL In general I want to find out what the opengl functions do in this piece of code such as glOrtho();.
I have searched around trying to find out in good detail what they mean and do but I have trouble finding any good explanations of the code. The SDL code I am fine with.
I was also wondering if anybody could describe well for me gltranslatef();
bool init_GL()
{
glClearColor( 0, 0, 0, 0 );
//Set projection
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
glOrtho( 0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, -1, 1 );
//Initialize modelview matrix
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
//If there was any errors
if( glGetError() != GL_NO_ERROR )
return false;
return true;
}
bool init()
{
if( SDL_Init( SDL_INIT_EVERYTHING ) < 0 )
return false;
//Create Window
if( SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_OPENGL ) == NULL )
return false;
//Initialize OpenGL
if( init_GL() == false )
return false;
//Set caption
SDL_WM_SetCaption( "OpenGL Test", NULL );
return true;
}
This code is from the lazyfoo tutorials but it doesn't describe a lot of the code.
Greatly appreciated to anybody who can help.
A: I'll break it down for you:
bool init_GL()
{
This function, init_GL I mean, is bad style. All what it does, actually belonged into the drawing function
glClearColor( 0, 0, 0, 0 );
glClearColor sets the color the framebuffer will be filled with (cleard) when calling glClear with the GL_COLOR_BUFFER_BIT set.
//Set projection
glMatrixMode( GL_PROJECTION );
glMatrixMode switches the matrix upon which OpenGL matrix manipulation functions have an effect. OpenGL knows the matrices "Projection", "Modelview", "Texture" and "Color". The last two are rarely touched.
glLoadIdentity();
Load Identity will put a identity matrix on the current position in the matrix stack. A identity matrix, multiplied with a vector, will yield the very same vector.
glOrtho( 0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, -1, 1 );
glOrtho multiplies the identity matrix with a orthographic projection matrix. Some projections, like orthographic or affine perspective can be described by a linear trasformation. Linear transformations can be expressed by matrices. In some way you may think the projection matrix as kind of the "lens" of the OpenGL camera (there is no camera in OpenGL though!).
//Initialize modelview matrix
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
Here the matrix mode is switched to the Modelview matrix. The Modelview matrix is used for both placing objects in the world (model-) and moving the world relative to the "camera" (-view, hence modelview).
//If there was any errors
if( glGetError() != GL_NO_ERROR )
{
return false;
}
This error checking code is wrong. In OpenGL you've to call glGetError in a loop until it returns GL_NO_ERROR.
return true;
}
bool init()
{
if( SDL_Init( SDL_INIT_EVERYTHING ) < 0 )
{
return false;
}
Initializes the SDL library, so it can be used.
//Create Window
if( SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_OPENGL ) == NULL )
{
return false;
}
SDL_SetVideoMode creates a window (if in a windowed graphics system, if operating on the naked framebuffer it will do like the name suggests, setting the video mode), maybe change the video mode to another display resolution (if in fullscreen mode), and create an OpenGL context.
//Initialize OpenGL
if( init_GL() == false )
{
return false;
}
//Set caption
SDL_WM_SetCaption( "OpenGL Test", NULL );
Finally this sets the window title.
return true;
}
Nothing gets rendered so far. Also this program lacks a event loop, so a window will appear only flashing on the screen, that disappear and the program terminate.
A: Basically you can say that both glOrtho and glTranslate produce matrices that are multiplied with the current rendering matrix. The final rendering matrix will be used to transform all vertices in your scene which will effect lighting, culling, perspective. So, in the end, all these matrices controls the way objects are rendered to your screen.
Using these (together with a multitude of other matrix functions) you can scale, rotate, translate objects in your scene and control if you should use orthogonal (parallel) projection or perspective projection. You can read up on these here:
glOrtho:
glOrtho describes a transformation that produces a parallel projection.
The current matrix (see glMatrixMode) is multiplied by this matrix
and the result replaces the current matrix
gltranslatef:
glTranslate produces a translation by (x, y, z).
The current matrix
(see
glMatrixMode)
is multiplied by this translation matrix
But I think that if you really want to learn OpenGL, and have fun doing so, follow tutorials and follow up with theory, graphical programming is a bit of a world on its own.
A: You seem to be a real beginner with OpenGL. I had the 1999 book of "OpenGL Super Bible" which explains everything very nicely (See http://www.starstonesoftware.com/OpenGL/) and it helped me a lot in learning OpenGL.
I could explain glOrtho and glTranslatef to you, but in a day you are going to need an explanation on glRotatef, gluPerspective, glBegin, glClear, glFlush, glVertex3f etc etc and you can't keep asking those questions here.
So my suggestion is to go buy a nice OpenGL book (like the OpenGL super bible) and start learning it by the book.
You could also take a look at this, for example on the transformations section, but I haven't read it myself so I don't know if it's good enough. This part is on early versions of OpenGL though and is only good for starting to get the idea. In modern OpenGL, you wouldn't be programming like that.
One word of advice, in modern OpenGL a lot of common practices in OpenGL 1.x are deprecated. If you searched google and ended up in NeHe's website, remember that what you learn in that website, you might want to forget about when you move on to newer versions of OpenGL.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596802",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to increase rows in NSMutableArray? NSString *categoryStr = categoryName.text;
NSLog(@"Category Name:--->%@",categoryStr);
appDelegate.categoryData = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
categoryStr, @"name",image ,@"image", nil] mutableCopy];
[appDelegate.categories addObject:appDelegate.categoryData];
NSLog(@"Category Data:--->%@",appDelegate.categories);
My problem is that every time I got only one rows means appDelegate.categories returns 1 row but I want to increment appDelegate.categories (NSMutableArray).
A: addObject adds a new entry to the array. If you're always getting only one entry it's because you keep reallocating the array vs using the old one.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596811",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: do not remove leading whitespaces when enclosing text in an environment using vim's latex-suite I am using vim with latex-suite plugin.
I have a piece of text, that I want to enclose in verbatim environment. Let's say it looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<errors>
<error>Record not found</error>
</errors>
So I visually select text, press <F5>, type verbatim and press <CR>. I get:
\begin{verbatim}
<?xml version="1.0" encoding="UTF-8"?>
<errors>
<error>Record not found</error>
</errors>
\end{verbatim}
And what I want to get is:
\begin{verbatim}
<?xml version="1.0" encoding="UTF-8"?>
<errors>
<error>Record not found</error>
</errors>
\end{verbatim}
Is there a way to prevent enclosing in environment using this mechanism from removing leading whitespaces? I have a lot xml samples, and I do not want to indent them or enclose in environment manually.
A: One way to do this is to embed XML syntax inside Tex syntax, then use the XML indentation rules on the XML code as determined by the syntax highlighting attribute of the lines in question.
With that you can just run the = indentation over a region and it should do the right thing indentation wise. Or maybe even it'll indent correctly first time.
First, make a .vim/after/syntax/tex directory and add the following code as .vim/after/syntax/tex/xmlembed.vim:
if exists("b:current_syntax")
unlet b:current_syntax
endif
syn include @XML syntax/xml.vim
syn region XMLEmbedded matchgroup=XMLCommand
\ start=+\\begin{verbatim}\n\+<?xml+rs=s+16
\ skip=+\\$+
\ end=+\\end{verbatim}+ contains=@XML
syn cluster texZone add=XMLEmbedded
hi def link XMLCommand texZone
func! TexXML(lnum)
let name = tolower(synIDattr(synID(a:lnum, 1, 1), "name"))
if name =~ 'xml'
return XmlIndentGet(a:lnum, 1)
endif
return -1
endfunc
runtime indent/xml.vim
set indentexpr=TexXML(v:lnum)
What that does is include XML syntax highlighting as @XML and define a region bounded by the begin/end (and also matching \begin{verbatim} part but include the <?xml is perhaps overkill, but just in case you want other non-xml verbose regions it might be worth having.
After that this snippet imports the XML indent rules with runtime indent/xml.vim. XML is indented by an expression, XmlIndentGet, but instead of that the indent expression is set to a wrapper function TexXML. This checks if the current line "looks like xml", and if so indents it like XML, otherwise uses the current indentation. For a line to look like XML the function simply checks if the syntax highlighting matches "xml".
You need to have syntax highlighting on for this to work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596814",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: free speech recognition engines for iOS? I am looking for some free speech recognition engines to use in my iphone application... can you suggest any?
A: Nuance just opened the doors for developers to the Dragon Mobile SDK (they are industry-leaders). have a look at NDEV Mobile
A: There are a couple of wrappers of the Sphinx speech recognition engine (http://cmusphinx.sourceforge.net/) available for iOS
https://github.com/KingOfBrian/VocalKit
Through reading his summary you can see he is actually pointing people towards http://www.politepix.com/openears
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596816",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Android-jquerymobile: how to define css for button onclick I'm using jQueryMobile pages inside my Android's WebView. For my jQM page buttons, i have css like..
jQuery(".pm_btn").css("background-image", "url(bluebutton.png)");
jQuery('.pm_btn').mousedown(function() {
jQuery(this).css("background-image", "url(redbutton.png)";
}).mouseup(function() {
jQuery(this).css("background-image", "url(bluebutton.png)");
});
`
On Button onclick, the background images are flipping correctly when I access jQM page from web browser. But this is not working when I accessed the same page from Android's WebView.
Can anybody plz help me to sort out this issue.
Thanks in advance.
Thanks,
nehatha
A: It worked for me
$('.btn').bind("vmousedown", function() {
jQuery(this).css("background-image", "url(image1.png)");
}).bind("vmouseup", function() {
$(this).css("background-image", "url(image2.png)");
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596817",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can you put span tag inside anchor tag in Html.ActionLink? Can anybody tell me how do I put span tag inside anchor tag?
This doesn't work:
@Html.ActionLink("<span>Home</span>", "Home", "Home",new { @class = "active" })
I get Html encoded output if I do like that.
A: Use Url.Action insted of Html.ActionLink. Try this
<a href="@Url.Action("Home","Home")" class="active">
<span>Home</span>
</a>
A: Do the following :
<a class="active"
href="@Url.Action("YourAction", new { controller = "YourController"})">
<span>content comes here</span>
</a>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596827",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: calculate the arithmetic elements of php array? this i my array
$arr = array(1,2,3,4,5);
How to get the result that calculate the value of this expression ((((1-2) -3)-4)-5)?
A: 2 times the first entry minus the whole sum - looks pretty quick.
echo (2 * reset($arr)) - array_sum($arr);
A: Just substract the sum of all elements but the first from the first element:
echo array_shift($arr) - array_sum($arr); # -13
To preserve the array, change the calculation a little:
echo $arr[0]*2 - array_sum($arr); # -13
And we're glad you didn't ask for eval:
echo eval('return '.implode('-', $arr).';'); # -13
However the best suggestion I can give is that you encapsulate the logic into a class and overload the array with it. So that the object than can provide a method for the calculation (Demo):
class Operands extends ArrayObject
{
public function operate($sign)
{
$sign = max(-1, min(1, $sign.'1'));
$arr = $this->getArrayCopy ();
return $arr[0]*(1-$sign) + $sign*array_sum($arr);
}
public function __invoke($sign) {
return $this->operate($sign);
}
}
$arr = new Operands($arr);
echo $arr('-'), ', ' , $arr('+');
A: <?php echo eval(implode("-", $arr)); ?>
A: Try this:
$arr = array(1,2,3,4,5);
// load the first number to subtract
$result = $arr[0];
$i = 1;
foreach($arr as $item)
{
if ($i !=1) // skip the first one
$result -= $item;
$i++;
}
echo $result;
?>
A: This?
<?php
foreach ($arr as $val)
{
$calc -= $val;
}
echo $calc;
?>
A: Like @mOrSa, but more readable:
<?php
$arr = array(1, 2, 3, 4, 5);
// load the first number to subtract
$result = $arr[0];
for ($i = 1; $i < count($arr); $i++)
{
$result -= $arr[i];
}
echo $result;
?>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596830",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: lastchild for Internet Explorer I know there are some ways to get the "lastchild" work for Internet Explorer. CSS doesn't seem to work that well.
I read about a jQuery version, but am not sure how to do that exactly.
I only need this because I use list styles with border-top and border-bottom to create "shadow-effects".
Here's my website.
The top navigation menu has a lastchild definition in a javascript fild but it doesn't seem to take proper effect:
jQuery("ul.menu li:last-child").addClass("last-child");
jQuery("ul.menu li:first-child").addClass("first-child");
The original CSS was something like that, but this displays the borders left and right in Firefox, too!:
.jqueryslidemenu ul li.first-child a{border-left:none}
.jqueryslidemenu ul.sub-menu li.first-child a{border-left:1px solid #444444!important}
.jqueryslidemenu ul li.last-child a{border-right:none}
.jqueryslidemenu ul.sub-menu li.last-child a{border-right:1px solid #444444!important}
/*IE6 hack to get sub menu links to behave correctly*/
* html .jqueryslidemenu ul li a{display: inline-block;}
I changed it to that and now the right-border only shows up in IE!:
.jqueryslidemenu ul li:first-child a{border-left:none;}
.jqueryslidemenu ul.sub-menu li.first-child a{border-left:1px solid #444444!important;}
.jqueryslidemenu ul li:last-child a{border-right:none;}
.jqueryslidemenu ul.sub-menu li.last-child a{border-right:1px solid #444444!important;}
/*IE6 hack to get sub menu links to behave correctly*/
* html .jqueryslidemenu ul li a{display: inline-block;}
A: Set the CSS programmatically using .children().last().css()
Or if you know which element is that while you are laying it out (in the backend), add a class of last to it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596834",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Rails 3 - ERROR Errno::EINVAL: Invalid argument when testing the page Hio,
i need help. I developed application in Ruby on Rails 3. Its simple application witch some scadfolds and only CRUD operation on mysql database. Because I am Windows 64-bit user i have sometimes problems with some gems(for example mysql2 gem etc.). But until now I have solved every problem. Now i am in situation, when I have application, and already when I test it on localhost I get this error in web browser:
Internal Server Error
Invalid argument
WEBrick/1.3.1 (Ruby/1.8.7/2011-02-18) at localhost:300
Webrick log:
*Started GET "/?mobile=0" for 127.0.0.1 at Thu Sep 29 13:25:53 +0200 2011
DEPRECATION WARNING: Setting filter_parameter_logging in ActionController is deprecated and has no longer effect, please set 'config.filter_parameters' in config/application.rb instead. (called from C:/Sites/stodolist/app/controllers/application_controller.rb:8)
Processing by UsersController#show as HTML
Parameters: {"mobile"=>"0"}
User Load (0.0ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
CACHE (0.0ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
SQL (1.0ms) BEGIN
AREL (1.0ms) UPDATE `users` SET `updated_at` = '2011-09-29 11:25:53', `perishable_token` = '0Mp7RB1VTjml8S7Syqh', `last_request_at` = '2011-09-29 11:25:53' WHERE `users`.`id` = 1
SQL (22.0ms) COMMIT
Task Load (2.0ms) SELECT `tasks`.* FROM `tasks` WHERE (`tasks`.user_id = 1)
Priority Load (0.0ms) SELECT `priorities`.* FROM `priorities` WHERE `priorities`.`id` = 1 LIMIT 1
Cathegory Load (1.0ms) SELECT `cathegories`.* FROM `cathegories` WHERE `cathegories`.`id` = 1 LIMIT 1
Status Load (1.0ms) SELECT `statuses`.* FROM `statuses` WHERE `statuses`.`id` = 1 LIMIT 1
Priority Load (1.0ms) SELECT `priorities`.* FROM `priorities` WHERE `priorities`.`id` = 2 LIMIT 1
Cathegory Load (1.0ms) SELECT `cathegories`.* FROM `cathegories` WHERE `cathegories`.`id` = 2 *LIMIT 1
CACHE (0.0ms) SELECT `statuses`.* FROM `statuses` WHERE `statuses`.`id` = 1 LIMIT 1*
Priority Load (0.0ms) SELECT `priorities`.* FROM `priorities` WHERE `priorities`.`id` = 3 LIMIT 1
Cathegory Load (0.0ms) SELECT `cathegories`.* FROM `cathegories` WHERE `cathegories`.`id` = 3 LIMIT 1
CACHE (0.0ms) SELECT `statuses`.* FROM `statuses` WHERE `statuses`.`id` = 1 LIMIT 1
0m SELECT `priorities`.* FROM `priorities` WHERE `priorities`.`id` = 4 LIMIT 1
CACHE (0.0ms) SELECT `cathegories`.* FROM `cathegories` WHERE `cathegories`.`id` = 1 LIMIT 1
CACHE (0.0ms) SELECT `statuses`.* FROM `statuses` WHERE `statuses`.`id` = 1 LIMIT 1
Timeline Load (1.0ms) SELECT `timelines`.* FROM `timelines` WHERE (`timelines`.user_id = 1)
Rendered users/show.html.erb within layouts/application (421.0ms)
Completed 200 OK in 619ms (Views: 448.0ms | ActiveRecord: 32.0ms)
[2011-09-29 13:25:57] ERROR Errno::EINVAL: Invalid argument*
*C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/railties-3.0.7/lib/railsrack/log_tailer.rb:25:in `write'
C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/railties-3.0.7/lib/rails/rack/log_tailer.rb:25:in `print'
C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/railties-3.0.7/lib/rails/rack/log_tailer.rb:25:in `tail!'
C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/railties-3.0.7/lib/rails/rack/log_tailer.rb:15:in `call'
C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/rack-1.2.3/lib/rack/content_length.rb:13:in `call'
C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/rack-1.2.3/lib/rack/handler/webrick.rb:52:in `service'
C:/RailsInstaller/Ruby1.8.7/lib/ruby/1.8/webrick/httpserver.rb:104:in `service'
C:/RailsInstaller/Ruby1.8.7/lib/ruby/1.8/webrick/httpserver.rb:65:in `run'
C:/RailsInstaller/Ruby1.8.7/lib/ruby/1.8/webrick/server.rb:173:in `start_thread'
C:/RailsInstaller/Ruby1.8.7/lib/ruby/1.8/webrick/server.rb:162:in `start'
C:/RailsInstaller/Ruby1.8.7/lib/ruby/1.8/webrick/server.rb:162:in `start_thread'
C:/RailsInstaller/Ruby1.8.7/lib/ruby/1.8/webrick/server.rb:95:in `start'
C:/RailsInstaller/Ruby1.8.7/lib/ruby/1.8/webrick/server.rb:92:in `each'
C:/RailsInstaller/Ruby1.8.7/lib/ruby/1.8/webrick/server.rb:92:in `start'
C:/RailsInstaller/Ruby1.8.7/lib/ruby/1.8/webrick/server.rb:23:in `start'
C:/RailsInstaller/Ruby1.8.7/lib/ruby/1.8/webrick/server.rb:82:in `start'
C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/rack-1.2.3/lib/rack/handler/webrick.rb:13:in `run'
C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/rack-1.2.3/lib/rack/server.rb:217:in `start'
C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/railties-3.0.7/lib/rails/commands/server.rb:65:in `start'
C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/railties-3.0.7/lib/rails/commands.rb:30
C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/railties-3.0.7/lib/rails/commands.rb:27:in `tap'
C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/railties-3.0.7/lib/rails/commands.rb:27
script/rails:6:in `require'
script/rails:6*
This error shows everytime when I click on some link_to
Here is my system properties:
*
*Windows 7 x86
*Ruby/1.8.7/2011-02-10
*WEBrick/1.3.1
*Rails 3.0.7
My routes:
resources :priorities
resources :timelines
resources :cathegories
resources :statuses
resources :user_sessions
resources :users
resource :user, :as => 'account'
resources :tasks
match 'signup' => 'users#new', :as => :signup
match 'admin' => "application#index", :as => :admin
match 'login' => "user_sessions#new", :as => :login
match 'logout' => "user_sessions#destroy", :as => :logout
root :to => "users#show"
Really dont no where is the error:( I think it can be in routes...
I'm sry for stupid question, I'm newbie..
Development log:
its weird becouse server log look like this:
Started GET "/user" for 127.0.0.1 at Thu Sep 29 14:12:00 +0200 2011
DEPRECATION WARNING: Setting filter_parameter_logging in ActionController is deprecated and has no longer effect, please set 'config.filter_parameters' in config/application.rb instead. (called from C:/Sites/stodolist/app/controllers/application_controller.rb:8)
Processing by UsersController#show as HTML
[1m[35mUser Load (1.0ms)[0m SELECT `users`.* FROM `users` WHERE `users`.`persistence_token` = '6e8fba00deefc7922358a3022942302058a31133d7b2dc98bcc1620a06869d36f81c5f42789da7e4fb7b36bddfd4ad628fe547fde111d9fe18af823e0698e8d5' LIMIT 1
[1m[36mUser Load (2.0ms)[0m [1mSELECT `users`.* FROM `users` WHERE `users`.`id` = 4 LIMIT 1[0m
[1m[35mSQL (0.0ms)[0m BEGIN
[1m[36mAREL (0.0ms)[0m [1mUPDATE `users` SET `updated_at` = '2011-09-29 12:12:01', `last_request_at` = '2011-09-29 12:12:01', `perishable_token` = 'v4g9FCSyQfuOAIFXfUQ' WHERE `users`.`id` = 4[0m
[1m[35mSQL (82.0ms)[0m COMMIT
[1m[36mTask Load (1.0ms)[0m [1mSELECT `tasks`.* FROM `tasks` WHERE (`tasks`.user_id = 4)[0m
[1m[35mTimeline Load (1.0ms)[0m SELECT `timelines`.* FROM `timelines` WHERE (`timelines`.user_id = 4)
Rendered users/show.html.erb within layouts/application (115.0ms)
Completed 200 OK in 321ms (Views: 143.0ms | ActiveRecord: 87.0ms)
A: Ok, i found solution of this prob. I decided to change my webserver to morgel. After two hours of working, no error. Maybe this issue really depand on my enviroment- Win 64bit/ruby/mysql/rails3 and webrick. I will see how its going...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596837",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Caching database query results on webserver in a database using .net cache provider classes I have an e-commerce like site to build and given the frequency and volume of request that we would have to handle, its best to incorporate caching in our code base from the beginning itself. I read about .net 4's system.runtime.cache and system.web.cache. These classes provide cache at application level. There is also a possibility of implementing our own custom provider using outputcacheprovider interface.
Now I was thinking that it would be better to have a small db server at webserver itself which will cache the results of frequently made sql queries which could be server to the web page and will save me a round trip to actual db server and db access.
I went through a lot of blogs but i didnt find anything directly related to this.
Now I have a few questions:
1. Is it good to have small dbserver at webserver to handle frequent queries ?
2. Is it possible to implement this kind of caching using outputcacheprovider ?
A: It wouldn't really do a lot other than put added load on your web server. The only time it might make a difference is if there sufficient lag on your network between the web server & db server to make it worthwhile.
The point of caching is you're holding the data in a processed form in a fast medium, ie memory.
You're better of looking at something like appfabric or memcache to provide your caching rather than a db.
Also, bear in find the difference between caching & outputcaching. caching is holding data in memory for your application to use as it needs. OutputCaching is storing the generated output for a page meaning that future requests get the cached version & you don't have to generate the page every time.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596840",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: ORACLE and Entity Framework. Error:the specified store provider cannot be found in the configuration or is not valid In my project I am using oracle and entity framework together.Both of my machines my developer machine win7 and my server win2008r2 I installed oracle beta entity framework and .net 4.0 framework.
However my projects works on local machine and does not work on server giving the error :
the specified store provider cannot be found in the configuration or is not valid
SystemArgumentException unable to find the requested .net Framework data provider ...
Anyone can help me ?
A: I had this problem before. I followed these instructions then it solved:
with windows 10 x64
1- Install Visual Studio 2015.
2- Install ODAC from http://www.oracle.com/partners/campaign/utilsoft-086879.html.
*install ODTforVS2015 from
http://www.oracle.com/technetwork/topics/dotnet/downloads/odacmsidownload-2745497.html
*copy tnsnames file witch configured in step #2 and paste it to Network folder of destination installation of step #3.
*change C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\Machine.config <system.Data> tag like this:
<system.data>
<DbProviderFactories>
<add name="ODP.NET, Unmanaged Driver" invariant="Oracle.DataAccess.Client" description="Oracle Data Provider for .NET, Unmanaged Driver" type="Oracle.DataAccess.Client.OracleClientFactory, Oracle.DataAccess, Version=4.121.1.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
<add name="ODP.NET, Managed Driver" invariant="Oracle.ManagedDataAccess.Client" description="Oracle Data Provider for .NET, Managed Driver" type="Oracle.ManagedDataAccess.Client.OracleClientFactory, Oracle.ManagedDataAccess, Version=4.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
</DbProviderFactories>
</system.data>
*add this line in web.config for web app, or in App.config if it is console App. under <configurations> </configurations> tag (Under not inside).
<system.data>
<DbProviderFactories>
<add name="ODP.NET, Managed Driver" invariant="Oracle.ManagedDataAccess.Client" description="Oracle Data Provider for .NET, Managed Driver" type="Oracle.ManagedDataAccess.Client.OracleClientFactory, Oracle.ManagedDataAccess, Version=4.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
</DbProviderFactories>
</system.data>
A: in short: do not use ODAC .net drivers, instead use oracle client complete installation.
modifying ODAC components may be a bit diffucilt. So install latest version of oracle client to all machines everything is well.
*
*old answer -
For both machines I installed first oracle data provider for .net and then oracle beta entity framework providers . So for both machines I have multiple oracle client instances.
In my development machine oracle beta entity framework is configured as default client. -I dont know when/how it changed/ who changed -
In server default provider is still old odp.net .
After changing the default provider at server to oracle beta entity framework provider it changed.
Thanks again.
A: In the Application Pool and Advanced Settings...
Have a look at the "Enable 32-Bit Applications" and see if it is enabled. It wasn't set on my Windows 7 64bit and I had the same issues.
I am guessing it might also be fixed by installing the 64bit ODAC but haven't tried that yet.
A: We were installing our application on a windows 2012 server and we were getting the same error, we tried to run the applications in the 32 bit mode , but results are same.
we tried to get the list of DbProviderFactories installed in the machine by a console app and figured out that the ODP.net Managed Driver is missing.
it finally worked when we ran the batch file we found
A: If you are getting this error in 2018 and you are using IIS Express like I am, you may want to check your .csproj settings and ensure that it is running under x64 bitness. (Right click you web application's csproj, go to "Web" tab, under the "Servers" section, change the bitness to x64).
A: Installing ManagedDataAcces solved the problem for me.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596850",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Hiding icefaces autocomplete list when there are no matches Friends!
I use icefaces ice:selectInputText item to represent input box with autocomplete hints list. Backing bean is returning list of suitable hints (it selects hints from one big list on condition that they contains characters already entered by user into input box).
All works fine. The only problem is that when there are no matches at all, I am trying to return empty list (also I've tried to return null instead) - I hope that list of hints would be hidden. But the list remains in the state which was created last time when there were more than 0 hints returned.
If it is possible to get rid of this undesirable behavior, could you please tell me where I can find info on how to achieve this.
thanks in advance,
Rodion
A: We came across this issue as well in our project. There is a bug in ICEfaces that causes the view not to update when the item list becomes empty. This was reported in ICEfaces fora: http://www.icefaces.org/JForum/posts/list/16406.page
The fix is to patch the icefaces-comps.jar package as proposed in the forum post above.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596851",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Move branch start in Mercurial My problem is similar to Mercurial move changes to a new branch, but is not exactly the same.
A colleague of mine started working on a new feature and issued a few local commits. Then he noticed "Oh well, that should go into a named branch" and thus created one. The problem is, the commits before should have been in that branch already. So the simplified history now looks a little like this:
O 7: default
|
O 6: default
|
| O 5: newbranch
| |
| O 4: default
| |
| O 3: default
| /
O 2: default
|
O 1: default
So default now has two open heads: 7 and 4. I'd like to get rid of the open head 4 but of course still have 3 and 4 merged back into the "main" default later on when we merge newbranch back into main (merging them now is undesired as it would bring changes into default that we don't want there yet).
The question is: what's the best way to handle this ?
Do a --close-branch on 5, create a new branch off 2 and re-apply revisions 3-5 ?
As far as I've understood there's no good way to simply say "newbranch started at 3 instead of 5".
Update: Since this is has already been pulled by others I don't want to rebase the revisions in question. Forcing the colleague to recreate/switch branches would be OK since that would affect only one person instead of 5.
A: To get rid of the extra default head, you could:
hg update -r 4
hg commit --close-branch -m "Closed extra default head. The changes from this branch will be merged along with 'newbranch', once it is complete."
When you eventually merge newbranch, it will include revisions 3-5 plus any others that you commit on top of 5.
The only potential problem with this is that revisions 3-4 will not be labeled as part of the named branch. If this is really important for you, then you should close both the extra default head and the newbranch head and start over with a new branch rooted at revision 2.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596854",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Qt: OSX: Where to put (both file manager and exec accessible) resources? im a bit confused about the most proper way to manage resources (files and folders) needed by the application.
I make it clear:
I have an executable ( developing on mac osx with qt ), and a i have a fixed folder hierarchy, where a bunch of configuration files are kept. Those files might be manually edited, added or delete.
Now on windows or linux, i would just easily get those files by simply accessing parent folders, and those folders are freely accessible by any OS file manager.
But in OSX my executable is inside the .APP bundle.
Then i should be able to retrieve resources from within the bundle ( even if resources management in qt creator sucks ), but the user should also be able to open and edit the app bundle, which is not feasibl at all... and i neather want to deploy any resource manager nor put the configs in (eg.)home subfolder ( i want to keep everything together ).
Is there any solution?
Thanks!
A: In OS X terms your config files should really be in Application Support, the user can access them there. However they can also access them from the app bundle if you put them in there by right clicking and selecting View Package Contents, you can then change the files and save them.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596856",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: can getJSON be used to get a value from an html tag id already rendered by a page?? json_decode? what i mean by this is after an html page is rendered, how can i get the value by using the html tag id??
ex: get the value of date by using td_date in my JS function??
below the code that puts the data on the page: listSuccess.php
foreach ($pager->getResults() as $msg)
{
echo "<tr id='td_id' value='$msgId'</tr>";
$date = add_date($msg->getCreatedAt(),$hr=2);
echo "<td class='td_show_contact_item' align='left' id='td_date'>".$date."</td>";
<td align='left' id='td_subject'>
<a href="<?php echo url_for('messagebox/read?cursor=').$cursor ?>" style='color:#ff0000 !important' class='spn_small_red_rbc'><?php echo $msg->getSubject();?></a>
</td>
echo "<td class='td_show_contact_item' align='left' id='td_from'>".$unique_code_from."</td>";
echo "<td id='block_url'>( ".$block_url." )</td>";
echo "</tr>";
++$cursor;
}
so in my JS:
function ax_get_new_msg_details()
{
var mTimer;
$.getJSON('/apps_dev.php/messagebox/newMessageDetails', function(data)
{
var messageExists = $('#' + data.td_id).length > 0;
if (!messageExists)
{
mTimer = setTimeout('ax_get_new_msg_details()',30000);
var str='<tr id="' + data.td_id + '">';
str += "<td class='td_show_contact_item' align='left' id='td_date'>"+data.td_date+'</td>';
str += "<td align='left' id='td_subject'><a href='#' style='color:#ff0000 !important' class='spn_small_red_rbc'>"+data.td_subject+"</a></td>";
str += "<td class='td_show_contact_item' align='left' id='td_from'>"+data.td_from +"</td>";
//str += "<td id='block_url'>"+data.block_url+"</td>";
str +='<tr>';
var tbl = $('#td_date').parents('table');
$(tbl).append(str);
}
});
}
then newMessageDetails.php in my actions.class.php
public function executeNewMessageDetails(sfWebRequest $request)
{
$profile_id = $this->getUser()->getAttribute('profile_id','zero');
$new_msgs = RcMessageBoxTablePeer::getNewMessages($profile_id);
if (count($new_msgs) >= 1)
{
foreach ($new_msgs as $row)
{
$date = $row->getCreatedAt();
$subject = $row->getSubject();
$from = $row->getProfileIdFrom();
$id = $row->getId();
$uc_record = RcProfileTablePeer::getById($from);
$uc_from = $uc_record->getUniqueCode();
//$block_url = 'Block User',"blocklist/block?unqiue_code=$uc_from",'class=link_medium_blue');
}
$output = array("td_date" => $date, "td_subject" => $subject, "td_from" => $uc_from, "td_id" => $id);
}
else
$output = "";
return $this->renderText(json_encode($output));
}
the data that i get from the JS function is correct but i need to somehow know that what is actually already on my page ie what was rendered already differs from what json returns and if data differs...update the page with the new json data
any advice?
A: Personally I use firefox and the web developer tool bar it not only allows you to see the source code but also allows you to view the generated source code, plus lots of other very useful tools hope this helps you.
A: Why not include your td_id in your tr tag and just compare the incoming id with the existing id?
var str='<tr id="' + data.td_id + '">';
Then in your update put this if condition around your code:
var messageExists = $('#' + data.td_id).length > 0;
if (!messageExists) {
// your existing code
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596859",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Stored procedure exception handling SQL> DECLARE
2 TotalUpd NUMBER(36) := 0;
3 BEGIN
4 dbms_output.put_line ('Job Start time............... : ' || to_char(SYSDATE, ' hh24:mi:ss'));
5 UPDATE Asset SET _status = 'PROGRESS' WHERE status is null;
6 TotalUpd := SQL%ROWCOUNT;
7 dbms_output.put_line('Total Records Updated. : ' || TotalUpd);
8 COMMIT;
9 EXCEPTION
10 WHEN NO_DATA_FOUND THEN
11 dbms_output.put_line ('No more data to update.');
12 WHEN OTHERS THEN
13 dbms_output.put_line ('Error while status as SUCCESS ');
14 END ;
15 /
The result for the above procedure is
Job Start time............... : 04:41:41
Total Records Updated. : 0
But my expected result is "No more row to be updated" must be printed,since i have truncated the table Asset.Please tell where I went wrong in this.
A: The NO_DATA_FOUND error is not thrown in update statements.
It is thrown in select into statements if the select statement would return nothing.
See also Tahiti on select into under select_item: *If the SELECT INTO statement returns no rows, PL/SQL raises the predefined exception NO_DATA_FOUND.*
Oracle does not consider it an exception if an update statement does not update anything, hence no exception is thrown. However, if a select into statement cannot fill the variables, it is considered an error (and therefore in this case the NO_DATA_EXCEPTION is thrown(
A: it is as simple as the update does not geneate an error if there is no data.
you need to look at the value of TotalUpd if you want to control the flow of your code
DECLARE
TotalUpd NUMBER(36) := 0;
BEGIN
dbms_output.put_line ('Job Start time............... : '
|| TO_CHAR(SYSDATE, ' hh24:mi:ss'));
UPDATE Asset SET _status = 'PROGRESS' WHERE status IS null;
TotalUpd := SQL%ROWCOUNT;
IF TotalUpd = 0 THEN
dbms_output.put_line ('No more data to update.');
ELSE
dbms_output.put_line('Total Records Updated. : '
|| TotalUpd);
END IF;
COMMIT;
EXCEPTION
WHEN OTHERS THEN
dbms_output.put_line ('Error while status as SUCCESS ');
END;
A: NO_DATA_FOUND is thrown if a select into does not return any row, not if no rows were updated after an update statement.
I suggest you move your logic for handling this exception after the update itself:
IF (SQL%ROWCOUNT = 0) THEN
dbms_output.put_line ('No more data to update.');
A: Think NO_DATA_FOUND exception is only raised by a SELECT statement which you aren't using. Try testing SQL%COUNT and output as required.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596860",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Regex to find inner if conditions I had a regex to find single if-then-else condition.
string pattern2 = @"if( *.*? *)then( *.*? *)(?:else( *.*? *))?endif";
Now, I need to extend this & provide looping if conditions. But the regex is not suitable to extract the then & else parts properly.
Example Looped IF condition:
if (2 > 1) then ( if(3>2) then ( if(4>3) then 4 else 3 endif ) else 2 endif) else 1 endif
Expected Result with Regex:
condition = (2>1)
then part = ( if(3>2) then ( if(4>3) then 4 else 3 endif ) else 2 endif)
else part = 1
I can check if else & then part have real values or a condition. Then i can use the same regex on this inner condition until everything is resolved.
The current regex returns result like:
condition = (2 > 1)
then part = ( if( 3>2) then ( if(4>3) then 3
else part = 3
Meaning, it returns the value after first "else" found. But actually, it has to extract from the last else.
Can someone help me with this?
A: You can adapt the solution on answer Can regular expressions be used to match nested patterns? ( http://retkomma.wordpress.com/2007/10/30/nested-regular-expressions-explained/ ).
That solution shows how to match content between html tags , even if it contains nested tags. Applying the same idea for parenthesis pairs should solve your problem.
EDIT:
using System;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
String matchParenthesis = @"
(?# line 01) \((
(?# line 02) (?>
(?# line 03) \( (?<DEPTH>)
(?# line 04) |
(?# line 05) \) (?<-DEPTH>)
(?# line 06) |
(?# line 07) .?
(?# line 08) )*
(?# line 09) (?(DEPTH)(?!))
(?# line 10) )\)
";
//string source = "if (2 > 1) then ( if(3>2) then ( if(4>3) then 4 else 3 endif ) else 2 endif) else 1 endif";
string source = "if (2 > 1) then 2 else ( if(3>2) then ( if(4>3) then 4 else 3 endif ) else 2 endif) endif";
string pattern = @"if\s*(?<condition>(?:[^(]*|" + matchParenthesis + @"))\s*";
pattern += @"then\s*(?<then_part>(?:[^(]*|" + matchParenthesis + @"))\s*";
pattern += @"else\s*(?<else_part>(?:[^(]*|" + matchParenthesis + @"))\s*endif";
Match match = Regex.Match(source, pattern,
RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase);
Console.WriteLine(match.Success.ToString());
Console.WriteLine("source: " + source );
Console.WriteLine("condition = " + match.Groups["condition"]);
Console.WriteLine("then part = " + match.Groups["then_part"]);
Console.WriteLine("else part = " + match.Groups["else_part"]);
}
}
}
A: If you replace endif with end you get
if (2 > 1) then ( if(3>2) then ( if(4>3) then 4 else 3 end) else 2 end) else 1 end
and you also got a perfectly fine Ruby expression. Download IronRuby and add references to IronRuby, IronRuby.Libraries, and Microsoft.Scripting to your project. You find them in C:\Program Files\IronRuby 1.0v4\bin then
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
using IronRuby;
and in your code
var engine = Ruby.CreateEngine();
int result = engine.Execute("if (2 > 1) then ( if(3>2) then ( if(4>3) then 4 else 3 end ) else 2 end) else 1 end");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596861",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Input Validation Silverlight i have a textbox which is not bound.
<TextBox x:Name="inputBox" Grid.Column="1" Grid.Row="1" />
The textbox is to only accept numbers (doubles) and show a warning at once something else(letters or symbols) is written in to the box.
On the TextChanged event, i do some calculations depending on the value enterd and show it in a TextBlock, therefor i need some way of validating that the input is a number as the user writes in the box, but i am having a hard time finding a good way to do this.
Any ideas?
A: What I have used before is a regex to disallow non-numeric characters. Maybe this is something that could be adapted?
My code was for a port on a server so only numbers but should be straightforward to add the . for doubles (I think "[^0-9\.]" should work but regexs aren't something I am fantastically good at :-) )
// Text change in Port text box
private void txtPort_TextChanged(object sender, TextChangedEventArgs e)
{
// Only allow numeric input into the Port setting.
Regex rxAllowed = new Regex(@"[^0-9]", RegexOptions.IgnoreCase);
txtPort.Text = rxAllowed.Replace(txtPort.Text, "");
txtPort.SelectionStart = txtPort.Text.Length;
}
A: This is another example of when to use a Behavior.
public class TextBoxValidator : Behavior<TextBox>
{
protected override void OnAttached()
{
AssociatedObject.TextChanged += new TextChanged(OnTextChanged);
}
private void OnTextChanged(object sender, TextChangedEventArgs e)
{
// Here you could add the code shown above by Firedragon or you could
// just use int.TryParse to see if the number if valid.
// You could also expose a Regex property on the behavior to allow lots of
// types of validation
}
}
You didn't really explain what actions you wanted to take when the user enters an invalid value.
A: Maybe it would be better to use Binding with ValueConverter that will update TextBlock's content. In this case you can implement validation for numeric value in within converter.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596865",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Smaato and iAds combined i am willing to implement iAds by default in my application which is now correctly showing, and also I have properly implemented Smaato's SDK.
Is there any method to show by default iAds and when this don't serves me an ad, then pull from Smaato?
Thank you
A: There is an example for this within the Smaato Ad SDK. When you open the folder iSomaDemoApp/iPhone you will see the files
SOMAiAdBannerView.h and
SOMAiAdBannerView.m
which implement the behavior you are looking for.
The usage is the same as a default SOMABannerView, but you can have a look at iAdViewController.m in the same directory to see an example.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596874",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: LINQ (Dynamic): OrderBy within a GroupBy using dynamic linq? I had the following query using normal linq and it was working great (using anonymous type),
var result = from s in Items
group s by s.StartTime into groupedItems
select new {groupedItems.Key, Items= groupedItems.OrderBy(x => x.Name) };
But using Dynamic Linq I cannot get it to order by within the groupby.
result = Items.GroupBy("StartTime", "it").OrderBy("Name");
It states the Name isn't available. It is worth noting that if I take my OrderBy off, everything works great but items inside each "Key" are not ordered.
A: This is a good question!
I simulated your situation by creating a class called Item.
public class Item
{
public DateTime StartTime { get; set; }
public string Name { get; set; }
}
and then created a basic list of items to do the groupby.
List<Item> Items = new List<Item>()
{
new Item() { StartTime = DateTime.Today, Name = "item2"},
new Item() { StartTime = DateTime.Today, Name = "item1"},
new Item() { StartTime = DateTime.Today.AddDays(-1), Name = "item3"},
};
Now the big difference in the 2 queries is where the order by is being performed. In the first query, when you perform groupedItems.OrderBy(x => x.Name) its being performed on a IGrouping<DateTime,Item> or a single entry as it iterates through all the groupings.
In the second query, the orderby is being performed after the fact. This means you're doing an orderby on a IEnumerable<IGrouping<DateTime,Item>> because the iterations have already happened.
Since Microsoft was nice they added something to help deal with this for expressions. This overload allows you to specify the item returned as it iterates through the collection. Here's an example of the code:
var expressionResult = Items.GroupBy(x => x.StartTime,
(key, grpItems) => new { key, Items = grpItems.OrderBy(y => y.Name) });
The second part of the GroupBy you can specify a lambda expression that takes a key and a grouping of items under that key and return an entry that you specify, which is the same as you're doing in the original query.
Hope this helps!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596878",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: selecting rows from table which have distinct values for a column In my thread based messaging system, the table schema is
> messages table
id(int auto incr primary key)
body(varchar)
time(datetime)
>message_reference table
id(int auto incr primary key)
message_id(forgain key from message table)
sender
receiver
Here, I want to select the first message id which is sent to a new receiver and sender is the user who is logged in.
Doing this with multiple queries and some code is obviously possible but can it be done with a single query for performance issues??
A: You can try
EDIT:
If the id is auto increment, then the id will also increase with time and you can use:
SELECT message_reference.message_id, message_reference.receiver, messages.body
FROM message_reference, messages
WHERE message_reference.message_id IN (SELECT MIN(message_reference.message_id)
FROM message_reference
GROUP BY message_reference.receiver)
AND message_reference.message_id = messages.id AND message_reference.sender = <sender>
A: Here's my best guess as to what you want, but it would be easier if you gave known inputs, example data, and expected output.
SELECT
MR2.message_id
FROM (
SELECT
MR.sender,
MR.receiver,
M.MIN(`time`) AS min_time
FROM
Message_References MR -- Either use plural names (my personal preference) or singular, but don't mix them
INNER JOIN Messages M ON
M.id = MR.message_id
WHERE
MR.sender = <sender>
GROUP BY
MR.received) SQ
INNER JOIN Message_References MR2 ON
MR2.sender = SQ.sender AND
MR2.receiver = SQ.receiver AND
MR2.`time` = SQ.min_time
A: select mr.message_id from
message_reference as mr inner join
(select mr1.reciever max(m1.time) as time from messages as m1
inner join message_reference as mr1 on mr1.message_id = m1.id
group by mr1.reciever) as last
on mr.reciever = last.reciever and mr.time = last.time
join message reference with "maxtime per reciever" table on reciever and time
A: Well I got the answer, Just a group by query worked the way I wanted. I used query
SELECT SENDER,
RECEIVER,
BODY,
TIME,
MESSAGE_ID
FROM MESSAGE_REF JOIN MESSAGE
ON MESSAGE.ID=MESSAGE_REF.MESSAGE_ID
ORDER BY 'TIME' GROUP BY RECEIVER`
Thanks everyone for the help.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596879",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: RSA encryption/decryption using java API is generating BadPaddingException:Data must start with zero public class RSAAPI extends JFrame implements ActionListener{
JButton encrypt,decrypt,clear,exit;
JLabel plainlbl,encrlbl,decrlbl;
JTextArea plainText,encrText,decrText;
static KeyPair kp;
static KeyPairGenerator kpg;
static Cipher cipher;
static PublicKey publicKey;
static PrivateKey privateKey;
public RSAAPI()
{
setLayout(null);
encrypt=new JButton("ENCRYPT");
decrypt=new JButton("DECRYPT");
clear=new JButton("CLEAR");
exit=new JButton("EXIT");
plainText=new JTextArea();
encrText=new JTextArea();
decrText=new JTextArea();
plainlbl=new JLabel("PLAIN-TEXT");
encrlbl=new JLabel("ENCRYPTED-TEXT");
decrlbl=new JLabel("DECRYPTED-TEXT");
plainlbl.setBounds(30,20,120,15);
plainText.setBounds(30,40,400,150);
encrypt.setBounds(180,195,90,15);
encrlbl.setBounds(30,215,120,15);
encrText.setBounds(30,235,400,150);
decrypt.setBounds(180,390,90,15);
decrlbl.setBounds(30,410,120,15);
decrText.setBounds(30,430,400,150);
clear.setBounds(80,585,90,15);
exit.setBounds(250,585,90,15);
add(encrypt);
add(decrypt);
add(clear);
add(plainlbl);
add(decrlbl);
add(encrlbl);
add(exit);
add(plainText);
add(encrText);
add(decrText);
encrypt.addActionListener(this);
decrypt.addActionListener(this);
clear.addActionListener(this);
exit.addActionListener(this);
setSize(500,650);
setVisible(true);
decrypt.setEnabled(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae)
{
byte[] inData,outData;
if(ae.getSource()==encrypt)
{
try{
inData= plainText.getText().getBytes();
outData=RSAAPI.encryptData(inData);
encrText.setLineWrap(true);
encrText.setText(new String(outData));
decrypt.setEnabled(true);
}
catch(Exception e){
e.printStackTrace();
}
}
else if(ae.getSource()==decrypt)
{
try{
inData= encrText.getText().getBytes();
outData=RSAAPI.decryptData(inData);
decrText.setLineWrap(true);
decrText.setText(new String(outData));
decrypt.setEnabled(false);
}
catch(Exception e){
e.printStackTrace();
}
}
else if(ae.getSource()==clear)
{
plainText.setText(null);
encrText.setText(null);
decrText.setText(null);
decrypt.setEnabled(false);
}
else if(ae.getSource()==exit)
{
System.exit(0);
}
}
public static byte[] encryptData(byte[] inData) throws Exception
{
publicKey=kp.getPublic();
cipher=Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE,publicKey);
return cipher.doFinal(inData);
}
public static byte[] decryptData(byte[] inData) throws Exception
{
privateKey=kp.getPrivate();
cipher=Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE,privateKey);
return cipher.doFinal(inData);
}
public static void main(String[] args) throws Exception
{
kpg=KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024);
kp=kpg.genKeyPair();
new RSAAPI();
}
}
A: You'll find that you are getting a discrepancy between the byte array that you have encrypted and are setting as a string in your JTextArea and the byte array that you are trying to decrypt.
Try to use Base64 encoding for displaying your encrypted data as such:
encrText.setText(new String(new BASE64Encoder().encode(outData)));
and
inData = new BASE64Decoder().decodeBuffer(encrText.getText());
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596882",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Cross-domain jQuery.getJSON from a Node.JS (using express) server does not work in Internet Explorer This is an annoying problem, and I don't suppose that it's only IE that has this problem. Basically I have a Node.js server, from which I am making cross-domain calls to get some JSON data for display.
This needs to be a JSONP call and I give a callback in the URL. What I am not sure is, how to do this?
So the website (domainA.com) has an HTML page with a JS script like this (all works fine in Firefox 3):
<script type="text/javascript">
var jsonName = 'ABC'
var url = 'http://domainB.com:8080/stream/aires/' //The JSON data to get
jQuery.getJSON(url+jsonName, function(json){
// parse the JSON data
var data = [], header, comment = /^#/, x;
jQuery.each(json.RESULT.ROWS,function(i,tweet){ ..... }
}
......
</script>
Now my Node.js server is very simple (I'm using express):
var app = require('express').createServer();
var express = require('express');
app.listen(3000);
app.get('/stream/aires/:id', function(req, res){
request('http://'+options.host+':'+options.port+options.path, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body); // Print the google web page.
res.writeHead(200, {
'Content-Type': 'application/json',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': 'true'
});
res.end(JSON.stringify(JSON.parse(body)));
}
})
});
How can I change these two so they will work with cross-domain GET in IE? I have been searching the internet and there seem to be a few different things like jQuery.support.cors = true; which does not work. There also seem to be a lot of lengthy workarounds.
There is no real 'ideal' design pattern which I have been able to find for this type of thing.
Seeing as I have control over both the web page and the cross domain web service I'm sending to what is the best change to make to ensure compatability across all IE versions along with FireFox, Opera, Chrome etc?
Cheers!
A: Say we have two servers, myServer.com and crossDomainServer.com, both of which we control.
Assuming we want a client of myServer.com to pull some data from crossDomainServer.com, first that client needs to make a JSONP request to crossDomainServer.com:
// client-side JS from myServer.com
// script tag gets around cross-domain security issues
var script = document.createElement('script');
script.src = 'http://crossDomainServer.com/getJSONPResponse';
document.body.appendChild(script); // triggers a GET request
On the cross-domain server we need to handle this GET request:
// in the express app for crossDomainServer.com
app.get('/getJSONPResponse', function(req, res) {
res.writeHead(200, {'Content-Type': 'application/javascript'});
res.end("__parseJSONPResponse(" + JSON.stringify('some data') + ");");
});
Then in our client-side JS we need a global function to parse the JSONP response:
// gets called when cross-domain server responds
function __parseJSONPResponse(data) {
// now you have access to your data
}
Works well across a wide variety of browsers, IE 6 included.
A: The following code shows how to handle the GET request (using express) and how to wrap the JSON response using the callback given:
app.get('/foo', function(req, res){
res.header('Content-Type', 'application/json');
res.header('Charset', 'utf-8')
res.send(req.query.callback + '({"something": "rather", "more": "pork", "tua": "tara"});');
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596885",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Resorting an NSMutableArray How does one resort an NSMutableArray using an index?
I would like to take an index e.g. 9 and everything up to 9, 0 - 8, needs to be put at the end of the array so the array would look something like this.
9, 10, 11, 12, 13, 0, 1, 2, 3, 4, 5, 6, 7, 8
in terms of the positioning.
How is this done in objective C?
Thanks
A: If you just want to move objets at index 0-8 to the end of the array, that's quite easy:
NSRange r = NSMakeRange(0,9); // the range of items to push to the end
// extract the first 9 items in the array to keep them around
NSArray* first9 = [yourArray subarrayWithRange:r];
// remove them from the original NSMutableArray
[yourArray removeObjectsInRange:r];
// add them back to the end
[yourArray addObjectsFromArray:first9];
A: NSMutableArray implements all the sort functions that NSArray does.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596887",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android - AES decryption failing with strange content lengths i am trying to decode an AES encrypted data that i get from a webservice.
The encrypted length is: 4256 bytes
The decrypted length is: 4247 bytes
Baiscally i think that would be ok because of some padding or something...
BUT. the data actually decrypts fine to plain text. Except that some characters are missing at the end.
What could possibly cause the missing characters at the end?
Here comes my decryption code:
public static byte[] decrypt(byte[] input) throws Exception {
byte[] rawKey = getKey("bla".getBytes());
SecretKeySpec secretKeySpec = new SecretKeySpec(rawKey, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
AlgorithmParameterSpec iv = new IvParameterSpec(new byte[] { 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, iv);
return cipher.doFinal(input);
}
A: Posting this as an answer because it's too long for a comment :(
Problem solved, it never was the decryption that was causing the error. Decryption was fine.
The actual problem was me, trying to convert the string to a json object while it was a json array.
That in combination with a logcat limit of 4k characters masked to actual json error messages and cut off my debug messages (so there never were any characters missing)...
A: As Paŭlo says, the problem is almost certainly in the padding. Set up a test decrypt() method with no padding: "AES/CBC/NoPadding" IIRC. Decrypt the same cyphertext and have a look at the actual bytes of padding that have been added to the end of the message. That should tell you what padding (if any) is actually being added to the message.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596888",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Turn on the network provider Is it possible to turn on the phone radios (3G/Data connection) from an android application, without navigating to the settings page?
How?
A: This question is similar to: how to turn internet connection (GPRS/EDGE/3G) on/off
Have a look at the project mentioned in the answer: http://code.google.com/p/apndroid/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596892",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Windows Authentication using roles for CRUD restrictions I am a student who is working on a website that has some things in common with SharePoint. I use ASP.NET MVC 3 to create an intranet site so people can be authenticated by Active Directory. I have trouble implementing these requirements:
*
*Users can define roles (not AD groups) and link Active Directory users to these roles.
*When documents or folders are uploaded, the user can give roles CRUD access to the document or can restrict roles from it.
Please help me or give me a link to a good article:)
A: CREATE TABLE role
(
role NVARCHAR(50) NOT NULL PRIMARY KEY,
create BIT NOT NULL,
read BIT NOT NULL,
update BIT NOT NULL,
delete BIT NOT NULL
)
CREATE TABLE item
(
id INT NOT NULL PRIMARY KEY,
name NVARCHAR(50) NOT NULL,
id_parent INT,
CONSTRAINT FK_item_item FOREIGN KEY(id_parent) REFERENCES item(id)
)
CREATE TABLE user
(
id INT NOT NULL PRIMARY KEY,
adUserName NVARCHAR(50) NOT NULL,
role NVARCHAR(50) NOT NULL,
CONSTRAINT FK_user_role FOREIGN KEY(role) REFERENCES role(role)
)
CREATE TABLE user_item_rights
(
id_user INT NOT NULL,
id_item INT NOT NULL,
create BIT NOT NULL,
read BIT NOT NULL,
update BIT NOT NULL,
delete BIT NOT NULL,
CONSTRAINT PK_user_item_rights PRIMARY KEY(id_user,id_item),
CONSTRAINT FK_user_item_rights_user FOREIGN KEY(id_user) REFERENCES user(id),
CONSTRAINT FK_user_item_rights_item FOREIGN KEY(id_item) REFERENCES item(id)
)
This should give you a idea of how you could implements this. You could also translate it to classes. You could also implement CRUD inheritance and so, or define a role_item_right table.
In my idea the user_item_rights overrides the default settings in the role.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596894",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Unable to instantiate subclass of WakefulIntentService as a receiver I'm implementing a datalogger service using WakefulIntentService and AlarmManager. I'm having trouble instantiating the receiver, however. Here's what I'm getting when I try to run the app.
ERROR/AndroidRuntime(3181): java.lang.RuntimeException: Unable to instantiate receiver my.package.WakefulLoggerIntentService: java.lang.InstantiationException: my.package.WakefulLoggerIntentService
Here's the relevant parts of the service class:
public class WakefulLoggerIntentService extends WakefulIntentService
{
public WakefulLoggerIntentService()
{
super("WakefulLoggerIntentService");
}
@Override
protected void doWakefulWork( Intent intent )
{
// Do the actual data logging.
}
}
I've added receiver element to my manifest:
<receiver android:name=".WakefulLoggerIntentService">
</receiver>
And here's the part that uses AlarmManager to schedule the logging events:
Intent i = new Intent(getApplicationContext(), WakefulLoggerIntentService.class);
PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), 0, i, 0);
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 30000, pi);
What am I missing?
A: WakefulLoggerIntentService is a Service. It is not a BroadcastReceiver.
To use WakefulIntentService, you need a BroadcastReceiver that is triggered by the alarm and, in turn, calls sendWakefulWork() to kick off your WakefulLoggerIntentService.
Also, you need to have your WakefulLoggerIntentService be registered in the manifest as a <service>, not a <receiver>.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596898",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Bind unbound Services in Android I'm developing a Android Service. I would like the service to run even when the application not is active. So I start it without binding it:
startService(new Intent(Service.class.getName()));
Now it will run continuously until I choose to stop it, right?
If I, from another activity, bind the service will it stop when I unbind it?
A: Not necessarily. However, you have to remember that if there is memory pressure, it may be killed depending on the priorities (and if it is unbound, any visible app will probably have higher priority). The lifecycle is described here:
http://developer.android.com/reference/android/app/Service.html#ProcessLifecycle
A: When the last client unbinds from the service, the system destroys the service (unless the service was also started by startService()).
It mean that your service will not stop even you unbind service from all activity in case of you had started service as startService()
For more details about bound service follow bellow link
Bound services
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596908",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MySQL query to return an avg price per month(get the month out of the date formated 2010-03-30 for example) I have three tables...
Given the following tables I would like to know how to write a query to return all the book sorted by month and with a
average price per month table (that would be something like SUM(invoices.total)/COUNT(invoices.total).
I have a date field which has a format of 2010-03-30, and I would like to get the months out of if…so I can sort the sum
by month. I'm using PHP and MySQL.
Thank you in advance!
books
-call_started
books_chapters
-id
invoices
-id
-invoice_type
-chapters_id
-total
A: I can not construct the full query from the schema in your question but you can group the results - GROUP BY(CONCAT(YEAR(date_field), MONTH(date_field))
If you elaborate or comment, I will improve my answer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596914",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Should meta tag fb:admins include the app:id number as well? I developed an application which produces many open graph instances. Each of these instances has a like button and a connect forum.
In my meta I specify my app:id and fb knows I am an admin for every forum. I can store the facebook ID of each of the open graph instances (my customers) and set app:admins as a meta tag.
*
*If I set app:admins, do I need to include my own ID? Will FB still know I own the app and have admin rights if I don't include my own ID? I would prefer not to have to add my own ID to each og instance.
*In initial testing I found that og didn't seem to work for me if I used both app:id and app:admins meta tags but I was not able to thoroughly test it before I gave up and just went with app:id.
A: For what you want you should just use the fb:app_id in your Open Graph tags. Any admins can be added as admins of your app in the Dev App. You could also have a separate app for each customer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596916",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: WinRT - TCP clients? I am building an IRC client in the new WinRT (.NET 4.5) framework for Windows 8 Metro applications.
However, I have some issues. I've already figured out that I need to use a StreamSocket to read TCP data, but I may be doing something wrong.
The reason I believe this is because I am not receiving any data.
Below you see my code. I haven't been able to find any code samples on the web regarding this.
class IRCClient
{
private StreamSocket tcpClient;
public string Server = "holmes.freenode.net";
public int Port = 6665;
public IRCClient()
{
tcpClient = new StreamSocket();
}
public async void Connect()
{
await tcpClient.ConnectAsync(
new Windows.Networking.HostName(Server),
Port.ToString(),
SocketProtectionLevel.PlainSocket);
DataReader reader = new DataReader(tcpClient.InputStream);
string data = reader.ReadString(reader.UnconsumedBufferLength);
MessageDialog dialog = new MessageDialog(data);
}
}
Data is always an empty string following that code. Furthermore, UnconsumedBufferLength always returns 0.
How come?
A: You need to tell the DataReader to read bytes from the stream before you interpret them (ReadString just interprets the bytes already read).
So, if you want to read a string of 20 bytes, do this:
DataReader reader = new DataReader(tcpClient.InputStream);
await reader.LoadAsync(20);
string data = reader.ReadString(reader.UnconsumedBufferLength);
If you want to read a string up to 20 bytes, do this:
DataReader reader = new DataReader(tcpClient.InputStream);
reader.InputStreamOptions = InputStreamOptions.Partial;
await reader.LoadAsync(20);
string data = reader.ReadString(reader.UnconsumedBufferLength);
See this video for more info: http://channel9.msdn.com/Events/BUILD/BUILD2011/PLAT-580T
Note that DataReader does not give you message boundaries; it's just a more convenient way of waiting for and reading binary data from a stream. You still need message framing.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596919",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Sorting based on one of many related entities Entity B (Book) has a one-to-many relationship with the entity D (Description). The idea is that a book has different descriptions for different languages.
I want to sort books based on their titles (D.title) for a given language (D.languageID)
If B had one-to-one relationship to D, I would do something like:
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"d.title" ascending:YES];
Of course, you may say, the model does not prevent a book from having many descriptions with the same languageID. But in this case any (e.g. the first) description would be ok for me.
Is my model wrong? What's the best solution now?
A: This is logically not possible. If you have many objects B belonging to A, which B is the sort routine supposed to take?
For example you have the entity A "Parent" and the entity B "Child" and the attribute of B "dateOfBirth". You cannot sort all Parent objects according to the lowest birth date because if two different parents have two children each, it is possible that each of them has a child that is older than one of the other's.
Clear?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596920",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Deploy / build application for OSX I have created my first XE2 FM HD application.
I have my OSX machine connected and running debug builds on OSX works fine, but I don't have a way to create a release version and copy it to another computer.
I tried just copying over the Package made by the debug but that's missing files.
Inside XE2 I went to Project -> Deployment.
For the OSX Debug deployment I have a green button, but under OSX Release deployment I don't.
Clues?
A: Here's step-by-step instructions for building the App bundle and putting in the required dynamic link library:
*
*Create a folder called MyApp.app
*Create a subfolder in Myapp.app called Contents
*Create a subfolder in Contents called MacOS
*Create a subfolder in Contents called Resources
*From your build, copy Info.plist into Contents
*From your build, copy the Mac binary to MacOS
*From your build, copy the icon to Resources
*Copy libcgunwind.1.0.dylib to MacOS
*Copy the .app folder to your Mac and double-click it to run
You will find libcunwind.1.0.dylib on your Mac where you installed the platform assistant, most likely:
/Users/username/Applications/Embarcadero/PAServer/
Here's a video tutorial on how to create the manual install Disk Image installer on the Mac.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596923",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Simple GWT RequestFactory crashes Used this http://code.google.com/webtoolkit/doc/latest/DevGuideRequestFactory.html tutorial to understand the basic concepts, but having problems running my app from Eclipse:
15:48:04.384 [ERROR] [Main] Uncaught exception escaped
com.google.web.bindery.event.shared.UmbrellaException: One or more exceptions caught, see full set in UmbrellaException#getCauses
at com.google.web.bindery.requestfactory.shared.impl.AbstractRequestContext.fail(AbstractRequestContext.java:727)
at com.google.web.bindery.requestfactory.shared.impl.AbstractRequestContext$5.onTransportFailure(AbstractRequestContext.java:1104)
at com.google.web.bindery.requestfactory.gwt.client.DefaultRequestTransport$1.onResponseReceived(DefaultRequestTransport.java:140)
at com.google.gwt.http.client.Request.fireOnResponseReceived(Request.java:287)
at com.google.gwt.http.client.RequestBuilder$1.onReadyStateChange(RequestBuilder.java:395)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103)
at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172)
at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessagesWhileWaitingForReturn(BrowserChannelServer.java:337)
at com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:218)
at com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:136)
at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:561)
at com.google.gwt.dev.shell.ModuleSpace.invokeNativeObject(ModuleSpace.java:269)
at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeObject(JavaScriptHost.java:91)
at com.google.gwt.core.client.impl.Impl.apply(Impl.java)
at com.google.gwt.core.client.impl.Impl.entry0(Impl.java:213)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103)
at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172)
at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessages(BrowserChannelServer.java:292)
at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:546)
at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:363)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.RuntimeException: Server Error 500 <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<title>Error 500 INTERNAL_SERVER_ERROR</title>
</head>
<body><h2>HTTP ERROR: 500</h2><pre>INTERNAL_SERVER_ERROR</pre>
<p>RequestURI=/gwtRequest</p><p><i><small><a href="http://jetty.mortbay.org/">Powered by Jetty://</a></small></i></p><br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
</body>
</html>
at com.google.web.bindery.requestfactory.shared.Receiver.onFailure(Receiver.java:44)
at com.google.web.bindery.requestfactory.shared.impl.AbstractRequest.onFail(AbstractRequest.java:118)
at com.google.web.bindery.requestfactory.shared.impl.AbstractRequestContext.fail(AbstractRequestContext.java:707)
at com.google.web.bindery.requestfactory.shared.impl.AbstractRequestContext$5.onTransportFailure(AbstractRequestContext.java:1104)
at com.google.web.bindery.requestfactory.gwt.client.DefaultRequestTransport$1.onResponseReceived(DefaultRequestTransport.java:140)
at com.google.gwt.http.client.Request.fireOnResponseReceived(Request.java:287)
at com.google.gwt.http.client.RequestBuilder$1.onReadyStateChange(RequestBuilder.java:395)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103)
at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172)
at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessagesWhileWaitingForReturn(BrowserChannelServer.java:337)
at com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:218)
at com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:136)
at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:561)
at com.google.gwt.dev.shell.ModuleSpace.invokeNativeObject(ModuleSpace.java:269)
at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeObject(JavaScriptHost.java:91)
at com.google.gwt.core.client.impl.Impl.apply(Impl.java)
at com.google.gwt.core.client.impl.Impl.entry0(Impl.java:213)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103)
at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172)
at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessages(BrowserChannelServer.java:292)
at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:546)
at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:363)
at java.lang.Thread.run(Unknown Source)
Here's the code that fails:
final EventBus eventBus = new SimpleEventBus();
final TestEntityRequestFactory requestFactory = GWT.create(TestEntityRequestFactory.class);
requestFactory.initialize(eventBus);
final Button button = new Button("omg");
RootPanel.get().add(button);
TestEntityRequest testEntityRequest = requestFactory.testEntityRequest();
Request<String> createReq = testEntityRequest.getOmg();
createReq.fire(new Receiver<String>() {
@Override
public void onSuccess(String arg0) {
button.setText(arg0);
}
});
I know my question is quite abstract, please use comments to ask for required details.
A: The problems is related that in GWT 2.4 they have introduced a special annotation processor that requestfactory-apt that you have to run before your request factory will work fine. Here's the solution http://vivagwt.blogspot.com/2011/09/requestfactory-en-gwt-24.html
I don't know Spanish but managed to understand the solution :-)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596926",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: CASE query clarification New to SQL and I've just created a SQL query with assitance:
SELECT CASE
WHEN exists (SELECT CLIENT_CODE FROM STG_DM_CLIENT
WHERE CLIENT_CODE
NOT IN (SELECT CLIENT_CODE FROM DM_CLIENT)) THEN 'A'
else
WHEN exists (SELECT STG.CLIENT_CODE AS TRAN_TYPE
FROM STG_DM_CLIENT STG
JOIN DM_CLIENT SRC
ON SRC.CLIENT_CODE = STG.CLIENT_CODE
WHERE (SRC.CLIENT_NAME <> STG.CLIENT_NAME)) THEN 'C'
END
FROM DM_CLIENT, STG_DM_CLIENT
Fails to provide the correct resulset, states incorect syntax next to when
Msg 156, Level 15, State 1, Line 8
Incorrect syntax near the keyword 'WHEN'.
Any ideas as to what I'm doing wrong
A: You only want to have an ELSE statement at the END. Proper format is something like:
CASE WHEN <condition 1> THEN <output 1>
WHEN <condition 2> THEN <output 2>
-- Optional, if left out assumes NULL for unhandled conditions
[ELSE <output 3> ]
END
When you put the ELSE after the first conditional the engine expects a final output, not another condition.
A: Let me format your example (without modificiation), so that the structure becomes visible:
SELECT CASE WHEN exists (SELECT CLIENT_CODE FROM STG_DM_CLIENT
WHERE CLIENT_CODE NOT IN (SELECT CLIENT_CODE FROM DM_CLIENT))
THEN 'A'
else WHEN exists (SELECT STG.CLIENT_CODE AS TRAN_TYPE
FROM STG_DM_CLIENT STG
JOIN DM_CLIENT SRC
ON SRC.CLIENT_CODE = STG.CLIENT_CODE
WHERE (SRC.CLIENT_NAME <> STG.CLIENT_NAME))
THEN 'C'
END
FROM DM_CLIENT, STG_DM_CLIENT
So your structure is:
CASE WHEN ... THEN ...
ELSE WHEN ... THEN ...
END
That's not correct. You can change it to either two nested case statements (complete with CASE and END):
CASE WHEN ... THEN ...
ELSE CASE WHEN ... THEN ...
END
END
or (better):
CASE WHEN ... THEN ...
WHEN ... THEN ...
[ELSE ...]
END
So, remove the else from your original statement and you should be fine.
A: It's not clear what your after, this is the closest valid statement;
SELECT
CASE WHEN EXISTS (...)
THEN 'A'
ELSE
CASE WHEN EXISTS (...)
THEN 'C'
ELSE 'Neither exists()'
END
END
When the 1st exists is matched you will get A
When the 1st does not exist you will get C if the 2nd does match
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596928",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can I start the next matching activity if my app is the default one I have an activity that works as a hook for various intents. Specifically, the VOICE_COMMAND and CALL_PRIVILEGED. (It is a requirement to use these.)
<activity android:name=".MyActivity"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.VOICE_COMMAND" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.CALL_PRIVILEGED" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="tel" />
</intent-filter>
</activity>
I ask the user to set my app as the default action for these intents so they don't have to select it every time. This is also a requirement.
The problem is that in certain cases I want my activity to work transparently and pass the intent to the dialer or other app. This should be selectable by the user. I achieved this by using getPackageManager().setComponentEnabledSetting(myCompName, isEnabled, PackageManager.DONT_KILL_APP) on my activity in certain places of the code.
Is there a more elegant way to do this? I tried startNextMatchingActivity(getIntent()) but that does not start anything (returns false). Does this mean that if there is a default action, then everything else is ignored from the intent resolution?
A: Currently (on Android 2.3) there seems to be no other way of forwarding the intent than doing it manually. Additionally, to send CALL_PRIVILEGED intent the app must have special permissions that only system apps have. (The app will receive not allowed exceptions otherwise.)
All in all, the intent must be converted to some other intent that my app can send and start the next activity manually by retrieving the list of applicable activities from the PackageManager.queryIntentActivities() API.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596929",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: iPhone simulator - simulate 3G connection I am testing the Reachability api, but my physical device only has WiFi access, as I don't have a phone contract. My code needs to distinguish between being connected to 3G/2G or WiFi. Is it possible to simulate a 3G connection on the iPhone simulator?
Clarifications: I am using Snow Leopard. Limiting the bandwidth is not what I need. I need for the actual interface to be identified as the 3G or 2G radio, as opposed to WiFi.
A: If you are using Lion try the Network Link Conditioner
Nowdays there is a part in Preferences on the device (when registered as a developer device) where a "Network Link Conditioner" is available.
A: You might also like Speed Limit.
Edit: I'm not sure if this will work as an identifier for 3g though. I'll update my answer after I do some tests (I'm working on exactly the same thing right now!)
A: I dont think that it is a build-in-functionality in iphone-simulator. But I test it sometimes on my device with wifi (and 3g) disabled.
If you dont have an iPhone but sth. similar (Android for instance) then just enable tethering on your device and use the tethered internet-connection. Then your iPhone-Simulator only gets slow speed ;)
edit: another idea is to limit the bandwidth of your mac. I found this tool online (have not tested it) which should be able to limit network-traffic (to your local router/modem)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596930",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
}
|
Q: Compare multi dimentional arrays in javascript I would like to compare 2 "multidimensional" arrays (arrays nested in arrays).
var old_dataArray=new Array(("id-2", "message", "user"), ("id-1", "message", "user"), ("id-0", "message", "user"));
var new_dataArray=new Array(("id-3", "message", "user"), ("id-2", "message", "user"), ("id-1", "message", "user"));
in this case, I would like to get the array("id-3", "message", "user") which is contained only in "old_dataArray" and not in "new_dataArray".
I've tried with the array_diff function presented here. http://phpjs.org/functions/array_diff:309
But it doesn't really work !.
A: From what I understand, you want to get all arrays in new_dataArray that are not in old_dataArray and I'm assuming that if the first element in each (the 'id-n' element) is the same, then so is the rest of the array. You can do so like this:
// create an array to store our results:
var results = new Array();
// loop through new_dataArray:
outerloop:
for (var i = 0; i < new_dataArray.length; ++i) {
// loop through old_dataArray to compare the i'th element
// in new_dataArray with each in old_dataArray:
for (var j = 0; j < old_dataArray.length; ++j) {
// check if the ids are the same
if (new_dataArray[i][0] == old_dataArray[j][0])
// yes it's there, so move on to the next element of new_dataArray
continue outerloop;
}
// if we get here, continue outerloop; was never called so
// this element is not in old_dataArray
results.push(new_dataArray[i]);
}
// now results contains all arrays that are in new_dataArray
// but not in old_dataArray
EDIT: If, however, you want ALL the elements in each array to be equal, not just the first (id-n) element, use this:
// create an array to store our results:
var results = new Array();
// loop through new_dataArray:
outerloop:
for (var i = 0; i < new_dataArray.length; ++i) {
// loop through old_dataArray to compare the i'th element
// in new_dataArray with each in old_dataArray:
innerloop:
for (var j = 0; j < old_dataArray.length; ++j) {
// check if the arrays are the same size:
if (new_dataArray[i].length != old_dataArray[j].length)
// no, so they must be different
continue innerloop;
// check if the arrays have the same values
for (var k = 0; k < old_dataArray[j].length; ++k) {
if (new_dataArray[i][k] != old_dataArray[j][k])
// the k'th element is different
continue innerloop;
}
// if we get here, then we have found a match, so move on
continue outerloop;
}
// if we get here, continue outerloop; was never called so
// this element is not in old_dataArray
results.push(new_dataArray[i]);
}
// now results contains all arrays that are in new_dataArray
// but not in old_dataArray
A: var old_dataArray = [["id-2", "message", "user"], ["id-1", "message", "user"], ["id-0", "message", "user"]];
var new_dataArray = [["id-3", "message", "user"], ["id-2", "message", "user"], ["id-1", "message", "user"]];
var result = [];
for (var i = 0; i < new_dataArray.length ; i++) {
var isInOldArray = false;
console.log(new_dataArray[i][0]);
for (var j = 0; j < old_dataArray.length; j++) {
if (old_dataArray[j][0] === new_dataArray[i][0]) {
isInOldArray = true;
break;
};
};
if (!isInOldArray) {
result.push(new_dataArray[i]);
};
};
alert(result);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Problems with Qualcomm Scorpion dual-core ARM NEON code? I am developing a native library for Android where I use ARM assembly optimizations and multithreading in order to get maximum performance on the dual-core ARM chipset MSM8660. While doing some measurements I noticed the following:
*
*The single-threaded library with NEON optimizations is faster than the single-threaded library with ARMv6 optimizations (as expected).
*The multi-threaded library with ARMv6 optimizations is faster than the single-threaded library with ARMv6 optimizations (as expected).
*The multi-threaded library with NEON optimizations is slower than the single-threaded library with NEON optimizations (definitely not expected!).
I have tried searching all over the net for an explanation for why this is but have so far not found any. It almost seems like all the cores share the same NEON pipeline or something like that, but all schematics seem to indicate that each core should have its own NEON unit. Does anyone know why this is happening?
A: First of all, what library are you using ?
You're correct, each core has it's own NEON unit, It is however their own proprietary 'VeNum' unit and not much information is provided about it, It was designed for the Cortex-A8 based Scorpion in 8x50 and was quite better than ARM's own implementation of NEON SIMD, However a good relief is that they (qcom) design their hardware in a way that it's compatible with the base refrence design so most code for a cortex-A8 will work just fine with Scorpion albeit with some performance hit due to possible different instruction timing.
If you're using "softfp" to compile your program, you will have an overhead of approx 20 cycles for every function you call which uses floating point arguments and or uses the NEON unit as transferring register data from the ARM core to Neon unit and vice versa is quite slow and can sometimes stall the core for many cycles waiting for the pipeline to flush.
Also for a threaded program using floating point unit, the kernel has to save the FP registers during a context switch so that incurs additional penalty for threads since we already know moving registers from neon to arm is slow and is known to stall the pipeline.
Additionally many other factors can lead to this such as a bad optimization from compiler, cache miss, not using the double issue feature of scorpion, bad instruction scheduling and switching of your thread from one core to another repeatedly.
A: It's probably because of cache misses. It's hard to tell without more information.
A: My guess would be that it is because of the extra cycle penalty involved in flushing the NEON pipeline. The NEON pipeline is behind the rest of the core, and so you see an extra cycle penalty for missed branches and so on.
If the threads have to synchronize quite often, or if you have a lot of locks, I think you are going to see big penalties with NEON.
The only way you are going to leverage NEON for an overall gain in performance with multi-threaded code is if the code is embarrassingly parallel and there is very little and infrequent communication between the threads.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596936",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Getting URL in Javascript Ok, I'm new to JavaScript and need some help here. Working on forward/backward buttons on a page. Essentially, the url looks like this http://webaddress.com/details?id=27
So, my two functions are meant to extract the url and forward to the same page decrementing or incrementing the details id as necessary when one of the buttons is clicked. For example when someone clicks on the next button, id=28 is shown; and if previous is clicked, id=26 is shown.
I think it's something like substring, I've seen it done somewhere before, but not sure how's done.
I need idea on how to approach it.
Any help will be appreciated.
Update: I was using @gion_13's code below, but looks like I'm missin something. It doesn't seem to work. Any other help will be appreciated.
A: You can use location.href to get or set the URL.
http://developer.mozilla.org/en/window.location
Use exec to extract the identifier.
extracted_id = /id=([0-9]+)$/.exec(location.href)[1]
http://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp/exec
A: *
*Read the url as var url = document.location.href
*Use regEx or indexOf "=" or document.location.search to find current page no
*Parse as int and +/- page number
*rebuild the the url
*document.location.replace(newurl)
A: The window.location object has the URL info you need. You can parse it using a regex. Here's some references:
*
*https://developer.mozilla.org/en/window.location
*https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp
A: To access the URL of the page, use document.URL, for example:
document.write(document.URL);
You can then modify the URL and open the new URL.
For lots of hints and tips, See JavaScript HTML DOM Examples.
A: function parseUrl(){
if(location.href.indexOf('?') == -1)
return null;
var aux = location.href.split('?');
var result = {
'href' : aux[0],
'params' : {}
};
var p = aux[1].split('&');
for(var i=0,l=p.length;i++)
{
var kv = p[i].split('=');
params[kv[0]] = kv[1];
}
return result;
}
function reconstructUrl(obj){
if(!obj)
return location;
var url = obj.href + '?';
for(var i in obj.params)
url += i + '=' + obj.params[i] + '&';
return encodeURI(url);
}
function getNextUrl(){
var urlObj = parseUrl();
urlObj.id++;
return reconstructUrl(urlObj);
}
function getPrevUrl(){
var urlObj = parseUrl();
urlObj.id--;
return reconstructUrl(urlObj);
}
A: You can do that without Javascript if you want. I think it's more efficient with PHP, because it will work even if some user has Javascript disabled.
You can try get the id like this:
<?php $my_id = $_GET['id']; ?>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596940",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jQuery filtering & sorting of tables - how to look "inside" html tags I am making use of a tablesorter library. My issue is that every item in a cell inside of my table is a link, and the library starts sorting things incorrectly because it's looking at the HTML inside the cell, instead of the text. In other words, in the following cell contents;
<a href="ledger.php?var=345345">$100.64</a> it sorts on:
<a href="ledger.php?var=345345"> instead of $100.64
I know there are ways to look at the text inside of cells. I started with the simple method that they have listed on the website, text extraction method. However, I can't for the life of me get this to function properly.
Using my JS code, can anyone tell me how to apply this text extraction properly? This is what I have now (below).
The current results of this code, when the "text extraction" line is NOT commented out, is that the plugin fails to load, and all jQuery on the page fails with it. The console error in web developer plugin is:
Error: node.childNodes[0].childNodes[0] is undefined Source File:
$(document).ready( function () {
// TableSorter
$("#dt-results")
.tablesorter({
widgets: ['zebra'],
sortList: [[0,1]],
// define a custom text extraction function
textExtraction: function(node) {
// extract data from markup and return it
return node.childNodes[0].childNodes[0].innerHTML;
}
})
.tablesorterPager({container: $("#pager")})
.tablesorterFilter({filterContainer: $("#filter-box"),
filterClearContainer: $("#filter-clear-button"),
filterCaseSensitive: false,
filterWaitTime: 100});
});
Thanks
A: Since you are using jQuery, why don't you use text()? See http://api.jquery.com/text/
textExtraction: function(node) {
return $(node).text();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596949",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Android Heap memory increase I am developing an application on Android 2.2 which takes extensive memory and my most operation cannot be complete because of low memory. Could anybody give me solution that how can I increase my application heap size. I have tried android:largeHeap="true" but it is not supported in Android API-8.
I am thankful you all.
A: Heap size depends on the hardware your running your app an. For example 16mb on a G1 and 32mb on a nexus one. Don't think there is much you can do about it. If you target versions below 3.0 that is.
A:
Could anybody give me solution that how can I increase my application heap size.
You can't. Instead, you need to do a better job with the memory you have.
I have tried android:largeHeap="true" but it is not supported in Android API-8.
As Google has indicated, all using this will do is tend to irritate users of your app. Your app will consume more memory and therefore will kick other apps out of memory more quickly. Some users will not like this behavior. And, it is very possible that this will only ever be a tablet option -- I would not assume that Ice Cream Sandwich phones will necessarily support android:largeHeap.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596950",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Batch File using sed in windows - unexpected append instead of replace I've been tasked with migrating a group of batch scripts to Windows 7 (from XP) and have had a few problems using sed for substitution. What i need the line to do is find LogPath and anything inside the double quotes should be replaced with ABC (just for testing - will actually be a UNC path).
However instead I'm getting two strange problems:
*
*it's deleting the first double quote
*more importantly it isn't
actually replacing anything inside the quotes, but instead is just
appending to this string
Here is the relevant line of the script:
sed \\fs-bri-01\9732\9732.hfls -i -e s,LogPath="*.",LogPath="ABC",g
This script works on Windows XP but not Windows 7.
A: Maybe the problem comes from the UNC path:
pushd \\fs-bri-01\9732
sed 9732.fls -i -e s,LogPath="*.",LogPath="ABC",g
popd
But maybe the problem comes from the quote characters and the way sed gets its argv array. Then you can try:
sed -i -e "s/LogPath=\".*\"/LogPath=\"ABC\"/g" \\fs-bri-01\9732\9732.hfls
A: Well figured a work around posting it below for anyone stuck in the same situation.
sed \\fs-bri-01\9732\9732.hfls -i -e "s/LogPath=\"[\:A-Z0-9a-z_\\\/\.\ ]*\"/LogPath=\"ABC\"/g"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596954",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: A use case for retry function? I read this snippet, and I am trying to understand how I can use retry, and I am unable to think of a use. How are others using it?
#!/usr/bin/ruby
for i in 1..5
retry if i > 2
puts "Value of local variable is #{i}"
end
A: There are several use cases. Here's one from the Programming Ruby book
@esmtp = true
begin
# First try an extended login. If it fails because the
# server doesn't support it, fall back to a normal login
if @esmtp then
@command.ehlo(helodom)
else
@command.helo(helodom)
end
rescue ProtocolError
if @esmtp then
@esmtp = false
retry
else
raise
end
end
An other common case is the email delivery. You might want to retry the SMTP delivery for N times adding a sleep between each retry to avoid temporary issues caused by network connectivity.
A: I am using it for a module that makes an api call to a 3rd party web api, and so if it fails, I retry 2 more times.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596966",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Animation while switching Activity in Android? I want an animation while switching from one activity to another in Android. The animation I'm aiming for is a bottom to top like animation.
How can I do that?
A: Yes it is possible. check out this question. You have to define animations in anim folder than you can overide current animation using
overridePendingTransition( R.anim.slide_in_up, R.anim.slide_out_up );
A: You can set your animation when you go to another activity using this
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
Also you can get same animation if you come back from last activity to previous activity by overriding method
@Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
A: A better way to do this is to create a style like below
<style name="SlideAnimation.Activity" parent="@android:style/Animation.Activity">
<item name="android:activityOpenEnterAnimation">@anim/slide_from_top</item>
<item name="android:activityOpenExitAnimation">@anim/slide_to_bottom</item>
<item name="android:activityCloseEnterAnimation">@anim/slide_from_bottom</item>
<item name="android:activityCloseExitAnimation">@anim/slide_to_top</item>
</style>
If you want to implement this for whole application then use it in app theme like be
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorWhite</item>
<item name="colorPrimaryDark">@color/colorWhite</item>
<item name="colorAccent">@color/colorAppBlue</item>
<item name="android:statusBarColor">@color/colorPrimaryDark</item>
<item name="android:windowAnimationStyle">@style/SlideAnimation.Activity</item>
</style>
And declare the AppTheme in manifest in application tag like below-
<application
android:name=".MyApp"
android:allowBackup="false"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:theme="@style/AppTheme"
>
And if you want to use for specific activity then apply the theme to that activity in manifest.
A: You can override the public boolean onOptionsItemSelected(MenuItem item)function, and use finish() followed by overridePendingTransition().
For example, add the following code in your activity:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: // navigation up.
finish();
overridePendingTransition(R.anim.ENTER_ANIMATION, R.anim.EXIT_ANIMATION);
return true;
case ....: // implementation of other menu items.
}
return super.onOptionsItemSelected(item);
}
The other way is overwriting the public boolean onNavigateUp() function. But onNavigateUp() is only for API level 16 and above.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596976",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
}
|
Q: Redirect to created invoice after it's saved I need to tweak magento admin so after a new invoice is created at a link like this:
admin/sales_order_invoice/new/order_id/550/
to redirect to
/admin/sales_order_invoice/view/invoice_id/384/order_id/550/
Right now, after an order is created magento redirects to admin/sales_order/view/order_id/542/
L.E.
Found out that redirect url is set in saveAction() from app/code/core/Mage/Adminhtml/controllers/Sales/Order/InvoiceController.php
Does anyone know a way to retrieve created invoiced inside that function?
A: I know this is an old question and the Mage_Adminhtml_Sales_Order_InvoiceController class may have changed since the question was asked, but I thought it may help someone.
The invoice object is already available in the saveAction function and is initialized in the _initInvoice function. To access the invoice id you just need to use $invoice->getId().
To update the URL you just need to change this:
$this->_redirect('*/sales_order/view', array('order_id' => $orderId));
to this:
$this->_redirect('*/sales_order_invoice/view', array('invoice_id' => $invoice->getId(), 'order_id' => $orderId));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596980",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Change dynamic part of an snippet that is included via JSF-2.0 templateing I have a problem with the JSF-2.0 templating mechanism. I implement some snippet that are
included to template file. But one of my snippet contains dynamic content.
I do not get an error. But nothing is replaced in my snipplet!
The result do only contain "No link list could be found" string. Do anybody know why?
Thanks
The snippet code
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets">
<div>
<ui:insert name="linkList">No link list could be found</ui:insert>
</div>
© MyCompany
</ui:composition>
The template code
...
<div class="footer">
<ui:insert name="footer">Footer</ui:insert>
</div>
...
The side where specify the template content
...
<ui:define name="footer">
<ui:include src="/snippets/footer.xhtml" />
</ui:define>
...
<ui:define name="linkList">
link structure for the footer
</ui:define>
A: The following line you have in snippet is -
<ui:insert name="linkList">No link list could be found</ui:insert>
is for templating and it should be in the template.
Include the snippet in the same way you have included the footer. Using
<ui:include src="snippet.xhtml" />
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596982",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: animate() & fadeTo() both synchronous I have a problem with the following two methods. $(this).fadeTo(200, .8).animate({bottom: 130}, 200); Both are synchronous, therefore first it fades to, then it animates.
Is it possible to use fadeTo with animate?
(CSS option 'opacity' is not cross-browser compatible and therefore not an option)
A: $(this).animate({
bottom: 130,
opacity: 0.8
}, 200);
jQuery will set things up to make opacity working on IE. See Animate opacity doesn't work properly on IE
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596983",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: returning boost list from exposed class I exposed a c++ class to python, one of its methods is something like:
boost::python::list getList() {
boost::python::list l
...
return l;
}
it works perfectly, and I dont get any compiler warning.. since I heard that working with containers is a mess with c++/python, I was just wondering if what I did is OK..
Thank you
A: Yes, this is the correct way of returning a list in Boost.Python. The "mess" is handled by boost::python::list.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596993",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Best way to programmatically create dial images? I'm working on a website that uses a lot of different sized and styled dials. These are used as progress indicators, so the more filled a dial is, the closer to 100% complete that item is.
I'm looking for a cross-browser, abstract solution so I can use the same solution across the different-styled dials. I'd use Google's Charts API, but unfortunately its dials don't offer the degree of customization needed. For an example, here are a handful of the images:
The functionality will be the same, but as you can see they're different dimensions.
I did try a solution with the Raphaël JavaScript library, but couldn't find a way to mask the complete image to show segments from 0 to 100%. The default image is grey, the complete image is the green ones you see above. I need to show values between 0 and 100.
Any help or guidance would be greatly appreciated.
A: Raphaël doesn't do non-rectangular clipping AFAIK, even though SVG supports that.
This clip-path animation might provide a bit of help for what you want to do.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596995",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Best way to design shopping cart domain model on C#? Google can`t help me. I find only this link: http://flylib.com/books/en/2.522.1.56/1/
So, once there is the question - why do we need divide Product and Item?
A: Product is too complex to use it on your Cart. We can imagine that Product holds data about: Manufacturer, Quantities on Stock, Categories, etc. So the better way is to introduce an Item that will hold only reference to real Product (for example ProductId) and Quantity (and others informations you need).
A: Google cannot write code for you, it doesn't know you. I suggest you ask your users exactly what they want, and just do it. In my experience (almost 20 years of coding), I've found that reinventing the wheel almost always takes less time in the long term than trying to use an existing wheel to fit into different specifications. All projects are unique.
Of course, you can take inspiration from what you find, but don't expect it to match your specifications.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596997",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to get muli-language (human language) intellisense in .Net I'm creating a library (C#, .Net), but I need to distribute it to customers in multiple countries. When you add XML comments to your classes, intellisense picks up the comments out of the assembly and gives you a nice description of your methods, properties, arguments, etc...
Is there any way I can make localized versions of my assembly so the XML comments are in the language of the locale, yet only have to maintain one copy of my source code?
A: I know this is an pretty old one, but it was the first hit to my google-query, so I would like to post my answer here for other google-users on this topic.
Yet, I don't know any tool which translates your xml-comments automatically, but if you do the translation for yourself, you can store the translated xml-file with the same name as the original one in a sub-folder, named by the targeted locale.
So I have my localized resources in a sub-folder 'de', where all German translated xml-comment files and localized satellite assemblies are stored.
When I reference my assembly, IntelliSense shows the localized texts, as the running application uses the localized strings.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7597006",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Mongodb match empty object in nested document I'm just wondering if this is possible to do in a single request?
Given
{
_id: 1,
foo: {
fred: {}, // <- I want to remove empty keys like this
barney: { bar: 1 } // <- But keep these keys
}
}
Expected
{
_id: 1,
foo: {
barney: { bar: 1 }
}
}
I know how to do it in several requests, but I'm trying to understand MongoDB better.
Note. fred becomes empty in update command like { $unset: { "fred.baz": 1 } } when baz is the last key in fred.
Maybe it is possible to remove it with its contents? But the command sender does not know, is there any other keys, except baz at the moment.
A: You can search for empty embedded docs ({ }) and $unset them .. here's an example in the JS shell:
db.mycoll.update(
{'foo.fred':{ }},
{ $unset: {'foo.fred':1} },
false, // upsert: no
true // multi: find all matches
)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7597013",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: Changing mercury color in thermometer in JFreeChart I have created a thermometer chart with JFreeChart, but I want to change the mercury color in thermometer. How can I do this? Here is my code so far; please explain where to change this code:
final DefaultValueDataset dataset = new DefaultValueDataset(new Double(10));
// create the chart...
final ThermometerPlot plot = new ThermometerPlot(dataset);
final JFreeChart chart = new JFreeChart("Thermometer Demo 2", // chart title
JFreeChart.DEFAULT_TITLE_FONT,
plot, // plot
false); // include legend
chart.setBackgroundPaint(new Color(241,250,224));
plot.setMercuryPaint();
final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setUpperBound(50);
A: You may be looking for setSubrangePaint(), demonstrated below.
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.ThermometerPlot;
import org.jfree.data.general.DefaultValueDataset;
/** @see http://stackoverflow.com/questions/7597015 */
public class ThermometerDemo extends JPanel {
private static final int W = 200;
private static final int H = 2 * W;
public ThermometerDemo(double value) {
this.setLayout(new GridLayout());
DefaultValueDataset dataset = new DefaultValueDataset(value);
ThermometerPlot plot = new ThermometerPlot(dataset);
plot.setSubrangePaint(0, Color.green.darker());
plot.setSubrangePaint(1, Color.orange);
plot.setSubrangePaint(2, Color.red.darker());
JFreeChart chart = new JFreeChart("Demo",
JFreeChart.DEFAULT_TITLE_FONT, plot, true);
this.add(new ChartPanel(chart, W, H, W, H, W, H,
false, true, true, true, true, true));
}
public static void main(final String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame f = new JFrame("Demo");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new GridLayout(1, 0));
f.add(new ThermometerDemo(40));
f.add(new ThermometerDemo(60));
f.add(new ThermometerDemo(80));
f.pack();
f.setVisible(true);
}
});
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7597015",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Passing Image between servers for remote saving My Spring application passes image file to Jersey application to get rid of all image manipulation tasks.
On receiving image, the Jersey application should save the image after several manipulations (crop, resize etc) and return image url.
For this, the Spring application has the below form in a JSP file:
<form method="POST" action="/asdf" enctype="multipart/form-data">
<input type="file" name="fstream"></input>
<input type="submit" value="Upload"/>
</form>
In my spring controller, I get DataInputString using:
DataInputStream in = new DataInputStream(request.getInputStream());
What would be an easy approach to carry out the desired action mentioned above?
How about converting it to BufferedImage in Spring app, POST it to the Jersey app, carry out required manipulations and save the image?
If that's fine, how do I convert DataInputStream to BufferedImage?
Thanks in advance.
A: Since there was no answer ...
*
*I obtained byte array from submitted form data
*Sent an object with byte[] being one of the attribute to REST server
*On server side, I converted byte[] to BufferedImage which I scaled (using ImgScalr API) as required, and saved it.
@Path("/image")
public class ImageController {
@PUT
@Path("upload/{fileName}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response upload(@PathParam("fileName") String fileName, FileBytes fileBytes){
byte[] bytearray = fileBytes.getFileBytes();
int len = bytearray.length;
if(len>0){
try {
int width=0, height=0, edge=0, px1=0, px2=0;
InputStream in = new ByteArrayInputStream(bytearray);
BufferedImage image = ImageIO.read(in);
File file = new File(Constants.PATH_TO_IMAGES+Constants.PATH_ORIGINAL+fileName+".jpg");
ImageIO.write(image, "png", file); //saving original image
width = image.getWidth();
height = image.getHeight();
//scaling as required
if(height>width){
px2 = (height-width)/2+1;
edge = width;
}else if(width>height){
px1 = (width-height)/2+1;
edge = height;
}else{
edge = width;
}
//using ImgScalr API to get scaled image
image = image.getSubimage(px1, px2, edge, edge);
image = Scalr.resize(image, 120);
file = new File(Constants.PATH_TO_IMAGES+Constants.PATH_THUMBNAIL+fileName+".jpg");
ImageIO.write(image, "png", file); //saving scaled image
} catch (Exception e) {
e.printStackTrace();
}
}
return Response.status(Status.OK).entity("Filename:"+fileName).build();
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7597024",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: difference between stdint.h and inttypes.h What is the difference between stdint.h and inttypes.h?
If none of them is used, uint64_t is not recognized but with either of them it is a defined type.
A: See the wikipedia article for inttypes.h.
Use stdint.h for a minimal set of definitions; use inttypes.h if you also need portable support for these in printf, scanf, et al.
A: stdint.h
Including this file is the "minimum requirement" if you want to work with the specified-width integer types of C99 (i.e. int32_t, uint16_t etc.).
If you include this file, you will get the definitions of these types, so that you will be able to use these types in declarations of variables and functions and do operations with these datatypes.
inttypes.h
If you include this file, you will get everything that stdint.h provides (because inttypes.h includes stdint.h), but you will also get facilities for doing printf and scanf (and fprintf, fscanf, and so on.) with these types in a portable way. For example, you will get the PRIu64 macro so that you can printf a uint64_t like this:
#include <stdio.h>
#include <inttypes.h>
int main (int argc, char *argv[]) {
// Only requires stdint.h to compile:
uint64_t myvar = UINT64_C(0) - UINT64_C(1);
// Requires inttypes.h to compile:
printf("myvar=%" PRIu64 "\n", myvar);
}
One reason you would want to use printf with inttypes.h is, for example, that uint64_t is long unsigned in Linux but long long unsigned in Windows. Thus, if you were to only include stdint.h (not inttypes.h), then, to write the above code and keep it cross-compatible between Linux and Windows, you would have to do the following (notice the ugly #ifdef):
#include <stdio.h>
#include <stdint.h>
int main (int argc, char *argv[]) {
// Only requires stdint.h to compile:
uint64_t myvar = UINT64_C(0) - UINT64_C(1);
// Not recommended.
// Requires different cases for different operating systems,
// because 'PRIu64' macro is unavailable (only available
// if inttypes.h is #include:d).
#ifdef __linux__
printf("myvar=%lu\n", myvar);
#elif _WIN32
printf("myvar=%llu\n", myvar);
#endif
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7597025",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "96"
}
|
Q: Adding UISearchBar programatically - Bar is Off Screen at Launch - iPad I have added a UISearchBar to a table in my iPad app using the below code. The table is on the left hand side of my split view controller.
The problem is that when the app starts the search bar is strangely off screen to the left - you can just see the last few pixels of it. If you click on it, or scroll down and back up, it reverts itself and looks like it should.
Can anyone suggest how to fix this ?
Thanks
searchBar = [[UISearchBar alloc] init];
self.tableView.tableHeaderView = searchBar;
searchController = [[UISearchDisplayController alloc]
initWithSearchBar:searchBar
contentsController:self];
searchBar.delegate = self;
searchController.delegate = self;
searchController.searchResultsDelegate=self;
searchController.searchResultsDataSource=self;
A: You can try to create the UISearchBar with a frame like:
CGRect searchViewFrame = CGRectMake(33, 33, 264, 31);
or whatever dimensions or origin.
Like other resource, you can create the UISearchBar within a UIView, and add this UIView to the UITableView:
UIView *containerSearch = [[UIView alloc] initWithFrame: searchViewFrame];
searchBar = [[UISearchBar alloc] init];
[containerSearch addSubview: searchBar];
self.tableView.tableHeaderView = containerSearch;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7597026",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Returning a string containing valid Json with Nancy I receive a string that contains valid JSON from another service.
I would like to just forward this string with Nancy but also set the content-type to "application/json" which will allow me to remove the need for using $.parseJSON(data) on the client side.
If I use Response.AsJson it seems to mangle the JSON in the string and adds escape characters.
I could create a Stream with the string and set the response type something like:
Response test = new Response();
test.ContentType = "application/json";
test.Contents = new MemoryStream(Encoding.UTF8.GetBytes(myJsonString));
but would like to know if there is a simpler way?
A: Looks like Nancy has got a nice Response.AsJson extension method:
Get["/providers"] = _ =>
{
var providers = this.interactiveDiagnostics
.AvailableDiagnostics
.Select(p => new { p.Name, p.Description, Type = p.GetType().Name, p.GetType().Namespace, Assembly = p.GetType().Assembly.GetName().Name })
.ToArray();
return Response.AsJson(providers);
};
A: Pretty much the way you do it. You could do
var response = (Response)myJsonString;
response.ContentType = "application/json";
You could just create an extension method on IResponseFormatter and provide your own AsXXXX helper. With the 0.8 release there will be some extensions on the response it self so you can do stuff like WithHeader(..), WithStatusCode() etc-
A: I like that you think there should be a better way because you're having to use 3 lines of code, I think that says something about Nancy :-)
I can't think of a "better" way to do it, you can either do it the GetBytes way:
Get["/"] = _ =>
{
var jsonBytes = Encoding.UTF8.GetBytes(myJsonString);
return new Response
{
ContentType = "application/json",
Contents = s => s.Write(jsonBytes, 0, jsonBytes.Length)
};
};
Or the "cast a string" way:
Get["/"] = _ =>
{
var response = (Response)myJsonString;
response.ContentType = "application/json";
return response;
};
Both do the same thing - the latter is less code, the former more descriptive (imo).
A: This also works:
Response.AsText(myJsonString, "application/json");
A: If all routes of your module return a JSON string, then you can set the content type in the After hook for all routes at once:
Get["/"] = _ =>
{
// ...
return myJsonString;
};
After += ctx =>
{
ctx.Response.ContentType = "application/json";
};
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7597035",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "50"
}
|
Q: Styling ASP.NET file uploader for different dimensions Is there any way to change the width of ASP.NET file uploader.
I tried adding the CssClass but unable to change the width. I just wondering is there any other way to achieve this.
Thanks
A: you can't change it directly some tricky solutions available like
http://aquantum-demo.appspot.com/file-upload
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7597038",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: MFMailComposeViewController in the delegate The question deals with an application which uses many views in a UINavigation controller Style.
I have a simple function in my delegate which can be used by all views to plot-out error message
// In Appdelegate.m
-(void)popErrorWindow:(NSString *)theError
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:theError
delegate:self cancelButtonTitle:@"OK" otherButtonTitles:@"Report",nil];
[alert show];
[alert release];
}
- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 1)
{
NSLog(@"report");
[self mailIt:@"error name"];
}
}
Now, wanting to have a mechanism that will email the error along with some other data I have created this:
-(void)mailIt:(NSString *)theError {
NSLog(@"Mail it");
pickerMail = [[MFMailComposeViewController alloc] init];
pickerMail.mailComposeDelegate = self;
[pickerMail setSubject:@"error via email"];
NSMutableString *body = [NSMutableString string];
[body appendString:@"Error XXX "];
[pickerMail setMessageBody:body isHTML:YES];
// Problem here:
[self.window presentModalViewController:pickerMail animated:YES];
}
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
// Problem here:
[self.window dismissModalViewControllerAnimated:YES];
//NSLog(@"mail was sent");
}
The problem is in self.window , which is not the right way to access this from the delegate,
I still want to have the mail element in the delegate as all views can call the error alert, and I would like to have only one place for this mechanism.
How should I do it from inside the delegate, what should replace the self.window?
A: Perhaps reimplementing popErrorWindow: and mailIt: in a category on UIViewController. This way you have access to the top-level view controller to call presentModalViewController and dismissModalViewControllerAnimated on.
Alternatively you can do this in a subclass of UIViewController and then make your other custom view controller's subclass of that. The downside to this method is when you have subclasses of classes other than UIViewController
A: - (void)mailComposeController:(MFMailComposeViewController *)controller
didFinishWithResult:(MFMailComposeResult)result
error:(NSError *)error
{
[controller dismissModalViewControllerAnimated:YES];
}
EDIT :
The - (void)presentModalViewController:(UIViewController *)vc and - (void)dismissModalViewControllerAnimated:(BOOL)animated methods are an UIViewController instance method, so you cannot use it with an UIWindow.
In order to present your mail controller with a nice animation, you can do that :
UIViewController *aController = self.navigationController.presentedViewController;
[aController presentModalViewController:pickerMail animated:YES];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7597039",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to extract all the IUPAC names mentioned in the data available from Pubchem(NCBI) into a text file? I want to build lists of prefixes and suffixes of some length from all the IUPAC names mentioned in Pubchem Database,so that I can use them further in my project as a feature.So I want all the IUPAC chemical names in a text file or in some format where I can extract these lists.
Thanks.
A: Sounds you need something like this Nist species list
You can search for most also in the Webbook but I failed to find a download link for the complete set.
In our lab we got a Cd(?) with the mass spectral database which contained the (complete? - well it got like 250.000 substances) database as text file. Maybe you can get that through some of the vendors.
A: The pubchem site offers you to download a dump of their data by ftp. Why not use that?
A: PubChem data can be downloaded via ftp from the PubChem site. A complete description of the available data can be obtained here: https://pubchemdocs.ncbi.nlm.nih.gov/downloads
Of particular interest for the question of IUPAC names, the data are downloadable from the "Compound Extras" section of the ftp site: ftp://ftp.ncbi.nlm.nih.gov/pubchem/Compound/Extras/
The README-Extras file in this location describes the data in detail. For the IUPAC names, the following information is provided:
CID-IUPAC.gz:
This is a listing of all CIDs with their computed IUPAC names.
It is a gzipped text file with CID, tab, IUPAC on each line. Note
that the names may contain UTF8 characters.
A download today (23-Apr-2020) contains 102,586,778 rows. An excerpt of the information is shown below.
> head CID-IUPAC
1 3-acetyloxy-4-(trimethylazaniumyl)butanoate
2 (2-acetyloxy-3-carboxypropyl)-trimethylazanium
3 5,6-dihydroxycyclohexa-1,3-diene-1-carboxylic acid
4 1-aminopropan-2-ol
5 (3-amino-2-oxopropyl) dihydrogen phosphate
6 1-chloro-2,4-dinitrobenzene
7 9-ethylpurin-6-amine
8 2,3-dihydroxy-3-methylpentanoic acid
9 (2,3,4,5,6-pentahydroxycyclohexyl) dihydrogen phosphate
11 1,2-dichloroethane
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7597049",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Select rows with same value and then insert a null record i have written an query but it inserts alternate null columns. I want the null column after different orderids. Suppose i have two orderids 100 and 101. i have only one record for orderid 100 and two records for orderid 101 so it should insert null column after orderid 100 and then after 101 orderid.
DECLARE @tmp TABLE
(
srno int identity (1,1) ,
orderid int,
orderdate datetime,
orderstatus varchar(255),
product_name varchar(255),
shipping_cost decimal(18,2),
Quantity int,
TotalPrice money,
SalesTax1 money,
CVV2_Response varchar(255),
ShipFirstName varchar(255),
ShipLastName varchar(255),
ShipAddress1 varchar(255),
ShipCity varchar(255),
ShipState varchar(255),
ShipPostalCode varchar(255),
EmailAddress varchar(255),
CustomerID int
)
SELECT CASE D.N WHEN 1 THEN ord.orderid end as orderid,CASE D.N WHEN 1 THEN ord.orderdate end as orderdate,
CASE D.N WHEN 1 THEN ord.OrderStatus end as Orderstatus,
CASE D.N WHEN 1 THEN ord.productname end as Productname,
CASE D.N WHEN 1 THEN ord.Quantity end as Quantity,
CASE D.N WHEN 1 THEN ord.TotalPrice end AS PaymentAmount,
CASE D.N WHEN 1 THEN ord.SalesTax1 ELSE 0.0 END AS Tax ,
CASE WHEN row_no = 1 THEN ord.totalshippingcost ELSE 0.0 END AS Totalshippingcost,
CASE D.N WHEN 1 THEN ord.CVV2_Response end as CVV2_Response ,
CASE D.N WHEN 1 THEN ord.ShipFirstName end as ShipFirstName ,
CASE D.N WHEN 1 THEN ord.ShipLastName end as ShipLastName ,
CASE D.N WHEN 1 THEN ord.ShipAddress1 end as ShipAddress1 ,
CASE D.N WHEN 1 THEN ord.ShipCity end as ShipCity ,
CASE D.N WHEN 1 THEN ord.ShipState end as ShipState ,
CASE D.N WHEN 1 THEN ord.ShipPostalCode end as ShipPostalCode,
CASE D.N WHEN 1 THEN ord.EmailAddress end AS CustomerEmail
FROM
(
SELECT ROW_NUMBER() OVER(PARTITION BY ord.orderid ORDER BY ord.orderid, ord.orderdate, ord.OrderStatus, odn.productname, odn.Quantity, odn.TotalPrice,ord.SalesTax1,ord.totalshippingcost,ord.CVV2_Response ,ord.ShipFirstName ,ord.ShipLastName ,
ord.ShipAddress1 ,ord.ShipCity ,ord.ShipState ,ord.ShipPostalCode ,cus.EmailAddress) AS row_no, ord.orderid,
ord.orderdate, ord.OrderStatus, odn.productname, odn.Quantity, odn.TotalPrice,ord.SalesTax1,ord.totalshippingcost,ord.CVV2_Response ,ord.ShipFirstName ,ord.ShipLastName ,
ord.ShipAddress1 ,ord.ShipCity ,ord.ShipState ,ord.ShipPostalCode ,cus.EmailAddress
FROM Orders AS ord
INNER JOIN orderdetails AS odn ON odn.orderid = ord.orderid INNER Join Customers AS cus on ord.CustomerID = cus.CustomerID WHERE ord.OrderStatus = 'Processing'
) ord
CROSS JOIN (SELECT 1 UNION ALL SELECT 2) AS D(N)
ORDER BY ord.orderid, ord.orderdate, ord.productname, D.N
A: Try this as order by:
order by row_number() over(order by ord.orderid, ord.orderdate, ord.productname)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7597050",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How to programmatically add calendar subscriptions on iOS? Via the settings panel of your iPhone, you can add a subscription to a remote .ics calendar format. I have a Dutch iPhone app that does this from within the app (see the screenshot below, "abonneren op de agenda" means "subscribe to the calendar"), but there must be others too.
I want to mimic this behavior for a project of mine, but I can't find the API to do this with. It looks like it's not a part of EventKit, but because there's no app switching going on when you hit 'subscribe' in the example app I suspect it's also not a url scheme.
Who knows?
A: Try something like this:
NSString *url = @"http://server/filename.ics";
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
This shows an uialertview with the question to the user if he/she wants to subscribe.
;)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7597051",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: ORA-22813: operand value exceeds system limits I'm having an issue with an oracle object I created. The goal of the stored procedure is to either retreive all wires contained on an airplane or compare the list of wires with another one (past airplane wire configuration). You will understand that this can be quite big... I did a first shot with a table of objects. I make a select statement and loop through a cursor to insert values in my objects. The problem comes from when I try this:
OPEN P_CURSOR FOR
SELECT * FROM TABLE(CAST(GET_WIRES(P_ACTUAL_HAR_LIST, P_END_IDENT_TYPES) AS TBL_TP_WIRE_LIST));
I get the ORA-22813: operand value exceeds system limits. So, I started looking on the internet and I found that I should have used a PIPELINED function, which I tryied. But, the PIPELINED function is not allowed in a PL/SQL context, so that doesn't fit my problem, since I need to rework the object afterward. So, I tryied a Global Temporary Table and I have now performance issue. I also tryied to contact the DBA if he could increase the PGA size, which he did (it's now 150mb) but I have the same problem. Maybe it's still not big enough, but I don't want him to reincrease it if it's not going to work... Just so you have an idea, I have 1 487 761 of those:
CREATE OR REPLACE
TYPE TP_WIRE_LIST_ENTRY AS OBJECT (
ATA_NUM VARCHAR2(8 BYTE),
EFFECTIVITIES VARCHAR2(4000 BYTE),
WIRE_ID VARCHAR2(50 BYTE),
DRAWING_NO VARCHAR2(25 BYTE),
END_IDENT_1 VARCHAR2(25 BYTE),
END_IDENT_2 VARCHAR2(25 BYTE),
PIN_1 VARCHAR2(25 BYTE),
PIN_2 VARCHAR2(25 BYTE),
TERM_1 VARCHAR2(25 BYTE),
TERM_2 VARCHAR2(25 BYTE),
DES_LENGTH NUMBER(6,2),
TECH_PUBS_REMARKS VARCHAR2(500 BYTE),
WIRE_CODE VARCHAR2(25 BYTE),
W_CODE VARCHAR2(3 BYTE),
AWG VARCHAR2(3 BYTE),
COLOR VARCHAR2(4 BYTE),
GA VARCHAR2(6 BYTE),
END_IDENT_DESC_1 VARCHAR2(50 BYTE),
END_IDENT_DESC_2 VARCHAR2(50 BYTE),
TECH_PUBS_REMARKS_1 VARCHAR2(500 BYTE),
TECH_PUBS_REMARKS_2 VARCHAR2(500 BYTE),
IDENT_TYPE_ID_1 VARCHAR2(10 BYTE),
IDENT_TYPE_ID_2 VARCHAR2(10 BYTE),
BUS_NAME_1 VARCHAR2(20 BYTE),
PROPERTY_COLLECTION_ID_1 NUMBER(10,0),
BUS_NAME_2 VARCHAR2(20 BYTE),
PROPERTY_COLLECTION_ID_2 NUMBER(10,0),
X_1 NUMBER(8,3),
Y_1 NUMBER(8,3),
Z_1 NUMBER(8,3),
UOM_1 VARCHAR2(10 BYTE),
X_2 NUMBER(8,3),
Y_2 NUMBER(8,3),
Z_2 NUMBER(8,3),
UOM_2 VARCHAR2(10 BYTE),
COORD_CODE_1 VARCHAR2(10 BYTE),
COORD_CODE_2 VARCHAR2(10 BYTE),
UOM_DESC_1 VARCHAR2(50 BYTE),
UOM_DESC_2 VARCHAR2(50 BYTE),
PART_NO VARCHAR2(25 BYTE),
PART_DESC VARCHAR2(50 BYTE),
WIRE_GAUGE VARCHAR2(4 BYTE),
SPEC_REFERENCE VARCHAR2(60 BYTE),
MPS_NUM VARCHAR2(25 BYTE),
PPS_NUM VARCHAR2(25 BYTE),
INSERTION_TOOL VARCHAR2(25 BYTE),
EXTRACTION_TOOL VARCHAR2(25 BYTE)
);
/
We work with Oracle9i Enterprise Edition Release 9.2.0.6.0
Best regards,
A: I ran into a similar situation in a data warehousing environment at a past job.
Did your DBA increate pga_aggregate_target or _pga_max_size or both? Keep in mind that when the DBA increases pga_aggregate_target to 150MB that doesn't mean that your session would be able to grab all of that 150MB. Oracle will only allow a given session to take a small fraction of that space. Increasing pga_aggregate_target from 150MB to 200MB will only give your session a few extra megs of memory to play with for in-memory operations IIRC.
If your DB server has more available memory, you'll have to have your DBA increase both pga_aggregate_target and _pga_max_size, otherwise you'll have to look at using a GTT or creating a scratch table to dump your data into and then work on it from there.
A: Just wanted to add this tidbit in case it helps someone else. We suddenly started getting this error in our PL/SQL when the DBA set RESULT_CACHE_MODE to AUTO as a test for another process. We didnt know he did this until much later. Anyway, setting it back to MANUAL fixed this problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7597053",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Javascript in browser IS able to use sockets/get info from web by itself? Is it possible to open sockets and get data from web in JavaScript.
My aim is: to work with web data using JS.
I have looked for XmlHttp/AJAX solution, but I have found one note, that AJAX can be used only for calling localhost programs, which will be used as proxy and then only returns data from web.
It's because of sandbox model in browsers, which don't allow to work with sockets/other sites from JavaScript, and it works only in localhost.
Are there any solutions with JS to work with other world?
A: Your issue is due to cross domain request security, where you can't asynchronously get data from a domain which doesn't match the current host (this includes subdomains). You can however use jsonp, but this relies on the service that you're quering to supply the data in a jsonp format (a function call with the json data as a response).
If you have no control over the services you're requesting (which i assume you don't), you can use a javascript library, such as YUI or jQuery to perform the cross domain request for you (which typically uses Flash as the data proxy). However this will only work if you the site in question allows cross domain requests from your domain (defined in crossdomain.xml).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7597056",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Android set(get) environmental variables in Java I have experimented little with Android OS and I tried to call System.getenv() to get environmental variables. It works e.g. for $PATH, but I was not able to define own variable, which can be accessible in this way... Is it possible?
I have tried to set and export variables from adb shell as a shell user but it does not work - no matter if I started the application from the phone menu or when I used the adb shell am command.
Can the Runtime.getRuntime().exec() help there? Will it help if I will have root access to the phone?
Thanks
A: Environment variables are only visible in a process that sets the variable, and child processes launched after setting the variable. When you set the environment variable from the adb shell you are not in the parent process of the process that launches the Android application, so the application cannot see the variable you set.
In Java (and Android) there is no System.setenv(), but if you need to set an environment variable for your own program to read there are always better ways. One such way is setting and getting Properties instead.
Setting environment variables in Java is not really possible (well, it is, but you don't want to do it). You can use ProcessBuilder if you want to set a variable that another process should read, but that's if the process is launched from a Java/Android program.
Think about what problem you're trying to solve, and if it can be done without using environment variables. They're not a good fit in Java, and are even worse on Android.
A: It is possible to set environment variables in Android applications. However, as @richq said, those variables will be only visible in processes launched from the application that has set environment variable (and JNI libraries used by the application).
See this post for regarding setting environment variables from Android application:
https://stackoverflow.com/a/22315463/927592
A: Android API 21 provides a way to set the environment variables. To set an environment variable, invoke Os.setenv.
See this android.system.Os documentation and this setenv(3) documentation.
Each process has its own environment, which is copied from the parent process's environment. So the environment variables are per-process.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7597058",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
}
|
Q: Add a language in the Stanford parser I would like to use the Stanford parser in another language not already implemented.
I looked on the website but found nothing that could help me with that.
I guess what I have to do is "just" create a new languagePCFG.ser but to do that?
Also, if anyone knows if French and Spanish are supposed to be released?
A: Several things are needed:
*
*You need a treebank (set of hand-parsed trees) from which the probabilities used in the parser are calculated
*You need language-specific files (like xLanguagePack, xTreebankParserParams, which specify things about the language, treebank encoding, and parsing options
*You then train the parser on the treebank to produce the grammar file (see makeSerialized.csh in the distribution)
*You might need a language-specific tokenizer to divide text into tokens
*If you want Stanford Dependencies output, then there is also a rule-based layer that defines the dependencies
Starting in 2011, we did start distributing a French model with the Stanford Parser. And starting in 2015, we have begun distributing a Spanish model.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7597061",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Qprocess messes my linux command up (i think). how to fix? I need to force my c++ QT4 application to read results from a linux command. I am trying to use Qprocess but as soon as my command gets complicated it get messed somehow (just guessing) and does not work.
Here i try to make for yu a small example:
QProcess process;
command = "ls -l | grep a | sort";
qDebug() << "Execute command -> "+command;
process.start( command );
process.waitForFinished(-1);
QString processStdout = process.readAllStandardOutput();
QString processStderr = process.readAllStandardError();
qDebug() << "Std out -> "+processStdout;
qDebug() << "Std err -> "+processStderr;
this will print:
Execute command -> ls -l | grep a | sort
"Std out -> "
"Std err -> ls: |: No such file or directory
while would correctly print the file names if runed from the consol.
If i replace the comman with somethink simpler such command = "ls -l"; it work smoothless
The error is returned on standar error by the OS.
I guess thereforethat the Qstring used for the command gets manipolated somehow. Any idea about wht's happening?
A: QProcess does not support shell commands. The pipe symbols is thus not interpreted by a shell, but instead directly passed to ls. ls interprets it as file name, and complains because apparantly there is no file named |.
You need to setup pipes manually by redirecting input and output streams of QProcess objects. Read the documentation to learn how to do this.
Generally how should avoid shell commands, and instead rely on Qt classes and functions. There is certainly no need to call grep or ls, because the same can be done easier with QRegExp, and QDir. If you need to execute subprocesses, then use the ::start(const QString&, const QStringList&, OpenMode) overload and pass all arguments as list to avoid quoting issues.
A: Try this :
Run shell from QProcess and pass arguments to shell. Example :
QStringList options;
options << "-c" << "ls -l | grep a | sort";
QProcess process;
process.start("/bin/sh", options); //Use sh or another shell
Let me know is this worked or not .
A: command = "ls -l | grep a | sort";
isn't actually a process but pipeline of 3 different processes: ls, grep and sort.
A: thanks all guys for the help.
in order to do what i needed i had to change the aproach using:
std::string cmd("/sbin/ifconfig eth0");
FILE* pfd = popen(cmd.c_str(), "r");
if (pfd)
{
while (!feof(pfd))
{
char buf[1024] = {0};
if (fgets(buf, sizeof(buf), pfd) > 0)
{
std::cout << "buf = " << buf; // a newline is already present
}
}
pclose(pfd);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7597062",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: is it considerably faster to query different tables than having a where clause imagine that we have this table:
create table Foo(
id int,
name varchar,
k int --can be 1 or 2 or 3
)
or we could have 3 tables for each value of k
create Fook1(
id int,
name varchar
)
...
create table Fook2
...
createa table Fook3
is it going to be considerably faster to do:
select * from Foo where k = 3
than doing:
select * from Fook3
A: Potentially, using multiple tables could be faster than using a single table (particularly if those tables are going to have many millions of records), but there would be trade-offs in terms of ease of use, manageability, etc.
However, you could have the benefits of both by partitioning your table.
A: -Do-Not-Do-That-
Oh, wait, that's not helpful, it's just beligerant :)
Partitioning the data in this way CAN yield performance benefits. But they also introduce other costs:
- Queries that need to span all three tables become more complex
- Your schema becomes more cluttered
- It's easier to make mistakes
- It's hard to ensure referential integrity
- You may need to include a view to unify the 3 tables
You are most likely much better off with an Index that has k within it. And depending on how you query the data, k may be the first field in that index. When you specify k = ?, it just needs to do a Very quick check in the index and then you're only looking at the relevant portion of the table. And, if the index is a clustered index, the data is even physically stored in that order.
I'd highly recommend making use of indexes in this way before partitioning your data. It's an optimisation with costs, and so should be approached when it can be shown Necessary, not as a safety net early in design.
A: It may depend on the DB, so a real example is needed. For instance, in Oracle you can use partitioning, which does exactly what you say here behind the curtains, or create a materialized view with the union and then have the option to do both.
Normally, I'd say that you should create a correct implementation and then tune; early optimization is the root of all evils, especially with DBs. I think it is quite likely that your bottleneck is not going to be where you expect it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7597063",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: QMainDialog become modal if has modal QDialog as parent on Mac OS X I create QMainWindow with parent widget which is modal QDialog. QMainWindow created as modl window ontop of dialog and doesn't has active close, minimize buttons and has grayed(unaccessable) menu.
I suppose access to QMainWindow's menu restricted since there is
QDialog with modal flag active. But I need to have a non modal QMainWindow with menu which can be accessed.
Is it possible? I use qt 4.5.2 and os x lion.
Thanks!
A: I'm having trouble imagining the context in which one would open a QMainWindow parented to a modal QDialog.
However, if you want the QMainWindow to act as a top-level window, don't set a parent.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7597065",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can we ON or OFF the device programatically? I know there is a way where we can reboot the device. And it shows immediate result.
But my need is as :-
I want that when I will be in my class-room my phone automatically goes to OFF. (Lets say at 2:00 PM), and when I will end my class, my phone will automatically ON (Lets say at 5:00 PM).
So I am looking for the ways where I can ON/OFF the device automatically.
Is this possible? If yes how can I do it?
A: No. Once ot goes off it cannot be turned on. I think you need to totally mute your phone rather than turning it off.
A: No. Third party applications do not have the permission to do that.
Check out these links
http://developer.android.com/reference/android/os/PowerManager.html
http://developer.android.com/reference/android/content/Intent.html#ACTION_SHUTDOWN
A: If you don't want your phone to receive calls and connect to any networks, enabling/disabling the AirplaneMode by using a AlarmManager (or a Timer) might be a better idea.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7597066",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: preg_match: trying to identify number formats I'm trying to identify not only "numbers" in a string, but tag what type of number it is, such as General, Fraction, Percentile, Ratio etc.
Now if I use a tool like http://rubular.com/, my patterns appear to work fine.
Rules?
([-+]?)([0-9]+)([,+]?)([.]?) //General
([-+]?[0-9.,]+[%]) //Percent
([0-9]+[\/][0-9]+(?:st|nd|rd|th)) //Fraction
([-+]?[0-9.,]+[:][-+]?[0-9.,]+) //Ratio
Strings to check?
1
1,000
1.000
-50.5
-1:+3
1,200.6:3.9
+2:-4
1/5th
25%
25.76%
1,001%
It's when I put them in php (if/elseif) constructs I always end up with the "general" number?
if (preg_match('/([-+]?[0-9.,]+[%])/',$string)) {
echo " PERCENTILE ";
} elseif (preg_match('/([0-9]+[\/][0-9]+(?:st|nd|rd|th))/',$string)) {
echo " FRACTION ";
} elseif (preg_match('/([-+]?[0-9.,]+[:][-+]?[0-9.,]+)/',$string)) {
echo " RATIO ";
} elseif (preg_match('/([-+]?)([0-9]+)([,+]?)([.]?)/',$string)) {
echo " CARDINAL ";
} else {
echo " GENERAL ";
}
No matter what, it echos "CARDINAL".
Yes, I've tried switching the order (Card/General first, then the others).
Yes, I've tried making them independant IF()s, and in reverse order (most general first).
Nothing appears to work.
Even a Single IF checking for any of the formats simply fails.
Either my rules are stuffed - or I'm doing something blatantly wrong.
A: Try surrounding each regular expression with ^ and $ so that it matches only if it matches the entire string or line. Without these, if a regular expression matches part of a number, then that's still a match. For example, '1,000' matches your regular expression for CARDINAL numbers, /([-+]?)([0-9]+)([,+]?)([.]?)/, because it matches the substring '1,'. If you add ^ and $, as in /^([-+]?)([0-9]+)([,+]?)([.]?)$/, then it no longer matches.
<?php
function check_format($string) {
if (preg_match('/^([-+]?[0-9.,]+[%])$/',$string)) {
echo " PERCENTILE ";
} elseif (preg_match('/^([0-9]+[\/][0-9]+(?:st|nd|rd|th))$/',$string)) {
echo " FRACTION ";
} elseif (preg_match('/^([-+]?[0-9.,]+[:][-+]?[0-9.,]+)$/',$string)) {
echo " RATIO ";
} elseif (preg_match('/^([-+]?)([0-9]+)([,+]?)([.]?)$/',$string)) {
echo " CARDINAL ";
} else {
echo " GENERAL ";
}
}
array_map("check_format", array(
"1",
"1,000",
"1.000",
"-50.5",
"-1:+3",
"1,200.6:3.9",
"+2:-4",
"1/5th",
"25%",
"25.76%",
"1,001%"
));
outputs:
CARDINAL GENERAL GENERAL GENERAL RATIO RATIO RATIO FRACTION PERCENTILE PERCENTILE PERCENTILE
EDIT: This might be a better regular expression for CARDINAL numbers:
/^([-+]?)([0-9]+)(?:,?[0-9]{3})*([.]?)$/
A: You error must come from somewhere else, I couldn't reproduce it. Try to put your code in an otherwise empty file to test it by itself and it should work fine.
Test.php:
$nums = array(
'1',
'1,000',
'1.000',
'-50.5',
'-1:+3',
'1,200.6:3.9',
'+2:-4',
'1/5th',
'25%',
'25.76%',
'1,001%'
);
foreach ($nums as $string) {
echo $string.': ';
if (preg_match('/([-+]?[0-9.,]+[%])/',$string)) {
echo " PERCENTILE ";
} elseif (preg_match('/([0-9]+[\/][0-9]+(?:st|nd|rd|th))/',$string)) {
echo " FRACTION ";
} elseif (preg_match('/([-+]?[0-9.,]+[:][-+]?[0-9.,]+)/',$string)) {
echo " RATIO ";
} elseif (preg_match('/([-+]?)([0-9]+)([,+]?)([.]?)/',$string)) {
echo " CARDINAL ";
} else {
echo " GENERAL ";
}
echo "\n";
}
$ php test.php
1: CARDINAL
1,000: CARDINAL
1.000: CARDINAL
-50.5: CARDINAL
-1:+3: RATIO
1,200.6:3.9: RATIO
+2:-4: RATIO
1/5th: FRACTION
25%: PERCENTILE
25.76%: PERCENTILE
1,001%: PERCENTILE
A: Please have a look on this .
<?php
$num = 12.20
$num = floatval(preg_replace('/[^\d.]/', '', num));
// output will be 12.2
//it always replace zero and you have number 12.00 then output will be 12
$num = 12.00
$num = floatval(preg_replace('/[^\d.]/', '', num));
// output will be 12
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7597069",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Spring jdbc templates : What is the best way to keep sql statement out of code There doesn't seem to be a named query support in Spring JDBC Templates. By named query I mean the facility to reference sql statement by name in java code and keep the actual statements in some configuration file.
In the absence of out-of-box support, I'm researching the best approach to keep the sql statements outside java code.
Here are the alternatives:
*
*properties file
*xml properties file
*spring context xml (dependency inject)
comments?
A: Java - Storing SQL statements in an external file
I did one system where queries were stored in the DB, too, which for what we needed was absolutely perfect, but very entertaining. The query to do query lookups was in the DB as well, which caused great hilarity when it broke (don't ask).
A: All the approaches you've considered as alternative will work, yet you are adding additional layer to your design if you move the statements out of Java classes which to me is unnecessary. Consider the overhead of keeping the statements outside Java class.
*
*Properties and XML will have be loaded to fetch a single statement.
*Inject will inject unnecessary statements into classes.
If I were you, I will create a class and have the statement listed in static final. This makes it transparent, avoid unnecessary layers and makes it flexible for whoever is going to maintain your code in the future.
Example:
//This does the job
public class SQLStatements
{
static public final String GET_NAME="SELECT Name FROM some_table WHERE ID=?";
}
A: I would prefer to store all the SQL queries in properties or xml file.
Then fetch all the queries and store them in Map or Properties object at the program boot up.
This provides the feasibility to change the query even after code deployment.
We can change the query in property file and then restart the application.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7597074",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Relationship Using Code first with Existing database When defining a relationship between two types is it important to include a navigation property on both types, such as in the following example:
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
public Category Category { get; set; }
}
public class Category
{
public int CategoryId { get; set; }
public string Name { get; set; }
public ICollection<Product> Products { get; set; }
}
Can I do without including the navigation property in Category ?
A: If you just want it infered by code first convention then yes you need both on either side. I'd also make the collection "virtual" to support lazy loading.
You can set it up using the fluent configuration when the model is built. It would be something like this
modelBuilder.Entity<Product>()
.HasMany(x => x.Category)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7597076",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I set Ant to copy specific files to output? I am developing in eclipse websites in php.
I want to create a build configuration using Ant, to copy files from the project folder to a specific output path.
How is this possible using eclipse builders?
A: Ant copy task: http://ant.apache.org/manual/Tasks/copy.html
Example which copies one file to another:
<!-- copy file -->
<copy file="./service.jar" tofile="./service-v1.jar" overwrite="true"/>
Example which copies all XML, PNG, and JSON files from one directory to another, maintaining folder structure:
<!-- copy files -->
<copy todir="./destination">
<fileset dir="./src">
<include name="**/*.xml"/>
<include name="**/*.png"/>
<include name="**/*.json"/>
</fileset>
</copy>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7597079",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Combining vector and bitmap graphics in a pdf When plotting images or heatmaps to pdfs as in the example below they are saved as vector objects where every pixel in the image or cell in the heatmap is represented by a square. Even at modest resolutions this results in unnecessarily large files that also renders uglily on some devices. Is there a way to make R save only the image area as a png or jpg embedded in the pdf but keep text, axes, anotations etc as vector graphics?
I'm asking since I am often printing R graphics, sometimes on large posters, and would like to combine the best of the two worlds. Of course I could save the entire figure as a high resolution png but that would not be as elegant, or combine it manually e.g. in Inkscape but it is quite tedious.
my.func <- function(x, y) x %*% t(y)
pdf(file="myPlot.pdf")
image(my.func(seq(-10,10,,500), seq(-5,15,,500)), col=heat.colors(100))
dev.off()
Thanks for your time, ideas and hopefully solutions!
A: Use ?rasterImage, or more conveniently in recent versions image with option useRaster = TRUE.
That will dramatically reduce the size of the file.
my.func <- function(x, y) x %*% t(y)
pdf(file="image.pdf")
image(my.func(seq(-10,10,,500), seq(-5,15,,500)), col=heat.colors(100))
dev.off()
pdf(file="rasterImage.pdf")
image(my.func(seq(-10,10,,500), seq(-5,15,,500)), col=heat.colors(100), useRaster = TRUE)
dev.off()
file.info("image.pdf")$size
file.info("rasterImage.pdf")$size
image.pdf: 813229 bytes
rasterImage.pdf 16511 bytes
See more details about the new features here:
http://developer.r-project.org/Raster/raster-RFC.html
http://journal.r-project.org/archive/2011-1/RJournal_2011-1_Murrell.pdf
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7597081",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Ruby - No gem to load in cronjob I use rvm. and ruby 1.9.2 is installed in rvm.
I have a script and it runs fine in terminal.
I have wrote a cron job for the same script:
27 * * * * su - sayuj -c 'cd /path/to/dir; /home/sayuj/.rvm/rubies/ruby-1.9.2-p136/bin/ruby script.rb >> /var/log/script.log 2>&1'
Then it shows no gem is to load error. I think the cron is not referring to the rvm ruby 1.9.2.
How can I fix this issue?
A: You need to change cd /path/to/dir; to the real directory.
Then, create a file named .rvmrc with this content inside:
rvm use 1.9.2
It'll execute every time you enter the directory, setting to the correct version of ruby.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7597085",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why StreamReader.EndOfStream property change the BaseStream.Position value I wrote this small program which reads every 5th character from Random.txt
In random.txt I have one line of text: ABCDEFGHIJKLMNOPRST. I got the expected result:
*
*Position of A is 0
*Position of F is 5
*Position of K is 10
*Position of P is 15
Here is the code:
static void Main(string[] args)
{
StreamReader fp;
int n;
fp = new StreamReader("d:\\RANDOM.txt");
long previousBSposition = fp.BaseStream.Position;
//In this point BaseStream.Position is 0, as expected
n = 0;
while (!fp.EndOfStream)
{
//After !fp.EndOfStream were executed, BaseStream.Position is changed to 19,
//so I have to reset it to a previous position :S
fp.BaseStream.Seek(previousBSposition, SeekOrigin.Begin);
Console.WriteLine("Position of " + Convert.ToChar(fp.Read()) + " is " + fp.BaseStream.Position);
n = n + 5;
fp.DiscardBufferedData();
fp.BaseStream.Seek(n, SeekOrigin.Begin);
previousBSposition = fp.BaseStream.Position;
}
}
My question is, why after line while (!fp.EndOfStream) BaseStream.Position is changed to 19, e.g. end of a BaseStream. I expected, obviously wrong, that BaseStream.Position will stay the same when I call EndOfStream check?
Thanks.
A: Thre only certain way to find out whether a Stream is at its end is to actually read something from it and check whether the return value is 0. (StreamReader has another way – checking its internal buffer, but you correctly don't let it do that by calling DiscardBufferedData.)
So, EndOfStream has to read at least one byte from the base stream. And since reading byte by byte is inefficient, it reads more. That's the reason why the call to EndOfStream changes the position to the end (it woulnd't be the end of file for bigger files).
It seems you don't actually need to use StreamReader, so you should use Stream (or specifically FileStream) directly:
using (Stream fp = new FileStream(@"d:\RANDOM.txt", FileMode.Open))
{
int n = 0;
while (true)
{
int read = fp.ReadByte();
if (read == -1)
break;
char c = (char)read;
Console.WriteLine("Position of {0} is {1}.", c, fp.Position);
n += 5;
fp.Position = n;
}
}
(I'm not sure what does setting the position beyond the end of file do in this situation, you may need to add a check for that.)
A: The base stream's Position property refers to the position of the last read byte in the buffer, not the actual position of the StreamReader's cursor.
A: You are right and I could reproduce your issue as well, anyway according to (MSDN: Read Text from a File) the proper way to read a text file with a StreamReader is the following, not yours (this also always closes and disposes the stream by using a using block):
try
{
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
String line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7597089",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Is it posible to get all the values of the text boxes with the same name? I have a doubt in javascript. Is it posible to get the values of text boxes with the same name ?
for example
<INPUT TYPE="text" NAME="inputbox" VALUE="">
<INPUT TYPE="text" NAME="inputbox" VALUE="">
these text boxes have same name, how can i get its values by name ?
OK, lemme come to the real problem i got, hope am explaining correctly.
I have a series of text boxes which i gotta validate now. Its not a big deal to validate textboxe normally.
But this is an array of text boxes where the id of the text boxes will be available only when the fields are added dynamically by clicking on the + button. when the press button is clicked the whole set of text boxes will appear. as many times its clicked, it will get added.
So its imposible to get the values to validate with the ID, so i tried by name.
JAVASCRIPT FUNCTION
function insComep()
{
// $("#doctorPri").validationEngine("updatePromptsPosition")
// jQuery("#doctorPri").validationEngine('attach', {promptPosition : "topRight"});
rl=document.getElementById("compeTable").rows.length;
var a=document.getElementById("compeTable").insertRow(rl);
var g=a.insertCell(0);
var f=a.insertCell(1);
var m=a.insertCell(2);
var n=a.insertCell(3);
var o=a.insertCell(4);
var p=a.insertCell(5);
var q=a.insertCell(6);
var r=a.insertCell(7);
var s=a.insertCell(8);
var t=a.insertCell(9);
//var v=a.insertCel1l(11);
//var u=a.insertCell(12);
g.innerHTML='<select name="competproduct[]" style="width:86px" id="competproduct'+rl+'" class="validate[required]" ><option value="">--Select--</option><?echo $product_str;?></select>';
f.innerHTML='<input type="text" name="competcompany[]" id="competcompany'+rl+'" size="10" class="validate[required]" >';
m.innerHTML='<input type="text" name="competbrand[]" id="competbrand'+rl+'" size="10" class="validate[required]" >';
n.innerHTML='<input type="text" name="competdrug[]" id="competdrug'+rl+'" size="10" class="validate[required]" >';
o.innerHTML='<input type="text" name="competquty[]" id="competquty'+rl+'" size="2" class="validate[required,custom[integer]] text-input" >';
p.innerHTML='<input type="text" name="competprice_frm[]" id="competprice_frm'+rl+'" size="2" class="validate[required,custom[number],funcCall[getPriceFromE]] text-input" />';
q.innerHTML='<input type="text" name="competprice_to[]" id="competprice_to'+rl+'" size="2" class="validate[required,custom[number],funcCall[getPriceTo]] text-input" />';
r.innerHTML='<input type="text" name="competmrp[]" id="competmrp'+rl+'" size="2" class="validate[required,custom[number],funcCall[getMrp]] text-input"/>';
s.innerHTML='<select name="ChemistParma[]" style="width:86px" id="ChemistParma'+rl+'" style="width:86px" ><option value="">--Select--</option><?echo $chemist_str;?></select>';
t.innerHTML='<img src="media/images/details_close.png" onClick="delCompe('+rl+'); "/>';
// jQuery("#doctorPri").validationEngine('attach', {promptPosition : "topRight"});
$("#doctorPri").validationEngine('hideAll');
}
HTML
<table width="100%" id='compeTable' border='0' style='margin-left:auto;margin-right:auto;margin-top:40px;' >
<tr style="border-bottom:1px solid #999999;"><td colspan='4'>
<div style="background:;padding:3px;text-align:left; ">
<font color='black'><strong >Competitor Detail(s):</strong></font><font color="red">*</font>
</div>
</td></tr>
<tr>
<td>Product Name:<font color="red">*</font></td>
<td>Company Name:<font color="red">*</font></td>
<td>Brand Name:<font color="red">*</font></td>
<td>Drug Name:<font color="red">*</font></td>
<td> Quantity:<font color="red">*</font></td>
<td>Pricefrom Dist:<font color="red">*</font></td>
<td >Price to Dist:<font color="red">*</font></td>
<td> MRP:<font color="red">*</font></td>
<td>Chemist<font color="red">*</font><input type='button'value='+' style='width:1px' style='width:1px' onclick='frame5()'/>
</td>
<td></td>
</tr>
<tr><td> </td></tr>
<tr>
<td>
<select name='competproduct[]' id='competproduct' style="width:86px" class="validate[required]" >
<option value=''>-select Product-</option>
<? echo $product_str;?>
</select>
</td>
<td>
<input type="text" name="competcompany[]" id="competcompany" size="10" class="validate[required]" >
</td>
<td ><input type="text" name="competbrand[]" id="competbrand" size="10" class="validate[required]" >
</td>
<td><input type="text" name="competdrug[]" id="competdrug" size="10" class="validate[required]" >
</td>
<td><input type="text" name="competquty[]" id="competquty" size="2" class="validate[required,custom[integer]] text-input" >
</td>
<td>
<input type="text" name="competprice_frm[]" id="competprice_frm" size="2" class="validate[required,custom[number],funcCall[getPriceFromE]] text-input" />
</td>
<td>
<input type="text" name="competprice_to[]" id="competprice_to" size="2" class="validate[required,custom[number],funcCall[getPriceTo]] text-input" />
</td>
<td><input type="text" name="competmrp[]" id="competmrp" size="2" class="validate[required,custom[number],funcCall[getMrp]] text-input" onBlur=''/>
</td>
<td>
<select name='ChemistParma[]' id='ChemistParma' style="width:86px">
<option value=''>-select chemict-</option>
<?echo $chemist_str?>
</select></td>
<td>
<img src="media/images/details_open.png" onClick="insComep()"/>
</td>
</tr>
</table>
A: It's quite simple,
document.getElementsByName("inputBox");
A: You can use a multitude of different methods.
1) Manual traversal of childNodes etc, and checking for nodeName. This is pretty involved and requires a lot of boring code, so I won't write an example of that here.
2) document.getElementsByTagName. This can also be used on DOM nodes, so you can do something like document.getElementById("my_form").getElementsByTagName("input"), depending on how the rest of the DOM looks of course.
3) document.querySelectorAll("input"). The string argument is a full CSS selector. Some older browsers doesn't support this though.
A: Here is example for you with your code:
<div id="inputs">
<INPUT TYPE="text" NAME="inputbox" VALUE="asd">
<INPUT TYPE="text" NAME="inputbox" VALUE="efs">
</div>
<script>
$(document).ready(function () {
var howmany = $('#inputs').children("input").length;
alert(howmany);
for( i=0; i<= howmany-1; i++ ) {
var input = $("#inputs").children("input").eq(i).attr('VALUE');
alert(input);
}
});
</script>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7597092",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to check the exist value Using VB.Net and Sql Server
I want to check the user Entry Value.
The User is entering the code in the textbox, before saving to the table, i want to check whethere code is already exist in the table or not.
Tried Code
cmd = New SqlCommand("Select code from table where code = '" & textbox1.Text & "' ", Con)
dr = cmd.ExecuteReader()
While dr.Read()
End While
If value is exist, then message to the user "Already Exist" other wise save to the table.
Need Vb.net Code Help
A: Use SELECT COUNT instead and then check for that being greater than zero:
cmd = New SqlCommand("SELECT COUNT(*) from table where code = '" & textbox1.Text & "' ", con)
Dim NumRecords as Int32 = cmd.ExecuteScalar
IF NumRecords > 0 THEN...
A: Make code as primary key since you want it to be unique
if the value entered by the user in code is already existing in the table , VIOLATION of primary key sql exception will be thrown
Catch that exception and display a warning message!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7597095",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do i set my cookies to a specific domain? I have www.mysite.com and static-cookieless.mysite.com. My www site seems to be setting cookies on mysite.com thus my static site is no longer cookieless. How do i set cookies to only my www site?
I am using plain javascript (well, jquery.cookie but i know how to edit that easily)
A: document.cookie = 'cookie_name=' + cookie_value+ ',path=/,domain=mydomain.com';
May be the link below will be useful
http://javascript.about.com/library/blwcookie.htm
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7597096",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: MYSQL SELECT QUERY where column is the same Hi I am trying to query a table in my database, basically I need to select the driver_id from the table where the team_id is the same as the users driver id, stored in a variable $user_driver_one. So pretty much selecting the other driver with the same team_id.
column driver_id 1 2 3 4 5 6 7 8 9 10
column team_id 3 3 2 2 1 1 4 4 5 5
So the user could have $user_driver_one = 4, so I need to select in a query the driver_id = 3, as driver_id 3 has the same team_id.
I am having problems with this, any help is much appreciated.
A: Make sure you escape the parameter
$user_driver_one = (int) $user_driver_one;
MySQL:
"SELECT `driver_id`
FROM `table`
WHERE `team_id` = (
SELECT `team_id`
FROM `table`
WHERE `driver_id` = '$user_driver_one'
LIMIT 1
)
AND `driver_id` != '$user_driver_one'";
A: SELECT driver_id FROM T1 WHERE team_id = driver_id AND team_id = @user_driver_one
A: If you're gonna use PHP it would look like this:
mysql_query("SELECT driver_id FROM tablename WHERE team_id = '$user_driver_one'");
Of course, some sanitation before doing a query would be smart, especially if you're assigning the $user_driver_one variable from a user input.
A: select driver_id from yourtablename where team_id in (select team_id from yourtablename where driver_id=4)and driver_id!=4
You can use $user_driver_one in place of 4
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7597097",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Eclipse create java executable with external libraries I've seen this topic in this forum but it I need a more basic explanation on how to do this.
I've done a program in Java with some external libraries (LWJGL and Slick).
So this is what I've done and my program won't start anyway, tell me where I've done wrong.
I have Eclipse 3.7.1
*
*My project is opened in Eclipse and runs well in Eclipse
*I click File -> Export
*I select Java -> Runnable JAR file
*Here I don't know what to choose in Launch configuration, when I click the dropdown I get the option to choose my main class so I do that.
*I select an export destination
*I select the option "Package required libraries into generated JAR" under Library Handling
*I don't know what ANT script is so I don't use that
*I click Finish
*I copy my images-folder to the same location as the generate JAR-file
*I try to start the JAR-file, something loads in the background but nothing happens, no window shows up, nothing.
*I check the Task manager in windows and sees that a javaw.exe is running
What did I miss?
My program uses images for graphics like this:
image = new Image("images/filname.png");
I wonder if I need to change the paths before exporting or the method to load these?
Thanks!
A: If you want to get things from inside a jar file you need to have them in your classpath and access them as resources.
The constructor you use, refers to a physical file which cannot peek inside a jar-file.
(EDIT) Also note that you have no guarantee where the current working directory is. Hence any relative references may break, as you see.
A: Read this to learn how to use JarSplice to export your Eclipse project to a runnable jar-file. Regarding images, you can put them in the same directory as a class file (in the jar) and then writeSampleClass.class.getResourceAsStream("image.png")to retrieve an InputStream of the image. Then you can load it however you like.
A: I had the same problem and I was able to fix it. All I did was copy the data folder (which contains my resources) into the *.jar file. You can do this for example with WinRAR.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7597099",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: XSLT to call secondary XML based on first XML element/attribute love the stuff - newbie Æthelred here
I have a XSLT 1.0 file pulling in a secondary XML (to a variable) to build a table
<xsl:variable name="table_values" select="document('./table_variants/external_table.xml')/xml/channel_1"/>
I then get the values i need from the variable, eg:
<xsl:value-of select="$table_values/monkey/tennis/@medals"/>
<xsl:value-of select="$table_values/monkey/tennis/@bananas"/>
What i want to do is have the first XML trigger/steer where to look for the table data.
I hoped i could, within the triggered XML, state the last part of the xpath - the 'channel_1' or 'channel_2',
<xsl:value-of select="xml/external_table_channel_to_use"/>
but apparently i cannot create a xpath on the fly like that
Please - What can i do?
A:
What i want to do is have the first XML trigger/steer where to look
for the table data. I hoped i could, within the triggered XML, state
the last part of the xpath - the 'channel_1' or 'channel_2',
<xsl:value-of select="xml/external_table_channel_to_use"/> but
apparently i cannot create a xpath on the fly like that
Please - What can i do?
This can easily be done just extending the code that you already have.
Change this:
<xsl:variable name="table_values" select=
"document('./table_variants/external_table.xml')/xml/channel_1"/>
to this:
<xsl:variable name="table_values" select=
"document('./table_variants/external_table.xml')
/xml/*[name() = $channelName"/>
Needless to say, the variable (or global, external param) $channelName should have a value that is the (string) name of the element you want to use in the last location step of the XPath expression.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7597101",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Generate PDF based on HTML code (iTextSharp, PDFSharp?) Does the library PDFSharp can - like iTextSharp - generate PDF files *take into account HTML formatting *? (bold (strong), spacing (br), etc.)
Previously I used iTextSharp and roughly handled in such a way (code below):
string encodingMetaTag = "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />";
string htmlCode = "text <div> <b> bold </ b> or <u> underlined </ u> <div/>";
var sr = new StringReader (encodingMetaTag + htmlCode);
var pdfDoc = new Document (PageSize.A4, 10f, 10f, 10f, 0f);
var = new HTMLWorker htmlparser (pdfDoc);
PdfWriter.GetInstance (pdfDoc, HttpContext.Current.Response.OutputStream);
pdfDoc.Open ();
htmlparser.Parse (sr);
pdfDoc.Close ();
incorporated into the appropriate HTML form to a PDF document dealt with the class object HTMLWorker.. so what with PDFSharp? Has PDFSharp similar solution?
A: Old question but none of above worked for me. Then i tried generatepdf method of HtmlRenderer in combination of pdfsharp. Hope it helps:
You must install a nuget named HtmlRenderer.pdfsharp.
var doc = TheArtOfDev.HtmlRenderer.PdfSharp.PdfGenerator.GeneratePdf("Your html in a string",PageSize.A4);
PdfPage page = new PdfPage();
XImage img = XImage.FromGdiPlusImage(bitmap);
doc.Pages.Add(page);
XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[0]);
xgr.DrawImage(img, 0, 0);
doc.Save(Server.MapPath("test.pdf"));
doc.Close();
A: If you only want a certain HTML string written to the PDF but not the rest, you can use the HtmlContainer from TheArtOfDev HtmlRenderer. This snippet uses V 1.5.1
using PdfSharp.Pdf;
using PdfSharp;
using PdfSharp.Drawing;
using TheArtOfDev.HtmlRenderer.PdfSharp;
//create a pdf document
using (PdfDocument doc = new PdfDocument())
{
doc.Info.Title = "StackOverflow Demo PDF";
//add a page
PdfPage page = doc.AddPage();
page.Size = PageSize.A4;
//fonts and styles
XFont font = new XFont("Arial", 10, XFontStyle.Regular);
XSolidBrush brush = new XSolidBrush(XColor.FromArgb(0, 0, 0));
using (XGraphics gfx = XGraphics.FromPdfPage(page))
{
//write a normal string
gfx.DrawString("A normal string written to the PDF.", font, brush, new XRect(15, 15, page.Width, page.Height), XStringFormats.TopLeft);
//write the html string to the pdf
using (var container = new HtmlContainer())
{
var pageSize = new XSize(page.Width, page.Height);
container.Location = new XPoint(15, 45);
container.MaxSize = pageSize;
container.PageSize = pageSize;
container.SetHtml("This is a <b>HTML</b> string <u>written</u> to the <font color=\"red\">PDF</font>.<br><br><a href=\"http://www.google.nl\">www.google.nl</a>");
using (var measure = XGraphics.CreateMeasureContext(pageSize, XGraphicsUnit.Point, XPageDirection.Downwards))
{
container.PerformLayout(measure);
}
gfx.IntersectClip(new XRect(0, 0, page.Width, page.Height));
container.PerformPaint(gfx);
}
}
//write the pdf to a byte array to serve as download, attach to an email etc.
byte[] bin;
using (MemoryStream stream = new MemoryStream())
{
doc.Save(stream, false);
bin = stream.ToArray();
}
}
A: In a project that I developed last year I used wkhtmltopdf (http://wkhtmltopdf.org/) to generate pdf from html then I read the file and get back it to the user.
It works fine for me and it could be an idea for you...
A: I know this question is old, but here's a clean way to do it...
You can use HtmlRenderer combined with PDFSharp to accomplish this:
Bitmap bitmap = new Bitmap(1200, 1800);
Graphics g = Graphics.FromImage(bitmap);
HtmlRenderer.HtmlContainer c = new HtmlRenderer.HtmlContainer();
c.SetHtml("<html><body style='font-size:20px'>Whatever</body></html>");
c.PerformPaint(g);
PdfDocument doc = new PdfDocument();
PdfPage page = new PdfPage();
XImage img = XImage.FromGdiPlusImage(bitmap);
doc.Pages.Add(page);
XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[0]);
xgr.DrawImage(img, 0, 0);
doc.Save(@"C:\test.pdf");
doc.Close();
Some people report that the final image looks a bit blurry, apparently due to automatic anti-aliasing. Here's a post message on how to fix that: http://forum.pdfsharp.com/viewtopic.php?f=2&t=1811&start=0
A: No, PDFsharp does not currently include code to parse HTML files.
A: I know there is a really old question but I realize that there is no one saying actually an accurate method to render an HTML into a PDF. Based on my test I found out that you need the following code to successfully do it.
Bitmap bitmap = new Bitmap(790, 1800);
Graphics g = Graphics.FromImage(bitmap);
XGraphics xg = XGraphics.FromGraphics(g, new XSize(bitmap.Width, bitmap.Height));
TheArtOfDev.HtmlRenderer.PdfSharp.HtmlContainer c = new TheArtOfDev.HtmlRenderer.PdfSharp.HtmlContainer();
c.SetHtml("Your html in a string here");
PdfDocument pdf = new PdfDocument();
PdfPage page = new PdfPage();
XImage img = XImage.FromGdiPlusImage(bitmap);
pdf.Pages.Add(page);
XGraphics xgr = XGraphics.FromPdfPage(pdf.Pages[0]);
c.PerformLayout(xgr);
c.PerformPaint(xgr);
xgr.DrawImage(img, 0, 0);
pdf.Save("test.pdf");
There is another way to do but you might have problems with the size.
PdfDocument pdf = PdfGenerator.GeneratePdf(text, PageSize.A4);
pdf.Save("test.pdf");
A: Have you guys heard of this. I might be answering very late but I thought it helps. It is very simple and works well.
var htmlContent = String.Format("<body>Hello world: {0}</body>",
DateTime.Now);
var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
var pdfBytes = htmlToPdf.GeneratePdf(htmlContent);
Edit: I came here with the question of converting HTML code to PDF using 'PDFSharp' and found out that 'PDFSharp' cannot do it then I found out about NReco and it worked for me so I felt it might help someone just like me.
A: HTML Renderer for PDF using PdfSharp can generate a PDF from an HTML
*
*as an image, or
*as text
before inserting to the PDF.
To render as an image, please refer to the code from Diego answer.
To render as text, please refer code below:
static void Main(string[] args)
{
string html = File.ReadAllText(@"C:\Temp\Test.html");
PdfDocument pdf = PdfGenerator.GeneratePdf(html, PageSize.A4, 20, null, OnStylesheetLoad, OnImageLoadPdfSharp);
pdf.Save(@"C:\Temp\Test.pdf");
}
public static void OnImageLoadPdfSharp(object sender, HtmlImageLoadEventArgs e)
{
var imgObj = Image.FromFile(@"C:\Temp\Test.png");
e.Callback(XImage.FromGdiPlusImage(imgObj));
}
public static void OnStylesheetLoad(object sender, HtmlStylesheetLoadEventArgs e)
{
e.SetStyleSheet = @"h1, h2, h3 { color: navy; font-weight:normal; }";
}
HTML code
<html>
<head>
<title></title>
<link rel="Stylesheet" href="StyleSheet" />
</head>
<body>
<h1>Images
<img src="ImageIcon" />
</h1>
</body>
</html>
A: Unfortunately, HtmlRenderer is not an appropriate library to be used in a project based on .NET 5.0:
System.IO.FileLoadException: 'Could not load file or assembly 'HtmlRenderer,
Version=1.5.0.6, Culture=neutral, PublicKeyToken=null'. The located assembly's
manifest definition does not match the assembly reference. (0x80131040)'
Also, I found that the dependency package HtmlRender.PdfSharp has the following warning message:
Package 'HtmlRenderer.PdfSharp 1.5.0.6' was restored using
'.NETFramework,Version=v4.6.1, .NETFramework,Version=v4.6.2,
.NETFramework,Version=v4.7, .NETFramework,Version=v4.7.1,
.NETFramework,Version=v4.7.2, .NETFramework,Version=v4.8' instead of the project
target framework 'net5.0'. This package may not be fully compatible with your project.
By the way, I managed to render HTML as PDF using another library IronPDF:
License.LicenseKey = "license key";
var renderer = new ChromePdfRenderer();
PdfDocument pdf = await renderer.RenderHtmlAsPdfAsync(youtHtml);
pdf.SaveAs("your html as pdf.pdf");
The line with License.LicenseKey is not necessary and you can remove it, but your pdf will be generated with the IronPDF watermark in the end of each page. But IronPDF provides getting trial license key.
A: after a long struggle, i succeed using Polybioz.HtmlRenderer.PdfSharp.Core
=> HtmlRenderer.PdfSharp.Core is a partial port of HtmlRenderer.PdfSharp for .NET Core
it work in Net5.0 :)
my solution, directly inspired from VDWWD and others
PdfPage page = new PdfPage();
PdfOutline outline = new PdfOutline();
page = document.AddPage();
XGraphics gfx_ = XGraphics.FromPdfPage(page);
using (var container = new HtmlContainer())
{
var pageSize = new XSize(page.Width, page.Height);
var x = 5;
var y = 100;
container.Location = new XPoint(x, y);
container.MaxSize = pageSize;
container.PageSize = pageSize;
const string latinstuff =
"Facin exeraessisit la consenim iureet dignibh eu <b>facilluptat</b> vercil dunt autpat. " +
"Ecte magna faccum dolor sequisc iliquat, quat, quipiss equipit accummy niate magna " +
"facil iure eraesequis am velit, quat atis dolore dolent luptat nulla adio odipissectet " +
"lan venis do essequatio conulla facillandrem <u>zzriusci</u> bla ad minim inis nim velit eugait " +
"aut aut lor at ilit ut nulla ate te eugait alit augiamet ad magnim iurem il eu feuissi.\n" +
"Guer sequis duis eu feugait luptat lum adiamet, si tate dolore mod eu facidunt adignisl in " +
"henim dolorem nulla faccum vel inis dolutpatum iusto od min ex euis adio exer sed del " +
"dolor ing enit veniamcon vullutat praestrud molenis ciduisim doloborem ipit nulla consequisi.\n" +
"Nos adit pratetu eriurem delestie del ut lumsandreet nis exerilisit wis nos alit venit praestrud " +
"dolor sum volore facidui blaor erillaortis ad ea augue corem dunt nis iustinciduis euisi.\n" +
"Ut ulputate volore min ut nulpute dolobor sequism olorperilit autatie modit wisl illuptat dolore " +
"min ut in ute doloboreet ip ex et am dunt at.";
//container.SetHtml("This is a <b>HTML</b> string <u>written</u> to the <font color=\"red\">PDF</font>.<br><br><a href=\"http://www.google.nl\">www.google.nl</a>");
string text = "This is a <b>HTML</b> string <u>written</u> to the <font color=\"red\">PDF</font>.<br>" +
$"<br><a href=\"http://www.google.nl\">www.google.nl</a>{DateTime.Now.ToLongTimeString()}";
text += latinstuff;
text += "<p style=\"text-align:center;\">" + latinstuff + "</p>";
text += "<p style=\"text-align:justify;\">" + latinstuff + "</p>";
text += "<div width=\"70mm\" style=\"text-align:justify;\"><p>" + latinstuff + "</p></div>";
container.SetHtml(text);
using (var measure = XGraphics.CreateMeasureContext(pageSize, XGraphicsUnit.Point, XPageDirection.Downwards))
{
container.PerformLayout(measure);
}
gfx_.IntersectClip(new XRect(0, 0, page.Width + 400, page.Height));
container.PerformLayout(gfx_);
container.PerformPaint(gfx_);
}
the only think which is remain is that the bold is not rendered (the "facilluptat" should be bolded) in the latinstuff, see my print screen of the page
A: I'll recommend you NReco.PdfGenerator because have free and paid license and its easy to install from nuget.
Main page: https://www.nrecosite.com/pdf_generator_net.aspx
Documentation: https://www.nrecosite.com/doc/NReco.PdfGenerator/
If you want create PDF from html file try:
String html = File.ReadAllText("main.html");
var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
htmlToPdf.GeneratePdf(html, null, "C:/Users/Tmp/Desktop/mapa.pdf");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7597103",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "25"
}
|
Q: Go to a specific directory in Java Servlet i have a app folder in tomcat webapps named BankApp, and there is a temp directory in it.
I want to get all the files in temp folder
I tried this :
File file = new File(path + "/temp/");
File[] list = file.listFiles();
for(int i=0;i<list.length;i++)
{
out.println(list[i].getName() + "<br/>");
}
but its not working, i mean giving null error
is it the right way to go to that folder ? i.e. BankApp\temp
Thanks !
A: Not a final answer, from the JavaDoc for java.util.File.listFiles():
An array of abstract pathnames denoting the files and directories in
the directory denoted by this abstract pathname. The array will be
empty if the directory is empty. Returns null if this abstract
pathname does not denote a directory, or if an I/O error occurs.
Are you sure the statement path + "/temp/" returns a valid (existing) path?
Edit: You must correctly identify the root path of your BankApp. You can do this by calling ServletContext.getRealPath("/"). See my answer to a previous question.
A: Define "it's not working" -- what happens?
If you want the files in the temp directory why do you getParentFile and list the files in that directory instead?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7597104",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: C# Asynchron call with Named Pipes in WCF I have a WCF host created with named pipes binding:
using System;
using System.ServiceModel;
using System.ServiceModel.Description;
namespace Microsoft.ServiceModel.Samples
{
// Define a service contract.
[ServiceContract]
public interface ICalculator
{
[OperationContract]
double Add(double n1, double n2);
}
// Step 1: Create service class that implements the service contract.
public class CalculatorService : ICalculator
{
// Step 2: Implement functionality for the service operations.
public double Add(double n1, double n2)
{
double result = n1 + n2;
Console.WriteLine("Received Add({0},{1})", n1, n2);
// Code added to write output to the console window.
Console.WriteLine("Return: {0}", result);
return result;
}
}
class Program
{
static void Main(string[] args)
{
// Step 1 of the address configuration procedure: Create a URI to serve as the base address.
Uri baseAddress = new Uri("net.pipe://localhost");
// Step 2 of the hosting procedure: Create ServiceHost
ServiceHost selfHost = new ServiceHost(typeof(CalculatorService), baseAddress);
try
{
selfHost.AddServiceEndpoint(
typeof(ICalculator),
new NetNamedPipeBinding(),
"Calc");
// Step 4 of the hosting procedure: Enable metadata exchange.
ServiceMetadataBehavior SMB = new ServiceMetadataBehavior();
selfHost.Description.Behaviors.Add(SMB);
selfHost.AddServiceEndpoint(typeof(IMetadataExchange),
MetadataExchangeBindings.CreateMexNamedPipeBinding(),
"mex");
// Step 5 of the hosting procedure: Start (and then stop) the service.
selfHost.Open();
Console.WriteLine("The service is ready.");
Console.WriteLine("Press <ENTER> to terminate service.");
Console.WriteLine();
Console.ReadLine();
// Close the ServiceHostBase to shutdown the service.
selfHost.Close();
}
catch (CommunicationException ce)
{
Console.WriteLine("An exception occurred: {0}", ce.Message);
selfHost.Abort();
}
}
}
}
This host starts up correct. Now, I want to be able to call the Add method asynchron. Therefore I use svcutil:
svcutil.exe /config:app.config /out:generatedProxy.cs net.pipe://localhost /a /tcv:Version35
The proxy client is generated and I use this implementation:
namespace Microsoft.ServiceModel.Samples
{
class Program
{
static void Main(string[] args)
{
CalculatorClient client = new CalculatorClient();
Console.ReadLine();
double value1 = 5;
double value2 = 3;
double result = client.Add(value1, value2);
Console.WriteLine("Add({0},{1}) = {2}", value1, value2, result);
Console.WriteLine("Now async");
value1 = 100.00D;
value2 = 15.99D;
client.AddCompleted += new EventHandler<AddCompletedEventArgs>(AddCallback);
client.AddAsync(value1, value2);
Console.WriteLine("Add({0},{1})", value1, value2);
client.Close();
}
// Asynchronous callbacks for displaying results.
static void AddCallback(object sender, AddCompletedEventArgs e)
{
Console.WriteLine("Add Result async: {0}", e.Result);
}
}
}
When running the client I get the following exception:
System.ServiceModel.CommunicationException: The server did not provide a meaningful reply
The problem is that when configuring this example to an http binding everything is fine, so I guess there must be something obeyed when working with async named pipes method call?!
Thanks, Juergen
A: Read through
http://msdn.microsoft.com/en-us/library/ms734701(v=VS.90).aspx
http://msdn.microsoft.com/en-us/library/system.servicemodel.operationcontractattribute.asyncpattern(v=VS.90).aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7597108",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to use NSUserDefaults to store a row property I have a tab bar based application, with a TableViewController on a tab.
When i update my app, i add a new row to my Table.
What i want to do is store the highlight color of a row of my TableViewController as soon as i insert a new one, for at least 3 sessions.
I know that i have to use NSUserDefaults, but, where?
I mean: should i use it into my rowViewController (which is a UIViewController) or into my TableViewController(where i have all the rows)?
And how can i import a cell property into the UIViewController(if is in there that i have to use the NSUserDefaults)?
i have something like:
- (void) applicationDidFinishLaunching:(NSNotification*) notice {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
[[NSUserDefaults standardUserDefaults] setInteger:0 forKey:cell];
if ([(NSInteger*)[[NSUserDefaults standardUserDefaults] integerForKey:cell] intValue] < 3) {
// render highlighted...
} else {
// render normal
} }
I can't do it 'cause it's a UIViewController, right? Then in the .h at
@interface rowViewController : UIViewController
should i add something in order to implement the cell and then to set its properties (color)?
Thanks in advance.
A: You can do it the way you did in your question, but there is a big problem in your code. You use NSInteger like if it was an object, whereas it is an atomic type.
Don't confuse NSInteger and NSNumber:
*
*NSNumber is a class that aims to encapsulate numbers in an Objective-C object so that you can use it where NSObjects are requested (like when you want to store them in NSDictionaries)
*NSInteger is an alias (typedef) for an integer type. Use it the same way you would use an int.
So in your code, NSUserDefaults's setInteger:forKey: and integerForKey: uses NSInteger values (namely atomic values, not objects). No need to use * and intValue then to retrieve the real value, you already have it! (The code like you wrote it will surely crash, interpreting an integer value as a pointer to a memory address!)
Moreover, you can't use the cell as the key of your NSUserDefaults. NSUserDefaults only accept strings for the keys, and moreover UITableViewCells are reused (recycled each time you scroll) and not persistant. You should instead build a string that uses the NSIndexPath of your cell and use it for your NSUserDefaults key; then store the background color of a cell/row at a given position in the UITableView (and anyway that's better separation of the Model and the View in the MVC design pattern).
// Build a string from the IndexPath that will be used as a unique key for your userdefaults, to store info on the corresponding row in your tableview
NSString* key = [NSString stringWithFormat:@"bkg_%i:%i",indexPath.section,indexPath.row];
[[NSUserDefaults standardUserDefaults] setInteger:0 forKey:key];
if ([[NSUserDefaults standardUserDefaults] integerForKey:key] < 3)
{
// render highlighted...
} else {
// render normal
}
Note that integerForKey: can be seen as a call to objectForKey: (that will return an NSObject, typically an NSNumber in your case, which is an object encapsulating the integer value) followed by a call to integerValue.
// These lines...
NSNumber* nbrObj = [[NSUserDefaults standardUserDefaults] objectForKey:@"mykey"];
NSInteger nbr = [nbrObj integerValue];
// are equivalent to the following, shorter line:
NSInteger nbr = [[NSUserDefaults standardUserDefaults] integerForKey:@"mykey"];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7597111",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: iOS: How to Backup a Project? What's the best way to backup a project?
To be more specific: I have a DropBox account and I prefer to have a copy of the project over there.
I assume I should copy all the h+m files.
Can I copy all the xib files? does it make any sense?
Can/Should I copy all the jpg/png/mp3 files that I use for resources?
Is there a proper way to do that, like a "backup project" button where I can select the target and it compresses the project in some smart way?
A: You need all of those and the project files, etc. Look in the project file to see all files referenced. Check to see if you have everything by making a copy and trying to build from the copy. You'll get complaints if you missed any thing.
A: Best thing is to copy the entire directory where all your project exists. Copy this directory to your dropbox folder. To open the project open yourproject.xcodeproj with xcode.
Although this method is okay for one time thing or when you are the only one working on your project but in the long run you should look at trying to adopt a source control versioning system like GIT. Xcode has wonderful integration with GIT.
Hope this helps...
A: The best way to backup a project is source control. There are many options available to get free or very cheap remote source control repositories where you can store a copy (and history) of your source. Checkout http://www.beanstalkapp.com or http://www.github.com for a start.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7597114",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: htaccess line - 500 error I have a htaccess file:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
I want to add the line below, but it gives me 500 error.
Options -Indexes
Can somebody help?
A: Check if the directory where your .htaccess lives in has enabled the neccessary AllowOverride (enabled must be: AuthConfig and Options at least) in the httpd.conf.
Make sure it is not within the
<IfModule mod_rewrite.c>
...
</IfModule>
part of your .htaccess
Usually you should have a logging-message in your error-log. I assume, that you will find something like this:
[alert] [client 192.xxx.xxx.xxx] /path/to/web/.htaccess: Options not allowed here
This solution does not always help (depending on the apache-version you are using): In some cases you have to move this section to your httpd.conf to make it work.
It is explained in detail in the apache-docs.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7597118",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android: Handling tap event on an ImageView inside of a HorizontalScrollView I have a bunch of ListViews inside of a HorizontalScrollView. I would like to have a "tap" event when the user taps on the image. Currently I am using the OnTouch event but this is a problem. If I swipe the HorizontalScrollView to view more images, the OnTouch event gets fired as soon as I swipe. I really only want it to get fired when I tap on an image but not when I am swiping the actual list of images. Any idea how to do that? Thank you!
A: You should use onClick instead of onTouch I think.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7597119",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MatchTemplate in OpenCV with Python I'm using opencv with python bindings. I'm trying to use the template match, but it's not performing exactly as I need it to. If there is no image matching the template I supply it, I don't want it to return a match. It seems to always return a match whether the actual template exists at all in the image I supply it.
I've looked at the documentation for the opencv with Python and can't seem to find any mention of how to set a minimum threshold for matching templates. I need it to be relatively strict when comparing the template to the image.
image = LoadImage("c:/image.png")
template = LoadImage("c:/image-crop2.png")
W,H = GetSize(image)
w,h = GetSize(template)
width = W - w + 1
height = H - h + 1
result = CreateImage((width, height), 32, 1)
MatchTemplate(image, template, result, CV_TM_CCORR)
(min_x, max_y, minloc, maxloc) = MinMaxLoc(result)
(x, y) = minloc
print result
A: See this answer: OpenCV. Drawing rectangle when matching
You are having exactly the same problem - MatchTemplate returns a kind of similarity map instead of single match position.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7597120",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Regarding Oauth 2.0 & https from October 1st I want to know several things about new changes that will be applicable from October 1st that are Oauth 2.0 & https.
Will it be compulsory to provide https link when creating new application?
I have enabled https on main domain and my applications are on subdomain so do I need to acquire certificate for subdomain also?
Also as mentioned in roadmap fb_sig parameter will be deprecated, so do I need to upgrade all my applications to Oauth 2.0 in order to make them work?
Please help me. Thanks in advance.
A: You must have ssl sertificate for your domain. It's not important where you buy or any other thing. facebook only look that if link is secure or not ( https)
So if you don' t have wildcard for your subdomains you have to buy wildcard for subdomains or ssl sertificate for each subdomain.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7597121",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to create a Magento 1.6 shipping module? I'm trying to create my own Magento shipping module in Magento 1.6. Since I have no experience making Magento modules, I'm trying to find a blank custom shipping module to add stuff to. There are a few tutorials online, but they all seem outdated or loaded with bugs.
Can anyone point me to something like this tutorial but working for 1.6?
Or perhaps a blank module already packaged in a zip file?
A: If you want a package for shipping module than you should follow this link
http://www.magentocommerce.com/magento-connect/ig-multi-flat-shipping.html
(or any other free shipping extension)
After installing this extension you can go through its Code that will enable you to create your own shipping module.
THANKS
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7597123",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.